Reproducing Russo, Claar, Furregoni et al. (2025) from dandiset 000458¶

Paper. Russo S, Claar LD, Furregoni G, Marks LC, Krishnan G, Zauli FM, et al., Koch C, Rembado I (2025). Thalamic feedback shapes brain responses evoked by cortical stimulation in mice and humans. Nature Communications 16:3627. doi:10.1038/s41467-025-58717-2. The claims file (claims/russo-2025.yaml) was written from the version of record in PubMed Central, with the supplement and the Source Data file.

Dandiset. DANDI:000458, version 0.230317.0039 (Claar et al. 2023, "Simultaneous electroencephalography, extracellular electrophysiology, and cortical electrical stimulation in head-fixed mice"). This is the version the paper's Data availability statement cites, and the only published version. The draft has the same 24 assets and size and lists 10 active uploads; it was not used.

What the dandiset holds. 24 sessions from 23 mice, each with 30-channel EEG, the LFP of up to three Neuropixels probes, sorted units, wheel speed and a trial table, in an awake, an isoflurane and sometimes a recovery epoch. Ten sessions (ten mice) have deep MOs stimulation while awake, nine of them with probes; these are the mouse data used here. The paper reports 26 EEG sessions from 15 mice and units from 21 mice, so the dandiset holds part of them. No session has stimulation of the posterior control areas of Figure S6.

Outside inputs. The human claims are tested on the paper's Source Data file (41467_2025_58717_MOESM4_ESM.xlsx from the publisher's site, checked by SHA-256), which is also the reference for the link claim. The optogenetic claims are in the second notebook, opto_russo_2025.ipynb, on the paper's figshare deposit (doi:10.6084/m9.figshare.28440311.v1).

Running. The helper russo.py streams the needed chunks of each file from the archive in parallel; the notebook takes about 15 minutes, nearly all of it reading the EEG and the MOs LFP of the ten sessions. The model section fetches and builds the paper's network model, which needs make and g++.

Claim Tested here Outcome
source-data-link yes partially reproduced
fig1a-tms-late-rest-active Source Data reproduced
fig1b-ieeg-late-rest-active Source Data reproduced
figs2-tms-controls Source Data reproduced
figs2a-tms-early-component Source Data reproduced
figs3b-ieeg-early-no-modulation Source Data reproduced
fig5a-human-mouse-similar no blocked, data missing
fig1c-eeg-late-rest-larger yes reproduced
fig1d-lfp-late-rest-larger yes reproduced
fig1e-csd-late-rest-larger yes reproduced
figs1b-mouse-plf yes reproduced
figs4-intensity-dependence yes reproduced
speed-threshold-robust yes not reproduced
figs5-early-component-mouse yes reproduced
figs6-posterior-no-modulation no blocked, data missing
triphasic-pattern yes partially reproduced
fig2b-thalamus-leads yes not reproduced
figs7a-active-shorter-latency yes reproduced
figs7b-latency-correlation yes reproduced
fig3a-thalamic-rate-higher-active yes reproduced
figs9-mos-rate-no-modulation yes not reproduced
figs10a-fs-trn-no-modulation yes reproduced (fragile)
fig3b-bimodal-isi yes not reproduced
figs11d-hf-earlier-less-variable yes not reproduced
figs12-intensity-shifts-to-hf yes reproduced
fig3e-baseline-rate-doubles yes reproduced
fig3e-lf-synchrony-reduced yes not reproduced
fig3e-hf-frequency-reduced yes reproduced
figs13-thalamic-features-predict-eeg yes not reproduced
figs13d-lf-crosscorrelation yes not reproduced
discussion-orthodromic-initial-excitation yes reproduced
fig2fg, figs8b, fig2h (optogenetics) second notebook see there
fig4e, fig4f, fig4hi, figs14a, figs14b (model) build and timing only blocked, not runnable (too slow for the time limit)
In [1]:
import hashlib
import io
import time
import warnings
import zlib

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
import statsmodels.formula.api as smf
from scipy import stats
from sklearn.cluster import KMeans
from statsmodels.stats.anova import anova_lm
from statsmodels.stats.multicomp import pairwise_tukeyhsd
from statsmodels.stats.multitest import multipletests

import diptest
import russo

warnings.filterwarnings("ignore")
pd.set_option("display.width", 220)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)


def claim_seed(claim):
    """Seed of a claim's generator (docs/protocol.md, Author, step 3)."""
    return zlib.crc32(f"russo-2025/{claim}".encode())


started = time.time()
index = russo.session_index()
deep = index[(index.region == "MOs") & (index.depth == "deep")]
S = {p: russo.process_session(p) for p in deep.path}
print(f"dandiset {russo.DANDISET_ID} version {russo.DANDISET_VERSION}: {index.path.nunique()} files; "
      f"{len(S)} sessions with deep MOs stimulation loaded in {time.time() - started:.0f} s")
dandiset 000458 version 0.230317.0039: 24 files; 10 sessions with deep MOs stimulation loaded in 754 s

Data check¶

Each check of the metadata against the values is stated under its output.

In [2]:
print("Awake electrical stimulation blocks in every file (target region and depth, currents in uA):")
print(index.to_string(index=False))
print("\nTarget regions in the trial tables:", sorted(index.region.unique()), "; depths:", sorted(index.depth.unique()))
print("Subjects in the dandiset:", index.subject.nunique(), "; files:", index.path.nunique())
print("Sessions with deep MOs stimulation:", len(deep), "from", deep.subject.nunique(), "mice;",
      "with Neuropixels probes:", int((deep.n_units > 0).sum()))
Awake electrical stimulation blocks in every file (target region and depth, currents in uA):
                                                   path subject region       depth            currents  n_trials  n_valid                            probes  n_units
sub-521885/sub-521885_ses-20200709_behavior+ecephys.nwb  521885    MOs superficial [20.0, 50.0, 100.0]       180      180                                []        0
sub-521886/sub-521886_ses-20200716_behavior+ecephys.nwb  521886    MOs superficial [20.0, 50.0, 100.0]       300      298                                []        0
sub-521887/sub-521887_ses-20200730_behavior+ecephys.nwb  521887    MOs superficial              [20.0]       200      199                                []        0
sub-543393/sub-543393_ses-20200820_behavior+ecephys.nwb  543393    MOs superficial              [70.0]       300      300                                []        0
sub-543394/sub-543394_ses-20200827_behavior+ecephys.nwb  543394    MOs superficial              [50.0]       300      300                                []        0
sub-546655/sub-546655_ses-20201023_behavior+ecephys.nwb  546655    MOs        deep  [50.0, 70.0, 90.0]       360      359            [LFPprobeB, LFPprobeC]      265
sub-551397/sub-551397_ses-20210211_behavior+ecephys.nwb  551397    MOs        deep  [10.0, 30.0, 50.0]       360      360            [LFPprobeB, LFPprobeF]      607
sub-551399/sub-551399_ses-20210128_behavior+ecephys.nwb  551399    MOs        deep  [40.0, 60.0, 80.0]       360      358            [LFPprobeB, LFPprobeF]      593
sub-569062/sub-569062_ses-20210218_behavior+ecephys.nwb  569062    MOs        deep  [15.0, 35.0, 60.0]       360      360 [LFPprobeB, LFPprobeD, LFPprobeF]      902
sub-569064/sub-569064_ses-20210408_behavior+ecephys.nwb  569064    MOs        deep  [15.0, 40.0, 60.0]       360      360 [LFPprobeB, LFPprobeC, LFPprobeF]      481
sub-569068/sub-569068_ses-20210304_behavior+ecephys.nwb  569068    MOs        deep  [10.0, 20.0, 40.0]       360      359 [LFPprobeB, LFPprobeD, LFPprobeF]      338
sub-569069/sub-569069_ses-20210312_behavior+ecephys.nwb  569069    MOs        deep  [20.0, 40.0, 70.0]       360      357 [LFPprobeB, LFPprobeC, LFPprobeF]      520
sub-569070/sub-569070_ses-20210401_behavior+ecephys.nwb  569070    MOs        deep  [20.0, 40.0, 60.0]       360      333                                []        0
sub-569072/sub-569072_ses-20210422_behavior+ecephys.nwb  569072    SSp        deep  [30.0, 50.0, 70.0]       360      359 [LFPprobeB, LFPprobeC, LFPprobeF]      995
sub-569073/sub-569073_ses-20210415_behavior+ecephys.nwb  569073    MOs        deep  [20.0, 40.0, 70.0]       360      336 [LFPprobeB, LFPprobeC, LFPprobeF]      631
sub-569073/sub-569073_ses-20210416_behavior+ecephys.nwb  569073    SSp        deep [60.0, 80.0, 100.0]       360      355 [LFPprobeB, LFPprobeC, LFPprobeF]      705
sub-571619/sub-571619_ses-20210319_behavior+ecephys.nwb  571619    MOs        deep  [20.0, 40.0, 60.0]       360      357 [LFPprobeB, LFPprobeC, LFPprobeF]      859
sub-571619/sub-571619_ses-20210319_behavior+ecephys.nwb  571619    MOs superficial  [20.0, 40.0, 60.0]       360      337 [LFPprobeB, LFPprobeC, LFPprobeF]      859
sub-571620/sub-571620_ses-20210513_behavior+ecephys.nwb  571620    SSp        deep [60.0, 80.0, 100.0]       360      360 [LFPprobeB, LFPprobeC, LFPprobeF]      771
sub-571620/sub-571620_ses-20210513_behavior+ecephys.nwb  571620    SSp superficial [60.0, 80.0, 100.0]       360      360 [LFPprobeB, LFPprobeC, LFPprobeF]      771
sub-575102/sub-575102_ses-20210603_behavior+ecephys.nwb  575102    MOs superficial  [50.0, 70.0, 90.0]       360      360 [LFPprobeB, LFPprobeC, LFPprobeF]      528
sub-586466/sub-586466_ses-20210729_behavior+ecephys.nwb  586466    SSp        deep  [20.0, 40.0, 60.0]       360      360            [LFPprobeB, LFPprobeF]      470
sub-586466/sub-586466_ses-20210729_behavior+ecephys.nwb  586466    SSp superficial  [20.0, 40.0, 60.0]       360      357            [LFPprobeB, LFPprobeF]      470
sub-586468/sub-586468_ses-20210819_behavior+ecephys.nwb  586468    SSp        deep  [25.0, 35.0, 45.0]       360      360 [LFPprobeB, LFPprobeC, LFPprobeF]      977
sub-586468/sub-586468_ses-20210819_behavior+ecephys.nwb  586468    SSp superficial  [25.0, 35.0, 45.0]       360        0 [LFPprobeB, LFPprobeC, LFPprobeF]      977
sub-590479/sub-590479_ses-20210921_behavior+ecephys.nwb  590479    SSp        deep  [40.0, 60.0, 80.0]       360      360            [LFPprobeB, LFPprobeF]      616
sub-590479/sub-590479_ses-20210921_behavior+ecephys.nwb  590479    SSp superficial  [40.0, 60.0, 80.0]       360      359            [LFPprobeB, LFPprobeF]      616
sub-590480/sub-590480_ses-20211111_behavior+ecephys.nwb  590480    SSp        deep  [30.0, 50.0, 70.0]       360      357 [LFPprobeB, LFPprobeC, LFPprobeF]      948
sub-590480/sub-590480_ses-20211111_behavior+ecephys.nwb  590480    SSp superficial  [30.0, 50.0, 70.0]       360      360 [LFPprobeB, LFPprobeC, LFPprobeF]      948
sub-599017/sub-599017_ses-20220210_behavior+ecephys.nwb  599017    SSp        deep  [30.0, 50.0, 70.0]       360      359 [LFPprobeB, LFPprobeC, LFPprobeF]      943
sub-599017/sub-599017_ses-20220210_behavior+ecephys.nwb  599017    SSp superficial  [30.0, 50.0, 70.0]       360      359 [LFPprobeB, LFPprobeC, LFPprobeF]      943

Target regions in the trial tables: ['MOs', 'SSp'] ; depths: ['deep', 'superficial']
Subjects in the dandiset: 23 ; files: 24
Sessions with deep MOs stimulation: 10 from 10 mice; with Neuropixels probes: 9

The trial tables hold electrical stimulation of MOs (deep and superficial) and of SSp (deep and superficial). No file has a stimulation target in visual or retrosplenial cortex or hippocampus, the control sessions of Figure S6. The paper's mouse results use deep MOs stimulation (Results: "targeting the deep layers of MOs (layer 5/6...)"); ten sessions from ten mice have it, nine of them with Neuropixels probes and units. The paper reports 26 EEG sessions from 15 mice (Figure 1C) and units from 21 mice (Figure S7B), so the dandiset holds part of its mouse data.

In [3]:
rows = []
for p, r in S.items():
    t = r["trials"]
    cur = t.groupby("intensity").current.first()
    rows.append({"subject": r["subject"], "trials": len(t), "valid": int(t.is_valid.sum()),
                 "low_uA": cur.get("low"), "medium_uA": cur.get("medium"), "high_uA": cur.get("high"),
                 "rest_0.1": int((~t.active).sum()), "active_0.1": int(t.active.sum()),
                 "speed_min": round(t.speed.min(), 3), "speed_max": round(t.speed.max(), 1),
                 "file_is_running": int(t.is_running.sum()), "speed>0": int((t.speed > 0).sum()),
                 "agree_is_running_vs_speed>0": round(float((t.is_running == (t.speed > 0)).mean()), 3),
                 "eeg_valid_channels": r["n_eeg_valid"], "MOs_LFP_channels": r.get("n_mos_channels"),
                 "eeg_artifact_lag_ms": r["eeg_artifact_lag_ms"], "lfp_artifact_lag_ms": r.get("lfp_artifact_lag_ms"),
                 "eeg_onset_err_ms": round(r["eeg_onset_err_ms"], 3), "lfp_onset_err_ms": r.get("lfp_onset_err_ms")})
sessions = pd.DataFrame(rows)
print(sessions.to_string(index=False))
for k in ["low_uA", "medium_uA", "high_uA"]:
    print(f"{k}: mean {sessions[k].mean():.2f} +- {sessions[k].std():.2f} (paper: high 66.15 +- 12.11, "
          "intermediate 47.35 +- 13.30, low 30.59 +- 15.80)")
ranges = np.array([r["eeg_range_uv"] for r in S.values()])
print(f"EEG after preprocessing, -1 to +0.5 s epochs: {ranges[:, 0].min():.0f} to {ranges[:, 1].max():.0f} uV")
subject  trials  valid  low_uA  medium_uA  high_uA  rest_0.1  active_0.1  speed_min  speed_max  file_is_running  speed>0  agree_is_running_vs_speed>0  eeg_valid_channels  MOs_LFP_channels  eeg_artifact_lag_ms  lfp_artifact_lag_ms  eeg_onset_err_ms  lfp_onset_err_ms
 546655     360    359    50.0       70.0     90.0       119         241        0.0       63.9              242      242                          1.0                  22             128.0                 -0.2                  0.2             0.400          0.398555
 551397     360    360    10.0       30.0     50.0       279          81        0.0       19.4               83       83                          1.0                  27             112.0                 -0.2                  0.6             0.397          0.399138
 551399     360    358    40.0       60.0     80.0       326          34        0.0       13.1               35       35                          1.0                  22              86.0                 -0.2                  0.6             0.398          0.398099
 569062     360    360    15.0       35.0     60.0       289          71        0.0       13.1               74       74                          1.0                  28             130.0                 -0.2                  0.6             0.397          0.399961
 569064     360    360    15.0       40.0     60.0       351           9        0.0       15.3               10       10                          1.0                  30             124.0                 -0.2                  0.6             0.399          0.397888
 569068     360    359    10.0       20.0     40.0       300          60        0.0       12.9               64       64                          1.0                  30             120.0                 -0.2                  0.6             0.399          0.397306
 569069     360    357    20.0       40.0     70.0       244         116        0.0       24.6              119      119                          1.0                  22              92.0                 -0.2                  0.6             0.400          0.398226
 569070     360    333    20.0       40.0     60.0       276          84        0.0       17.0               85       85                          1.0                  26               NaN                 -0.2                  NaN             0.397               NaN
 569073     360    336    20.0       40.0     70.0       284          76        0.0       24.8               77       77                          1.0                  27              90.0                 -0.2                  0.2             0.400          0.397438
 571619     360    357    20.0       40.0     60.0       313          47        0.0       26.3               53       53                          1.0                  24             120.0                 -0.2                  0.6             0.399          0.397982
low_uA: mean 22.00 +- 12.95 (paper: high 66.15 +- 12.11, intermediate 47.35 +- 13.30, low 30.59 +- 15.80)
medium_uA: mean 41.50 +- 14.15 (paper: high 66.15 +- 12.11, intermediate 47.35 +- 13.30, low 30.59 +- 15.80)
high_uA: mean 64.00 +- 14.30 (paper: high 66.15 +- 12.11, intermediate 47.35 +- 13.30, low 30.59 +- 15.80)
EEG after preprocessing, -1 to +0.5 s epochs: -6565 to 6347 uV

Every session has 120 trials at each of three currents, as the Methods state (up to 120 pulses per intensity). The currents of this subset (printed above) are close to the paper's means. Wheel speed is in cm/s and ranges from 0 to tens of cm/s. The file's is_running is defined as a mean speed above 0 cm/s; the agreement column shows it matches the mean speed from -0.5 to +0.5 s computed here from the running_speed series, which is consistent with the trial times and the speed sharing a clock (both come from the same pipeline, so this does not prove it). The paper's threshold is 0.1 cm/s, used below.

Clock of the signals: the onset of each trial falls within one sample (0.4 ms) of an EEG and LFP timestamp, and the stimulation artifact in the raw trial-averaged EEG and LFP sits within one sample of the onset in every session (columns *_artifact_lag_ms), so the EEG, the LFP and the trial table share a clock.

In [4]:
units = pd.concat([r["units"].assign(subject=r["subject"]) for r in S.values() if r.get("has_probes")], ignore_index=True)
print("waveform_duration over all units: min %.3f, median %.3f, max %.3f (the file says seconds)" %
      (units.waveform_duration.min(), units.waveform_duration.median(), units.waveform_duration.max()))
print("\nUnits by class and mouse (MOs RS > 0.4 ms, FS <= 0.4; SM-TH relay > 0.45, TRN < 0.35):")
print(pd.crosstab(units.subject, units.cls).to_string())
print("\nSM-TH nuclei of the units:", units[units.area == "SM-TH"].location.value_counts().to_dict())
print("Thalamic reticular nucleus (RT) units by location:", int((units.location == "RT").sum()))

U = pd.concat([russo.unit_trial_table(r) for r in S.values() if r.get("has_probes")], ignore_index=True)
U["active"] = U.speed > russo.SPEED_THRESHOLD
U = U[U.is_valid]
H = U[(U.intensity == "high") & U.responsive]
resp = H.groupby(["subject", "cls"]).unit.nunique().unstack(fill_value=0)
print("\nResponsive units at high intensity (7 SD rule), by mouse:")
print(resp.to_string())
print("Totals:", resp.sum().to_dict(), "(paper: 1269 relay units from 21 mice, 67 TRN, 145 FS)")

