Reproducing Huszár et al. (2022) from DANDI:000552¶

Paper. Huszár R, Zhang Y, Blockus H, Buzsáki G (2022). Preconfigured dynamics in the hippocampus are guided by embryonic birthdate and rate of neurogenesis. Nature Neuroscience 25, 1201-1212. doi:10.1038/s41593-022-01138-x.

Claims. claims/huszar-2022.yaml, written from the author manuscript in PubMed Central (PMC10807234) with its Reporting Summary and Supplementary Information (Supplementary Tables 1 to 5), and the paper's code (github.com/rhuszar/optotagCA1_final, commit 51320d4). Method details the claims file lacks are taken from the Methods and legends of that text, cited beside the code in huszar.py.

Dataset. DANDI:000552, version 0.261113.1035 (doi:10.48324/dandi.000552/0.261113.1035), the most recent published version. The paper cites no version (it was published before the dandiset). The earlier published version, 0.230630.2304, lacks what the claims need: its release notes say it had no light-responsive labels, no light pulses, units for only some sessions and LFP in only 13 files, while 0.261113.1035 holds all of these for the 104 sessions. It therefore also matches the claims file's description better. Only the 104 processed files are read, streamed from the archive; the 11 raw wide-band files are not.

This notebook streams every processed file and takes about 47 minutes, most of it reading two LFP channels per session for the theta analyses.

Claim Tested here
cohort-birthdates, st1-animal-sessions, sessions-durations, spwr-duration, unit-count, ed2-light-responsive-count yes
fig1e-labelled-fraction, fig1f-rem-shift, fig1g-rate-by-birthdate, fig1h-burst-by-birthdate yes
fig2b-synchrony-per-animal, fig2c-theta-cofiring, fig2d-theta-depth, fig2f-ripple-firing-by-birthdate, fig2g-ripple-cofiring yes
maze-cohort, maze-task, novel-explorations yes
fig5b-spatial-info-by-birthdate, fig5c-sbd-ratemap-overlap, fig5d-overlap-by-distance, fig5e-pv-decorrelation, fig5f-remap-together yes
fig6c-theta-rate-preserved, fig6d-rate-lower-novel, fig6d-info-lower-novel, fig6c-novel-ratemap-corr-higher, fig6e-sbd-novel-overlap, fig6f-remap-together-novel yes, open fields at an assumed scale
fig7b-sbd-convergence, fig7ce-convergence-by-birthdate, fig7d-transmission-gamma, fig7fg-convergence-cofiring yes
ed1-brdu-specificity, fig1c-radial-depth blocked: histology not in the dataset
ed2-waveform-validation blocked: light-evoked waveforms need the wide-band signal, absent for 91 of 96 sessions
ed3-depth-control yes
ed5-matched-controls blocked: no L-ratio in the dataset (the rate-matched half is run for the record)
fig3c, fig3e, ed6, fig4d-model-fit blocked: not run; the assembly matrix as first planned (dense, 1 ms bins) needs 9 to 12 GB per session, and a chunked version was not built in the time (see the attempt record)
ed7-sbd-coactivation blocked: depends on fig3e-assembly-expression (part e is run for the record)
ed10-waveform-matched-controls blocked: depends on ed2-waveform-validation (its own parts are run for the record)
In [1]:
import json, time, zlib, resource, collections
import numpy as np, pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import huszar as h
pd.set_option("display.width", 200); pd.set_option("display.max_columns", 30)
KEY = "huszar-2022"
def seed(claim): return zlib.crc32(f"{KEY}/{claim}".encode())
SEEDS_PLUS = [0, 1000, 2000, 3000, 4000]
T0 = time.time()

Data check¶

In [2]:
metas = h.survey(workers=8)
S = pd.DataFrame([{"session": m["session_id"], "subject": m["subject_id"], "sex": m["sex"], "age": m["age"],
                   "birthdate": m["birthdate"], "units": m["n_units"],
                   "pyr": sum(c == "Pyramidal Cell" for c in m.get("u_putative_cell_type", [])),
                   "narrow": sum(c == "Narrow Interneuron" for c in m.get("u_putative_cell_type", [])),
                   "wide": sum(c == "Wide Interneuron" for c in m.get("u_putative_cell_type", [])),
                   "unknown_type": sum(c not in ("Pyramidal Cell", "Narrow Interneuron", "Wide Interneuron")
                                       for c in m.get("u_putative_cell_type", [])),
                   "light_resp": int(np.sum(m.get("u_light_responsive", []))),
                   "lfp_min": m["lfp_duration_s"] / 60, "last_spike_min": m["last_spike"] / 60,
                   "lfp_rate": m.get("lfp_rate"), "ripples": len(m["rip_start"]),
                   "states": "/".join(sorted(set(m["sleep"]["label"]))) if m["sleep"] else "",
                   "pulses": m["n_pulses"], "beh_epochs": len(h.behaviour_epochs(m)),
                   "envs": ",".join(e[2] for e in h.behaviour_epochs(m)),
                   "trials": len(m["trials"]["start_time"]) if m["trials"] else 0}
                  for m in metas]).sort_values("session").reset_index(drop=True)
META = {m["session_id"]: m for m in metas}
S["homecage_mouse"] = ~S.subject.isin(h.HOMECAGE_EXCLUDED)
print(len(S), "processed files,", S.subject.nunique(), "subjects,", S.session.nunique(), "distinct session ids")
print("LFP rate(s):", S.lfp_rate.unique(), "Hz; LFP duration against last spike, max |difference| =",
      round(float((S.lfp_min - S.last_spike_min).abs().max()), 2), "min")
print(S.groupby("subject").agg(sex=("sex", "first"), birthdate=("birthdate", "first"), sessions=("session", "size"),
                               units=("units", "sum"), pyr=("pyr", "sum"), light_resp=("light_resp", "sum")).to_string())
print("\ncell types over all files:", S[["pyr", "narrow", "wide", "unknown_type"]].sum().to_dict())
print("sleep-state labels per session:", S.states.value_counts().to_dict())
print("behavioural environments:", collections.Counter(e for s in S.envs for e in s.split(",") if e))
print("ages:", S.age.unique(), " sexes:", S.sex.unique())
# deposited twice? identical spike counts or ripple counts between sessions
dup = S[S.duplicated(["units", "ripples", "pulses"], keep=False)]
print("sessions sharing unit, ripple and pulse counts (possible duplicates):", len(dup))
cols = [set(m["u_columns"]) for m in metas]
print("units table columns in every file:", sorted(set.intersection(*cols)), "; in some files only:", sorted(set.union(*cols) - set.intersection(*cols)))
print("unit columns naming an isolation metric (L-ratio, isolation distance):", [c for c in set.union(*cols) if "ratio" in c.lower() or "isol" in c.lower()])
print("waveform_mean shape after the unit axis:", collections.Counter(tuple(m["wf_shape"][1:]) for m in metas if m["wf_shape"]),
      "; electrodes per file:", collections.Counter(m["n_electrodes"] for m in metas))
print("files with electrodes on two faces of the shanks (probe_side Front and Back), by mouse:", dict(collections.Counter(m["subject_id"] for m in metas if len(m["probe_sides"]) > 1)))
104 processed files, 17 subjects, 104 distinct session ids
LFP rate(s): [1250.] Hz; LFP duration against last spike, max |difference| = 13.56 min
         sex birthdate  sessions  units   pyr  light_resp
subject                                                  
e13_16f1   F     E13.5         9   1213  1013         124
e13_1f1    F     E13.5         5    360   271           6
e13_1m1    M     E13.5        12   1432  1139          14
e13_26m1   M     E13.5         4    853   712          40
e14_1m1    M     E14.5        12    853   604          56
e14_2m2    M     E14.5         4    583   475           9
e14_2m3    M     E14.5         8    452   345          67
e15_10m1   M     E15.5         7    704   509          44
e15_13f1   F     E15.5         4   1385  1187          53
e15_4m1    M     E15.5         3    202   155          35
e15_4m2    M     E15.5         4    375   262          68
e15_5m1    M     E15.5         3    233   160          19
e15_9f1    F     E15.5         7    610   450          67
e16_1f1    F     E16.5         9    604   485          49
e16_2m1    M     E16.5         5    301   244          23
e16_3m1    M     E16.5         4    697   587          43
e16_3m2    M     E16.5         4    799   645          69

cell types over all files: {'pyr': 9243, 'narrow': 1850, 'wide': 560, 'unknown_type': 3}
sleep-state labels per session: {'Awake/Non-REM/REM': 101, 'Awake': 2, 'Awake/Non-REM': 1}
behavioural environments: Counter({'figure-8 maze': 53, 'tmaze_familiar': 12, 'tmaze_ipshita': 3, 'linear_thomas': 3, 'linear_manu': 3, 'openField_gergo': 3, 'openField_coolbox': 2, 'openField_thomas': 2})
ages: <StringArray>
['P3M/P6M']
Length: 1, dtype: str  sexes: <StringArray>
['F', 'M']
Length: 2, dtype: str
sessions sharing unit, ripple and pulse counts (possible duplicates): 0
units table columns in every file: ['acg_tau_rise', 'cluster_id', 'electrode_group', 'electrodes', 'electrodes_index', 'firing_rate', 'id', 'light_responsive', 'max_electrode', 'meanings_tables', 'opto_h_reliable', 'opto_int_ratemod', 'opto_int_ratemod_pval', 'opto_p_salt', 'putative_cell_type', 'shank_id', 'spike_times', 'spike_times_index', 'trough_to_peak', 'unit_name', 'waveform_mean'] ; in some files only: []
unit columns naming an isolation metric (L-ratio, isolation distance): []
waveform_mean shape after the unit axis: Counter({(72, 64): 79, (72, 128): 25}) ; electrodes per file: Counter({64: 79, 128: 25})
files with electrodes on two faces of the shanks (probe_side Front and Back), by mouse: {'e13_16f1': 9, 'e13_26m1': 4, 'e14_2m2': 4, 'e15_13f1': 4, 'e15_9f1': 7, 'e16_1f1': 9, 'e16_2m1': 5, 'e16_3m1': 4, 'e16_3m2': 4}
In [3]:
# Clock checks (protocol, author step 2): spikes against light pulses, ripples and position, each with a shifted control.
chk_sessions = [s for s in ["e13_16f1_210302", "e14_2m3_201125", "e15_9f1_200720", "e16_3m1_210201", "e15_4m2_191213"]]
CK = pd.DataFrame(h.run_sessions(h.clock_checks, [META[s] for s in chk_sessions]))
print(CK.round(3).to_string())
           session  pulse_true  pulse_shift  rip_rate_true  rip_rate_shift  si_true  si_shift
0  e13_16f1_210302        6860         1354          5.815           1.050    0.585     0.133
1   e14_2m3_201125        6107          863          7.613           1.358    0.897     0.173
2   e15_9f1_200720        5724          385          5.125           0.944    1.073     0.186
3   e16_3m1_210201        3379          613          3.180           0.707    0.559     0.140
4   e15_4m2_191213         954          360          7.400           1.177      NaN       NaN

The files describe 17 mice and 104 sessions, one file per session with no duplicates by unit, ripple and pulse counts. Every session has units with cell types, light pulses, ripples and LFP at 1,250 Hz; 101 sessions have wake, non-REM and REM states, one has no REM, and two (e13_1f1_200305 and e13_1f1_200307) have wake only. In the five sessions checked, light-responsive cells fire 2.7 to 15 times more in the 10 ms after the pulse onsets than 1 s later, pyramidal cells fire 4.5 to 6.3 times faster in the ripples than in windows shifted by 1 s, and in the four maze sessions among them the median spatial information falls from between 0.56 and 1.07 bits/s to between 0.13 and 0.19 bits/s when spikes are shifted by 30 s against the position. Spikes, pulses, ripples and position are therefore consistent with one clock in those sessions; other sessions were not checked this way. The theta section adds the same contrast for the LFP.

The units table has the same 21 columns in every file and none is an isolation metric (no L-ratio). waveform_mean holds each unit's mean waveform on every channel (72 samples by 64 or 128 channels). The 25 files with 128 channels (9 mice) mark their electrodes Front or Back (probe_side): two faces of the same four shanks, with the same x positions on both faces. The two wake-only sessions hold a single sleep-state row each, Awake over the whole recording (414.7 and 331.5 min), with 1,942 and 1,247 ripples detected, so they were scored but carry no sleep.

Counts: cohort, sessions, units¶

Claim cohort-birthdates: Chronic recordings were made from 17 adult mice (12 males, 5 females) electroporated at E13.5 (n = 4), E14.5 (n = 3), E15.5 (n = 6) and E16.5 (n = 4).

In [4]:
sub = S.groupby("subject").agg(sex=("sex", "first"), birthdate=("birthdate", "first")).reset_index()
print("mice:", len(sub), " males:", int((sub.sex == "M").sum()), " females:", int((sub.sex == "F").sum()))
print("per birthdate:", sub.birthdate.value_counts().sort_index().to_dict())
st1 = pd.DataFrame({"subject": h.ST1_ORDER})
st1["table_birthdate"] = [h.birthdate(s) for s in h.ST1_ORDER]
st1 = st1.merge(sub, on="subject", how="left")
print("subjects of Supplementary Table 1 found in the dataset:", int(st1.sex.notna().sum()), "of", len(st1),
      "; birthdate agrees:", int((st1.table_birthdate == st1.birthdate).sum()))
mice: 17  males: 12  females: 5
per birthdate: {'E13.5': 4, 'E14.5': 3, 'E15.5': 6, 'E16.5': 4}
subjects of Supplementary Table 1 found in the dataset: 17 of 17 ; birthdate agrees: 17

Result: reproduced. The files hold 17 mice, 12 male and 5 female, with 4, 3, 6 and 4 mice electroporated at E13.5 to E16.5; all 17 animals of Supplementary Table 1 are present with the table's birthdate. Sex and birthdate come from the subject ids, as the files say.

Claim st1-animal-sessions: Supplementary Table 1 lists each mouse's recording sessions and light-responsive cells; the 15 homecage mice contribute 96 sessions and 664 light-responsive cells, and the 17 mice 104 sessions.

In [5]:
per = S.groupby("subject").agg(sessions=("session", "size"), light_resp=("light_resp", "sum"), pyr=("pyr", "sum"))
T = pd.DataFrame({"subject": h.ST1_ORDER, "table_sessions": h.ST1_SESSIONS, "table_light": h.ST1_LIGHT}).set_index("subject")
T = T.join(per)
T["pct_light"] = (100 * T.light_resp / T.pyr).round(2)
T["sessions_match"] = T.sessions == T.table_sessions
T["light_match"] = T.light_resp == T.table_light
print(T.to_string())
hm = T.index[~T.index.isin(h.HOMECAGE_EXCLUDED)]
print("\nsessions of the 15 homecage mice:", int(T.loc[hm, "sessions"].sum()), "; of all 17:", int(T.sessions.sum()))
print("light-responsive cells of the 15 homecage mice:", int(T.loc[hm, "light_resp"].sum()))
print("mice whose session count matches:", int(T.sessions_match.sum()), "of 17; light-responsive count matches:",
      int(T.light_match.sum()), "of 17")
          table_sessions  table_light  sessions  light_resp   pyr  pct_light  sessions_match  light_match
subject                                                                                                  
e13_1m1               12           14        12          14  1139       1.23            True         True
e13_1f1                5            6         5           6   271       2.21            True         True
e14_1m1               12           56        12          56   604       9.27            True         True
e15_4m1                3           35         3          35   155      22.58            True         True
e15_4m2                4           68         4          68   262      25.95            True         True
e15_5m1                3           19         3          19   160      11.88            True         True
e13_16f1               9          124         9         124  1013      12.24            True         True
e14_2m2                4            9         4           9   475       1.89            True         True
e14_2m3                8           67         8          67   345      19.42            True         True
e15_9f1                7           67         7          67   450      14.89            True         True
e15_10m1               7           44         7          44   509       8.64            True         True
e16_1f1                9           49         9          49   485      10.10            True         True
e16_2m1                5           23         5          23   244       9.43            True         True
e16_3m1                4           43         4          43   587       7.33            True         True
e13_26m1               4           40         4          40   712       5.62            True         True
e15_13f1               4           53         4          53  1187       4.47            True         True
e16_3m2                4           69         4          69   645      10.70            True         True

sessions of the 15 homecage mice: 96 ; of all 17: 104
light-responsive cells of the 15 homecage mice: 664
mice whose session count matches: 17 of 17; light-responsive count matches: 17 of 17

Result: reproduced. Every one of the 17 mice has the table's session count and the table's number of light-responsive cells; the 15 homecage mice give 96 sessions and 664 light-responsive cells, and the 17 mice 104 sessions.

Claim sessions-durations: The recordings comprise 92 sessions lasting 113.7 to 475.6 min (median 309.1 min), each including a homecage period of sleep and wake.

In [6]:
S["duration_min"] = S.lfp_min
S["has_nrem"] = S.states.str.contains("Non-REM")
for lab, sel in [("96 sessions of the 15 homecage mice", S.homecage_mouse), ("104 sessions of all 17 mice", S.index >= 0)]:
    d = S.loc[sel, "duration_min"]
    print(f"{lab}: n = {len(d)}, median {d.median():.1f} min, range {d.min():.1f} to {d.max():.1f} min; "
          f"all within 102.3-523.2: {bool(((d >= 102.33) & (d <= 523.16)).all())}; "
          f"sessions without non-REM: {int((~S.loc[sel, 'has_nrem']).sum())}")
print("sessions without non-REM sleep:", S.loc[~S.has_nrem, ["session", "states"]].values.tolist())
print("count reading of 92 sessions: none of the session sets has 92; 96 is within 92 +- 9.2:", abs(96 - 92) <= 9.2,
      "; 104 is:", abs(104 - 92) <= 9.2)
for s in ["e13_1f1_200305", "e13_1f1_200307"]:
    ss = pd.DataFrame(META[s]["sleep"]); ss["min"] = (ss.stop_time - ss.start_time) / 60
    print(f"{s}: recording {S.set_index('session').lfp_min[s]:.1f} min; sleep-state rows {len(ss)}, labels {ss.label.value_counts().to_dict()}, "
          f"scored {ss['min'].sum():.1f} min from {ss.start_time.min()/60:.1f} to {ss.stop_time.max()/60:.1f} min; ripples {len(META[s]['rip_start'])}")
96 sessions of the 15 homecage mice: n = 96, median 309.9 min, range 113.7 to 475.6 min; all within 102.3-523.2: True; sessions without non-REM: 2
104 sessions of all 17 mice: n = 104, median 319.6 min, range 113.7 to 494.2 min; all within 102.3-523.2: True; sessions without non-REM: 2
sessions without non-REM sleep: [['e13_1f1_200305', 'Awake'], ['e13_1f1_200307', 'Awake']]
count reading of 92 sessions: none of the session sets has 92; 96 is within 92 +- 9.2: True ; 104 is: False
e13_1f1_200305: recording 414.7 min; sleep-state rows 1, labels {'Awake': 1}, scored 414.7 min from 0.0 to 414.7 min; ripples 1942
e13_1f1_200307: recording 331.5 min; sleep-state rows 1, labels {'Awake': 1}, scored 331.5 min from 0.0 to 331.5 min; ripples 1247

Result: not reproduced. No session set has 92 sessions; under the 96-session reading the count (96) is within 92 +- 9.2, the median is 309.9 min and every duration lies within 113.7 to 475.6 min, the paper's exact range. Two sessions (e13_1f1_200305, e13_1f1_200307) hold only wake in their sleep states (one Awake row over the whole recording), so the criterion's requirement that every session holds non-REM sleep fails, and the criterion has no partial outcome for this case; this is asked of a reader (questions/huszar-2022.yaml).

Claim unit-count: The dataset includes 9,471 well-isolated units, 7,411 putative pyramidal cells and 2,060 putative interneurons (1,556 narrow waveform, 504 wide waveform).

In [7]:
for lab, sel in [("(a) 96 sessions of the 15 homecage mice", S.homecage_mouse), ("(b) 104 sessions of all 17 mice", S.index >= 0)]:
    x = S.loc[sel]
    print(f"{lab}: units {x.units.sum()}, pyramidal {x.pyr.sum()}, interneurons {x.narrow.sum() + x.wide.sum()} "
          f"(narrow {x.narrow.sum()}, wide {x.wide.sum()}), other type {x.unknown_type.sum()}")
(a) 96 sessions of the 15 homecage mice: units 9472, pyramidal 7411, interneurons 2060 (narrow 1556, wide 504), other type 1
(b) 104 sessions of all 17 mice: units 11656, pyramidal 9243, interneurons 2410 (narrow 1850, wide 560), other type 3

Result: reproduced. Over the 96 sessions of the 15 homecage mice there are 7,411 pyramidal cells and 2,060 interneurons (1,556 narrow, 504 wide), the paper's numbers exactly; the total is 9,472 units, the paper's 9,471 plus one unit without a cell type.

Claim ed2-light-responsive-count: 664 of 7,411 putative pyramidal neurons (8.96%) were light-responsive, that is, birthdated, leaving 6,747 nonresponsive.

In [8]:
x = S[S.homecage_mouse]
U = pd.DataFrame([{"session": m["session_id"], "subject": m["subject_id"], "ct": c, "lr": l, "p_salt": p, "h_rel": r}
                  for m in metas for c, l, p, r in zip(m["u_putative_cell_type"], m["u_light_responsive"],
                                                       m["u_opto_p_salt"], m["u_opto_h_reliable"])])