# Spike clock: population response of responsive MOs RS units in 2-10 ms against the same window
# of onsets shifted by +1.7 s (between pulses, 3.5-4.5 s apart).
rows = []
for r in S.values():
    if not r.get("has_probes"):
        continue
    t = r["trials"]
    hi = (t.intensity == "high").to_numpy()
    on, sh = [], []
    for i, (rel, trial) in r["spikes"].items():
        if r["units"].loc[i, "cls"] not in ("RS", "relay"):
            continue
        sel = hi[trial]
        on.append(((rel[sel] >= 0.002) & (rel[sel] < 0.010)).sum() / hi.sum() / 0.008)
        sh.append(((rel[sel] >= -0.3) & (rel[sel] < -0.292)).sum() / hi.sum() / 0.008)
    rows.append({"subject": r["subject"], "units": len(on), "rate_2_10ms": np.mean(on), "rate_-300_-292ms": np.mean(sh)})
print("\nMean rate of RS and relay units in 2-10 ms after the pulse and in an 8 ms window 300 ms before it (Hz):")
print(pd.DataFrame(rows).round(2).to_string(index=False))
waveform_duration over all units: min 0.110, median 0.577, max 2.074 (the file says seconds)

Units by class and mouse (MOs RS > 0.4 ms, FS <= 0.4; SM-TH relay > 0.45, TRN < 0.35):
cls      FS   RS  TRN  TRN-RT  other  relay
subject                                    
546655    0   18    0      23    224      0
551397    5   84    7       0    429     82
551399   10   89   15       0    427     52
569062   12  120    5       0    634    131
569064    5   24    0       0    452      0
569068   13   49    5       0    255     16
569069    3   29    0       0    433     55
569073    1   28    4       0    516     82
571619    8   95    3       0    716     37

SM-TH nuclei of the units: {'VAL': 179, 'PO': 145, 'VPL': 125, 'VPM': 117, 'CL': 56}
Thalamic reticular nucleus (RT) units by location: 30
Responsive units at high intensity (7 SD rule), by mouse:
cls      FS  RS  TRN  TRN-RT  relay
subject                            
546655    0  12    0       1      0
551397    4  61    5       0     65
551399    8  63    3       0      1
569062   10  55    1       0    118
569064    5  19    0       0      0
569068    5  34    3       0     13
569069    3  15    0       0     42
569073    1  21    4       0     45
571619    7  70    2       0     19
Totals: {'FS': 43, 'RS': 350, 'TRN': 18, 'TRN-RT': 1, 'relay': 303} (paper: 1269 relay units from 21 mice, 67 TRN, 145 FS)

Mean rate of RS and relay units in 2-10 ms after the pulse and in an 8 ms window 300 ms before it (Hz):
subject  units  rate_2_10ms  rate_-300_-292ms
 546655     18        22.92              2.60
 551397    166        41.06              5.74
 551399    141        23.46              6.91
 569062    251        30.92              4.76
 569064     24        30.25              2.13
 569068     65        32.45              4.63
 569069     84        18.22              6.44
 569073    110        31.78              6.96
 571619    132        21.29              3.05

waveform_duration is described in the files as seconds; its values (0.110 to 2.074, cell above) are milliseconds, and are read as such. The spiking rate in the 2 to 10 ms after the pulse is far above the rate in a window of equal length before it in every mouse, so the units and the trial times share a clock. Unit analyses use the trials the file marks valid (is_valid); the paper removed bad trials using a lab spreadsheet that is not public.

In [5]:
def state_table(sig, intens=("high",), thr=0.1, chan="all", win="late", meas="amp"):
    """One row per session and intensity: the measure at rest and during running."""
    rows = []
    for r in S.values():
        if sig not in r:
            continue
        d = r[sig]
        d = d[(d.threshold == thr) & (d.chan == chan) & (d.window == win) & d.intensity.isin(intens)]
        for i, g in d.groupby("intensity"):
            g = g.set_index("state")
            rows.append({"subject": r["subject"], "intensity": i, "rest": g.loc["rest", meas],
                         "active": g.loc["active", meas], "n_rest": int(g.loc["rest", "n"]),
                         "n_active": int(g.loc["active", "n"])})
    return pd.DataFrame(rows)


def signed_rank(t, label, by_mouse=False):
    t = t.dropna(subset=["rest", "active"])
    if by_mouse:
        t = t.groupby("subject")[["rest", "active"]].mean().reset_index()
    w = stats.wilcoxon(t.rest, t.active) if len(t) > 1 else None
    return {"reading": label, "n": len(t), "rest_median": t.rest.median(), "active_median": t.active.median(),
            "rest_larger": int((t.rest > t.active).sum()), "p": (w.pvalue if w else np.nan),
            "effect_median_diff": (t.rest - t.active).median()}


READINGS = {"(a)(i) high, all channels and trials": (("high",), "all"),
            "(a)(ii) high, valid channels and trials": (("high",), "valid"),
            "(b)(i) high and medium, all": (("high", "medium"), "all"),
            "(b)(ii) high and medium, valid": (("high", "medium"), "valid")}


def readings_table(sig, meas="amp", win="late", thr=0.1, by_mouse_b=False):
    out = []
    for label, (intens, chan) in READINGS.items():
        t = state_table(sig, intens, thr, chan, win, meas)
        out.append(signed_rank(t, label))
        if by_mouse_b and len(intens) == 2:
            out.append(signed_rank(t, label + ", mean per mouse", by_mouse=True))
    return pd.DataFrame(out)

fig1c-eeg-late-rest-larger¶

In mice, the late (150 to 250 ms) EEG response to deep MOs electrical stimulation has a larger rectified amplitude at rest than during running.

Rectified amplitude: the absolute value of the trial-averaged EP from 150 to 250 ms, averaged over time and EEG channels; two-tailed Wilcoxon signed-rank test pairing rest and active per session (criterion). Readings as the criterion lists them: (a) high intensity only, (b) high and medium as separate sessions; (i) all channels and trials, (ii) the channels (is_data_valid) and trials (is_valid) the file flags as good. The code's measure (mean absolute single-trial signal after baseline z-scoring) is a variant.

In [6]:
res_1c = readings_table("eeg")
print(res_1c.round(6).to_string(index=False))
var = pd.DataFrame([signed_rank(state_table("eeg", intens, chan=chan, meas="code_amp"), "code measure " + lab)
                    for lab, (intens, chan) in READINGS.items()])
print("\nVariant, the code's measure (z units):")
print(var.round(6).to_string(index=False))
t1c = state_table("eeg")
print("\nPer session, reading (a)(i), uV:")
print(t1c.round(2).to_string(index=False))
print("Range of plotted amplitudes: %.1f to %.1f uV" % (t1c[["rest", "active"]].min().min(), t1c[["rest", "active"]].max().max()))
                                reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   (a)(i) high, all channels and trials 10    81.695827      42.553001           10 0.001953           39.129735
(a)(ii) high, valid channels and trials 10    84.480480      36.270048           10 0.001953           37.452538
            (b)(i) high and medium, all 20    69.189606      29.165662           19 0.000004           35.666316
         (b)(ii) high and medium, valid 20    65.382755      27.263404           19 0.000004           37.452538

Variant, the code's measure (z units):
                                             reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   code measure (a)(i) high, all channels and trials 10     1.764440       1.326715            9 0.003906            0.627757
code measure (a)(ii) high, valid channels and trials 10     1.769213       1.317289            9 0.003906            0.613956
            code measure (b)(i) high and medium, all 20     1.660007       0.984781           19 0.000004            0.624250
         code measure (b)(ii) high and medium, valid 20     1.687574       1.017803           19 0.000004            0.614158

Per session, reading (a)(i), uV:
subject intensity   rest  active  n_rest  n_active
 546655      high  73.16   28.85      38        82
 551397      high  90.23   40.17      96        24
 551399      high  69.02   44.93     106        14
 569062      high  97.67   61.36      92        28
 569064      high 100.34   74.52     117         3
 569068      high 169.30   71.97     101        19
 569069      high 130.40   71.23      81        39
 569070      high  68.74   26.78      92        28
 569073      high  56.31   34.75     101        19
 571619      high  59.35   39.87     105        15
Range of plotted amplitudes: 26.8 to 169.3 uV
In [7]:
tt = russo.times()
tw = tt[(tt >= -0.1) & (tt < 0.4)]
fig, ax = plt.subplots(1, 2, figsize=(10, 3.2))
for st, col in [("rest", "k"), ("active", "r")]:
    tr = np.mean([r["eeg_trace"][("high", st)] for r in S.values()], 0)
    ax[0].plot(tw * 1e3, tr, col, label=st)
ax[0].axvspan(150, 250, color="0.9")
ax[0].set_xlabel("ms from pulse"); ax[0].set_ylabel("|mean EP|, mean over channels (uV)"); ax[0].legend()
ax[1].plot([0, 1], t1c[["rest", "active"]].T.values, "o-", color="0.5")
ax[1].set_xticks([0, 1], ["rest", "active"]); ax[1].set_ylabel("late rectified amplitude (uV)")
plt.tight_layout(); plt.show()
traces = np.array([[r["eeg_trace"][("high", st)] for r in S.values()] for st in ["rest", "active"]]).mean(1)
print("Left panel range: %.1f to %.1f uV over -100 to 400 ms" % (traces.min(), traces.max()))
No description has been provided for this image
Left panel range: 5.0 to 211.9 uV over -100 to 400 ms

**Result: reproduced. The late EEG rectified amplitude is larger at rest than during running in all 10 sessions at high intensity (median 81.7 against 42.6 uV, two-tailed signed-rank p = 0.00195), and the test gives p < 0.05 with rest larger under all four readings (p = 0.00195 for both channel and trial selections at high intensity, p = 4e-06 with high and medium as 20 sessions). The code's z-scored single-trial measure agrees (p = 0.0039 and 4e-06). Ten sessions from ten mice are used, where the paper reports 26 sessions from 15 mice.

fig1d-lfp-late-rest-larger¶

In mice, the late (150 to 250 ms) MOs LFP response to MOs stimulation has a larger rectified amplitude at rest than during running.

LFP of the Neuropixels channels the file places in MOs, detrended -2 to +2 s epochs, 0 to 3 ms artifact mirrored, z-scored per channel and trial to -1 to -0.01 s; rectified amplitude of the trial average over 150 to 250 ms and MOs channels (criterion). Each mouse has one session, so for reading (a) sessions are mice; for reading (b) the test is shown across the 18 session and intensity values and with the two intensities averaged per mouse.

In [8]:
res_1d = readings_table("lfp", by_mouse_b=True)
print(res_1d.round(6).to_string(index=False))
t1d = state_table("lfp")
print("\nPer mouse, reading (a)(i), z units:")
print(t1d.round(3).to_string(index=False))
                                       reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
          (a)(i) high, all channels and trials  9     1.977962       1.544234            7 0.019531            0.616410
       (a)(ii) high, valid channels and trials  9     2.001489       1.220359            7 0.027344            0.888249
                   (b)(i) high and medium, all 18     1.807378       0.747418           16 0.000038            1.017664
   (b)(i) high and medium, all, mean per mouse  9     1.815484       0.999212            9 0.003906            0.889475
                (b)(ii) high and medium, valid 18     1.828172       0.754410           16 0.000053            1.062594
(b)(ii) high and medium, valid, mean per mouse  9     1.831743       0.820562            9 0.003906            0.983523

Per mouse, reading (a)(i), z units:
subject intensity  rest  active  n_rest  n_active
 546655      high 0.794   0.618      38        82
 551397      high 1.714   0.834      96        24
 551399      high 1.978   0.743     106        14
 569062      high 2.890   1.161      92        28
 569064      high 1.846   1.866     117         3
 569068      high 2.359   2.532     101        19
 569069      high 3.519   2.302      81        39
 569073      high 2.360   1.743     101        19
 571619      high 1.830   1.544     105        15

Result: reproduced. The late MOs LFP rectified amplitude (z units) is larger at rest in 7 of 9 mice at high intensity (median 1.98 against 1.54, p = 0.0195; with the valid channels and trials p = 0.027), and in 16 of 18 session and intensity values with high and medium (p = 3.8e-05; 9 of 9 mice when the two are averaged, p = 0.0039).

fig1e-csd-late-rest-larger¶

In mice, the late MOs CSD response to MOs stimulation is larger at rest than during running, with a current sink between layers 2/3 and 5 at the time of the late response for high and medium but not low intensity.

CSD as in the Methods (helper docstring), z-scored like the LFP, over the MOs depth range. The sink is described from the depth profile and does not decide the claim.

In [9]:
res_1e = readings_table("csd", by_mouse_b=True)
print(res_1e.round(6).to_string(index=False))
t1e = state_table("csd")
print("\nPer mouse, reading (a)(i), z units:")
print(t1e.round(3).to_string(index=False))
# Depth profile at the late response: mean CSD (z) over 150-250 ms, by depth third of the MOs span, rest
tw = tt[(tt >= -0.1) & (tt < 0.4)]
lw = (tw >= 0.15) & (tw < 0.25)
rows = []
for r in S.values():
    if "csd_depth_profile" not in r:
        continue
    for inten in ["low", "medium", "high"]:
        prof = r["csd_depth_profile"][(inten, "rest")][:, lw].mean(1)
        thirds = np.array_split(prof[::-1], 3)  # from the surface (largest vertical position) down
        rows.append({"subject": r["subject"], "intensity": inten, **{f"third_{k + 1}": float(th.mean()) for k, th in enumerate(thirds)}})
prof = pd.DataFrame(rows)
print("\nMean late CSD at rest by third of the MOs depth range (1 = most superficial), median over mice:")
print(prof.groupby("intensity")[["third_1", "third_2", "third_3"]].median().round(3).to_string())
                                       reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
          (a)(i) high, all channels and trials  9     1.255964       0.764554            7 0.019531            0.411453
       (a)(ii) high, valid channels and trials  9     1.255964       0.764554            7 0.019531            0.409520
                   (b)(i) high and medium, all 18     1.019691       0.549668           15 0.000107            0.476331
   (b)(i) high and medium, all, mean per mouse  9     1.060105       0.599423            8 0.011719            0.460682
                (b)(ii) high and medium, valid 18     1.019691       0.549668           15 0.000107            0.475824
(b)(ii) high and medium, valid, mean per mouse  9     1.076125       0.595536            8 0.011719            0.480589

Per mouse, reading (a)(i), z units:
subject intensity  rest  active  n_rest  n_active
 546655      high 0.864   0.452      38        82
 551397      high 1.281   0.580      96        24
 551399      high 1.445   0.790     106        14
 569062      high 1.294   0.566      92        28
 569064      high 0.828   0.906     117         3
 569068      high 1.004   0.629     101        19
 569069      high 1.257   0.779      81        39
 569073      high 1.256   0.956     101        19
 571619      high 0.651   0.765     105        15

Mean late CSD at rest by third of the MOs depth range (1 = most superficial), median over mice:
           third_1  third_2  third_3
intensity                           
high        -0.010   -0.685    0.540
low          0.005   -0.090   -0.007
medium       0.048   -0.592    0.267

Result: reproduced. The late MOs CSD amplitude is larger at rest in 7 of 9 mice at high intensity (median 1.26 against 0.76, p = 0.0195) and in 15 of 18 values with high and medium (p = 0.00011). At rest the middle third of the MOs depth range carries a negative mean CSD (a sink) in the late window at high (-0.69) and medium (-0.59) intensity and much less at low (-0.09); this is a description and does not decide the claim.

figs1b-mouse-plf¶

In mice the PLF of the late response is larger at rest than during running for LFP and CSD, while for EEG the difference does not reach significance (p = 0.055).

PLF per channel is the absolute value of the trial average of the unit phase vectors of the Hilbert transform, averaged over 150 to 250 ms and over channels (criterion), with the readings of the three amplitude claims.

In [10]:
for sig in ["lfp", "csd", "eeg"]:
    print(sig.upper())
    print(readings_table(sig, meas="plf").round(6).to_string(index=False))
LFP
                                reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   (a)(i) high, all channels and trials  9     0.770757       0.662863            7 0.019531            0.100950
(a)(ii) high, valid channels and trials  9     0.771848       0.663799            7 0.019531            0.108048
            (b)(i) high and medium, all 18     0.726834       0.560343           15 0.000420            0.104422
         (b)(ii) high and medium, valid 18     0.732289       0.565980           15 0.000328            0.116719
CSD
                                reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   (a)(i) high, all channels and trials  9     0.590213       0.447295            8 0.027344            0.139376
(a)(ii) high, valid channels and trials  9     0.590213       0.452946            8 0.019531            0.139376
            (b)(i) high and medium, all 18     0.559173       0.360902           16 0.003365            0.172161
         (b)(ii) high and medium, valid 18     0.559173       0.360902           16 0.002808            0.171647
EEG
                                reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   (a)(i) high, all channels and trials 10     0.559839       0.370785            9 0.005859            0.192379
(a)(ii) high, valid channels and trials 10     0.576234       0.392500            9 0.005859            0.186432
            (b)(i) high and medium, all 20     0.540956       0.343944           18 0.000048            0.195457
         (b)(ii) high and medium, valid 20     0.545501       0.327874           18 0.000048            0.192947

Result: reproduced. The late PLF is larger at rest for the LFP (7 of 9 mice, p = 0.0195 at high intensity; p = 0.00042 with high and medium) and the CSD (8 of 9, p = 0.027 and 0.020 for the two selections; p = 0.0034 with high and medium). For the EEG, which does not decide the claim, the difference is significant here (9 of 10 sessions, p = 0.0059), where the paper reports p = 0.055.

figs4-intensity-dependence¶

The state modulation of the late response depends on stimulation intensity; EEG late amplitude is larger at rest for high and intermediate but not low intensity, LFP at all three, and CSD for high and intermediate but not low.

One value per mouse, state and intensity; all channels and trials, and the file's valid channels and trials as a second reading.

In [11]:
rows = []
for sig in ["eeg", "lfp", "csd"]:
    for chan in ["all", "valid"]:
        for inten in ["high", "medium", "low"]:
            rows.append({"signal": sig, "chan": chan, "intensity": inten,
                         **signed_rank(state_table(sig, (inten,), chan=chan), "")})
res_s4 = pd.DataFrame(rows).drop(columns="reading")
print(res_s4.round(6).to_string(index=False))
signal  chan intensity  n  rest_median  active_median  rest_larger        p  effect_median_diff
   eeg   all      high 10    81.695827      42.553001           10 0.001953           39.129735
   eeg   all    medium 10    58.883305      19.213380            9 0.003906           34.067667
   eeg   all       low 10     8.092937      12.855539            2 0.193359           -4.828853
   eeg valid      high 10    84.480480      36.270048           10 0.001953           37.452538
   eeg valid    medium 10    62.083607      18.104603            9 0.003906           37.605521
   eeg valid       low 10     6.701035      10.492898            2 0.275391           -4.028163
   lfp   all      high  9     1.977962       1.544234            7 0.019531            0.616410
   lfp   all    medium  9     1.638427       0.421183            9 0.003906            1.068728
   lfp   all       low  9     0.331730       0.149278            7 0.039062            0.083929
   lfp valid      high  9     2.001489       1.220359            7 0.027344            0.888249
   lfp valid    medium  9     1.632864       0.421671            9 0.003906            1.078798
   lfp valid       low  9     0.338490       0.199091            6 0.054688            0.085079
   csd   all      high  9     1.255964       0.764554            7 0.019531            0.411453
   csd   all    medium  9     0.864246       0.332601            8 0.007812            0.621175
   csd   all       low  9     0.186898       0.196618            2 0.164062           -0.041806
   csd valid      high  9     1.255964       0.764554            7 0.019531            0.409520
   csd valid    medium  9     0.896286       0.332601            8 0.007812            0.638416
   csd valid       low  9     0.186898       0.215405            2 0.164062           -0.045925