U = U[~U.subject.isin(h.HOMECAGE_EXCLUDED)]
pyrU = U[U.ct == "Pyramidal Cell"]
a = int(pyrU.lr.sum()); b = int(((pyrU.p_salt <= 0.001) & (pyrU.h_rel.astype(bool))).sum())
b2 = int(((pyrU.p_salt < 0.001) & (pyrU.h_rel.astype(bool))).sum())
print(f"(a) stored light_responsive: {a} of {len(pyrU)} pyramidal ({100*a/len(pyrU):.2f}%), nonresponsive {len(pyrU)-a}")
print(f"(b) from the stored SALT p and reliability flag (p_salt <= 0.001 and h_reliable): {b}; with p < 0.001 (the code's): {b2}")
print("light_responsive outside pyramidal cells:", int(U[U.ct != 'Pyramidal Cell'].lr.sum()))
print("p_salt missing among pyramidal cells:", int(pyrU.p_salt.isna().sum()))
(a) stored light_responsive: 664 of 7411 pyramidal (8.96%), nonresponsive 6747
(b) from the stored SALT p and reliability flag (p_salt <= 0.001 and h_reliable): 664; with p < 0.001 (the code's): 664
light_responsive outside pyramidal cells: 0
p_salt missing among pyramidal cells: 0

Result: reproduced. The stored labels give 664 light-responsive cells of 7,411 pyramidal cells (8.96%), and the same 664 follow from the stored SALT p and reliability flag.

Claim spwr-duration: The median duration of SPW-Rs across all recordings is 36.4 ms, under detection limits of 20 to 200 ms.

In [9]:
rows = []
for m in metas:
    d = np.asarray(m["rip_dur"]) * 1000
    hc = h.homecage_intervals(m)
    rip = np.c_[m["rip_start"], m["rip_stop"]]
    k = h.in_intervals(rip[:, 0], hc) & h.in_intervals(rip[:, 1], hc)
    rows.append({"session": m["session_id"], "subject": m["subject_id"], "all": d, "hc": d[k]})
R = pd.DataFrame(rows)
for setlab, sel in [("96 homecage-mouse sessions", ~R.subject.isin(h.HOMECAGE_EXCLUDED)), ("104 sessions", R.index >= 0)]:
    for rl in ["all", "hc"]:
        arrs = R.loc[sel, rl]
        pooled = np.concatenate(arrs.values)
        meds = np.array([np.median(a) for a in arrs if len(a)])
        print(f"{setlab}, ripples={'(i) all detected' if rl=='all' else '(ii) homecage'}: n = {len(pooled)}; "
              f"(a) pooled median {np.median(pooled):.2f} ms; (b) median of session medians {np.median(meds):.2f}; "
              f"(c) mean of session medians {np.mean(meds):.2f}; range {pooled.min():.1f} to {pooled.max():.1f} ms; "
              f"outside 20-200 ms: {int(((pooled < 20) | (pooled > 200)).sum())}")
allr = np.concatenate(R["all"].values)
print("ripple durations: start-stop agree with ripple_durations column to", 
      np.max(np.abs(np.concatenate([(np.asarray(m['rip_stop']) - np.asarray(m['rip_start'])) * 1000 - np.asarray(m['rip_dur']) * 1000 for m in metas]))), "ms")
96 homecage-mouse sessions, ripples=(i) all detected: n = 428509; (a) pooled median 36.00 ms; (b) median of session medians 36.80; (c) mean of session medians 36.28; range 20.0 to 199.2 ms; outside 20-200 ms: 0
96 homecage-mouse sessions, ripples=(ii) homecage: n = 333156; (a) pooled median 36.80 ms; (b) median of session medians 36.80; (c) mean of session medians 36.38; range 20.0 to 198.4 ms; outside 20-200 ms: 0
104 sessions, ripples=(i) all detected: n = 494578; (a) pooled median 36.00 ms; (b) median of session medians 36.00; (c) mean of session medians 36.13; range 20.0 to 199.2 ms; outside 20-200 ms: 0
104 sessions, ripples=(ii) homecage: n = 364305; (a) pooled median 36.00 ms; (b) median of session medians 36.80; (c) mean of session medians 36.23; range 20.0 to 198.4 ms; outside 20-200 ms: 0
ripple durations: start-stop agree with ripple_durations column to 0.0 ms

Result: reproduced. Every combination of reading gives a median between 36.00 and 36.80 ms, within 36.4 +- 3.64 ms; the mean of session medians of all detected ripples (the code's reading) is 36.28 ms over the 96 sessions. All 494,578 ripples last 20.0 to 199.2 ms.

Claim fig1e-labelled-fraction: The fraction of light-responsive pyramidal cells per session follows a bell-shaped wave over birthdates, peaking at E15.5 (E13.5 5.39%, E14.5 11.16%, E15.5 14.74%, E16.5 9.16%).

In [10]:
x = S[S.homecage_mouse].copy()
x["pct"] = 100 * x.light_resp / x.pyr
g = x.groupby("birthdate").pct
print(pd.DataFrame({"sessions": g.size(), "mean": g.mean().round(2), "sd": g.std().round(2)}).to_string())
groups = [x[x.birthdate == b].pct.values for b in h.BIRTHDATES]
for k in SEEDS_PLUS:
    F, p = h.boot_anova(groups, rng=np.random.default_rng(seed("fig1e-labelled-fraction") + k))
    print(f"seed +{k}: bootstrap ANOVA F = {F:.3f}, p = {p:.4f}")
print("by mouse:", x.groupby(["birthdate", "subject"]).pct.mean().round(2).to_dict())
           sessions   mean    sd
birthdate                       
E13.5            30   5.39  4.99
E14.5            24  11.16  8.53
E15.5            24  14.74  8.68
E16.5            18   9.16  3.84
seed +0: bootstrap ANOVA F = 8.525, p = 0.0000
seed +1000: bootstrap ANOVA F = 8.525, p = 0.0000
seed +2000: bootstrap ANOVA F = 8.525, p = 0.0000
seed +3000: bootstrap ANOVA F = 8.525, p = 0.0000
seed +4000: bootstrap ANOVA F = 8.525, p = 0.0000
by mouse: {('E13.5', 'e13_16f1'): 11.81, ('E13.5', 'e13_1f1'): 2.25, ('E13.5', 'e13_1m1'): 1.69, ('E13.5', 'e13_26m1'): 6.01, ('E14.5', 'e14_1m1'): 9.09, ('E14.5', 'e14_2m2'): 2.08, ('E14.5', 'e14_2m3'): 18.81, ('E15.5', 'e15_10m1'): 7.87, ('E15.5', 'e15_4m1'): 22.28, ('E15.5', 'e15_4m2'): 25.07, ('E15.5', 'e15_5m1'): 11.39, ('E15.5', 'e15_9f1'): 13.89, ('E16.5', 'e16_1f1'): 9.72, ('E16.5', 'e16_2m1'): 9.49, ('E16.5', 'e16_3m1'): 7.5}

Result: reproduced. The per-session means are 5.39, 11.16, 14.74 and 9.16% over 30, 24, 24 and 18 sessions, the paper's values, with F = 8.525 as printed; the bootstrap ANOVA gives p < 0.0002 under all five seeds, E13.5 is lowest and E15.5 highest.

Homecage single-cell and SPW-R measures¶

One pass over the 96 sessions of the 15 homecage mice (h.homecage_session). The homecage period is the recording up to the second behavioural subsession, without the light pulse periods and the maze epochs (claims, opening comment; getHomecageMetrics.m). SPW-Rs are the dataset's (bz_FindRipples, as the Methods), those starting and ending in the homecage period.

In [11]:
HM = [META[s] for s in S.loc[S.homecage_mouse, "session"]]
t = time.time()
hc_res = h.run_sessions(h.homecage_session, HM)
CELLS = pd.DataFrame([c for r in hc_res for c in r[0]])
PAIRS = pd.DataFrame([p for r in hc_res for p in r[1]])
HCI = pd.DataFrame([r[2] for r in hc_res])
LR = CELLS[CELLS.lr]
print(f"{time.time()-t:.0f} s; pyramidal cells {len(CELLS)}, light-responsive {len(LR)}; pairs SBD {int(PAIRS.sbd.sum())}, DBD {int((~PAIRS.sbd).sum())}")
print("homecage period per session (min): median", round(HCI.hc_dur.median() / 60, 1), "range", round(HCI.hc_dur.min() / 60, 1), "-", round(HCI.hc_dur.max() / 60, 1))
print("homecage ripples per session: median", int(HCI.n_rip_hc.median()), "range", HCI.n_rip_hc.min(), "-", HCI.n_rip_hc.max(), "; of all ripples", round(HCI.n_rip_hc.sum() / HCI.n_rip.sum(), 3))
print("light-responsive cells per birthdate:", LR.groupby("birthdate").size().to_dict())
105 s; pyramidal cells 7411, light-responsive 664; pairs SBD 3751, DBD 50461
homecage period per session (min): median 237.3 range 33.7 - 383.7
homecage ripples per session: median 3537 range 11 - 6972 ; of all ripples 0.777
light-responsive cells per birthdate: {'E13.5': 184, 'E14.5': 132, 'E15.5': 233, 'E16.5': 115}
In [12]:
def by_bd(df, col, claim, test="kw", n_seeds=5):
    groups = [df[df.birthdate == b][col].dropna().values for b in h.BIRTHDATES]
    med = [float(np.median(g)) for g in groups]
    print(f"{col}: n = {[len(g) for g in groups]}, medians = {np.round(med, 4).tolist()}, ranges = "
          f"{[(round(float(g.min()), 3), round(float(g.max()), 3)) for g in groups]}")
    ps = []
    for k in SEEDS_PLUS[:n_seeds]:
        f = h.boot_kw if test == "kw" else h.boot_anova
        st, p = f(groups, rng=np.random.default_rng(seed(claim) + k))
        ps.append(p)
    print(f"  bootstrap {'Kruskal-Wallis H' if test=='kw' else 'ANOVA F'} = {st:.3f}; p under the claim's seed and +1000..+4000: {ps}")
    return med, ps

Claim fig1g-rate-by-birthdate: Earlier-born light-responsive pyramidal neurons have higher firing rates (medians 1.57, 1.63, 1.62 and 1.16 Hz for E13.5 to E16.5).

In [13]:
med, ps = by_bd(LR, "rate", "fig1g-rate-by-birthdate")
print("E16.5 lowest:", int(np.argmin(med)) == 3)
print("within tolerance:", [abs(a - b) <= t for a, b, t in zip(med, [1.57, 1.63, 1.62, 1.16], [0.157, 0.163, 0.162, 0.116])])
print("by mouse (median rate):", LR.groupby(["birthdate", "subject"]).rate.median().round(2).to_dict())
rate: n = [184, 132, 233, 115], medians = [1.5165, 1.6199, 1.5438, 1.1523], ranges = [(0.13, 9.783), (0.033, 5.216), (0.033, 6.76), (0.079, 4.464)]
  bootstrap Kruskal-Wallis H = 8.456; p under the claim's seed and +1000..+4000: [0.0342, 0.041, 0.0372, 0.0394, 0.0366]
E16.5 lowest: True
within tolerance: [True, True, True, True]
by mouse (median rate): {('E13.5', 'e13_16f1'): 1.6, ('E13.5', 'e13_1f1'): 2.24, ('E13.5', 'e13_1m1'): 1.56, ('E13.5', 'e13_26m1'): 1.26, ('E14.5', 'e14_1m1'): 1.23, ('E14.5', 'e14_2m2'): 1.98, ('E14.5', 'e14_2m3'): 1.7, ('E15.5', 'e15_10m1'): 1.37, ('E15.5', 'e15_4m1'): 1.06, ('E15.5', 'e15_4m2'): 1.16, ('E15.5', 'e15_5m1'): 1.61, ('E15.5', 'e15_9f1'): 2.06, ('E16.5', 'e16_1f1'): 1.14, ('E16.5', 'e16_2m1'): 1.19, ('E16.5', 'e16_3m1'): 1.16}

Result: reproduced. Medians 1.52, 1.62, 1.54 and 1.15 Hz over 184, 132, 233 and 115 light-responsive cells are within tolerance, E16.5 is lowest, and the bootstrap Kruskal-Wallis gives p = 0.034 (0.034 to 0.041 over the five seeds).

Claim fig1h-burst-by-birthdate: Burst index is an inverted-U function of birthdate (medians 0.1167, 0.1272, 0.136, 0.1082 for E13.5 to E16.5).

In [14]:
med, ps = by_bd(LR, "burst", "fig1h-burst-by-birthdate")
print("legend 2-5 ms: inverted-U:", h.inverted_u(med), "; within tolerance:",
      [abs(a - b) <= t for a, b, t in zip(med, [0.1167, 0.1272, 0.136, 0.1082], [0.0117, 0.0127, 0.0136, 0.0108])])
med35, ps35 = by_bd(LR, "burst35", "fig1h-burst-by-birthdate", n_seeds=1)
print("code 3-5 ms variant: inverted-U:", h.inverted_u(med35))
print("by mouse (median 2-5 ms):", LR.groupby(["birthdate", "subject"]).burst.median().round(3).to_dict())
burst: n = [184, 132, 233, 115], medians = [0.0873, 0.0912, 0.1031, 0.0798], ranges = [(0.008, 0.634), (0.0, 0.412), (0.0, 1.8), (0.003, 1.375)]
  bootstrap Kruskal-Wallis H = 20.643; p under the claim's seed and +1000..+4000: [0.0002, 0.0002, 0.0, 0.0, 0.0004]
legend 2-5 ms: inverted-U: True ; within tolerance: [False, False, False, False]
burst35: n = [184, 132, 233, 115], medians = [0.0802, 0.0795, 0.0936, 0.0737], ranges = [(0.008, 0.624), (0.0, 0.412), (0.0, 1.8), (0.002, 1.355)]
  bootstrap Kruskal-Wallis H = 22.238; p under the claim's seed and +1000..+4000: [0.0]
code 3-5 ms variant: inverted-U: True
by mouse (median 2-5 ms): {('E13.5', 'e13_16f1'): 0.077, ('E13.5', 'e13_1f1'): 0.083, ('E13.5', 'e13_1m1'): 0.07, ('E13.5', 'e13_26m1'): 0.112, ('E14.5', 'e14_1m1'): 0.095, ('E14.5', 'e14_2m2'): 0.096, ('E14.5', 'e14_2m3'): 0.074, ('E15.5', 'e15_10m1'): 0.072, ('E15.5', 'e15_4m1'): 0.208, ('E15.5', 'e15_4m2'): 0.181, ('E15.5', 'e15_5m1'): 0.263, ('E15.5', 'e15_9f1'): 0.073, ('E16.5', 'e16_1f1'): 0.067, ('E16.5', 'e16_2m1'): 0.096, ('E16.5', 'e16_3m1'): 0.078}

Result: partially reproduced. The bootstrap Kruskal-Wallis gives p <= 0.0004 under all seeds and the medians form an inverted U (0.087, 0.091, 0.103, 0.080, highest at E15.5), but all four medians are about 25% below the paper's (0.117 to 0.136) and outside tolerance; the code's 3-5 ms variant is lower still (0.074 to 0.094).

Claim fig2f-ripple-firing-by-birthdate: SPW-R firing rates (medians 7.8, 8.75, 8.01, 6.13 Hz) and participation (0.245, 0.268, 0.235, 0.194) of light-responsive neurons are inverted-U functions of birthdate.

In [15]:
m1, p1 = by_bd(LR, "rip_rate", "fig2f-ripple-firing-by-birthdate")
m2, p2 = by_bd(LR, "rip_part", "fig2f-ripple-firing-by-birthdate")
print("rate: inverted-U", h.inverted_u(m1), "within tolerance", [abs(a - b) <= 0.1 * b for a, b in zip(m1, [7.8, 8.75, 8.01, 6.13])])
print("participation: inverted-U", h.inverted_u(m2), "within tolerance", [abs(a - b) <= 0.1 * b + 1e-12 for a, b in zip(m2, [0.245, 0.268, 0.235, 0.194])])
print("by mouse (median SPW-R rate):", LR.groupby(["birthdate", "subject"]).rip_rate.median().round(2).to_dict())
rip_rate: n = [184, 132, 233, 115], medians = [7.484, 8.8232, 7.9118, 6.1295], ranges = [(0.211, 24.637), (0.283, 30.4), (0.0, 53.618), (0.157, 24.278)]
  bootstrap Kruskal-Wallis H = 19.939; p under the claim's seed and +1000..+4000: [0.0002, 0.0, 0.0, 0.0, 0.0]
rip_part: n = [184, 132, 233, 115], medians = [0.237, 0.2686, 0.2355, 0.1942], ranges = [(0.01, 0.649), (0.01, 0.664), (0.0, 0.895), (0.005, 0.59)]
  bootstrap Kruskal-Wallis H = 17.853; p under the claim's seed and +1000..+4000: [0.001, 0.0002, 0.0, 0.0002, 0.0006]
rate: inverted-U True within tolerance [True, True, True, True]
participation: inverted-U True within tolerance [True, True, True, True]
by mouse (median SPW-R rate): {('E13.5', 'e13_16f1'): 7.76, ('E13.5', 'e13_1f1'): 7.0, ('E13.5', 'e13_1m1'): 5.28, ('E13.5', 'e13_26m1'): 7.91, ('E14.5', 'e14_1m1'): 8.09, ('E14.5', 'e14_2m2'): 11.87, ('E14.5', 'e14_2m3'): 9.53, ('E15.5', 'e15_10m1'): 6.96, ('E15.5', 'e15_4m1'): 7.86, ('E15.5', 'e15_4m2'): 6.9, ('E15.5', 'e15_5m1'): 7.18, ('E15.5', 'e15_9f1'): 10.02, ('E16.5', 'e16_1f1'): 4.79, ('E16.5', 'e16_2m1'): 7.59, ('E16.5', 'e16_3m1'): 5.78}

Result: reproduced. SPW-R rate medians 7.48, 8.82, 7.91 and 6.13 Hz and participation 0.237, 0.269, 0.236 and 0.194 are within tolerance, both are inverted U, and both bootstrap Kruskal-Wallis tests give p <= 0.001 under all seeds.

Claim fig2g-ripple-cofiring: SBD pairs cofire more than DBD pairs in SPW-Rs (median 0.0399 against 0.0231).

In [16]:
def sbd_dbd(df, col):
    s, d = df[df.sbd][col].dropna(), df[~df.sbd][col].dropna()
    p = stats.ranksums(s, d).pvalue
    print(f"{col}: SBD median {s.median():.4f} (n = {len(s)}), DBD median {d.median():.4f} (n = {len(d)}), "
          f"two-sided Wilcoxon rank-sum p = {p:.3g}; dropped (NaN) SBD {int(df[df.sbd][col].isna().sum())}, DBD {int(df[~df.sbd][col].isna().sum())}")
    return s.median(), d.median(), p
s, d, p = sbd_dbd(PAIRS, "rip_corr")
print("within tolerance:", abs(s - 0.0399) <= 0.004, abs(d - 0.0231) <= 0.0023)
print("per birthdate SBD/DBD medians:", PAIRS.groupby(["birthdate", "sbd"]).rip_corr.median().round(4).to_dict())
rip_corr: SBD median 0.0385 (n = 3738), DBD median 0.0226 (n = 50171), two-sided Wilcoxon rank-sum p = 4.74e-98; dropped (NaN) SBD 13, DBD 290
within tolerance: True True
per birthdate SBD/DBD medians: {('E13.5', False): 0.0192, ('E13.5', True): 0.0393, ('E14.5', False): 0.0323, ('E14.5', True): 0.0408, ('E15.5', False): 0.0285, ('E15.5', True): 0.0394, ('E16.5', False): 0.0164, ('E16.5', True): 0.0308}

Result: reproduced. SBD median 0.0385 against DBD 0.0226 (3,738 and 50,171 pairs with a correlation), rank-sum p = 4.7e-98; both within tolerance.

Claim fig2b-synchrony-per-animal: Same-birthdate (SBD) pairs fire more synchronously than different-birthdate (DBD) pairs in 11 of 13 animals.

In [17]:
rows = []
for sbj, g in PAIRS.groupby("subject"):
    s, d = g[g.sbd], g[~g.sbd]
    ra = (s.rip_corr.dropna(), d.rip_corr.dropna())
    rb = (s["sync"].dropna(), d["sync"].dropna())
    pa = stats.ranksums(*ra).pvalue if len(ra[0]) and len(ra[1]) else np.nan
    rows.append({"subject": sbj, "sbd_pairs": len(s), "dbd_pairs": len(d),
                 "a_sbd_med": ra[0].median() if len(ra[0]) else np.nan, "a_dbd_med": ra[1].median(), "a_p": pa,
                 "a_higher_sig": bool(len(ra[0]) and ra[0].median() > ra[1].median() and pa < 0.05),
                 "b_diff": (rb[0].mean() - rb[1].mean()) if len(rb[0]) else np.nan})
A = pd.DataFrame(rows)
A["b_positive"] = A.b_diff > 0
print(A.round(4).to_string())
el = A[A.sbd_pairs > 0]
t13 = A[~A.subject.isin(["e13_1f1", "e13_1m1"])]
print(f"the 13 animals of the claim (without e13_1f1 and e13_1m1, the two E13.5 mice with one light-responsive cell in most sessions): "
      f"(a) SBD higher with p < 0.05 in {int(t13.a_higher_sig.sum())}; (b) z-scored CCG difference > 0 in {int(t13.b_positive.sum())}")
print(f"animals with SBD pairs: {len(el)}; (a) SBD higher with p < 0.05: {int(el.a_higher_sig.sum())}; "
      f"(a') SBD median higher regardless of p: {int((el.a_sbd_med > el.a_dbd_med).sum())}; (b) mean z-scored CCG difference > 0: {int(el.b_positive.sum())}")
     subject  sbd_pairs  dbd_pairs  a_sbd_med  a_dbd_med     a_p  a_higher_sig  b_diff  b_positive
0   e13_16f1        977      13198     0.0403     0.0183  0.0000          True  1.2942        True
1    e13_1f1          1        349     0.0023     0.0386  0.3199         False  0.6701        True
2    e13_1m1          2       1348     0.0334     0.0250  0.7743         False -0.8463       False
3   e13_26m1        220       6260     0.0328     0.0201  0.0000          True  1.2603        True
4    e14_1m1        174       2838     0.0432     0.0318  0.0277          True  0.5391        True
5    e14_2m2          8       1068     0.0551     0.0289  0.0266          True  2.8483        True
6    e14_2m3        351       2494     0.0399     0.0350  0.0670         False  0.2059        True
7   e15_10m1        206       3316     0.0379     0.0244  0.0000          True  0.7846        True
8    e15_4m1        199       1452     0.0394     0.0329  0.0657         False  0.2905        True
9    e15_4m2        707       3566     0.0279     0.0248  0.0214          True -0.1117       False
10   e15_5m1         59        943     0.0385     0.0245  0.0103          True  0.5492        True
11   e15_9f1        408       4365     0.0567     0.0341  0.0000          True  0.9744        True
12   e16_1f1        148       2521     0.0206     0.0085  0.0000          True  0.5210        True
13   e16_2m1         48       1022     0.0087     0.0156  0.6151         False  0.6069        True
14   e16_3m1        243       5721     0.0400     0.0215  0.0000          True  0.5365        True
the 13 animals of the claim (without e13_1f1 and e13_1m1, the two E13.5 mice with one light-responsive cell in most sessions): (a) SBD higher with p < 0.05 in 10; (b) z-scored CCG difference > 0 in 12
animals with SBD pairs: 15; (a) SBD higher with p < 0.05: 10; (a') SBD median higher regardless of p: 13; (b) mean z-scored CCG difference > 0: 13

Result: reproduced. Of the 13 animals of the claim, SBD pairs cofire more in SPW-Rs than DBD pairs with p < 0.05 in 10 (reading a), and the z-scored CCG of SBD pairs exceeds that of DBD pairs in 12 (reading b); both are in the range 10 to 12. The two E13.5 mice the paper leaves out do have SBD pairs in the files (1 and 2 pairs).

Theta¶

Two LFP channels per session are read in full (h.theta_session), over the 96 homecage-mouse sessions and the 8 sessions of the two novel-only mice. The main one follows the Methods' rule, a channel with a positive sharp wave (above the centre of the pyramidal layer). The sharp wave of each channel is its mean LFP 0 to 50 ms after the ripple peaks minus its mean 100 to 50 ms before them, in microvolts, over the ripples of homecage non-REM sleep (all ripples in the sessions with 20 or fewer of them, printed below). Among the channels of the centre's shank with a positive sharp wave and larger rel_y than the centre (above it), the one with the largest ripple power is taken, on another shank when that shank has none, and the channel next to the centre with larger rel_y when no shank has one (assumption, pick_theta_channel; how the paper picked among qualifying channels is not said). Both halves of the Methods' phrase are required: in the first revision a positive channel below the centre also qualified, which 6 sessions used (verifier, round 2). The second channel is the pyramidal layer centre itself, run as a variant, and each theta claim is also shown on the sessions whose channel follows the rule.

In [18]:
TH_SESS = [META[s] for s in S.loc[S.homecage_mouse | S.subject.isin(h.NOVEL_MICE), "session"]]
t = time.time()
th_res = h.run_sessions(h.theta_session_novel, TH_SESS, workers=5)
TC_ALL = pd.DataFrame([c for r in th_res for c in r[0]])
TP_ALL = pd.DataFrame([p for r in th_res for p in r[1]])
TO = pd.DataFrame([{k: v for k, v in r[2].items() if k != "theta_corr_mat"} for r in th_res])
TR_ALL = pd.DataFrame([x for r in th_res for x in r[3]])
TMAT = {r[2]["session"]: r[2]["theta_corr_mat"] for r in th_res}
# main reading: the theta channel of the Methods' rule; variant: the pyramidal layer centre
TC, TP, TR = (d[d.ref == "rule"].copy() for d in (TC_ALL, TP_ALL, TR_ALL))
TCc, TPc, TRc = (d[d.ref == "centre"].copy() for d in (TC_ALL, TP_ALL, TR_ALL))
RULE_SESS = set(TO[TO["where"] != "none positive, next channel with larger rel_y"].session)
print(f"{time.time()-t:.0f} s, {len(th_res)} sessions; peak memory of this process {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1e6:.2f} GB")
print("theta channel, by where a channel with a positive sharp wave was found:", TO["where"].value_counts().to_dict())
print("theta channel position relative to the layer centre of its shank (rel_y difference, um):", TO.dy_theta.value_counts().sort_index().to_dict())
print("sharp wave (uV, 0-50 ms after ripple peaks minus 100-50 ms before): theta channel median", round(TO.sw_theta.median(), 1),
      "range", round(TO.sw_theta.min(), 1), "to", round(TO.sw_theta.max(), 1), "; pyramidal layer centre median", round(TO.sw_pyr.median(), 1))
print("on the centre's shank, channel next above the centre: median", round(TO.sw_next_above.median(), 1), "uV, positive in", int((TO.sw_next_above > 0).sum()),
      "of", int(TO.sw_next_above.notna().sum()), "; next below: median", round(TO.sw_next_below.median(), 1), "uV, negative in", int((TO.sw_next_below < 0).sum()),
      "of", int(TO.sw_next_below.notna().sum()))
print("channels with a positive sharp wave on the centre's shank, with larger rel_y than the centre:", int(TO.n_pos_above.sum()), "; with smaller:", int(TO.n_pos_below.sum()),
      "; sessions with any positive channel above / below:", int((TO.n_pos_above > 0).sum()), "/", int((TO.n_pos_below > 0).sum()))
rs = TO[TO.session.isin(RULE_SESS)]
print("sessions following the rule:", len(RULE_SESS), "of", len(TO), "; their theta channel lies above the centre (rel_y larger) in", int((rs.dy_theta > 0).sum()),
      "and has a positive sharp wave in", int((rs.sw_theta > 0).sum()))
print("sessions whose sharp wave uses all ripples (20 or fewer in homecage non-REM):", TO[TO.all_ripples].session.tolist())
print("theta channel same as the layer centre:", int((TO.theta_ch == TO.pyr_ch).sum()), "sessions")
print("theta cycles in homecage wake per session: median", int(TO.n_cycles_hc_wake.median()), "range", TO.n_cycles_hc_wake.min(), "-", TO.n_cycles_hc_wake.max(),
      "; on the centre channel median", int(TO.n_cycles_hc_wake_centre.median()))
hcm = ~TC.subject.isin(h.HOMECAGE_EXCLUDED)
print("clock check, light-responsive cells of homecage mice locked in wake at p < 0.01: phases as given",
      int((TC[hcm].wake_p < 0.01).sum()), "of", int(hcm.sum()), "; with spikes against the phase 10.3 s later",
      int((TC[hcm].wake_p_shift < 0.01).sum()), "; median wake MRL", round(TC[hcm].wake_mrl.median(), 4), "against", round(TC[hcm].wake_mrl_shift.median(), 4))
print(TO[["session", "where", "all_ripples", "dy_theta", "sw_theta", "sw_pyr", "sw_next_above", "sw_next_below", "n_pos_above", "n_pos_below"]].round(1).to_string())
1808 s, 104 sessions; peak memory of this process 0.71 GB
theta channel, by where a channel with a positive sharp wave was found: {'same shank': 66, 'none positive, next channel with larger rel_y': 32, 'other shank': 6}
theta channel position relative to the layer centre of its shank (rel_y difference, um): {0.0: 1, 20.0: 72, 40.0: 24, 60.0: 6, 80.0: 1}
sharp wave (uV, 0-50 ms after ripple peaks minus 100-50 ms before): theta channel median 10.4 range -142.1 to 145.2 ; pyramidal layer centre median -48.6
on the centre's shank, channel next above the centre: median -12.7 uV, positive in 42 of 103 ; next below: median -105.5 uV, negative in 81 of 83
channels with a positive sharp wave on the centre's shank, with larger rel_y than the centre: 320 ; with smaller: 7 ; sessions with any positive channel above / below: 66 / 5
sessions following the rule: 72 of 104 ; their theta channel lies above the centre (rel_y larger) in 72 and has a positive sharp wave in 72
sessions whose sharp wave uses all ripples (20 or fewer in homecage non-REM): ['e13_1f1_200305', 'e13_1f1_200306', 'e13_1f1_200307', 'e13_1m1_200305', 'e15_4m1_191125', 'e15_9f1_200723']
theta channel same as the layer centre: 1 sessions
theta cycles in homecage wake per session: median 2994 range 63 - 15512 ; on the centre channel median 2841
clock check, light-responsive cells of homecage mice locked in wake at p < 0.01: phases as given 558 of 664 ; with spikes against the phase 10.3 s later 29 ; median wake MRL 0.0981 against 0.0151
              session                                          where  all_ripples  dy_theta  sw_theta  sw_pyr  sw_next_above  sw_next_below  n_pos_above  n_pos_below
0     e13_16f1_210302  none positive, next channel with larger rel_y        False      20.0    -114.2  -152.6         -114.2         -227.9            0            0
1     e13_16f1_210312                                    other shank        False      20.0      21.2  -140.2          -80.9         -197.5            0            0
2     e13_16f1_210314                                     same shank        False      60.0       7.9   -87.3          -36.6         -154.4            2            0
3     e13_16f1_210315                                    other shank        False      20.0      24.3  -119.7          -71.2         -184.9            0            0
4     e13_16f1_210317  none positive, next channel with larger rel_y        False      20.0    -131.0  -176.4         -131.0         -254.7            0            0
5     e13_16f1_210319  none positive, next channel with larger rel_y        False      20.0    -114.7  -174.1         -114.7         -215.6            0            0
6     e13_16f1_210322                                     same shank        False      60.0      14.5   -59.6          -18.6         -157.8            2            0
7     e13_16f1_210328                                     same shank        False      40.0       4.0   -36.2           -5.6            NaN            2            0
8     e13_16f1_210331                                     same shank        False      20.0      11.2   -20.4           11.2            NaN            3            0
9      e13_1f1_200228                                     same shank        False      20.0      16.3     7.1           16.3          -34.6            5            0
10     e13_1f1_200229                                     same shank        False      40.0       8.8   -40.3          -25.1          -90.2            2            0
11     e13_1f1_200305  none positive, next channel with larger rel_y         True      20.0     -85.4  -107.2          -85.4         -141.7            0            0
12     e13_1f1_200306  none positive, next channel with larger rel_y         True       0.0     -30.0   -30.0            NaN          -54.6            0            2
13     e13_1f1_200307  none positive, next channel with larger rel_y         True      20.0     -96.9  -113.0          -96.9         -128.0            0            2
14     e13_1m1_200220                                     same shank        False      20.0      62.1    66.6           62.1            NaN            6            0
15     e13_1m1_200221                                     same shank        False      20.0      66.3    16.3           66.3          -84.8            5            0
16     e13_1m1_200222  none positive, next channel with larger rel_y        False      20.0     -57.8   -64.4          -57.8         -142.6            0            0
17     e13_1m1_200223                                     same shank        False      40.0      92.9   -65.4           -4.0         -240.6            4            0
18     e13_1m1_200224  none positive, next channel with larger rel_y        False      20.0     -32.4  -132.3          -32.4         -176.8            0            0
19     e13_1m1_200225                                     same shank        False      20.0      25.1    30.5           25.1          -78.2            3            0
20     e13_1m1_200226  none positive, next channel with larger rel_y        False      20.0     -53.9   -43.7          -53.9         -128.6            0            0
21     e13_1m1_200227                                     same shank        False      40.0      54.0   -92.2          -88.4         -237.9            6            0
22     e13_1m1_200228  none positive, next channel with larger rel_y        False      20.0    -117.7  -114.2         -117.7         -192.0            0            0
23     e13_1m1_200229                                     same shank        False      40.0      21.5   -52.4          -42.6         -206.6            2            0
24     e13_1m1_200305                                     same shank         True      20.0      21.8    37.4           21.8          -94.0            3            0
25     e13_1m1_200306  none positive, next channel with larger rel_y        False      20.0     -34.8   -86.8          -34.8          -64.2            0            0
26    e13_26m1_211019                                     same shank        False      20.0      17.1     1.7           17.1            NaN            5            0
27    e13_26m1_211116  none positive, next channel with larger rel_y        False      20.0     -61.1   -87.4          -61.1            NaN            0            0
28    e13_26m1_211119  none positive, next channel with larger rel_y        False      20.0     -48.5   -83.9          -48.5            NaN            0            0
29    e13_26m1_211124  none positive, next channel with larger rel_y        False      20.0    -131.8  -149.3         -131.8            NaN            0            0
30     e14_1m1_200130                                     same shank        False      20.0       7.6   -24.7            7.6         -142.5            3            0
31     e14_1m1_200201                                     same shank        False      20.0      34.8    -0.5           34.8          -66.2           11            0
32     e14_1m1_200203  none positive, next channel with larger rel_y        False      20.0     -24.8   -52.5          -24.8         -121.4            0            0
33     e14_1m1_200204                                     same shank        False      40.0       1.1   -56.8          -18.6         -106.3            1            0
34     e14_1m1_200205  none positive, next channel with larger rel_y        False      20.0     -75.5  -102.2          -75.5         -157.5            0            0
35     e14_1m1_200206  none positive, next channel with larger rel_y        False      20.0     -17.9   -48.8          -17.9          -84.5            0            0
36     e14_1m1_200207                                     same shank        False      20.0      47.4     1.9           47.4          -34.8            6            0
37     e14_1m1_200208                                     same shank        False      20.0      20.5   -14.0           20.5          -84.9            2            0
38     e14_1m1_200210                                     same shank        False      40.0       3.0  -102.8          -12.7         -156.0            1            0
39     e14_1m1_200211                                     same shank        False      20.0      19.3   -17.0           19.3          -92.2            3            0
40     e14_1m1_200212  none positive, next channel with larger rel_y        False      20.0     -10.9   -45.7          -10.9         -102.1            0            0
41     e14_1m1_200213                                     same shank        False      20.0      18.6   -29.3           18.6         -119.4            3            0
42     e14_2m2_201013                                     same shank        False      20.0      59.0    -1.4           59.0          -71.8           14            0
43     e14_2m2_201017                                     same shank        False      40.0      17.6   -50.5           -1.2            NaN            2            0
44     e14_2m2_201019                                     same shank        False      60.0       7.0  -103.6          -37.2            NaN            2            0
45     e14_2m2_201022                                    other shank        False      40.0       5.6   -32.2          -13.2          -70.7            0            0
46     e14_2m3_201017  none positive, next channel with larger rel_y        False      20.0     -63.6  -103.4          -63.6         -139.4            0            0
47     e14_2m3_201019                                     same shank        False      20.0      22.1   -19.6           22.1          -46.6           11            0
48     e14_2m3_201118                                     same shank        False      20.0      41.5    46.2           41.5            NaN            3            0
49     e14_2m3_201121                                     same shank        False      20.0       1.4   -57.1            1.4         -103.3            4            0
50     e14_2m3_201125                                     same shank        False      40.0      21.7   -55.0          -44.8         -111.2            8            0
51     e14_2m3_201129                                     same shank        False      20.0      95.2    18.9           95.2           16.0            7            1
52     e14_2m3_201206                                     same shank        False      40.0      49.0   -35.8          -32.1         -111.5            4            0
53     e14_2m3_201208                                     same shank        False      40.0      51.6   -35.7          -38.1         -110.9            4            0
54    e15_10m1_200716                                     same shank        False      80.0       2.5   -82.1          -57.5         -114.7            1            0
55    e15_10m1_200719                                     same shank        False      40.0       9.6   -55.0          -26.4         -105.5            3            0
56    e15_10m1_200723                                     same shank        False      20.0      59.3    14.3           59.3          -59.0           14            0
57    e15_10m1_200727                                     same shank        False      20.0      29.8    -0.2           29.8          -69.3           12            0
58    e15_10m1_200803                                     same shank        False      20.0      93.5    29.6           93.5            NaN           14            0
59    e15_10m1_200809                                     same shank        False      20.0      72.6     5.8           72.6            NaN            7            0
60    e15_10m1_200812                                     same shank        False      20.0       6.6   -37.7            6.6          -87.5            3            0
61    e15_13f1_220117                                     same shank        False      20.0      74.7    20.8           74.7           -8.5            9            0
62    e15_13f1_220118  none positive, next channel with larger rel_y        False      20.0      -4.2   -50.2           -4.2          -90.5            0            0
63    e15_13f1_220119                                     same shank        False      40.0      23.4  -108.0           -2.4         -151.2            6            0
64    e15_13f1_220120                                     same shank        False      20.0       4.3   -36.4            4.3         -155.8            7            0
65     e15_4m1_191121                                     same shank        False      20.0      51.3   -48.4           51.3         -177.1            5            0
66     e15_4m1_191125                                     same shank         True      20.0      66.9     8.1           66.9         -102.5            6            0
67     e15_4m1_191203                                     same shank        False      40.0      64.0    -5.6           57.8          -44.0            2            0
68     e15_4m2_191212  none positive, next channel with larger rel_y        False      20.0     -20.7   -48.3          -20.7            NaN            0            0
69     e15_4m2_191213                                     same shank        False      20.0      30.2   -31.8           30.2         -134.7            4            0
70     e15_4m2_191215                                     same shank        False      20.0      42.5   -27.6           42.5          -96.7           10            0
71     e15_4m2_191216                                     same shank        False      20.0      58.1    39.9           58.1           14.2            3            1
72   e15_5m1_200313_1                                     same shank        False      20.0      67.6    72.1           67.6            NaN            2            0
73   e15_5m1_200313_2                                     same shank        False      40.0     145.2   114.1          128.2            NaN            7            0
74     e15_5m1_200314                                     same shank        False      60.0      40.2   -45.2           -3.7         -152.8            3            0
75     e15_9f1_200715                                     same shank        False      20.0      76.7    41.9           76.7          -21.0           10            1
76     e15_9f1_200717  none positive, next channel with larger rel_y        False      20.0     -25.9   -54.4          -25.9          -82.2            0            0
77     e15_9f1_200720                                     same shank        False      60.0       1.7   -51.4          -17.0          -71.9            1            0
78     e15_9f1_200723                                    other shank         True      40.0      14.8   -67.3          -51.4          -89.0            0            0
79     e15_9f1_200729                                     same shank        False      20.0      15.3   -26.7           15.3          -50.3            1            0
80     e15_9f1_200802                                    other shank        False      20.0       2.2   -53.6          -30.2          -74.0            0            0
81     e15_9f1_200809  none positive, next channel with larger rel_y        False      20.0     -16.9   -72.9          -16.9         -101.0            0            0
82     e16_1f1_200823                                    other shank        False      40.0       7.3   -24.5           -4.6          -55.3            0            0
83     e16_1f1_200917                                     same shank        False      40.0      21.4   -54.4           -6.0          -98.6            4            0
84     e16_1f1_200918                                     same shank        False      40.0      16.4   -55.5          -13.4         -101.3            4            0
85     e16_1f1_200919  none positive, next channel with larger rel_y        False      40.0     -91.7   -68.7          -91.7         -187.1            0            0
86     e16_1f1_200920  none positive, next channel with larger rel_y        False      40.0    -108.1   -68.4         -108.1         -173.3            0            0
87     e16_1f1_200923                                     same shank        False      60.0       9.6  -112.0          -41.8         -191.5            1            0
88     e16_1f1_201001                                     same shank        False      20.0      38.9    25.6           38.9           -2.2            5            0
89     e16_1f1_201002                                     same shank        False      20.0       4.3   -59.7            4.3         -124.6            9            0
90     e16_1f1_201004                                     same shank        False      20.0      11.6   -14.1           11.6          -46.4            2            0
91     e16_2m1_201116                                     same shank        False      20.0      41.1     3.2           41.1          -60.6            6            0
92     e16_2m1_201119  none positive, next channel with larger rel_y        False      20.0    -125.3  -204.3         -125.3         -294.5            0            0
93     e16_2m1_201121                                     same shank        False      40.0      15.2  -112.4          -35.0         -210.3            2            0
94     e16_2m1_201129  none positive, next channel with larger rel_y        False      20.0    -101.7  -185.9         -101.7         -250.1            0            0
95     e16_2m1_201206  none positive, next channel with larger rel_y        False      20.0    -142.1  -231.3         -142.1          -74.7            0            0
96     e16_3m1_210111                                     same shank        False      20.0      40.3     3.2           40.3            NaN            6            0
97     e16_3m1_210119  none positive, next channel with larger rel_y        False      20.0     -40.4   -65.4          -40.4         -133.0            0            0
98     e16_3m1_210201                                     same shank        False      20.0       0.1   -27.8            0.1            NaN            7            0
99     e16_3m1_210203                                     same shank        False      40.0       6.1   -64.6          -29.2            NaN            3            0
100    e16_3m2_211210  none positive, next channel with larger rel_y        False      20.0     -53.3   -48.7          -53.3            NaN            0            0
101    e16_3m2_211211  none positive, next channel with larger rel_y        False      20.0     -25.6   -26.2          -25.6            NaN            0            0
102    e16_3m2_211212                                     same shank        False      20.0      13.1     6.6           13.1            NaN            2            0
103    e16_3m2_211213  none positive, next channel with larger rel_y        False      20.0     -78.2   -87.7          -78.2         -166.0            0            0

Claim fig1f-rem-shift: Earlier-born light-responsive neurons more often shift their preferred theta phase in REM sleep (30.89% at E13.5 to 19.7% at E16.5; regression slope -3.42% per day).

In [19]:
TCH = TC[hcm].copy()
def rem_shift(df, thr):
    b = df[(df.wake_p < thr) & (df.rem_p < thr)].copy()
    wd, rd = np.degrees(b.wake_phase), np.degrees(b.rem_phase)
    b["shift"] = ((wd >= 120) & (wd <= 300)) & ~((rd >= 120) & (rd <= 300))
    return b
def slope_test(b, claim, k):
    rng = np.random.default_rng(seed(claim) + k)
    x = np.array([h.BD_DAY[d] for d in h.BIRTHDATES])
    grp = [b[b.birthdate == d]["shift"].values.astype(float) for d in h.BIRTHDATES]
    fr = np.array([g.mean() * 100 for g in grp])
    sl = np.polyfit(x, fr, 1)[0]
    boots = [np.polyfit(x, [rng.choice(g, len(g)).mean() * 100 for g in grp], 1)[0] for _ in range(1000)]
    pool = np.concatenate(grp)
    null = [np.polyfit(x, [rng.choice(pool, len(g)).mean() * 100 for g in grp], 1)[0] for _ in range(1000)]
    return fr, sl, np.percentile(boots, [2.5, 97.5]), float(np.mean(np.array(null) <= sl))
for thr in (0.01, 0.05):
    b = rem_shift(TCH, thr)
    print(f"Rayleigh threshold {thr}: cells locked in both states per birthdate {b.groupby('birthdate').size().tolist()}")
    for k in (SEEDS_PLUS if thr == 0.01 else [0]):
        fr, sl, ci, p = slope_test(b, "fig1f-rem-shift", k)
        print(f"  seed +{k}: % REM shifting {np.round(fr, 2).tolist()}, slope {sl:.2f} %/day, 95% CI {np.round(ci, 2).tolist()}, one-tailed p = {p:.3f}")
print("paper's n locked in both states (legend): [123, 106, 143, 76]")
for lab, df in (("variant, sessions whose channel follows the rule (positive sharp wave above the centre)", TCH[TCH.session.isin(RULE_SESS)]),
                ("variant, phase from the pyramidal layer centre channel", TCc[~TCc.subject.isin(h.HOMECAGE_EXCLUDED)])):
    b = rem_shift(df, 0.01)
    fr, sl, ci, p = slope_test(b, "fig1f-rem-shift", 0)
    print(f"{lab}: n {b.groupby('birthdate').size().tolist()}, % REM shifting {np.round(fr, 2).tolist()}, slope {sl:.2f} %/day, 95% CI {np.round(ci, 2).tolist()}, one-tailed p = {p:.3f}")
b = rem_shift(TCH, 0.01)
print("within tolerance (0.01):", [abs(a - e) <= t for a, e, t in zip(slope_test(b, 'fig1f-rem-shift', 0)[0], [30.89, 24.5, 23.8, 19.7], [3.09, 2.45, 2.38, 1.97])])
print("by mouse, % shifting (0.01):", (b.groupby(["birthdate", "subject"])["shift"].mean() * 100).round(1).to_dict())
Rayleigh threshold 0.01: cells locked in both states per birthdate [90, 75, 76, 60]
  seed +0: % REM shifting [27.78, 21.33, 21.05, 23.33], slope -1.36 %/day, 95% CI [-5.8, 2.9], one-tailed p = 0.277
  seed +1000: % REM shifting [27.78, 21.33, 21.05, 23.33], slope -1.36 %/day, 95% CI [-5.53, 3.23], one-tailed p = 0.301
  seed +2000: % REM shifting [27.78, 21.33, 21.05, 23.33], slope -1.36 %/day, 95% CI [-5.93, 3.16], one-tailed p = 0.280
  seed +3000: % REM shifting [27.78, 21.33, 21.05, 23.33], slope -1.36 %/day, 95% CI [-5.75, 3.04], one-tailed p = 0.272
  seed +4000: % REM shifting [27.78, 21.33, 21.05, 23.33], slope -1.36 %/day, 95% CI [-5.9, 2.87], one-tailed p = 0.269
Rayleigh threshold 0.05: cells locked in both states per birthdate [112, 93, 109, 71]
  seed +0: % REM shifting [28.57, 23.66, 24.77, 19.72], slope -2.54 %/day, 95% CI [-6.39, 1.0], one-tailed p = 0.092
paper's n locked in both states (legend): [123, 106, 143, 76]
variant, sessions whose channel follows the rule (positive sharp wave above the centre): n [54, 65, 63, 46], % REM shifting [27.78, 20.0, 17.46, 23.91], slope -1.41 %/day, 95% CI [-6.76, 3.49], one-tailed p = 0.259
variant, phase from the pyramidal layer centre channel: n [93, 83, 75, 64], % REM shifting [27.96, 20.48, 18.67, 21.88], slope -2.01 %/day, 95% CI [-5.83, 2.53], one-tailed p = 0.183
within tolerance (0.01): [np.False_, np.False_, np.False_, np.False_]
by mouse, % shifting (0.01): {('E13.5', 'e13_16f1'): 33.3, ('E13.5', 'e13_1f1'): 0.0, ('E13.5', 'e13_1m1'): 16.7, ('E13.5', 'e13_26m1'): 11.8, ('E14.5', 'e14_1m1'): 24.0, ('E14.5', 'e14_2m2'): 75.0, ('E14.5', 'e14_2m3'): 9.5, ('E15.5', 'e15_10m1'): 5.0, ('E15.5', 'e15_4m1'): 40.0, ('E15.5', 'e15_4m2'): 14.3, ('E15.5', 'e15_5m1'): 0.0, ('E15.5', 'e15_9f1'): 34.6, ('E16.5', 'e16_1f1'): 27.8, ('E16.5', 'e16_2m1'): 27.3, ('E16.5', 'e16_3m1'): 19.4}

Result: not reproduced, resting on the choice of theta channel. On the rule's channel 90, 75, 76 and 60 cells are locked in both states (the legend's n are 123, 106, 143 and 76), and the fractions of REM-shifting cells are 27.78, 21.33, 21.05 and 23.33%, all four outside tolerance; the slope is -1.36% per day (95% interval -5.8 to 2.9) with one-tailed p 0.269 to 0.301 over the five seeds, so it is not significant. No reading gives a significant slope: the code's Rayleigh threshold of 0.05 gives -2.54 (p = 0.092), the sessions whose channel follows the rule only -1.41 (p = 0.259), and the layer centre channel -2.01 (p = 0.183).

Claim fig2d-theta-depth: Intermediate-birthdate neurons have lower theta depth modulation in waking (medians 0.127, 0.099, 0.094, 0.103) but not in REM sleep.

In [20]:
w = TCH[TCH.wake_p < 0.01].rename(columns={"wake_mrl": "wake_depth"})
r = TCH[TCH.rem_p < 0.01].rename(columns={"rem_mrl": "rem_depth"})
mw, pw = by_bd(w, "wake_depth", "fig2d-theta-depth")
mr, pr = by_bd(r, "rem_depth", "fig2d-theta-depth")
print("wake: E14.5 and E15.5 both below E13.5 and E16.5:", max(mw[1], mw[2]) < min(mw[0], mw[3]),
      "; within tolerance:", [abs(a - e) <= 0.1 * e for a, e in zip(mw, [0.127, 0.099, 0.094, 0.103])])
print("by mouse (median wake depth):", w.groupby(["birthdate", "subject"]).wake_depth.median().round(3).to_dict())
for lab, df in (("variant, sessions whose channel follows the rule", TCH[TCH.session.isin(RULE_SESS)]),
                ("variant, pyramidal layer centre channel", TCc[~TCc.subject.isin(h.HOMECAGE_EXCLUDED)])):
    ww = df[df.wake_p < 0.01]
    g = [ww[ww.birthdate == b_].wake_mrl.values for b_ in h.BIRTHDATES]
    st, pv = h.boot_kw(g, rng=np.random.default_rng(seed("fig2d-theta-depth")))
    md = [float(np.median(x)) for x in g]
    print(f"{lab}: wake n {[len(x) for x in g]}, medians {np.round(md, 4).tolist()}, H = {st:.2f}, p = {pv:.4f}; "
          f"E14.5 and E15.5 below both: {max(md[1], md[2]) < min(md[0], md[3])}; within tolerance: {[abs(a - e) <= 0.1 * e for a, e in zip(md, [0.127, 0.099, 0.094, 0.103])]}")
wake_depth: n = [176, 114, 172, 96], medians = [0.1206, 0.0903, 0.0925, 0.104], ranges = [(0.035, 0.307), (0.023, 0.319), (0.036, 0.291), (0.028, 0.359)]
  bootstrap Kruskal-Wallis H = 35.813; p under the claim's seed and +1000..+4000: [0.0, 0.0, 0.0, 0.0, 0.0]
rem_depth: n = [98, 87, 106, 70], medians = [0.1464, 0.1414, 0.1472, 0.1479], ranges = [(0.034, 0.357), (0.03, 0.358), (0.044, 0.373), (0.032, 0.436)]
  bootstrap Kruskal-Wallis H = 1.654; p under the claim's seed and +1000..+4000: [0.6406, 0.66, 0.6628, 0.6568, 0.6436]
wake: E14.5 and E15.5 both below E13.5 and E16.5: True ; within tolerance: [True, True, True, True]
by mouse (median wake depth): {('E13.5', 'e13_16f1'): 0.125, ('E13.5', 'e13_1f1'): 0.114, ('E13.5', 'e13_1m1'): 0.098, ('E13.5', 'e13_26m1'): 0.103, ('E14.5', 'e14_1m1'): 0.136, ('E14.5', 'e14_2m2'): 0.096, ('E14.5', 'e14_2m3'): 0.07, ('E15.5', 'e15_10m1'): 0.09, ('E15.5', 'e15_4m1'): 0.125, ('E15.5', 'e15_4m2'): 0.079, ('E15.5', 'e15_5m1'): 0.086, ('E15.5', 'e15_9f1'): 0.094, ('E16.5', 'e16_1f1'): 0.091, ('E16.5', 'e16_2m1'): 0.099, ('E16.5', 'e16_3m1'): 0.106}
variant, sessions whose channel follows the rule: wake n [103, 99, 142, 67], medians [0.1219, 0.0886, 0.0925, 0.1041], H = 34.58, p = 0.0000; E14.5 and E15.5 below both: True; within tolerance: [True, False, True, True]
variant, pyramidal layer centre channel: wake n [175, 119, 171, 102], medians [0.1207, 0.0946, 0.0915, 0.1147], H = 37.32, p = 0.0000; E14.5 and E15.5 below both: True; within tolerance: [True, True, True, False]

Result: reproduced, resting on the choice of theta channel. Wake depth modulation medians 0.121, 0.090, 0.093 and 0.104 are within tolerance, E14.5 and E15.5 are below E13.5 and E16.5, and the bootstrap Kruskal-Wallis gives p < 0.0002 under all seeds; in REM sleep the medians are 0.141 to 0.148 and p = 0.64 to 0.66, so no difference is found, as the paper reports. The variants keep the profile and the test but each puts one median just outside tolerance: E14.5 0.089 on the sessions whose channel follows the rule, E16.5 0.115 on the layer centre channel.

Claim fig2c-theta-cofiring: SBD pairs cofire more than DBD pairs in theta cycles (median 0.0189 against 0.0087).

In [21]:
TPH = TP[~TP.subject.isin(h.HOMECAGE_EXCLUDED)]
s, d, p = sbd_dbd(TPH, "theta_corr")
print("pairs SBD", int(TPH.sbd.sum()), "DBD", int((~TPH.sbd).sum()), "; within tolerance:", abs(s - 0.0189) <= 0.0019, abs(d - 0.0087) <= 0.0009)
print("variant, sessions whose channel follows the rule:")
s2, d2, p2 = sbd_dbd(TPH[TPH.session.isin(RULE_SESS)], "theta_corr")
print("   within tolerance:", abs(s2 - 0.0189) <= 0.0019, abs(d2 - 0.0087) <= 0.0009)
print("variant, pyramidal layer centre channel:")
s3, d3, p3 = sbd_dbd(TPc[~TPc.subject.isin(h.HOMECAGE_EXCLUDED)], "theta_corr")
print("   within tolerance:", abs(s3 - 0.0189) <= 0.0019, abs(d3 - 0.0087) <= 0.0009)
print("per birthdate SBD/DBD medians:", TPH.groupby(["birthdate", "sbd"]).theta_corr.median().round(4).to_dict())
theta_corr: SBD median 0.0170 (n = 3727), DBD median 0.0070 (n = 50392), two-sided Wilcoxon rank-sum p = 1.28e-42; dropped (NaN) SBD 24, DBD 69
pairs SBD 3751 DBD 50461 ; within tolerance: False False
variant, sessions whose channel follows the rule:
theta_corr: SBD median 0.0164 (n = 2959), DBD median 0.0069 (n = 35533), two-sided Wilcoxon rank-sum p = 1.68e-30; dropped (NaN) SBD 24, DBD 61
   within tolerance: False False
variant, pyramidal layer centre channel:
theta_corr: SBD median 0.0178 (n = 3727), DBD median 0.0079 (n = 50391), two-sided Wilcoxon rank-sum p = 4.34e-42; dropped (NaN) SBD 24, DBD 70
   within tolerance: True True
per birthdate SBD/DBD medians: {('E13.5', False): 0.0047, ('E13.5', True): 0.0216, ('E14.5', False): 0.0151, ('E14.5', True): 0.0245, ('E15.5', False): 0.0064, ('E15.5', True): 0.0096, ('E16.5', False): 0.0077, ('E16.5', True): 0.0167}

Result: partially reproduced, resting on the choice of theta channel. SBD median 0.0170 against DBD 0.0070 over 3,727 and 50,392 pairs with a correlation, rank-sum p = 1.3e-42; both medians lie just below their tolerance (0.0170 to 0.0208 and 0.0078 to 0.0096; the SBD median rounds to the lower bound but the printed check puts it below). On the sessions whose channel follows the rule (72 of the 104) the medians are 0.0164 and 0.0069; with the phase from the layer centre channel they are 0.0178 and 0.0079, both within tolerance.

Claim fig6c-theta-rate-preserved: Individual pyramidal neurons preserve their theta-related firing rates between the familiar and novel environments (Spearman rho = 0.7378, n = 2,544 neurons).

In [22]:
NS = S.loc[S.subject.isin(h.NOVEL_MICE), "session"].tolist()
TRN = TR[TR.session.isin(NS)].copy()
def theta_rates(wake_only, src=None):
    x = (TRN if src is None else src)
    x = x[x.wake_only == wake_only]
    fam = x[x.epoch == 0].set_index(["session", "unit"])
    nov = x[x.epoch > 0].groupby(["session", "unit"])[["spikes", "dur"]].sum()
    df = fam[["rate", "lr"]].rename(columns={"rate": "fam"}).join(nov)
    df["nov"] = df.spikes / df.dur
    return df.dropna(subset=["fam", "nov"])
print("novel sessions:", len(NS), "; novel subsessions:", TRN[TRN.epoch > 0].groupby(["session", "epoch"]).ngroups)
for wo in (True, False):
    df = theta_rates(wo)
    rho, p = stats.spearmanr(df.fam, df.nov)
    print(f"{'Methods, cycles in wake' if wo else 'code variant, no wake restriction'}: n = {len(df)} cells, Spearman rho = {rho:.4f}, p = {p:.3g}")
df = theta_rates(True)
print("per mouse rho:", {s: round(stats.spearmanr(g.fam, g.nov)[0], 3) for s, g in df.reset_index().assign(subject=lambda d: d.session.str[:8]).groupby("subject")})
print("theta cycles per subsession (wake only): median", int(TRN[TRN.wake_only].groupby(['session','epoch']).n_cycles.first().median()),
      "min", int(TRN[TRN.wake_only].groupby(['session','epoch']).n_cycles.first().min()))
dfc = theta_rates(True, TRc[TRc.session.isin(NS)])
print(f"variant, pyramidal layer centre channel: n = {len(dfc)}, Spearman rho = {stats.spearmanr(dfc.fam, dfc.nov)[0]:.4f}")
print("novel sessions whose channel follows the rule:", len(RULE_SESS & set(NS)), "of", len(NS))
dfr = theta_rates(True, TRN[TRN.session.isin(RULE_SESS)])
print(f"variant, the novel sessions whose channel follows the rule: n = {len(dfr)} cells, Spearman rho = {stats.spearmanr(dfr.fam, dfr.nov)[0]:.4f}, p = {stats.spearmanr(dfr.fam, dfr.nov)[1]:.3g}")
novel sessions: 12 ; novel subsessions: 16
Methods, cycles in wake: n = 2544 cells, Spearman rho = 0.7351, p = 0
code variant, no wake restriction: n = 2544 cells, Spearman rho = 0.7351, p = 0
per mouse rho: {'e13_26m1': np.float64(0.742), 'e15_13f1': np.float64(0.735), 'e16_3m2_': np.float64(0.723)}
theta cycles per subsession (wake only): median 2204 min 335
variant, pyramidal layer centre channel: n = 2544, Spearman rho = 0.7381
novel sessions whose channel follows the rule: 5 of 12
variant, the novel sessions whose channel follows the rule: n = 1259 cells, Spearman rho = 0.7340, p = 1.87e-213

Result: reproduced, resting on the choice of theta channel. Over the 2,544 pyramidal cells of the 12 novel sessions (the paper's n), theta-related rates in the familiar and novel subsessions correlate with Spearman rho = 0.735, p < 1e-300; the same with or without the wake restriction, 0.723 to 0.742 in each mouse, 0.738 on the layer centre channel, and 0.734 over the 1,259 cells of the 5 novel sessions whose channel follows the rule.

Claim fig6d-rate-lower-novel: Theta-related firing rates are slightly lower in novel environments than in the familiar one (median 0.69 against 0.77 Hz).

In [23]:
for wo in (True, False):
    df = theta_rates(wo)
    p = stats.ranksums(df.nov, df.fam).pvalue
    pw = stats.wilcoxon(df.nov, df.fam).pvalue
    print(f"{'Methods (wake)' if wo else 'code variant'}: familiar median {df.fam.median():.3f} Hz, novel median {df.nov.median():.3f} Hz, "
          f"n = {len(df)}; rank-sum p = {p:.3g}; paired signed-rank p = {pw:.3g}")
dfc = theta_rates(True, TRc[TRc.session.isin(NS)])
print(f"variant, pyramidal layer centre channel: familiar median {dfc.fam.median():.3f} Hz, novel {dfc.nov.median():.3f} Hz, rank-sum p = {stats.ranksums(dfc.nov, dfc.fam).pvalue:.3g}")
dfr = theta_rates(True, TRN[TRN.session.isin(RULE_SESS)])
print(f"variant, the novel sessions whose channel follows the rule: n = {len(dfr)}, familiar median {dfr.fam.median():.3f} Hz, novel {dfr.nov.median():.3f} Hz, "
      f"rank-sum p = {stats.ranksums(dfr.nov, dfr.fam).pvalue:.3g}; paired signed-rank p = {stats.wilcoxon(dfr.nov, dfr.fam).pvalue:.3g}")
Methods (wake): familiar median 0.757 Hz, novel median 0.672 Hz, n = 2544; rank-sum p = 0.000931; paired signed-rank p = 2.76e-07
code variant: familiar median 0.757 Hz, novel median 0.672 Hz, n = 2544; rank-sum p = 0.000929; paired signed-rank p = 2.79e-07
variant, pyramidal layer centre channel: familiar median 0.755 Hz, novel 0.676 Hz, rank-sum p = 0.00256
variant, the novel sessions whose channel follows the rule: n = 1259, familiar median 0.704 Hz, novel 0.643 Hz, rank-sum p = 0.051; paired signed-rank p = 0.00466

Result: reproduced, resting on the choice of theta channel. Median theta-related rate 0.757 Hz in the familiar maze and 0.672 Hz in novel environments over 2,544 cells, rank-sum p = 0.00093 (paired signed-rank p = 2.8e-7); both within tolerance. On the layer centre channel 0.755 and 0.676 Hz, p = 0.0026. On the 5 novel sessions whose channel follows the rule (1,259 cells) the medians are 0.704 and 0.643 Hz with rank-sum p = 0.051 and paired signed-rank p = 0.0047, so the rank-sum test the claim names falls just short of 0.05 on that subset.

Familiar figure-eight maze¶

Claim maze-cohort: Nine mice (E13.5 n = 2, E14.5 n = 2, E15.5 n = 2, E16.5 n = 3) ran a spatial alternation task on a familiar figure-eight maze, and three mice explored novel environments.

In [24]:
fam = S[S.subject.isin(h.FAMILIAR_MICE) & (S.beh_epochs > 0)]
print("familiar-maze mice with figure-eight sessions:", fam.subject.nunique(), fam.groupby("birthdate").subject.nunique().to_dict(),
      "; sessions:", len(fam))
print("first environment of their sessions:", fam.envs.str.split(",").str[0].value_counts().to_dict())
nov = S[S.subject.isin(h.NOVEL_MICE)]
nov_has = nov[nov.envs.str.split(",").str.len() > 1]
print("novel-environment mice with a later subsession:", nov_has.subject.nunique(), sorted(nov_has.subject.unique()),
      "; sessions:", len(nov_has), "of", len(nov))
other = S[~S.subject.isin(h.FAMILIAR_MICE | h.NOVEL_MICE) & (S.beh_epochs > 0)]
print("other mice with behavioural subsessions:", other.subject.unique().tolist(), len(other), "sessions")
familiar-maze mice with figure-eight sessions: 9 {'E13.5': 2, 'E14.5': 2, 'E15.5': 2, 'E16.5': 3} ; sessions: 57
first environment of their sessions: {'figure-8 maze': 53, 'tmaze_familiar': 4}
novel-environment mice with a later subsession: 3 ['e13_26m1', 'e15_13f1', 'e16_3m2'] ; sessions: 12 of 12
other mice with behavioural subsessions: [] 0 sessions

Result: reproduced. The nine mice of the table's Figure 5 column have 57 sessions with a first subsession on the figure-eight (2, 2, 2 and 3 mice per birthdate), and the three mice of the Figure 6 column have later subsessions in all 12 of their sessions.

In [25]:
FM = [META[s] for s in fam.session]
t = time.time()
mz = h.run_sessions(h.maze_session, FM)
print(f"{time.time()-t:.0f} s, {len(mz)} sessions, pyramidal cells {sum(len(x['pyr']) for x in mz)}, light-responsive {sum(int(x['lr'].sum()) for x in mz)}")
57 s, 57 sessions, pyramidal cells 4820, light-responsive 466

Claim maze-task: On the figure-eight maze each trial was 205 cm long, position was tracked at 30 Hz, and animals ran at least ten trials along each arm in every session.

In [26]:
tl = pd.DataFrame([{"session": x["session"], "x0": t["x0"], "x1": t["x1"], "arm": t["arm"]} for x in mz for t in x["trials"]])
tl["extent"] = tl.x1 - tl.x0
print("linearized extent per trial (cm): median", round(tl.extent.median(), 1), "range", round(tl.extent.min(), 1), "-", round(tl.extent.max(), 1),
      "; max position", round(tl.x1.max(), 1))
rates = np.array([1 / x["dt"] for x in mz])
print("tracking rate (1/median interval): median", round(float(np.median(rates)), 2), "Hz, range", round(rates.min(), 2), "-", round(rates.max(), 2))
tc = pd.DataFrame([{"session": x["session"], **x["trial_counts"]} for x in mz])
tc["min_type"] = tc[["left", "right"]].min(axis=1); tc["total"] = tc.left + tc.right
print("sessions:", len(tc), "; with >= 10 of each type:", int((tc.min_type >= 10).sum()), "; with >= 20 trials:", int((tc.total >= 20).sum()))
print(tc[tc.min_type < 10].to_string())
# trials table itself, before any mapping filter: trials inside the familiar epoch by visited arm
tt = []
for x in mz:
    m = META[x["session"]]; t0, t1 = h.behaviour_epochs(m)[0][:2]; tr = m["trials"]
    arms = [a for s_, e_, a in zip(tr["start_time"], tr["stop_time"], tr["visited_arm"]) if s_ >= t0 - 1 and e_ <= t1 + 1]
    tt.append({"session": x["session"], "table_left": arms.count("left"), "table_right": arms.count("right"),
               "table_other": len(arms) - arms.count("left") - arms.count("right"), "table_all_rows": len(tr["start_time"]),
               "mapped_left": x["trial_counts"]["left"], "mapped_right": x["trial_counts"]["right"]})
TT = pd.DataFrame(tt); TT["table_min"] = TT[["table_left", "table_right"]].min(axis=1)
print("trials table: sessions with >= 10 of each arm", int((TT.table_min >= 10).sum()), "of", len(TT), "; with >= 20 left plus right",
      int((TT.table_left + TT.table_right >= 20).sum()), "; sessions where the mapped counts differ from the table:",
      int(((TT.table_left != TT.mapped_left) | (TT.table_right != TT.mapped_right)).sum()))
print("other visited_arm values:", collections.Counter(a for x in mz for a in META[x["session"]]["trials"]["visited_arm"] if a not in ("left", "right")))
print(TT.to_string())
linearized extent per trial (cm): median 202.8 range 1.8 - 205.0 ; max position 205.0
tracking rate (1/median interval): median 30.0 Hz, range 30.0 - 30.0
sessions: 57 ; with >= 10 of each type: 30 ; with >= 20 trials: 51
            session  left  right  min_type  total
0   e13_16f1_210302    15      7         7     22
3   e13_16f1_210315    11      9         9     20
13   e14_2m2_201013     7      8         7     15
14   e14_2m2_201017     8     12         8     20
16   e14_2m2_201022     9     10         9     19
17   e14_2m3_201017    19      8         8     27
25  e15_10m1_200716    12      8         8     20
26  e15_10m1_200719    12      8         8     20
27  e15_10m1_200723     8      8         8     16
30  e15_10m1_200809    12      9         9     21
31  e15_10m1_200812    13      9         9     22
32   e15_9f1_200715    14      7         7     21
33   e15_9f1_200717    11      9         9     20
38   e15_9f1_200809    12      8         8     20
39   e16_1f1_200823     7     13         7     20
40   e16_1f1_200917    13      7         7     20
41   e16_1f1_200918    17      9         9     26
42   e16_1f1_200919    21      8         8     29
43   e16_1f1_200920    13      9         9     22
44   e16_1f1_200923    13      9         9     22
45   e16_1f1_201001    12      8         8     20
46   e16_1f1_201002    13      7         7     20
47   e16_1f1_201004    15      9         9     24
48   e16_2m1_201116     7      5         5     12
50   e16_2m1_201121     9     13         9     22
51   e16_2m1_201129    10      8         8     18
53   e16_3m1_210111     8     10         8     18
trials table: sessions with >= 10 of each arm 30 of 57 ; with >= 20 left plus right 51 ; sessions where the mapped counts differ from the table: 2
other visited_arm values: Counter()
            session  table_left  table_right  table_other  table_all_rows  mapped_left  mapped_right  table_min
0   e13_16f1_210302          15            7            0              22           15             7          7
1   e13_16f1_210312          11           10            0              21           11            10         10
2   e13_16f1_210314          14           11            0              25           14            11         11
3   e13_16f1_210315          11            9            0              20           11             9          9
4   e13_16f1_210317          14           11            0              25           14            11         11
5   e13_16f1_210319          16           10            0              26           16            10         10
6   e13_16f1_210322          15           10            0              25           15            10         10
7   e13_16f1_210328          11           10            0              21           11            10         10
8   e13_16f1_210331          12           10            0              22           12            10         10
9   e13_26m1_211019          27           20            0              80           27            20         20
10  e13_26m1_211116          11           10            0              33           11            10         10
11  e13_26m1_211119          13           12            0              83           13            12         12
12  e13_26m1_211124          13           13            0              29           13            13         13
13   e14_2m2_201013           7            8            0              15            7             8          7
14   e14_2m2_201017           9           12            0              21            8            12          9
15   e14_2m2_201019          10           11            0              21           10            11         10
16   e14_2m2_201022           9           10            0              19            9            10          9
17   e14_2m3_201017          19            8            0              27           19             8          8
18   e14_2m3_201019          13           10            0              23           13            10         10
19   e14_2m3_201118          14           10            0              24           14            10         10
20   e14_2m3_201121          12           10            0              22           12            10         10
21   e14_2m3_201125          12           10            0              22           12            10         10
22   e14_2m3_201129          15           10            0              25           15            10         10
23   e14_2m3_201206          17           15            0              32           17            15         15
24   e14_2m3_201208          22           17            0              39           22            17         17
25  e15_10m1_200716          12            8            0              20           12             8          8
26  e15_10m1_200719          12            8            0              20           12             8          8
27  e15_10m1_200723           8            8            0              16            8             8          8
28  e15_10m1_200727          16           11            0              27           16            11         11
29  e15_10m1_200803          11           10            0              21           11            10         10
30  e15_10m1_200809          12            9            0              21           12             9          9
31  e15_10m1_200812          13            9            0              22           13             9          9
32   e15_9f1_200715          14            7            0              21           14             7          7
33   e15_9f1_200717          11            9            0              20           11             9          9
34   e15_9f1_200720          18           12            0              30           18            12         12
35   e15_9f1_200723          12           10            0              22           12            10         10
36   e15_9f1_200729          15           13            0              28           15            13         13
37   e15_9f1_200802          17           11            0              28           16            11         11
38   e15_9f1_200809          12            8            0              20           12             8          8
39   e16_1f1_200823           7           13            0              20            7            13          7
40   e16_1f1_200917          13            7            0              20           13             7          7
41   e16_1f1_200918          17            9            0              26           17             9          9
42   e16_1f1_200919          21            8            0              29           21             8          8
43   e16_1f1_200920          13            9            0              22           13             9          9
44   e16_1f1_200923          13            9            0              22           13             9          9
45   e16_1f1_201001          12            8            0              20           12             8          8
46   e16_1f1_201002          13            7            0              20           13             7          7
47   e16_1f1_201004          15            9            0              24           15             9          9
48   e16_2m1_201116           7            5            0              12            7             5          5
49   e16_2m1_201119          10           10            0              20           10            10         10
50   e16_2m1_201121           9           13            0              22            9            13          9
51   e16_2m1_201129          10            8            0              18           10             8          8
52   e16_2m1_201206          10           10            0              20           10            10         10
53   e16_3m1_210111           8           10            0              18            8            10          8
54   e16_3m1_210119          12           14            0              26           12            14         12
55   e16_3m1_210201          15           15            0              30           15            15         15
56   e16_3m1_210203          12           10            0              22           12            10         10

Result: not reproduced. Trials span a median 202.8 cm of linearized position (maximum 205.0) and tracking runs at 30.0 Hz, both within tolerance, but only 30 of 57 sessions hold at least ten trials of each type, and 6 sessions hold fewer than 20 trials in all, so neither the full nor the partial condition on trial counts holds. The trials table itself, before any mapping filter, gives the same: 30 of 57 sessions with ten of each arm and 51 with at least 20; the counted trials differ from the table by one trial in two sessions, and no visited_arm value other than left or right occurs.

Claim novel-explorations: The novel-environment mice made 16 novel environment explorations in six distinct environments (two linear tracks, three open fields and one figure-eight maze).

In [27]:
ex = [(m["session_id"], e[2]) for m in metas if m["subject_id"] in h.NOVEL_MICE for e in h.behaviour_epochs(m)[1:]]
print("novel explorations (subsessions after the first):", len(ex))
print("by environment:", collections.Counter(e for _, e in ex))
print("distinct environments:", len(set(e for _, e in ex)))
novel explorations (subsessions after the first): 16
by environment: Counter({'tmaze_ipshita': 3, 'linear_thomas': 3, 'linear_manu': 3, 'openField_gergo': 3, 'openField_coolbox': 2, 'openField_thomas': 2})
distinct environments: 6

Result: reproduced. The three novel mice have 16 subsessions after the familiar one, in six environments: two linear tracks, three open fields and one novel figure-eight (tmaze_ipshita).

Claim fig5b-spatial-info-by-birthdate: Spatial information (medians 0.836, 1.05, 1.35, 0.88 bits/s) and spatial coverage (36, 44, 44, 18 cm) on the familiar maze are largest in intermediate-birthdate neurons.

In [28]:
def cell_maze_measures(x):
    out = []
    M, occ = x["maps"], x["occ"]
    for c in range(M.shape[1]):
        rl, rr = M[0, c], M[1, c]
        cat, ocat = np.r_[rl, rr], np.r_[occ[0], occ[1]]
        def cov(rate, o, use_info):
            ok = np.isfinite(rate) & (o > 0)
            p = o[ok] / o[ok].sum(); r = rate[ok]; mr = np.sum(p * r)
            hi = r > 5
            if use_info:
                with np.errstate(divide="ignore", invalid="ignore"):
                    term = (r / mr) * np.log2(r / mr)
                hi = hi & (term > 1)
            return int(hi.sum())
        out.append({"session": x["session"], "subject": x["subject"], "birthdate": x["birthdate"], "lr": bool(x["lr"][c]), "unit": int(x["unit"][c]),
                    "si_cat": h.skaggs_info(cat, ocat),
                    "si_mean": np.nanmean([h.skaggs_info(rl, occ[0]), h.skaggs_info(rr, occ[1])]),
                    "cov_a_cat": cov(cat, ocat, True), "cov_b_cat": cov(cat, ocat, False),
                    "cov_a_mean": np.mean([cov(rl, occ[0], True), cov(rr, occ[1], True)]),
                    "cov_b_mean": np.mean([cov(rl, occ[0], False), cov(rr, occ[1], False)])})
    return out
MC = pd.DataFrame([r for x in mz for r in cell_maze_measures(x)])
ML = MC[MC.lr]
exp_si, exp_cov = [0.836, 1.05, 1.35, 0.88], [36, 44, 44, 18]
for col in ["si_cat", "si_mean"]:
    med, ps = by_bd(ML, col, "fig5b-spatial-info-by-birthdate", n_seeds=5 if col == "si_cat" else 1)
    print(f"  {col}: inverted-U {h.inverted_u(med)}, within tolerance {[abs(a - e) <= 0.1 * e for a, e in zip(med, exp_si)]}")
for col in ["cov_a_cat", "cov_b_cat", "cov_a_mean", "cov_b_mean"]:
    med, ps = by_bd(ML, col, "fig5b-spatial-info-by-birthdate", n_seeds=5 if col == "cov_a_cat" else 1)
    print(f"  {col}: inverted-U {h.inverted_u(med)}, within tolerance {[abs(a - e) <= 0.1 * e for a, e in zip(med, exp_cov)]}")
print("by mouse (median si_cat):", ML.groupby(["birthdate", "subject"]).si_cat.median().round(3).to_dict())
/tmp/ipykernel_2343/1532546999.py:18: RuntimeWarning: Mean of empty slice
  "si_mean": np.nanmean([h.skaggs_info(rl, occ[0]), h.skaggs_info(rr, occ[1])]),
si_cat: n = [164, 76, 111, 115], medians = [0.5639, 0.6321, 0.9183, 0.6201], ranges = [(0.018, 3.652), (0.059, 3.473), (0.074, 3.157), (0.024, 2.399)]
  bootstrap Kruskal-Wallis H = 23.133; p under the claim's seed and +1000..+4000: [0.0, 0.0, 0.0, 0.0, 0.0]
  si_cat: inverted-U True, within tolerance [False, False, False, False]
si_mean: n = [164, 76, 111, 115], medians = [0.5182, 0.6167, 0.8685, 0.5358], ranges = [(0.018, 3.362), (0.06, 3.434), (0.064, 3.042), (0.024, 2.325)]
  bootstrap Kruskal-Wallis H = 22.903; p under the claim's seed and +1000..+4000: [0.0]
  si_mean: inverted-U True, within tolerance [False, False, False, False]
cov_a_cat: n = [164, 76, 111, 115], medians = [29.5, 31.5, 31.0, 12.0], ranges = [(0.0, 142.0), (0.0, 151.0), (0.0, 157.0), (0.0, 125.0)]
  bootstrap Kruskal-Wallis H = 17.984; p under the claim's seed and +1000..+4000: [0.0002, 0.0002, 0.0008, 0.0002, 0.0004]
  cov_a_cat: inverted-U True, within tolerance [False, False, False, False]
cov_b_cat: n = [164, 76, 111, 115], medians = [34.5, 32.0, 37.0, 12.0], ranges = [(0.0, 274.0), (0.0, 277.0), (0.0, 407.0), (0.0, 270.0)]
  bootstrap Kruskal-Wallis H = 20.046; p under the claim's seed and +1000..+4000: [0.0002]
  cov_b_cat: inverted-U True, within tolerance [True, False, False, False]
cov_a_mean: n = [164, 76, 111, 115], medians = [13.25, 15.0, 15.5, 6.0], ranges = [(0.0, 63.0), (0.0, 69.5), (0.0, 77.5), (0.0, 57.0)]
  bootstrap Kruskal-Wallis H = 17.609; p under the claim's seed and +1000..+4000: [0.0004]
  cov_a_mean: inverted-U True, within tolerance [False, False, False, False]
cov_b_mean: n = [164, 76, 111, 115], medians = [17.25, 16.0, 18.5, 6.0], ranges = [(0.0, 137.0), (0.0, 138.5), (0.0, 203.5), (0.0, 135.0)]
  bootstrap Kruskal-Wallis H = 20.046; p under the claim's seed and +1000..+4000: [0.0002]
  cov_b_mean: inverted-U True, within tolerance [False, False, False, False]
by mouse (median si_cat): {('E13.5', 'e13_16f1'): 0.571, ('E13.5', 'e13_26m1'): 0.53, ('E14.5', 'e14_2m2'): 0.606, ('E14.5', 'e14_2m3'): 0.782, ('E15.5', 'e15_10m1'): 0.796, ('E15.5', 'e15_9f1'): 1.05, ('E16.5', 'e16_1f1'): 0.563, ('E16.5', 'e16_2m1'): 0.722, ('E16.5', 'e16_3m1'): 0.685}

Result: partially reproduced. Both measures differ across birthdates (bootstrap Kruskal-Wallis p <= 0.0008 under all readings and seeds) and both have their highest median at E14.5 or E15.5 with E13.5 and E16.5 below it, as the claim states, but no reading brings all the medians within tolerance: spatial information is 0.56, 0.63, 0.92 and 0.62 bits/s (concatenated maps) against 0.836, 1.05, 1.35 and 0.88, that is 29.5 to 40% below, and coverage 29.5, 31.5, 31 and 12 cm (reading a) against 36, 44, 44 and 18. Under coverage reading (b) the E13.5 median (34.5 cm) is within tolerance and the other three are not.

Claim fig5c-sbd-ratemap-overlap: SBD pairs have higher spatial ratemap correlations than DBD pairs on the familiar maze (median 0.0152 against -0.0256).

In [29]:
STEM = slice(74, 205)  # bins 75 to 205, post_stem_inds (claims)
def corr_visited(a, b):
    ok = np.isfinite(a) & np.isfinite(b)
    if ok.sum() < 3 or a[ok].std() == 0 or b[ok].std() == 0:
        return np.nan
    return float(np.corrcoef(a[ok], b[ok])[0, 1])
def corr_code(a, b):
    if not (np.isfinite(a).all() and np.isfinite(b).all()) or a.std() == 0 or b.std() == 0:
        return np.nan
    return float(np.corrcoef(a, b)[0, 1])
rows = []
for x in mz:
    M = x["maps"]; V = np.concatenate([M[0][:, STEM], M[1][:, STEM]], axis=1)
    lr = np.where(x["lr"])[0]; nr = np.where(~x["lr"])[0]
    for sbd, pp in ((True, [(a, b) for i, a in enumerate(lr) for b in lr[i + 1:]]), (False, [(a, b) for a in lr for b in nr])):
        for a, b in pp:
            rows.append({"session": x["session"], "subject": x["subject"], "birthdate": x["birthdate"], "sbd": sbd, "a": a, "b": b,
                         "r": corr_visited(V[a], V[b]), "r_code": corr_code(V[a], V[b]),
                         "rL": corr_visited(M[0][a, STEM], M[0][b, STEM]), "rR": corr_visited(M[1][a, STEM], M[1][b, STEM]),
                         "dshank": abs(int(x["shank"][a]) - int(x["shank"][b])),
                         "dist": 250 * round(abs(float(x["x"][a]) - float(x["x"][b])) / 250),
                         "el_dist": float(np.hypot(x["x"][a] - x["x"][b], x["y"][a] - x["y"][b])),
                         "ua": int(x["unit"][a]), "ub": int(x["unit"][b])})
MP = pd.DataFrame(rows)
s, d, p = sbd_dbd(MP, "r")
print("within tolerance:", abs(s - 0.0152) <= 0.0015, abs(d + 0.0256) <= 0.0026)
s2, d2, p2 = sbd_dbd(MP, "r_code")
print("by mouse SBD/DBD medians:", MP.groupby(["subject", "sbd"]).r.median().round(4).to_dict())
r: SBD median 0.0189 (n = 2609), DBD median -0.0239 (n = 39843), two-sided Wilcoxon rank-sum p = 5.89e-09; dropped (NaN) SBD 0, DBD 122
within tolerance: False True
r_code: SBD median 0.0187 (n = 2519), DBD median -0.0249 (n = 37562), two-sided Wilcoxon rank-sum p = 8.09e-09; dropped (NaN) SBD 90, DBD 2403
by mouse SBD/DBD medians: {('e13_16f1', False): -0.0277, ('e13_16f1', True): 0.0282, ('e13_26m1', False): -0.0313, ('e13_26m1', True): -0.017, ('e14_2m2', False): -0.0313, ('e14_2m2', True): 0.1681, ('e14_2m3', False): -0.0253, ('e14_2m3', True): -0.029, ('e15_10m1', False): -0.0306, ('e15_10m1', True): -0.0064, ('e15_9f1', False): 0.0042, ('e15_9f1', True): 0.0609, ('e16_1f1', False): 0.0017, ('e16_1f1', True): 0.0678, ('e16_2m1', False): -0.0445, ('e16_2m1', True): -0.003, ('e16_3m1', False): -0.0321, ('e16_3m1', True): 0.0245}

Result: partially reproduced. Over 2,609 SBD and 39,965 DBD pairs (the paper's counts), SBD median 0.0189 against DBD -0.0239, rank-sum p = 5.9e-9; the DBD median is within tolerance and the SBD median is above it (0.0137 to 0.0167). The code's variant gives 0.0187 and -0.0249.

Claim fig5d-overlap-by-distance: Ratemap overlap of SBD pairs is larger than that of DBD pairs within 250 micrometres (same and adjacent shanks) but not at 500 micrometres.

In [30]:
import statsmodels.formula.api as smf
import statsmodels.api as sm
from statsmodels.stats.multicomp import pairwise_tukeyhsd
print("shank distance from the electrodes' x positions against |shank difference| x 250 um: agreeing in", int((MP.dist == 250 * MP.dshank).sum()), "of", len(MP),
      "pairs (files with Front and Back faces have both faces of each shank at the same x)")
D5 = MP[MP.dshank <= 2].dropna(subset=["r"]).copy()
D5["dist"] = D5.dshank * 250; D5["grp"] = np.where(D5.sbd, "SBD", "DBD")   # kcoords difference (criterion)
print("pairs by shank distance (um) and group:", D5.groupby(["dist", "grp"]).size().to_dict(), "; dropped at 750 um:", int((MP.dshank > 2).sum()))
fit = smf.ols("r ~ C(grp, Sum) * C(dist, Sum)", data=D5).fit()
print(sm.stats.anova_lm(fit, typ=3).round(4).to_string())
means = D5.groupby(["dist", "grp"]).r.mean()
print("means:", means.round(4).to_dict())
expd = {(0, "SBD"): 0.0707, (0, "DBD"): 0.0284, (250, "SBD"): 0.0445, (250, "DBD"): 0.0173, (500, "SBD"): 0.0195, (500, "DBD"): 0.0151}
print("within tolerance:", {k: abs(means[k] - v) <= 0.1 * v for k, v in expd.items()})
tk = pairwise_tukeyhsd(D5.r, D5.grp + "_" + D5.dist.astype(str))
tt = pd.DataFrame(tk.summary().data[1:], columns=tk.summary().data[0])
print(tt[[a.split("_")[1] == b.split("_")[1] for a, b in zip(tt.group1, tt.group2)]].to_string())
# The model above has the interaction, so its six cell means are the group means and its residual mean square is the
# six-group one: Tukey-Kramer over the six groups is the comparison MATLAB's multcompare makes on that anovan model.
print("residual mean square, two-way model", round(fit.mse_resid, 6), "; six-group one-way", round(smf.ols("r ~ C(grp):C(dist)", data=D5).fit().mse_resid, 6))
shank distance from the electrodes' x positions against |shank difference| x 250 um: agreeing in 42224 of 42574 pairs (files with Front and Back faces have both faces of each shank at the same x)
pairs by shank distance (um) and group: {(0, 'DBD'): 13494, (0, 'SBD'): 1205, (250, 'DBD'): 20544, (250, 'SBD'): 1021, (500, 'DBD'): 4459, (500, 'SBD'): 335} ; dropped at 750 um: 1394
                             sum_sq       df        F  PR(>F)
Intercept                    5.9308      1.0  91.1821  0.0000
C(grp, Sum)                  0.9431      1.0  14.5001  0.0001
C(dist, Sum)                 0.9538      2.0   7.3317  0.0007
C(grp, Sum):C(dist, Sum)     0.1198      2.0   0.9210  0.3981
Residual                  2670.1494  41052.0      NaN     NaN
means: {(0, 'DBD'): 0.0268, (0, 'SBD'): 0.0601, (250, 'DBD'): 0.0147, (250, 'SBD'): 0.0386, (500, 'DBD'): 0.011, (500, 'SBD'): 0.0234}
within tolerance: {(0, 'SBD'): np.False_, (0, 'DBD'): np.True_, (250, 'SBD'): np.False_, (250, 'DBD'): np.False_, (500, 'SBD'): np.False_, (500, 'DBD'): np.False_}
     group1   group2  meandiff   p-adj   lower   upper  reject
2     DBD_0    SBD_0    0.0333  0.0002  0.0115  0.0552    True
7   DBD_250  SBD_250    0.0238  0.0413  0.0005  0.0472    True
11  DBD_500  SBD_500    0.0125  0.9554 -0.0287  0.0536   False
residual mean square, two-way model 0.065043 ; six-group one-way 0.065043

Result: partially reproduced. The birthdate main effect has p = 0.0001 over 2,561 SBD and 38,497 DBD pairs, and SBD exceeds DBD by Tukey's test at 0 um (p = 0.0002) and 250 um (p = 0.041) but not at 500 um (p = 0.96), as the paper says; five of the six means are outside the tight tolerances (for example SBD 0 um 0.060 against 0.0707).

Claim fig5e-pv-decorrelation: Population firing-rate vectors at the same linearized position decorrelate between left and right trials once the animal leaves the common stem (median correlations stem 0.93, turn 1 0.412, arm 0.372, turn 2 0.394).

In [31]:
SEG = {"stem": (0, 74), "turn 1": (74, 111), "arm": (111, 185), "turn 2": (185, 205)}
pv = []
for x in mz:
    M = x["maps"]
    for b in range(205):
        a1, a2 = M[0][:, b], M[1][:, b]
        ok = np.isfinite(a1) & np.isfinite(a2)
        r = np.corrcoef(a1[ok], a2[ok])[0, 1] if ok.sum() > 2 and a1[ok].std() > 0 and a2[ok].std() > 0 else np.nan
        seg = [k for k, (lo, hi) in SEG.items() if lo <= b < hi][0]
        pv.append({"session": x["session"], "bin": b, "seg": seg, "r": r})
PV = pd.DataFrame(pv)
print("PV correlations per segment:", PV.groupby("seg").r.agg(["median", "count"]).round(4).loc[list(SEG)].to_dict(), "; NaN:", int(PV.r.isna().sum()))
groups = [PV[PV.seg == k].r.dropna().values for k in SEG]
for k in SEEDS_PLUS:
    H_, p = h.boot_kw(groups, rng=np.random.default_rng(seed("fig5e-pv-decorrelation") + k), n_boot=5000 if k == 0 else 1000)
    print(f"seed +{k}: bootstrap Kruskal-Wallis H = {H_:.1f}, p = {p:.4f}")
meds = [np.median(g) for g in groups]
print("within tolerance:", [abs(a - e) <= 0.1 * e for a, e in zip(meds, [0.93, 0.412, 0.372, 0.3944])], "; stem highest:", int(np.argmax(meds)) == 0)
PV correlations per segment: {'median': {'stem': 0.93, 'turn 1': 0.4878, 'arm': 0.4072, 'turn 2': 0.4074}, 'count': {'stem': 4074, 'turn 1': 2106, 'arm': 4209, 'turn 2': 1136}} ; NaN: 160
seed +0: bootstrap Kruskal-Wallis H = 7588.7, p = 0.0000
seed +1000: bootstrap Kruskal-Wallis H = 7588.7, p = 0.0000
seed +2000: bootstrap Kruskal-Wallis H = 7588.7, p = 0.0000
seed +3000: bootstrap Kruskal-Wallis H = 7588.7, p = 0.0000
seed +4000: bootstrap Kruskal-Wallis H = 7588.7, p = 0.0000
within tolerance: [np.True_, np.False_, np.True_, np.True_] ; stem highest: True

Result: partially reproduced. Median PV correlations are 0.930 on the stem, 0.488 on turn 1, 0.407 on the arm and 0.407 on turn 2; the stem is highest and the bootstrap Kruskal-Wallis gives p < 0.0002 under all seeds, but the turn 1 median is outside tolerance (0.371 to 0.453).

Claim fig5f-remap-together: Between left and right trials, ratemaps of SBD pairs reorganize closer together than those of DBD pairs.

In [32]:
LRp = MP.dropna(subset=["rL", "rR"])
obs = pd.concat([LRp.assign(x=LRp.rL, y=LRp.rR), LRp.assign(x=LRp.rR, y=LRp.rL)])
sb = obs[obs.sbd]
edges = np.percentile(np.r_[sb.rL, sb.rR], [0, 33, 66, 99])
print("tercile edges (SBD, both trial types):", np.round(edges, 4).tolist())
for lab, open_ in (("edges as the code has them", False), ("variant, outer edges open", True)):
    e = edges.copy()
    if open_: e[0], e[-1] = -np.inf, np.inf
    o = obs.copy(); o["ter"] = pd.cut(o.x, e, labels=[1, 2, 3], include_lowest=True)
    o = o.dropna(subset=["ter"]); o["grp"] = np.where(o.sbd, "SBD", "DBD")
    fit = smf.ols("y ~ C(grp, Sum) * C(ter, Sum)", data=o).fit()
    an = sm.stats.anova_lm(fit, typ=3)
    mt = o.groupby(["ter", "grp"], observed=True).y.mean().unstack()
    print(f"{lab}: n SBD {int(o.sbd.sum())}, DBD {int((~o.sbd).sum())}; birthdate F = {an.loc['C(grp, Sum)', 'F']:.2f}, p = {an.loc['C(grp, Sum)', 'PR(>F)']:.3g}; "
          f"tercile p = {an.loc['C(ter, Sum)', 'PR(>F)']:.3g}; interaction p = {an.loc['C(grp, Sum):C(ter, Sum)', 'PR(>F)']:.3g}")
    print("   tercile means:", mt.round(4).to_dict(), "; SBD > DBD in each tercile:", bool((mt.SBD > mt.DBD).all()))
tercile edges (SBD, both trial types): [-0.7994, -0.1574, 0.1937, 0.8459]
edges as the code has them: n SBD 5144, DBD 77443; birthdate F = 24.04, p = 9.47e-07; tercile p = 2.17e-13; interaction p = 0.601
   tercile means: {'DBD': {1: 0.0022, 2: 0.0215, 3: 0.0434}, 'SBD': {1: 0.0197, 2: 0.0488, 3: 0.0724}} ; SBD > DBD in each tercile: True
variant, outer edges open: n SBD 5196, DBD 78250; birthdate F = 25.13, p = 5.38e-07; tercile p = 1.9e-14; interaction p = 0.557
   tercile means: {'DBD': {1: 0.0021, 2: 0.0215, 3: 0.0444}, 'SBD': {1: 0.0197, 2: 0.0488, 3: 0.0745}} ; SBD > DBD in each tercile: True

Result: reproduced. The birthdate main effect has F = 24.0, p = 9.5e-7 with SBD higher, and SBD exceeds DBD in each tercile (0.020, 0.049, 0.072 against 0.002, 0.022, 0.043); the variant with open outer edges gives the same.

Claim ed3-depth-control: Birthdate differences in single-cell features are not explained by anatomical depth alone; after matching depth distributions the bell-shaped birthdate profiles remain in most resamplings.

Depth of a neuron is the position of its maximum-waveform channel relative to the SPW reversal of its shank (criterion), the reversal taken from the sharp-wave profile of the theta section (pick_theta_channel: the steepest positive-to-negative step between neighbouring channels, interpolated to zero). On a shank without a reversal the shank's ripple-power centre stands in (assumption; counted below, and the centre is used for every shank as a variant). Each resampling draws, per birthdate, as many cells as the group holds, with replacement, so that the group's depth distribution in 20 um bins is that of all light-responsive cells (h.depth_match_draw), and keeps the draw when the bootstrap Kruskal-Wallis test on depth gives 0.4 < p < 0.6 (resample_depth.m, claims); the six measures are then tested with the bootstrap Kruskal-Wallis test. The homecage measures are resampled over the 664 homecage light-responsive cells, the maze measures over the 466 maze ones. To fit the run's time the inner bootstrap tests use 200 resamplings for the depth test and 300 for each measure (p resolution 0.005 and 0.003, against thresholds of 0.4, 0.6 and 0.05); a draw is retried at most 100 times, and the four extra seeds run 20 resamplings each.

In [33]:
REV = {r["session"]: (r["rev"], r["cen"]) for _, r in TO.iterrows()}
def depth_of(df, centre_only=False):
    out, fb = [], 0
    for s_, sh_, y_ in zip(df.session, df.col, df.y):
        rev, cen = REV[s_]
        r = rev.get(int(sh_), np.nan)
        if centre_only or not np.isfinite(r):
            fb += not centre_only; r = cen.get(int(sh_), np.nan)
        out.append(y_ - r)
    return np.array(out), fb
HCD = LR.copy()
HCD["depth"], nfb = depth_of(HCD)
HCD["depth_centre"], _ = depth_of(HCD, centre_only=True)
th_ = TC[hcm & (TC.wake_p < 0.01)].set_index(["session", "unit"]).wake_mrl
HCD["theta_depth"] = [th_.get((s_, u_), np.nan) for s_, u_ in zip(HCD.session, HCD.unit)]
MZD = ML.merge(CELLS[["session", "unit", "col", "y"]], on=["session", "unit"], how="left")
MZD["depth"], nfb_m = depth_of(MZD)
MZD["depth_centre"], _ = depth_of(MZD, centre_only=True)
print("homecage light-responsive cells", len(HCD), "; shanks without a reversal, ripple centre used, cells:", nfb, "; maze cells", len(MZD), "fallback", nfb_m)
print("depth (um, positive above the reversal) by birthdate, median:", HCD.groupby("birthdate").depth.median().round(1).to_dict(),
      "; range", round(HCD.depth.min(), 1), "to", round(HCD.depth.max(), 1))
g0 = [HCD[HCD.birthdate == b].depth.values for b in h.BIRTHDATES]
print("depth across birthdates before matching: H = %.3f, p = %.4f (paper H = 26.327, p = 0)" % h.boot_kw_fast(g0, 5000, np.random.default_rng(seed("ed3-depth-control"))))
REF = HCD.depth.values
def ed3_run(df, cols, rng, n_res=500, n_boot=300, dcol="depth"):
    d = df[dcol].values; grp = df.birthdate.values; tries, hits, kept_p = 0, {c: 0 for c in cols}, []
    ok = np.isfinite(d)
    df, d, grp = df[ok], d[ok], grp[ok]
    for r_ in range(n_res):
        for k_ in range(100):
            idx = h.depth_match_draw(d, grp, REF, rng); tries += 1
            _, p_ = h.boot_kw_fast([d[idx][grp[idx] == b] for b in h.BIRTHDATES], 200, rng)
            if 0.4 < p_ < 0.6: break
        kept_p.append(p_)
        sub = df.iloc[idx]
        for c in cols:
            _, pc = h.boot_kw_fast([sub[sub.birthdate == b][c].dropna().values for b in h.BIRTHDATES], n_boot, rng)
            hits[c] += pc < 0.05
    return {c: hits[c] / n_res for c in cols}, tries / n_res, float(np.mean([0.4 < p < 0.6 for p in kept_p]))
t = time.time()
E3 = {}
for k in SEEDS_PLUS:
    n_res = 500 if k == 0 else 20
    fh, tr_h, okh = ed3_run(HCD, ["burst", "rip_rate", "rip_part", "theta_depth"], np.random.default_rng(seed("ed3-depth-control") + k), n_res)
    fm, tr_m, okm = ed3_run(MZD, ["si_cat", "cov_a_cat"], np.random.default_rng(seed("ed3-depth-control") + 1 + k), n_res)
    E3[k] = {**fh, **fm}
    print(f"seed +{k} ({n_res} resamplings): fractions with p < 0.05 {dict((c, round(v, 3)) for c, v in E3[k].items())}; draws per kept resampling {tr_h:.1f} and {tr_m:.1f}; "
          f"kept draws with 0.4 < depth p < 0.6: {okh:.2f} and {okm:.2f}")
exp3 = {"burst": 0.712, "rip_rate": 0.988, "rip_part": 0.938, "theta_depth": 1.0, "si_cat": 0.726, "cov_a_cat": 0.738}
print("within tolerance (claim's seed):", {c: abs(E3[0][c] - v) <= 0.1 * v for c, v in exp3.items()})
fc, _, _ = ed3_run(HCD, ["burst", "rip_rate", "rip_part", "theta_depth"], np.random.default_rng(seed("ed3-depth-control") + 2), 50, dcol="depth_centre")
print("variant, depth from the ripple-power centre of every shank (50 resamplings):", {c: round(v, 3) for c, v in fc.items()})
print(f"{time.time()-t:.0f} s")
homecage light-responsive cells 664 ; shanks without a reversal, ripple centre used, cells: 376 ; maze cells 466 fallback 318
depth (um, positive above the reversal) by birthdate, median: {'E13.5': 0.0, 'E14.5': -2.2, 'E15.5': -7.5, 'E16.5': -0.6} ; range -175.7 to 160.0
depth across birthdates before matching: H = 23.548, p = 0.0000 (paper H = 26.327, p = 0)
seed +0 (500 resamplings): fractions with p < 0.05 {'burst': 0.98, 'rip_rate': 0.99, 'rip_part': 0.992, 'theta_depth': 1.0, 'si_cat': 0.98, 'cov_a_cat': 0.992}; draws per kept resampling 5.8 and 5.0; kept draws with 0.4 < depth p < 0.6: 1.00 and 1.00
seed +1000 (20 resamplings): fractions with p < 0.05 {'burst': 0.9, 'rip_rate': 1.0, 'rip_part': 1.0, 'theta_depth': 1.0, 'si_cat': 1.0, 'cov_a_cat': 1.0}; draws per kept resampling 6.3 and 4.6; kept draws with 0.4 < depth p < 0.6: 1.00 and 1.00
seed +2000 (20 resamplings): fractions with p < 0.05 {'burst': 1.0, 'rip_rate': 1.0, 'rip_part': 1.0, 'theta_depth': 1.0, 'si_cat': 1.0, 'cov_a_cat': 1.0}; draws per kept resampling 5.1 and 6.2; kept draws with 0.4 < depth p < 0.6: 1.00 and 1.00
seed +3000 (20 resamplings): fractions with p < 0.05 {'burst': 1.0, 'rip_rate': 1.0, 'rip_part': 1.0, 'theta_depth': 1.0, 'si_cat': 1.0, 'cov_a_cat': 1.0}; draws per kept resampling 5.0 and 5.3; kept draws with 0.4 < depth p < 0.6: 1.00 and 1.00
seed +4000 (20 resamplings): fractions with p < 0.05 {'burst': 1.0, 'rip_rate': 0.95, 'rip_part': 0.95, 'theta_depth': 1.0, 'si_cat': 1.0, 'cov_a_cat': 1.0}; draws per kept resampling 5.7 and 6.0; kept draws with 0.4 < depth p < 0.6: 1.00 and 1.00
within tolerance (claim's seed): {'burst': False, 'rip_rate': True, 'rip_part': True, 'theta_depth': True, 'si_cat': False, 'cov_a_cat': False}
variant, depth from the ripple-power centre of every shank (50 resamplings): {'burst': 0.92, 'rip_rate': 1.0, 'rip_part': 0.98, 'theta_depth': 1.0}
137 s

Result: not reproduced, resting on the depth reference. Depth differs across birthdates before matching (bootstrap H = 23.5, p < 0.0002; the paper's H = 26.3), and every kept resampling has 0.4 < p < 0.6 on depth (5.8 and 5.0 draws per kept resampling), so the matching holds. The fractions of matched resamplings with p < 0.05 are 0.980 (burst index), 0.990 (SPW-R rate), 0.992 (SPW-R participation), 1.000 (wake theta depth), 0.980 (spatial information) and 0.992 (coverage). SPW-R rate, participation and theta depth are within tolerance; burst index, spatial information and coverage lie above the paper's 0.712, 0.726 and 0.738 beyond tolerance. The criterion's partial outcome needs the burst fraction within tolerance, so the outcome is not reproduced, although the birthdate differences survive depth matching more often than in the paper. The four extra seeds (20 resamplings each) give 0.90 to 1.0 for every measure, and depth from the ripple-power centre on every shank gives 0.92 to 1.0 for the homecage measures, the burst fraction outside tolerance under each (0.90 to 1.0 over the extra seeds, 0.92 on the ripple-power centre). 376 of the 664 homecage cells lie on shank faces without a sharp-wave reversal, where the ripple-power centre stands in.

Novel environments¶

Rate maps in the familiar figure-eight and in the later subsessions of the 12 sessions of the three novel mice (h.novel_session). The novel figure-eight and the linear tracks use their linearized position, which the files give in centimeters, in 1 cm bins (the table prints each series, its unit and bin count). The open fields have only the 2D head position, in the lab's units with no scale; they are binned assuming one unit is 1 cm, and at 2, 0.5 and 0.85 cm per unit as variants. The evidence for the assumption is printed below the subsession table: where a lab-unit 2D series that is not normalized to 0-1 runs beside a linearized series in cm (two linear tracks and the novel figure-eight), the simultaneous speeds give 0.85 to 0.93 cm per unit, against 1.00 to 1.19 for the familiar maze's 2D series, which the files give in cm; the open fields themselves carry no such check. Maps are in 1 cm x 1 cm bins smoothed with a 4.5 cm FWHM Gaussian (Methods). The linear_manu subsession of e16_3m2_211211 has no position series inside its epoch: the series named for it lies inside the openField_thomas epoch (printed below), so it is left out.

In [34]:
t = time.time()
nv = h.run_sessions(h.novel_session, [META[s] for s in NS])
NE = pd.DataFrame([{"session": x["session"], "epoch": e["epoch"], "env": e["env"], "used": e["maps"] is not None, "kind": e.get("kind", ""),
                    "series": e.get("series", ""), "unit": e.get("unit", ""), "bins": e.get("nbins"),
                    "why": e.get("why", ""), "trials": e.get("trial_counts")} for x in nv for e in x["epochs"]])
print(f"{time.time()-t:.0f} s"); print(NE.to_string())
print("novel subsessions with maps:", int(NE[(NE.epoch > 0) & NE.used].shape[0]), "of", int((NE.epoch > 0).sum()))
# the one novel subsession without maps: where its position series lies
m = META["e16_3m2_211211"]
print("e16_3m2_211211 epochs:", [(e[2], round(e[0]), round(e[1])) for e in h.behaviour_epochs(m)])
print("e16_3m2_211211 position series:", {k: (round(v["t0"]), round(v["t1"]), v["unit"]) for k, v in m["series"].items()})
38 s
            session  epoch                env   used    kind                                                      series         unit    bins                                    why                     trials
0   e13_26m1_211019      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 27, 'right': 20}
1   e13_26m1_211019      1      tmaze_ipshita   True  linear   LinearizedPosition/LinearizedSpatialSeries2_tmaze_ipshita  centimeters   170.0                                         {'left': 21, 'right': 12}
2   e13_26m1_211116      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 11, 'right': 10}
3   e13_26m1_211116      1      linear_thomas   True  linear   LinearizedPosition/LinearizedSpatialSeries2_linear_thomas  centimeters   100.0                                           {'left': 4, 'right': 5}
4   e13_26m1_211119      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 13, 'right': 12}
5   e13_26m1_211119      1        linear_manu   True  linear     LinearizedPosition/LinearizedSpatialSeries2_linear_manu  centimeters   110.0                                         {'left': 29, 'right': 29}
6   e13_26m1_211124      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 13, 'right': 13}
7   e13_26m1_211124      1    openField_gergo   True    open              SubjectPosition/SpatialSeries2_openField_gergo         n.a.  1188.0                                                              None
8   e15_13f1_220117      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 20, 'right': 12}
9   e15_13f1_220117      1  openField_coolbox   True    open            SubjectPosition/SpatialSeries2_openField_coolbox         n.a.   576.0                                                              None
10  e15_13f1_220118      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 15, 'right': 10}
11  e15_13f1_220118      1        linear_manu   True  linear     LinearizedPosition/LinearizedSpatialSeries2_linear_manu  centimeters   110.0                                         {'left': 34, 'right': 34}
12  e15_13f1_220118      2   openField_thomas   True    open             SubjectPosition/SpatialSeries3_openField_thomas         n.a.  2332.0                                                              None
13  e15_13f1_220119      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 19, 'right': 10}
14  e15_13f1_220119      1    openField_gergo   True    open              SubjectPosition/SpatialSeries2_openField_gergo         n.a.  1188.0                                                              None
15  e15_13f1_220119      2      tmaze_ipshita   True  linear   LinearizedPosition/LinearizedSpatialSeries3_tmaze_ipshita  centimeters   170.0                                         {'left': 19, 'right': 13}
16  e15_13f1_220120      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 27, 'right': 19}
17  e15_13f1_220120      1      linear_thomas   True  linear   LinearizedPosition/LinearizedSpatialSeries2_linear_thomas  centimeters   100.0                                         {'left': 24, 'right': 25}
18   e16_3m2_211210      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 11, 'right': 12}
19   e16_3m2_211210      1  openField_coolbox   True    open            SubjectPosition/SpatialSeries2_openField_coolbox         n.a.   576.0                                                              None
20   e16_3m2_211211      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 16, 'right': 16}
21   e16_3m2_211211      1   openField_thomas   True    open             SubjectPosition/SpatialSeries2_openField_thomas         n.a.  2376.0                                                              None
22   e16_3m2_211211      2        linear_manu  False                                                                                      NaN  no linearized series inside the epoch                       None
23   e16_3m2_211212      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 13, 'right': 16}
24   e16_3m2_211212      1    openField_gergo   True    open              SubjectPosition/SpatialSeries2_openField_gergo         n.a.  1188.0                                                              None
25   e16_3m2_211212      2      linear_thomas   True  linear   LinearizedPosition/LinearizedSpatialSeries3_linear_thomas  centimeters   100.0                                         {'left': 17, 'right': 17}
26   e16_3m2_211213      0     tmaze_familiar   True  linear  LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar  centimeters   205.0                                         {'left': 10, 'right': 17}
27   e16_3m2_211213      1      tmaze_ipshita   True  linear   LinearizedPosition/LinearizedSpatialSeries2_tmaze_ipshita  centimeters   170.0                                         {'left': 16, 'right': 13}
novel subsessions with maps: 15 of 16
e16_3m2_211211 epochs: [('tmaze_familiar', 5270, 6533), ('openField_thomas', 9559, 12002), ('linear_manu', 15124, 16771)]
e16_3m2_211211 position series: {'LinearizedPosition/LinearizedSpatialSeries1_tmaze_familiar': (5294, 6524, 'centimeters'), 'LinearizedPosition/LinearizedSpatialSeries3_linear_manu': (9575, 11203, 'centimeters'), 'SubjectPosition/SpatialSeries1_tmaze_familiar': (5294, 6524, 'centimeters'), 'SubjectPosition/SpatialSeries2_openField_thomas': (9571, 11996, 'n.a.'), 'SubjectPosition/SpatialSeries3_linear_manu': (9575, 11203, 'n.a.')}
In [35]:
# The scale of the 2D positions (assumption for the open fields; h.position_scale_check)
PSC = pd.DataFrame([r for rows in h.run_sessions(h.position_scale_check, [META[s] for s in NS]) for r in rows])
print(PSC.round(2).to_string())
nz = PSC[(PSC.unit != "centimeters") & PSC.cm_per_unit_from_speed.notna()]
print("cm per unit from the simultaneous speeds: familiar figure-eight (2D series in cm)",
      [round(float(v), 2) for v in PSC[PSC.unit == "centimeters"].cm_per_unit_from_speed.agg(["min", "median", "max"])],
      "; lab-unit series spanning more than 2 units", nz[nz.x_max - nz.x_min > 2].cm_per_unit_from_speed.round(2).tolist(),
      "; series spanning 0 to 1", nz[nz.x_max - nz.x_min <= 2].cm_per_unit_from_speed.round(1).tolist())
op = PSC[PSC.env.str.startswith("openField")]
fam2d = PSC[PSC.unit == "centimeters"].set_index("session").speed_p90
print("open fields: extent in lab units", {f"{r.session} {r.env}": (round(r.x_max - r.x_min, 2), round(r.y_max - r.y_min, 2)) for r in op.itertuples()})
print("open fields: 90th percentile of 1 s speed, lab units/s, against the same session's familiar 2D speed in cm/s:",
      {f"{r.session} {r.env}": (round(r.speed_p90, 1), round(float(fam2d[r.session]), 1)) for r in op.itertuples()})
            session  epoch                env                            series         unit  x_min   x_max  y_min   y_max  speed_p90  lin_cm  cm_per_unit_from_speed
0   e13_26m1_211019      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   2.17   90.02   3.65   89.32      17.69  221.91                    1.19
1   e13_26m1_211019      1      tmaze_ipshita      SpatialSeries2_tmaze_ipshita         n.a.   0.01    0.73   0.06    0.98       0.15  169.99                  100.35
2   e13_26m1_211116      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.68   92.41   1.70   89.41      12.40  221.91                    1.08
3   e13_26m1_211116      1      linear_thomas      SpatialSeries2_linear_thomas         n.a.   0.26    0.89   0.04    0.77       0.08  100.00                  104.87
4   e13_26m1_211119      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.30   92.04   2.59   89.45      13.64  221.93                    1.11
5   e13_26m1_211119      1        linear_manu        SpatialSeries2_linear_manu         n.a.   0.01    0.20   0.00    1.00       0.12  110.00                  107.36
6   e13_26m1_211124      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   2.21   91.68   2.81   89.16      14.93  221.91                    1.11
7   e13_26m1_211124      1    openField_gergo    SpatialSeries2_openField_gergo         n.a.   0.00   31.50   0.00   35.00       9.03     NaN                     NaN
8   e15_13f1_220117      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.19   92.83   2.82   89.32      13.15  221.91                    1.05
9   e15_13f1_220117      1  openField_coolbox  SpatialSeries2_openField_coolbox         n.a.   0.00   22.50   0.00   22.50       5.70     NaN                     NaN
10  e15_13f1_220118      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.32   91.99   1.08   89.27      11.18  221.91                    1.00
11  e15_13f1_220118      1        linear_manu        SpatialSeries2_linear_manu         n.a.   1.85   22.94   0.30  116.03      14.91  110.00                    0.85
12  e15_13f1_220118      2   openField_thomas   SpatialSeries3_openField_thomas         n.a.   0.00   42.67   0.00   51.91      11.61     NaN                     NaN
13  e15_13f1_220119      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.48   92.81   1.82   89.09      13.17  221.91                    1.00
14  e15_13f1_220119      1    openField_gergo    SpatialSeries2_openField_gergo         n.a.   0.00   31.50   0.00   35.00       9.23     NaN                     NaN
15  e15_13f1_220119      2      tmaze_ipshita      SpatialSeries3_tmaze_ipshita         n.a.   0.29   66.08   0.46   89.40      13.50  169.99                    0.93
16  e15_13f1_220120      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.72   92.41   2.91   89.32      14.23  221.91                    1.06
17  e15_13f1_220120      1      linear_thomas      SpatialSeries2_linear_thomas         n.a.   0.24    0.90   0.03    0.75       0.09  100.00                   91.77
18   e16_3m2_211210      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.30   92.02   1.36   88.05      11.60  221.93                    1.02
19   e16_3m2_211210      1  openField_coolbox  SpatialSeries2_openField_coolbox         n.a.   0.00   22.50   0.00   22.50       4.72     NaN                     NaN
20   e16_3m2_211211      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   7.16   90.17   4.20   88.46      15.77  221.65                    1.17
21   e16_3m2_211211      1   openField_thomas   SpatialSeries2_openField_thomas         n.a.   0.00   42.98   0.00   52.82       6.93     NaN                     NaN
22   e16_3m2_211212      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.66   90.98   1.76   87.88      12.29  221.91                    1.02
23   e16_3m2_211212      1    openField_gergo    SpatialSeries2_openField_gergo         n.a.   0.00   31.50   0.00   35.00       7.85     NaN                     NaN
24   e16_3m2_211212      2      linear_thomas      SpatialSeries3_linear_thomas         n.a.  28.93  110.22   5.49   93.53      10.51  100.00                    0.88
25   e16_3m2_211213      0     tmaze_familiar     SpatialSeries1_tmaze_familiar  centimeters   1.22   92.05   2.35   89.21      12.06  221.93                    1.03
26   e16_3m2_211213      1      tmaze_ipshita      SpatialSeries2_tmaze_ipshita         n.a.   0.00    0.74   0.01    0.99       0.13  169.99                   84.13
cm per unit from the simultaneous speeds: familiar figure-eight (2D series in cm) [1.0, 1.05, 1.19] ; lab-unit series spanning more than 2 units [0.85, 0.93, 0.88] ; series spanning 0 to 1 [100.4, 104.9, 107.4, 91.8, 84.1]
open fields: extent in lab units {'e13_26m1_211124 openField_gergo': (31.5, 35.0), 'e15_13f1_220117 openField_coolbox': (22.5, 22.5), 'e15_13f1_220118 openField_thomas': (42.67, 51.91), 'e15_13f1_220119 openField_gergo': (31.5, 35.0), 'e16_3m2_211210 openField_coolbox': (22.5, 22.5), 'e16_3m2_211211 openField_thomas': (42.98, 52.82), 'e16_3m2_211212 openField_gergo': (31.5, 35.0)}
open fields: 90th percentile of 1 s speed, lab units/s, against the same session's familiar 2D speed in cm/s: {'e13_26m1_211124 openField_gergo': (9.0, 14.9), 'e15_13f1_220117 openField_coolbox': (5.7, 13.1), 'e15_13f1_220118 openField_thomas': (11.6, 11.2), 'e15_13f1_220119 openField_gergo': (9.2, 13.2), 'e16_3m2_211210 openField_coolbox': (4.7, 11.6), 'e16_3m2_211211 openField_thomas': (6.9, 15.8), 'e16_3m2_211212 openField_gergo': (7.8, 12.3)}
In [36]:
NOVEL_BINS = {"tmaze_ipshita": slice(50, 164)}  # novel figure-eight bins 51-164 (code, claims); linear tracks all bins
nrows, crows = [], []
for x in nv:
    lr = np.where(x["lr"])[0]; nr = np.where(~x["lr"])[0]
    pairs = [(True, a, b) for i, a in enumerate(lr) for b in lr[i + 1:]] + [(False, a, b) for a in lr for b in nr]
    for e in x["epochs"]:
        if e["maps"] is None: continue
        if e["kind"] == "open":   # 2D maps, flattened; the lab-unit scale as assumed (1 cm per unit) and two variants
            versions = [(s, M[0], occ[0]) for s, (M, occ) in e["scales"].items()]
        else:
            M, occ = e["maps"], e["occ"]
            sl = STEM if e["epoch"] == 0 else NOVEL_BINS.get(e["env"], slice(None))
            versions = [(1.0, np.concatenate([M[0][:, sl], M[1][:, sl]], axis=1), None)]
        for scale, V, occ1 in versions:
            for c in range(V.shape[0]):
                if e["kind"] == "open":
                    cat, ocat = V[c], occ1
                else:
                    cat, ocat = np.r_[M[0, c], M[1, c]], np.r_[occ[0], occ[1]]
                ok = np.isfinite(cat) & (ocat > 0)
                r = cat[ok]; mr = r.mean()
                with np.errstate(divide="ignore", invalid="ignore"):
                    eq = float(np.nanmean(np.where(r > 0, r * np.log2(r / mr), 0))) if mr > 0 else np.nan
                crows.append({"session": x["session"], "epoch": e["epoch"], "env": e["env"], "kind": e["kind"], "scale": scale, "unit": c,
                              "lr": bool(x["lr"][c]), "si": h.skaggs_info(cat, ocat), "si_equal": eq})
            for sbd, a, b in pairs:
                nrows.append({"session": x["session"], "epoch": e["epoch"], "env": e["env"], "kind": e["kind"], "scale": scale,
                              "sbd": sbd, "a": a, "b": b, "r": corr_visited(V[a], V[b])})