Result: reproduced, under the all-channels reading. EEG: rest larger at high (p = 0.0020) and medium (p = 0.0039), not at low (p = 0.19, rest larger in 2 of 10). LFP: rest larger at all three (p = 0.020, 0.0039 and 0.039). CSD: high (p = 0.020) and medium (p = 0.0078), not low (p = 0.16). With the file's valid channels and trials the LFP low-intensity test gives p = 0.055, so under that reading the LFP part would not hold.

speed-threshold-robust¶

The EEG, LFP and CSD state modulations remain when the speed threshold separating rest and active trials is raised up to 5 cm/s.

Thresholds 0.1, 0.5, 1, 2 and 5 cm/s (criterion's grid), reading (a)(i) of the base claims (high intensity, all channels and trials), and the same with the file's valid channels and trials. A session enters at a threshold when it has at least one trial in each state; at least 10 per state is a variant. The file's own is_running (above 0 cm/s) is shown as well.

In [12]:
rows = []
for sig in ["eeg", "lfp", "csd"]:
    for chan in ["all", "valid"]:
        for thr in russo.THRESHOLDS + ["file"]:
            t = state_table(sig, ("high",), thr, chan)
            t = t[(t.n_rest >= 1) & (t.n_active >= 1)]
            t10 = t[(t.n_rest >= 10) & (t.n_active >= 10)]
            a, b = signed_rank(t, ""), signed_rank(t10, "")
            rows.append({"signal": sig, "chan": chan, "threshold": thr, "n": a["n"], "rest_larger": a["rest_larger"],
                         "p": a["p"], "n_min10": b["n"], "p_min10": b["p"]})
res_thr = pd.DataFrame(rows)
print(res_thr.round(6).to_string(index=False))

# The criterion as written: at each threshold of the grid, EEG, LFP and CSD give p < 0.05 with rest larger
# (reading (a)(i), all channels and trials, sessions with at least one trial per state)
grid = res_thr[(res_thr.chan == "all") & res_thr.threshold.isin(russo.THRESHOLDS)].copy()
grid["passes"] = (grid.p < 0.05) & (grid.rest_larger > grid.n / 2)
print("\nCriterion, p < 0.05 with rest larger:")
print(grid.pivot(index="threshold", columns="signal", values="passes").to_string())
print(f"All three signals at every threshold: {bool(grid.passes.all())}")
signal  chan threshold  n  rest_larger        p  n_min10  p_min10
   eeg   all       0.1 10           10 0.001953        9 0.003906
   eeg   all       0.5 10           10 0.001953        8 0.007812
   eeg   all       1.0 10           10 0.001953        7 0.015625
   eeg   all       2.0 10           10 0.001953        6 0.031250
   eeg   all       5.0 10           10 0.001953        5 0.062500
   eeg   all      file 10           10 0.001953        9 0.003906
   eeg valid       0.1 10           10 0.001953        9 0.003906
   eeg valid       0.5 10           10 0.001953        7 0.015625
   eeg valid       1.0 10           10 0.001953        6 0.031250
   eeg valid       2.0 10           10 0.001953        6 0.031250
   eeg valid       5.0 10           10 0.001953        5 0.062500
   eeg valid      file 10           10 0.001953        9 0.003906
   lfp   all       0.1  9            7 0.019531        8 0.015625
   lfp   all       0.5  9            8 0.027344        7 0.046875
   lfp   all       1.0  9            8 0.027344        6 0.093750
   lfp   all       2.0  9            8 0.039062        5 0.187500
   lfp   all       5.0  9            8 0.097656        4 0.125000
   lfp   all      file  9            7 0.019531        8 0.015625
   lfp valid       0.1  9            7 0.027344        8 0.023438
   lfp valid       0.5  9            8 0.027344        6 0.093750
   lfp valid       1.0  9            8 0.027344        5 0.187500
   lfp valid       2.0  9            8 0.027344        5 0.187500
   lfp valid       5.0  9            8 0.097656        4 0.125000
   lfp valid      file  9            7 0.019531        8 0.015625
   csd   all       0.1  9            7 0.019531        8 0.015625
   csd   all       0.5  9            7 0.074219        7 0.015625
   csd   all       1.0  9            7 0.074219        6 0.031250
   csd   all       2.0  9            7 0.250000        5 0.062500
   csd   all       5.0  9            7 0.359375        4 0.125000
   csd   all      file  9            7 0.019531        8 0.015625
   csd valid       0.1  9            7 0.019531        8 0.015625
   csd valid       0.5  9            7 0.074219        6 0.031250
   csd valid       1.0  9            7 0.074219        5 0.062500
   csd valid       2.0  9            7 0.250000        5 0.062500
   csd valid       5.0  9            7 0.359375        4 0.125000
   csd valid      file  9            7 0.019531        8 0.015625

Criterion, p < 0.05 with rest larger:
signal       csd   eeg    lfp
threshold                    
0.1         True  True   True
0.5        False  True   True
1.0        False  True   True
2.0        False  True   True
5.0        False  True  False
All three signals at every threshold: False

Result: not reproduced. The EEG modulation holds at every threshold from 0.1 to 5 cm/s (10 of 10 sessions, p = 0.00195 each). The LFP holds up to 2 cm/s (p = 0.039) and not at 5 cm/s (p = 0.098). The CSD holds only at 0.1 cm/s (p = 0.0195); from 0.5 cm/s on p = 0.074 to 0.36, with rest larger in 7 of 9 mice throughout. The criterion asks for EEG, LFP and CSD at every threshold and has no clause for a partial result, so the failures of LFP and CSD in the check above make the claim not reproduced, by the same rule as fig3e-lf-synchrony-reduced. With at least 10 trials per state the EEG also loses significance at 5 cm/s (5 sessions, p = 0.0625). This outcome was proposed after the second verification round and agreed by the third.

figs5-early-component-mouse¶

In mice the early (3 to 50 ms) EEG component is not modulated by state, while the early LFP amplitude is larger during running and the early CSD amplitude differs between states (the legend gives no direction for the CSD).

The three amplitude measures over 3 to 50 ms, with the readings of the late claims. The EEG part is a claim of absence judged on the paper's test (two-sided signed-rank, p >= 0.05).

In [13]:
for sig in ["eeg", "lfp", "csd"]:
    print(sig.upper(), "early 3-50 ms amplitude")
    print(readings_table(sig, win="early").round(6).to_string(index=False))
print("EEG early PLF (reported, paper p = 0.052)")
print(readings_table("eeg", meas="plf", win="early").round(6).to_string(index=False))
EEG early 3-50 ms amplitude
                                reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   (a)(i) high, all channels and trials 10    96.053730     101.645096            7 0.232422            5.416672
(a)(ii) high, valid channels and trials 10    84.230247      80.430462            7 0.160156            7.374714
            (b)(i) high and medium, all 20    84.136532      84.207886           12 0.840822            1.684607
         (b)(ii) high and medium, valid 20    78.548347      75.369480           13 0.388376            4.587378
LFP early 3-50 ms amplitude
                                reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   (a)(i) high, all channels and trials  9     3.752555       4.761584            2 0.019531           -1.179847
(a)(ii) high, valid channels and trials  9     3.775613       4.780037            2 0.019531           -1.157581
            (b)(i) high and medium, all 18     3.469001       4.255142            5 0.001289           -0.910885
         (b)(ii) high and medium, valid 18     3.474435       4.289099            5 0.001289           -0.942760
CSD early 3-50 ms amplitude
                                reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   (a)(i) high, all channels and trials  9     2.504149       2.010203            7 0.054688            0.299712
(a)(ii) high, valid channels and trials  9     2.501849       2.010203            7 0.054688            0.296793
            (b)(i) high and medium, all 18     1.849101       1.874587           12 0.048279            0.231463
         (b)(ii) high and medium, valid 18     1.850889       1.883232           12 0.048279            0.243678
EEG early PLF (reported, paper p = 0.052)
                                reading  n  rest_median  active_median  rest_larger        p  effect_median_diff
   (a)(i) high, all channels and trials 10     0.708941       0.702915            5 0.921875            0.001796
(a)(ii) high, valid channels and trials 10     0.703970       0.713660            5 0.695312           -0.000769
            (b)(i) high and medium, all 20     0.683256       0.660880            8 0.474905           -0.013558
         (b)(ii) high and medium, valid 20     0.660143       0.676191            9 0.388376           -0.011876

Result: reproduced, under reading (b). The early EEG amplitude does not differ by state under any reading (p = 0.16 to 0.84). The early LFP amplitude is larger during running (rest larger in 2 of 9 mice, p = 0.0195; reading (b) 5 of 18, p = 0.0013). The early CSD differs at p = 0.048 with high and medium (rest larger in 12 of 18, medians 1.85 and 1.87) but not at high alone (p = 0.055), so the CSD part holds under reading (b) only.

figs6-posterior-no-modulation¶

Blocked (data_missing): no file of the dandiset has electrical stimulation of visual or retrosplenial cortex or hippocampus (data check, target regions are MOs and SSp only).

triphasic-pattern¶

Deep MOs stimulation evokes a triphasic spiking pattern in MOs and SM-TH, an initial excitation within 10 ms, an off period of about 10 to 140 ms (127.8 +- 4.1 ms of silence) and a rebound excitation at 140 to 250 ms.

Population PSTH (1 ms bins) of responsive RS units in MOs and relay units in SM-TH at high intensity, per mouse. Readings of the silence (criterion): (a) per mouse, the median over units of the first-spike latency in 75 to 250 ms minus 10 ms, averaged over mice; (b) per mouse, the time the population rate stays below its baseline mean minus 2 SD after the initial peak.

In [14]:
def psth_shape(r, cls):
    c, rate, n = russo.population_psth(r, cls)
    if rate is None:
        return None
    base = rate[(c >= -0.5) & (c < -0.05)]
    mu, sd = base.mean(), base.std()
    init = rate[(c >= 0.002) & (c < 0.010)]
    off = rate[(c >= 0.010) & (c < 0.140)]
    reb = rate[(c >= 0.140) & (c < 0.250)]
    # reading (b): from the end of the initial peak (first bin after 2 ms back under the mean), time below mu - 2 SD
    k0 = np.searchsorted(c, 0.010)
    below = rate < mu - 2 * sd
    k = k0
    while k < len(rate) and not below[k] and c[k] < 0.05:
        k += 1
    start = k
    while k < len(rate) and (below[k] or np.all(below[k:k + 3])):
        k += 1
    silence_b = (c[k] - c[start]) * 1e3 if start < len(rate) and below[start] else 0.0
    return {"units": n, "baseline_Hz": mu, "initial_peak_Hz": init.max(), "initial_peak_ms": c[(c >= 0.002) & (c < 0.010)][init.argmax()] * 1e3,
            "frac_10_140_below_baseline": float((off < mu).mean()), "rebound_peak_Hz": reb.max(),
            "rebound_peak_ms": c[(c >= 0.140) & (c < 0.250)][reb.argmax()] * 1e3, "silence_b_ms": silence_b}


rows = []
for r in S.values():
    if not r.get("has_probes"):
        continue
    for cls in ["RS", "relay"]:
        s = psth_shape(r, cls)
        if s:
            lat = H[(H.subject == r["subject"]) & (H.cls == cls)].groupby("unit").lat_reb.median()
            rows.append({"subject": r["subject"], "cls": cls, **s, "silence_a_ms": (lat.median() - 0.010) * 1e3})
tri = pd.DataFrame(rows)
print(tri.round(2).to_string(index=False))
print("\nMean over mice:")
print(tri.groupby("cls")[["initial_peak_Hz", "baseline_Hz", "frac_10_140_below_baseline", "rebound_peak_Hz",
                          "rebound_peak_ms", "silence_a_ms", "silence_b_ms"]].mean().round(2).to_string())
print("Paper: silence 127.8 +- 4.1 ms")

fig, ax = plt.subplots(1, 2, figsize=(10, 3))
for k, cls in enumerate(["RS", "relay"]):
    for r in S.values():
        if r.get("has_probes"):
            c, rate, n = russo.population_psth(r, cls)
            if rate is not None:
                sm = np.convolve(rate, np.ones(5) / 5, "same")
                ax[k].plot(c * 1e3, sm, lw=0.8)
    ax[k].set_xlim(-100, 400); ax[k].set_ylim(0, 150); ax[k].set_title(f"{cls} units, high intensity, per mouse"); ax[k].set_xlabel("ms")
ax[0].set_ylabel("rate (Hz), 5 ms running mean")
plt.tight_layout(); plt.show()
print("Smoothed rates above 150 Hz (outside the axes), by class:", {cls: int(sum((np.convolve(russo.population_psth(r, cls)[1], np.ones(5) / 5, "same") > 150).sum()
      for r in S.values() if r.get("has_probes") and russo.population_psth(r, cls)[1] is not None)) for cls in ["RS", "relay"]}, "bins")
subject   cls  units  baseline_Hz  initial_peak_Hz  initial_peak_ms  frac_10_140_below_baseline  rebound_peak_Hz  rebound_peak_ms  silence_b_ms  silence_a_ms
 546655    RS     12         2.91            85.42              2.5                        0.98            13.89            159.5           4.0        173.31
 551397    RS     61         4.98           120.49              3.5                        1.00            16.39            160.5         128.0        156.57
 551397 relay     65         7.08            99.87              6.5                        0.85            24.74            150.5         101.0        158.38
 551399    RS     63         2.64            59.52              4.5                        1.00            12.17            177.5           1.0        172.29
 551399 relay      1         8.48            50.00              7.5                        0.93            75.00            163.5           0.0        151.75
 569062    RS     55         4.25            73.03              2.5                        0.97            19.24            162.5         107.0        158.45
 569062 relay    118         5.22            89.05              7.5                        0.77            22.60            160.5          93.0        151.57
 569064    RS     19         2.87           117.54              4.5                        1.00            11.40            178.5           1.0        192.75
 569068    RS     34         4.25           159.31              3.5                        1.00            13.24            160.5           5.0        181.16
 569068 relay     13         7.30            58.97              8.5                        0.86            20.51            160.5          71.0        147.28
 569069    RS     15         6.35            47.78              3.5                        1.00            33.33            193.5         148.0        187.16
 569069 relay     42         7.32            42.06              8.5                        0.98            34.52            183.5         119.0        175.17
 569073    RS     21         3.22            73.41              5.5                        0.95            28.17            158.5           1.0        154.45
 569073 relay     45         8.84            97.41              6.5                        0.95            20.37            156.5         115.0        168.31
 571619    RS     70         2.86            47.02              5.5                        0.98            10.71            161.5         126.0        167.50
 571619 relay     19         3.66            20.61              9.5                        0.80            17.11            161.5           1.0        173.45

Mean over mice:
       initial_peak_Hz  baseline_Hz  frac_10_140_below_baseline  rebound_peak_Hz  rebound_peak_ms  silence_a_ms  silence_b_ms
cls                                                                                                                          
RS               87.06         3.81                        0.99            17.62           168.06        171.52         57.89
relay            65.43         6.84                        0.88            30.69           162.36        160.84         71.43
Paper: silence 127.8 +- 4.1 ms
No description has been provided for this image
Smoothed rates above 150 Hz (outside the axes), by class: {'RS': 0, 'relay': 0} bins
In [15]:
def silence_b(c, rate, smooth_ms):
    """Reading (b) on the PSTH smoothed by a running mean over smooth_ms 1 ms bins: from the first bin
    after 10 ms below the baseline mean minus 2 SD (baseline -500 to -50 ms of the smoothed PSTH),
    the time until it comes back above."""
    sm = np.convolve(rate, np.ones(smooth_ms) / smooth_ms, "same") if smooth_ms > 1 else rate
    base = sm[(c >= -0.5) & (c < -0.05)]
    mu, sd = base.mean(), base.std()
    below = sm < mu - 2 * sd
    k = np.searchsorted(c, 0.010)
    while k < len(sm) and not below[k] and c[k] < 0.05:
        k += 1
    if k >= len(sm) or not below[k]:
        return mu, sd, 0.0
    start = k
    while k < len(sm) and below[k]:
        k += 1
    return mu, sd, (c[k] - c[start]) * 1e3


SMOOTH = [1, 2, 5, 10, 20]
rows = []
for r in S.values():
    if not r.get("has_probes"):
        continue
    for cls in ["RS", "relay"]:
        c, rate, n = russo.population_psth(r, cls)
        if rate is None:
            continue
        row = {"subject": r["subject"], "cls": cls, "units": n}
        for k in SMOOTH:
            mu, sd, s = silence_b(c, rate, k)
            if k in (1, 10):
                row[f"base_mean_{k}ms"], row[f"base_sd_{k}ms"], row[f"threshold_{k}ms"] = mu, sd, mu - 2 * sd
            row[f"silence_{k}ms"] = s
        rows.append(row)
sb = pd.DataFrame(rows)
print("Baseline mean, SD and threshold (mean - 2 SD) of the population rate, Hz, at 1 ms and smoothed over 10 ms:")
print(sb[["subject", "cls", "units", "base_mean_1ms", "base_sd_1ms", "threshold_1ms", "base_mean_10ms", "base_sd_10ms",
          "threshold_10ms"]].round(2).to_string(index=False))
print("\nReading (b), silence (ms) by smoothing width:")
print(sb[["subject", "cls", "units"] + [f"silence_{k}ms" for k in SMOOTH]].round(1).to_string(index=False))
print("\nMean over mice (ms); paper 127.8 +- 4.1, so 123.7 to 131.9:")
print(sb.groupby("cls")[[f"silence_{k}ms" for k in SMOOTH]].mean().round(1).to_string())
print("Without the relay population of 551399 (one unit):",
      sb[(sb.cls == "relay") & (sb.subject != "551399")][[f"silence_{k}ms" for k in SMOOTH]].mean().round(1).to_dict())
Baseline mean, SD and threshold (mean - 2 SD) of the population rate, Hz, at 1 ms and smoothed over 10 ms:
subject   cls  units  base_mean_1ms  base_sd_1ms  threshold_1ms  base_mean_10ms  base_sd_10ms  threshold_10ms
 546655    RS     12           2.91         1.43           0.05            2.90          0.47            1.97
 551397    RS     61           4.98         0.80           3.39            4.96          0.32            4.32
 551397 relay     65           7.08         1.00           5.09            7.06          0.45            6.15
 551399    RS     63           2.64         0.64           1.36            2.63          0.23            2.17
 551399 relay      1           8.48         8.26          -8.03            8.43          2.40            3.62
 569062    RS     55           4.25         0.81           2.63            4.23          0.33            3.58
 569062 relay    118           5.22         0.59           4.03            5.20          0.26            4.68
 569064    RS     19           2.87         1.12           0.63            2.86          0.43            2.01
 569068    RS     34           4.25         1.03           2.18            4.23          0.37            3.49
 569068 relay     13           7.30         2.13           3.05            7.27          0.73            5.81
 569069    RS     15           6.35         1.86           2.63            6.34          0.61            5.11
 569069 relay     42           7.32         1.12           5.09            7.29          0.40            6.49
 569073    RS     21           3.22         1.19           0.85            3.21          0.42            2.38
 569073 relay     45           8.84         1.17           6.51            8.81          0.48            7.86
 571619    RS     70           2.86         0.59           1.68            2.86          0.22            2.41
 571619 relay     19           3.66         1.22           1.22            3.65          0.50            2.66

Reading (b), silence (ms) by smoothing width:
subject   cls  units  silence_1ms  silence_2ms  silence_5ms  silence_10ms  silence_20ms
 546655    RS     12          4.0        105.0        125.0         125.0         121.0
 551397    RS     61        128.0        133.0        134.0         132.0         127.0
 551397 relay     65        101.0        108.0        109.0         107.0         101.0
 551399    RS     63          1.0        131.0        138.0         136.0         131.0
 551399 relay      1          0.0          0.0          2.0          20.0          71.0
 569062    RS     55        107.0        110.0        122.0         121.0         116.0
 569062 relay    118         93.0         97.0         97.0          95.0          92.0
 569064    RS     19          1.0        133.0        139.0         137.0         132.0
 569068    RS     34          5.0        126.0        139.0         137.0         131.0
 569068 relay     13         71.0         88.0        100.0         103.0         102.0
 569069    RS     15        148.0        155.0        156.0         157.0         151.0
 569069 relay     42        119.0        125.0        126.0         124.0         119.0
 569073    RS     21          1.0          2.0        123.0         120.0         116.0
 569073 relay     45        115.0        117.0        119.0         119.0         114.0
 571619    RS     70        126.0        129.0        131.0         130.0         126.0
 571619 relay     19          1.0         70.0         88.0          96.0          92.0

Mean over mice (ms); paper 127.8 +- 4.1, so 123.7 to 131.9:
       silence_1ms  silence_2ms  silence_5ms  silence_10ms  silence_20ms
cls                                                                     
RS            57.9        113.8        134.1         132.8         127.9
relay         71.4         86.4         91.6          94.9          98.7
Without the relay population of 551399 (one unit): {'silence_1ms': 83.3, 'silence_2ms': 100.8, 'silence_5ms': 106.5, 'silence_10ms': 107.3, 'silence_20ms': 103.3}

Result: partially reproduced. The triphasic pattern is present in every mouse: the initial peak falls at 2.5 to 9.5 ms, the rate is below baseline over a mean of 99% (RS) and 88% (relay) of 10 to 140 ms, and the rebound peaks at 150 to 194 ms. The silence does not match 127.8 +- 4.1 ms under either reading of the criterion: (a) 171.5 ms (RS) and 160.8 ms (relay), (b) 57.9 and 71.4 ms. Reading (b) on 1 ms bins is degenerate: with baseline rates of 2.6 to 8.8 Hz the threshold, baseline mean minus 2 SD, is 0.05 to 6.51 Hz and below zero for the one-unit relay population of 551399, and 7 of the 16 populations give silences of 0 to 5 ms. On PSTHs smoothed by a running mean, the RS silence is 113.8 ms (2 ms), 134.1 (5 ms), 132.8 (10 ms) and 127.9 ms (20 ms), within 123.7 to 131.9 ms only at 20 ms; the relay silence stays at 86.4 to 98.7 ms (100.8 to 107.3 ms without 551399). So the RS value comes near the paper's at wider smoothing, and the relay value does not at any width.

fig2b-thalamus-leads¶

The late rebound of SM-TH units precedes that of MOs RS units and the late CSD, LFP and EEG peaks, at rest and during running.

Per mouse at high intensity (criterion): SM-TH and MOs latency, per trial the median over responsive relay (SM-TH) or RS (MOs) units of the first-spike latency in 75 to 250 ms, averaged over trials; EEG, LFP and CSD latency, per trial the largest GFP peak in 75 to 250 ms whose prominence exceeds the baseline mean plus 3 SD, averaged over trials. Two-way ANOVA on measure and state, Tukey HSD on the measure. Tukey within each state is shown as well.

In [16]:
def trial_unit_latency(cls, col="lat_reb", frame=H):
    """Per mouse and trial, the median over the class's responsive units of the latency."""
    return frame[frame.cls == cls].groupby(["subject", "trial"])[col].median()


rows = []
for r in S.values():
    if not r.get("has_probes"):
        continue
    t = r["trials"]
    hi = (t.intensity == "high") & t.is_valid
    per = {"EEG": pd.Series(r["eeg_lat"]), "LFP": pd.Series(r["lfp_lat"]), "CSD": pd.Series(r["csd_lat"])}
    for name, cls in [("SM-TH", "relay"), ("MOs", "RS")]:
        s = trial_unit_latency(cls)
        if r["subject"] in s.index.get_level_values(0):
            per[name] = s.loc[r["subject"]].reindex(range(len(t)))
    for name, lat in per.items():
        for st, m in [("rest", hi & ~t.active), ("active", hi & t.active)]:
            v = lat[m.to_numpy()].dropna()
            if len(v):
                rows.append({"subject": r["subject"], "measure": name, "state": st, "latency": v.mean(), "trials": len(v)})
lat2b = pd.DataFrame(rows)
print("Mean latency (ms) over mice, and number of mice:")
print((lat2b.groupby(["measure", "state"]).latency.agg(["mean", "std", "size"]) * [1e3, 1e3, 1]).round(1).to_string())
fit = smf.ols("latency ~ C(measure) * C(state)", data=lat2b).fit()
print("\nTwo-way ANOVA (type II):")
print(anova_lm(fit, typ=2).to_string())
tk = pairwise_tukeyhsd(lat2b.latency * 1e3, lat2b.measure)
print("\nTukey HSD on measure (ms):")
print(tk.summary())
for st in ["rest", "active"]:
    d = lat2b[lat2b.state == st]
    print(f"\nTukey HSD on measure, {st} only:")
    print(pairwise_tukeyhsd(d.latency * 1e3, d.measure).summary())
Mean latency (ms) over mice, and number of mice:
                 mean   std  size
measure state                    
CSD     active  158.0  11.2   9.0
        rest    172.3   9.6   9.0
EEG     active  163.3  15.1   8.0
        rest    176.1   9.4   9.0
LFP     active  160.9  13.7   8.0
        rest    173.2   8.0   9.0
MOs     active  158.6  11.1   9.0
        rest    175.0  10.4   9.0
SM-TH   active  146.4  18.2   7.0
        rest    173.4   9.8   7.0

Two-way ANOVA (type II):
                       sum_sq    df          F        PR(>F)
C(measure)           0.000784   4.0   1.412909  2.380759e-01
C(state)             0.005465   1.0  39.377285  2.135243e-08
C(measure):C(state)  0.000539   4.0   0.971303  4.284773e-01
Residual             0.010269  74.0        NaN           NaN
Tukey HSD on measure (ms):
 Multiple Comparison of Means - Tukey HSD, FWER=0.05 
=====================================================
group1 group2 meandiff p-adj   lower    upper  reject
-----------------------------------------------------
   CSD    EEG   4.9427 0.8462  -8.6084 18.4938  False
   CSD    LFP   2.2634 0.9901 -11.2877 15.8146  False
   CSD    MOs   1.6578 0.9968 -11.6984 15.0139  False
   CSD  SM-TH  -5.2636 0.8411 -19.5419  9.0147  False
   EEG    LFP  -2.6793 0.9823 -16.4226 11.0641  False
   EEG    MOs  -3.2849 0.9609  -16.836 10.2662  False
   EEG  SM-TH -10.2063   0.29 -24.6672  4.2546  False
   LFP    MOs  -0.6057 0.9999 -14.1568 12.9454  False
   LFP  SM-TH   -7.527 0.5956 -21.9879  6.9338  False
   MOs  SM-TH  -6.9214 0.6589 -21.1997  7.3569  False
-----------------------------------------------------

Tukey HSD on measure, rest only:
 Multiple Comparison of Means - Tukey HSD, FWER=0.05 
=====================================================
group1 group2 meandiff p-adj   lower    upper  reject
-----------------------------------------------------
   CSD    EEG   3.8343 0.9101  -8.9551 16.6237  False
   CSD    LFP   0.9186 0.9996 -11.8708  13.708  False
   CSD    MOs   2.7396 0.9721 -10.0498  15.529  False
   CSD  SM-TH   1.1066 0.9993 -12.5658 14.7791  False
   EEG    LFP  -2.9157 0.9651 -15.7051  9.8737  False
   EEG    MOs  -1.0948 0.9992 -13.8841 11.6946  False
   EEG  SM-TH  -2.7277 0.9785 -16.4001 10.9448  False
   LFP    MOs    1.821  0.994 -10.9684 14.6103  False
   LFP  SM-TH    0.188    1.0 -13.4844 13.8605  False
   MOs  SM-TH  -1.6329 0.9969 -15.3054 12.0395  False
-----------------------------------------------------

Tukey HSD on measure, active only:
 Multiple Comparison of Means - Tukey HSD, FWER=0.05 
=====================================================
group1 group2 meandiff p-adj   lower    upper  reject
-----------------------------------------------------
   CSD    EEG   5.2993 0.9318 -13.9531 24.5517  False
   CSD    LFP   2.8861 0.9925 -16.3663 22.1384  False
   CSD    MOs    0.576    1.0 -18.1016 19.2535  False
   CSD  SM-TH -11.6338 0.4629  -31.601  8.3333  False
   EEG    LFP  -2.4132 0.9966 -22.2238 17.3973  False
   EEG    MOs  -4.7233 0.9542 -23.9757 14.5291  False
   EEG  SM-TH -16.9331 0.1469  -37.439  3.5727  False
   LFP    MOs  -2.3101 0.9968 -21.5624 16.9423  False
   LFP  SM-TH -14.5199 0.2715 -35.0257   5.986  False
   MOs  SM-TH -12.2098 0.4144  -32.177  7.7573  False
-----------------------------------------------------
In [17]:
# Variant: the EEG and LFP GFP over the channels the file marks valid (the CSD has no such flag)
rows = []
for r in S.values():
    if not r.get("has_probes"):
        continue
    t = r["trials"]
    hi = (t.intensity == "high") & t.is_valid
    per = {"EEG": pd.Series(r["eeg_lat_valid"]), "LFP": pd.Series(r["lfp_lat_valid"]), "CSD": pd.Series(r["csd_lat"])}
    for name, cls in [("SM-TH", "relay"), ("MOs", "RS")]:
        s = trial_unit_latency(cls)
        if r["subject"] in s.index.get_level_values(0):
            per[name] = s.loc[r["subject"]].reindex(range(len(t)))
    for name, lat in per.items():
        for st, m in [("rest", hi & ~t.active), ("active", hi & t.active)]:
            v = lat[m.to_numpy()].dropna()
            if len(v):
                rows.append({"subject": r["subject"], "measure": name, "state": st, "latency": v.mean(), "trials": len(v)})
lat2b_valid = pd.DataFrame(rows)
print("Valid channels only. Mean latency (ms) over mice, and number of mice:")
print((lat2b_valid.groupby(["measure", "state"]).latency.agg(["mean", "std", "size"]) * [1e3, 1e3, 1]).round(1).to_string())
print("\nTwo-way ANOVA (type II):")
print(anova_lm(smf.ols("latency ~ C(measure) * C(state)", data=lat2b_valid).fit(), typ=2).to_string())
print("\nTukey HSD on measure (ms):")
print(pairwise_tukeyhsd(lat2b_valid.latency * 1e3, lat2b_valid.measure).summary())
Valid channels only. Mean latency (ms) over mice, and number of mice:
                 mean   std  size
measure state                    
CSD     active  158.0  11.2   9.0
        rest    172.3   9.6   9.0
EEG     active  160.4  13.3   9.0
        rest    174.3   7.0   9.0
LFP     active  160.6  13.4   8.0
        rest    172.1   6.8   9.0
MOs     active  158.6  11.1   9.0
        rest    175.0  10.4   9.0
SM-TH   active  146.4  18.2   7.0
        rest    173.4   9.8   7.0

Two-way ANOVA (type II):
                       sum_sq    df          F        PR(>F)
C(measure)           0.000542   4.0   1.059540  3.825687e-01
C(state)             0.005564   1.0  43.528893  5.219572e-09
C(measure):C(state)  0.000540   4.0   1.056941  3.838597e-01
Residual             0.009587  75.0        NaN           NaN

Tukey HSD on measure (ms):
 Multiple Comparison of Means - Tukey HSD, FWER=0.05 
=====================================================
group1 group2 meandiff p-adj   lower    upper  reject
-----------------------------------------------------
   CSD    EEG   2.2096 0.9895   -10.82 15.2392  False
   CSD    LFP   1.5274 0.9976 -11.6924 14.7472  False
   CSD    MOs   1.6578 0.9965 -11.3718 14.6873  False
   CSD  SM-TH  -5.2636 0.8289 -19.1928  8.6656  False
   EEG    LFP  -0.6822 0.9999  -13.902 12.5376  False
   EEG    MOs  -0.5518    1.0 -13.5814 12.4777  False
   EEG  SM-TH  -7.4732 0.5672 -21.4024   6.456  False
   LFP    MOs   0.1303    1.0 -13.0895 13.3501  False
   LFP  SM-TH   -6.791  0.665 -20.8983  7.3163  False
   MOs  SM-TH  -6.9214 0.6378 -20.8506  7.0078  False
-----------------------------------------------------

Result: not reproduced. The measure factor of the two-way ANOVA is not significant (F = 1.41, p = 0.24) and no Tukey comparison of SM-TH with another measure is (adjusted p 0.29 to 0.84). SM-TH has the shortest mean latency during running (146.4 ms against 158.0 to 163.3 for the others) but not at rest (173.4 against 172.3 to 176.1). With the EEG and LFP GFP over the valid channels only, the measure factor gives p = 0.38 and the Tukey comparisons of SM-TH adjusted p 0.57 to 0.83. Only 7 mice have responsive relay units, against 20 in the paper.

figs7a-active-shorter-latency¶

Late responses have shorter latencies during running than at rest for all measures.

In the data of fig2b-thalamus-leads: reproduced when the mean latency is shorter in active than rest for all five measures; the state factor of the ANOVA is reported.

In [18]:
m7 = lat2b.groupby(["measure", "state"]).latency.mean().unstack() * 1e3
m7["active_minus_rest_ms"] = m7.active - m7.rest
paired = lat2b.pivot_table(index=["subject", "measure"], columns="state", values="latency").dropna()
m7["mice_active_shorter"] = (paired.active < paired.rest).groupby("measure").sum()
m7["mice"] = paired.groupby("measure").size()
print(m7.round(2).to_string())
print("\nState factor of the two-way ANOVA: F = %.2f, p = %.4g" % tuple(anova_lm(fit, typ=2).loc["C(state)", ["F", "PR(>F)"]]))
state    active    rest  active_minus_rest_ms  mice_active_shorter  mice
measure                                                                 
CSD      158.05  172.29                -14.25                    9     9
EEG      163.35  176.13                -12.78                    7     8
LFP      160.93  173.21                -12.28                    7     8
MOs      158.62  175.03                -16.41                    9     9
SM-TH    146.41  173.40                -26.99                    7     7

State factor of the two-way ANOVA: F = 39.38, p = 2.135e-08

Result: reproduced. The mean latency is shorter during running for all five measures (by 12.3 to 27.0 ms), in 7 to 9 mice per measure, and the state factor of the ANOVA gives F = 39.4, p = 2.1e-08.

figs7b-latency-correlation¶

On single trials, the later the SM-TH units rebound, the later the MOs units and the CSD, LFP and EEG peaks.

Per trial at high intensity, the latencies of fig2b-thalamus-leads before averaging; four mixed models Measure ~ ThalamicUnits + (1 | MouseID) (statsmodels mixedlm).

In [19]:
rows = []
for r in S.values():
    if not r.get("has_probes"):
        continue
    t = r["trials"]
    th = trial_unit_latency("relay")
    if r["subject"] not in th.index.get_level_values(0):
        continue
    d = pd.DataFrame({"TH": th.loc[r["subject"]].reindex(range(len(t))),
                      "MOs": trial_unit_latency("RS").loc[r["subject"]].reindex(range(len(t))),
                      "EEG": r["eeg_lat"], "LFP": r["lfp_lat"], "CSD": r["csd_lat"]})
    d["subject"] = r["subject"]
    d = d[((t.intensity == "high") & t.is_valid).to_numpy()]
    rows.append(d)
pt7 = pd.concat(rows) * 1
for c in ["TH", "MOs", "EEG", "LFP", "CSD"]:
    pt7[c] = pt7[c] * 1e3
out = []
for m in ["MOs", "CSD", "LFP", "EEG"]:
    d = pt7.dropna(subset=["TH", m])
    fm = smf.mixedlm(f"{m} ~ TH", d, groups=d["subject"]).fit()
    rho = stats.spearmanr(d.TH, d[m])
    out.append({"measure": m, "trials": len(d), "mice": d.subject.nunique(), "slope": fm.params["TH"],
                "p": fm.pvalues["TH"], "spearman_r": rho.statistic, "spearman_p": rho.pvalue})
print(pd.DataFrame(out).to_string(index=False))
measure  trials  mice    slope            p  spearman_r   spearman_p
    MOs     796     7 0.331785 9.272879e-71    0.537241 1.006414e-60
    CSD     570     7 0.309834 1.414725e-43    0.538365 3.779009e-44
    LFP     706     7 0.301413 3.996153e-20    0.431137 2.530431e-33
    EEG     547     7 0.425402 6.452003e-35    0.464873 1.117943e-30

Result: reproduced. On single trials the SM-TH rebound latency predicts the MOs, CSD, LFP and EEG latencies with positive slopes 0.30 to 0.43 (mixed models, p = 4e-20 to 9e-71; 547 to 796 trials from 7 mice).

fig3a-thalamic-rate-higher-active¶

The evoked firing rate of SM-TH units in the late window (150 to 250 ms) is higher during running than at rest, unlike the late EP component.

Responsive relay units at high intensity; per unit and trial, spikes in 150 to 250 ms over 0.1 s. Readings (criterion): (a) per unit, signed-rank on unit pairs; (b) per mouse, the median over its units, signed-rank; (c) per trial, the mean over the session's units, rank-sum on rest against active trials pooled over sessions. Variant: the code's rank-sum on per-session medians. As the sessions differ in rate and in their fractions of active trials, reading (c) is also shown within each session and as a session-stratified rank-sum (van Elteren); these are checks, not readings of the criterion.

In [20]:
def rate_readings(cls, frame=H, col="rate_late"):
    d = frame[frame.cls == cls]
    pu = d.groupby(["subject", "unit", "active"])[col].mean().unstack().dropna()
    pm = pu.groupby("subject").median()
    pt = d.groupby(["subject", "trial", "active"])[col].mean().reset_index()
    out = []
    w = stats.wilcoxon(pu[False], pu[True])
    out.append({"reading": "(a) per unit, signed-rank", "n": len(pu), "rest": pu[False].mean(), "active": pu[True].mean(), "p": w.pvalue})
    if len(pm) > 1:
        w = stats.wilcoxon(pm[False], pm[True])
        out.append({"reading": "(b) per mouse median, signed-rank", "n": len(pm), "rest": pm[False].median(), "active": pm[True].median(), "p": w.pvalue})
    a, rr = pt[pt.active][col], pt[~pt.active][col]
    out.append({"reading": "(c) per trial, rank-sum", "n": f"{len(rr)} rest, {len(a)} active", "rest": rr.mean(), "active": a.mean(),
                "p": stats.mannwhitneyu(rr, a).pvalue})
    sm = d.groupby(["subject", "active"])[col].median().unstack()
    out.append({"reading": "code variant, per-session medians, rank-sum", "n": len(sm), "rest": sm[False].median(), "active": sm[True].median(),
                "p": stats.mannwhitneyu(sm[False].dropna(), sm[True].dropna()).pvalue})
    return pd.DataFrame(out), pu


r3a, pu3a = rate_readings("relay")
print(r3a.to_string(index=False))
print("\nPer mouse (median over units, Hz):")
print(pu3a.groupby("subject").agg(["median", "size"]).round(2).to_string())
                                    reading                    n      rest    active        p
                  (a) per unit, signed-rank                  303 14.413052 14.784399 0.412055
          (b) per mouse median, signed-rank                    7 13.097826 13.333333 0.296875
                    (c) per trial, rank-sum 681 rest, 150 active 13.869338 17.154068 0.000535
code variant, per-session medians, rank-sum                    7 10.000000 10.000000 0.243153

Per mouse (median over units, Hz):
active   False       True      
        median size median size
subject                        
551397   16.98   65  12.08   65
551399   16.23    1  35.00    1
569062   13.10  118  13.21  118
569068    7.33   13  11.05   13
569069   18.94   42  17.63   42
569073   11.78   45  17.50   45
571619   10.48   19  13.33   19
In [21]:
def van_elteren(d, col):
    """Session-stratified rank-sum test (van Elteren 1960): rest against active trials within each
    session, rank sums weighted by 1/(n+1), normal approximation with the tie correction."""
    num, var = 0.0, 0.0
    for _, s in d.groupby("subject"):
        a, r = s[s.active][col].to_numpy(), s[~s.active][col].to_numpy()
        if len(a) == 0 or len(r) == 0:
            continue
        n = len(a) + len(r)
        ranks = stats.rankdata(np.r_[a, r])
        _, cnt = np.unique(np.r_[a, r], return_counts=True)
        v = len(a) * len(r) / 12 * ((n + 1) - (cnt ** 3 - cnt).sum() / (n * (n - 1)))
        w = 1 / (n + 1)
        num += w * (ranks[:len(a)].sum() - len(a) * (n + 1) / 2)
        var += w ** 2 * v
    z = num / np.sqrt(var)
    return z, 2 * stats.norm.sf(abs(z))


def per_session_rates(cls, frame=H, col="rate_late"):
    """Reading (c) within each session: per trial the mean over the session's units, rest against active."""
    d = frame[frame.cls == cls]
    pt = d.groupby(["subject", "trial", "active"])[col].mean().reset_index()
    rows = []
    for s, g in pt.groupby("subject"):
        a, r = g[g.active][col], g[~g.active][col]
        rows.append({"subject": s, "units": d[d.subject == s].unit.nunique(), "trials_rest": len(r), "trials_active": len(a),
                     "rest_Hz": r.mean(), "active_Hz": a.mean(),
                     "p_ranksum": stats.mannwhitneyu(r, a).pvalue if len(a) and len(r) else np.nan})
    z, p = van_elteren(pt, col)
    return pd.DataFrame(rows), z, p


t3a, z, p = per_session_rates("relay")
print("Relay units, per session (reading (c) within each session):")
print(t3a.round(4).to_string(index=False))
print(f"van Elteren, stratified by session: z = {z:.2f} (positive: active larger), p = {p:.2g}")
print(f"Sessions with active larger: {int((t3a.active_Hz > t3a.rest_Hz).sum())} of {len(t3a)}; "
      f"significant (p < 0.05) active larger {int(((t3a.active_Hz > t3a.rest_Hz) & (t3a.p_ranksum < 0.05)).sum())}, "
      f"rest larger {int(((t3a.active_Hz < t3a.rest_Hz) & (t3a.p_ranksum < 0.05)).sum())}")
Relay units, per session (reading (c) within each session):
subject  units  trials_rest  trials_active  rest_Hz  active_Hz  p_ranksum
 551397     65           96             24  17.2644    13.5128     0.0000
 551399      1          106             14  16.2264    35.0000     0.0346
 569062    118           92             28  12.6815    13.0115     0.9505
 569068     13          101             19   8.5758    13.8462     0.0036
 569069     42           80             38  19.1518    18.2456     0.2341
 569073     45          101             12  13.6062    17.7778     0.0082
 571619     19          105             15  10.7469    14.9825     0.0032
van Elteren, stratified by session: z = 1.30 (positive: active larger), p = 0.19
Sessions with active larger: 5 of 7; significant (p < 0.05) active larger 4, rest larger 1

Result: reproduced, under reading (c) only. Per trial, the mean late rate of responsive relay units is higher during running (17.2 against 13.9 Hz; rank-sum p = 0.00054, 681 rest and 150 active trials). Per unit (303 units, 14.8 against 14.4 Hz, p = 0.41) and per mouse (7 mice, p = 0.30) the difference is not significant, nor with the code's per-session medians (p = 0.24). The pooled per-trial test mixes sessions with different rates and fractions of active trials. Within sessions the rate is higher during running in 5 of 7 (significantly in 4: 551399, 569068, 569073, 571619) and significantly lower in 551397 (17.3 against 13.5 Hz); the session-stratified van Elteren test gives p = 0.19. The criterion accepts reading (c), so the outcome stands, but it does not hold within sessions taken together.

figs9-mos-rate-no-modulation¶

The late evoked firing rate of MOs units is not modulated by state.

Claim of absence, on the paper's test: responsive RS units in MOs, one median per mouse and state, two-sided signed-rank across mice. All MOs units (RS and FS) are a variant, since the Figure S9A legend says MOs units.

In [22]:
r9, pu9 = rate_readings("RS")
print("RS units")
print(r9.to_string(index=False))
Hm = H.assign(cls=H.cls.replace({"FS": "MOs_all", "RS": "MOs_all"}))
r9b, _ = rate_readings("MOs_all", frame=Hm)
print("\nVariant, all responsive MOs units")
print(r9b.to_string(index=False))
RS units
                                    reading                    n     rest   active            p
                  (a) per unit, signed-rank                  350 7.566796 5.836253 5.665608e-10
          (b) per mouse median, signed-rank                    9 3.645833 3.333333 1.171875e-02
                    (c) per trial, rank-sum 836 rest, 234 active 7.828562 6.818918 1.637080e-04
code variant, per-session medians, rank-sum                    9 0.000000 0.000000 1.000000e+00

Variant, all responsive MOs units
                                    reading                    n     rest   active            p
                  (a) per unit, signed-rank                  393 9.353059 7.016566 2.607877e-11
          (b) per mouse median, signed-rank                    9 3.958333 3.333333 2.734375e-02
                    (c) per trial, rank-sum 836 rest, 234 active 9.252354 7.906644 1.611060e-05
code variant, per-session medians, rank-sum                    9 0.000000 0.000000 5.848299e-01

Result: not reproduced. On the paper's test, per-mouse medians of responsive RS units, the late rate differs by state (9 mice, 3.65 against 3.33 Hz, p = 0.0117), lower during running. All responsive MOs units give p = 0.027, and per unit p = 6e-10.

figs10a-fs-trn-no-modulation¶

The late evoked firing of putative cortical interneurons (FS) and TRN units is not modulated by state.

Claim of absence. Responsive FS units in MOs and thalamic units under 0.35 ms, with the reading of the unit of test adopted in fig3a-thalamic-rate-higher-active, (c), and all readings shown; the same within-session and session-stratified checks as there. TRN is the SM-TH units under 0.35 ms; the variant TRN+RT adds the units under 0.35 ms located in RT itself.

In [23]:
for cls in ["FS", "TRN"]:
    r10, _ = rate_readings(cls)
    print(cls)
    print(r10.to_string(index=False))
FS
                                    reading                    n      rest    active        p
                  (a) per unit, signed-rank                   43 23.892409 16.623769 0.006789
          (b) per mouse median, signed-rank                    8 21.247642 14.345238 0.039062
                    (c) per trial, rank-sum 798 rest, 153 active 22.086615 20.257470 0.347934
code variant, per-session medians, rank-sum                    8 20.000000 10.000000 0.182962
TRN
                                    reading                    n      rest    active        p
                  (a) per unit, signed-rank                   18 32.881176 35.188214 0.392738
          (b) per mouse median, signed-rank                    6 26.515573 30.238095 0.312500
                    (c) per trial, rank-sum 601 rest, 112 active 31.214642 30.315476 0.884833
code variant, per-session medians, rank-sum                    6 15.000000 15.000000 1.000000
In [24]:
for cls in ["FS", "TRN"]:
    t, z, p = per_session_rates(cls)
    print(f"{cls} units, per session (reading (c) within each session):")
    print(t.round(4).to_string(index=False))
    print(f"van Elteren, stratified by session: z = {z:.2f} (positive: active larger), p = {p:.2g}\n")
# Variant: TRN also counts the units under 0.35 ms located in RT itself (TRN-RT)
Hrt = H[H.cls.isin(["TRN", "TRN-RT"])].assign(cls="TRN+RT")
r10rt, _ = rate_readings("TRN+RT", frame=Hrt)
print("TRN with RT units:")
print(r10rt.to_string(index=False))
t, z, p = per_session_rates("TRN+RT", frame=Hrt)
print(t.round(4).to_string(index=False))
print(f"van Elteren, stratified by session: z = {z:.2f} (positive: active larger), p = {p:.2g}")

# The criterion as written (reading (c), the one adopted in fig3a), next to the within-session check, for fig3a too
rows = []
for claim, cls, frame in [("fig3a (relay, active larger)", "relay", H), ("figs10a FS", "FS", H), ("figs10a TRN", "TRN", H)]:
    rr = rate_readings(cls, frame=frame)[0].set_index("reading").loc["(c) per trial, rank-sum"]
    _, z, p = per_session_rates(cls, frame=frame)
    rows.append({"claim": claim, "rest_Hz": rr.rest, "active_Hz": rr.active, "p_reading_c": rr.p, "van_Elteren_z": z, "p_van_Elteren": p})
crit = pd.DataFrame(rows)
print("\nReading (c), pooled over sessions, against the session-stratified test:")
print(crit.round(4).to_string(index=False))
print(f"figs10a by the criterion (neither FS nor TRN p < 0.05 under reading (c)): "
      f"{'reproduced' if (crit.p_reading_c[1:] >= 0.05).all() else 'not reproduced'}")
FS units, per session (reading (c) within each session):
subject  units  trials_rest  trials_active  rest_Hz  active_Hz  p_ranksum
 551397      4           96             24  30.9896    19.1667     0.0000
 551399      8          106             14  20.4953    13.6607     0.0003
 569062     10           92             28  39.8696    23.6071     0.0000
 569064      5          117              3   2.1197     3.3333     0.2808
 569068      5          101             19  28.5545    18.9474     0.0009
 569069      3           80             38  22.7917    27.6316     0.0033
 569073      1          101             12  24.0594    15.8333     0.0405
 571619      7          105             15  13.5646    11.8095     0.3391
van Elteren, stratified by session: z = -5.69 (positive: active larger), p = 1.3e-08

TRN units, per session (reading (c) within each session):
subject  units  trials_rest  trials_active  rest_Hz  active_Hz  p_ranksum
 551397      5           96             24  34.3750    49.2500     0.0027
 551399      3          106             14  28.0503    32.3810     0.1221
 569062      1           92             28  12.5000    10.7143     0.8637
 569068      3          101             19  19.5710    16.3158     0.3155
 569073      4          101             12  41.5842    32.0833     0.0700
 571619      2          105             15  49.1429    51.0000     0.9239
van Elteren, stratified by session: z = 0.86 (positive: active larger), p = 0.39

TRN with RT units:
                                    reading                    n      rest    active        p
                  (a) per unit, signed-rank                   19 31.967762 33.895007 0.465317
          (b) per mouse median, signed-rank                    7 24.801980 28.333333 0.687500
                    (c) per trial, rank-sum 639 rest, 193 active 30.281690 22.048359 0.000008
code variant, per-session medians, rank-sum                    7 10.000000 10.000000 1.000000
subject  units  trials_rest  trials_active  rest_Hz  active_Hz  p_ranksum
 546655      1           38             81  15.5263    10.6173     0.0187
 551397      5           96             24  34.3750    49.2500     0.0027
 551399      3          106             14  28.0503    32.3810     0.1221
 569062      1           92             28  12.5000    10.7143     0.8637
 569068      3          101             19  19.5710    16.3158     0.3155
 569073      4          101             12  41.5842    32.0833     0.0700
 571619      2          105             15  49.1429    51.0000     0.9239
van Elteren, stratified by session: z = -0.29 (positive: active larger), p = 0.77
Reading (c), pooled over sessions, against the session-stratified test:
                       claim  rest_Hz  active_Hz  p_reading_c  van_Elteren_z  p_van_Elteren
fig3a (relay, active larger)  13.8693    17.1541       0.0005         1.3032         0.1925
                  figs10a FS  22.0866    20.2575       0.3479        -5.6897         0.0000
                 figs10a TRN  31.2146    30.3155       0.8848         0.8635         0.3879
figs10a by the criterion (neither FS nor TRN p < 0.05 under reading (c)): reproduced

Result: reproduced, by the criterion, which fixes the test as the per-trial reading (c) adopted for fig3a-thalamic-rate-higher-active: neither FS (22.1 against 20.3 Hz, p = 0.35) nor TRN (31.2 against 30.3 Hz, p = 0.88) differs by state (table above). This outcome was proposed after the second verification round and agreed by the third. It is fragile on two counts.

First, FS rates are lower during running per unit and per mouse (p = 0.0068 and 0.039), and within sessions they are lower in 6 of 8 (significantly in 5), with van Elteren p = 1.3e-08; in 569069 they are significantly higher during running (27.6 against 22.8 Hz, p = 0.0033). The pooled test hides this because the sessions differ in rate and in their fractions of active trials, as for fig3a (van Elteren p = 0.19).

Second, the outcome depends on TRN being the SM-TH units under 0.35 ms. Adding the one responsive RT unit (546655) to TRN makes the pooled per-trial TRN test significant (30.3 against 22.0 Hz, p = 8e-06), which would make the claim not reproduced. This comes from the same mixing (that session has 81 of 119 trials active); stratified by session it gives p = 0.77, and per unit and per mouse p = 0.47 and 0.69. TRN on the SM-TH class does not differ under any reading (p = 0.31 to 1) nor within sessions (van Elteren p = 0.39).

fig3b-bimodal-isi¶

The evoked late ISI of putative thalamic relay units is bimodal, splitting them into high-firing (HF, ISI below 17.88 ms, 569 units) and low-firing (LF, 700 units) groups, while the ISI distributions of cortical RS, cortical FS and TRN units are unimodal.

Evoked ISI per unit: the median over trials of the interval between the first spike and the next in the window, (a) 150 to 250 ms (Methods) or (b) 75 to 250 ms (code). k-means with two clusters on the log ISI of the relay units, seeded from the claim; threshold the largest ISI of the short cluster. Hartigan's dip test on log10 ISI per class, with the diptest package (tabulated p-values); the paper's code used unidip, which does not run with current numpy.

In [25]:
SEED_3B = claim_seed("fig3b-bimodal-isi")


def isi_split(col, seed):
    isi = H.groupby(["subject", "unit", "cls"])[col].median().dropna().reset_index()
    rel = isi[isi.cls == "relay"].copy()
    km = KMeans(2, n_init=10, random_state=seed).fit(np.log(rel[col].to_numpy() * 1e3).reshape(-1, 1))
    short = int(np.argmin(km.cluster_centers_.ravel()))
    rel["group"] = np.where(km.labels_ == short, "HF", "LF")
    thr = rel.loc[rel.group == "HF", col].max() * 1e3
    return isi, rel, thr


res3b = {}
for label, col in [("(a) 150-250 ms", "isi_late"), ("(b) 75-250 ms", "isi_reb")]:
    isi, rel, thr = isi_split(col, SEED_3B)
    res3b[label] = (isi, rel, thr)
    dips = {c: diptest.diptest(np.log10(isi[isi.cls == c][col].to_numpy() * 1e3)) for c in ["relay", "TRN", "RS", "FS"]}
    print(f"{label}: units per class {isi.groupby('cls').size().to_dict()}")
    print(f"  k-means: HF {int((rel.group == 'HF').sum())}, LF {int((rel.group == 'LF').sum())}, threshold {thr:.2f} ms")
    print("  dip test (dip, p):", {c: (round(d, 4), round(p, 4)) for c, (d, p) in dips.items()})
    print("  relay ISI percentiles 5, 25, 50, 75, 95 (ms):", np.round(np.percentile(rel[col] * 1e3, [5, 25, 50, 75, 95]), 2))
    print(f"  relay units with ISI above 17.88 ms: {int((rel[col] * 1e3 > 17.88).sum())} of {len(rel)}")
    seeds = []
    for k in range(5):
        _, rk, tk_ = isi_split(col, SEED_3B + 1000 * k)
        seeds.append((int((rk.group == "HF").sum()), round(tk_, 2)))
    print("  HF count and threshold under seeds +0, +1000, ..., +4000:", seeds)

fig, ax = plt.subplots(1, 4, figsize=(13, 2.6))
isi, rel, thr = res3b["(a) 150-250 ms"]
for k, c in enumerate(["relay", "TRN", "RS", "FS"]):
    v = np.log10(isi[isi.cls == c].isi_late * 1e3)
    ax[k].hist(v, 30); ax[k].set_title(f"{c} (n = {len(v)})"); ax[k].set_xlabel("log10 evoked ISI (ms)")
    ax[k].axvline(np.log10(17.88), color="r", lw=0.8)
plt.tight_layout(); plt.show()
print("Plotted log10 ISI range:", round(np.log10(isi.isi_late * 1e3).min(), 2), "to", round(np.log10(isi.isi_late * 1e3).max(), 2))
(a) 150-250 ms: units per class {'FS': 39, 'RS': 271, 'TRN': 18, 'TRN-RT': 1, 'relay': 296}
  k-means: HF 278, LF 18, threshold 6.93 ms
  dip test (dip, p): {'relay': (0.0186, 0.7325), 'TRN': (0.0668, 0.749), 'RS': (0.0169, 0.9064), 'FS': (0.0409, 0.9233)}
  relay ISI percentiles 5, 25, 50, 75, 95 (ms): [ 2.03  2.33  2.63  3.5  10.72]
  relay units with ISI above 17.88 ms: 8 of 296
  HF count and threshold under seeds +0, +1000, ..., +4000: [(278, np.float64(6.93)), (277, np.float64(6.63)), (277, np.float64(6.63)), (278, np.float64(6.93)), (278, np.float64(6.93))]
(b) 75-250 ms: units per class {'FS': 39, 'RS': 276, 'TRN': 18, 'TRN-RT': 1, 'relay': 296}
  k-means: HF 281, LF 15, threshold 7.50 ms
  dip test (dip, p): {'relay': (0.0186, 0.7321), 'TRN': (0.0973, 0.1467), 'RS': (0.018, 0.824), 'FS': (0.0467, 0.7717)}
  relay ISI percentiles 5, 25, 50, 75, 95 (ms): [2.05 2.33 2.67 3.74 7.67]
  relay units with ISI above 17.88 ms: 10 of 296
  HF count and threshold under seeds +0, +1000, ..., +4000: [(281, np.float64(7.5)), (281, np.float64(7.5)), (281, np.float64(7.5)), (281, np.float64(7.5)), (281, np.float64(7.5))]
No description has been provided for this image
Plotted log10 ISI range: 0.25 to 1.93
In [26]:
# Variant: TRN also counts the units under 0.35 ms located in RT itself (TRN-RT)
for label, (isi, rel, thr) in res3b.items():
    col = "isi_late" if label.startswith("(a)") else "isi_reb"
    v = isi[isi.cls.isin(["TRN", "TRN-RT"])][col].to_numpy() * 1e3
    d, p = diptest.diptest(np.log10(v))
    print(f"{label}: TRN with RT units, {len(v)} units ({int((isi.cls == 'TRN-RT').sum())} from RT), dip {d:.4f}, p = {p:.4f}")
(a) 150-250 ms: TRN with RT units, 19 units (1 from RT), dip 0.0633, p = 0.7985
(b) 75-250 ms: TRN with RT units, 19 units (1 from RT), dip 0.0922, p = 0.1787

Result: not reproduced. The evoked ISI of the 296 relay units is not bimodal (dip test p = 0.73 for 150 to 250 ms, 0.64 for 75 to 250 ms); the median is 2.6 ms and only 8 units have an ISI above 17.88 ms. k-means splits off a small long-ISI group (HF 278, LF 18, threshold 6.9 ms; 281, 15 and 7.5 ms in the wider window). TRN, RS and FS are unimodal (p = 0.15 to 0.95), and TRN with the RT unit too (p = 0.80 and 0.18). The counts and threshold under the four other seeds are 277 to 281 and 6.6 to 7.5 ms. Every HF and LF claim below is tested on these groups: an LF group of 18 units (8 with the 17.88 ms threshold) from 4 mice, against 700 LF units in the paper.

figs11d-hf-earlier-less-variable¶

HF units respond earlier and with less latency variability than LF units in the early window (3 to 50 ms).

HF and LF as split in fig3b-bimodal-isi (reading (a) window; the paper's 17.88 ms threshold as a variant). Per unit, the median over trials of the first-spike latency in 3 to 50 ms and its SD. Readings (criterion): (a) per mouse medians, signed-rank on the mouse pairs; (b) rank-sum on unit values.

In [27]:
def hf_lf_groups(split):
    if split == "k-means (a)":
        rel = res3b["(a) 150-250 ms"][1]
        return rel.set_index(["subject", "unit"]).group
    rel = res3b["(a) 150-250 ms"][1].copy()
    rel["group"] = np.where(rel.isi_late * 1e3 < 17.88, "HF", "LF")
    return rel.set_index(["subject", "unit"]).group


rows = []
for split in ["k-means (a)", "17.88 ms"]:
    g = hf_lf_groups(split)
    d = H[H.cls == "relay"].groupby(["subject", "unit"]).lat_early.agg(["median", "std"]).join(g, how="inner")
    for meas in ["median", "std"]:
        hf, lf = d[d.group == "HF"][meas].dropna(), d[d.group == "LF"][meas].dropna()
        pm = d.groupby(["subject", "group"])[meas].median().unstack().dropna()
        rows.append({"split": split, "measure": "latency" if meas == "median" else "latency SD",
                     "HF_units": len(hf), "LF_units": len(lf), "HF_median_ms": hf.median() * 1e3, "LF_median_ms": lf.median() * 1e3,
                     "p_ranksum_units": stats.mannwhitneyu(hf, lf).pvalue if len(lf) and len(hf) else np.nan,
                     "mice_with_both": len(pm), "p_signedrank_mice": stats.wilcoxon(pm.HF, pm.LF).pvalue if len(pm) > 1 else np.nan,
                     "mice_HF_lower": int((pm.HF < pm.LF).sum())})
print(pd.DataFrame(rows).round(5).to_string(index=False))
      split    measure  HF_units  LF_units  HF_median_ms  LF_median_ms  p_ranksum_units  mice_with_both  p_signedrank_mice  mice_HF_lower
k-means (a)    latency       277        18       8.23611       6.68518          0.00017               4              0.875              1
k-means (a) latency SD       275        18       2.58599       3.48325          0.11725               4              0.125              4
   17.88 ms    latency       287         8       8.20158       6.68518          0.00786               2              0.500              0
   17.88 ms latency SD       285         8       2.59056       6.59716          0.10093               2              1.000              1

Result: not reproduced. With the k-means split HF units respond later than LF units in 3 to 50 ms (median 8.24 against 6.69 ms, rank-sum p = 0.00017), the reverse of the claim; their latency SD is lower (2.59 against 3.48 ms) but not significantly (p = 0.12). Per mouse only 4 mice have both groups (p = 0.88 and 0.125). The 17.88 ms split gives the same direction.

figs12-intensity-shifts-to-hf¶

Higher stimulation intensities recruit more responsive thalamic units and a larger share of HF relative to LF units, LF units shifting to HF as intensity increases.

Units classed HF or LF by the 17.88 ms threshold at each intensity, the ISI per unit computed at that intensity with the window of fig3b reading (a) (criterion).

In [28]:
R = U[U.responsive & (U.cls == "relay")]
isi_i = R.groupby(["intensity", "subject", "unit"]).isi_late.median().dropna().reset_index()
isi_i["HF"] = isi_i.isi_late * 1e3 < 17.88
tab = R.groupby("intensity").apply(lambda d: d.groupby(["subject", "unit"]).ngroups).rename("responsive_units").to_frame()
tab["units_with_isi"] = isi_i.groupby("intensity").size()
tab["HF_fraction"] = isi_i.groupby("intensity").HF.mean()
print(tab.loc[["low", "medium", "high"]].round(3).to_string())
pm12 = isi_i.groupby(["subject", "intensity"]).HF.mean().unstack()
print("\nHF fraction per mouse:")
print(pm12[["low", "medium", "high"]].round(3).to_string())
both = pm12[["low", "high"]].dropna()
print(f"Mice with units at low and high: {len(both)}; HF fraction higher at high than low in {int((both.high > both.low).sum())}, "
      f"equal in {int((both.high == both.low).sum())}")
print("\nRelay units with an evoked ISI behind each mouse's HF fraction:")
print(isi_i.groupby(["subject", "intensity"]).size().unstack(fill_value=0)[["low", "medium", "high"]].to_string())
           responsive_units  units_with_isi  HF_fraction
intensity                                               
low                      13              10        0.600
medium                  216             211        0.972
high                    303             296        0.973

HF fraction per mouse:
intensity    low  medium   high
subject                        
551397       NaN   0.917  0.900
551399       NaN     NaN  1.000
569062     0.833   1.000  1.000
569068       NaN   1.000  1.000
569069     0.000   1.000  1.000
569073     0.000   0.900  0.955
571619     1.000   1.000  1.000
Mice with units at low and high: 4; HF fraction higher at high than low in 3, equal in 1

Relay units with an evoked ISI behind each mouse's HF fraction:
intensity  low  medium  high
subject                     
551397       0      48    60
551399       0       0     1
569062       6      96   117
569068       0       1    13
569069       2      34    42
569073       1      20    44
571619       1      12    19

Result: reproduced. Responsive relay units increase from 13 (low) to 216 (medium) to 303 (high), and the HF fraction from 0.600 to 0.972 to 0.973; per mouse the HF fraction is higher at high than at low intensity in 3 of the 4 mice with units at both. The increase from medium to high is 0.001, and the low-intensity value rests on 10 units: 6, 2, 1 and 1 in the four mice.

fig3e-baseline-rate-doubles¶

During running the baseline firing rate of thalamic relay units almost doubles (6.78 +- 4.4 Hz at rest, 12.48 +- 4.6 Hz active), for both HF and LF units.

Baseline rate per unit and trial: spikes in -1 to -0.01 s over 0.99 s, responsive relay units at high intensity, HF and LF as split in fig3b-bimodal-isi (k-means, reading (a)); the 17.88 ms threshold is a variant. Readings (criterion): (a) per trial, the mean over the group's units, rest against active trials pooled over sessions, rank-sum, Bonferroni over HF and LF; the mean and SD are over the HF and LF trial values pooled; (b) per unit, mean over rest and active trials, signed-rank.

In [29]:
def grouped(split):
    g = hf_lf_groups(split).rename("group")
    return H[H.cls == "relay"].join(g, on=["subject", "unit"], how="inner")


def per_trial(df, func):
    """Per session, trial and group: a value over the group's units in that trial."""
    return df.groupby(["subject", "trial", "group", "active"]).apply(func).rename("v").dropna().reset_index()


def feature_tests(pt, pu=None, bonf=2):
    rows = []
    for grp in ["HF", "LF"]:
        d = pt[pt.group == grp]
        rest, act = d[~d.active].v, d[d.active].v
        p = stats.mannwhitneyu(rest, act).pvalue if len(rest) and len(act) else np.nan
        row = {"group": grp, "trials_rest": len(rest), "trials_active": len(act), "rest_mean": rest.mean(), "rest_sd": rest.std(),
               "active_mean": act.mean(), "active_sd": act.std(), "p_ranksum_trials_bonf": min(1, p * bonf)}
        if pu is not None:
            u = pu[pu.group == grp]
            w = stats.wilcoxon(u[False], u[True]) if len(u) > 1 else None
            row.update({"units_or_mice": len(u), "rest_med_b": u[False].median(), "active_med_b": u[True].median(),
                        "p_signedrank_b_bonf": min(1, w.pvalue * bonf) if w else np.nan})
        rows.append(row)
    return pd.DataFrame(rows)


for split in ["k-means (a)", "17.88 ms"]:
    G = grouped(split)
    pt = per_trial(G, lambda d: d.rate_base.mean())
    pu = G.groupby(["group", "subject", "unit", "active"]).rate_base.mean().unstack().dropna().reset_index()
    print(f"HF/LF split: {split}")
    print(feature_tests(pt, pu).round(5).to_string(index=False))
    both = pt.groupby("active").v.agg(["mean", "std", "size"])
    print("HF and LF trial values pooled (Hz): rest %.2f +- %.2f (n %d), active %.2f +- %.2f (n %d); paper 6.78 +- 4.4 and 12.48 +- 4.6"
          % (both.loc[False, "mean"], both.loc[False, "std"], both.loc[False, "size"], both.loc[True, "mean"], both.loc[True, "std"], both.loc[True, "size"]))
    allu = per_trial(H[H.cls == "relay"].assign(group="all"), lambda d: d.rate_base.mean())
    print("All responsive relay units, per trial (Hz): rest %.2f, active %.2f\n" % (allu[~allu.active].v.mean(), allu[allu.active].v.mean()))
HF/LF split: k-means (a)
group  trials_rest  trials_active  rest_mean  rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          681            150    5.19574  3.59215     12.45203    4.60089                    0.0            278     3.80366      11.07504              0.00000
   LF          369            102    9.82873  6.68476     17.74697    9.36848                    0.0             18    12.75685      21.71717              0.00002
HF and LF trial values pooled (Hz): rest 6.82 +- 5.38 (n 1050), active 14.60 +- 7.39 (n 252); paper 6.78 +- 4.4 and 12.48 +- 4.6
All responsive relay units, per trial (Hz): rest 5.42, active 12.63

HF/LF split: 17.88 ms
group  trials_rest  trials_active  rest_mean  rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          681            150    5.33251  3.62728     12.63894    4.61827                    0.0            288     3.80366      11.21332              0.00000
   LF          197             36   15.73262  6.96761     26.23457    9.10964                    0.0              8    13.60386      26.05219              0.01562
HF and LF trial values pooled (Hz): rest 7.67 +- 6.32 (n 878), active 15.27 +- 7.87 (n 186); paper 6.78 +- 4.4 and 12.48 +- 4.6
All responsive relay units, per trial (Hz): rest 5.42, active 12.63

Result: reproduced. Per trial, the baseline rate of relay units rises from 6.82 +- 5.38 Hz at rest to 14.60 +- 7.39 Hz during running (HF and LF trial values pooled; paper 6.78 +- 4.4 and 12.48 +- 4.6), both within tolerance, and both HF (5.20 to 12.45 Hz) and LF (9.83 to 17.75 Hz) rise with corrected p < 1e-5. Per unit the same holds (p < 0.0001). With the 17.88 ms split the active mean is 15.27 Hz, also within tolerance.

fig3e-lf-synchrony-reduced¶

During running the rebound onset variability (ROV) of LF units increases (35.7 +- 11.8 to 40.7 +- 8.2 ms), a loss of synchrony, while the ROV of HF units does not change.

ROV per trial: the SD across the group's units of the first-spike latency, in (a) 150 to 250 ms (Methods) or (b) 75 to 250 ms (code); trials with at least two units firing. Unit of test (criterion): per trial, rank-sum (Bonferroni over HF and LF); per mouse, the mean ROV of its rest and active trials, signed-rank.

In [30]:
def rov(col):
    return lambda d: d[col].std() * 1e3 if d[col].notna().sum() >= 2 else np.nan


for split in ["k-means (a)", "17.88 ms"]:
    G = grouped(split)
    for label, col in [("(a) 150-250 ms", "lat_late"), ("(b) 75-250 ms", "lat_reb")]:
        pt = per_trial(G, rov(col))
        pm = pt.groupby(["group", "subject", "active"]).v.mean().unstack().dropna().reset_index()
        print(f"split {split}, window {label} (ms)")
        print(feature_tests(pt, pm).round(5).to_string(index=False))
        print()
split k-means (a), window (a) 150-250 ms (ms)
group  trials_rest  trials_active  rest_mean  rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          563            134   26.95022  7.71263     26.96724    6.28800                      1              6    27.32800      28.28809                    1
   LF          235             61   26.32283 14.66035     25.78208   10.35455                      1              4    24.61566      26.95587                    1

split k-means (a), window (b) 75-250 ms (ms)
group  trials_rest  trials_active  rest_mean  rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          573            136   31.72003  9.10294     31.92873    8.06763                1.00000              6    32.18323      33.41389               0.4375
   LF          257             74   44.32266 24.94598     57.82821   21.98919                0.00004              4    36.22598      48.42406               0.2500

split 17.88 ms, window (a) 150-250 ms (ms)
group  trials_rest  trials_active  rest_mean  rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          563            134   26.99312  7.65881     27.13460    6.11385                1.00000              6    27.29955      28.72931                0.875
   LF           97             25   25.31853 13.79079     27.84488    8.95108                0.62642              2    21.05902      22.75559                1.000

split 17.88 ms, window (b) 75-250 ms (ms)
group  trials_rest  trials_active  rest_mean  rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          573            136   32.43141  8.72114     32.96598    7.40487                0.86442              6    32.47022      33.51556               0.3125
   LF          100             27   41.67060 21.03000     46.62174   19.01034                0.52830              2    34.84970      48.52261               1.0000

Result: not reproduced. No reading meets the criterion. In 75 to 250 ms with the k-means split the LF onset variability rises during running (44.3 to 57.8 ms, per-trial rank-sum corrected p = 4e-05) and the HF one does not (31.7 and 31.9, p = 1), but the active LF mean, 57.8 ms, is outside 40.7 +- 8.2 ms. In 150 to 250 ms LF does not change (26.3 and 25.8 ms, p = 1), nor with the paper's 17.88 ms split in either window. Per mouse (4 mice with LF units) no change is significant. The LF group has 18 units.

fig3e-hf-frequency-reduced¶

During running the late response frequency of HF units falls (309 +- 126 to 241 +- 116 Hz), while that of LF units does not change significantly.

Response frequency: per trial, the median ISI across the group's units, inverted (code, criterion); windows as in fig3e-lf-synchrony-reduced. Unit of test: per trial, rank-sum; per unit, the mean frequency over rest and over active trials, signed-rank.

In [31]:
for split in ["k-means (a)", "17.88 ms"]:
    G = grouped(split)
    for label, col in [("(a) 150-250 ms", "isi_late"), ("(b) 75-250 ms", "isi_reb")]:
        pt = per_trial(G, lambda d: 1.0 / d[col].median() if d[col].notna().any() else np.nan)
        pu = (1.0 / G[col]).groupby([G.group, G.subject, G.unit, G.active]).mean().unstack().dropna().reset_index()
        print(f"split {split}, window {label} (Hz)")
        print(feature_tests(pt, pu).round(5).to_string(index=False))
        print()
split k-means (a), window (a) 150-250 ms (Hz)
group  trials_rest  trials_active  rest_mean   rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          615            143  369.39509  99.84456    268.44282  130.78128                0.00000            273   363.12402     286.71240              0.00000
   LF          227             68   94.09546 100.38824    102.15712  101.85187                0.55155             15   103.44777      63.62683              0.97742

split k-means (a), window (b) 75-250 ms (Hz)
group  trials_rest  trials_active  rest_mean   rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          632            149  370.21545 101.23188    278.55538  132.87572                    0.0            275   361.02146     290.76841                  0.0
   LF          272             77  101.48154  98.34055     89.93590   81.30276                    1.0             17   116.45938      84.27988                  1.0

split 17.88 ms, window (a) 150-250 ms (Hz)
group  trials_rest  trials_active  rest_mean   rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          615            143  365.34588 101.58413    261.19590  130.90618                0.00000            281   361.15766     283.58079                  0.0
   LF          136             31   66.58179  99.24759     77.31121   98.68996                0.05502              7    49.13911      53.65413                  1.0

split 17.88 ms, window (b) 75-250 ms (Hz)
group  trials_rest  trials_active  rest_mean   rest_sd  active_mean  active_sd  p_ranksum_trials_bonf  units_or_mice  rest_med_b  active_med_b  p_signedrank_b_bonf
   HF          632            149  365.95241 102.11928    272.15771  131.95178                0.00000            285   359.28226     288.70939               0.0000
   LF          164             34   90.36604 108.21977    102.92270  118.71975                0.30232              7    61.67655      80.07671               0.4375

Result: reproduced. Per trial, the response frequency of HF units falls from 369 +- 100 Hz at rest to 268 +- 131 Hz during running (150 to 250 ms; paper 309 +- 126 and 241 +- 116), both within tolerance, with corrected p < 1e-5, while LF does not change (94 and 102 Hz, p = 0.55). The same holds in 75 to 250 ms (370 and 279 Hz) and per unit.

figs13-thalamic-features-predict-eeg¶

On single trials, baseline thalamic rate predicts HF response frequency and LF onset variability, and the late EEG amplitude is predicted by ROV of HF and LF units and by HF response frequency, but not by LF response frequency.

Per trial at high intensity: the HF and LF features of the two claims above (window (a), k-means split), the group's baseline rate, and the single-trial EEG late amplitude (mean over valid channels of |EEG| in 150 to 250 ms). Models from the Methods with statsmodels mixedlm; readings (a) raw values, (b) the code's transforms (log of the EEG amplitude and of the frequencies, every term centred).

In [32]:
G = grouped("k-means (a)")
feat = {}
for grp in ["HF", "LF"]:
    d = G[G.group == grp]
    gb = d.groupby(["subject", "trial"])
    feat[f"Base{grp}"] = gb.rate_base.mean()
    feat[f"ROV{grp}"] = gb.lat_late.apply(lambda x: x.std() * 1e3 if x.notna().sum() >= 2 else np.nan)
    feat[f"Freq{grp}"] = gb.isi_late.apply(lambda x: 1.0 / x.median() if x.notna().any() else np.nan)
F13 = pd.DataFrame(feat)
eeg_amp = pd.concat({r["subject"]: pd.Series(r["eeg_single_late"]) for r in S.values()}, names=["subject", "trial"])
F13["EEG"] = eeg_amp.reindex(F13.index)
F13 = F13.reset_index()


def fit13(df, formula, transform):
    d = df.copy()
    if transform:
        for c in ["EEG", "FreqHF", "FreqLF"]:
            if c in d:
                d[c] = np.log(d[c])
        for c in d.columns:
            if c not in ("subject", "trial"):
                d[c] = d[c] - d[c].mean()
    return smf.mixedlm(formula, d, groups=d["subject"]).fit()


rows = []
expect = {("ROVHF", "BaseHF"): False, ("FreqHF", "BaseHF"): True, ("ROVLF", "BaseLF"): True, ("FreqLF", "BaseLF"): False,
          ("EEG", "ROVHF"): True, ("EEG", "FreqHF"): True, ("EEG", "ROVLF"): True, ("EEG", "FreqLF"): False}
for transform in [False, True]:
    for y, x in [("ROVHF", "BaseHF"), ("FreqHF", "BaseHF"), ("ROVLF", "BaseLF"), ("FreqLF", "BaseLF")]:
        d = F13.dropna(subset=[y, x])
        f = fit13(d[["subject", "trial", y, x]], f"{y} ~ {x}", transform)
        rows.append({"reading": "(b) code transforms" if transform else "(a) raw", "model": f"{y} ~ {x}", "term": x, "trials": len(d),
                     "mice": d.subject.nunique(), "coef": f.params[x], "p": f.pvalues[x], "paper_significant": expect[(y, x)]})
    d = F13.dropna(subset=["EEG", "ROVHF", "FreqHF", "ROVLF", "FreqLF"])
    if len(d) > 10 and d.subject.nunique() > 1:
        f = fit13(d[["subject", "trial", "EEG", "FreqHF", "ROVHF", "FreqLF", "ROVLF"]], "EEG ~ FreqHF + ROVHF + FreqLF + ROVLF", transform)
        for x in ["ROVHF", "FreqHF", "ROVLF", "FreqLF"]:
            rows.append({"reading": "(b) code transforms" if transform else "(a) raw", "model": "EEG ~ FreqHF + ROVHF + FreqLF + ROVLF", "term": x,
                         "trials": len(d), "mice": d.subject.nunique(), "coef": f.params[x], "p": f.pvalues[x], "paper_significant": expect[("EEG", x)]})
    else:
        print(f"EEG model not fitted: {len(d)} trials with all four features from {d.subject.nunique()} mice")
r13 = pd.DataFrame(rows)
r13["matches_paper"] = (r13.p < 0.05) == r13.paper_significant
print(r13.round(5).to_string(index=False))
print("\nTrials with each feature:", F13[["ROVHF", "FreqHF", "ROVLF", "FreqLF", "EEG"]].notna().sum().to_dict())
            reading                                 model   term  trials  mice     coef       p  paper_significant  matches_paper
            (a) raw                        ROVHF ~ BaseHF BaseHF     697     6  0.11500 0.08498              False           True
            (a) raw                       FreqHF ~ BaseHF BaseHF     758     7 -7.35080 0.00000               True           True
            (a) raw                        ROVLF ~ BaseLF BaseLF     296     4 -0.05408 0.64811               True          False
            (a) raw                       FreqLF ~ BaseLF BaseLF     295     4 -1.97221 0.01271              False          False
            (a) raw EEG ~ FreqHF + ROVHF + FreqLF + ROVLF  ROVHF     262     3  0.02843 0.96355               True          False
            (a) raw EEG ~ FreqHF + ROVHF + FreqLF + ROVLF FreqHF     262     3  0.18598 0.00000               True           True
            (a) raw EEG ~ FreqHF + ROVHF + FreqLF + ROVLF  ROVLF     262     3  0.94669 0.00000               True           True
            (a) raw EEG ~ FreqHF + ROVHF + FreqLF + ROVLF FreqLF     262     3  0.01399 0.58198              False           True
(b) code transforms                        ROVHF ~ BaseHF BaseHF     697     6  0.11500 0.08498              False           True
(b) code transforms                       FreqHF ~ BaseHF BaseHF     758     7 -0.03360 0.00000               True           True
(b) code transforms                        ROVLF ~ BaseLF BaseLF     296     4 -0.05408 0.64811               True          False
(b) code transforms                       FreqLF ~ BaseLF BaseLF     295     4 -0.02019 0.00354              False          False
(b) code transforms EEG ~ FreqHF + ROVHF + FreqLF + ROVLF  ROVHF     262     3 -0.00064 0.91577               True          False
(b) code transforms EEG ~ FreqHF + ROVHF + FreqLF + ROVLF FreqHF     262     3  0.44104 0.00000               True           True
(b) code transforms EEG ~ FreqHF + ROVHF + FreqLF + ROVLF  ROVLF     262     3  0.00836 0.00000               True           True
(b) code transforms EEG ~ FreqHF + ROVHF + FreqLF + ROVLF FreqLF     262     3  0.02945 0.30276              False           True

Trials with each feature: {'ROVHF': 697, 'FreqHF': 758, 'ROVLF': 296, 'FreqLF': 295, 'EEG': 831}

Result: not reproduced. Five of the eight effects match the paper's pattern under both readings: baseline rate predicts HF frequency (p < 1e-5) and not HF ROV (p = 0.085); the EEG amplitude is predicted by HF frequency and LF ROV (p < 1e-5) and not LF frequency (p = 0.58 and 0.30). Baseline rate does not predict LF ROV (p = 0.65) and does predict LF frequency (p = 0.013 and 0.0035), and HF ROV does not predict the EEG (p = 0.96 and 0.92). The LF features rest on 4 mice and the EEG model on 262 trials from 3 mice.

figs13d-lf-crosscorrelation¶

Cross-correlation between LF thalamic units differs between rest and running, while that between HF units does not.

Per pair of units of the same group in a session (k-means split), in the late window: 2 ms bins of the absolute delays between their spikes on the same trial, divided by the number of seed spikes; the value is the mean of the first five bins (Methods). Rest and active per pair, signed-rank. Window (a) 150 to 250 ms or (b) 75 to 250 ms.

In [33]:
grp = hf_lf_groups("k-means (a)")
rows = []
for r in S.values():
    if not r.get("has_probes"):
        continue
    t = r["trials"]
    ok = ((t.intensity == "high") & t.is_valid).to_numpy()
    uid = r["units"].unit_id
    members = {}
    for i, (rel, trial) in r["spikes"].items():
        key = (r["subject"], int(uid.loc[i]))
        if key in grp.index:
            members.setdefault(grp.loc[key], []).append((rel, trial))
    for g, us in members.items():
        for wl, win in [("(a)", russo.LATE), ("(b)", russo.REBOUND)]:
            per = []
            for rel, trial in us:
                m = (rel >= win[0]) & (rel < win[1])
                per.append([rel[m & (trial == k)] for k in range(len(t))])
            for a in range(len(us)):
                for b in range(a + 1, len(us)):
                    v = {}
                    for st in ["rest", "active"]:
                        sel = ok & (t.active == (st == "active")).to_numpy()
                        idx = np.nonzero(sel)[0]
                        v[st] = russo.crosscorr_value([per[a][k] for k in idx], [per[b][k] for k in idx])
                    rows.append({"subject": r["subject"], "group": g, "window": wl, **v})
cc = pd.DataFrame(rows).dropna()
out = []
for (g, wl), d in cc.groupby(["group", "window"]):
    w = stats.wilcoxon(d.rest, d.active) if len(d) > 1 else None
    out.append({"group": g, "window": wl, "pairs": len(d), "mice": d.subject.nunique(), "rest_median": d.rest.median(),
                "active_median": d.active.median(), "rest_larger": int((d.rest > d.active).sum()), "p": w.pvalue if w else np.nan})
print(pd.DataFrame(out).round(5).to_string(index=False))
group window  pairs  mice  rest_median  active_median  rest_larger       p
   HF    (a)   9588     6      0.06923        0.05161         5928 0.00000
   HF    (b)   9588     6      0.07251        0.07614         4494 0.00000
   LF    (a)     48     4      0.05508        0.07165           16 0.00654
   LF    (b)     48     4      0.06013        0.08530           15 0.00556

Result: not reproduced. LF pairs (48 pairs, 4 mice) differ between states (p = 0.0065), but they are more correlated during running (rest larger in 16 of 48), the reverse of the criterion's direction, and HF pairs (9588 pairs) also differ (p < 1e-5) in both windows.

discussion-orthodromic-initial-excitation¶

The first-spike latency of the initial response is more variable in SM-TH than in MOs, and does not differ between SM-TH nuclei and TRN.

Per responsive unit at high intensity, the median and SD over trials of the first-spike latency in 3 to 50 ms. SM-TH are the relay units, MOs all responsive MOs units (RS and FS), TRN the thalamic units under 0.35 ms. Readings (criterion): (a) rank-sum on unit values; (b) signed-rank on per-mouse medians for mice with units in both groups.

In [34]:
d = H.copy()
d["grp"] = d.cls.replace({"relay": "SM-TH", "RS": "MOs", "FS": "MOs"})
pu = d.groupby(["grp", "subject", "unit"]).lat_early.agg(["median", "std"]).reset_index()
rows = []
for meas, g1, g2 in [("std", "SM-TH", "MOs"), ("median", "SM-TH", "TRN")]:
    a, b = pu[pu.grp == g1][meas].dropna(), pu[pu.grp == g2][meas].dropna()
    pm = pu.groupby(["subject", "grp"])[meas].median().unstack()[[g1, g2]].dropna()
    rows.append({"measure": "latency SD" if meas == "std" else "latency", "groups": f"{g1} vs {g2}", "units": f"{len(a)} / {len(b)}",
                 "median_1_ms": a.median() * 1e3, "median_2_ms": b.median() * 1e3, "p_ranksum": stats.mannwhitneyu(a, b).pvalue,
                 "mice": len(pm), "p_signedrank_mice": stats.wilcoxon(pm[g1], pm[g2]).pvalue if len(pm) > 1 else np.nan,
                 "mice_1_larger": int((pm[g1] > pm[g2]).sum())})
print(pd.DataFrame(rows).round(5).to_string(index=False))
   measure       groups     units  median_1_ms  median_2_ms  p_ranksum  mice  p_signedrank_mice  mice_1_larger
latency SD SM-TH vs MOs 298 / 362      2.55196      1.27596    0.00000     7            0.01562              7
   latency SM-TH vs TRN  301 / 18      8.10341     10.39646    0.07299     6            0.43750              3
In [35]:
# Variant: TRN also counts the units under 0.35 ms located in RT itself (TRN-RT)
d = H.copy()
d["grp"] = d.cls.replace({"relay": "SM-TH", "RS": "MOs", "FS": "MOs", "TRN-RT": "TRN"})
pu = d.groupby(["grp", "subject", "unit"]).lat_early.agg(["median", "std"]).reset_index()
a, b = pu[pu.grp == "SM-TH"]["median"].dropna(), pu[pu.grp == "TRN"]["median"].dropna()
pm = pu.groupby(["subject", "grp"])["median"].median().unstack()[["SM-TH", "TRN"]].dropna()
print(f"Latency, SM-TH relay against TRN with RT units: {len(a)} / {len(b)} units, medians {a.median() * 1e3:.2f} and "
      f"{b.median() * 1e3:.2f} ms, rank-sum p = {stats.mannwhitneyu(a, b).pvalue:.4f}; {len(pm)} mice, "
      f"signed-rank p = {stats.wilcoxon(pm['SM-TH'], pm['TRN']).pvalue:.4f}")
Latency, SM-TH relay against TRN with RT units: 301 / 19 units, medians 8.10 and 10.24 ms, rank-sum p = 0.0496; 6 mice, signed-rank p = 0.4375

Result: reproduced. The first-spike latency in 3 to 50 ms is more variable in SM-TH relay units than in MOs units (median SD 2.55 against 1.28 ms, rank-sum p < 1e-5; higher in 7 of 7 mice, p = 0.016), and the latency of SM-TH relay and TRN units does not differ (8.10 against 10.40 ms, p = 0.073; per mouse p = 0.44). With the RT unit added to TRN the rank-sum on units gives p = 0.0496 (8.10 against 10.24 ms) and the per-mouse test p = 0.44, so the claim holds under reading (b) with either TRN class.

source-data-link¶

The dandiset holds the mouse sessions behind the paper's Figure 1C and Figure 2B, so that values computed from it agree with the per-session and per-subject values in the paper's Source Data file.

No identifier links the Source Data rows to sessions, so the distributions are compared (criterion): the session count of Figure 1C (26 +- 3), its two medians (within 10%), and the five Figure 2B means (at least four within 10%), computed with the methods of fig1c and fig2b. The Source Data file is read from the publisher's site and checked against its SHA-256.

In [36]:
SOURCE_DATA_URL = ("https://static-content.springer.com/esm/art%3A10.1038%2Fs41467-025-58717-2/"
                   "MediaObjects/41467_2025_58717_MOESM4_ESM.xlsx")
SOURCE_DATA_SHA256 = "5feebc5a6c6ced1441d0a74af35c7b18e1c2064f1e633f88c74ab0cd8689d0f7"
raw = requests.get(SOURCE_DATA_URL, timeout=120).content
print("Source Data SHA-256 matches:", hashlib.sha256(raw).hexdigest() == SOURCE_DATA_SHA256, f"({len(raw)} bytes)")
xl = pd.ExcelFile(io.BytesIO(raw))


def paired_sheet(name):
    """Sheets with one value per subject: the two value columns below their header row."""
    d = pd.read_excel(xl, sheet_name=name, header=None)
    hdr = d.index[d.iloc[:, 1:].notna().sum(1) >= 2][0]
    cols = [c for c in d.columns[1:] if pd.notna(d.loc[hdr, c])]
    out = d.loc[hdr + 1:, cols].astype(float).dropna(how="all")
    out.columns = [str(d.loc[hdr, c]).strip() for c in cols]
    return out.reset_index(drop=True)


def box_sheet(name):
    """Box-plot sheets: for each block (title in row 1), rows are states and columns Min .. Max."""
    d = pd.read_excel(xl, sheet_name=name, header=None)
    out = {}
    titles = [(c, str(d.iloc[1, c])) for c in d.columns if pd.notna(d.iloc[1, c])]
    for c, title in titles:
        lab_col = c - 1
        rows = {}
        for i in range(5, len(d)):
            lab = d.iloc[i, lab_col]
            if pd.notna(lab):
                rows[str(lab).strip()] = d.iloc[i, c:c + 5].astype(float).to_numpy()
        out[title] = pd.DataFrame(rows, index=["min", "q25", "median", "q75", "max"]).T
    return out


sd1c = paired_sheet("Figure 1 C")
sd2b = pd.read_excel(xl, sheet_name="Figure 2 B", header=2).iloc[:, 1:]
print("Figure 1 C: %d pairs, medians rest %.1f, active %.1f uV" % (len(sd1c), sd1c.iloc[:, 0].median(), sd1c.iloc[:, 1].median()))
print("Figure 2 B: per-subject latencies, n and mean (ms):", {c: (int(sd2b[c].notna().sum()), round(sd2b[c].mean() * 1e3, 1)) for c in sd2b.columns})

rows = []
for label, (intens, chan) in READINGS.items():
    t = state_table("eeg", intens, chan=chan).dropna(subset=["rest", "active"])
    rows.append({"reading": label, "sessions": len(t), "rest_median": t.rest.median(), "active_median": t.active.median(),
                 "rest_vs_SD_%": 100 * (t.rest.median() / sd1c.iloc[:, 0].median() - 1),
                 "active_vs_SD_%": 100 * (t.active.median() / sd1c.iloc[:, 1].median() - 1)})
print("\nFigure 1C part:")
print(pd.DataFrame(rows).round(2).to_string(index=False))

# Figure 2B part: per mouse, mean latency over all high-intensity valid trials (both states)
per_mouse = {}
for r in S.values():
    if not r.get("has_probes"):
        continue
    t = r["trials"]
    hi = ((t.intensity == "high") & t.is_valid).to_numpy()
    vals = {"EEG (s)": np.nanmean(r["eeg_lat"][hi]), "LFP (s)": np.nanmean(r["lfp_lat"][hi]), "CSD (s)": np.nanmean(r["csd_lat"][hi])}
    for name, cls in [("SM-TH (s)", "relay"), ("MOs (s)", "RS")]:
        s = trial_unit_latency(cls)
        if r["subject"] in s.index.get_level_values(0):
            v = s.loc[r["subject"]].reindex(range(len(t)))[hi]
            vals[name] = v.mean()
    per_mouse[r["subject"]] = vals
pm2b = pd.DataFrame(per_mouse).T
cmp = pd.DataFrame({"mice": pm2b.notna().sum(), "this_mean_ms": pm2b.mean() * 1e3, "SD_n": sd2b.notna().sum(),
                    "SD_mean_ms": sd2b.mean() * 1e3})
cmp["diff_%"] = 100 * (cmp.this_mean_ms / cmp.SD_mean_ms - 1)
print("\nFigure 2B part:")
print(cmp.round(2).to_string())
print("Within 10%:", int((cmp["diff_%"].abs() <= 10).sum()), "of 5")
Source Data SHA-256 matches: True (347792 bytes)
Figure 1 C: 26 pairs, medians rest 97.9, active 67.7 uV
Figure 2 B: per-subject latencies, n and mean (ms): {'SM-TH (s)': (20, np.float64(153.8)), 'MOs (s)': (15, np.float64(170.7)), 'CSD (s)': (12, np.float64(173.8)), 'LFP (s)': (13, np.float64(170.1)), 'EEG (s)': (13, np.float64(171.3))}

Figure 1C part:
                                reading  sessions  rest_median  active_median  rest_vs_SD_%  active_vs_SD_%
   (a)(i) high, all channels and trials        10        81.70          42.55        -16.52          -37.17
(a)(ii) high, valid channels and trials        10        84.48          36.27        -13.67          -46.45
            (b)(i) high and medium, all        20        69.19          29.17        -29.30          -56.94
         (b)(ii) high and medium, valid        20        65.38          27.26        -33.19          -59.75

Figure 2B part:
           mice  this_mean_ms  SD_n  SD_mean_ms  diff_%
CSD (s)       9        170.31    12      173.76   -1.99
EEG (s)       9        173.44    13      171.31    1.24
LFP (s)       9        169.94    13      170.15   -0.12
MOs (s)       9        171.79    15      170.66    0.66
SM-TH (s)     7        168.52    20      153.84    9.54
Within 10%: 5 of 5

Result: partially reproduced. The Figure 2B part holds: the five mean latencies are within 10% of the Source Data means (-2.0 to +9.5%). The Figure 1C part does not: the dandiset holds 10 deep MOs sessions (20 with high and medium), against 26 in the Source Data, and the medians are 16.5% (rest) and 37.2% (active) below the Source Data medians at high intensity.

Human claims on the Source Data file¶

The human recordings are not public. The claims below are tested, as their criteria say, on the per-subject values or box-plot summaries in the paper's Source Data file (data: elsewhere).

fig1a-tms-late-rest-active¶

In 12 healthy subjects, the late (150 to 250 ms) TMS-evoked EEG response over premotor channels has a larger rectified amplitude and phase locking at rest than during active hand squeezing (amplitude 1.37 +- 0.59 against 0.77 +- 0.22 uV; PLF 0.21 +- 0.07 against 0.15 +- 0.05).

In [37]:
a1 = paired_sheet("Figure 1 A")
rest, act = a1.iloc[:, 0], a1.iloc[:, 1]
w = stats.wilcoxon(rest, act)
print(f"Figure 1 A: {len(a1)} subjects; rest {rest.mean():.3f} +- {rest.std():.3f} uV, active {act.mean():.3f} +- {act.std():.3f} uV; "
      f"rest larger in {int((rest > act).sum())}; two-sided signed-rank p = {w.pvalue:.4g} (paper 0.002)")
print(f"Within tolerance: rest |{rest.mean():.3f} - 1.37| <= 0.59: {abs(rest.mean() - 1.37) <= 0.59}; "
      f"active |{act.mean():.3f} - 0.77| <= 0.22: {abs(act.mean() - 0.77) <= 0.22}")
s1a = box_sheet("Figure S1A")
for k, v in s1a.items():
    print(f"\nFigure S1A, {k}:")
    print(v.to_string())
Figure 1 A: 12 subjects; rest 1.379 +- 0.588 uV, active 0.771 +- 0.223 uV; rest larger in 12; two-sided signed-rank p = 0.0004883 (paper 0.002)
Within tolerance: rest |1.379 - 1.37| <= 0.59: True; active |0.771 - 0.77| <= 0.22: True

Figure S1A, TMS-EEG [-]:
         min    q25  median    q75    max
Rest    0.08  0.185   0.215  0.275  0.300
Active  0.05  0.130   0.165  0.180  0.195

Figure S1A, SPES-LFP [-]:
          min   q25  median    q75    max
Rest    0.305  0.43   0.515  0.605  0.725
Active  0.290  0.40   0.440  0.515  0.680

Result: reproduced. The 12 Source Data pairs give 1.379 +- 0.588 uV at rest and 0.771 +- 0.223 uV active, within the paper's values, rest larger in 12 of 12 (two-sided signed-rank p = 0.00049; paper 0.002). The PLF medians are 0.215 at rest and 0.165 active; the PLF test cannot be rerun from the box-plot summary.

fig1b-ieeg-late-rest-active¶

In 5 epilepsy patients, the late (150 to 250 ms) iEEG response to single-pulse electrical stimulation of premotor cortex is smaller in rectified amplitude and PLF during active hand squeezing than at rest.

In [38]:
b1 = paired_sheet("Figure 1 B")
rest, act = b1.iloc[:, 0], b1.iloc[:, 1]
print(f"Figure 1 B: {len(b1)} subjects; rest mean {rest.mean():.3f}, active {act.mean():.3f} (z); "
      f"active lower in {int((act < rest).sum())} of {len(b1)}; differences {np.round((rest - act).to_numpy(), 3).tolist()}")
print(f"Signed-rank on the 5 pairs (not the paper's test): p = {stats.wilcoxon(rest, act).pvalue:.4f}")
iplf = [v for k, v in s1a.items() if "SPES" in k][0]
print(f"Figure S1A iEEG PLF medians: rest {iplf.loc['Rest', 'median']}, active {iplf.loc['Active', 'median']}")
Figure 1 B: 5 subjects; rest mean 5.279, active 3.946 (z); active lower in 5 of 5; differences [1.961, 0.6, 2.994, 0.978, 0.131]
Signed-rank on the 5 pairs (not the paper's test): p = 0.0625
Figure S1A iEEG PLF medians: rest 0.515, active 0.44

Result: reproduced. Active is lower than rest in 5 of 5 subjects (means 5.28 and 3.95 z), and the iEEG PLF medians are 0.515 at rest and 0.44 active. The paper's mixed model on contacts cannot be rerun from the public values.

figs2-tms-controls¶

The TMS late-component modulation is also seen with passive hand movement and with leg cycling, is absent for posterior TMS, is absent for median nerve somatosensory evoked potentials, and does not differ between hand closing and opening.

In [39]:
g = paired_sheet("Figure S2G")
w = stats.wilcoxon(g.iloc[:, 0], g.iloc[:, 1])
print(f"Figure S2G: {len(g)} subjects, columns {list(g.columns)}; means {g.mean().round(3).to_dict()}; "
      f"two-sided signed-rank p = {w.pvalue:.4f} (paper 0.57)")
late = {}
for sheet in ["Figure S2A", "Figure S2C", "Figure S2D", "Figure S2E"]:
    b = box_sheet(sheet)
    k = [t for t in b if t.lower().startswith("late rect")][0]
    late[sheet] = b[k]["median"]
    print(f"{sheet}, late rectified amplitude medians: {b[k]['median'].to_dict()}")
print("S2A passive median below rest:", late["Figure S2A"]["Passive"] < late["Figure S2A"]["Rest"],
      "; S2C cycling median below rest:", late["Figure S2C"]["Cycling"] < late["Figure S2C"]["Rest"])
Figure S2G: 12 subjects, columns ['Relaxation', 'Contraction']; means {'Relaxation': 0.443, 'Contraction': 0.477}; two-sided signed-rank p = 0.6069 (paper 0.57)
Figure S2A, late rectified amplitude medians: {'Rest': 1.2, 'Active': 0.8, 'Passive': 0.65}
Figure S2C, late rectified amplitude medians: {'Rest': 0.8, 'Cycling': 0.62}
Figure S2D, late rectified amplitude medians: {'Rest': 0.75, 'Active': 0.6, 'Passive': 0.6}
Figure S2E, late rectified amplitude medians: {'Rest': 0.75, 'Active': 0.8, 'Passive': 0.65}
S2A passive median below rest: True ; S2C cycling median below rest: True

Result: reproduced, as far as the public data allow. Contraction and relaxation do not differ (12 pairs, p = 0.61; paper 0.57), and the late amplitude median at rest (1.2 and 0.8 uV) exceeds the passive (0.65) and cycling (0.62) medians. The absence of modulation for posterior TMS and SSEP is not testable from the box-plot summaries (medians rest 0.75, active 0.6; and 0.75, 0.8).

figs2a-tms-early-component¶

The early (3 to 50 ms) TMS-evoked component is reduced in amplitude during active movement but not in phase locking (2.24 +- 0.45 against 1.88 +- 0.32 uV; PLF 0.43 in both), and its reduction is not correlated with that of the late component.

In [40]:
b = box_sheet("Figure S2A")
early = b[[t for t in b if t.lower().startswith("early rect")][0]]
eplf = b[[t for t in b if t.lower().startswith("early plf")][0]]
print("Early rectified amplitude (uV):"); print(early.to_string())
print("Early PLF:"); print(eplf.to_string())
r_, a_ = early.loc["Rest", "median"], early.loc["Active", "median"]
print(f"rest median {r_} > active median {a_}: {r_ > a_}; rest within 2.24 +- 0.45: {abs(r_ - 2.24) <= 0.45}; "
      f"active within 1.88 +- 0.32: {abs(a_ - 1.88) <= 0.32}")
Early rectified amplitude (uV):
          min   q25  median  q75   max
Rest     1.75  1.85    2.15  2.4  3.20
Active   1.45  1.65    1.75  2.1  2.50
Passive  1.80  1.85    1.95  2.2  2.45
Early PLF:
          min    q25  median    q75    max
Rest     0.30  0.360   0.410  0.470  0.590
Active   0.30  0.385   0.400  0.435  0.600
Passive  0.22  0.350   0.395  0.475  0.635
rest median 2.15 > active median 1.75: True; rest within 2.24 +- 0.45: True; active within 1.88 +- 0.32: True

Result: reproduced, as far as the public data allow. The early amplitude median is 2.15 uV at rest and 1.75 uV active, each within the paper's mean and SD; the early PLF medians are 0.41 and 0.40. The tests and the correlation cannot be recomputed from box-plot summaries.

figs3b-ieeg-early-no-modulation¶

The early (3 to 50 ms) iEEG response to electrical stimulation in humans is not modulated by state, in monopolar or bipolar derivation.

In [41]:
d = pd.read_excel(xl, sheet_name="Figure S3B", header=None)
rows = []
for c in range(1, d.shape[1]):
    title = d.iloc[1, c]
    if pd.isna(title):
        continue
    v = d.iloc[5:, [c, c + 1]].astype(float).dropna()
    w = stats.wilcoxon(v.iloc[:, 0], v.iloc[:, 1])
    rows.append({"measure": str(title), "subjects": len(v), "rest_mean": v.iloc[:, 0].mean(), "active_mean": v.iloc[:, 1].mean(),
                 "differences_rest_minus_active": np.round((v.iloc[:, 0] - v.iloc[:, 1]).to_numpy(), 3).tolist(), "p_signedrank": w.pvalue})
print(pd.DataFrame(rows).to_string(index=False))
print("With five pairs the smallest two-sided exact signed-rank p is 0.0625.")
                                     measure  subjects  rest_mean  active_mean           differences_rest_minus_active  p_signedrank
Monopolar Rectified amplitude [log(z-value)]         5     0.6360       0.6620        [-0.08, -0.06, 0.08, -0.07, 0.0]        0.7500
                           Monopolar PLF [-]         5     0.7084       0.7288 [-0.077, 0.016, -0.011, -0.024, -0.006]        0.3125
  Bipolar Rectified amplitude [log(z-value)]         5     0.7040       0.7120       [-0.05, -0.08, 0.09, -0.01, 0.01]        0.8750
                             Bipolar PLF [-]         5     0.6960       0.7080          [-0.05, 0.0, 0.0, 0.01, -0.02]        0.5000
With five pairs the smallest two-sided exact signed-rank p is 0.0625.

Result: reproduced, on a test that cannot find an effect. None of the four signed-rank tests on the five subjects gives p < 0.05 (p = 0.31 to 0.88), and the per-subject differences are small and of mixed sign (-0.08 to +0.09). With five pairs the smallest possible p is 0.0625.

Model claims (fig4e, fig4f, fig4hi, figs14a, figs14b)¶

The criteria ask for a rerun of the paper's model, the stim branch of github.com/bazhlab-ucsd/sleep-stage-transition (commit 76ea885), with the analysis code on figshare (doi:10.6084/m9.figshare.25773501.v1, MATLAB). The Methods (Thalamocortical network model) give the two states: rest as the parameters were tuned, active with the CX to TC and CX to RE miniEPSPs raised from 30 to 50 and the thalamic acetylcholine level lowered from 1.3 to 1; 30 trials of 15 s (15 rest, 15 active), the pulse at 8 to 9.75 s in steps of 125 ms. The cell below fetches the model at the commit, builds it in a temporary directory with the Makefile, and times 200 ms of simulation of the published network, to estimate what the 30 trials cost on this runner (4 CPUs).

In [42]:
import os
import subprocess
import tarfile
import tempfile

MODEL_REPO = "bazhlab-ucsd/sleep-stage-transition"   # branch stim, the paper's model (claims file)
MODEL_COMMIT = "76ea8853fa4e97ac8c47032bc00f378a0920f9d0"
TEST_MS = 200                                         # simulated time of each timing run


def set_params(text, **kw):
    lines = [(f"{k.split()[0]} {kw[k.split()[0]]}" if k.strip() and k.split()[0] in kw else k) for k in text.splitlines()]
    return "\n".join(lines) + "\n"


with tempfile.TemporaryDirectory() as tmp:
    tgz = requests.get(f"https://codeload.github.com/{MODEL_REPO}/tar.gz/{MODEL_COMMIT}", timeout=300).content
    tarfile.open(fileobj=io.BytesIO(tgz)).extractall(tmp, filter="data")
    src = os.path.join(tmp, os.listdir(tmp)[0])
    params = open(os.path.join(src, "params.txt")).read()
    keys = ["tmax", "num_mp_threads", "stim_cx_start", "stim_cx_end", "stim_cx_strength", "stim_cx_start_neuron",
            "stim_cx_end_neuron", "stim_in_start_neuron", "stim_in_end_neuron", "ach_cx_awake", "ach_th_awake"]
    print(f"{MODEL_REPO} at {MODEL_COMMIT[:7]}: the parameter set in params.txt")
    print({l.split()[0]: l.split()[1] for l in params.splitlines() if l.strip() and l.split()[0] in keys})
    print("CX to TC and CX to RE AMPA_D2 lines of network.cfg (Mini_s is the miniEPSP strength):")
    for l in open(os.path.join(src, "network.cfg")).read().splitlines():
        if l.split()[:3] in (["CX", "TC", "AMPA_D2"], ["CX", "RE", "AMPA_D2"]):
            print("  " + l.strip())
    t0 = time.time()
    for cmd in (["make", "-s", "mindcurrent"], ["make", "-s", "network"]):
        r = subprocess.run(cmd, cwd=src, capture_output=True, text=True)
        print(" ".join(cmd), "exit", r.returncode)
    with open(os.path.join(src, "connection_info2"), "w") as fh:
        subprocess.run(["./generate_network", "network.cfg"], cwd=src, stdout=fh, stderr=subprocess.DEVNULL, check=True)
    print(f"built the model and its network in {time.time() - t0:.0f} s")
    speed = {}
    for threads in [1, 4]:
        os.makedirs(os.path.join(src, f"run{threads}"))
        with open(os.path.join(src, f"run{threads}", "params.txt"), "w") as fh:
            fh.write(set_params(params, tmax=TEST_MS, num_mp_threads=threads))
        t0 = time.time()
        subprocess.run(["./mindcurrent", f"run{threads}/params.txt", f"run{threads}", "connection_info2"], cwd=src,
                       capture_output=True, check=True)
        speed[threads] = (time.time() - t0) / (TEST_MS / 1000)
        print(f"{threads} thread(s): {TEST_MS} ms simulated in {time.time() - t0:.1f} s, "
              f"{speed[threads]:.0f} s per simulated second")

# Methods: 30 trials (15 rest, 15 active), pulse at 8 to 9.75 s in steps of 125 ms, trials of 15 s
pulses = 8.0 + 0.125 * np.arange(15)
sim_min = 2 * (pulses + 0.25).sum()        # each trial simulated only to 250 ms after its pulse
sim_full = 30 * 15.0
for label, s in [("to 250 ms after each pulse", sim_min), ("15 s trials (Methods)", sim_full)]:
    print(f"30 trials {label}: {s:.0f} s simulated; four single-thread runs at once "
          f"{s * speed[1] / 4 / 3600:.1f} h, one four-thread run {s * speed[4] / 3600:.1f} h")
print("Notebook limit 1 h (docs/protocol.md); fig4hi-model-gaba-contributions adds runs with TRN silenced, "
      "IN silenced and a grid of GABA-A strengths")
bazhlab-ucsd/sleep-stage-transition at 76ea885: the parameter set in params.txt
{'tmax': '7000', 'num_mp_threads': '30', 'stim_cx_start': '6000', 'stim_cx_end': '6002', 'stim_cx_strength': '100.0', 'stim_cx_start_neuron': '125', 'stim_cx_end_neuron': '375', 'stim_in_start_neuron': '25', 'stim_in_end_neuron': '75', 'ach_cx_awake': '1.0', 'ach_th_awake': '1.3'}
CX to TC and CX to RE AMPA_D2 lines of network.cfg (Mini_s is the miniEPSP strength):
  CX     TC   AMPA_D2     1   10000    1    1  fixed    0.00000010   30.000000    0.5  #15
  CX     RE   AMPA_D2     1   10000    1    1  fixed    0.00000010   30.000000    0.5  #15
make -s mindcurrent exit 0
make -s network exit 0
built the model and its network in 5 s
1 thread(s): 200 ms simulated in 24.9 s, 124 s per simulated second
4 thread(s): 200 ms simulated in 16.4 s, 82 s per simulated second
30 trials to 250 ms after each pulse: 274 s simulated; four single-thread runs at once 2.4 h, one four-thread run 6.2 h
30 trials 15 s trials (Methods): 450 s simulated; four single-thread runs at once 3.9 h, one four-thread run 10.3 h
Notebook limit 1 h (docs/protocol.md); fig4hi-model-gaba-contributions adds runs with TRN silenced, IN silenced and a grid of GABA-A strengths

Blocked (not_runnable). The model builds and runs: one parameter set ships with the branch (the rest state: thalamic acetylcholine 1.3, CX to TC and CX to RE miniEPSP strength 30), and the active state is a change of three values the Methods give. The obstacle is time: on this runner one simulated second takes about 120 s on one thread and 80 s on four (cell above; the timing varies between runs: 121 to 123 s and 82 to 83 s in the three runs of the last revision, 158 s and 113 s in an earlier run). The 30 trials of fig4e, fig4f, figs14a and figs14b need 274 s of simulation even when each trial stops 250 ms after its pulse (450 s for the Methods' 15 s trials), about 2.3 h with four single-thread runs at once (3.8 h for 15 s trials), against the notebook's one-hour limit; fig4hi adds runs with TRN silenced, with IN silenced and over a grid of GABA-A strengths. The analysis code is MATLAB and was not ported.

Summary¶

Claim Outcome
source-data-link partially reproduced
fig1a-tms-late-rest-active reproduced (Source Data)
fig1b-ieeg-late-rest-active reproduced (Source Data)
figs2-tms-controls reproduced (Source Data)
figs2a-tms-early-component reproduced (Source Data)
figs3b-ieeg-early-no-modulation reproduced (Source Data)
fig5a-human-mouse-similar blocked, data missing
fig1c-eeg-late-rest-larger reproduced
fig1d-lfp-late-rest-larger reproduced
fig1e-csd-late-rest-larger reproduced
figs1b-mouse-plf reproduced
figs4-intensity-dependence reproduced
speed-threshold-robust not reproduced
figs5-early-component-mouse reproduced
figs6-posterior-no-modulation blocked, data missing
triphasic-pattern partially reproduced
fig2b-thalamus-leads not reproduced
figs7a-active-shorter-latency reproduced
figs7b-latency-correlation reproduced
fig3a-thalamic-rate-higher-active reproduced
figs9-mos-rate-no-modulation not reproduced
figs10a-fs-trn-no-modulation reproduced (fragile)
fig3b-bimodal-isi not reproduced
figs11d-hf-earlier-less-variable not reproduced
figs12-intensity-shifts-to-hf reproduced
fig3e-baseline-rate-doubles reproduced
fig3e-lf-synchrony-reduced not reproduced
fig3e-hf-frequency-reduced reproduced
figs13-thalamic-features-predict-eeg not reproduced
figs13d-lf-crosscorrelation not reproduced
discussion-orthodromic-initial-excitation reproduced
optogenetic claims (3) second notebook
model claims (5) blocked, not runnable (too slow for the time limit)

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 dandiset holds 10 of the paper's mouse sessions with deep MOs stimulation (the paper: 26 EEG sessions from 15 mice, units from 21 mice), so every mouse test has fewer animals. Bad channels and trials were removed in the paper by visual inspection and a lab spreadsheet; here all channels and trials, and the file's own is_data_valid and is_valid flags, are both shown. Responsive units use 10 ms bins in place of the paper's adaptive kernel. The dip test uses the diptest package. The CSD averages the two sites of each Neuropixels row. The rest against running rate tests of fig3a and figs10a are shown also within sessions (van Elteren), as pooling trials over sessions mixes sessions with different rates and fractions of active trials. The HF and LF groups are a k-means split with 18 LF units (8 at the paper's 17.88 ms), so every HF and LF claim is tested on groups unlike the paper's 569 HF and 700 LF units. The model claims were built and timed, not run. The human claims use the per-subject values and box-plot summaries of the Source Data file, as their criteria say.

What was found about the dataset. The units' waveform_duration is described as seconds and holds milliseconds. The trial table's is_running uses a 0 cm/s threshold, not the paper's 0.1 cm/s. No session has stimulation of the posterior control areas of Figure S6. The EEG, LFP, units and trial table share a clock: in the trial-averaged raw signals the stimulation artifact sits within 0.2 ms of the trial onset in the EEG and within 0.6 ms (1.5 samples) in the LFP of every session, and units fire in 2 to 10 ms after the pulse in every mouse. The relay units' evoked ISIs are unimodal here (median 2.6 ms), with few units above the paper's 17.88 ms threshold, so the HF and LF split of the paper's Figure 3 cannot be recovered from this subset.

In [43]:
print(f"Total run time {(time.time() - started) / 60:.1f} min")
Total run time 13.7 min