NP_ALL = pd.DataFrame(nrows); NC_ALL = pd.DataFrame(crows)
def at_scale(df, s): return df[(df.kind == "linear") | (df.scale == s)]
NP, NC = at_scale(NP_ALL, 1.0), at_scale(NC_ALL, 1.0)
print("cells x subsessions:", len(NC), "; pairs x subsessions:", len(NP), "; NaN correlations:", int(NP.r.isna().sum()))
print("open-field bins visited per subsession (1 cm per unit):", NC[NC.kind == "open"].groupby(["session", "env"]).size().to_dict())
cells x subsessions: 5856 ; pairs x subsessions: 71802 ; NaN correlations: 889
open-field bins visited per subsession (1 cm per unit): {('e13_26m1_211124', 'openField_gergo'): 153, ('e15_13f1_220117', 'openField_coolbox'): 333, ('e15_13f1_220118', 'openField_thomas'): 318, ('e15_13f1_220119', 'openField_gergo'): 288, ('e16_3m2_211210', 'openField_coolbox'): 159, ('e16_3m2_211211', 'openField_thomas'): 161, ('e16_3m2_211212', 'openField_gergo'): 162}

Claim fig6d-info-lower-novel: Spatial information is lower in novel environments than in the familiar one (median 0.39 against 0.88 bits/s).

In [37]:
for col in ("si", "si_equal"):
    f_, n_ = NC[NC.epoch == 0][col].dropna(), NC[NC.epoch > 0][col].dropna()
    p = stats.ranksums(n_, f_).pvalue
    print(f"{col}: familiar median {f_.median():.3f} bits/s (n = {len(f_)}), novel median {n_.median():.3f} (n = {len(n_)}), rank-sum p = {p:.3g}")
print("novel medians by environment:", NC[NC.epoch > 0].groupby("env").si.median().round(3).to_dict())
for s_ in h.OPEN_SCALES[1:]:
    d_ = at_scale(NC_ALL, s_); f_, n_ = d_[d_.epoch == 0].si.dropna(), d_[d_.epoch > 0].si.dropna()
    print(f"variant, open fields at {s_} cm per unit: familiar {f_.median():.3f}, novel {n_.median():.3f} (n = {len(n_)}), rank-sum p = {stats.ranksums(n_, f_).pvalue:.3g}")
d_ = NC[NC.kind != "open"]; f_, n_ = d_[d_.epoch == 0].si.dropna(), d_[d_.epoch > 0].si.dropna()
print(f"variant, open fields left out: novel {n_.median():.3f} (n = {len(n_)}), rank-sum p = {stats.ranksums(n_, f_).pvalue:.3g}")
si: familiar median 0.661 bits/s (n = 2532), novel median 0.260 (n = 3289), rank-sum p = 4.95e-100
si_equal: familiar median 0.684 bits/s (n = 2532), novel median 0.289 (n = 3289), rank-sum p = 8.41e-97
novel medians by environment: {'linear_manu': 0.341, 'linear_thomas': 0.303, 'openField_coolbox': 0.046, 'openField_gergo': 0.255, 'openField_thomas': 0.388, 'tmaze_ipshita': 0.449}
variant, open fields at 2.0 cm per unit: familiar 0.661, novel 0.305 (n = 3293), rank-sum p = 1.1e-76
variant, open fields at 0.5 cm per unit: familiar 0.661, novel 0.226 (n = 3274), rank-sum p = 2.45e-127
variant, open fields at 0.85 cm per unit: familiar 0.661, novel 0.251 (n = 3287), rank-sum p = 1.47e-105
variant, open fields left out: novel 0.367 (n = 1728), rank-sum p = 9.85e-36

Result: partially reproduced. Spatial information is lower in novel environments than on the familiar maze (median 0.260 over 3,289 cell-environment values against 0.661 bits/s over 2,532 cells, rank-sum p = 5.0e-100), but both medians are outside tolerance. The same holds under every reading of the open-field scale (novel 0.305 at 2 cm per unit, 0.226 at 0.5, 0.251 at 0.85) and without the open fields (0.367, within tolerance, with the familiar median still outside), all with p < 1e-35.

Claim fig6c-novel-ratemap-corr-higher: Pairwise spatial ratemap correlations are higher in novel environments (median 0.048) than in the familiar environment (median -0.045).

In [38]:
f_, n_ = NP[NP.epoch == 0].r.dropna(), NP[NP.epoch > 0].r.dropna()
p = stats.ranksums(n_, f_).pvalue
print(f"familiar median {f_.median():.4f} (n = {len(f_)}), novel median {n_.median():.4f} (n = {len(n_)}), rank-sum p = {p:.3g}")
print("within tolerance:", abs(f_.median() + 0.045) <= 0.0045, abs(n_.median() - 0.048) <= 0.0048)
print("novel medians by environment:", NP[NP.epoch > 0].groupby("env").r.median().round(4).to_dict())
for s_ in h.OPEN_SCALES[1:]:
    d_ = at_scale(NP_ALL, s_); f_, n_ = d_[d_.epoch == 0].r.dropna(), d_[d_.epoch > 0].r.dropna()
    print(f"variant, open fields at {s_} cm per unit: familiar {f_.median():.4f}, novel {n_.median():.4f} (n = {len(n_)}), rank-sum p = {stats.ranksums(n_, f_).pvalue:.3g}")
d_ = NP[NP.kind != "open"]; f_, n_ = d_[d_.epoch == 0].r.dropna(), d_[d_.epoch > 0].r.dropna()
print(f"variant, open fields left out: novel {n_.median():.4f} (n = {len(n_)}), rank-sum p = {stats.ranksums(n_, f_).pvalue:.3g}")
familiar median -0.0451 (n = 31211), novel median -0.0307 (n = 39702), rank-sum p = 0.784
within tolerance: True False
novel medians by environment: {'linear_manu': -0.0306, 'linear_thomas': -0.0104, 'openField_coolbox': -0.0074, 'openField_gergo': -0.0292, 'openField_thomas': -0.0415, 'tmaze_ipshita': -0.0483}
variant, open fields at 2.0 cm per unit: familiar -0.0451, novel -0.0246 (n = 39748), rank-sum p = 2.07e-06
variant, open fields at 0.5 cm per unit: familiar -0.0451, novel -0.0331 (n = 39532), rank-sum p = 0.0104
variant, open fields at 0.85 cm per unit: familiar -0.0451, novel -0.0313 (n = 39683), rank-sum p = 0.567
variant, open fields left out: novel -0.0320 (n = 22373), rank-sum p = 0.751

Result: not reproduced, resting on the assumed open-field scale. With the open fields at 1 cm per lab unit, the novel median pairwise ratemap correlation is -0.031 over 39,702 pair-environment values (the paper has 41,991) against -0.045 on the familiar maze, rank-sum p = 0.78: higher, but not significantly. The outcome depends on that scale: at 0.85 cm per unit, the scale the simultaneous speeds give for the lab-unit series of the linear tracks and the novel figure-eight (0.85, 0.88 and 0.93 cm per unit, against 1.00 to 1.19 for the familiar maze's 2D series in cm), p = 0.57, and without the open fields p = 0.75, the same outcome; at 2 cm per unit p = 2.1e-6 and at 0.5 cm per unit p = 0.010, which would give partially reproduced. The data do not give the open fields' scale: their positions start at 0 and end at round values (31.5 x 35.0, 22.5 x 22.5 units) or near them (about 43 x 52), and their 90th-percentile speeds, 4.7 to 11.6 units/s, are at or below the same sessions' 11.2 to 15.8 cm/s on the familiar maze (in six of seven below), which fits a scale near 1 and does not rule out 2. The familiar median is within tolerance; the novel one (0.048 expected) is not under any reading (-0.025 to -0.033).

Claim fig6e-sbd-novel-overlap: In novel environments SBD pairs have higher ratemap correlations than DBD pairs (median 0.117 against 0.046).

In [39]:
s, d, p = sbd_dbd(NP[NP.epoch > 0], "r")
print("within tolerance:", abs(s - 0.117) <= 0.0117, abs(d - 0.046) <= 0.0046)
print("by environment SBD/DBD medians:", NP[NP.epoch > 0].groupby(["env", "sbd"]).r.median().round(4).to_dict())
for s_ in h.OPEN_SCALES[1:]:
    d_ = at_scale(NP_ALL, s_); d_ = d_[d_.epoch > 0]
    a_, b_ = d_[d_.sbd].r.dropna(), d_[~d_.sbd].r.dropna()
    print(f"variant, open fields at {s_} cm per unit: SBD {a_.median():.4f} DBD {b_.median():.4f}, rank-sum p = {stats.ranksums(a_, b_).pvalue:.3g}")
d_ = NP[(NP.epoch > 0) & (NP.kind != "open")]
print(f"variant, open fields left out: SBD {d_[d_.sbd].r.median():.4f} DBD {d_[~d_.sbd].r.median():.4f}, p = {stats.ranksums(d_[d_.sbd].r.dropna(), d_[~d_.sbd].r.dropna()).pvalue:.3g}")
r: SBD median 0.0206 (n = 1390), DBD median -0.0326 (n = 38312), two-sided Wilcoxon rank-sum p = 0.00111; dropped (NaN) SBD 0, DBD 335
within tolerance: False False
by environment SBD/DBD medians: {('linear_manu', False): -0.0339, ('linear_manu', True): 0.0767, ('linear_thomas', False): -0.0134, ('linear_thomas', True): 0.0371, ('openField_coolbox', False): -0.0086, ('openField_coolbox', True): 0.0526, ('openField_gergo', False): -0.03, ('openField_gergo', True): -0.0242, ('openField_thomas', False): -0.0427, ('openField_thomas', True): 0.0042, ('tmaze_ipshita', False): -0.0496, ('tmaze_ipshita', True): 0.0072}
variant, open fields at 2.0 cm per unit: SBD 0.0186 DBD -0.0259, rank-sum p = 0.00023
variant, open fields at 0.5 cm per unit: SBD 0.0231 DBD -0.0349, rank-sum p = 0.00368
variant, open fields at 0.85 cm per unit: SBD 0.0198 DBD -0.0327, rank-sum p = 0.00116
variant, open fields left out: SBD 0.0296 DBD -0.0343, p = 0.00202

Result: partially reproduced. In novel environments SBD pairs correlate more than DBD pairs (median 0.021 against -0.033 over 1,390 and 38,312 values, rank-sum p = 0.0011), but both medians are outside tolerance (0.117 and 0.046 expected). The same holds at 2, 0.5 and 0.85 cm per unit (p = 0.00023, 0.0037 and 0.0012) and without the open fields (p = 0.002).

Claim fig6f-remap-together-novel: Ratemaps of SBD pairs remain closer together than those of DBD pairs between the familiar and novel environments.

In [40]:
famr = NP[NP.epoch == 0][["session", "a", "b", "sbd", "r"]].rename(columns={"r": "fam"})
novr = NP[NP.epoch > 0][["session", "a", "b", "epoch", "r"]].rename(columns={"r": "nov"})
J = novr.merge(famr, on=["session", "a", "b"]).dropna(subset=["fam", "nov"])
J["grp"] = np.where(J.sbd, "SBD", "DBD")
ea = np.percentile(famr.fam.dropna(), [0, 33, 66, 99])  # each familiar pair once (legend)
eb = np.percentile(np.r_[famr.fam.dropna(), novr.nov.dropna()], [0, 33, 66, 99])
for lab, e in (("(a) familiar SBD and DBD correlations", ea), ("(b) code, all three columns", eb)):
    e = e.copy(); e[0], e[-1] = -np.inf, np.inf
    o = J.copy(); o["ter"] = pd.cut(o.fam, e, labels=[1, 2, 3])
    fit = smf.ols("nov ~ C(grp, Sum) * C(ter, Sum)", data=o).fit()
    an = sm.stats.anova_lm(fit, typ=3)
    mt = o.groupby(["ter", "grp"], observed=True).nov.mean().unstack()
    print(f"{lab}: n SBD {int(o.sbd.sum())}, DBD {int((~o.sbd).sum())}; birthdate F = {an.loc['C(grp, Sum)', 'F']:.2f}, p = {an.loc['C(grp, Sum)', 'PR(>F)']:.3g}; "
          f"tercile p = {an.loc['C(ter, Sum)', 'PR(>F)']:.3g}; interaction p = {an.loc['C(grp, Sum):C(ter, Sum)', 'PR(>F)']:.3g}")
    print("   tercile means:", mt.round(4).to_dict(), "; terciles with SBD > DBD:", int((mt.SBD > mt.DBD).sum()),
          "; SBD mean over all", round(o[o.sbd].nov.mean(), 4), "DBD", round(o[~o.sbd].nov.mean(), 4))
print("familiar pairs entering twice (sessions with two novel environments):", int(J.duplicated(["session", "a", "b"]).sum()))
# variant: one novel value per pair, the mean over its novel environments
J1 = J.groupby(["session", "a", "b", "sbd", "grp"], as_index=False).agg(nov=("nov", "mean"), fam=("fam", "first"))
e = ea.copy(); e[0], e[-1] = -np.inf, np.inf
o = J1.copy(); o["ter"] = pd.cut(o.fam, e, labels=[1, 2, 3])
an = sm.stats.anova_lm(smf.ols("nov ~ C(grp, Sum) * C(ter, Sum)", data=o).fit(), typ=3)
print(f"variant, one value per pair (reading a edges): n SBD {int(o.sbd.sum())}, DBD {int((~o.sbd).sum())}; birthdate F = {an.loc['C(grp, Sum)', 'F']:.2f}, p = {an.loc['C(grp, Sum)', 'PR(>F)']:.3g}")
print("Supplementary Table 5 tercile means, for comparison: SBD 0.0952, 0.1566, 0.15; DBD 0.0851, 0.0846, 0.0989")
def remap_novel_p(NPx):
    fr = NPx[NPx.epoch == 0][["session", "a", "b", "sbd", "r"]].rename(columns={"r": "fam"})
    nr = NPx[NPx.epoch > 0][["session", "a", "b", "epoch", "r"]].rename(columns={"r": "nov"})
    j = nr.merge(fr, on=["session", "a", "b"]).dropna(subset=["fam", "nov"]); j["grp"] = np.where(j.sbd, "SBD", "DBD")
    e = np.percentile(fr.fam.dropna(), [0, 33, 66, 99]); e[0], e[-1] = -np.inf, np.inf
    j["ter"] = pd.cut(j.fam, e, labels=[1, 2, 3])
    an = sm.stats.anova_lm(smf.ols("nov ~ C(grp, Sum) * C(ter, Sum)", data=j).fit(), typ=3)
    mt = j.groupby(["ter", "grp"], observed=True).nov.mean().unstack()
    return an.loc["C(grp, Sum)", "F"], an.loc["C(grp, Sum)", "PR(>F)"], int((mt.SBD > mt.DBD).sum()), j[j.sbd].nov.mean() > j[~j.sbd].nov.mean()
for s_ in h.OPEN_SCALES[1:]:
    F_, p_, k_, hi_ = remap_novel_p(at_scale(NP_ALL, s_))
    print(f"variant (a), open fields at {s_} cm per unit: birthdate F = {F_:.2f}, p = {p_:.3g}; SBD higher overall: {hi_}; terciles with SBD > DBD: {k_}")
F_, p_, k_, hi_ = remap_novel_p(NP[NP.kind != "open"])
print(f"variant (a), open fields left out: birthdate F = {F_:.2f}, p = {p_:.3g}; SBD higher overall: {hi_}; terciles with SBD > DBD: {k_}")
(a) familiar SBD and DBD correlations: n SBD 1380, DBD 37762; birthdate F = 7.75, p = 0.00536; tercile p = 0.000685; interaction p = 0.0073
   tercile means: {'DBD': {1: 0.008, 2: 0.0145, 3: 0.0152}, 'SBD': {1: 0.0044, 2: 0.0304, 3: 0.0721}} ; terciles with SBD > DBD: 2 ; SBD mean over all 0.0358 DBD 0.0126
(b) code, all three columns: n SBD 1380, DBD 37762; birthdate F = 8.39, p = 0.00378; tercile p = 0.00106; interaction p = 0.0106
   tercile means: {'DBD': {1: 0.0083, 2: 0.0137, 3: 0.0155}, 'SBD': {1: 0.0051, 2: 0.0316, 3: 0.0727}} ; terciles with SBD > DBD: 2 ; SBD mean over all 0.0358 DBD 0.0126
familiar pairs entering twice (sessions with two novel environments): 8134
variant, one value per pair (reading a edges): n SBD 1202, DBD 29806; birthdate F = 7.02, p = 0.00807
Supplementary Table 5 tercile means, for comparison: SBD 0.0952, 0.1566, 0.15; DBD 0.0851, 0.0846, 0.0989
variant (a), open fields at 2.0 cm per unit: birthdate F = 9.72, p = 0.00183; SBD higher overall: True; terciles with SBD > DBD: 2
variant (a), open fields at 0.5 cm per unit: birthdate F = 5.18, p = 0.0229; SBD higher overall: True; terciles with SBD > DBD: 2
variant (a), open fields at 0.85 cm per unit: birthdate F = 7.56, p = 0.00597; SBD higher overall: True; terciles with SBD > DBD: 2
variant (a), open fields left out: birthdate F = 5.84, p = 0.0157; SBD higher overall: True; terciles with SBD > DBD: 3

Result: reproduced, resting on the assumed open-field scale. Under both readings of the tercile edges the birthdate main effect has p = 0.0054 and 0.0038 with SBD higher (mean novel correlation 0.036 against 0.013 over 1,380 SBD and 37,762 DBD observations); SBD exceeds DBD in the middle and upper terciles, not the lowest, and the interaction has p = 0.0073 under reading (a). Counting each pair once in the ANOVA (the mean over its novel environments) gives p = 0.0081. Under reading (a) the main effect holds with SBD higher at 2, 0.5 and 0.85 cm per unit (p = 0.0018, 0.023 and 0.0060) and without the open fields (p = 0.016, SBD above DBD in all three terciles). The tercile means (SBD 0.004, 0.030, 0.072; DBD 0.008, 0.015, 0.015) are all below those of Supplementary Table 5 (SBD 0.0952, 0.1566, 0.15; DBD 0.0851, 0.0846, 0.0989), as the novel correlations as a whole are lower here (fig6c-novel-ratemap-corr-higher).

Monosynaptic connections¶

Pyramidal-to-interneuron CCGs in 0.8 ms bins from spikes outside the light pulse periods, over the 96 homecage-mouse sessions (h.mono_session). The Methods give the test as identical to the reliability test of the light-responsive detection (hollowed Gaussian baseline, 15 ms s.d., Poisson tests at alpha 0.001 Bonferroni corrected, the peak against the bins before zero lag) and refer to English et al. (2017) for the rest. Assumed: the lags tested (0.8 to 2.8 ms, the window of the transmission measure), the hollow fraction (0.6, the value of Stark and Abeles 2009 that English et al. use), and minimums of 100 presynaptic spikes and 50 CCG counts. The second cell changes each in turn: the reliability test's literal "3 bins surrounding" the peak, hollow 0.4 and 0.8, kernel s.d. 7 and 10 ms, no minimums, and alpha 1e-5.

In [41]:
t = time.time()
mo = h.run_sessions(h.mono_session, HM)
CON_ALL = pd.DataFrame([r for x in mo for r in x["rows"]])
CON = CON_ALL[CON_ALL.v_main].reset_index(drop=True)
npairs = sum(x["conn"].size for x in mo)
print(f"{time.time()-t:.0f} s; possible pyramidal-interneuron pairs {npairs}; tested (>= 100 presynaptic spikes, CCG with >= 50 counts) "
      f"{sum(x['n_tested'] for x in mo)}; connections {int(sum(x['conn'].sum() for x in mo))}")
346 s; possible pyramidal-interneuron pairs 184230; tested (>= 100 presynaptic spikes, CCG with >= 50 counts) 183641; connections 50618
In [42]:
# The detector's assumed details, one at a time (h.MONO_VARIANTS): connections, fig7b convergence, the share of pyramidal
# pairs with a shared target (fig7fg), the transmission peak (fig7d) and the transmission medians of light-responsive presynaptic cells (fig7ce).
centres = np.sqrt(h.ISI_EDGES[:-1] * h.ISI_EDGES[1:]) * 1000
vrows = []
for v, spec in h.MONO_VARIANTS.items():
    sb_, db_, nz_, tot_ = [], [], 0, 0
    for x in mo:
        c = x["flags"][v]; lr = np.where(x["lr"])[0]; nr = np.where(~x["lr"])[0]
        sb_ += [h.convergence(c, a, b) for i, a in enumerate(lr) for b in lr[i + 1:]]
        db_ += [h.convergence(c, a, b) for a in lr for b in nr]
        ci = c.astype(int); sh = ci @ ci.T; iu = np.triu_indices(len(ci), 1); nz_ += int((sh[iu] > 0).sum()); tot_ += len(iu[0])
    sb_, db_ = np.array(sb_, float), np.array(db_, float)
    sb_, db_ = sb_[np.isfinite(sb_)], db_[np.isfinite(db_)]
    cv_ = CON_ALL[CON_ALL["v_" + v]]
    mean_ = np.nanmean(np.array(cv_.stp_isi.tolist(), float), 0)
    stp_ = cv_[cv_.pre_lr].groupby("birthdate").stp.median()
    vrows.append({"variant": v, **{k: str(val) for k, val in spec.items()}, "connections": int(sum(x["flags"][v].sum() for x in mo)),
                  "SBD_cv": np.median(sb_), "DBD_cv": np.median(db_), "p": stats.ranksums(sb_, db_).pvalue,
                  "pct_shared": 100 * nz_ / tot_, "peak_ms": centres[int(np.nanargmax(mean_))],
                  "stp_medians": np.round(stp_.values, 4).tolist()})
VR = pd.DataFrame(vrows)
print(VR.drop(columns=[c for c in VR.columns if c not in ("variant", "connections", "SBD_cv", "DBD_cv", "p", "pct_shared", "peak_ms", "stp_medians")]).round(4).to_string())
print("paper: 31,932 connections, convergence 0.2727 and 0.2, 65.27% shared, peak in 15-23 ms; settings:", {k: v for k, v in h.MONO_VARIANTS.items()})
       variant  connections  SBD_cv  DBD_cv    p  pct_shared  peak_ms                       stp_medians
0         main        50618  0.4545  0.3636  0.0     86.2407  34.8884   [0.0141, 0.0153, 0.0172, 0.015]
1        peak3        50756  0.4545  0.3684  0.0     86.3679  34.8884     [0.014, 0.0153, 0.017, 0.015]
2    hollow0.4        50575  0.4545  0.3636  0.0     86.2106  34.8884   [0.0141, 0.0153, 0.0172, 0.015]
3    hollow0.8        50663  0.4545  0.3636  0.0     86.2975  34.8884   [0.0141, 0.0153, 0.0171, 0.015]
4        sd7ms        49564  0.4545  0.3636  0.0     85.2465  34.8884  [0.0144, 0.0156, 0.0178, 0.0153]
5       sd10ms        50149  0.4545  0.3636  0.0     85.8259  34.8884   [0.0142, 0.0153, 0.0174, 0.015]
6  no_minimums        50621  0.4545  0.3636  0.0     86.2501  34.8884   [0.0141, 0.0153, 0.0172, 0.015]
7    alpha1e-5        38402  0.3846  0.2778  0.0     74.4806  34.8884  [0.0163, 0.0177, 0.0203, 0.0181]
paper: 31,932 connections, convergence 0.2727 and 0.2, 65.27% shared, peak in 15-23 ms; settings: {'main': {}, 'peak3': {'window': 'peak'}, 'hollow0.4': {'hollow': 0.4}, 'hollow0.8': {'hollow': 0.8}, 'sd7ms': {'sd_s': 0.007}, 'sd10ms': {'sd_s': 0.01}, 'no_minimums': {'min_counts': 0, 'min_pre': 0}, 'alpha1e-5': {'alpha': 1e-05}}

Claim fig7b-sbd-convergence: SBD pyramidal pairs converge onto the same interneurons more than DBD pairs (median convergence 0.2727 against 0.2).

In [43]:
crow = []
for x in mo:
    c = x["conn"]; lr = np.where(x["lr"])[0]; nr = np.where(~x["lr"])[0]
    for i, a in enumerate(lr):
        for b in lr[i + 1:]: crow.append({"session": x["session"], "subject": x["subject"], "birthdate": x["birthdate"], "sbd": True, "cv": h.convergence(c, a, b)})
        for b in nr: crow.append({"session": x["session"], "subject": x["subject"], "birthdate": x["birthdate"], "sbd": False, "cv": h.convergence(c, a, b)})
CV = pd.DataFrame(crow)
s, d, p = sbd_dbd(CV, "cv")
print("within tolerance:", abs(s - 0.2727) <= 0.0273, abs(d - 0.2) <= 0.02)
print("by birthdate SBD/DBD medians:", CV.groupby(["birthdate", "sbd"]).cv.median().round(4).to_dict())
cv: SBD median 0.4545 (n = 3748), DBD median 0.3636 (n = 50341), two-sided Wilcoxon rank-sum p = 1.31e-79; dropped (NaN) SBD 3, DBD 120
within tolerance: False False
by birthdate SBD/DBD medians: {('E13.5', False): 0.4286, ('E13.5', True): 0.5455, ('E14.5', False): 0.2857, ('E14.5', True): 0.4286, ('E15.5', False): 0.3, ('E15.5', True): 0.4, ('E16.5', False): 0.375, ('E16.5', True): 0.4286}

Result: partially reproduced, resting on the assumed connection detector. SBD pairs converge more than DBD pairs (median 0.455 against 0.364, rank-sum p = 1.3e-79), but both medians are far above the paper's (0.273 and 0.200); the detector finds 50,618 connections against the paper's 31,932. No variant of the detector's assumed details brings the count near the paper's (49,564 to 50,756 connections, 38,402 at alpha 1e-5), and under every variant SBD exceeds DBD, with SBD medians of 0.385 to 0.455 and DBD medians of 0.278 to 0.368, all above the paper's 0.273 and 0.200.

Claim fig7ce-convergence-by-birthdate: Convergence onto interneurons (DBD-corrected medians 0.0857, 0.1071, 0.1, 0.0285) and spike transmission probability (0.0184, 0.0202, 0.0222, 0.0199) are bell-shaped functions of the presynaptic neurons' birthdate.

In [44]:
sb = CV[CV.sbd].dropna().copy()
dm = CV[~CV.sbd].groupby("birthdate").cv.median()
sb["cv_corr"] = sb.cv - sb.birthdate.map(dm)
m1, p1 = by_bd(sb, "cv_corr", "fig7ce-convergence-by-birthdate")
print("corrected convergence: inverted-U", h.inverted_u(m1), "within tolerance", [abs(a - e) <= 0.1 * abs(e) for a, e in zip(m1, [0.0857, 0.1071, 0.1, 0.0285])])
L7 = CON[CON.pre_lr]
m2, p2 = by_bd(L7, "stp", "fig7ce-convergence-by-birthdate")
print("transmission: inverted-U", h.inverted_u(m2),
      "; within tolerance, legend:", [abs(a - e) <= 0.1 * e for a, e in zip(m2, [0.0184, 0.0202, 0.0222, 0.0199])],
      "; table:", [abs(a - e) <= 0.1 * e for a, e in zip(m2, [0.0238, 0.02356, 0.0247, 0.0195])])
cv_corr: n = [1199, 532, 1578, 439], medians = [0.1169, 0.1429, 0.1, 0.0536], ranges = [(-0.429, 0.571), (-0.286, 0.714), (-0.3, 0.7), (-0.375, 0.625)]
  bootstrap Kruskal-Wallis H = 47.339; p under the claim's seed and +1000..+4000: [0.0, 0.0, 0.0, 0.0, 0.0]
corrected convergence: inverted-U True within tolerance [False, False, True, False]
stp: n = [2040, 671, 1584, 859], medians = [0.0141, 0.0153, 0.0172, 0.015], ranges = [(0.0, 0.21), (0.001, 0.377), (0.0, 0.347), (0.0, 0.289)]
  bootstrap Kruskal-Wallis H = 35.518; p under the claim's seed and +1000..+4000: [0.0, 0.0, 0.0, 0.0, 0.0]
transmission: inverted-U True ; within tolerance, legend: [False, False, False, False] ; table: [False, False, False, False]

Result: partially reproduced, resting on the assumed connection detector. Corrected convergence (medians 0.117, 0.143, 0.100, 0.054) and transmission probability (0.0141, 0.0153, 0.0172, 0.0150) are both inverted U across birthdates with bootstrap Kruskal-Wallis p < 0.0002, but only one median of the eight (corrected convergence, E15.5) is within tolerance under either reading of the transmission medians. Under the detector variants at most two of the four transmission medians are within tolerance of the legend's (alpha 1e-5).

Claim fig7d-transmission-gamma: Spike transmission probability peaks at presynaptic interspike intervals of 15 to 23 ms, in the gamma range, with short-term depression at shorter intervals.

In [45]:
isi = np.array(CON.stp_isi.tolist(), float)
centres = np.sqrt(h.ISI_EDGES[:-1] * h.ISI_EDGES[1:]) * 1000
mean = np.nanmean(isi, 0)
print(pd.DataFrame({"isi_lo_ms": h.ISI_EDGES[:-1] * 1000, "isi_hi_ms": h.ISI_EDGES[1:] * 1000, "centre_ms": centres,
                    "mean_stp": mean, "n": np.isfinite(isi).sum(0)}).round(4).to_string())
k = int(np.nanargmax(mean))
print(f"peak bin {h.ISI_EDGES[k]*1000:.1f}-{h.ISI_EDGES[k+1]*1000:.1f} ms (centre {centres[k]:.1f}); in 13.5-25.3 ms: {13.5 <= centres[k] <= 25.3}; "
      f"shortest bin {mean[0]:.4f} below peak {mean[k]:.4f}: {mean[0] < mean[k]}")
for lab, sel in (("light-responsive presynaptic only", CON.pre_lr.values),):
    mm = np.nanmean(isi[sel], 0); kk = int(np.nanargmax(mm)); print(lab, "peak centre", round(centres[kk], 1), "ms")
# how firm is the peak bin: connections resampled with replacement, the claim's seed and four more
inside = (centres >= 13.5) & (centres <= 25.3)
for k_s in SEEDS_PLUS:
    rng7d = np.random.default_rng(seed("fig7d-transmission-gamma") + k_s)
    pk, dif = [], []
    for _ in range(1000 if k_s == 0 else 200):
        mm = np.nanmean(isi[rng7d.integers(0, len(isi), len(isi))], 0)
        pk.append(int(np.nanargmax(mm))); dif.append(mm[5] - mm[4])
    pk, dif = np.array(pk), np.array(dif)
    print(f"seed +{k_s}: {len(pk)} resamplings; peak bin centre counts", {f"{centres[j]:.1f} ms": int((pk == j).sum()) for j in np.unique(pk)},
          f"; fraction with the peak in 13.5-25.3 ms {np.mean(inside[pk]):.3f}; 29-42 minus 20-29 ms bin mean {np.mean(dif):.5f}, 95% interval {np.percentile(dif, 2.5):.5f} to {np.percentile(dif, 97.5):.5f}")
    isi_lo_ms  isi_hi_ms  centre_ms  mean_stp      n
0      5.0000     7.1182     5.9658    0.0190  50579
1      7.1182    10.1338     8.4932    0.0213  50587
2     10.1338    14.4270    12.0914    0.0229  50579
3     14.4270    20.5389    17.2138    0.0249  50541
4     20.5389    29.2402    24.5064    0.0266  50464
5     29.2402    41.6277    34.8884    0.0269  50348
6     41.6277    59.2631    49.6687    0.0267  50214
7     59.2631    84.3696    70.7107    0.0262  50276
8     84.3696   120.1124   100.6670    0.0257  50381
9    120.1124   170.9976   143.3141    0.0254  50449
10   170.9976   243.4400   204.0286    0.0253  50437
11   243.4400   346.5724   290.4645    0.0249  50465
12   346.5724   493.3964   413.5186    0.0248  50485
13   493.3964   702.4218   588.7040    0.0248  50522
14   702.4218  1000.0000   838.1061    0.0248  50560
peak bin 29.2-41.6 ms (centre 34.9); in 13.5-25.3 ms: False; shortest bin 0.0190 below peak 0.0269: True
light-responsive presynaptic only peak centre 34.9 ms
seed +0: 1000 resamplings; peak bin centre counts {'34.9 ms': 999, '49.7 ms': 1} ; fraction with the peak in 13.5-25.3 ms 0.000; 29-42 minus 20-29 ms bin mean 0.00033, 95% interval 0.00017 to 0.00050
seed +1000: 200 resamplings; peak bin centre counts {'34.9 ms': 200} ; fraction with the peak in 13.5-25.3 ms 0.000; 29-42 minus 20-29 ms bin mean 0.00033, 95% interval 0.00017 to 0.00048
seed +2000: 200 resamplings; peak bin centre counts {'34.9 ms': 200} ; fraction with the peak in 13.5-25.3 ms 0.000; 29-42 minus 20-29 ms bin mean 0.00033, 95% interval 0.00018 to 0.00049
seed +3000: 200 resamplings; peak bin centre counts {'34.9 ms': 200} ; fraction with the peak in 13.5-25.3 ms 0.000; 29-42 minus 20-29 ms bin mean 0.00034, 95% interval 0.00018 to 0.00051
seed +4000: 200 resamplings; peak bin centre counts {'34.9 ms': 199, '49.7 ms': 1} ; fraction with the peak in 13.5-25.3 ms 0.000; 29-42 minus 20-29 ms bin mean 0.00033, 95% interval 0.00017 to 0.00050

Result: not reproduced, resting on the assumed connection detector. Mean transmission probability rises from 0.0190 at 5-7 ms ISIs to a peak of 0.0269 in the 29-42 ms bin (centre 34.9 ms), outside 13.5 to 25.3 ms; the shortest-ISI bin is below the peak, as the claim's depression at short intervals says. The peak exceeds the 20-29 ms bin (0.0266, centre 24.5 ms, inside the range) by 0.0003; with the connections resampled, that difference has a 95% interval of 0.00017 to 0.00050 and the peak is in the 29-42 ms bin in 999 of 1,000 resamplings, never inside 13.5 to 25.3 ms, under all five seeds. The peak stays in the same bin under every detector variant.

Claim fig7fg-convergence-cofiring: Of 184,230 possible pyramidal-interneuron pairs, 31,932 are monosynaptically connected; 65.27% of pyramidal pairs share at least one postsynaptic interneuron, and cofiring in SPW-Rs, theta cycles and ratemap overlap all increase with convergence.

In [46]:
RMAT = {r[2]["session"]: r[2]["rip_corr_mat"] for r in hc_res}
MAPV = {}
for x in mz:
    MAPV[x["session"]] = np.concatenate([x["maps"][0][:, STEM], x["maps"][1][:, STEM]], axis=1)
rows, nz, tot, anyt = [], 0, 0, 0
for x in mo:
    c = x["conn"].astype(int); n = len(c)
    if n < 2: continue
    sh = c @ c.T; un = c.shape[1] - (1 - c) @ (1 - c).T  # shared targets; union of targets
    iu = np.triu_indices(n, 1)
    nz += int((sh[iu] > 0).sum()); tot += len(iu[0]); anyt += int((un[iu] > 0).sum())
    lr = x["lr"]; rm = RMAT[x["session"]]; tm = TMAT[x["session"]]; V = MAPV.get(x["session"])
    for a, b in zip(*iu):
        if sh[a, b] == 0: continue
        rows.append({"session": x["session"], "nr_pair": (not lr[a]) and (not lr[b]), "cv": sh[a, b] / un[a, b],
                     "rip": rm[a, b], "theta": tm[a, b], "map": corr_visited(V[a], V[b]) if V is not None else np.nan})
Q = pd.DataFrame(rows)
nconn = int(sum(x["conn"].sum() for x in mo))
print("legend's pyramidal pairs (108,468 with zero and 207,254 with nonzero convergence):", 108468 + 207254, "; here, all pairs", tot, "and pairs with any target", anyt)
print(f"connections {nconn} of {npairs} possible; pyramidal pairs with >= 1 shared interneuron {nz} of {tot} ({100*nz/tot:.2f}%); "
      f"of pairs with any target {anyt} ({100*nz/max(anyt,1):.2f}%)")
def quint_reg(df, col, claim, k):
    d = df.dropna(subset=[col]).copy()
    d["q"] = pd.qcut(d.cv.rank(method="first"), 5, labels=False) + 1
    X = d.q.values.astype(float); Y = d[col].values
    def tstat(x, y):
        xm = x - x.mean(); b = (xm @ (y - y.mean())) / (xm @ xm)
        res = y - y.mean() - b * xm; se = np.sqrt((res @ res) / (len(y) - 2) / (xm @ xm)); return b, b / se
    b, t = tstat(X, Y)
    rng = np.random.default_rng(seed(claim) + k)
    null = np.array([tstat(X, rng.choice(Y, len(Y)))[1] for _ in range(1000)])
    return b, t, float(np.mean(np.abs(null) >= abs(t))), [round(float(v), 4) for v in d.groupby("q")[col].mean()], len(d)
for lab, sel in (("(a) nonresponsive pairs", Q.nr_pair), ("(b) all pyramidal pairs", Q.index >= 0)):
    for col in ("rip", "theta", "map"):
        b, t, p, qm, n = quint_reg(Q[sel], col, "fig7fg-convergence-cofiring", 0)
        print(f"{lab}, {col}: n = {n}, quintile means {qm}, slope {b:.4f}, t = {t:.2f}, bootstrap p = {p:.3f}")
for k in SEEDS_PLUS[1:]:
    print(f"seed +{k} (a):", [round(quint_reg(Q[Q.nr_pair], col, 'fig7fg-convergence-cofiring', k)[2], 3) for col in ("rip", "theta", "map")])
b, t, p, qm, n = quint_reg(Q[Q.nr_pair & Q.session.isin(RULE_SESS)], "theta", "fig7fg-convergence-cofiring", 0)
print(f"variant, (a) theta on the sessions whose channel follows the rule: n = {n}, quintile means {qm}, slope {b:.4f}, t = {t:.2f}, bootstrap p = {p:.3f}")
b, t, p, qm, n = quint_reg(Q[Q.nr_pair & ~Q.session.isin(RULE_SESS)], "theta", "fig7fg-convergence-cofiring", 0)
print(f"variant, (a) theta on the other sessions: n = {n}, quintile means {qm}, slope {b:.4f}, t = {t:.2f}, bootstrap p = {p:.3f}")
legend's pyramidal pairs (108,468 with zero and 207,254 with nonzero convergence): 315722 ; here, all pairs 371756 and pairs with any target 370837
connections 50618 of 184230 possible; pyramidal pairs with >= 1 shared interneuron 320605 of 371756 (86.24%); of pairs with any target 370837 (86.45%)
(a) nonresponsive pairs, rip: n = 272239, quintile means [0.0163, 0.0193, 0.0236, 0.0268, 0.0327], slope 0.0040, t = 55.48, bootstrap p = 0.000
(a) nonresponsive pairs, theta: n = 272533, quintile means [0.0076, 0.0096, 0.0117, 0.0139, 0.0194], slope 0.0028, t = 48.59, bootstrap p = 0.000
(a) nonresponsive pairs, map: n = 195615, quintile means [0.0111, 0.0115, 0.0109, 0.0096, 0.0206], slope 0.0017, t = 4.26, bootstrap p = 0.000
(b) all pyramidal pairs, rip: n = 319936, quintile means [0.0171, 0.02, 0.0245, 0.0279, 0.0341], slope 0.0042, t = 63.89, bootstrap p = 0.000
(b) all pyramidal pairs, theta: n = 320254, quintile means [0.0079, 0.0099, 0.0121, 0.0146, 0.0202], slope 0.0029, t = 55.31, bootstrap p = 0.000
(b) all pyramidal pairs, map: n = 234283, quintile means [0.0111, 0.0118, 0.012, 0.013, 0.0221], slope 0.0023, t = 6.30, bootstrap p = 0.000
seed +1000 (a): [0.0, 0.0, 0.0]
seed +2000 (a): [0.0, 0.0, 0.0]
seed +3000 (a): [0.0, 0.0, 0.0]
seed +4000 (a): [0.0, 0.0, 0.0]
variant, (a) theta on the sessions whose channel follows the rule: n = 181592, quintile means [0.0077, 0.0094, 0.0122, 0.0138, 0.0185], slope 0.0026, t = 37.28, bootstrap p = 0.000
variant, (a) theta on the other sessions: n = 90941, quintile means [0.0077, 0.0098, 0.0108, 0.014, 0.0212], slope 0.0031, t = 30.74, bootstrap p = 0.000

Result: not reproduced, resting on the assumed connection detector. The possible pairs are 184,230, the paper's number exactly, but the detector finds 50,618 connections (31,932 +- 3,193 expected) and 86.2% of pyramidal pairs share an interneuron (65.27 +- 6.53% expected). The slopes of SPW-R cofiring, theta cofiring and ratemap correlation on convergence quintile are positive under both readings (0.0040, 0.0028 and 0.0017 for nonresponsive pairs, reading a; 0.0042, 0.0029 and 0.0023 for all pairs, reading b; bootstrap p < 0.001 under all seeds), so the slope part holds. SPW-R and theta cofiring rise across all five quintiles; the ratemap correlation of nonresponsive pairs is flat over the first four (0.0111, 0.0115, 0.0109, 0.0096) and rises in the top quintile (0.0206). On the sessions whose theta channel follows the rule the theta slope is 0.0026 (p < 0.001). The detector variants give 38,402 to 50,756 connections and 74.5 to 86.4% of pairs with a shared interneuron, all outside tolerance. The legend's zero and nonzero pairs sum to 315,722, against 371,756 pyramidal pairs here (370,837 with any target), so the paper's pair set differs in a way the outputs do not show.

Blocked claims¶

Claim ed2-waveform-validation: Light-evoked spikes most resemble the spontaneous spikes of their own cluster, and light-responsive and nonresponsive pyramidal cells have the same waveform trough-to-peak.

The waveform distance needs the waveforms of light-evoked spikes, which need the wide-band signal around the pulses. The processed files hold only each unit's mean waveform over all spikes; the wide-band signal is in the 11 raw files, of which 5 are homecage-mouse sessions (52 to 141 GB each). The claim is blocked. The trough-to-peak part alone is printed here for the record; it does not decide the outcome.

In [47]:
rows = []
for m in metas:
    if m["subject_id"] in h.HOMECAGE_EXCLUDED: continue
    for c, l, v in zip(m["u_putative_cell_type"], m["u_light_responsive"], m["u_trough_to_peak"]):
        if c == "Pyramidal Cell": rows.append({"lr": l, "ttp": v})
TT = pd.DataFrame(rows)
a, b = TT[TT.lr].ttp.dropna(), TT[~TT.lr].ttp.dropna()
print(f"trough-to-peak: light-responsive mean {a.mean():.3f} ms (n = {len(a)}), nonresponsive mean {b.mean():.3f} ms (n = {len(b)}), "
      f"two-sided t-test p = {stats.ttest_ind(a, b).pvalue:.3g}")
trough-to-peak: light-responsive mean 0.696 ms (n = 664), nonresponsive mean 0.700 ms (n = 6747), two-sided t-test p = 0.134

Claim ed5-matched-controls: The SBD advantage in SPW-R, theta, familiar ratemap and novel ratemap correlations survives matching DBD pairs to SBD pairs in firing rate and in cluster isolation (L-ratio).

The L-ratio half cannot be run: the units table holds no isolation metric (data check). The rate-matched half is run here for the record; it does not decide the outcome. DBD pairs are drawn to the SBD pairs' joint distribution of the two cells' rates (h.subsample2d, subsample2D_local.m), to the SBD group size, 500 times. The rate used: SPW-R cofiring, the SPW-R firing rate (legend); novel ratemap correlations, the theta-related rate in that novel environment (legend; wake cycles of the theta section); theta cofiring and familiar ratemap correlations, the homecage firing rate (assumption: the theta-related rate is computed here only for the novel sessions).

In [48]:
rng5 = np.random.default_rng(seed("ed5-matched-controls"))
CI = CELLS.set_index(["session", "unit"])
def matched_fraction(df, col, va, vb, n_res=500):
    df = df.dropna(subset=[col])
    vals = np.c_[va(df), vb(df)]
    ok = np.all(np.isfinite(vals), 1); df, vals = df[ok], vals[ok]
    s_, d_ = df.sbd.values, ~df.sbd.values
    sv, dv, dc = vals[s_], vals[d_], df[col].values[d_]
    sc = df[col].values[s_]
    ps, meds = [], []
    for _ in range(n_res):
        k = h.subsample2d(sv, dv, len(sv), rng5)
        ps.append(stats.ranksums(sc, dc[k]).pvalue); meds.append(np.median(dc[k]))
    ps = np.array(ps)
    print(f"  {col}: SBD n {len(sc)} median {np.median(sc):.4f}; matched DBD median {np.median(meds):.4f}; fraction with p < 0.05 {np.mean(ps < 0.05):.3f}; "
          f"rate medians SBD {np.round(np.median(sv, 0), 3).tolist()} DBD {np.round(np.median(dv, 0), 3).tolist()}")
    return float(np.mean(ps < 0.05))
rr = lambda df, u: np.array([CI.rip_rate.get((s_, x_), np.nan) for s_, x_ in zip(df.session, df[u])])
hr = lambda df, u: np.array([CI.rate.get((s_, x_), np.nan) for s_, x_ in zip(df.session, df[u])])
f5 = {}
f5["spwr"] = matched_fraction(PAIRS, "rip_corr", lambda d: rr(d, "a"), lambda d: rr(d, "b"))
f5["theta"] = matched_fraction(TPH, "theta_corr", lambda d: hr(d, "a"), lambda d: hr(d, "b"))
f5["familiar"] = matched_fraction(MP, "r", lambda d: hr(d, "ua"), lambda d: hr(d, "ub"))
PYRMAP = {x["session"]: x["pyr"] for x in nv}
NR_ = TR[TR.wake_only & (TR.epoch > 0)].set_index(["session", "unit", "epoch"]).rate
NPn = NP[NP.epoch > 0].copy()
NPn["ua"] = [int(PYRMAP[s_][a_]) for s_, a_ in zip(NPn.session, NPn.a)]; NPn["ub"] = [int(PYRMAP[s_][b_]) for s_, b_ in zip(NPn.session, NPn.b)]
tr_ = lambda d, u: np.array([NR_.get((s_, x_, e_), np.nan) for s_, x_, e_ in zip(d.session, d[u], d.epoch)])
f5["novel"] = matched_fraction(NPn, "r", lambda d: tr_(d, "ua"), lambda d: tr_(d, "ub"))
print("rate-matched fractions:", {k: round(v, 3) for k, v in f5.items()}, "; paper: every resampling for SPW-R and theta, 499/500 familiar, 0.958 novel")
  rip_corr: SBD n 3738 median 0.0385; matched DBD median 0.0333; fraction with p < 0.05 1.000; rate medians SBD [8.23, 6.839] DBD [7.256, 4.242]
  theta_corr: SBD n 3727 median 0.0170; matched DBD median 0.0092; fraction with p < 0.05 1.000; rate medians SBD [1.714, 1.112] DBD [1.449, 0.88]
  r: SBD n 2609 median 0.0189; matched DBD median -0.0251; fraction with p < 0.05 0.998; rate medians SBD [1.77, 1.279] DBD [1.454, 0.883]
  r: SBD n 1390 median 0.0206; matched DBD median -0.0220; fraction with p < 0.05 0.498; rate medians SBD [1.559, 0.849] DBD [1.018, 0.64]
rate-matched fractions: {'spwr': 1.0, 'theta': 1.0, 'familiar': 0.998, 'novel': 0.498} ; paper: every resampling for SPW-R and theta, 499/500 familiar, 0.958 novel

Claim ed10-waveform-matched-controls: Same-shank SBD pairs have more similar waveforms than DBD pairs, but among same-shank pairs more than 60 micrometres apart, whose waveform distances do not differ, SBD pairs still cofire more in SPW-Rs and theta cycles and have higher familiar ratemap correlations.

The claim depends on ed2-waveform-validation, which is blocked, so it is blocked too. Its own parts need only the spontaneous mean waveforms and the electrode layout, which the files hold (waveform_mean over all channels; data check), so they are computed here for the record. Distance between two cells is that between their maximum-waveform channels; the waveform profile distance is the L2 norm of the difference of the mean waveforms concatenated over the shank's good channels (legend; the code's division by the number of channels as a variant). Waveform-matched resampling draws DBD pairs to the SBD waveform-distance distribution (100 bins of log10 distance, as h.subsample2d), at the size of the full same-shank SBD group, 500 times.

In [49]:
rng10 = np.random.default_rng(seed("ed10-waveform-matched-controls"))
SS = PAIRS[PAIRS.shank_a == PAIRS.shank_b].copy()
far = SS[SS.el_dist > 60]
for lab, df in (("same shank", SS), ("same shank, > 60 um", far)):
    for col in ("wf_dist", "wf_dist_code"):
        a_, b_ = df[df.sbd][col].dropna(), df[~df.sbd][col].dropna()
        print(f"{lab}, {col}: SBD median {a_.median():.4g} (n = {len(a_)}), DBD {b_.median():.4g} (n = {len(b_)}), rank-sum p = {stats.ranksums(a_, b_).pvalue:.3g}")
TPk = TPH.set_index(["session", "a", "b"]).theta_corr
far = far.assign(theta_corr=[TPk.get((s_, a_, b_), np.nan) for s_, a_, b_ in zip(far.session, far.a, far.b)])
SSt = SS.assign(theta_corr=[TPk.get((s_, a_, b_), np.nan) for s_, a_, b_ in zip(SS.session, SS.a, SS.b)])
WF = SS.set_index(["session", "a", "b"]).wf_dist
MPs = MP[MP.dshank == 0].copy()
MPs["wf_dist"] = [WF.get((s_, a_, b_), np.nan) for s_, a_, b_ in zip(MPs.session, MPs.ua, MPs.ub)]
farm = MPs[MPs.el_dist > 60]
exp10 = {"rip_corr": (0.037, 0.021), "theta_corr": (0.019, 0.0092), "r": (0.0079, -0.0308)}
for col, df in (("rip_corr", far), ("theta_corr", far), ("r", farm)):
    a_, b_ = df[df.sbd][col].dropna(), df[~df.sbd][col].dropna()
    e_ = exp10[col]
    print(f"> 60 um, {col}: SBD median {a_.median():.4f} (n = {len(a_)}) DBD {b_.median():.4f} (n = {len(b_)}), rank-sum p = {stats.ranksums(a_, b_).pvalue:.3g}; "
          f"within tolerance {abs(a_.median() - e_[0]) <= 0.1 * abs(e_[0])}, {abs(b_.median() - e_[1]) <= 0.1 * abs(e_[1])}")
def wf_matched(df, col, n_res=500):
    df = df.dropna(subset=[col, "wf_dist"]); s_ = df[df.sbd]; d_ = df[~df.sbd]
    ps = [stats.ranksums(s_[col], d_[col].values[h.subsample2d(s_.wf_dist.values, d_.wf_dist.values, len(s_), rng10)]).pvalue for _ in range(n_res)]
    return float(np.mean(np.array(ps) < 0.05))
print("waveform-matched fractions with p < 0.05, all same-shank pairs: SPW-R", wf_matched(SS, "rip_corr"), "; theta", wf_matched(SSt, "theta_corr"),
      "; familiar ratemap", wf_matched(MPs, "r"), "(paper: every homecage resampling, 0.894 ratemap)")
same shank, wf_dist: SBD median 0.0003218 (n = 1743), DBD 0.0004151 (n = 15996), rank-sum p = 2.94e-108
same shank, wf_dist_code: SBD median 1.315e-05 (n = 1743), DBD 1.558e-05 (n = 15996), rank-sum p = 5.24e-23
same shank, > 60 um, wf_dist: SBD median 0.0003621 (n = 347), DBD 0.0004334 (n = 3588), rank-sum p = 4.54e-17
same shank, > 60 um, wf_dist_code: SBD median 1.732e-05 (n = 347), DBD 1.66e-05 (n = 3588), rank-sum p = 0.617
> 60 um, rip_corr: SBD median 0.0364 (n = 346) DBD 0.0202 (n = 3574), rank-sum p = 9.85e-11; within tolerance True, True
> 60 um, theta_corr: SBD median 0.0199 (n = 345) DBD 0.0087 (n = 3586), rank-sum p = 2.74e-05; within tolerance True, True
> 60 um, r: SBD median 0.0143 (n = 252) DBD -0.0278 (n = 3007), rank-sum p = 0.0779; within tolerance False, True
waveform-matched fractions with p < 0.05, all same-shank pairs: SPW-R 1.0 ; theta 1.0 ; familiar ratemap 0.132 (paper: every homecage resampling, 0.894 ratemap)

Claim ed7-sbd-coactivation: Groups of more than two SBD neurons coactivate in SPW-Rs more than equal-sized control groups; hard-coded SBD assemblies are expressed above control in 62 of 65 sessions.

The claim depends on fig3e-assembly-expression, which is blocked, so it is blocked too, and its part (b) needs the assembly expression on the 1 ms matrix of that claim. Part (e) needs only which cells fire in each SPW-R, and is computed here for the record: per session with at least two light-responsive cells, the fraction of homecage SPW-Rs in which exactly k of them fire, z-scored against 1,000 groups of as many nonresponsive pyramidal cells drawn at random.

In [50]:
rng7 = np.random.default_rng(seed("ed7-sbd-coactivation"))
zr = []
for r in hc_res:
    info = r[2]; lrc, nrc = info["lr_cols"], info["nr_cols"]
    if len(lrc) < 2 or len(nrc) < len(lrc) or info["n_rip_rows"] == 0: continue
    act = np.unpackbits(info["active"], axis=0, count=info["n_rip_rows"]).astype(bool)
    g = len(lrc); kk = np.arange(1, g + 1)
    obs = np.bincount(act[:, lrc].sum(1), minlength=g + 1)[1:] / len(act)
    sel = np.zeros((len(nrc), 1000), np.float32)
    for j in range(1000): sel[rng7.choice(len(nrc), g, replace=False), j] = 1
    cnt = (act[:, nrc].astype(np.float32) @ sel).astype(int)   # coactive cells of each random group in each SPW-R
    null = np.stack([(cnt == k).mean(0) for k in kk], axis=1)
    z = (obs - null.mean(0)) / np.where(null.std(0) > 0, null.std(0), np.nan)
    for k, zz in zip(kk, z): zr.append({"session": info["session"], "n_lr": g, "k": k, "z": zz})
Z7 = pd.DataFrame(zr)
print("sessions with >= 2 light-responsive cells:", Z7.session.nunique(), "(paper 84); with >= 3:", Z7[Z7.n_lr >= 3].session.nunique(), "(paper 65)")
print("mean z by k (finite values):", Z7.groupby("k").z.apply(lambda v: round(v[np.isfinite(v)].mean(), 3)).head(8).to_dict())
zz = Z7[(Z7.k > 2) & np.isfinite(Z7.z)].z
print(f"mean z for k > 2: {zz.mean():.3f} over {len(zz)} session-k values; one-sample t p = {stats.ttest_1samp(zz, 0).pvalue:.3g}")
sessions with >= 2 light-responsive cells: 78 (paper 84); with >= 3: 65 (paper 65)
mean z by k (finite values): {1: -1.11, 2: -0.103, 3: 0.857, 4: 2.179, 5: 3.949, 6: 4.891, 7: 6.823, 8: 5.961}
mean z for k > 2: 8.728 over 431 session-k values; one-sample t p = 8.85e-12

The other blocked claims are not computed here: the histology of ed1-brdu-specificity and fig1c-radial-depth is not in the dataset; the assembly claims (fig3c, fig3e, ed6) and the model of fig4d were not run (see the attempt record).

The resampled fractions of ed5 and ed10 come from one generator per claim shared across their comparisons, so a change earlier in the sequence (here the theta pairs, after the theta channel was revised) moves the later ones: the novel ratemap fraction of ed5 was 0.604 in the previous run and is 0.498 here, and the ratemap fraction of ed10 0.106 and 0.132.

In [51]:
print(f"notebook runtime {(time.time() - T0)/60:.1f} min; peak memory of this process {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1e6:.2f} GB")
notebook runtime 48.8 min; peak memory of this process 1.45 GB

Summary¶

Claim Outcome
cohort-birthdates reproduced
st1-animal-sessions reproduced
sessions-durations not reproduced (two sessions without sleep; all else holds; asked of a reader)
spwr-duration reproduced
unit-count reproduced
ed2-light-responsive-count reproduced
ed2-waveform-validation blocked: data missing
ed1-brdu-specificity, fig1c-radial-depth blocked: data missing
fig1e-labelled-fraction reproduced
fig1f-rem-shift not reproduced (assumed theta channel)
fig1g-rate-by-birthdate reproduced
fig1h-burst-by-birthdate partially reproduced
ed3-depth-control not reproduced (fractions above the paper's; assumed depth reference)
fig2b-synchrony-per-animal reproduced
fig2c-theta-cofiring partially reproduced (assumed theta channel)
fig2d-theta-depth reproduced (assumed theta channel)
fig2f-ripple-firing-by-birthdate reproduced
fig2g-ripple-cofiring reproduced
ed5-matched-controls blocked: data missing (L-ratio)
fig3c, fig3e, ed6, fig4d blocked: too large (not run; see the attempt record)
ed7-sbd-coactivation blocked: too large (depends on fig3e; part e run for the record)
maze-cohort reproduced
maze-task not reproduced (trial counts)
novel-explorations reproduced
fig5b-spatial-info-by-birthdate partially reproduced
fig5c-sbd-ratemap-overlap partially reproduced
fig5d-overlap-by-distance partially reproduced
fig5e-pv-decorrelation partially reproduced
fig5f-remap-together reproduced
fig6c-theta-rate-preserved reproduced (assumed theta channel)
fig6d-rate-lower-novel reproduced (assumed theta channel)
fig6d-info-lower-novel partially reproduced
fig6c-novel-ratemap-corr-higher not reproduced (assumed open-field scale)
fig6e-sbd-novel-overlap partially reproduced
fig6f-remap-together-novel reproduced (assumed open-field scale)
fig7b-sbd-convergence partially reproduced (assumed detector)
fig7ce-convergence-by-birthdate partially reproduced (assumed detector)
fig7d-transmission-gamma not reproduced (assumed detector)
fig7fg-convergence-cofiring not reproduced (assumed detector)
ed10-waveform-matched-controls blocked: data missing (depends on ed2-waveform-validation)

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. The theta channel follows the Methods' rule (a channel with a positive sharp wave, measured against a pre-ripple baseline, above the centre of the pyramidal layer) in 72 of 104 sessions; in the other 32 no shank has a channel above its centre with a positive sharp wave, and the channel next to the centre with larger rel_y is used. Six sessions with 20 or fewer ripples in homecage non-REM sleep take the sharp wave over all their ripples. Every theta claim is also shown on the sessions whose channel follows the rule, and every one but fig7fg-convergence-cofiring on the layer centre channel. The monosynaptic detector follows the Methods' description with assumed lags, kernel, Bonferroni count and minimums, and finds 38,402 to 50,756 connections under its variants, 20% to 59% more than the paper's 31,932. Open fields are binned assuming one lab unit is 1 cm, with 2, 0.5 and 0.85 cm per unit as variants. Depth for the depth control is taken from the sharp-wave reversal of each shank face, and from the ripple-power centre where no reversal is found. Rate maps use a constant-velocity Kalman filter whose settings the paper does not give. The bootstrap post hoc test is replaced by Tukey's test on the six distance and birthdate groups.

What was found about the dataset. The files give the paper's counts of mice, sessions, units, cell types and light-responsive cells exactly, and the paper's per-session labelled fractions. Two sessions of e13_1f1 hold wake only in their sleep states. In e16_3m2_211211 the position series named for the linear_manu subsession lies inside the openField_thomas subsession. Open-field positions have no spatial scale, and the lab-unit positions of the other novel environments use different scales (0 to 1 in five series, 0.85 to 0.93 cm per unit in three, from their simultaneous linearized positions). The units table has no L-ratio. Mice e13_1f1 and e13_1m1, which the paper says had a single light-responsive cell per session, have 1 and 2 same-birthdate pairs in the files. 27 of 57 familiar-maze sessions hold fewer than ten trials of one type, in the trials table itself.