Reproducing Petersen & Buzsaki (2020) from DANDI:000059¶

Paper: Petersen PC, Buzsaki G (2020). Cooling of medial septum reveals theta phase lag coordination of hippocampal cell assemblies. Neuron 107, 731-744. doi:10.1016/j.neuron.2020.05.023.

Dataset: DANDI:000059, version 0.261115.0311 (doi:10.48324/dandi.000059/0.261115.0311). The paper cites no version of the dandiset. This is the most recent published version; it holds the 51 sessions of 5 rats as one file per session, with the lab's trial cooling states, the measured MS temperature where it exists, the linearized position and the cell types, which the analyses use. The earlier versions (0.210812.1514, 0.230907.2101, 0.250624.0444) split each session into raw and processed files and, by the new version's release notes, had wrong electrode groups and trial times one sample late; none matches the claims file's description better.

Claims: claims/petersen-2020.yaml, written from the accepted author manuscript in PubMed Central (PMC7442698) with the STAR Methods and the Supplemental Information (Figures S1 to S6). Protocol pilot-15.

Data are streamed from the archive; nothing is written to disk. Loading reduces each session to its trials, head tracking, MS temperature, the theta of one CA1 LFP channel during the trials, and the spikes of the curated units during the trials.

The table of claims and outcomes is in the Summary at the end; which claims are tested and which blocked is listed here.

claim tested here
session-structure, cooling-time-course tested
fig2g, fig2h, fig2j, fig2i, disc-theta-frequency-12-percent tested
fig6d, fig6e, fig6c, fig6f, fig6g, fig6h, fig6i, suppl5j, fig4e, fig5-speed-control-cooling tested
suppl2-place-cell-rates-decrease, suppl2ab, disc-interneuron-rates-decrease, suppl5gh tested
fig4b, fig4c, fig4ac, fig4a, fig3c, fig3d, fig3e, fig3f, fig3hi, fig4d, suppl3e, fig4f, fig4gh, suppl2e, suppl3 tested
fig5d, fig5e, fig5h, fig5i, fig5j, fig5k, suppl2d tested
fig5cg-compression blocked, methods_underspecified: the surface fit of the Methods fails on the density (see its section)
suppl1g-waveforms-unchanged see its section
suppl1-hippocampal-temperature blocked, data_missing: no hippocampal temperature in the dandiset
In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "1")
import time, resource, warnings
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy import stats
import ms_cooling as mc
warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)
pd.set_option("display.float_format", lambda v: f"{v:.4g}")
T_START = time.time()
In [2]:
sessions = mc.list_sessions()
print(f"dandiset {mc.DANDISET} version {mc.VERSION}: {len(sessions)} NWB files")
print(sessions.groupby("rat").size().to_string())
SESS = mc.load_all(sessions, workers=4)
print(f"loaded in {time.time() - T_START:.0f} s; peak memory of this process "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
dandiset 000059 version 0.261115.0311: 51 NWB files
rat
MS10     9
MS12     9
MS13     5
MS21    15
MS22    13
loaded in 104 s; peak memory of this process 1.45 GB

Data check¶

In [3]:
rows = []
for S in SESS:
    tr = S["trials"]
    tt, T = S["temp"]
    U = S.get("units", [])
    ct = pd.Series([u["cell_type"] for u in U]).value_counts().to_dict() if U else {}
    rows.append(dict(rat=S["rat"], session=S["session"], trials=len(tr),
                     pre=(tr.state == "Pre").sum(), cooling=(tr.state == "Cooling").sum(),
                     post=(tr.state == "Post").sum(), transition=(tr.state == "transition (excluded)").sum(),
                     other=(~tr.state.isin(["Pre", "Cooling", "Post", "transition (excluded)"])).sum(),
                     errors=int(tr.error.sum()), cooling_epochs=len(S["onsets"]),
                     temp=S["temp_kind"], temp_min=np.nanmin(T), temp_max=np.nanmax(T),
                     pos_hz=round(1 / S["pos_dt"], 1), lfp=S["has_lfp"],
                     theta_ch=S.get("theta_info", {}).get("channel"),
                     theta_ch_bad=S.get("theta_info", {}).get("theta_tag_bad"),
                     good_units=len(U), pyr=ct.get("Pyramidal Cell", 0),
                     nint=ct.get("Narrow Interneuron", 0), wint=ct.get("Wide Interneuron", 0),
                     untyped=ct.get("", 0) + ct.get("Unknown", 0)))
SAN = pd.DataFrame(rows)
print(SAN.to_string())
print()
print("sessions per rat:", SAN.groupby("rat").size().to_dict())
print("sessions with measured MS temperature:", (SAN.temp == "measured").sum(),
      "; modelled (not a measurement):", (SAN.temp == "modelled").sum())
print("sessions with LFP:", SAN.lfp.sum(), "; with curated units:", (SAN.good_units > 0).sum(),
      "; with typed pyramidal cells:", (SAN.pyr > 0).sum())
print("sessions with two cooling epochs:", (SAN.cooling_epochs > 1).sum())
print("tracking rate (Hz) by session:", SAN.pos_hz.value_counts().to_dict(),
      "; rates the descriptions give:", sorted(set(S["beh_desc"].split("OptiTrack head tracking at ")[1].split(" Hz")[0] for S in SESS)))
# the rate each session's description gives, against the rate of its timestamps
desc_hz = pd.Series({S["session"]: float(S["beh_desc"].split("OptiTrack head tracking at ")[1].split(" Hz")[0]) for S in SESS})
ts_hz = SAN.set_index("session").pos_hz
print("sessions by (description rate, timestamp rate):", pd.DataFrame(dict(desc=desc_hz, ts=ts_hz)).groupby(["desc", "ts"]).size().to_dict(),
      "; sessions whose description differs from the timestamps by more than 1 Hz:", int((np.abs(desc_hz - ts_hz) > 1).sum()))
allspd = np.concatenate([S["beh"]["speed"] for S in SESS])
alllin = np.concatenate([S["beh"]["lin"] for S in SESS])
print(f"speed (cm/s): 1st, 50th, 99th percentiles {np.nanpercentile(allspd, [1, 50, 99]).round(1)}; "
      f"linearized position (cm): {np.nanmin(alllin):.1f} to {np.nanmax(alllin):.1f}")
alltr = pd.concat([S["trials"].assign(session=S["session"]) for S in SESS])
print(f"trial duration (s): median {np.median(alltr.stop - alltr.start):.2f}, range "
      f"{(alltr.stop - alltr.start).min():.2f} to {(alltr.stop - alltr.start).max():.2f}")
print("arm run (from the linearized position) against the trial label 'condition', by error:")
print(pd.crosstab([alltr.error, alltr.condition], alltr.arm))
th = alltr.dropna(subset=["f_hil"])
print(f"trial theta frequency (Hilbert, Hz): {th.f_hil.min():.2f} to {th.f_hil.max():.2f}, median {th.f_hil.median():.2f}")
print(f"trial MS temperature (C), measured sessions: "
      f"{alltr[alltr.session.isin(SAN.session[SAN.temp == 'measured'])].temp.describe()[['min', '50%', 'max']].round(2).to_dict()}")
MEAS_ALL = [S for S in SESS if S["temp_kind"] == "measured"]
for S in MEAS_ALL:
    if True:
        tt, T = S["temp"]
        raw_bad = np.isnan(T).sum()
        if raw_bad:
            print(f"  {S['session']}: {raw_bad} temperature samples outside 5 to 45 C set to NaN")
raw = pd.DataFrame({S["session"]: S["temp_raw_range"] for S in MEAS_ALL}, index=["raw_min", "raw_max"]).T
print(f"raw measured temperature before cleaning (C): lowest {raw.raw_min.min():.1f}, highest {raw.raw_max.max():.1f}; sessions with raw values outside 5 to 45 C:")
print(raw[(raw.raw_min < 5) | (raw.raw_max > 45)].round(1).to_string())
# rails near 5 and 10 C fall inside 5 to 45 C; check that no sample within the trials falls below 15 C
low = {}
for S in MEAS_ALL:
    tt, T = S["temp"]
    tr = S["trials"]
    w = (tt >= tr.start.min()) & (tt <= tr.stop.max())
    low[S["session"]] = (int(np.sum(T[w] < 15)), int(np.sum(T < 15)))
print("measured temperature samples below 15 C (within the trials, in the whole trace):",
      {k: v for k, v in low.items() if v[1] > 0}, "; sessions with any within the trials:", sum(v[0] > 0 for v in low.values()))
print("lowest trial temperature per measured session (C):",
      pd.Series({S["session"]: S["trials"].temp.min() for S in MEAS_ALL}).round(1).sort_values().head(5).to_dict())
ep = [S for S in SESS if "epochs" in S]
envs = pd.concat([S["epochs"].assign(session=S["session"]) for S in ep])
print("epoch environments and paradigms:")
print(envs.groupby(["behavioral_paradigm", "environment"]).size())# the 2018-07-19 sessions are labelled as cooled: theta frequency before and during the labelled cooling
for nm in ["MS21-180719-155941", "MS22-180719-122813"]:
    tr = next(S for S in SESS if S["session"] == nm)["trials"]
    g = tr.groupby("state")[["f_hil", "f_spec", "temp"]].mean()
    print(f"{nm}: pre {g.loc['Pre'].round(2).to_dict()}, cooling {g.loc['Cooling'].round(2).to_dict()}; lowest trial temperature {tr.temp.min():.2f} C")
# sessions with two cooling epochs: where the second ends against the last trial
for S in SESS:
    if len(S["onsets"]) > 1 and S["session"].startswith(("MS12-170717", "MS12-170718")):
        print(f"{S['session']}: cooling onsets {S['onsets']} s, offsets {S['offsets']} s; last trial ends at {S['trials'].stop.max():.0f} s")
     rat             session  trials  pre  cooling  post  transition  other  errors  cooling_epochs      temp  temp_min  temp_max  pos_hz    lfp  theta_ch theta_ch_bad  good_units  pyr  nint  wint  untyped
0   MS10  MS10-170307-154746      37   21       10     6           0      0       7               1  modelled        37        37      40   True        46      [False]          15   11     2     1        1
1   MS10  MS10-170311-180956     130   43       31    56           0      0      16               1  modelled        22        37      40   True        46      [False]           0    0     0     0        0
2   MS10  MS10-170313-122631     143   39       47    57           0      0      22               2  modelled     20.76        37      40   True        46      [False]           0    0     0     0        0
3   MS10  MS10-170314-163038     142   52       47    43           0      0      16               1  modelled        22        37      40   True        46      [False]          16   13     0     3        0
4   MS10  MS10-170317-153237     201   52       55    93           1      0      11               1  modelled        22        37      40   True        46      [False]          12   11     0     1        0
5   MS10  MS10-170319-180352     204   49       92    63           0      0      16               2  modelled     21.03        37      40   True        52      [False]           5    0     0     0        5
6   MS10  MS10-170320-212321     179   53       60    66           0      0      17               1  modelled        22        37      30   True        52      [False]           2    0     0     0        2
7   MS10  MS10-170321-164406     130   52       54    24           0      0      20               1  modelled        22        37   119.8   True        52      [False]           0    0     0     0        0
8   MS10  MS10-170323-173246     154   48       67    30           9      0      14               1  modelled        22        37   119.8   True        52      [False]           4    0     0     0        4
9   MS12  MS12-170713-093400     115   32       51    19          13      0       5               2  modelled     19.73     37.19   119.8   True         8      [False]           0    0     0     0        0
10  MS12  MS12-170714-122034     151   39       57    36          19      0       7               2  modelled     18.49     50.16   119.8   True         8      [False]          37   30     6     1        0
11  MS12  MS12-170715-111545     173   42       53    55          23      0      13               2  modelled     19.09     37.06   119.8  False       NaN         None          41   36     3     2        0
12  MS12  MS12-170716-172307     146   41       52    36          17      0      13               2  modelled     18.58     37.44   119.8   True        19      [False]          36   32     3     1        0
13  MS12  MS12-170717-111614     134   39       54    26          15      0       7               2  modelled     18.75     36.96   119.8   True        67      [False]          33   30     2     1        0
14  MS12  MS12-170718-101720     125   38       60    17          10      0       3               2  modelled     19.57     36.57   119.8   True        19      [False]           0    0     0     0        0
15  MS12  MS12-170719-095305     149   35       47    41          26      0       5               2  measured     20.06     37.18   119.8   True        19      [False]          40   31     7     2        0
16  MS12  MS12-170720-093528     155   39       32    69          15      0      10               1  measured     20.53        45   119.8   True        19      [False]           0    0     0     0        0
17  MS12  MS12-170723-141121     140   32       42    54          12      0       6               1  modelled     23.07     36.82   119.8   True        19      [False]           0    0     0     0        0
18  MS13  MS13-171127-133330     160   42       35    49          34      0       5               2  measured     17.87        36   119.8   True        20      [False]           0    0     0     0        0
19  MS13  MS13-171128-113924     159   62       30    50          17      0       8               2  measured      18.5     37.84   119.8   True        20      [False]          63   53     6     4        0
20  MS13  MS13-171129-105507     121   42       41    29           9      0       5               1  modelled      19.1     37.57   119.8   True        20      [False]         104   89     5     9        1
21  MS13  MS13-171130-121758     174   33       52    59          30      0      13               2  modelled     18.54     37.55   119.8   True        82       [True]         123  108     6     9        0
22  MS13  MS13-171201-130527     133   44       24    56           9      0       7               1  measured     20.27     37.62   119.8   True        20      [False]          54   43     7     4        0
23  MS21  MS21-180621-141817     125   33       27    57           8      0       5               1  measured     18.24     40.41   119.8   True        63      [False]          23    0     0     0       23
24  MS21  MS21-180622-174411     131   36       20    58          17      0       8               1  measured     20.65     40.84   119.8   True        63      [False]           0    0     0     0        0
25  MS21  MS21-180623-170717     122   39       33    36          14      0       9               1  measured     18.18        45   119.8   True        63      [False]           0    0     0     0        0
26  MS21  MS21-180625-153927     128   35       36    43          14      0      23               1  measured     16.73        45   119.8   True        63      [False]          68   50    12     6        0
27  MS21  MS21-180627-143449     179   43       58    65          12      1      33               1  modelled     17.91     37.31   119.8   True        79      [False]         145  121    16     8        0
28  MS21  MS21-180628-155921     168   39       29    76          24      0      13               1  measured     20.23     37.49   119.8   True        63      [False]          98   76    15     7        0
29  MS21  MS21-180629-110332     169   40       50    59          20      0      16               1  measured     18.99     37.26   119.8   True        63      [False]         145  121    14    10        0
30  MS21  MS21-180711-112927     129   36       38    40          15      0      13               1  measured     18.07     37.87   119.8   True        63      [False]           0    0     0     0        0
31  MS21  MS21-180712-103200     127   38       28    56           5      0      15               1  measured     21.03     38.08   119.8   True        63      [False]          55   47     5     3        0
32  MS21  MS21-180719-155941     132   39       36    46          11      0      11               1  measured     37.45     39.52   119.8   True        40      [False]         110   92    15     3        0
33  MS21  MS21-180720-110037     187   38       55    80          14      0      17               1  measured     20.74        45   119.8   True        63      [False]           0    0     0     0        0
34  MS21  MS21-180724-144402     192   45       71    54          22      0      13               1  measured     20.17     37.76   119.8   True        63      [False]           0    0     0     0        0
35  MS21  MS21-180730-120605     138   36       23    63          16      0       5               1  measured      22.5      38.5   119.8   True        63      [False]           0    0     0     0        0
36  MS21  MS21-180802-120147     152   41       20    77          14      0      15               1  measured      21.8     40.37   119.8   True        63      [False]           0    0     0     0        0
37  MS21  MS21-180803-142301     121   33       48    30          10      0      13               1  measured     19.92        45   119.8   True        63      [False]           0    0     0     0        0
38  MS22  MS22-180621-131028     115   31       25    42          17      0      14               2  measured     22.38     44.99   119.8   True        63      [False]          21    0     0     0       21
39  MS22  MS22-180622-115734      80   29       31    15           5      0      16               1  measured      21.6        45   119.8   True        63      [False]           0    0     0     0        0
40  MS22  MS22-180623-170141     113   28       34    43           8      0      23               1  measured     5.002     42.33   119.8   True        63      [False]           0    0     0     0        0
41  MS22  MS22-180625-162932     116   27       44    28          17      0      18               1  measured     21.85     39.57   119.8   True        63      [False]           0    0     0     0        0
42  MS22  MS22-180626-110916     134   30       31    59          14      0      22               1  measured     22.59     40.73   119.8   True        63      [False]           0    0     0     0        0
43  MS22  MS22-180627-114856     162   33       45    71          13      0      19               1  measured     23.49     37.32   119.8   True        63      [False]           0    0     0     0        0
44  MS22  MS22-180628-120341     159   36       59    57           7      0      24               1  modelled     22.68     37.43   119.8   True         0      [False]          67   38    22     5        2
45  MS22  MS22-180629-110319     143   40       50    38          15      0      11               1  measured     23.11     37.52   119.8   True         0      [False]         151  129    20     2        0
46  MS22  MS22-180711-112912     111   39       29    29          14      0      14               1  measured     23.35     37.36   119.8   True         6      [False]          63   45    16     2        0
47  MS22  MS22-180712-102504     151   38       52    44          17      0       9               1  measured     5.004      37.9   119.8   True         6      [False]           0    0     0     0        0
48  MS22  MS22-180719-122813     142   77       26    31           8      0      11               1  measured     35.17     37.34   119.8   True        55      [False]          59   43    12     4        0
49  MS22  MS22-180720-110055     141   45       47    35          14      0       6               1  measured     9.978     44.99   119.8   True         6      [False]          71   46    20     5        0
50  MS22  MS22-180724-144421     138   37       59    26          16      0      12               1  measured     24.03        45   119.8   True         6      [False]           0    0     0     0        0

sessions per rat: {'MS10': 9, 'MS12': 9, 'MS13': 5, 'MS21': 15, 'MS22': 13}
sessions with measured MS temperature: 31 ; modelled (not a measurement): 20
sessions with LFP: 50 ; with curated units: 28 ; with typed pyramidal cells: 23
sessions with two cooling epochs: 13
tracking rate (Hz) by session: {119.8: 44, 40.0: 6, 30.0: 1} ; rates the descriptions give: ['120', '30', '40']
sessions by (description rate, timestamp rate): {(30.0, 30.0): 1, (40.0, 40.0): 6, (120.0, 119.8): 44} ; sessions whose description differs from the timestamps by more than 1 Hz: 0
speed (cm/s): 1st, 50th, 99th percentiles [  1.1  14.6 121.7]; linearized position (cm): 0.0 to 345.2
trial duration (s): median 2.93, range 1.82 to 9.98
arm run (from the linearized position) against the trial label 'condition', by error:
arm              Left  Right
error condition             
False Left       3290      4
      Right         0   3312
True  Left          0    315
      Right         0    339
trial theta frequency (Hilbert, Hz): 4.93 to 9.75, median 8.16
trial MS temperature (C), measured sessions: {'min': 17.05, '50%': 36.98, 'max': 44.11}
  MS12-170720-093528: 77908 temperature samples outside 5 to 45 C set to NaN
  MS21-180623-170717: 56 temperature samples outside 5 to 45 C set to NaN
  MS21-180625-153927: 144003 temperature samples outside 5 to 45 C set to NaN
  MS21-180720-110037: 13098 temperature samples outside 5 to 45 C set to NaN
  MS21-180803-142301: 137436 temperature samples outside 5 to 45 C set to NaN
  MS22-180621-131028: 89 temperature samples outside 5 to 45 C set to NaN
  MS22-180622-115734: 32291 temperature samples outside 5 to 45 C set to NaN
  MS22-180623-170141: 39196 temperature samples outside 5 to 45 C set to NaN
  MS22-180712-102504: 165668 temperature samples outside 5 to 45 C set to NaN
  MS22-180720-110055: 154296 temperature samples outside 5 to 45 C set to NaN
  MS22-180724-144421: 110998 temperature samples outside 5 to 45 C set to NaN
raw measured temperature before cleaning (C): lowest -1750.9, highest 1354.1; sessions with raw values outside 5 to 45 C:
                    raw_min  raw_max
MS12-170720-093528     20.5     49.7
MS21-180623-170717     18.2     45.5
MS21-180625-153927     16.7     1354
MS21-180720-110037     20.7     81.4
MS21-180803-142301     19.9    801.5
MS22-180621-131028     22.4     45.3
MS22-180622-115734     21.6       50
MS22-180623-170141   -256.6     42.3
MS22-180712-102504    -1751     37.9
MS22-180720-110055       10     1276
MS22-180724-144421       24       50
measured temperature samples below 15 C (within the trials, in the whole trace): {'MS22-180623-170141': (0, 1498), 'MS22-180712-102504': (0, 944), 'MS22-180720-110055': (0, 89)} ; sessions with any within the trials: 0
lowest trial temperature per measured session (C): {'MS21-180625-153927': 17.1, 'MS21-180711-112927': 18.1, 'MS21-180623-170717': 18.4, 'MS21-180621-141817': 18.6, 'MS21-180629-110332': 19.0}
epoch environments and paradigms:
behavioral_paradigm           environment       
                                                     2
Homecage_Sleep                                       2
                              Homecage_Rat          42
LinearTrack_AlteringSlopes    Linear_Track_Peter     1
LinearTrack_EndToEnd          Linear_Track_Peter     4
ThetaMaze_AlternativeRunning  Linear_Track_Peter     2
                              Theta_Maze_Peter      22
Wheelbox_FreeRunning          Wheel_Box              2
dtype: int64
MS21-180719-155941: pre {'f_hil': 7.53, 'f_spec': 7.69, 'temp': 38.35}, cooling {'f_hil': 8.13, 'f_spec': 8.25, 'temp': 38.22}; lowest trial temperature 37.61 C
MS22-180719-122813: pre {'f_hil': 8.68, 'f_spec': 8.63, 'temp': 37.1}, cooling {'f_hil': 8.27, 'f_spec': 8.57, 'temp': 37.23}; lowest trial temperature 36.96 C
MS12-170717-111614: cooling onsets [15138.718, 16410.155] s, offsets [15775.019, 25683.516] s; last trial ends at 16845 s
MS12-170718-101720: cooling onsets [17428.25, 18721.179] s, offsets [18069.98, 28409.4] s; last trial ends at 19286 s

Checks of the description against the data:

  • Tracking rate. The behaviour descriptions give 120, 40 or 30 Hz, and in every session the rate they give matches the timestamps (44 sessions at about 120 Hz, 6 at 40 Hz, 1 at 30 Hz; printed above). The paper says 120 Hz.
  • Temperature. Sessions without a measured septal trace hold the lab's modelled curve, labelled "NOT A MEASUREMENT"; every analysis of temperature uses only the measured traces. Some measured traces hold artefacts: raw values from -1751 to 1354 C, in 11 sessions outside 5 to 45 C (printed above). These are set to NaN; values near 5 and 10 C in three MS22 sessions lie outside the trials.
  • Arms. In correct trials the arm run (from the linearized position) is the trial's condition, and in error trials the other arm, as the trial table's description says (table above).
  • Clock. The streams share the recording clock by their descriptions. The contrast below checks it: theta frequency of the trials is lower in cooling than in pre in nearly every session, and the decrease is aligned on the dataset's cooling onset (section fig6c); errors rise after the onset. A shift of the labels by the length of the cooling block removes the contrast (printed next).
In [4]:
# label-shift control of the trial clock: theta frequency contrast cooling - pre with true labels and
# with the cooling block moved 30 trials later
d_true, d_shift = [], []
for S in SESS:
    tr = S["trials"]
    if "f_hil" not in tr:
        continue
    lab = tr.state.values
    d_true.append(tr.f_hil[lab == "Cooling"].mean() - tr.f_hil[lab == "Pre"].mean())
    sh = np.roll(lab, 30)
    d_shift.append(tr.f_hil[sh == "Cooling"].mean() - tr.f_hil[sh == "Pre"].mean())
print(f"cooling - pre theta frequency: true labels median {np.nanmedian(d_true):.3f} Hz "
      f"({np.sum(np.array(d_true) < 0)} of {len(d_true)} sessions negative); labels shifted 30 trials median "
      f"{np.nanmedian(d_shift):.3f} Hz ({np.sum(np.array(d_shift) < 0)} of {len(d_shift)} negative)")
cooling - pre theta frequency: true labels median -0.814 Hz (48 of 50 sessions negative); labels shifted 30 trials median 0.462 Hz (3 of 50 negative)

Shared definitions¶

  • Sets of sessions. MEAS: sessions with a measured MS temperature trace (31; the 20 others hold the lab's modelled curve, which is not used). LFPS: sessions with LFP (50). The two sessions of 2018-07-19 (MS21 and MS22) are labelled as cooled, but their measured temperature does not fall; they are kept, as the lab's labels are, and results without them are shown where they could matter.
  • States, the readings of the claims file's opening comment: lab the dataset's trial labels (Pre, Cooling, Post; transition trials left out); m12 and m10 cooling is the trials that start within 12 or 10 min after cooling onset. Cooling onset is the time stamp in the dataset's cooling table (the first epoch where a session has two).
  • Trial theta: f_hil/p_hil the mean Hilbert instantaneous frequency and mean squared amplitude over the trial (reading a), f_spec/p_spec the peak of the trial's 4 to 10 Hz periodogram (reading b); _run versions use only samples above 10 cm/s.
  • Aligned trials: first trial after onset is 1, the last before is -1; trials after a second cooling onset are left out of aligned series. The aligned series spans trials -40 to 80 (standard choice; the paper's Figure 6C shows about this range). Fewer sessions contribute at its ends than near the onset (for the measured sessions with LFP, 11 at the fewest, against 31; printed in fig2g).
In [5]:
MEAS = [S for S in SESS if S["temp_kind"] == "measured"]
MEAS_NAMES = {S["session"] for S in MEAS}
LFPS = [S for S in SESS if S["has_lfp"]]
# the lab's theta channel of MS13-171130 is marked bad in the electrodes table; results without it are shown
BAD_THETA = {S["session"] for S in LFPS if any(S["theta_info"].get("theta_tag_bad", []))}
LFPS_GOOD = [S for S in LFPS if S["session"] not in BAD_THETA]
FLAT = {"MS21-180719-155941", "MS22-180719-122813"}
STATE_READINGS = ["lab", "m12", "m10"]
THETA_F = ["f_hil", "f_spec", "f_hil_run"]
THETA_P = ["p_hil", "p_spec", "p_hil_run"]
for S in SESS:
    tr = S["trials"]
    for r in STATE_READINGS:
        tr["st_" + r] = mc.state_labels(tr, S["onset"], r).values
    if S["has_lfp"]:
        pre = tr.st_lab == "Pre"
        for c in THETA_P:
            tr[c + "_norm"] = tr[c] / tr.loc[pre, c].mean()
    tr["err"] = tr.error.astype(float)
    tr["trial_no"] = np.arange(len(tr))
print("sessions whose tagged theta channel is marked bad:", sorted(BAD_THETA))
print(f"MEAS {len(MEAS)} sessions ({pd.Series([S['rat'] for S in MEAS]).value_counts().to_dict()}), "
      f"LFPS {len(LFPS)} sessions")


def fmt_p(p):
    return f"{p:.2g}"


def aligned(SS, col, k=(-40, 80)):
    a, d = mc.aligned_series(SS, col, k_range=k)
    return a
sessions whose tagged theta channel is marked bad: ['MS13-171130-121758']
MEAS 31 sessions ({'MS21': 14, 'MS22': 12, 'MS13': 3, 'MS12': 2}), LFPS 50 sessions

session-structure¶

A session holds about 40 control trials, then about 20 to 60 cooling trials and 20 to 80 recovery trials, 80 to 200 trials in all with a mean of 150.

In [6]:
ntr = SAN.trials.values
print(f"sessions {len(ntr)}: trials per session mean {ntr.mean():.1f}, median {np.median(ntr):.0f}, "
      f"range {ntr.min()} to {ntr.max()}; sessions outside 72 to 220: {np.sum((ntr < 72) | (ntr > 220))} "
      f"({', '.join(SAN.session[(ntr < 72) | (ntr > 220)])})")
res = []
for r in STATE_READINGS:
    c = np.array([(S["trials"]["st_" + r] == "Cooling").sum() for S in SESS])
    p = np.array([(S["trials"]["st_" + r] == "Pre").sum() for S in SESS])
    q = np.array([(S["trials"]["st_" + r] == "Post").sum() for S in SESS])
    res.append(dict(reading=r, median_pre=np.median(p), median_cooling=np.median(c), median_post=np.median(q),
                    cooling_in_18_66=18 <= np.median(c) <= 66, post_in_18_88=18 <= np.median(q) <= 88))
print(pd.DataFrame(res).to_string(index=False))
print("by rat, mean trials:", SAN.groupby("rat").trials.mean().round(1).to_dict())
print(f"without MS10-170307 (37 trials): mean {ntr[ntr >= 72].mean():.1f}")
sessions 51: trials per session mean 142.4, median 141, range 37 to 204; sessions outside 72 to 220: 1 (MS10-170307-154746)
reading  median_pre  median_cooling  median_post  cooling_in_18_66  post_in_18_88
    lab          39              45           46              True           True
    m12          39              49           50              True           True
    m10          39              41           58              True           True
by rat, mean trials: {'MS10': 146.7, 'MS12': 143.1, 'MS13': 149.4, 'MS21': 146.7, 'MS22': 131.2}
without MS10-170307 (37 trials): mean 144.5

Result: partially reproduced. The 51 sessions hold 142.4 trials on average (135 to 165 allowed), and the median numbers of pre (39), cooling (45, 49 or 41 by state reading) and post trials (46, 50 or 58) fall in the allowed ranges, but one session, MS10-170307, has 37 trials, outside 72 to 220.

cooling-time-course¶

MS cooling typically peaked about 60 s after its onset and lasted about 10 to 12 minutes, about 50 trials.

In [7]:
rows = []
for S in MEAS:
    tt, T = S["temp"]
    tr = S["trials"]
    on = S["onset"]
    pre_med = np.nanmedian(T[(tt >= tr.start.min()) & (tt < on)])
    w = (tt >= on) & (tt <= on + 300) & np.isfinite(T)
    tmin_t = tt[w][np.nanargmin(T[w])] - on
    tmin = np.nanmin(T[w])
    # (a) time until the temperature is again within 1 C of the pre median, after the minimum
    after = (tt > on + tmin_t) & np.isfinite(T)
    back = np.where(after & (T >= pre_med - 1))[0]
    dur_a = (tt[back[0]] - on) / 60 if len(back) else np.nan
    # (b) the lab's cooling interval: onset to the end of the first 'cooling' interval
    ct = S["cooling_table"]
    c1 = ct[(ct.label == "cooling") & (ct.start >= on - 1)].iloc[0]
    dur_b = (c1.stop - on) / 60
    ncool = int(((tr.start >= on) & (tr.start <= c1.stop) & (tr.state == "Cooling")).sum())
    ncool_a = int(((tr.start >= on) & (tr.start <= on + dur_a * 60)).sum()) if np.isfinite(dur_a) else np.nan
    rows.append(dict(rat=S["rat"], session=S["session"], pre_median=pre_med, minimum=tmin,
                     t_min_s=tmin_t, dur_a_min=dur_a, dur_b_min=dur_b, cooling_trials_lab=ncool,
                     trials_in_dur_a=ncool_a))
CT = pd.DataFrame(rows)
print(CT.round(2).to_string(index=False))
med = CT.drop(columns=["rat", "session"]).median()
print("medians:", med.round(2).to_dict())
CT_nf = CT[~CT.session.isin(FLAT)]
print("medians without the two flat 2018-07-19 sessions:", CT_nf.drop(columns=["rat", "session"]).median().round(2).to_dict())
print(f"time to minimum within 40.5 to 66 s: {40.5 <= med.t_min_s <= 66}; "
      f"duration (a) {med.dur_a_min:.1f} min, (b) {med.dur_b_min:.1f} min, within 9 to 13.2 or 13.5 to 16.5: "
      f"(a) {(9 <= med.dur_a_min <= 13.2) or (13.5 <= med.dur_a_min <= 16.5)}, (b) {(9 <= med.dur_b_min <= 13.2) or (13.5 <= med.dur_b_min <= 16.5)}; "
      f"cooling trials (lab) {med.cooling_trials_lab:.0f}, within 45 to 55 or 18 to 66: {(45 <= med.cooling_trials_lab <= 55) or (18 <= med.cooling_trials_lab <= 66)}")
print("by rat, median time to minimum (s):", CT.groupby("rat").t_min_s.median().round(1).to_dict())
 rat            session  pre_median  minimum  t_min_s  dur_a_min  dur_b_min  cooling_trials_lab  trials_in_dur_a
MS12 MS12-170719-095305       36.59    20.07    118.8      16.84      10.61                  20               42
MS12 MS12-170720-093528        36.6    20.53     69.8      15.05       9.91                  32               58
MS13 MS13-171127-133330       35.79     24.9    20.45       3.96       2.66                  10               18
MS13 MS13-171128-113924        37.4    20.36    38.45       8.09       6.39                  25               35
MS13 MS13-171201-130527       37.47    20.27      127       7.29       5.06                  24               27
MS21 MS21-180621-141817       37.04    18.24    203.6      11.58       9.62                  27               33
MS21 MS21-180622-174411       40.11    20.65    59.15        NaN       6.07                  20              NaN
MS21 MS21-180623-170717       42.21    18.18    72.35      23.12       6.46                  33               83
MS21 MS21-180625-153927       37.03    16.73    209.6      11.75       8.77                  36               50
MS21 MS21-180628-155921       37.05    20.23     74.1       7.85       5.24                  29               50
MS21 MS21-180629-110332       36.94    18.99    115.2      10.87       8.27                  50               69
MS21 MS21-180711-112927       37.08    18.07     62.9      13.73      10.32                  38               54
MS21 MS21-180712-103200       37.24    23.06    178.7      11.34       7.88                  28               33
MS21 MS21-180719-155941       38.36    38.09    73.43       1.22      12.61                  36                6
MS21 MS21-180720-110037        41.5    20.74    142.8      236.4      10.15                  55              147
MS21 MS21-180724-144402       37.55    20.17    86.95       15.6      10.91                  71              104
MS21 MS21-180730-120605       37.38     22.5     80.4       7.97        4.7                  23               40
MS21 MS21-180802-120147       37.77     21.8    93.25       9.54       5.74                  20               38
MS21 MS21-180803-142301       37.43    19.92    231.4      12.87       9.94                  48               58
MS22 MS22-180621-131028       39.24    24.13    89.82       4.53       4.16                   7                7
MS22 MS22-180622-115734       37.99     21.6      125      10.73       8.03                  31               36
MS22 MS22-180623-170141        37.6    21.24    180.4      12.14       8.81                  34               42
MS22 MS22-180625-162932       37.34    21.85    124.2      11.75       8.04                  44               63
MS22 MS22-180626-110916       37.44    23.34    109.7      10.85       7.94                  31               45
MS22 MS22-180627-114856       37.13    23.49    148.1      12.28       8.52                  45               62
MS22 MS22-180629-110319       37.04    23.11    124.7      13.68       9.76                  50               70
MS22 MS22-180711-112912       36.47    23.35    93.85      11.15       8.14                  29               43
MS22 MS22-180712-102504       37.44    22.56    105.7      12.09       8.11                  52               73
MS22 MS22-180719-122813       37.13    37.15    237.7       3.96       8.81                  26               18
MS22 MS22-180720-110055       37.38    23.64    61.75      13.27        7.4                  47               77
MS22 MS22-180724-144421       37.78    24.03    133.4      17.09      10.85                  59               88
medians: {'pre_median': 37.38, 'minimum': 21.6, 't_min_s': 109.65, 'dur_a_min': 11.66, 'dur_b_min': 8.14, 'cooling_trials_lab': 32.0, 'trials_in_dur_a': 47.5}
medians without the two flat 2018-07-19 sessions: {'pre_median': 37.38, 'minimum': 21.24, 't_min_s': 109.65, 'dur_a_min': 11.75, 'dur_b_min': 8.11, 'cooling_trials_lab': 32.0, 'trials_in_dur_a': 50.0}
time to minimum within 40.5 to 66 s: False; duration (a) 11.7 min, (b) 8.1 min, within 9 to 13.2 or 13.5 to 16.5: (a) True, (b) False; cooling trials (lab) 32, within 45 to 55 or 18 to 66: True
by rat, median time to minimum (s): {'MS12': 94.3, 'MS13': 38.4, 'MS21': 90.1, 'MS22': 124.4}

Result: partially reproduced. Over the 31 sessions with a measured MS temperature, the median time from cooling onset to the minimum is 109.7 s, outside 40.5 to 66 s. The median time until the temperature is again within 1 C of the pre median is 11.7 min (within 9 to 13.2 min), and the median number of trials in the lab's first cooling interval is 32 (within the Results' 18 to 66); the lab's cooling interval itself lasts 8.1 min.

fig2g-theta-freq-temperature, fig2h-theta-power-temperature¶

Theta frequency decreased linearly with MS temperature, down to 20 C (R = 0.81, P = 5.4e-48).

Theta power also decreased with MS temperature, less tightly than frequency (R = 0.54, P = 1.2e-16).

Readings (claims file): (a) aligned trials averaged over sessions; (b) 1 C temperature bins, R over bin means; (c) all trials pooled. Measured-temperature sessions with LFP.

In [8]:
MEAS_L = [S for S in MEAS if S["has_lfp"]]


def temp_corr(SS, col):
    out = {}
    a = mc.aligned_series(SS, col)[0]
    t = mc.aligned_series(SS, "temp")[0]
    j = a.index.intersection(t.index)
    out["a_aligned"] = mc.corr(t.loc[j, "mean"], a.loc[j, "mean"])
    d = pd.concat([S["trials"][["temp", col]] for S in SS]).dropna()
    d["bin"] = np.floor(d.temp)
    g = d.groupby("bin")[col].agg(["mean", "count"])
    g = g[g["count"] >= 5]
    out["b_bins"] = mc.corr(g.index.values, g["mean"].values)
    out["c_pooled"] = mc.corr(d.temp, d[col])
    return out


def corr_table(SS, cols):
    rows = []
    for c in cols:
        for k, (r, p, n) in temp_corr(SS, c).items():
            rows.append(dict(measure=c, reading=k, R=r, P=p, n=n))
    return pd.DataFrame(rows)
In [9]:
G2 = corr_table(MEAS_L, THETA_F)
G2["R_in_tol"] = (G2.R - 0.81).abs() <= 0.081
G2["P<1e-10"] = G2.P < 1e-10
print(G2.to_string(index=False))
print("without the two flat sessions:")
print(corr_table([S for S in MEAS_L if S["session"] not in FLAT], ["f_hil", "f_spec"]).to_string(index=False))
a = mc.aligned_series(MEAS_L, "f_hil")[0]
t = mc.aligned_series(MEAS_L, "temp")[0]
print(f"aligned series: trials {a.index.min()} to {a.index.max()}, sessions per trial {a.n.min()} to {a.n.max()}; "
      f"mean temperature {t['mean'].min():.1f} to {t['mean'].max():.1f} C; theta {a['mean'].min():.2f} to {a['mean'].max():.2f} Hz")
d = pd.concat([S["trials"][["temp", "f_hil"]] for S in MEAS_L]).dropna()
fit = stats.linregress(d.temp, d.f_hil)
print(f"pooled trials: slope {fit.slope:.3f} Hz/C, lowest trial temperature {d.temp.min():.1f} C")
fig, ax = plt.subplots(1, 2, figsize=(9, 3.5))
ax[0].scatter(d.temp, d.f_hil, s=2, alpha=0.3)
ax[0].set_xlabel("MS temperature (C)"); ax[0].set_ylabel("theta frequency (Hz)")
ax[1].errorbar(t.loc[a.index, "mean"], a["mean"], yerr=a.se, fmt="o", ms=3)
ax[1].set_xlabel("mean MS temperature (C)"); ax[1].set_title("aligned trials")
plt.tight_layout(); plt.show()
print(f"plotted: all {len(d)} trials and {len(a)} aligned trials; no point outside the axes")
  measure   reading      R          P    n  R_in_tol  P<1e-10
    f_hil a_aligned 0.9779  4.322e-82  120     False     True
    f_hil    b_bins 0.9589   1.23e-14   26     False     True
    f_hil  c_pooled  0.554          0 4313     False     True
   f_spec a_aligned 0.9353  4.697e-55  120     False     True
   f_spec    b_bins 0.9285  8.148e-12   26     False     True
   f_spec  c_pooled 0.4808 2.215e-248 4313     False     True
f_hil_run a_aligned 0.9789  3.316e-83  120     False     True
f_hil_run    b_bins 0.9615  5.708e-15   26     False     True
f_hil_run  c_pooled 0.5629          0 4313     False     True
without the two flat sessions:
measure   reading      R          P    n
  f_hil a_aligned 0.9757  1.187e-79  120
  f_hil    b_bins 0.9709   2.06e-16   26
  f_hil  c_pooled 0.5805          0 4039
 f_spec a_aligned 0.9381  3.601e-56  120
 f_spec    b_bins 0.9342  3.073e-12   26
 f_spec  c_pooled 0.5011 9.378e-256 4039
aligned series: trials -40 to 80, sessions per trial 11 to 31; mean temperature 23.6 to 37.9 C; theta 7.49 to 8.65 Hz
pooled trials: slope 0.063 Hz/C, lowest trial temperature 17.1 C
plotted: all 4313 trials and 120 aligned trials; no point outside the axes

Result: partially reproduced. Theta frequency rises with MS temperature under every reading with P below 1e-10, but no R is within 0.729 to 0.891: aligned trials give R = 0.978 (Hilbert, 120 points), temperature bins 0.959, pooled trials 0.554 (4313 trials); the spectral reading gives 0.935, 0.929 and 0.481. The pooled slope is 0.063 Hz per C and trial temperatures reach 17.1 C.

In [10]:
H2 = corr_table(MEAS_L, THETA_P + [c + "_norm" for c in THETA_P])
H2["R_in_tol"] = (H2.R - 0.54).abs() <= 0.054
H2["P<1e-5"] = H2.P < 1e-5
fr = G2.set_index(["measure", "reading"]).R
H2["freq_R_same_reading"] = [fr.get((m.replace("p_", "f_").replace("_norm", ""), k), np.nan) for m, k in zip(H2.measure, H2.reading)]
H2["below_freq_R"] = H2.R < H2.freq_R_same_reading
print(H2.to_string(index=False))
       measure   reading       R         P    n  R_in_tol  P<1e-5  freq_R_same_reading  below_freq_R
         p_hil a_aligned  0.4953 8.878e-09  120      True    True               0.9779          True
         p_hil    b_bins   0.515  0.007104   26      True   False               0.9589          True
         p_hil  c_pooled 0.05456 0.0003378 4313     False   False                0.554          True
        p_spec a_aligned  0.7613  5.96e-24  120     False    True               0.9353          True
        p_spec    b_bins  0.7198 3.401e-05   26     False   False               0.9285          True
        p_spec  c_pooled  0.1597 5.026e-26 4313     False    True               0.4808          True
     p_hil_run a_aligned  0.4873 1.664e-08  120      True    True               0.9789          True
     p_hil_run    b_bins   0.526  0.005781   26      True   False               0.9615          True
     p_hil_run  c_pooled 0.05578 0.0002471 4313     False   False               0.5629          True
    p_hil_norm a_aligned  0.4893 1.419e-08  120      True    True               0.9779          True
    p_hil_norm    b_bins  0.5766  0.002047   26      True   False               0.9589          True
    p_hil_norm  c_pooled 0.07547 6.969e-07 4313     False    True                0.554          True
   p_spec_norm a_aligned   0.811 3.015e-29  120     False    True               0.9353          True
   p_spec_norm    b_bins  0.7968  1.11e-06   26     False    True               0.9285          True
   p_spec_norm  c_pooled   0.282 1.219e-79 4313     False    True               0.4808          True
p_hil_run_norm a_aligned  0.4827  2.36e-08  120     False    True               0.9789          True
p_hil_run_norm    b_bins   0.581  0.001856   26      True   False               0.9615          True
p_hil_run_norm  c_pooled 0.07664 4.679e-07 4313     False    True               0.5629          True

Result: reproduced. Under reading (a), aligned trials with the mean squared Hilbert amplitude, R = 0.495 (P = 8.9e-9, 120 points), within 0.486 to 0.594 and below the frequency R of 0.978 under the same reading. The normalised power gives R = 0.489. The spectral peak power gives larger R (0.761) and pooled trials much smaller ones (0.055).

fig2j-frequency-consistent-across-animals¶

The relationship of theta frequency with MS temperature was more consistent across animals than that of theta power.

In [11]:
rows = []
for rat in sorted(set(S["rat"] for S in MEAS_L)):
    SS = [S for S in MEAS_L if S["rat"] == rat]
    for c in ["f_hil", "p_hil", "p_hil_norm", "f_spec", "p_spec_norm"]:
        r, p, n = temp_corr(SS, c)["a_aligned"]
        rows.append(dict(rat=rat, sessions=len(SS), measure=c, R=r, P=p, n=n))
J2 = pd.DataFrame(rows)
print(J2.pivot(index="rat", columns="measure", values="R").round(3))
print(J2.pivot(index="rat", columns="measure", values="P").map(fmt_p))
for c in ["f_hil", "p_hil", "p_hil_norm", "f_spec", "p_spec_norm"]:
    v = J2[J2.measure == c]
    print(f"{c}: range of R {v.R.max() - v.R.min():.3f}, SD {v.R.std():.3f}, rats with P < 0.05 {int((v.P < 0.05).sum())} of {len(v)}, all positive {bool((v.R > 0).all())}")
print("MS10 has no measured temperature, so 4 of the 5 rats can be tested.")
measure  f_hil  f_spec  p_hil  p_hil_norm  p_spec_norm
rat                                                   
MS12     0.559   0.634  -0.03       0.129        0.086
MS13     0.857   0.768 -0.139       0.185        0.354
MS21     0.958   0.856   0.63       0.681        0.756
MS22     0.944    0.93 -0.251      -0.209        0.722
measure    f_hil   f_spec    p_hil p_hil_norm p_spec_norm
rat                                                      
MS12     3.8e-11    1e-14     0.75       0.16        0.35
MS13     8.8e-36  1.4e-24     0.13      0.044     7.4e-05
MS21     9.3e-66  1.2e-35  1.2e-14    1.1e-17     1.9e-23
MS22     7.2e-59  3.1e-53   0.0057      0.022     1.4e-20
f_hil: range of R 0.399, SD 0.186, rats with P < 0.05 4 of 4, all positive True
p_hil: range of R 0.881, SD 0.396, rats with P < 0.05 2 of 4, all positive False
p_hil_norm: range of R 0.890, SD 0.367, rats with P < 0.05 3 of 4, all positive False
f_spec: range of R 0.296, SD 0.127, rats with P < 0.05 4 of 4, all positive True
p_spec_norm: range of R 0.670, SD 0.319, rats with P < 0.05 3 of 4, all positive True
MS10 has no measured temperature, so 4 of the 5 rats can be tested.

Result: reproduced. In each of the 4 rats with a measured temperature, theta frequency correlates positively with MS temperature (R 0.559 to 0.958, every P below 4e-11), and the range of R over rats is 0.399 for frequency against 0.881 for raw power and 0.890 for normalised power (SD 0.186 against 0.396 and 0.367). MS10 has only the modelled temperature curve, so the fifth rat cannot be tested.

fig2i-theta-pre-cooling-post¶

MS cooling induced a fast and reversible decrease of hippocampal theta frequency and power, lower during cooling than before and after it.

In [12]:
rows = []
for r, fc, pc, sset in [(r, fc, pc, "all") for r in STATE_READINGS for fc, pc in [("f_hil", "p_hil"), ("f_spec", "p_spec"), ("f_hil_run", "p_hil_run")]] + \
        [("lab", fc, pc, "without MS13-171130") for fc, pc in [("f_hil", "p_hil"), ("f_spec", "p_spec")]]:
    if True:
        M = []
        for S in (LFPS if sset == "all" else LFPS_GOOD):
            tr = S["trials"]
            g = tr.groupby("st_" + r)[[fc, pc]].mean()
            if not {"Pre", "Cooling", "Post"} <= set(g.index):
                continue
            M.append(dict(fpre=g.loc["Pre", fc], fcool=g.loc["Cooling", fc], fpost=g.loc["Post", fc],
                          ppre=g.loc["Pre", pc], pcool=g.loc["Cooling", pc], ppost=g.loc["Post", pc]))
        M = pd.DataFrame(M)
        rows.append(dict(states=r, theta=fc, sessions=len(M), set=sset,
                         f_pre=M.fpre.mean(), f_cool=M.fcool.mean(), f_post=M.fpost.mean(),
                         P_f_cool_pre=mc.signrank(M.fcool, M.fpre)[0], P_f_cool_post=mc.signrank(M.fcool, M.fpost)[0],
                         P_p_cool_pre=mc.signrank(M.pcool, M.ppre)[0], P_p_cool_post=mc.signrank(M.pcool, M.ppost)[0],
                         f_lower_both=bool((M.fcool < M.fpre).mean() > 0.5 and (M.fcool < M.fpost).mean() > 0.5),
                         p_cool_over_pre=np.median(M.pcool / M.ppre), p_cool_over_post=np.median(M.pcool / M.ppost)))
I2 = pd.DataFrame(rows)
I2["all_four_P<0.05_lower"] = (I2[["P_f_cool_pre", "P_f_cool_post", "P_p_cool_pre", "P_p_cool_post"]] < 0.05).all(1) & (I2.p_cool_over_pre < 1) & (I2.p_cool_over_post < 1) & I2.f_lower_both
print(I2.to_string(index=False))
states     theta  sessions                 set  f_pre  f_cool  f_post  P_f_cool_pre  P_f_cool_post  P_p_cool_pre  P_p_cool_post  f_lower_both  p_cool_over_pre  p_cool_over_post  all_four_P<0.05_lower
   lab     f_hil        50                 all  8.294   7.564   8.355      2.24e-12      1.776e-15      0.004178         0.4152          True            0.904             1.055                  False
   lab    f_spec        50                 all  8.404    7.59   8.446      8.06e-11      3.553e-15     2.472e-07      3.189e-06          True           0.8235            0.8654                   True
   lab f_hil_run        50                 all  8.301   7.573   8.372      2.24e-12      1.776e-15      0.005406         0.4319          True           0.9074             1.057                  False
   m12     f_hil        49                 all  8.296   7.738   8.277     1.612e-10      4.867e-13      0.009706         0.6501          True            0.939             1.038                  False
   m12    f_spec        49                 all  8.411   7.773    8.36     5.623e-10      1.588e-12     1.435e-05      1.657e-07          True           0.8618            0.8955                   True
   m12 f_hil_run        49                 all  8.303   7.749   8.293     1.612e-10      4.867e-13       0.01129         0.6219          True           0.9375             1.033                  False
   m10     f_hil        49                 all  8.296   7.655   8.255     6.178e-12      8.882e-14      0.009706          0.608          True           0.9457             1.039                  False
   m10    f_spec        49                 all  8.411   7.679   8.337     1.612e-10      8.882e-14     1.322e-06      1.657e-07          True           0.8523             0.867                   True
   m10 f_hil_run        49                 all  8.303   7.665   8.271     6.178e-12      8.882e-14       0.01163         0.6643          True           0.9582              1.04                  False
   lab     f_hil        49 without MS13-171130  8.278   7.554   8.346      4.48e-12      3.553e-15      0.006061         0.2899          True           0.9054             1.059                  False
   lab    f_spec        49 without MS13-171130  8.391   7.579    8.44      1.43e-10      7.105e-15     4.523e-07      5.791e-06          True            0.838            0.8717                   True
/tmp/ipykernel_2386/1848272810.py:21: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  I2["all_four_P<0.05_lower"] = (I2[["P_f_cool_pre", "P_f_cool_post", "P_p_cool_pre", "P_p_cool_post"]] < 0.05).all(1) & (I2.p_cool_over_pre < 1) & (I2.p_cool_over_post < 1) & I2.f_lower_both

Result: reproduced. Under the spectral theta reading, cooling lowers theta frequency against pre and post and theta power against pre and post (all four signed-rank P below 1e-4, power ratios 0.82 and 0.87) under each of the three state readings, over 50 sessions with the lab states and 49 with the 12 and 10 min readings. Under the Hilbert reading frequency falls (8.29 to 7.56 Hz, back to 8.36) but power during cooling does not differ from post (P = 0.42). Without MS13-171130, whose tagged theta channel is marked bad, the spectral reading gives the same result (49 sessions, all four P below 1e-5).

disc-theta-frequency-12-percent¶

During MS cooling LFP theta frequency decreased by about 12%.

In [13]:
rows = []
for r in STATE_READINGS:
    for fc in THETA_F:
        A, B = [], []
        for S in LFPS:
            g = S["trials"].groupby("st_" + r)[fc].mean()
            if not {"Pre", "Cooling", "Post"} <= set(g.index):
                continue
            A.append(100 * (1 - g["Cooling"] / g["Pre"]))
            B.append(100 * (1 - g["Cooling"] / ((g["Pre"] + g["Post"]) / 2)))
        rows.append(dict(states=r, theta=fc, a_vs_pre=np.mean(A), b_vs_pre_post=np.mean(B)))
for fc in THETA_F:
    al = aligned(LFPS, fc)
    pre = al.loc[al.index < 0, "mean"].mean()
    rows.append(dict(states="aligned", theta=fc, c_largest_aligned=100 * (1 - al.loc[al.index > 0, "mean"].min() / pre)))
D12 = pd.DataFrame(rows)
print(D12.to_string(index=False))
vals = D12[["a_vs_pre", "b_vs_pre_post", "c_largest_aligned"]].values.ravel()
vals = vals[np.isfinite(vals)]
print(f"readings within 10.8 to 13.2%: {int(np.sum((vals >= 10.8) & (vals <= 13.2)))} of {len(vals)}; all show a decrease: {bool((vals > 0).all())}")
 states     theta  a_vs_pre  b_vs_pre_post  c_largest_aligned
    lab     f_hil     8.642          9.101                NaN
    lab    f_spec     9.481          9.904                NaN
    lab f_hil_run      8.61          9.121                NaN
    m12     f_hil     6.616           6.61                NaN
    m12    f_spec     7.444          7.334                NaN
    m12 f_hil_run     6.564          6.608                NaN
    m10     f_hil     7.618          7.494                NaN
    m10    f_spec      8.57          8.334                NaN
    m10 f_hil_run     7.577            7.5                NaN
aligned     f_hil       NaN            NaN              11.08
aligned    f_spec       NaN            NaN              12.89
aligned f_hil_run       NaN            NaN              10.94
readings within 10.8 to 13.2%: 3 of 21; all show a decrease: True

Result: reproduced. Reading (c), the largest decrease of the aligned mean series relative to its pre mean, gives 11.1% (Hilbert, within 10.8 to 13.2%) and 12.9% (spectral). Readings (a) and (b), the mean per-session decrease against pre or against pre and post, give 6.6 to 9.9%.

fig6d-errors-increase¶

MS cooling increased choice errors about 3-fold, within each rat (P < 0.05 for all animals) and across all animals (P = 1e-6).

In [14]:
def error_rates(SS, r):
    rows = []
    for S in SS:
        tr = S["trials"]
        s = tr["st_" + r]
        rows.append(dict(rat=S["rat"], session=S["session"],
                         pre=100 * tr.err[s == "Pre"].mean(), cool=100 * tr.err[s == "Cooling"].mean(),
                         post=100 * tr.err[s == "Post"].mean(),
                         prepost=100 * tr.err[s.isin(["Pre", "Post"])].mean()))
    return pd.DataFrame(rows)
In [15]:
rows = []
for r in STATE_READINGS:
    E = error_rates(SESS, r)
    for ctrl in ["pre", "prepost"]:
        ratio_i = E.cool.mean() / E[ctrl].mean()
        ok = E[ctrl] > 0
        ratio_ii = np.nanmedian(E.cool[ok] / E[ctrl][ok])
        p_all = mc.signrank(E.cool, E[ctrl])[0]
        per_rat = {}
        for rat, g in E.groupby("rat"):
            if len(g) >= 6:
                per_rat[rat] = mc.signrank(g.cool, g[ctrl])[0]
            else:
                tr = pd.concat([S["trials"] for S in SESS if S["rat"] == rat])
                s = tr["st_" + r]
                c = tr.err[s == "Cooling"]
                k = tr.err[s.isin(["Pre"] if ctrl == "pre" else ["Pre", "Post"])]
                per_rat[rat] = mc.ranksum(c, k)
        rows.append(dict(states=r, control=ctrl, mean_cool=E.cool.mean(), mean_ctrl=E[ctrl].mean(),
                         ratio_i=ratio_i, ratio_ii=ratio_ii, P_sessions=p_all, n=len(E),
                         **{f"P_{k}": v for k, v in per_rat.items()}))
D6 = pd.DataFrame(rows)
D6["ratio_in_tol"] = ((D6.ratio_i - 3).abs() <= 0.3) | ((D6.ratio_ii - 3).abs() <= 0.3)
D6["P<1e-5"] = D6.P_sessions < 1e-5
D6["all_rats_P<0.05"] = (D6[[c for c in D6 if c.startswith("P_MS")]] < 0.05).all(1)
print(D6.to_string(index=False))
print("rats with fewer than 6 sessions (tested over trials with rank-sum):",
      [k for k, v in SAN.groupby("rat").size().items() if v < 6])
E = error_rates(SESS, "lab")
print("per rat mean error rates (lab states):")
print(E.groupby("rat")[["pre", "cool", "post"]].mean().round(2))
states control  mean_cool  mean_ctrl  ratio_i  ratio_ii  P_sessions  n   P_MS10   P_MS12  P_MS13   P_MS21  P_MS22  ratio_in_tol  P<1e-5  all_rats_P<0.05
   lab     pre      15.14      7.339    2.063     2.113   7.126e-06 51  0.02734  0.02734  0.2424  0.02155 0.04785         False    True            False
   lab prepost      15.14      6.876    2.202      2.25   9.169e-07 51  0.02734 0.007812  0.2327 0.003357 0.03271         False    True            False
   m12     pre      13.88      7.047    1.969     1.864    8.53e-06 51  0.01562  0.05078  0.4294   0.0946 0.01709         False    True            False
   m12 prepost      13.88       6.96    1.994     2.108   1.214e-07 51  0.01562  0.01953  0.4427  0.04126 0.01709         False    True            False
   m10     pre      14.68      7.047    2.083     2.071   1.403e-07 51 0.007812  0.02734  0.3615  0.03534  0.0105         False    True            False
   m10 prepost      14.68      7.215    2.035     2.133    1.26e-08 51  0.01562  0.01953  0.3484 0.004272 0.02661         False    True            False
rats with fewer than 6 sessions (tested over trials with rank-sum): ['MS13']
per rat mean error rates (lab states):
       pre  cool  post
rat                   
MS10  6.31 18.93  9.35
MS12  4.84  8.45  2.53
MS13   3.4  9.61   4.5
MS21  7.75 17.04  5.63
MS22 10.82 17.08 10.31
/tmp/ipykernel_2386/4041587801.py:25: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  D6["all_rats_P<0.05"] = (D6[[c for c in D6 if c.startswith("P_MS")]] < 0.05).all(1)

Result: partially reproduced. Errors rise during cooling: 15.1% of cooling trials against 7.3% of pre trials, signed-rank P = 7.1e-6 over 51 sessions (9.2e-7 against pre and post), below 1e-5. The ratio is 1.9 to 2.3 under every reading, outside 2.7 to 3.3, and MS13 (5 sessions, tested over trials) does not reach P < 0.05 (P = 0.23 to 0.44); the other four rats do under the lab states.

fig6e-errors-recover¶

The error rate after cooling did not differ from the error rate before it.

In [16]:
for r in STATE_READINGS:
    E = error_rates(SESS, r)
    p, n = mc.signrank(E.post, E.pre)
    print(f"states {r}: post - pre median {np.nanmedian(E.post - E.pre):.2f} percentage points, "
          f"mean pre {E.pre.mean():.2f}%, post {E.post.mean():.2f}%, signed-rank P = {p:.3g} (n = {n})")
states lab: post - pre median -0.42 percentage points, mean pre 7.34%, post 6.82%, signed-rank P = 0.547 (n = 51)
states m12: post - pre median -0.76 percentage points, mean pre 7.05%, post 7.11%, signed-rank P = 0.804 (n = 50)
states m10: post - pre median 0.18 percentage points, mean pre 7.05%, post 7.53%, signed-rank P = 0.969 (n = 50)

Result: reproduced. Post error rates do not differ from pre (lab states: 6.8% against 7.3%, median difference -0.42 points, signed-rank P = 0.55, 51 sessions; P = 0.80 and 0.97 under the 12 and 10 min readings).

fig6c-worst-trials-4-to-8¶

The worst memory performance occurred between trials 4 and 8 after the onset of cooling, when MS temperature reached its minimum, together with the largest decreases of theta frequency and power.

In [17]:
err_a = aligned(SESS, "err")
temp_a = aligned(MEAS, "temp")
f_a = {c: aligned(LFPS, c) for c in ["f_hil", "f_spec"]}
p_a = {c: aligned(LFPS, c) for c in ["p_hil_norm", "p_spec_norm"]}
w = (err_a.index >= 1) & (err_a.index <= 40)


def argext(s, fn, lo=1, hi=40):
    v = s.loc[(s.index >= lo) & (s.index <= hi)]
    return int(v.idxmax() if fn == "max" else v.idxmin())


for smooth in ["none", "5-trial mean"]:
    e = err_a["mean"] if smooth == "none" else err_a["mean"].rolling(5, center=True, min_periods=1).mean()
    k_err = argext(e, "max")
    out = dict(error_max_trial=k_err, error_max=float(e.loc[k_err]),
               temp_min_trial=argext(temp_a["mean"], "min"))
    for c, v in f_a.items():
        out[c + "_min_trial"] = argext(v["mean"], "min")
    for c, v in p_a.items():
        out[c + "_min_trial"] = argext(v["mean"], "min")
    print(f"smoothing {smooth}: {out}")
fg = {c: aligned(LFPS_GOOD, c) for c in ["f_hil", "f_spec", "p_hil_norm", "p_spec_norm"]}
print("without MS13-171130 (theta channel marked bad), minimum trial in 1 to 40:", {c: argext(v["mean"], "min") for c, v in fg.items()})
print(f"pre error incidence (aligned trials -40 to -1): {err_a.loc[err_a.index < 0, 'mean'].mean():.3f}")
print("error incidence on aligned trials 1 to 15:", err_a.loc[1:15, "mean"].round(3).tolist())
print("mean temperature on aligned trials 1 to 15:", temp_a.loc[1:15, "mean"].round(1).tolist())
print("theta frequency (Hilbert) on aligned trials 1 to 15:", f_a["f_hil"].loc[1:15, "mean"].round(2).tolist())
print("theta power (Hilbert, normalised) on aligned trials 1 to 15:", p_a["p_hil_norm"].loc[1:15, "mean"].round(3).tolist())
fig, ax = plt.subplots(4, 1, figsize=(7, 8), sharex=True)
ax[0].plot(err_a.index, err_a["mean"]); ax[0].set_ylabel("error incidence")
ax[1].plot(temp_a.index, temp_a["mean"]); ax[1].set_ylabel("MS temp (C)")
ax[2].plot(f_a["f_hil"].index, f_a["f_hil"]["mean"]); ax[2].set_ylabel("theta (Hz)")
ax[3].plot(p_a["p_hil_norm"].index, p_a["p_hil_norm"]["mean"]); ax[3].set_ylabel("theta power / pre")
for a_ in ax:
    a_.axvline(0, color="k", lw=0.5)
ax[3].set_xlabel("trial from cooling onset")
plt.tight_layout(); plt.show()
smoothing none: {'error_max_trial': 8, 'error_max': 0.3137254901960784, 'temp_min_trial': 7, 'f_hil_min_trial': 8, 'f_spec_min_trial': 6, 'p_hil_norm_min_trial': 8, 'p_spec_norm_min_trial': 8}
smoothing 5-trial mean: {'error_max_trial': 6, 'error_max': 0.2156862745098039, 'temp_min_trial': 7, 'f_hil_min_trial': 8, 'f_spec_min_trial': 6, 'p_hil_norm_min_trial': 8, 'p_spec_norm_min_trial': 8}
without MS13-171130 (theta channel marked bad), minimum trial in 1 to 40: {'f_hil': 8, 'f_spec': 6, 'p_hil_norm': 8, 'p_spec_norm': 8}
pre error incidence (aligned trials -40 to -1): 0.068
error incidence on aligned trials 1 to 15: [0.039, 0.216, 0.137, 0.255, 0.157, 0.176, 0.176, 0.314, 0.216, 0.157, 0.078, 0.157, 0.157, 0.176, 0.118]
mean temperature on aligned trials 1 to 15: [26.6, 25.8, 24.7, 24.3, 23.8, 23.6, 23.6, 24.1, 24.2, 24.3, 24.6, 24.7, 25.1, 25.4, 25.6]
theta frequency (Hilbert) on aligned trials 1 to 15: [7.69, 7.69, 7.54, 7.54, 7.5, 7.42, 7.37, 7.36, 7.48, 7.48, 7.52, 7.45, 7.48, 7.5, 7.57]
theta power (Hilbert, normalised) on aligned trials 1 to 15: [0.898, 0.861, 0.848, 0.812, 0.822, 0.83, 0.796, 0.787, 0.85, 0.831, 0.837, 0.916, 0.843, 0.897, 0.888]

Result: reproduced. Without smoothing, the error incidence over aligned trials 1 to 40 peaks at trial 8 (0.31 against 0.07 before onset), and the minima of mean MS temperature (trial 7), theta frequency (trial 8, Hilbert; 6, spectral) and theta power (trial 8) all fall in trials 4 to 8. With a 5-trial mean the error peak is at trial 6. Without MS13-171130 (theta channel marked bad) the theta minima fall on the same trials (8 and 6 for frequency, 8 for power).

fig6f-errors-temperature, fig6g-errors-theta-frequency, fig6h-errors-theta-power, fig6i-errors-not-speed¶

Readings (claims file, fig6f): (a) over aligned trials, error incidence against the mean of the measure across sessions, unsmoothed and with a 5-trial mean; (b) all trials pooled, the 0 or 1 error against the trial's value; (c) per rat as (a).

In [18]:
def err_corr(SS, col, smooth=False):
    e = mc.aligned_series(SS, "err")[0]["mean"]
    v = mc.aligned_series(SS, col)[0]["mean"]
    if smooth:
        e = e.rolling(5, center=True, min_periods=1).mean()
        v = v.rolling(5, center=True, min_periods=1).mean()
    j = e.index.intersection(v.index)
    return mc.corr(e.loc[j], v.loc[j])


def err_table(SS, col):
    rows = []
    r, p, n = err_corr(SS, col)
    rows.append(dict(reading="a aligned", rat="all", R=r, P=p, n=n))
    r, p, n = err_corr(SS, col, smooth=True)
    rows.append(dict(reading="a aligned, 5-trial mean", rat="all", R=r, P=p, n=n))
    d = pd.concat([S["trials"][["err", col]] for S in SS]).dropna()
    r, p, n = mc.corr(d.err, d[col])
    rows.append(dict(reading="b pooled trials", rat="all", R=r, P=p, n=n))
    for rat in sorted(set(S["rat"] for S in SS)):
        r, p, n = err_corr([S for S in SS if S["rat"] == rat], col)
        rows.append(dict(reading="c per rat", rat=rat, R=r, P=p, n=n))
        r, p, n = err_corr([S for S in SS if S["rat"] == rat], col, smooth=True)
        rows.append(dict(reading="c per rat, 5-trial mean", rat=rat, R=r, P=p, n=n))
    return pd.DataFrame(rows)
In [19]:
F6 = err_table(MEAS, "temp")
F6["R_in_tol"] = (F6.R + 0.35).abs() <= 0.035
print(F6.to_string(index=False))
                reading  rat       R         P    n  R_in_tol
              a aligned  all -0.6361 5.866e-15  120     False
a aligned, 5-trial mean  all -0.8688 8.139e-38  120     False
        b pooled trials  all -0.1531 4.894e-24 4313     False
              c per rat MS12 -0.2043   0.02584  119     False
c per rat, 5-trial mean MS12 -0.3942 9.177e-06  119     False
              c per rat MS13 -0.2763  0.002255  120     False
c per rat, 5-trial mean MS13 -0.6235 2.813e-14  120     False
              c per rat MS21 -0.5204 1.112e-09  120     False
c per rat, 5-trial mean MS21 -0.8106 3.367e-29  120     False
              c per rat MS22 -0.4019 5.376e-06  120     False
c per rat, 5-trial mean MS22 -0.6757 2.541e-17  120     False

Result: partially reproduced. Error incidence correlates negatively with MS temperature with P < 0.01 under the readings over aligned trials (R = -0.636 unsmoothed, -0.869 smoothed) and over pooled trials (R = -0.153, P = 4.9e-24), but no R is within -0.385 to -0.315. Per rat the unsmoothed R are -0.20 (MS12, P = 0.026), -0.28, -0.52 and -0.40.

In [20]:
for c in ["f_hil", "f_spec"]:
    G6 = err_table(LFPS, c)
    G6["R_in_tol"] = (G6.R + 0.35).abs() <= 0.035
    print(c); print(G6.to_string(index=False))
print("restricted to the measured-temperature sessions (f_hil):")
print(err_table(MEAS_L, "f_hil").head(3).to_string(index=False))
f_hil
                reading  rat       R         P    n  R_in_tol
              a aligned  all -0.7069 1.838e-19  120     False
a aligned, 5-trial mean  all -0.9116 2.278e-47  120     False
        b pooled trials  all -0.1157 1.529e-22 7087     False
              c per rat MS10 -0.3914 9.853e-06  120     False
c per rat, 5-trial mean MS10 -0.7136 5.904e-20  120     False
              c per rat MS12 -0.3032 0.0007628  120     False
c per rat, 5-trial mean MS12   -0.48  2.89e-08  120     False
              c per rat MS13 -0.3842  1.48e-05  120      True
c per rat, 5-trial mean MS13 -0.6283 1.574e-14  120     False
              c per rat MS21 -0.5357 2.895e-10  120     False
c per rat, 5-trial mean MS21 -0.8333 3.734e-32  120     False
              c per rat MS22 -0.4205 1.735e-06  120     False
c per rat, 5-trial mean MS22 -0.6884 3.703e-18  120     False
f_spec
                reading  rat        R         P    n  R_in_tol
              a aligned  all  -0.6802   1.3e-17  120     False
a aligned, 5-trial mean  all  -0.9103 4.979e-47  120     False
        b pooled trials  all -0.06027 3.822e-07 7087     False
              c per rat MS10  -0.2827  0.001754  120     False
c per rat, 5-trial mean MS10  -0.6709 5.117e-17  120     False
              c per rat MS12  -0.2591   0.00427  120     False
c per rat, 5-trial mean MS12  -0.3568 6.328e-05  120      True
              c per rat MS13  -0.3412 0.0001366  120      True
c per rat, 5-trial mean MS13  -0.5916 1.118e-12  120     False
              c per rat MS21  -0.4549 1.794e-07  120     False
c per rat, 5-trial mean MS21  -0.8165 6.237e-30  120     False
              c per rat MS22  -0.4129 2.777e-06  120     False
c per rat, 5-trial mean MS22  -0.6588 2.852e-16  120     False
restricted to the measured-temperature sessions (f_hil):
                reading rat       R         P    n
              a aligned all -0.6524 6.861e-16  120
a aligned, 5-trial mean all -0.8731 1.287e-38  120
        b pooled trials all  -0.151  1.76e-23 4323

Result: partially reproduced. Error incidence correlates negatively with theta frequency with P < 0.01 under every reading (aligned R = -0.707, pooled -0.116, per rat -0.30 to -0.54, all five rats P < 0.001). Only MS13 (-0.384) is within -0.385 to -0.315 and the pooled readings are not, so no reading puts R in tolerance.

In [21]:
for c, SS in [("p_hil_norm", LFPS), ("p_hil", LFPS), ("p_spec_norm", LFPS), ("p_hil_norm without MS13-171130", LFPS_GOOD)]:
    H6 = err_table(SS, c.split(" ")[0])
    pr = H6[H6.reading == "c per rat"]
    n1 = int(((pr.R < -0.3) & (pr.P < 0.01)).sum())
    n2 = int(((pr.R > -0.3) & (pr.P < 0.01)).sum())
    print(f"{c}: rats with R < -0.3 and P < 0.01: {n1} of {len(pr)}; with R > -0.3 and P < 0.01: {n2}")
    print(pr[["rat", "R", "P", "n"]].to_string(index=False))
p_hil_norm: rats with R < -0.3 and P < 0.01: 2 of 5; with R > -0.3 and P < 0.01: 0
 rat       R         P   n
MS10 -0.1803   0.04871 120
MS12 0.04701    0.6102 120
MS13 -0.3506 8.649e-05 120
MS21 -0.4826 2.382e-08 120
MS22  0.1247    0.1747 120
p_hil: rats with R < -0.3 and P < 0.01: 3 of 5; with R > -0.3 and P < 0.01: 0
 rat       R         P   n
MS10  -0.355 6.919e-05 120
MS12 -0.0323    0.7262 120
MS13 -0.3141 0.0004773 120
MS21 -0.4385 5.478e-07 120
MS22  0.1901    0.0376 120
p_spec_norm: rats with R < -0.3 and P < 0.01: 1 of 5; with R > -0.3 and P < 0.01: 0
 rat       R         P   n
MS10 -0.0387    0.6747 120
MS12  0.1199     0.192 120
MS13 -0.2015   0.02729 120
MS21 -0.4445 3.664e-07 120
MS22 -0.1911   0.03653 120
p_hil_norm without MS13-171130: rats with R < -0.3 and P < 0.01: 2 of 5; with R > -0.3 and P < 0.01: 0
 rat       R         P   n
MS10 -0.1803   0.04871 120
MS12 0.04701    0.6102 120
MS13  -0.315 0.0004573 120
MS21 -0.4826 2.382e-08 120
MS22  0.1247    0.1747 120

Result: reproduced. With the per-session normalised Hilbert power, 2 of 5 rats (MS13 R = -0.351, MS21 R = -0.483) have R below -0.3 with P < 0.01. The raw Hilbert power gives 3 rats and the normalised spectral power 1; no rat has R above -0.3 with P < 0.01. Without MS13-171130 (theta channel marked bad), 2 of 5 rats still count (MS13 R = -0.315, P = 4.6e-4). The count depends on the power measure: the outcome holds under the first.

In [22]:
for c in ["speed_all", "speed_run"]:
    I6 = err_table(SESS, c)
    pr = I6[I6.reading == "c per rat"]
    print(f"{c}: rats with P < 0.05: {int((pr.P < 0.05).sum())} of {len(pr)}")
    print(I6.to_string(index=False))
speed_all: rats with P < 0.05: 2 of 5
                reading  rat        R         P    n
              a aligned  all  -0.1462    0.1111  120
a aligned, 5-trial mean  all  -0.1554   0.09018  120
        b pooled trials  all   -0.172  2.55e-49 7260
              c per rat MS10  -0.2761  0.002267  120
c per rat, 5-trial mean MS10   -0.558 3.567e-11  120
              c per rat MS12  -0.1578   0.08515  120
c per rat, 5-trial mean MS12 -0.02973    0.7472  120
              c per rat MS13  -0.3275 0.0002607  120
c per rat, 5-trial mean MS13  -0.3756 2.369e-05  120
              c per rat MS21 -0.06788    0.4613  120
c per rat, 5-trial mean MS21  0.03247    0.7248  120
              c per rat MS22  -0.1499    0.1022  120
c per rat, 5-trial mean MS22  0.04689    0.6111  120
speed_run: rats with P < 0.05: 2 of 5
                reading  rat        R         P    n
              a aligned  all  -0.1276    0.1648  120
a aligned, 5-trial mean  all  -0.1394     0.129  120
        b pooled trials  all  -0.1518  1.13e-38 7260
              c per rat MS10  -0.2797  0.001976  120
c per rat, 5-trial mean MS10  -0.5548 4.877e-11  120
              c per rat MS12  -0.1562   0.08835  120
c per rat, 5-trial mean MS12 -0.01883    0.8383  120
              c per rat MS13  -0.3313  0.000219  120
c per rat, 5-trial mean MS13  -0.3767 2.234e-05  120
              c per rat MS21 -0.05805    0.5288  120
c per rat, 5-trial mean MS21  0.03694    0.6887  120
              c per rat MS22  -0.1166    0.2045  120
c per rat, 5-trial mean MS22  0.08555    0.3529  120

Result: not reproduced. Two of five rats show a significant correlation of error incidence with mean trial speed over aligned trials: MS10 R = -0.276 (P = 0.0023) and MS13 R = -0.328 (P = 0.00026); the others have P 0.09 to 0.46. Pooled over sessions the aligned R is -0.146 (P = 0.11).

suppl5j-errors-best-theta-frequency¶

Error rates correlated best with theta frequency, in correlations and partial correlations, and had no significant relationship to running speed.

In [23]:
def partial_corr(df, x, y, covars):
    import numpy.linalg as la
    d = df[[x, y] + covars].dropna()
    Z = np.column_stack([np.ones(len(d))] + [d[c].values for c in covars])
    rx = d[x].values - Z @ la.lstsq(Z, d[x].values, rcond=None)[0]
    ry = d[y].values - Z @ la.lstsq(Z, d[y].values, rcond=None)[0]
    r = np.corrcoef(rx, ry)[0, 1]
    dof = len(d) - 2 - len(covars)
    t_ = r * np.sqrt(dof / (1 - r ** 2))
    return r, 2 * stats.t.sf(abs(t_), dof), len(d)


for fc, pc, SS_name in [("f_hil", "p_hil_norm", "MEAS_L"), ("f_spec", "p_spec_norm", "MEAS_L")]:
    SS = MEAS_L
    A = pd.DataFrame({k: mc.aligned_series(SS, c)[0]["mean"] for k, c in
                      [("err", "err"), ("temp", "temp"), ("freq", fc), ("power", pc), ("speed", "speed_all")]}).dropna()
    rows = []
    for v in ["temp", "freq", "power", "speed"]:
        r, p, n = mc.corr(A.err, A[v])
        pr, pp, _ = partial_corr(A, "err", v, [o for o in ["temp", "freq", "power", "speed"] if o != v])
        rows.append(dict(measure=v, R=r, P=p, partial_R=pr, partial_P=pp, n=n))
    T5 = pd.DataFrame(rows)
    best_c = T5.measure[T5.R.abs().idxmax()]
    best_p = T5.measure[T5.partial_R.abs().idxmax()]
    sp_row = T5[T5.measure == "speed"].iloc[0]
    print(f"theta {fc}/{pc} over aligned trials of {SS_name} ({len(A)} trials):")
    print(T5.to_string(index=False))
    print(f"  largest |R|: {best_c}; largest |partial R|: {best_p}; speed P {sp_row.P:.3g}, partial P {sp_row.partial_P:.3g}")
theta f_hil/p_hil_norm over aligned trials of MEAS_L (120 trials):
measure       R         P  partial_R  partial_P   n
   temp -0.6361 5.866e-15    0.03974     0.6705 120
   freq -0.6524 6.861e-16    -0.2143    0.02035 120
  power -0.2573  0.004547  -0.006607     0.9436 120
  speed 0.02607    0.7774     0.2107     0.0226 120
  largest |R|: freq; largest |partial R|: freq; speed P 0.777, partial P 0.0226
theta f_spec/p_spec_norm over aligned trials of MEAS_L (120 trials):
measure       R         P  partial_R  partial_P   n
   temp -0.6361 5.866e-15    -0.2525   0.006016 120
   freq -0.6039 2.835e-13   -0.04438     0.6347 120
  power -0.5304 4.647e-10    0.03609     0.6993 120
  speed 0.02607    0.7774     0.1759    0.05788 120
  largest |R|: temp; largest |partial R|: temp; speed P 0.777, partial P 0.0579

Result: partially reproduced. With the Hilbert theta measures over 120 aligned trials of the measured-temperature sessions, theta frequency has the largest correlation with errors (R = -0.652) and the largest partial correlation (-0.214, P = 0.020), but speed, unrelated in the plain correlation (P = 0.78), has a significant partial correlation (0.211, P = 0.023). With the spectral measures temperature is largest in both.

fig4e-speed-decreases-within-session¶

Running speed decreased relatively monotonically within a session, over the entire session.

In [24]:
for c in ["speed_all", "speed_run"]:
    sa = aligned(SESS, c)
    r, p, n = mc.corr(sa.index.values, sa["mean"].values, "spearman")
    per = [mc.corr(S["trials"].trial_no, S["trials"][c], "spearman")[0] for S in SESS]
    per = np.array(per)
    ps, _ = mc.signrank(per)
    print(f"{c}: aligned mean speed against trial: Spearman {r:.3f}, P = {p:.3g} (n = {n}); "
          f"per session Spearman negative in {np.sum(per < 0)} of {len(per)} (median {np.nanmedian(per):.3f}); "
          f"signed-rank of per-session values P = {ps:.3g}")
    print("   by rat, median per-session Spearman:",
          pd.Series(per, index=[S["rat"] for S in SESS]).groupby(level=0).median().round(3).to_dict())
speed_all: aligned mean speed against trial: Spearman -0.873, P = 1.16e-38 (n = 120); per session Spearman negative in 50 of 51 (median -0.445); signed-rank of per-session values P = 7.35e-10
   by rat, median per-session Spearman: {'MS10': -0.464, 'MS12': -0.445, 'MS13': -0.498, 'MS21': -0.463, 'MS22': -0.339}
speed_run: aligned mean speed against trial: Spearman -0.881, P = 2.93e-40 (n = 120); per session Spearman negative in 50 of 51 (median -0.450); signed-rank of per-session values P = 7.35e-10
   by rat, median per-session Spearman: {'MS10': -0.458, 'MS12': -0.446, 'MS13': -0.513, 'MS21': -0.463, 'MS22': -0.367}

Result: reproduced. The aligned mean speed falls with trial number (Spearman -0.873, P = 1.2e-38, 120 trials), the per-session Spearman correlation of speed with trial number is negative in 50 of 51 sessions (median -0.445), and the signed-rank test gives P = 7.4e-10; every rat has a negative median.

Place fields¶

Pyramidal cells are the curated units typed "Pyramidal Cell" by the lab's CellExplorer file. Rate maps on the linearized maze (0 to 350 cm), left and right runs apart (Figure 3A, B), from the frames of the trials (the claims file's running reading (a); trials are the runs). Fields by the Figure 5 rule of the Methods on the map over all trials of the arm (states pooled, so that the field has the same boundaries in every state; an assumption, the paper does not say on which map fields are drawn). Figures 3 and 4 use the claims file's reading (b): the same rule with a peak above 10 Hz; reading (a), boundaries held by the dataset, is not available (the dandiset holds no place fields). Bins of 5 cm (main) and 3 cm (variant), the Methods' range. Per-state measures use the dataset's state labels (lab), and the 12 min reading (m12) as a variant.

In [25]:
T0 = time.time()
USESS = [S for S in SESS if S["has_units"] and any(u["cell_type"] == "Pyramidal Cell" for u in S["units"])]
FIELDS, MEASURES = {}, {}
for binw in (5.0, 3.0):
    for rd in (["lab", "m12"] if binw == 5.0 else ["lab"]):
        Fs, Ms = [], []
        for S in USESS:
            F, maps, edges = mc.session_fields(S, binw=binw)
            if not len(F):
                continue
            M = mc.field_state_measures(S, F, edges, state_col="st_" + rd)
            M["peak_all"] = np.repeat(F.peak_rate.values, 3)
            M["peak_pos"] = np.repeat(F.peak_pos.values, 3)
            Fs.append(F); Ms.append(M)
        FIELDS[(binw, rd)] = pd.concat(Fs, ignore_index=True)
        MEASURES[(binw, rd)] = pd.concat(Ms, ignore_index=True)
print(f"fields computed in {time.time() - T0:.0f} s")
for k, F in FIELDS.items():
    print(f"bins {k[0]} cm, states {k[1]}: {len(F)} fields (Figure 5 rule) of {F.groupby(['session', 'u']).ngroups} cells in "
          f"{F.session.nunique()} sessions; {int((F.peak_rate > 10).sum())} with peak above 10 Hz")
print("pyramidal cells per session:", {S["session"]: sum(u["cell_type"] == "Pyramidal Cell" for u in S["units"]) for S in USESS})


def wide(key=(5.0, "lab"), fig34=True, cols=None):
    M = MEASURES[key]
    if fig34:
        M = M[M.peak_all > 10]
    W = M.pivot_table(index=["session", "rat", "u", "arm", "lo", "hi"], columns="state", values=cols, aggfunc="first")
    return W
fields computed in 314 s
bins 5.0 cm, states lab: 1438 fields (Figure 5 rule) of 651 cells in 23 sessions; 1223 with peak above 10 Hz
bins 5.0 cm, states m12: 1438 fields (Figure 5 rule) of 651 cells in 23 sessions; 1223 with peak above 10 Hz
bins 3.0 cm, states lab: 1645 fields (Figure 5 rule) of 682 cells in 23 sessions; 1392 with peak above 10 Hz
pyramidal cells per session: {'MS10-170307-154746': 11, 'MS10-170314-163038': 13, 'MS10-170317-153237': 11, 'MS12-170714-122034': 30, 'MS12-170715-111545': 36, 'MS12-170716-172307': 32, 'MS12-170717-111614': 30, 'MS12-170719-095305': 31, 'MS13-171128-113924': 53, 'MS13-171129-105507': 89, 'MS13-171130-121758': 108, 'MS13-171201-130527': 43, 'MS21-180625-153927': 50, 'MS21-180627-143449': 121, 'MS21-180628-155921': 76, 'MS21-180629-110332': 121, 'MS21-180712-103200': 47, 'MS21-180719-155941': 92, 'MS22-180628-120341': 38, 'MS22-180629-110319': 129, 'MS22-180711-112912': 45, 'MS22-180719-122813': 43, 'MS22-180720-110055': 46}

suppl2-place-cell-rates-decrease¶

Within-field and peak firing rates of place cells decreased moderately during MS cooling (11% and 12%; P < 1e-9 and P < 1e-11).

In [26]:
rows = []
for key in MEASURES:
    for fig34 in (True, False):
        W = wide(key, fig34, ["rate_in", "peak"])
        for m in ["rate_in", "peak"]:
            pre, cool = W[(m, "Pre")], W[(m, "Cooling")]
            ok = np.isfinite(pre) & np.isfinite(cool) & (pre > 0)
            dec = 100 * (1 - cool[ok] / pre[ok])
            rows.append(dict(bins=key[0], states=key[1], fields=("peak>10" if fig34 else "Fig5 rule"), measure=m, n=int(ok.sum()),
                             a_median_dec=np.median(dec), b_dec_of_mean=100 * (1 - cool[ok].mean() / pre[ok].mean()),
                             c_mean_dec=dec.mean(), P=mc.signrank(cool[ok], pre[ok])[0]))
R2 = pd.DataFrame(rows)
print(R2.to_string(index=False))
print("by rat (5 cm, lab, peak > 10 Hz), reading (b):")
W = wide((5.0, "lab"), True, ["rate_in", "peak"])
print(W.groupby(level="rat").apply(lambda g: pd.Series({"n": len(g), "rate_in_dec": 100 * (1 - g[("rate_in", "Cooling")].mean() / g[("rate_in", "Pre")].mean()),
                                                         "peak_dec": 100 * (1 - g[("peak", "Cooling")].mean() / g[("peak", "Pre")].mean())})).round(2))
 bins states    fields measure    n  a_median_dec  b_dec_of_mean  c_mean_dec         P
    5    lab   peak>10 rate_in 1186        0.3761          3.971      -89.17    0.1222
    5    lab   peak>10    peak 1194         2.913          5.559      -280.4 0.0007123
    5    lab Fig5 rule rate_in 1390         1.016          4.673      -92.02    0.0448
    5    lab Fig5 rule    peak 1402         4.017          6.273      -256.5 6.289e-05
    5    m12   peak>10 rate_in 1170        -2.566          0.977      -94.93    0.4876
    5    m12   peak>10    peak 1177         1.371          4.043      -287.2   0.05414
    5    m12 Fig5 rule rate_in 1372        -2.716          1.551      -99.61    0.5563
    5    m12 Fig5 rule    peak 1383         1.298          4.642      -277.5   0.02082
    3    lab   peak>10 rate_in 1346         1.191           4.68      -91.56   0.03915
    3    lab   peak>10    peak 1352         4.365          5.514       -75.8 0.0001654
    3    lab Fig5 rule rate_in 1583         2.036          6.171      -97.15  0.002654
    3    lab Fig5 rule    peak 1592         5.807           6.84      -72.67  6.24e-07
by rat (5 cm, lab, peak > 10 Hz), reading (b):
       n  rate_in_dec  peak_dec
rat                            
MS10  39        24.77     16.66
MS12 271       -11.44     -0.36
MS13 159        17.96     13.48
MS21 483         6.15      6.52
MS22 271         0.08      1.67

Result: partially reproduced. Rates fall less than the paper reports. With 5 cm bins and fields peaking above 10 Hz, the within-field rate falls by 0.4 to 4.0% (P = 0.12) and the peak rate by 2.9 to 5.6% (P = 7.1e-4). With 3 cm bins both decreases are significant (within-field P = 0.039, peak P = 1.7e-4), but no reading brings them near 11 and 12%. Only one P is below 1e-6, the peak rate with 3 cm bins and the Figure 5 rule fields (P = 6.2e-7, a 5.8 to 6.8% decrease). The mean of per-field decreases is dominated by fields with near-zero pre rates.

suppl2ab-rates-correlated¶

Firing rates of pyramidal cells before and during MS cooling were strongly correlated (R = 0.7, P < 1e-58).

In [27]:
rows = []
for key in MEASURES:
    for fig34 in (True, False):
        W = wide(key, fig34, ["rate_in", "peak"])
        for m in ["rate_in", "peak"]:
            pre, cool = W[(m, "Pre")], W[(m, "Cooling")]
            ok = np.isfinite(pre) & np.isfinite(cool) & (pre > 0) & (cool > 0)
            r1, p1, n = mc.corr(pre[ok], cool[ok])
            r2, p2, _ = mc.corr(np.log10(pre[ok]), np.log10(cool[ok]))
            rows.append(dict(bins=key[0], states=key[1], fields=("peak>10" if fig34 else "Fig5 rule"), measure=m, n=n,
                             R_linear=r1, P_linear=p1, R_log=r2, P_log=p2))
AB = pd.DataFrame(rows)
AB["in_tol"] = ((AB.R_linear - 0.7).abs() <= 0.07) & (AB.P_linear < 1e-20) | ((AB.R_log - 0.7).abs() <= 0.07) & (AB.P_log < 1e-20)
print(AB.to_string(index=False))
 bins states    fields measure    n  R_linear   P_linear  R_log      P_log  in_tol
    5    lab   peak>10 rate_in 1185    0.6575 1.204e-147 0.5423   1.45e-91    True
    5    lab   peak>10    peak 1193    0.6188 5.047e-127 0.4884   1.54e-72   False
    5    lab Fig5 rule rate_in 1384    0.6767 5.131e-186 0.5574 8.379e-114    True
    5    lab Fig5 rule    peak 1396    0.6522 6.036e-170 0.5224  1.438e-98    True
    5    m12   peak>10 rate_in 1169    0.6714 4.944e-154 0.5528  1.571e-94    True
    5    m12   peak>10    peak 1177    0.6277 5.926e-130 0.4897  5.186e-72   False
    5    m12 Fig5 rule rate_in 1368      0.69 5.767e-194 0.5666 5.235e-117    True
    5    m12 Fig5 rule    peak 1380    0.6609 5.666e-174 0.5086  1.189e-91    True
    3    lab   peak>10 rate_in 1341      0.64 2.005e-155 0.5198  1.071e-93    True
    3    lab   peak>10    peak 1345    0.6001 2.144e-132 0.5257  1.969e-96   False
    3    lab Fig5 rule rate_in 1573     0.663 9.577e-200 0.5296 1.885e-114    True
    3    lab Fig5 rule    peak 1580    0.6388 6.343e-182 0.5466  9.09e-124    True

Result: reproduced. The within-field rates of 1185 fields before and during cooling correlate with R = 0.658 (P = 1.2e-147), within 0.63 to 0.77; peak rates give 0.619 and log scales 0.49 to 0.57.

fig4b-fp-flfp-decrease¶

MS cooling decreased both the oscillation frequency of place cells (fp) and the LFP theta frequency in their fields (fLFP) by about the same degree, and both recovered (fLFP 8.4, 7.7, 8.5 Hz; fp 10.6, 9.5, 10.4 Hz before, during and after; n = 365).

Fields are kept when the autocorrelogram has a peak between 50 and 150 ms in each state (criterion). fLFP readings: (a) at the field's spikes, (b) over the time in the field (from the theta cycles whose middle falls in the field).

In [28]:
EXP = dict(flfp=(8.4, 7.7, 8.5), flfp_tol=(0.38, 0.36, 0.29), fp=(10.6, 9.5, 10.4), fp_tol=(0.95, 0.84, 0.72))


def fp_fields(key=(5.0, "lab"), fig34=True):
    W = wide(key, fig34, ["fp", "flfp_spk", "flfp_time", "size", "v_time", "v_spk", "info", "prec_slope", "rate_in", "peak"])
    ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
    return W[ok]


rows = []
for key in MEASURES:
    for fig34 in (True, False):
        W = fp_fields(key, fig34)
        for fl in ["flfp_spk", "flfp_time"]:
            m_fp = [W[("fp", s)].mean() for s in mc.STATES]
            m_fl = [W[(fl, s)].mean() for s in mc.STATES]
            inside = all(abs(m_fl[i] - EXP["flfp"][i]) <= EXP["flfp_tol"][i] for i in range(3)) and \
                all(abs(m_fp[i] - EXP["fp"][i]) <= EXP["fp_tol"][i] for i in range(3))
            rows.append(dict(bins=key[0], states=key[1], fields=("peak>10" if fig34 else "Fig5 rule"), flfp=fl, n=len(W),
                             fp_pre=m_fp[0], fp_cool=m_fp[1], fp_post=m_fp[2],
                             flfp_pre=m_fl[0], flfp_cool=m_fl[1], flfp_post=m_fl[2],
                             P_fp=mc.signrank(W[("fp", "Cooling")], W[("fp", "Pre")])[0],
                             P_flfp=mc.signrank(W[(fl, "Cooling")], W[(fl, "Pre")])[0],
                             all_six_in_tol=inside))
B4 = pd.DataFrame(rows)
print(B4.to_string(index=False))
W = fp_fields()
print(f"main (5 cm, lab, peak > 10 Hz): {len(W)} fields of {len(wide((5.0, 'lab'), True, ['fp']))} kept; SD over fields "
      f"fp {[round(float(W[('fp', s)].std()), 2) for s in mc.STATES]}, fLFP (spikes) {[round(float(W[('flfp_spk', s)].std()), 2) for s in mc.STATES]}")
print("by rat, mean fp and fLFP (spikes) per state:")
print(W.groupby(level="rat")[[("fp", s) for s in mc.STATES] + [("flfp_spk", s) for s in mc.STATES]].mean().round(2))
print("fields per rat:", W.groupby(level="rat").size().to_dict())
 bins states    fields      flfp    n  fp_pre  fp_cool  fp_post  flfp_pre  flfp_cool  flfp_post      P_fp     P_flfp  all_six_in_tol
    5    lab   peak>10  flfp_spk  878    10.5    9.644    10.36     8.272      7.623      8.431 1.942e-75 1.626e-101            True
    5    lab   peak>10 flfp_time  878    10.5    9.644    10.36     8.529      7.811      8.625 1.942e-75 3.429e-126            True
    5    lab Fig5 rule  flfp_spk  993    10.5    9.625    10.35     8.288      7.625      8.434 1.499e-81 1.411e-116            True
    5    lab Fig5 rule flfp_time  993    10.5    9.625    10.35     8.541       7.81      8.628 1.499e-81 4.185e-143            True
    5    m12   peak>10  flfp_spk  886    10.5    9.878    10.23      8.28      7.832      8.331 5.455e-54  2.063e-74            True
    5    m12   peak>10 flfp_time  886    10.5    9.878    10.23      8.54      8.017      8.533 5.455e-54 3.943e-111            True
    5    m12 Fig5 rule  flfp_spk 1007    10.5    9.861    10.23     8.294      7.831      8.335 1.098e-57   5.09e-87            True
    5    m12 Fig5 rule flfp_time 1007    10.5    9.861    10.23     8.549      8.014      8.538 1.098e-57 7.441e-128            True
    3    lab   peak>10  flfp_spk  938   10.52    9.692    10.36     8.282      7.636      8.439 1.327e-72 4.252e-105            True
    3    lab   peak>10 flfp_time  938   10.52    9.692    10.36     8.536      7.817      8.631 1.327e-72 2.206e-131            True
    3    lab Fig5 rule  flfp_spk 1039   10.52    9.677    10.37     8.291      7.635      8.441 8.015e-78 1.216e-115            True
    3    lab Fig5 rule flfp_time 1039   10.52    9.677    10.37     8.542      7.818      8.631 8.015e-78 5.024e-145            True
main (5 cm, lab, peak > 10 Hz): 878 fields of 1205 kept; SD over fields fp [1.21, 1.03, 0.98], fLFP (spikes) [0.67, 0.53, 0.51]
by rat, mean fp and fLFP (spikes) per state:
         fp               flfp_spk             
state   Pre Cooling  Post      Pre Cooling Post
rat                                            
MS10   9.84    9.02  9.28     7.91    7.03  7.7
MS12  10.57    9.11 10.18     7.99    7.52 8.47
MS13  11.05   10.07 10.61     8.95    7.99 8.82
MS21  10.36    9.71 10.42     8.07    7.45 8.22
MS22  10.53    9.87 10.47     8.66    7.96 8.74
fields per rat: {'MS10': 30, 'MS12': 173, 'MS13': 92, 'MS21': 384, 'MS22': 199}
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)

Result: reproduced. Over 878 fields with an autocorrelogram peak in every state (5 cm bins, fields above 10 Hz), fp is 10.50, 9.64 and 10.36 Hz and fLFP at the spikes 8.27, 7.62 and 8.43 Hz before, during and after cooling, all six within tolerance, with both decreases significant (signed-rank P = 1.9e-75 and 1.6e-101). Every other reading also puts all six within tolerance. The paper has 365 fields.

fig4c-fp-flfp-correlation¶

fp and fLFP were correlated across place fields before, during and after cooling (R = 0.61, 0.59 and 0.36; P < 1e-6 each), with the range of fp larger than that of fLFP.

In [29]:
rows = []
for key in MEASURES:
    for fig34 in (True, False):
        W = fp_fields(key, fig34)
        for fl in ["flfp_spk", "flfp_time"]:
            r = {}
            for s in mc.STATES:
                R_, P_, n = mc.corr(W[("fp", s)], W[(fl, s)])
                r[f"R_{s}"], r[f"P_{s}"] = R_, P_
            sd = [W[("fp", s)].std() > W[(fl, s)].std() for s in ("Pre", "Cooling")]
            rows.append(dict(bins=key[0], states=key[1], fields=("peak>10" if fig34 else "Fig5 rule"), flfp=fl, n=len(W), **r,
                             sd_fp_gt_flfp_pre_cool=all(sd)))
C4 = pd.DataFrame(rows)
C4["all_in_tol"] = ((C4.R_Pre - 0.61).abs() <= 0.061) & ((C4.R_Cooling - 0.59).abs() <= 0.059) & ((C4.R_Post - 0.36).abs() <= 0.036)
print(C4.to_string(index=False))
 bins states    fields      flfp    n  R_Pre     P_Pre  R_Cooling  P_Cooling  R_Post    P_Post  sd_fp_gt_flfp_pre_cool  all_in_tol
    5    lab   peak>10  flfp_spk  878 0.2476 9.843e-14     0.4255  6.332e-40  0.2379  9.17e-13                    True       False
    5    lab   peak>10 flfp_time  878 0.3639 6.903e-29     0.4418  2.986e-43  0.3104 4.668e-21                    True       False
    5    lab Fig5 rule  flfp_spk  993 0.2531 5.571e-16     0.3946  2.397e-38  0.2261 5.597e-13                    True       False
    5    lab Fig5 rule flfp_time  993 0.3639 1.866e-32      0.427  2.822e-45  0.2841 6.819e-20                    True       False
    5    m12   peak>10  flfp_spk  886 0.2568 8.227e-15     0.4795  3.848e-52  0.3472 1.685e-26                    True       False
    5    m12   peak>10 flfp_time  886 0.3605 1.402e-28      0.494  1.058e-55  0.4091 4.439e-37                    True       False
    5    m12 Fig5 rule  flfp_spk 1007 0.2606 4.286e-17     0.4616  2.769e-54  0.3292  6.98e-27                    True       False
    5    m12 Fig5 rule flfp_time 1007  0.363 9.881e-33      0.476  4.382e-58  0.3899 6.561e-38                    True       False
    3    lab   peak>10  flfp_spk  938 0.2266  2.19e-12     0.4166  1.125e-40  0.2308 8.349e-13                    True       False
    3    lab   peak>10 flfp_time  938 0.3227 3.566e-24     0.4352   1.24e-44  0.2593  7.11e-16                    True       False
    3    lab Fig5 rule  flfp_spk 1039 0.2083 1.191e-11     0.3858  3.261e-38  0.2121 4.896e-12                    True       False
    3    lab Fig5 rule flfp_time 1039 0.3124 5.965e-25     0.4111  1.255e-43  0.2363 1.174e-14                    True       False
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)

Result: partially reproduced. fp and fLFP correlate positively in every state with P below 1e-11 under every reading, and fp spreads more than fLFP (SD 1.21 against 0.67 Hz pre, 1.03 against 0.53 Hz cooling), but R is lower than the paper's: 0.25, 0.43 and 0.24 at the spikes and 0.36, 0.44 and 0.31 over the time in the field, against 0.61, 0.59 and 0.36.

fig4ac-fp-flfp-difference-preserved¶

During MS cooling fp and fLFP decreased in parallel, so the difference fp - fLFP remained constant.

In [30]:
for key in [(5.0, "lab"), (3.0, "lab"), (5.0, "m12")]:
    W = fp_fields(key)
    for fl in ["flfp_spk", "flfp_time"]:
        d = {s: W[("fp", s)] - W[(fl, s)] for s in mc.STATES}
        p, n = mc.signrank(d["Cooling"], d["Pre"])
        print(f"bins {key[0]}, states {key[1]}, fLFP {fl}: fp - fLFP mean pre {d['Pre'].mean():.2f}, cooling {d['Cooling'].mean():.2f}, "
              f"post {d['Post'].mean():.2f} Hz; median change cooling - pre {np.median(d['Cooling'] - d['Pre']):.3f} Hz; signed-rank P = {p:.3g} (n = {n})")
print("paper's means give fp - fLFP of 2.2, 1.8 and 1.9 Hz")
bins 5.0, states lab, fLFP flfp_spk: fp - fLFP mean pre 2.22, cooling 2.02, post 1.93 Hz; median change cooling - pre -0.141 Hz; signed-rank P = 1.09e-06 (n = 878)
bins 5.0, states lab, fLFP flfp_time: fp - fLFP mean pre 1.97, cooling 1.83, post 1.74 Hz; median change cooling - pre -0.125 Hz; signed-rank P = 0.000203 (n = 878)
bins 3.0, states lab, fLFP flfp_spk: fp - fLFP mean pre 2.24, cooling 2.06, post 1.93 Hz; median change cooling - pre -0.125 Hz; signed-rank P = 3.37e-05 (n = 938)
bins 3.0, states lab, fLFP flfp_time: fp - fLFP mean pre 1.99, cooling 1.87, post 1.73 Hz; median change cooling - pre -0.108 Hz; signed-rank P = 0.00185 (n = 938)
bins 5.0, states m12, fLFP flfp_spk: fp - fLFP mean pre 2.22, cooling 2.05, post 1.90 Hz; median change cooling - pre -0.132 Hz; signed-rank P = 2.76e-06 (n = 886)
bins 5.0, states m12, fLFP flfp_time: fp - fLFP mean pre 1.96, cooling 1.86, post 1.70 Hz; median change cooling - pre -0.128 Hz; signed-rank P = 0.000422 (n = 886)
paper's means give fp - fLFP of 2.2, 1.8 and 1.9 Hz
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)

Result: not reproduced. fp - fLFP falls slightly during cooling (2.22 to 2.02 Hz, median change -0.14 Hz), and the signed-rank test over 878 fields finds it (P = 1.1e-6; P = 2.0e-4 with fLFP over the time in the field). The paper's own means give 2.2 and 1.8 Hz.

fig3c-field-size-correlated, fig3d-size-fp-negative, fig3e-model-field-size, fig3f-information-unchanged¶

In [31]:
for key in MEASURES:
    W = wide(key, True, ["size"])
    ok = W[("size", "Pre")].notna() & W[("size", "Cooling")].notna()
    r, p, n = mc.corr(W.loc[ok, ("size", "Pre")], W.loc[ok, ("size", "Cooling")])
    dd = W.loc[ok, ("size", "Cooling")] - W.loc[ok, ("size", "Pre")]
    print(f"bins {key[0]}, states {key[1]}: R of size pre against cooling {r:.3f} (P = {p:.2g}, n = {n}); "
          f"median size pre {W.loc[ok, ('size', 'Pre')].median():.1f} cm, cooling {W.loc[ok, ('size', 'Cooling')].median():.1f} cm; "
          f"median change {dd.median():.1f} cm, signed-rank P = {mc.signrank(dd)[0]:.3g}")
bins 5.0, states lab: R of size pre against cooling 0.465 (P = 5.9e-65, n = 1193); median size pre 60.0 cm, cooling 60.0 cm; median change 0.0 cm, signed-rank P = 0.0824
bins 5.0, states m12: R of size pre against cooling 0.490 (P = 3.3e-72, n = 1177); median size pre 60.0 cm, cooling 60.0 cm; median change 0.0 cm, signed-rank P = 7.31e-06
bins 3.0, states lab: R of size pre against cooling 0.410 (P = 1.4e-55, n = 1345); median size pre 48.0 cm, cooling 51.0 cm; median change 0.0 cm, signed-rank P = 0.19

Result: not reproduced. Field size before and during cooling correlates with R = 0.465 (1193 fields, 5 cm bins), 0.490 (12 min states) and 0.410 (3 cm bins), all below 0.5. The median size does not change (60 cm in both; signed-rank P = 0.082).

In [32]:
for key in MEASURES:
    W = fp_fields(key)
    out = []
    for s in mc.STATES:
        r, p, n = mc.corr(W[("size", s)], W[("fp", s)])
        lr = stats.linregress(W[("fp", s)], W[("size", s)])
        out.append(f"{s}: R {r:.3f} (P = {p:.2g}), slope {lr.slope:.2f} cm/Hz, intercept {lr.intercept:.1f} cm")
    print(f"bins {key[0]}, states {key[1]}, n = {len(W)}: " + "; ".join(out))
bins 5.0, states lab, n = 878: Pre: R -0.181 (P = 7e-08), slope -7.61 cm/Hz, intercept 155.9 cm; Cooling: R -0.204 (P = 1.1e-09), slope -9.89 cm/Hz, intercept 173.2 cm; Post: R -0.141 (P = 2.8e-05), slope -7.13 cm/Hz, intercept 152.5 cm
bins 5.0, states m12, n = 886: Pre: R -0.186 (P = 2.7e-08), slope -7.82 cm/Hz, intercept 158.0 cm; Cooling: R -0.177 (P = 1.2e-07), slope -9.68 cm/Hz, intercept 177.5 cm; Post: R -0.173 (P = 2.3e-07), slope -8.68 cm/Hz, intercept 167.0 cm
bins 3.0, states lab, n = 938: Pre: R -0.152 (P = 2.8e-06), slope -4.62 cm/Hz, intercept 109.8 cm; Cooling: R -0.177 (P = 4.5e-08), slope -6.20 cm/Hz, intercept 122.0 cm; Post: R -0.161 (P = 7e-07), slope -5.64 cm/Hz, intercept 119.4 cm
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)

Result: partially reproduced. Field size and fp correlate negatively in every state (R = -0.181, -0.204 and -0.141; P = 7e-8, 1.1e-9 and 2.8e-5), weaker than -0.49 and -0.40 and with P above 1e-9 in all three states (the smallest, cooling, is 1.1e-9). The regression slopes are -7.6, -9.9 and -7.1 cm/Hz; the cooling intercept is higher, not lower.

In [33]:
for key in MEASURES:
    W = fp_fields(key)
    for v in ["v_time", "v_spk"]:
        for fl in ["flfp_spk", "flfp_time"]:
            out = []
            for s in mc.STATES:
                dfp = W[("fp", s)] - W[(fl, s)]
                ok = dfp > 0
                pred = W[(v, s)][ok] / dfp[ok]
                r, p, n = mc.corr(W[("size", s)][ok], pred)
                out.append(f"{s} R {r:.3f} (P = {p:.2g}, n = {n}, left out {int((~ok).sum())})")
            print(f"bins {key[0]}, states {key[1]}, v {v}, fLFP {fl}: " + "; ".join(out))
bins 5.0, states lab, v v_time, fLFP flfp_spk: Pre R -0.009 (P = 0.8, n = 861, left out 17); Cooling R 0.134 (P = 7.7e-05, n = 862, left out 16); Post R 0.127 (P = 0.0002, n = 859, left out 19)
bins 5.0, states lab, v v_time, fLFP flfp_time: Pre R 0.059 (P = 0.088, n = 851, left out 27); Cooling R 0.048 (P = 0.16, n = 866, left out 12); Post R 0.008 (P = 0.81, n = 854, left out 24)
bins 5.0, states lab, v v_spk, fLFP flfp_spk: Pre R -0.006 (P = 0.85, n = 861, left out 17); Cooling R 0.117 (P = 0.00057, n = 862, left out 16); Post R 0.111 (P = 0.0011, n = 859, left out 19)
bins 5.0, states lab, v v_spk, fLFP flfp_time: Pre R 0.058 (P = 0.092, n = 851, left out 27); Cooling R 0.051 (P = 0.13, n = 866, left out 12); Post R 0.007 (P = 0.83, n = 854, left out 24)
bins 5.0, states m12, v v_time, fLFP flfp_spk: Pre R -0.007 (P = 0.84, n = 866, left out 20); Cooling R 0.055 (P = 0.1, n = 879, left out 7); Post R -0.022 (P = 0.52, n = 868, left out 18)
bins 5.0, states m12, v v_time, fLFP flfp_time: Pre R -0.018 (P = 0.61, n = 857, left out 29); Cooling R 0.042 (P = 0.21, n = 875, left out 11); Post R 0.075 (P = 0.027, n = 861, left out 25)
bins 5.0, states m12, v v_spk, fLFP flfp_spk: Pre R -0.005 (P = 0.89, n = 866, left out 20); Cooling R 0.050 (P = 0.14, n = 879, left out 7); Post R -0.022 (P = 0.51, n = 868, left out 18)
bins 5.0, states m12, v v_spk, fLFP flfp_time: Pre R -0.012 (P = 0.73, n = 857, left out 29); Cooling R 0.039 (P = 0.25, n = 875, left out 11); Post R 0.064 (P = 0.06, n = 861, left out 25)
bins 3.0, states lab, v v_time, fLFP flfp_spk: Pre R -0.031 (P = 0.35, n = 914, left out 24); Cooling R 0.005 (P = 0.88, n = 922, left out 16); Post R 0.054 (P = 0.1, n = 908, left out 30)
bins 3.0, states lab, v v_time, fLFP flfp_time: Pre R 0.010 (P = 0.75, n = 906, left out 32); Cooling R 0.096 (P = 0.0035, n = 923, left out 15); Post R 0.016 (P = 0.63, n = 901, left out 37)
bins 3.0, states lab, v v_spk, fLFP flfp_spk: Pre R -0.032 (P = 0.33, n = 914, left out 24); Cooling R -0.004 (P = 0.89, n = 922, left out 16); Post R 0.057 (P = 0.087, n = 908, left out 30)
bins 3.0, states lab, v v_spk, fLFP flfp_time: Pre R 0.018 (P = 0.59, n = 906, left out 32); Cooling R 0.100 (P = 0.0023, n = 923, left out 15); Post R -0.007 (P = 0.83, n = 901, left out 37)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)
/tmp/ipykernel_2386/1927467069.py:6: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  ok = W["fp"].notna().all(1) & W["flfp_spk"].notna().all(1)

Result: not reproduced. The size predicted by v / (fp - fLFP) does not correlate with the measured size before cooling under any reading (R -0.032 to 0.059, P >= 0.088), and the cooling and post R are 0.134 at most.

In [34]:
for key in MEASURES:
    for fig34 in (True, False):
        W = wide(key, fig34, ["info"]).groupby(level=["session", "rat", "u", "arm"]).first()
        out = []
        for a_, b_ in [("Pre", "Cooling"), ("Cooling", "Post"), ("Pre", "Post")]:
            p, n = mc.signrank(W[("info", b_)], W[("info", a_)])
            out.append(f"{a_}-{b_}: median change {np.nanmedian(W[('info', b_)] - W[('info', a_)]):.3f} bits/spike, P = {p:.3g}")
        print(f"bins {key[0]}, states {key[1]}, {'peak>10' if fig34 else 'Fig5 rule'} (n = {len(W)}): " + "; ".join(out))
print("information is per map (cell and arm), counted once per map with a field; a cell with fields on both arms counts once per arm")
# equal trials per state: Skaggs information is biased upward with fewer data, and the states differ in trial counts
rng_info = np.random.default_rng(31)
T0 = time.time()
IEQ = []
for S in USESS:
    F = FIELDS[(5.0, "lab")]
    F = F[F.session == S["session"]]
    if len(F):
        I = mc.info_equal_trials(S, F, np.arange(0, 355, 5.0), "st_lab", n_draws=20, rng=rng_info)
        I["peak10"] = [bool(((F.u == u) & (F.arm == a) & (F.peak_rate > 10)).any()) for u, a in zip(I.u, I.arm)]
        IEQ.append(I)
IEQ = pd.concat(IEQ, ignore_index=True)
print(f"equal-trial information ({time.time() - T0:.0f} s): trials per state and arm, median {IEQ.trials.median():.0f} (range {IEQ.trials.min()} to {IEQ.trials.max()})")
tc = pd.concat([S["trials"].assign(session=S["session"]) for S in USESS]).groupby(["session", "arm", "st_lab"]).size().unstack()
print("trials per state and arm (unequal reading), median:", tc.median().to_dict())
for lab_, I in [("peak>10", IEQ[IEQ.peak10]), ("Fig5 rule", IEQ)]:
    out = []
    for a_, b_ in [("Pre", "Cooling"), ("Cooling", "Post"), ("Pre", "Post")]:
        p, n = mc.signrank(I[b_], I[a_])
        out.append(f"{a_}-{b_}: median change {np.nanmedian(I[b_] - I[a_]):.3f} bits/spike, P = {p:.3g}")
    print(f"equal trials, bins 5.0, states lab, {lab_} (n = {len(I)}; median pre {I.Pre.median():.3f}, cooling {I.Cooling.median():.3f}, post {I.Post.median():.3f}): " + "; ".join(out))# equal spikes per state, and information minus the bias of a spatially uniform rate (shuffle-corrected):
# speed falls within sessions, so equal trials do not mean equal time or spikes
rng_info2 = np.random.default_rng(37)
T0 = time.time()
ISP = []
for S in USESS:
    F = FIELDS[(5.0, "lab")]
    F = F[F.session == S["session"]]
    if len(F):
        I = mc.info_equal_spikes(S, F, np.arange(0, 355, 5.0), "st_lab", n_draws=20, rng=rng_info2)
        I["peak10"] = [bool(((F.u == u) & (F.arm == a) & (F.peak_rate > 10)).any()) for u, a in zip(I.u, I.arm)]
        ISP.append(I)
ISP = pd.concat(ISP, ignore_index=True)
occ_t = pd.DataFrame([dict(session=S["session"], arm=a, state=s_, t=mc.occupancy(S, a, np.arange(0, 355, 5.0), S["trials"].st_lab.values == s_).sum())
                      for S in USESS for a in ("Left", "Right") for s_ in mc.STATES]).pivot_table(index=["session", "arm"], columns="state", values="t")
print(f"equal-spike and shuffle-corrected information ({time.time() - T0:.0f} s): {len(ISP)} maps with at least 20 spikes in every state; "
      f"spikes per state after equalising, median {ISP.spikes.median():.0f}; occupancy per arm, median pre {occ_t.Pre.median():.0f} s, "
      f"cooling {occ_t.Cooling.median():.0f} s, post {occ_t.Post.median():.0f} s")
print(f"estimated bias (information of a uniform-rate map with the same spikes and occupancy), median: pre {ISP.bias_Pre.median():.3f}, "
      f"cooling {ISP.bias_Cooling.median():.3f}, post {ISP.bias_Post.median():.3f} bits/spike")
for lab_, I in [("peak>10", ISP[ISP.peak10]), ("Fig5 rule", ISP)]:
    for m_, nm_ in [("eq", "equal spikes"), ("corr", "shuffle-corrected")]:
        out = []
        for a_, b_ in [("Pre", "Cooling"), ("Cooling", "Post"), ("Pre", "Post")]:
            p, n = mc.signrank(I[f"{m_}_{b_}"], I[f"{m_}_{a_}"])
            out.append(f"{a_}-{b_}: median change {np.nanmedian(I[f'{m_}_{b_}'] - I[f'{m_}_{a_}']):.3f} bits/spike, P = {p:.3g}")
        print(f"{nm_}, bins 5.0, states lab, {lab_} (n = {len(I)}; median pre {I[f'{m_}_Pre'].median():.3f}, cooling {I[f'{m_}_Cooling'].median():.3f}, "
              f"post {I[f'{m_}_Post'].median():.3f}): " + "; ".join(out))
bins 5.0, states lab, peak>10 (n = 908): Pre-Cooling: median change -0.015 bits/spike, P = 0.346; Cooling-Post: median change -0.015 bits/spike, P = 0.0784; Pre-Post: median change -0.038 bits/spike, P = 0.00543
bins 5.0, states lab, Fig5 rule (n = 1018): Pre-Cooling: median change -0.019 bits/spike, P = 0.281; Cooling-Post: median change -0.019 bits/spike, P = 0.0329; Pre-Post: median change -0.041 bits/spike, P = 0.00117
bins 5.0, states m12, peak>10 (n = 908): Pre-Cooling: median change -0.032 bits/spike, P = 0.0248; Cooling-Post: median change -0.007 bits/spike, P = 0.476; Pre-Post: median change -0.039 bits/spike, P = 0.00293
bins 5.0, states m12, Fig5 rule (n = 1018): Pre-Cooling: median change -0.035 bits/spike, P = 0.00752; Cooling-Post: median change -0.007 bits/spike, P = 0.392; Pre-Post: median change -0.042 bits/spike, P = 0.000572
bins 3.0, states lab, peak>10 (n = 948): Pre-Cooling: median change -0.025 bits/spike, P = 0.114; Cooling-Post: median change -0.022 bits/spike, P = 0.0233; Pre-Post: median change -0.063 bits/spike, P = 0.000105
bins 3.0, states lab, Fig5 rule (n = 1057): Pre-Cooling: median change -0.037 bits/spike, P = 0.0518; Cooling-Post: median change -0.029 bits/spike, P = 0.00229; Pre-Post: median change -0.070 bits/spike, P = 4e-06
information is per map (cell and arm), counted once per map with a field; a cell with fields on both arms counts once per arm
equal-trial information (14 s): trials per state and arm, median 17 (range 5 to 26)
trials per state and arm (unequal reading), median: {'Cooling': 21.0, 'Post': 23.0, 'Pre': 20.0}
equal trials, bins 5.0, states lab, peak>10 (n = 902; median pre 1.243, cooling 1.239, post 1.208): Pre-Cooling: median change -0.017 bits/spike, P = 0.221; Cooling-Post: median change -0.014 bits/spike, P = 0.218; Pre-Post: median change -0.030 bits/spike, P = 0.016
equal trials, bins 5.0, states lab, Fig5 rule (n = 1011; median pre 1.235, cooling 1.226, post 1.196): Pre-Cooling: median change -0.024 bits/spike, P = 0.144; Cooling-Post: median change -0.015 bits/spike, P = 0.141; Pre-Post: median change -0.033 bits/spike, P = 0.00467
equal-spike and shuffle-corrected information (27 s): 939 maps with at least 20 spikes in every state; spikes per state after equalising, median 171; occupancy per arm, median pre 58 s, cooling 72 s, post 72 s
estimated bias (information of a uniform-rate map with the same spikes and occupancy), median: pre 0.056, cooling 0.049, post 0.040 bits/spike
equal spikes, bins 5.0, states lab, peak>10 (n = 848; median pre 1.195, cooling 1.204, post 1.161): Pre-Cooling: median change -0.010 bits/spike, P = 0.472; Cooling-Post: median change -0.018 bits/spike, P = 0.107; Pre-Post: median change -0.025 bits/spike, P = 0.0318
shuffle-corrected, bins 5.0, states lab, peak>10 (n = 848; median pre 1.109, cooling 1.116, post 1.085): Pre-Cooling: median change -0.007 bits/spike, P = 0.754; Cooling-Post: median change -0.012 bits/spike, P = 0.182; Pre-Post: median change -0.022 bits/spike, P = 0.0851
equal spikes, bins 5.0, states lab, Fig5 rule (n = 939; median pre 1.177, cooling 1.190, post 1.155): Pre-Cooling: median change -0.015 bits/spike, P = 0.43; Cooling-Post: median change -0.025 bits/spike, P = 0.0697; Pre-Post: median change -0.024 bits/spike, P = 0.0239
shuffle-corrected, bins 5.0, states lab, Fig5 rule (n = 939; median pre 1.081, cooling 1.085, post 1.073): Pre-Cooling: median change -0.007 bits/spike, P = 0.695; Cooling-Post: median change -0.020 bits/spike, P = 0.122; Pre-Post: median change -0.022 bits/spike, P = 0.0742

Result: not reproduced. Spatial information does not change from pre to cooling (median change -0.015 bits per spike, signed-rank P = 0.35 over 908 maps) or from cooling to post (P = 0.078), but it falls from pre to post (median change -0.038, P = 0.0054), so one of the three comparisons is significant. Every field set and bin size finds the pre to post decrease (P = 4e-6 to 0.0054). With the trials of each state subsampled to the same number (median 17 per state and arm, 20 draws), which removes the bias of unequal state sizes, pre to post still falls (median change -0.030 bits per spike, P = 0.016 over 902 maps; P = 0.0047 with the Figure 5 rule fields), while pre to cooling (P = 0.22) and cooling to post (P = 0.22) do not differ. Equal trials do not mean equal time or spikes, as speed falls within sessions (median occupancy per arm 58 s pre against 72 s cooling and post). With the spikes of each state subsampled to the same number (median 171; 848 maps with fields above 10 Hz and at least 20 spikes in every state, 939 with the Figure 5 rule fields), pre to post still falls (median change -0.025 bits per spike, P = 0.032 with fields above 10 Hz; P = 0.024 with the Figure 5 rule fields). With the information corrected by subtracting that of a uniform-rate map with the same spikes and occupancy (estimated bias, median 0.056 bits per spike pre against 0.040 post), no comparison is significant (pre to post median change -0.022, P = 0.085 and 0.074; pre to cooling P = 0.75 and 0.70). The outcome follows the criterion's measure, Skaggs information without correction; part of the pre to post decrease is the difference in estimated bias (medians 0.056 against 0.040), and what remains is not significant.

fig4d-precession-slope-decrease¶

The phase precession slope decreased slightly but significantly during MS cooling (P < 0.007 and P < 0.0003).

Circular-linear regression (Kempter et al. 2012) of theta phase on position within the field, position scaled to the field (0 to 1), so the slope is in radians per field; fields with at least 10 spikes in a state (standard choice). The slope is searched over plus and minus 2 cycles per field (4 pi rad; an assumption, as the paper gives no range); 1 cycle, which pins many fields at its bound, and 3 cycles are variants. The fraction of slopes at the bound is printed.

In [35]:
BOUND = {"prec_slope": 4 * np.pi, "prec_slope_1c": 2 * np.pi, "prec_slope_3c": 6 * np.pi}
for col, rng_name in [("prec_slope", "2 cycles (main)"), ("prec_slope_1c", "1 cycle"), ("prec_slope_3c", "3 cycles")]:
    for key in MEASURES:
        W = wide(key, True, [col])
        W = W.dropna()
        s = {k: W[(col, k)] for k in mc.STATES}
        at_b = {k: float((np.abs(np.abs(v) - BOUND[col]) < 1e-3).mean()) for k, v in s.items()}
        out = [f"n = {len(W)}; median slope pre {s['Pre'].median():.3f}, cooling {s['Cooling'].median():.3f}, post {s['Post'].median():.3f} rad/field; "
               f"fraction at the search bound pre {at_b['Pre']:.3f}, cooling {at_b['Cooling']:.3f}, post {at_b['Post']:.3f}"]
        for a_ in ["Pre", "Post"]:
            p_mag, _ = mc.signrank(s["Cooling"].abs(), s[a_].abs())
            p_sig, _ = mc.signrank(s["Cooling"], s[a_])
            out.append(f"cooling vs {a_}: |slope| median change {np.median(s['Cooling'].abs() - s[a_].abs()):.4f} (P = {p_mag:.3g}); "
                       f"signed slope median change {np.median(s['Cooling'] - s[a_]):.4f} (P = {p_sig:.3g})")
        print(f"range {rng_name}, bins {key[0]}, states {key[1]}: " + "; ".join(out))
    if col == "prec_slope":
        Wb = wide((5.0, "lab"), True, [col]).dropna()
        off = (np.abs(np.abs(Wb) - BOUND[col]) >= 1e-3).all(1)
        Wb = Wb[off]
        print(f"   main reading without fields at the bound in any state (n = {len(Wb)}): cooling vs pre |slope| P = "
              f"{mc.signrank(Wb[(col, 'Cooling')].abs(), Wb[(col, 'Pre')].abs())[0]:.3g}, signed P = {mc.signrank(Wb[(col, 'Cooling')], Wb[(col, 'Pre')])[0]:.3g}; "
              f"cooling vs post |slope| P = {mc.signrank(Wb[(col, 'Cooling')].abs(), Wb[(col, 'Post')].abs())[0]:.3g}, signed P = {mc.signrank(Wb[(col, 'Cooling')], Wb[(col, 'Post')])[0]:.3g}")
W = wide((5.0, "lab"), True, ["prec_slope"]).dropna()
print(f"fraction of negative slopes (pre, main reading): {(W[('prec_slope', 'Pre')] < 0).mean():.3f}")
range 2 cycles (main), bins 5.0, states lab: n = 1044; median slope pre -5.598, cooling -5.297, post -5.499 rad/field; fraction at the search bound pre 0.098, cooling 0.079, post 0.091; cooling vs Pre: |slope| median change -0.1263 (P = 0.0161); signed slope median change 0.1263 (P = 0.0653); cooling vs Post: |slope| median change -0.0270 (P = 0.0734); signed slope median change 0.0682 (P = 0.0686)
range 2 cycles (main), bins 5.0, states m12: n = 1039; median slope pre -5.566, cooling -5.442, post -5.589 rad/field; fraction at the search bound pre 0.099, cooling 0.077, post 0.086; cooling vs Pre: |slope| median change -0.0798 (P = 0.0609); signed slope median change 0.0327 (P = 0.572); cooling vs Post: |slope| median change -0.0377 (P = 0.258); signed slope median change 0.0452 (P = 0.113)
range 2 cycles (main), bins 3.0, states lab: n = 1152; median slope pre -5.005, cooling -4.747, post -4.979 rad/field; fraction at the search bound pre 0.072, cooling 0.067, post 0.078; cooling vs Pre: |slope| median change -0.1354 (P = 0.00408); signed slope median change 0.1096 (P = 0.0563); cooling vs Post: |slope| median change -0.0195 (P = 0.0833); signed slope median change 0.0701 (P = 0.00616)
   main reading without fields at the bound in any state (n = 840): cooling vs pre |slope| P = 0.0898, signed P = 0.0772; cooling vs post |slope| P = 0.201, signed P = 0.0804
range 1 cycle, bins 5.0, states lab: n = 1044; median slope pre -4.595, cooling -4.630, post -4.654 rad/field; fraction at the search bound pre 0.318, cooling 0.281, post 0.304; cooling vs Pre: |slope| median change 0.0000 (P = 0.226); signed slope median change 0.0000 (P = 0.818); cooling vs Post: |slope| median change 0.0000 (P = 0.707); signed slope median change 0.0000 (P = 0.394)
range 1 cycle, bins 5.0, states m12: n = 1039; median slope pre -4.563, cooling -4.771, post -4.787 rad/field; fraction at the search bound pre 0.313, cooling 0.290, post 0.311; cooling vs Pre: |slope| median change 0.0000 (P = 0.596); signed slope median change 0.0000 (P = 0.202); cooling vs Post: |slope| median change 0.0000 (P = 0.769); signed slope median change 0.0000 (P = 0.61)
range 1 cycle, bins 3.0, states lab: n = 1152; median slope pre -4.394, cooling -4.312, post -4.328 rad/field; fraction at the search bound pre 0.263, cooling 0.232, post 0.239; cooling vs Pre: |slope| median change 0.0000 (P = 0.0543); signed slope median change 0.0000 (P = 0.328); cooling vs Post: |slope| median change 0.0000 (P = 0.939); signed slope median change 0.0000 (P = 0.372)
range 3 cycles, bins 5.0, states lab: n = 1044; median slope pre -5.755, cooling -5.495, post -5.775 rad/field; fraction at the search bound pre 0.034, cooling 0.042, post 0.038; cooling vs Pre: |slope| median change -0.1253 (P = 0.149); signed slope median change 0.1473 (P = 0.0547); cooling vs Post: |slope| median change -0.0562 (P = 0.176); signed slope median change 0.1213 (P = 0.0371)
range 3 cycles, bins 5.0, states m12: n = 1039; median slope pre -5.747, cooling -5.605, post -5.852 rad/field; fraction at the search bound pre 0.034, cooling 0.043, post 0.039; cooling vs Pre: |slope| median change -0.0660 (P = 0.329); signed slope median change 0.0591 (P = 0.638); cooling vs Post: |slope| median change -0.0704 (P = 0.157); signed slope median change 0.1225 (P = 0.0473)
range 3 cycles, bins 3.0, states lab: n = 1152; median slope pre -5.131, cooling -4.890, post -5.104 rad/field; fraction at the search bound pre 0.036, cooling 0.043, post 0.033; cooling vs Pre: |slope| median change -0.1630 (P = 0.0144); signed slope median change 0.1313 (P = 0.161); cooling vs Post: |slope| median change -0.0666 (P = 0.119); signed slope median change 0.1260 (P = 0.00246)
fraction of negative slopes (pre, main reading): 0.865
/tmp/ipykernel_2386/1544035160.py:18: Pandas4Warning: Starting with pandas version 4.0 all arguments of all will be keyword-only.
  off = (np.abs(np.abs(Wb) - BOUND[col]) >= 1e-3).all(1)

Result: partially reproduced (assumed). With the slope searched over plus and minus 2 cycles per field (main reading; 8 to 10% of the slopes at the bound), precession is flatter during cooling than before (median change of |slope| -0.13 rad per field, signed-rank P = 0.016 over 1044 fields) but not significantly flatter than after (P = 0.073); the signed slope gives P = 0.065 and 0.069. With 3 cm bins the magnitude reading gives P = 0.0041 against pre and 0.083 against post, and the signed reading 0.056 and 0.0062. No reading gives P < 0.05 for both comparisons. With a range of 1 cycle, 23 to 32% of the slopes sit at the bound and no comparison is significant (P 0.054 to 0.94); with 3 cycles at most one comparison per reading is significant. The outcome rests on the slope range, which the paper does not give, and on the fields whose slope sits at the bound: without the 2-cycle bound fields in any state (840 fields), no comparison is significant (cooling against pre P = 0.090 for |slope| and 0.077 signed, against post 0.20 and 0.080). With 3 cycles the significant comparison is the signed slope against post (P = 0.037), while against pre |slope| gives P = 0.149 and the signed slope 0.055. The flattening against pre is therefore weak evidence.

suppl3e-precession-temperature, fig4a-frequency-temperature-slopes¶

Per field and trial (reading a): slope and fp from that trial's in-field spikes, with the mean MS temperature at those spikes. Per field and state (reading b): the state's values with the state's mean temperature at the field's spikes. Measured-temperature sessions only. For a per-trial slope at least 5 spikes are needed (standard choice).

In [36]:
T0 = time.time()
MEAS_NAMES = {S["session"] for S in MEAS}
F5 = FIELDS[(5.0, "lab")]
F5 = F5[F5.peak_rate > 10]
rows = []
for S in USESS:
    if S["session"] not in MEAS_NAMES:
        continue
    sp = S["sp"]
    tt, T = S["temp"]
    ok = np.isfinite(T)
    sp_temp = np.interp(sp.t, tt[ok], T[ok])
    for _, f in F5[F5.session == S["session"]].iterrows():
        m = (sp.u.values == f.u) & (sp.arm.values == f.arm) & (sp.lin.values >= f.lo) & (sp.lin.values < f.hi)
        su = sp[m].assign(temp=sp_temp[m])
        for ti, g in su.groupby("trial"):
            r = dict(session=S["session"], rat=S["rat"], u=f.u, arm=f.arm, lo=f.lo, trial=ti, n=len(g),
                     state=S["trials"].st_lab.values[ti], temp=g.temp.mean(), flfp=g.theta_f.mean())
            if len(g) >= 5:
                x = (g.lin.values - f.lo) / (f.hi - f.lo)
                ph = np.mod(g.phase_u.values, 2 * np.pi)
                r["slope"] = mc.circ_lin_slope(x, ph)[0]
                r["slope_1c"] = mc.circ_lin_slope(x, ph, 1.0)[0]
            r["fp"] = mc.acg_frequency([g.t.values * 1000])[0] if len(g) >= 2 else np.nan
            rows.append(r)
FT = pd.DataFrame(rows)
print(f"field-trial values: {len(FT)} passes of {FT.groupby(['session', 'u', 'arm', 'lo']).ngroups} fields in {FT.session.nunique()} sessions; "
      f"with a slope {FT.slope.notna().sum()}, with an fp {FT.fp.notna().sum()} ({time.time() - T0:.0f} s)")
# per field and state: the state's mean temperature at the field's spikes
FS = FT.groupby(["session", "rat", "u", "arm", "lo", "state"]).apply(
    lambda g: pd.Series(dict(temp=np.average(g.temp, weights=g.n), n=g.n.sum()))).reset_index()
MW = MEASURES[(5.0, "lab")]
MW = MW[MW.peak_all > 10]
FS = FS.merge(MW[["session", "u", "arm", "lo", "state", "prec_slope", "prec_slope_1c", "fp", "flfp_spk", "flfp_time"]],
              on=["session", "u", "arm", "lo", "state"])
print(f"field-state values: {len(FS)}")
field-trial values: 41304 passes of 701 fields in 12 sessions; with a slope 31617, with an fp 31216 (25 s)
field-state values: 2070
In [37]:
for sc, fc, bnd, lab_ in [("slope", "prec_slope", 4 * np.pi, "2 cycles (main)"), ("slope_1c", "prec_slope_1c", 2 * np.pi, "1 cycle")]:
    d = FT.dropna(subset=[sc, "temp"])
    r, p, n = mc.corr(d.temp, d[sc])
    print(f"range {lab_}: (a) field and trial: R = {r:.4f}, P = {p:.3g}, n = {n}; fraction at the bound {(np.abs(np.abs(d[sc]) - bnd) < 1e-3).mean():.3f}")
    d = FS.dropna(subset=[fc, "temp"])
    r2, p2, n2 = mc.corr(d.temp, d[fc])
    print(f"range {lab_}: (b) field and state: R = {r2:.4f}, P = {p2:.3g}, n = {n2}")
    print(f"   within tolerance (-0.0297 to -0.0243) with P < 1e-10: (a) {abs(r + 0.027) <= 0.0027 and p < 1e-10}, (b) {abs(r2 + 0.027) <= 0.0027 and p2 < 1e-10}")
range 2 cycles (main): (a) field and trial: R = -0.0262, P = 3.15e-06, n = 31617; fraction at the bound 0.178
range 2 cycles (main): (b) field and state: R = -0.0274, P = 0.222, n = 1993
   within tolerance (-0.0297 to -0.0243) with P < 1e-10: (a) False, (b) False
range 1 cycle: (a) field and trial: R = -0.0273, P = 1.23e-06, n = 31617; fraction at the bound 0.377
range 1 cycle: (b) field and state: R = -0.0243, P = 0.279, n = 1993
   within tolerance (-0.0297 to -0.0243) with P < 1e-10: (a) False, (b) False

Result: partially reproduced. Per field and trial (31617 values; range of 2 cycles per field, 18% of the per-trial slopes at the bound), the precession slope correlates with MS temperature with R = -0.0262, within -0.0297 to -0.0243, but P = 3.2e-6, not below 1e-10. Per field and state, R = -0.0274 with P = 0.22. With a range of 1 cycle the values are R = -0.0273 (P = 1.2e-6) and -0.0243 (P = 0.28).

In [38]:
rows = []
for reading, D, fpc, flc in [("a field-trial", FT, "fp", "flfp"), ("b field-state", FS, "fp", "flfp_spk"), ("b field-state, fLFP over time", FS, "fp", "flfp_time")]:
    for meas, col in [("fLFP", flc), ("fp", fpc)]:
        dd = D.dropna(subset=["temp", col])
        lr = stats.linregress(dd.temp, dd[col])
        rows.append(dict(reading=reading, measure=meas, R=lr.rvalue, slope_Hz_per_C=lr.slope, P=lr.pvalue, n=len(dd)))
A4 = pd.DataFrame(rows)
print(A4.to_string(index=False))
print("expected: fLFP R 0.66 (0.594 to 0.726), slope 0.071 (0.0639 to 0.0781); fp R 0.38 (0.342 to 0.418), slope 0.09 (0.081 to 0.099)")
print(f"field-trial fp: passes with fewer than 2 spikes or no autocorrelogram peak are dropped ({FT.fp.isna().sum()} of {len(FT)})")
                      reading measure      R  slope_Hz_per_C          P     n
                a field-trial    fLFP  0.184          0.0583          0 41304
                a field-trial      fp 0.1553         0.05423 8.596e-168 31216
                b field-state    fLFP 0.4025         0.05862  1.834e-81  2070
                b field-state      fp 0.3005         0.06743  3.579e-40  1862
b field-state, fLFP over time    fLFP 0.6852         0.06778  2.87e-286  2065
b field-state, fLFP over time      fp 0.3005         0.06743  3.579e-40  1862
expected: fLFP R 0.66 (0.594 to 0.726), slope 0.071 (0.0639 to 0.0781); fp R 0.38 (0.342 to 0.418), slope 0.09 (0.081 to 0.099)
field-trial fp: passes with fewer than 2 spikes or no autocorrelogram peak are dropped (10088 of 41304)

Result: partially reproduced. Both rise with MS temperature at P below 1e-30. Per field and state with fLFP over the time in the field, fLFP gives R = 0.685 and a slope of 0.068 Hz per C, both within tolerance, but fp gives R = 0.301 and 0.067 Hz per C, both below. Per field and trial the R values are lower (0.18 and 0.16).

fig4f-speed-theta-power¶

Running speed correlated with theta power.

In [39]:
d = pd.concat([S["trials"][["speed_all", "p_hil", "p_hil_norm", "p_spec_norm"]].assign(rat=S["rat"]) for S in LFPS]).dropna()
for c in ["p_hil", "p_hil_norm", "p_spec_norm"]:
    r, p, n = mc.corr(d.speed_all, d[c])
    per = {rat: mc.corr(g.speed_all, g[c])[:2] for rat, g in d.groupby("rat")}
    print(f"{c}: (a) all trials R = {r:.3f}, P = {p:.3g}, n = {n}; (b) per rat " +
          ", ".join(f"{k} R {v[0]:.3f} P {v[1]:.2g}" for k, v in per.items()) +
          f"; rats with P < 0.05: {sum(v[1] < 0.05 for v in per.values())} of {len(per)}")
p_hil: (a) all trials R = 0.071, P = 2.65e-09, n = 7087; (b) per rat MS10 R -0.007 P 0.81, MS12 R 0.061 P 0.04, MS13 R 0.053 P 0.15, MS21 R 0.156 P 1.6e-13, MS22 R 0.125 P 2.3e-07; rats with P < 0.05: 3 of 5
p_hil_norm: (a) all trials R = 0.023, P = 0.0492, n = 7087; (b) per rat MS10 R -0.020 P 0.46, MS12 R 0.068 P 0.024, MS13 R 0.118 P 0.0013, MS21 R 0.168 P 2.6e-15, MS22 R 0.330 P 1.1e-44; rats with P < 0.05: 4 of 5
p_spec_norm: (a) all trials R = 0.004, P = 0.729, n = 7087; (b) per rat MS10 R -0.123 P 7.2e-06, MS12 R 0.071 P 0.018, MS13 R 0.173 P 1.9e-06, MS21 R 0.029 P 0.18, MS22 R 0.144 P 2.2e-09; rats with P < 0.05: 4 of 5

Result: reproduced. Over all 7087 trials, mean speed correlates positively with theta power (R = 0.071, P = 2.7e-9, raw Hilbert power). Per rat 3 to 4 of 5 rats reach P < 0.05 depending on the power measure. MS10 reaches it only with the normalised spectral power, where its R is negative (R = -0.123, P = 7.2e-6), so with that measure 3 of the 4 significant rats have a positive R.

fig4gh-fp-speed¶

fp depended on running speed more strongly than fLFP, so fp - fLFP increased with speed, and fp during cooling was lower at all velocities.

In [40]:
T0 = time.time()
rng = np.random.default_rng(4)


def speed_bins(binv):
    rows = []
    for S in USESS:
        if not S["has_lfp"]:
            continue
        sp = S["sp"]
        st = S["trials"].st_lab.values
        for _, f in F5[F5.session == S["session"]].iterrows():
            m = (sp.u.values == f.u) & (sp.arm.values == f.arm) & (sp.lin.values >= f.lo) & (sp.lin.values < f.hi)
            su = sp[m].assign(vb=np.floor(sp.speed.values[m] / binv) * binv, state=st[sp.trial.values[m]])
            for (vb, s), g in list(su.groupby(["vb", "state"])) + [((vb, "all"), g) for vb, g in su.groupby("vb")]:
                if s not in ("Pre", "Cooling", "all") or len(g) < 2:
                    continue
                fpv = mc.acg_frequency([gg.t.values * 1000 for _, gg in g.groupby("trial")])[0]
                rows.append(dict(session=S["session"], u=f.u, arm=f.arm, lo=f.lo, vb=vb, state=s,
                                 fp=fpv, flfp=g.theta_f.mean(), n=len(g)))
    return pd.DataFrame(rows)


for binv in (10.0, 20.0):
    SB = speed_bins(binv)
    A = SB[(SB.state == "all")].dropna(subset=["fp"])
    A = A[A.vb >= 10]
    l1 = stats.linregress(A.vb + binv / 2, A.fp)
    l2 = stats.linregress(A.vb + binv / 2, A.flfp)
    keys = A.groupby(["session", "u", "arm", "lo"]).ngroup().values
    boots = []
    for _ in range(500):
        pick = rng.integers(0, keys.max() + 1, keys.max() + 1)
        idx = np.concatenate([np.where(keys == k)[0] for k in pick])
        x = A.vb.values[idx]
        boots.append(np.polyfit(x, A.fp.values[idx], 1)[0] - np.polyfit(x, A.flfp.values[idx], 1)[0])
    lo_, hi_ = np.percentile(boots, [2.5, 97.5])
    print(f"bins {binv:.0f} cm/s, states pooled, {len(A)} field-bins of {len(np.unique(keys))} fields: fp slope {l1.slope:.4f} Hz per cm/s "
          f"(P = {l1.pvalue:.3g}), fLFP slope {l2.slope:.4f} (P = {l2.pvalue:.3g}); difference 95% bootstrap interval [{lo_:.4f}, {hi_:.4f}]")
    P_ = SB[SB.state.isin(["Pre", "Cooling"])].dropna(subset=["fp"]).pivot_table(index=["session", "u", "arm", "lo", "vb"], columns="state", values="fp")
    P_ = P_.dropna()
    g = P_.groupby(level="vb").agg(n=("Pre", "size"), pre=("Pre", "median"), cool=("Cooling", "median"))
    g = g[g.n >= 10]
    g["cool_lower"] = g.cool < g.pre
    print(g.round(3).to_string())
    print(f"  speed bins with at least 10 fields in both states: {len(g)}, cooling lower in {int(g.cool_lower.sum())}")
print(f"({time.time() - T0:.0f} s)")
bins 10 cm/s, states pooled, 5435 field-bins of 1148 fields: fp slope 0.0106 Hz per cm/s (P = 2.66e-60), fLFP slope 0.0045 (P = 3.42e-55); difference 95% bootstrap interval [0.0044, 0.0076]
       n   pre  cool  cool_lower
vb                              
0     13 8.929 9.524       False
10    35 8.403 8.264        True
20    48 8.811 8.299        True
30    41 9.009 9.009       False
40    69 9.259 9.091        True
50    86 9.615 9.259        True
60   105 9.524 9.009        True
70   176 9.524 9.259        True
80   221 9.804 9.346        True
90   225    10 9.174        True
100  209 9.804 9.346        True
110  183 9.901 9.524        True
120   60 10.36 10.53       False
130   24 11.56 8.969        True
  speed bins with at least 10 fields in both states: 14, cooling lower in 11
bins 20 cm/s, states pooled, 3271 field-bins of 1121 fields: fp slope 0.0115 Hz per cm/s (P = 3.22e-46), fLFP slope 0.0040 (P = 7.47e-34); difference 95% bootstrap interval [0.0055, 0.0095]
       n   pre  cool  cool_lower
vb                              
0     57 8.475 8.065        True
20   106 8.772 8.696        True
40   161 9.804 9.091        True
60   265 9.804 9.174        True
80   390  10.1 9.615        True
100  323 10.31 9.615        True
120   81 10.75  10.2        True
140   11  11.9  10.1        True
  speed bins with at least 10 fields in both states: 8, cooling lower in 8
(61 s)

Result: partially reproduced. In 10 cm/s bins with states pooled, fp rises with speed (0.0106 Hz per cm/s, P = 2.7e-60) faster than fLFP (0.0045; bootstrap interval of the difference 0.0044 to 0.0076), but fp during cooling is below pre in 11 of 14 speed bins, not all (0, 30 and 120 cm/s are not). With 20 cm/s bins it is below in all 8.

suppl2e-trial-speed-theta-frequency¶

Over trials, mean theta frequency correlated positively with mean running speed before, during and after MS cooling, with the largest changes at 10 to 40 cm/s.

In [41]:
d = pd.concat([S["trials"][["speed_all", "f_hil", "f_spec", "st_lab"]] for S in LFPS])
for fc in ["f_hil", "f_spec"]:
    out = []
    nst = 0
    for s in mc.STATES:
        g = d[d.st_lab == s].dropna(subset=[fc, "speed_all"])
        r, p, n = mc.corr(g.speed_all, g[fc])
        lo_ = g[(g.speed_all >= 10) & (g.speed_all < 40)]
        hi_ = g[g.speed_all >= 40]
        s1 = stats.linregress(lo_.speed_all, lo_[fc]).slope if len(lo_) > 2 else np.nan
        s2 = stats.linregress(hi_.speed_all, hi_[fc]).slope
        nst += s1 > s2
        out.append(f"{s}: R {r:.3f} (P = {p:.3g}, n = {n}); slope 10-40 cm/s {s1:.4f} (n = {len(lo_)}), above 40 {s2:.4f} Hz per cm/s")
    print(f"{fc}: " + "; ".join(out) + f"; states with the low-speed slope larger: {nst}")
print(f"trials with mean speed below 40 cm/s: {(d.speed_all < 40).sum()} of {len(d)}")
f_hil: Pre: R 0.360 (P = 5.62e-62, n = 1988); slope 10-40 cm/s -0.0043 (n = 14), above 40 0.0166 Hz per cm/s; Cooling: R 0.259 (P = 3.21e-34, n = 2144); slope 10-40 cm/s 0.0685 (n = 12), above 40 0.0104 Hz per cm/s; Post: R 0.387 (P = 2.03e-84, n = 2337); slope 10-40 cm/s 0.0505 (n = 32), above 40 0.0164 Hz per cm/s; states with the low-speed slope larger: 2
f_spec: Pre: R 0.283 (P = 7.75e-38, n = 1988); slope 10-40 cm/s 0.1725 (n = 14), above 40 0.0186 Hz per cm/s; Cooling: R 0.214 (P = 1.4e-23, n = 2144); slope 10-40 cm/s 0.1262 (n = 12), above 40 0.0124 Hz per cm/s; Post: R 0.265 (P = 8.25e-39, n = 2337); slope 10-40 cm/s 0.0391 (n = 32), above 40 0.0151 Hz per cm/s; states with the low-speed slope larger: 3
trials with mean speed below 40 cm/s: 61 of 7087

Result: reproduced. Trial theta frequency correlates positively with trial speed in pre, cooling and post (Hilbert R = 0.360, 0.259 and 0.387; P below 1e-33), and the slope over trials of 10 to 40 cm/s exceeds that above 40 cm/s in cooling and post (2 of 3 states; 3 of 3 with the spectral reading). Only 61 of 7087 trials have a mean speed below 40 cm/s.

suppl3-theta-cycle-duration¶

Theta cycles were consistently longer during MS cooling at every position on the track and returned to control duration after cooling, and the duration profile did not correlate with the speed profile along the track.

In [42]:
rows = []
C = []
for S in LFPS:
    c = S["cycles"].copy()
    c["state"] = S["trials"].st_lab.values[c.trial.values]
    c["session"] = S["session"]
    C.append(c)
    g = c.groupby("state").dur.median()
    if {"Pre", "Cooling", "Post"} <= set(g.index):
        rows.append(dict(session=S["session"], pre=g["Pre"], cool=g["Cooling"], post=g["Post"]))
CD = pd.DataFrame(rows)
C = pd.concat(C)
print(f"sessions {len(CD)}; median cycle duration (ms) pre {1000 * CD.pre.median():.1f}, cooling {1000 * CD.cool.median():.1f}, post {1000 * CD.post.median():.1f}")
print(f"cooling vs pre P = {mc.signrank(CD.cool, CD.pre)[0]:.3g} (longer in {(CD.cool > CD.pre).sum()}); cooling vs post P = {mc.signrank(CD.cool, CD.post)[0]:.3g} "
      f"(longer in {(CD.cool > CD.post).sum()}); post vs pre P = {mc.signrank(CD.post, CD.pre)[0]:.3g}, median post - pre {1000 * np.median(CD.post - CD.pre):.2f} ms")
for arm in ["Left", "Right"]:
    cc = C[(C.arm == arm) & (C.lin >= 0)]
    cc = cc.assign(pb=np.floor(cc.lin / 5) * 5)
    g = cc.groupby(["pb", "state"]).agg(dur=("dur", "mean"), speed=("speed", "mean"), n=("dur", "size")).unstack("state")
    g = g[(g[("n", "Pre")] >= 50) & (g[("n", "Cooling")] >= 50)]
    longer = (g[("dur", "Cooling")] > g[("dur", "Pre")]).mean()
    r, p, n = mc.corr(g[("dur", "Pre")], g[("speed", "Pre")])
    print(f"{arm} runs: {len(g)} position bins (at least 50 cycles per state); cooling longer than pre in {100 * longer:.1f}% of bins; "
          f"pre duration against pre speed over bins R = {r:.3f}, P = {p:.3g}")
sessions 50; median cycle duration (ms) pre 117.6, cooling 130.4, post 117.6
cooling vs pre P = 1.22e-09 (longer in 48); cooling vs post P = 1.11e-09 (longer in 49); post vs pre P = 0.956, median post - pre 0.00 ms
Left runs: 42 position bins (at least 50 cycles per state); cooling longer than pre in 100.0% of bins; pre duration against pre speed over bins R = -0.428, P = 0.00465
Right runs: 65 position bins (at least 50 cycles per state); cooling longer than pre in 100.0% of bins; pre duration against pre speed over bins R = -0.322, P = 0.00889

Result: partially reproduced. Theta cycles are longer during cooling (median 130.4 against 117.6 ms pre and post; P = 1.2e-9 and 1.1e-9 over 50 sessions), post does not differ from pre (P = 0.96), and cooling is longer in every position bin of both arms. The pre duration profile, however, correlates with the speed profile along the track (R = -0.43 and -0.32; P = 0.0047 and 0.0089).

disc-interneuron-rates-decrease¶

Firing rates of interneurons decreased during MS cooling by about 14%, about the same degree as place cells.

Rate of a unit in a state: its spikes in the state's trials over the summed duration of those trials (running reading a), or its spikes above 10 cm/s over the time above 10 cm/s in those trials (reading b).

In [43]:
def unit_state_rates(S, state_col="st_lab"):
    tr = S["trials"]
    b = S["beh"]
    bti = mc._beh_trial_index(S)
    dt = np.gradient(b["t"])
    st_tr = tr[state_col].values
    sp = S["sp"]
    st_sp = st_tr[sp.trial.values]
    run_sp = sp.speed.values > mc.RUN_SPEED
    rows = []
    dur = {s: (tr.stop - tr.start)[st_tr == s].sum() for s in mc.STATES}
    run_t = {}
    for s in mc.STATES:
        m = bti >= 0
        m[m] = st_tr[bti[m]] == s
        run_t[s] = dt[m & (np.nan_to_num(b["speed"]) > mc.RUN_SPEED)].sum()
    for k, U in enumerate(S["units"]):
        r = dict(session=S["session"], rat=S["rat"], u=k, cell_type=U["cell_type"])
        mu = sp.u.values == k
        for s in mc.STATES:
            r[f"all_{s}"] = (mu & (st_sp == s)).sum() / dur[s] if dur[s] > 0 else np.nan
            r[f"run_{s}"] = (mu & (st_sp == s) & run_sp).sum() / run_t[s] if run_t[s] > 0 else np.nan
        rows.append(r)
    return pd.DataFrame(rows)


UR = pd.concat([unit_state_rates(S) for S in SESS if S["has_units"] and len(S["units"])], ignore_index=True)
print("curated units by type:", UR.cell_type.replace("", "(none)").value_counts().to_dict())
curated units by type: {'Pyramidal Cell': 1295, 'Narrow Interneuron': 214, 'Wide Interneuron': 93, '(none)': 55, 'Unknown': 4}
In [44]:
rows = []
for lab_, types in [("a narrow", ["Narrow Interneuron"]), ("b narrow and wide", ["Narrow Interneuron", "Wide Interneuron"]),
                    ("pyramidal (reference)", ["Pyramidal Cell"])]:
    g = UR[UR.cell_type.isin(types)]
    for run in ["all", "run"]:
        pre, cool = g[f"{run}_Pre"], g[f"{run}_Cooling"]
        ok = (pre > 0) & np.isfinite(cool)
        dec = 100 * (1 - cool[ok] / pre[ok])
        rows.append(dict(units=lab_, running=run, n=int(ok.sum()), a_median_dec=np.median(dec),
                         b_dec_of_mean=100 * (1 - cool[ok].mean() / pre[ok].mean()), c_mean_dec=dec.mean(),
                         P=mc.signrank(cool[ok], pre[ok])[0]))
IR = pd.DataFrame(rows)
IR["in_12.6_15.4"] = IR[["a_median_dec", "b_dec_of_mean", "c_mean_dec"]].apply(lambda r: bool(((r - 14).abs() <= 1.4).any()), axis=1)
print(IR.to_string(index=False))
g = UR[UR.cell_type.isin(["Narrow Interneuron", "Wide Interneuron"])]
print("interneurons by rat (n, decrease of the mean, all frames):")
print(g.groupby("rat").apply(lambda x: pd.Series(dict(n=len(x), dec=100 * (1 - x.all_Cooling.mean() / x.all_Pre.mean())))).round(2))
                units running    n  a_median_dec  b_dec_of_mean  c_mean_dec         P  in_12.6_15.4
             a narrow     all  194           4.2          8.713      -125.1   0.02252         False
             a narrow     run  194         4.234          7.847      -130.6   0.06452         False
    b narrow and wide     all  276         3.066          7.975      -109.3    0.1094         False
    b narrow and wide     run  276        0.2842          7.103      -112.9    0.2531         False
pyramidal (reference)     all 1128         7.138           6.15      -62.35 0.0005338         False
pyramidal (reference)     run 1128         6.301          5.465      -64.75  0.002711         False
interneurons by rat (n, decrease of the mean, all frames):
       n   dec
rat           
MS10   7   7.5
MS12  28  -6.2
MS13  50  8.65
MS21 114 12.29
MS22 108  3.75

Result: partially reproduced. Narrow waveform interneurons fire less during cooling (194 units, signed-rank P = 0.023), but by 4.2% (median of per-unit decreases) or 8.7% (decrease of the mean), not 14%; the mean of per-unit decreases is negative, pulled by units with near-zero pre rates; narrow and wide together fall by 3.1 to 8.0% (P = 0.11). Pyramidal cells fall by 6.1 to 7.1% (P = 5e-4).

suppl5gh-rates-follow-temperature¶

Firing rates of pyramidal cells and putative interneurons decreased immediately after MS cooling onset and their changes correlated with MS temperature, not with the delayed hippocampal temperature.

In [45]:
def trial_rates(S, types):
    tr = S["trials"]
    sp = S["sp"]
    dur = (tr.stop - tr.start).values
    out = []
    for k, U in enumerate(S["units"]):
        if U["cell_type"] not in types:
            continue
        cnt = np.bincount(sp.trial.values[sp.u.values == k], minlength=len(tr))
        rate = cnt / dur
        pre = rate[tr.st_lab.values == "Pre"].mean()
        keep = np.ones(len(tr), bool)
        if len(S["onsets"]) > 1:
            keep &= tr.start.values < S["onsets"][1]
        out.append(pd.DataFrame(dict(session=S["session"], u=k, aligned=tr.aligned.values, rate=rate,
                                     norm=rate / pre if pre > 0 else np.nan, temp=tr.temp.values))[keep])
    return pd.concat(out) if out else pd.DataFrame()


for cls, types in [("interneurons", ["Narrow Interneuron", "Wide Interneuron"]), ("pyramidal cells", ["Pyramidal Cell"])]:
    TRt = pd.concat([trial_rates(S, types) for S in SESS if S["has_units"]])
    TRt = TRt[(TRt.aligned >= -40) & (TRt.aligned <= 80)]
    n_units = TRt.groupby(["session", "u"]).ngroups
    n_sess = TRt.session.nunique()
    for col in ["norm", "rate"]:
        per = TRt.groupby(["session", "u"]).apply(lambda g: pd.Series(dict(
            early=g[(g.aligned >= 1) & (g.aligned <= 5)][col].mean(), pre=g[g.aligned < 0][col].mean())))
        p_early, n_ = mc.signrank(per.early, per.pre)
        dd = (per.early - per.pre).dropna()
        p_less = stats.wilcoxon(dd, alternative="less").pvalue
        ser = TRt.groupby("aligned")[col].mean()
        TRm = TRt[TRt.session.isin(MEAS_NAMES)]
        ser_m = TRm.groupby("aligned")[col].mean()
        temp_m = mc.aligned_series([S for S in MEAS if S["session"] in set(TRm.session)], "temp")[0]["mean"]
        j = ser_m.index.intersection(temp_m.index)
        r, p, n = mc.corr(ser_m.loc[j], temp_m.loc[j])
        print(f"{cls}, {col}: {n_units} units in {n_sess} sessions; mean of trials 1 to 5 {per.early.mean():.3f} against pre {per.pre.mean():.3f} "
              f"(medians {per.early.median():.3f} and {per.pre.median():.3f}; signed-rank P = {p_early:.3g}, one-sided P (early below pre) = {p_less:.3g}, n = {n_}, below in {int((per.early < per.pre).sum())}); "
              f"aligned series against MS temperature (measured sessions, {TRm.groupby(['session', 'u']).ngroups} units): R = {r:.3f}, P = {p:.3g}, n = {n}")
print("expected units: 319 interneurons and 1104 pyramidal cells across 19 sessions (tolerance 32 and 110)")
print("hippocampal temperature: not in the dandiset; the comparison with it is not made")
interneurons, norm: 307 units in 23 sessions; mean of trials 1 to 5 1.082 against pre 0.996 (medians 0.887 and 1.000; signed-rank P = 0.000288, one-sided P (early below pre) = 0.000144, n = 273, below in 171); aligned series against MS temperature (measured sessions, 201 units): R = 0.113, P = 0.217, n = 120
interneurons, rate: 307 units in 23 sessions; mean of trials 1 to 5 10.131 against pre 11.652 (medians 2.136 and 2.606; signed-rank P = 1.92e-06, one-sided P (early below pre) = 9.61e-07, n = 304, below in 171); aligned series against MS temperature (measured sessions, 201 units): R = 0.806, P = 1.1e-28, n = 120
pyramidal cells, norm: 1295 units in 23 sessions; mean of trials 1 to 5 1.283 against pre 0.986 (medians 0.785 and 1.000; signed-rank P = 4.79e-18, one-sided P (early below pre) = 2.39e-18, n = 1117, below in 719); aligned series against MS temperature (measured sessions, 776 units): R = 0.147, P = 0.11, n = 120
pyramidal cells, rate: 1295 units in 23 sessions; mean of trials 1 to 5 1.796 against pre 2.026 (medians 0.650 and 0.776; signed-rank P = 6.27e-16, one-sided P (early below pre) = 3.14e-16, n = 1284, below in 719); aligned series against MS temperature (measured sessions, 776 units): R = 0.532, P = 4.03e-10, n = 120
expected units: 319 interneurons and 1104 pyramidal cells across 19 sessions (tolerance 32 and 110)
hippocampal temperature: not in the dandiset; the comparison with it is not made

Result: reproduced. Under the raw-rate reading, interneurons (307 units, 23 sessions) and pyramidal cells (1295 units) fire less on aligned trials 1 to 5 than before onset (signed-rank P = 1.9e-6 and 6.3e-16), and the aligned rate series correlate positively with MS temperature (R = 0.806, P = 1.1e-28; R = 0.532, P = 4.0e-10). Normalised rates do not give both parts: their medians on trials 1 to 5 are below pre (0.887 and 0.785 against 1.000; one-sided signed-rank P = 1.4e-4 and 2.4e-18), but the means are above (1.08 and 1.28, pulled up by units with low pre rates), and the normalised series do not correlate with temperature (R = 0.113, P = 0.22; R = 0.147, P = 0.11). The interneuron count is within 287 to 351; the pyramidal count, 1295 over 23 sessions, is above 994 to 1214.

suppl2d-interneuron-oscillation-slows¶

The theta oscillation frequency of putative fast spiking interneurons decreased with MS cooling, as did that of pyramidal cells, by about 14% on average, and pyramidal cells oscillated faster than interneurons.

Spikes during running (above 10 cm/s, Figure S2D "during running"): within place fields for pyramidal cells (fields of the Figure 3 and 4 set), across the whole maze (all trial spikes) for interneurons.

In [46]:
rows = []
for S in SESS:
    if not S["has_units"]:
        continue
    sp = S["sp"]
    st = S["trials"].st_lab.values[sp.trial.values]
    run = sp.speed.values > mc.RUN_SPEED
    for k, U in enumerate(S["units"]):
        if U["cell_type"] in ("Narrow Interneuron", "Wide Interneuron"):
            r = dict(session=S["session"], rat=S["rat"], cls=U["cell_type"], u=k)
            for s in ("Pre", "Cooling"):
                m = (sp.u.values == k) & (st == s) & run
                g = sp[m]
                r[s] = mc.acg_frequency([gg.t.values * 1000 for _, gg in g.groupby("trial")])[0] if len(g) > 10 else np.nan
            rows.append(r)
IF = pd.DataFrame(rows)
# pyramidal: fp of the place fields from running in-field spikes
rows = []
for S in USESS:
    sp = S["sp"]
    st = S["trials"].st_lab.values[sp.trial.values]
    for _, f in F5[F5.session == S["session"]].iterrows():
        r = dict(session=S["session"], rat=S["rat"], cls="Pyramidal Cell", u=f.u)
        for s in ("Pre", "Cooling"):
            m = (sp.u.values == f.u) & (sp.arm.values == f.arm) & (sp.lin.values >= f.lo) & (sp.lin.values < f.hi) & (st == s) & (sp.speed.values > mc.RUN_SPEED)
            g = sp[m]
            r[s] = mc.acg_frequency([gg.t.values * 1000 for _, gg in g.groupby("trial")])[0] if len(g) > 1 else np.nan
        rows.append(r)
PF = pd.DataFrame(rows)
ALLF = pd.concat([IF, PF], ignore_index=True)
rows = []
for lab_, sel in [("a narrow interneurons", ALLF.cls == "Narrow Interneuron"),
                  ("b narrow and wide interneurons", ALLF.cls.isin(["Narrow Interneuron", "Wide Interneuron"])),
                  ("pyramidal (fields)", ALLF.cls == "Pyramidal Cell"),
                  ("pooled: narrow and wide interneurons and pyramidal fields", ALLF.cls.notna())]:
    g = ALLF[sel].dropna(subset=["Pre", "Cooling"])
    dec = 100 * (1 - g.Cooling / g.Pre)
    rows.append(dict(units=lab_, n=len(g), pre_median=g.Pre.median(), cool_median=g.Cooling.median(),
                     a_median_dec=dec.median(), b_dec_of_mean=100 * (1 - g.Cooling.mean() / g.Pre.mean()), c_mean_dec=dec.mean(),
                     P=mc.signrank(g.Cooling, g.Pre)[0]))
D2 = pd.DataFrame(rows)
print(D2.to_string(index=False))
print(f"interneurons dropped for no autocorrelogram peak in a state: {IF[['Pre', 'Cooling']].isna().any(axis=1).sum()} of {len(IF)}; "
      f"pyramidal fields dropped: {PF[['Pre', 'Cooling']].isna().any(axis=1).sum()} of {len(PF)}")
                                                    units    n  pre_median  cool_median  a_median_dec  b_dec_of_mean  c_mean_dec         P
                                    a narrow interneurons  145       8.929        8.403          8.73          6.871       6.356 6.361e-13
                           b narrow and wide interneurons  191       8.929        8.475          8.73          6.626       5.805  1.01e-14
                                       pyramidal (fields)  974       10.42        9.524         8.607          8.233       7.452 1.252e-80
pooled: narrow and wide interneurons and pyramidal fields 1165        10.2        9.346         8.621          7.998       7.182 1.332e-93
interneurons dropped for no autocorrelogram peak in a state: 116 of 307; pyramidal fields dropped: 249 of 1223

Result: partially reproduced. The oscillation frequency of narrow waveform interneurons falls during cooling (median 8.93 to 8.40 Hz, signed-rank P = 6.4e-13, 145 units), and pyramidal cells oscillate faster than interneurons before cooling (median 10.42 against 8.93 Hz), but the decrease is 6.4 to 8.7% for each class and 7.2 to 8.6% pooled, not 12.6 to 15.4%.

fig3hi-population-vector-unchanged¶

The spatial scale of the population vector correlation of pyramidal cells was not affected by MS cooling.

Per session, arm and state: population vectors of the pyramidal cells' smoothed rate maps (5 cm bins) along the linearized maze; the decorrelation curve is the mean Pearson correlation of vectors d bins apart; the scale is the distance (interpolated) where it first drops to 0.5. The session's scale is the mean of its two arms.

In [47]:
rows = []
for S in USESS:
    edges = np.arange(0, 355, 5.0)
    pyr = [k for k, U in enumerate(S["units"]) if U["cell_type"] == "Pyramidal Cell"]
    sp = S["sp"]
    st_tr = S["trials"].st_lab.values
    st = st_tr[sp.trial.values]
    r = dict(session=S["session"], rat=S["rat"], n_pyr=len(pyr))
    for s in mc.STATES:
        sc = []
        for arm in ("Left", "Right"):
            occ = mc.occupancy(S, arm, edges, st_tr == s)
            M = []
            for k in pyr:
                cnt, _ = np.histogram(sp.lin[(sp.u.values == k) & (sp.arm.values == arm) & (st == s)], bins=edges)
                raw = np.where(occ > 0, cnt / np.where(occ > 0, occ, 1), np.nan)
                M.append(mc.smooth_map(raw, occ))
            M = np.array(M)
            good = np.isfinite(M).all(0)
            M = M[:, good]
            nb = M.shape[1]
            curve = []
            for dd in range(0, min(nb, 40)):
                cs = [np.corrcoef(M[:, i], M[:, i + dd])[0, 1] for i in range(nb - dd)]
                curve.append(np.nanmean(cs))
            curve = np.array(curve)
            below = np.where(curve < 0.5)[0]
            if len(below) and below[0] > 0:
                j = below[0]
                x = (j - 1) + (curve[j - 1] - 0.5) / (curve[j - 1] - curve[j])
                sc.append(5.0 * x)
            else:
                sc.append(np.nan)
        r[s] = np.nanmean(sc)
    rows.append(r)
PV = pd.DataFrame(rows)
print(PV.round(2).to_string(index=False))
p, n = mc.signrank(PV.Cooling, PV.Pre)
print(f"scale (cm) median pre {PV.Pre.median():.2f}, cooling {PV.Cooling.median():.2f}, post {PV.Post.median():.2f}; "
      f"median change cooling - pre {np.median(PV.Cooling - PV.Pre):.2f} cm; signed-rank P = {p:.3g} (n = {n} sessions)")
           session  rat  n_pyr   Pre  Cooling  Post
MS10-170307-154746 MS10     11 46.96    103.7 24.96
MS10-170314-163038 MS10     13 20.01    18.66 20.73
MS10-170317-153237 MS10     11 48.11    29.47 26.32
MS12-170714-122034 MS12     30 20.75    21.56 20.79
MS12-170715-111545 MS12     36 26.51    33.85 24.08
MS12-170716-172307 MS12     32 23.11    23.56 22.19
MS12-170717-111614 MS12     30 22.93    24.11 20.81
MS12-170719-095305 MS12     31 22.72    26.01 23.51
MS13-171128-113924 MS13     53  21.4    19.08 20.44
MS13-171129-105507 MS13     89 23.01    29.91  21.7
MS13-171130-121758 MS13    108 19.22    20.42 19.88
MS13-171201-130527 MS13     43 21.15    18.77 21.53
MS21-180625-153927 MS21     50 22.81    22.77 23.53
MS21-180627-143449 MS21    121 23.79    22.61 23.58
MS21-180628-155921 MS21     76 24.03    23.83 25.85
MS21-180629-110332 MS21    121 26.07    24.86 24.78
MS21-180712-103200 MS21     47 31.81    30.57 29.49
MS21-180719-155941 MS21     92 26.06    25.91 25.26
MS22-180628-120341 MS22     38 34.66    113.6 43.53
MS22-180629-110319 MS22    129 43.79    46.24 42.37
MS22-180711-112912 MS22     45 30.91    27.29 30.73
MS22-180719-122813 MS22     43 36.97     26.7 24.86
MS22-180720-110055 MS22     46 24.95    28.47 27.44
scale (cm) median pre 24.03, cooling 25.91, post 24.08; median change cooling - pre -0.05 cm; signed-rank P = 0.731 (n = 23 sessions)

Result: reproduced. The distance at which the population vector correlation falls to 0.5 does not change with cooling (median 24.0 cm pre, 25.9 cm cooling, median change -0.05 cm, signed-rank P = 0.73 over 23 sessions).

Place cell pairs (Figure 5)¶

Fields by the Figure 5 rule (5 cm bins, lab states). Pairs are overlapping fields of different cells on the same arm (Methods, "individual overlapping fields"). Spikes as the animal passes through the fields: reading (a) each cell's spikes in its own field, reading (b) both cells' spikes in the union of the two fields. Per pair and state, the cross-correlogram (1 ms bins, lags of plus and minus 400 ms) is convolved with a 60-bin Gaussian window, and the phase cross-correlogram (unwrapped theta phase, 0.01 pi bins over plus and minus 6 pi, for spike pairs within 400 ms) with a 60-bin window (Methods). A pair is used in a state when its cross-correlogram holds at least 20 spike pairs within 200 ms (standard choice; the paper gives no minimum). Summed cross-correlograms sum the pairs' cross-correlograms, each scaled to unit sum (standard choice). The period of a summed cross-correlogram, the spacing of its peaks, is measured as the period of its largest Fourier component (50 to 200 ms; pi to 4 pi on the phase axis) after the slow trend is removed (standard choice; a peak-picking rule gave unstable spacings on the noisier per-session sums). For the pooled sums the spacing of the peaks themselves is printed too (peak_spacing).

In [48]:
T0 = time.time()
LAGS = np.arange(-400, 401)
PH_BIN = 0.01 * np.pi
PH_MAX = 6 * np.pi
PH_LAGS = np.arange(-int(round(PH_MAX / PH_BIN)), int(round(PH_MAX / PH_BIN)) + 1) * PH_BIN


def pair_ccgs(S, FF, reading):
    sp = S["sp"]
    st = S["trials"].st_lab.values[sp.trial.values]
    has_ph = S["has_lfp"]
    # spikes of each cell on each arm, held once
    by = {}
    for (u, arm), g in sp.assign(state=st).groupby(["u", "arm"]):
        by[(u, arm)] = (g.lin.values, g.t.values * 1000, g.phase_u.values if has_ph else None, g.state.values)
    rows = []
    for arm in ("Left", "Right"):
        Fa = FF[(FF.arm == arm)].reset_index(drop=True)
        for i in range(len(Fa)):
            for j in range(i + 1, len(Fa)):
                f1, f2 = Fa.iloc[i], Fa.iloc[j]
                if f1.u == f2.u or f1.hi <= f2.lo or f2.hi <= f1.lo:
                    continue
                # order the pair so that Ltr (peak 2 - peak 1) is signed consistently
                if f2.peak_pos < f1.peak_pos:
                    f1, f2 = f2, f1
                if reading == "a":
                    b1, b2 = (f1.lo, f1.hi), (f2.lo, f2.hi)
                else:
                    b1 = b2 = (min(f1.lo, f2.lo), max(f1.hi, f2.hi))
                l1, t1, p1, s1 = by[(f1.u, arm)]
                l2, t2, p2, s2 = by[(f2.u, arm)]
                m1 = (l1 >= b1[0]) & (l1 < b1[1])
                m2 = (l2 >= b2[0]) & (l2 < b2[1])
                r = dict(session=S["session"], rat=S["rat"], arm=arm, u1=f1.u, u2=f2.u, Ltr=f2.peak_pos - f1.peak_pos)
                for s in ("Pre", "Cooling", "Post"):
                    k1, k2 = m1 & (s1 == s), m2 & (s2 == s)
                    if has_ph:
                        d, dph = mc.pair_diffs(t1[k1], t2[k2], 400, p1[k1], p2[k2])
                    else:
                        d = mc.pair_diffs(t1[k1], t2[k2], 400)
                    h = np.bincount(np.clip(np.round(d).astype(int) + 400, 0, 800), minlength=801).astype(float)
                    r[f"n_{s}"] = h[200:601].sum()
                    r[f"ccg_{s}"] = mc.smooth60(h)
                    if has_ph:
                        kk = np.clip(np.round(dph / PH_BIN).astype(int) + (len(PH_LAGS) // 2), 0, len(PH_LAGS) - 1)
                        r[f"pccg_{s}"] = mc.smooth60(np.bincount(kk, minlength=len(PH_LAGS)).astype(float))
                rows.append(r)
    return rows


def ccg_period(y, kind="time"):
    """Period of a summed cross-correlogram (mc.dominant_period): 50 to 200 ms on
    the time axis, pi to 4 pi on the phase axis; the trend is a Gaussian of 50 ms
    (time) or 0.5 pi (phase)."""
    if kind == "time":
        return mc.dominant_period(y, LAGS, 50, 200, 50)
    return mc.dominant_period(y, PH_LAGS, np.pi, 4 * np.pi, 50)


PAIRS = {}
F5all = FIELDS[(5.0, "lab")]
for reading in ("a", "b"):
    rows = []
    for S in USESS:
        FF = F5all[F5all.session == S["session"]]
        rows += pair_ccgs(S, FF, reading)
    PAIRS[reading] = pd.DataFrame(rows)
print(f"pair cross-correlograms in {time.time() - T0:.0f} s")
for k, P in PAIRS.items():
    use = {s: (P[f"n_{s}"] >= 20) for s in mc.STATES}
    print(f"reading {k}: {len(P)} overlapping pairs in {P.session.nunique()} sessions; usable pre {use['Pre'].sum()}, cooling {use['Cooling'].sum()}, "
          f"post {use['Post'].sum()}, all three {(use['Pre'] & use['Cooling'] & use['Post']).sum()}; sessions with usable pairs in every state "
          f"{P[use['Pre'] & use['Cooling'] & use['Post']].session.nunique()}")
    print("   pairs by rat (usable in pre):", P[use["Pre"]].groupby("rat").size().to_dict())


def summed(P, states, kind="ccg"):
    tot = 0
    n = 0
    for s in states:
        ok = P[f"n_{s}"] >= 20
        for v in P.loc[ok, f"{kind}_{s}"]:
            if v.sum() > 0:
                tot = tot + v / v.sum()
                n += 1
    return (tot if n else None), n


def peak_spacing(y, lags=LAGS, lim=300):
    """Spacing of the peaks of a summed cross-correlogram (the criterion's way (i)).
    The slow trend (a Gaussian of 50 ms, as in ccg_period) is removed, and peaks
    are local maxima within +-lim ms with a prominence of at least 10% of the
    detrended range there, so that small shoulders are not counted (standard
    choices). Returns the mean distance between successive peaks, the distance
    from the peak nearest zero to its neighbours, and the peak lags."""
    from scipy.signal import find_peaks
    from scipy.ndimage import gaussian_filter1d
    if y is None:
        return np.nan, np.nan, []
    z = y - gaussian_filter1d(y, 50)
    w = np.abs(lags) <= lim
    pk = find_peaks(z, prominence=0.1 * (z[w].max() - z[w].min()))[0]
    pk = pk[np.abs(lags[pk]) <= lim]
    if len(pk) < 2:
        return np.nan, np.nan, list(lags[pk])
    j = int(np.argmin(np.abs(lags[pk])))
    nbr = [lags[pk[j]] - lags[pk[j - 1]]] if j > 0 else []
    nbr += [lags[pk[j + 1]] - lags[pk[j]]] if j + 1 < len(pk) else []
    return float(np.mean(np.diff(lags[pk]))), float(np.mean(nbr)), [int(v) for v in lags[pk]]


def lfp_period_ms(S, states):
    tr = S["trials"]
    return 1000 * np.mean(1 / tr.f_hil[tr.st_lab.isin(states)]) if S["has_lfp"] else np.nan


SBYNAME = {S["session"]: S for S in SESS}
pair cross-correlograms in 19 s
reading a: 12834 overlapping pairs in 23 sessions; usable pre 9482, cooling 10447, post 10463, all three 8310; sessions with usable pairs in every state 23
   pairs by rat (usable in pre): {'MS10': 86, 'MS12': 1306, 'MS13': 712, 'MS21': 4944, 'MS22': 2434}
reading b: 12834 overlapping pairs in 23 sessions; usable pre 11212, cooling 11805, post 11861, all three 10407; sessions with usable pairs in every state 23
   pairs by rat (usable in pre): {'MS10': 96, 'MS12': 1523, 'MS13': 790, 'MS21': 5900, 'MS22': 2903}

fig5d-ccg-period¶

The theta-repeated cross-correlograms of place cell pairs had a period of about 85 ms before cooling, shorter than the LFP theta period (about 110 ms), and the period lengthened during MS cooling in each session (P = 0.002), while the period of the phase cross-correlograms was unaffected (P = 0.32).

In [49]:
PER = {}
for k, P in PAIRS.items():
    for pre_states, lab_ in [(["Pre"], "pre"), (["Pre", "Post"], "pre and post")]:
        y, n = summed(P, pre_states)
        per = ccg_period(y)
        lfp = np.nanmean([lfp_period_ms(SBYNAME[s_], pre_states) for s_ in P.session.unique()])
        sp_all, sp_c, pk_l = peak_spacing(y)
        print(f"reading {k}, all pairs pooled, {lab_}: {n} pair cross-correlograms, period {per:.1f} ms (Fourier); peak spacing {sp_all:.1f} ms "
              f"(mean over peaks within 300 ms), {sp_c:.1f} ms (central peak to its neighbours), peaks at {pk_l} ms; mean LFP theta period {lfp:.1f} ms")
    rows = []
    for sess, g in P.groupby("session"):
        r = dict(session=sess, rat=g.rat.iloc[0])
        for cond, states in [("control", ["Pre", "Post"]), ("cooling", ["Cooling"]), ("pre", ["Pre"])]:
            y, n = summed(g, states)
            r[f"n_{cond}"] = n
            r[f"T_{cond}"] = ccg_period(y)
            yp, _ = summed(g, states, "pccg") if SBYNAME[sess]["has_lfp"] else (None, 0)
            r[f"Tph_{cond}"] = ccg_period(yp, "phase")
        rows.append(r)
    PS = pd.DataFrame(rows)
    PER[k] = PS
    every = set(P[(P.n_Pre >= 20) & (P.n_Cooling >= 20) & (P.n_Post >= 20)].session)
    for set_name, sel in [("a all sessions with pairs", PS.n_cooling > 0), ("b sessions with pairs in every state", PS.session.isin(every))]:
        d = PS[sel].dropna(subset=["T_control", "T_cooling"])
        p, n = mc.signrank(d.T_cooling, d.T_control)
        dp = PS[sel].dropna(subset=["Tph_control", "Tph_cooling"])
        pp, npp = mc.signrank(dp.Tph_cooling, dp.Tph_control)
        print(f"  reading {k}, sessions {set_name}: n = {n}; period control median {d.T_control.median():.1f} ms, cooling {d.T_cooling.median():.1f} ms; "
              f"longer in {(d.T_cooling > d.T_control).sum()} of {n}; signed-rank P = {p:.3g}; phase period control {dp.Tph_control.median() / np.pi:.3f} pi, "
              f"cooling {dp.Tph_cooling.median() / np.pi:.3f} pi, P = {pp:.3g} (n = {npp})")
    print(PS.round(2).to_string(index=False))
reading a, all pairs pooled, pre: 9482 pair cross-correlograms, period 108.1 ms (Fourier); peak spacing 107.2 ms (mean over peaks within 300 ms), 102.5 ms (central peak to its neighbours), peaks at [-181, -75, 21, 130, 248] ms; mean LFP theta period 120.9 ms
reading a, all pairs pooled, pre and post: 19945 pair cross-correlograms, period 109.6 ms (Fourier); peak spacing 108.2 ms (mean over peaks within 300 ms), 105.5 ms (central peak to its neighbours), peaks at [-184, -79, 20, 132, 249] ms; mean LFP theta period 120.1 ms
  reading a, sessions a all sessions with pairs: n = 23; period control median 108.3 ms, cooling 120.0 ms; longer in 19 of 23; signed-rank P = 0.00485; phase period control 1.859 pi, cooling 1.843 pi, P = 0.305 (n = 22)
  reading a, sessions b sessions with pairs in every state: n = 23; period control median 108.3 ms, cooling 120.0 ms; longer in 19 of 23; signed-rank P = 0.00485; phase period control 1.859 pi, cooling 1.843 pi, P = 0.305 (n = 22)
           session  rat  n_control  T_control  Tph_control  n_cooling  T_cooling  Tph_cooling  n_pre  T_pre  Tph_pre
MS10-170307-154746 MS10         48      102.6         5.74         24        109          5.7     29   98.7     5.45
MS10-170314-163038 MS10         49      103.9         5.43         21      122.5         5.78     26  106.4     3.24
MS10-170317-153237 MS10         71      126.8         6.26         38      115.6         7.95     31  115.6     7.03
MS12-170714-122034 MS12        779      115.2         6.07        452        127         6.24    340  112.2     5.97
MS12-170715-111545 MS12        385        112          NaN        217      128.2          NaN    191  109.6      NaN
MS12-170716-172307 MS12        633      110.3         6.11        354      130.6         6.26    321  109.2     6.06
MS12-170717-111614 MS12        567      113.8         6.13        343      129.8         6.22    310  114.8     6.24
MS12-170719-095305 MS12        312      113.8         5.77        185      123.4            6    144  114.8     5.52
MS13-171128-113924 MS13        106      91.02         5.32         51      109.6         5.63     51  87.26     5.24
MS13-171129-105507 MS13        270      98.85         5.52        132      121.6          5.8    141     99     5.49
MS13-171130-121758 MS13       1031      101.8         5.67        556      113.6         5.75    473  97.81     5.48
MS13-171201-130527 MS13        120      97.96         5.45         49      104.7         5.01     47  91.15     4.94
MS21-180625-153927 MS21        537      109.2         4.65        277      93.36         4.58    238  105.7     6.06
MS21-180627-143449 MS21       3506      118.5          6.3       1872      135.7         6.35   1613  120.9     6.26
MS21-180628-155921 MS21       2882      107.8          5.8       1347        120         5.66   1359    106     5.66
MS21-180629-110332 MS21       1491        105         5.93        907      120.2         6.16    728  100.5     5.75
MS21-180712-103200 MS21        413      109.4         5.88        233      115.4         5.61    148  110.3      4.1
MS21-180719-155941 MS21       1646      109.4         5.97        788      106.7          5.9    858  111.7     5.93
MS22-180628-120341 MS22        312      108.3          5.9        154      115.8         5.49    141  111.5     5.97
MS22-180629-110319 MS22       3253      108.3         5.99       1680      120.7         5.88   1555  107.3     5.87
MS22-180711-112912 MS22        835      107.4         5.93        407        113         5.87    404  105.2     5.77
MS22-180719-122813 MS22         78        180         4.53         37      138.6         5.08     43  85.44     4.58
MS22-180720-110055 MS22        621      84.78         5.08        323      89.78         4.95    291  81.61     4.88
reading b, all pairs pooled, pre: 11212 pair cross-correlograms, period 104.5 ms (Fourier); peak spacing 103.5 ms (mean over peaks within 300 ms), 100.0 ms (central peak to its neighbours), peaks at [-170, -72, 19, 128, 244] ms; mean LFP theta period 120.9 ms
reading b, all pairs pooled, pre and post: 23073 pair cross-correlograms, period 106.6 ms (Fourier); peak spacing 104.0 ms (mean over peaks within 300 ms), 102.0 ms (central peak to its neighbours), peaks at [-172, -75, 19, 129, 244] ms; mean LFP theta period 120.1 ms
  reading b, sessions a all sessions with pairs: n = 23; period control median 105.9 ms, cooling 115.8 ms; longer in 18 of 23; signed-rank P = 0.0415; phase period control 1.841 pi, cooling 1.786 pi, P = 0.321 (n = 22)
  reading b, sessions b sessions with pairs in every state: n = 23; period control median 105.9 ms, cooling 115.8 ms; longer in 18 of 23; signed-rank P = 0.0415; phase period control 1.841 pi, cooling 1.786 pi, P = 0.321 (n = 22)
           session  rat  n_control  T_control  Tph_control  n_cooling  T_cooling  Tph_cooling  n_pre  T_pre  Tph_pre
MS10-170307-154746 MS10         53      101.8         5.83         25      108.2         5.58     31  101.5      5.4
MS10-170314-163038 MS10         63      103.2         5.29         30      123.9         6.62     32  106.6     5.39
MS10-170317-153237 MS10         73      127.2         6.04         40       77.1         5.15     33  114.8     3.88
MS12-170714-122034 MS12        939      123.4          6.6        513      120.2         5.58    433  124.6     6.71
MS12-170715-111545 MS12        443      110.5          NaN        236        123          NaN    214  109.4      NaN
MS12-170716-172307 MS12        716      110.7         6.18        377      123.7         5.92    362  108.2     6.09
MS12-170717-111614 MS12        655      111.1         6.02        358      125.5         5.93    344  110.1     6.09
MS12-170719-095305 MS12        363      118.7         6.07        203      122.3         5.52    170  121.4     6.07
MS13-171128-113924 MS13        113        101         5.23         55      109.8         5.59     55  87.61     5.11
MS13-171129-105507 MS13        319         99         5.46        159      129.8         6.06    163   99.3     5.48
MS13-171130-121758 MS13       1107      102.2          5.7        594      114.6         5.83    521  99.15     5.53
MS13-171201-130527 MS13        126      100.5         5.66         51      103.7         4.95     51  93.89     4.68
MS21-180625-153927 MS21        628        109         4.72        335      92.17         4.62    281  106.6     5.99
MS21-180627-143449 MS21       4159      117.2         6.26       2130      133.2         6.13   1991  115.4      5.9
MS21-180628-155921 MS21       3228      106.4         5.63       1547      118.5         5.85   1567  103.5     5.48
MS21-180629-110332 MS21       1795        103         5.83       1012      116.2         5.99    869    100     5.63
MS21-180712-103200 MS21        479      105.9         3.25        259        114          5.7    199  106.7     3.39
MS21-180719-155941 MS21       1910      104.4         5.75        912      104.5         5.88    993  106.6     3.68
MS22-180628-120341 MS22        336      115.6         6.22        168      110.5         5.35    161  120.7     6.49
MS22-180629-110319 MS22       3808      105.5         5.82       1913      115.8         5.63   1875  102.4     5.64
MS22-180711-112912 MS22        948      102.6         5.67        481        108         5.55    468  100.5     5.58
MS22-180719-122813 MS22         94      180.5        10.29         44      134.3         5.05     53  110.3     3.77
MS22-180720-110055 MS22        718      84.34         5.21        363       89.9         4.91    346  81.61     4.89

Result: partially reproduced. Under pair reading (a), the summed pre cross-correlogram of 9482 pairs has a period of 108.1 ms, shorter than the LFP theta period of 120.9 ms but outside 76.5 to 93.5 ms. Per session the period lengthens during cooling (108.3 to 120.0 ms, longer in 19 of 23 sessions, P = 0.0049), and the phase period does not change (1.86 against 1.84 pi, P = 0.31). Reading (b) gives 104.5 ms and P = 0.042. The spacing of the peaks of the summed pre cross-correlogram, measured directly, is 107.2 ms (mean over 5 peaks within 300 ms; 102.5 ms from the central peak to its neighbours) under pair reading (a) and 103.5 ms under (b), also outside 76.5 to 93.5 ms.

The second way of the criterion, the parameter b of the surface fit, is in fig5cg-compression below.

fig5e-phase-period-below-2pi¶

The period of the summed phase cross-correlograms of place cell pairs was shorter than one theta cycle (2 pi), as place cells oscillate faster than LFP theta.

In [50]:
for k, P in PAIRS.items():
    for states, lab_ in [(["Pre"], "pre"), (["Cooling"], "cooling")]:
        y, n = summed(P[P.session.map(lambda s_: SBYNAME[s_]["has_lfp"])], states, "pccg")
        per = ccg_period(y, "phase")
        print(f"reading {k}, {lab_}: {n} pairs, phase period {per / np.pi:.3f} pi rad (below 2 pi: {per < 2 * np.pi})")
reading a, pre: 9291 pairs, phase period 1.867 pi rad (below 2 pi: True)
reading a, cooling: 10230 pairs, phase period 1.905 pi rad (below 2 pi: True)
reading b, pre: 10998 pairs, phase period 1.826 pi rad (below 2 pi: True)
reading b, cooling: 11569 pairs, phase period 1.862 pi rad (below 2 pi: True)

Result: reproduced. The summed phase cross-correlograms have periods of 1.87 pi (pre) and 1.91 pi (cooling) under pair reading (a), and 1.83 and 1.86 pi under reading (b), all below 2 pi.

fig5h-time-lags-increase, fig5i-phase-lags-unchanged¶

Pair lag: (a) the largest peak within half the LFP theta period of zero lag in that state (within pi for phase); (b) the peak nearest zero. Absolute values. Signed-rank over pairs usable in both states.

In [51]:
def pair_lag(y, lags, half):
    pk = mc.peaks(y)
    if len(pk) == 0:
        return np.nan, np.nan
    near = pk[np.abs(lags[pk]) <= half]
    la = lags[near[np.argmax(y[near])]] if len(near) else np.nan
    lb = lags[pk[np.argmin(np.abs(lags[pk]))]]
    return la, lb


LAG = {}
for k, P in PAIRS.items():
    rows = []
    for _, p in P.iterrows():
        S = SBYNAME[p.session]
        r = dict(session=p.session, rat=p.rat, Ltr=p.Ltr)
        for s in mc.STATES:
            ok = p[f"n_{s}"] >= 20
            half = lfp_period_ms(S, [s]) / 2 if S["has_lfp"] else 60.0
            la, lb = pair_lag(p[f"ccg_{s}"], LAGS, half) if ok else (np.nan, np.nan)
            r[f"ta_{s}"], r[f"tb_{s}"] = la, lb
            if S["has_lfp"] and ok:
                pa, pb = pair_lag(p[f"pccg_{s}"], PH_LAGS, np.pi)
            else:
                pa = pb = np.nan
            r[f"pa_{s}"], r[f"pb_{s}"] = pa, pb
        rows.append(r)
    LAG[k] = pd.DataFrame(rows)
In [52]:
for k, L in LAG.items():
    for rd in ("ta", "tb"):
        out = []
        for a_, b_ in [("Pre", "Cooling"), ("Post", "Cooling"), ("Pre", "Post")]:
            x, y = L[f"{rd}_{a_}"].abs(), L[f"{rd}_{b_}"].abs()
            ok = x.notna() & y.notna()
            p, n = mc.signrank(y[ok], x[ok])
            pr = mc.ranksum(L[f"{rd}_{b_}"].abs(), L[f"{rd}_{a_}"].abs())
            out.append(f"{a_} {x[ok].median():.1f} vs {b_} {y[ok].median():.1f} ms, signed-rank P = {p:.3g} (n = {n}), rank-sum over all pairs P = {pr:.3g}")
        print(f"pairs {k}, lag {rd}: " + "; ".join(out))
# per session: pairs share cells and sessions, so the median |lag| of each session and state is compared over sessions
for k, L in LAG.items():
    for rd in ("ta", "tb"):
        g = L.groupby("session")[[f"{rd}_{s}" for s in mc.STATES]].agg(lambda v: np.nanmedian(np.abs(v)))
        out = []
        for a_, b_ in [("Pre", "Cooling"), ("Post", "Cooling"), ("Pre", "Post")]:
            p, n = mc.signrank(g[f"{rd}_{b_}"], g[f"{rd}_{a_}"])
            out.append(f"{a_} {g[f'{rd}_{a_}'].median():.1f} vs {b_} {g[f'{rd}_{b_}'].median():.1f} ms, {b_} longer in "
                       f"{int((g[f'{rd}_{b_}'] > g[f'{rd}_{a_}']).sum())} of {n}, P = {p:.3g}")
        print(f"per session, pairs {k}, lag {rd}: " + "; ".join(out))
pairs a, lag ta: Pre 27.0 vs Cooling 30.0 ms, signed-rank P = 1.89e-31 (n = 8506), rank-sum over all pairs P = 1.35e-16; Post 27.0 vs Cooling 30.0 ms, signed-rank P = 9.29e-45 (n = 9232), rank-sum over all pairs P = 4.53e-23; Pre 27.0 vs Post 27.0 ms, signed-rank P = 0.0341 (n = 8283), rank-sum over all pairs P = 0.163
pairs a, lag tb: Pre 15.0 vs Cooling 17.0 ms, signed-rank P = 1.56e-13 (n = 8821), rank-sum over all pairs P = 0.000174; Post 16.0 vs Cooling 16.0 ms, signed-rank P = 0.000551 (n = 9597), rank-sum over all pairs P = 0.851; Pre 15.0 vs Post 16.0 ms, signed-rank P = 6.88e-05 (n = 8602), rank-sum over all pairs P = 5.35e-05
pairs b, lag ta: Pre 27.0 vs Cooling 30.0 ms, signed-rank P = 2.53e-37 (n = 10639), rank-sum over all pairs P = 8.09e-20; Post 27.0 vs Cooling 30.0 ms, signed-rank P = 3.22e-61 (n = 11213), rank-sum over all pairs P = 5.4e-31; Pre 27.0 vs Post 27.0 ms, signed-rank P = 0.00824 (n = 10548), rank-sum over all pairs P = 0.0194
pairs b, lag tb: Pre 14.0 vs Cooling 15.0 ms, signed-rank P = 2.21e-15 (n = 10746), rank-sum over all pairs P = 3.76e-06; Post 15.0 vs Cooling 15.0 ms, signed-rank P = 0.00652 (n = 11327), rank-sum over all pairs P = 0.781; Pre 14.0 vs Post 15.0 ms, signed-rank P = 8.74e-08 (n = 10657), rank-sum over all pairs P = 8.32e-06
per session, pairs a, lag ta: Pre 27.0 vs Cooling 30.0 ms, Cooling longer in 16 of 23, P = 0.0142; Post 27.0 vs Cooling 30.0 ms, Cooling longer in 17 of 23, P = 0.0115; Pre 27.0 vs Post 27.0 ms, Post longer in 9 of 23, P = 0.983
per session, pairs a, lag tb: Pre 15.0 vs Cooling 15.0 ms, Cooling longer in 9 of 23, P = 0.227; Post 16.0 vs Cooling 15.0 ms, Cooling longer in 6 of 23, P = 0.0397; Pre 15.0 vs Post 16.0 ms, Post longer in 12 of 23, P = 0.948
per session, pairs b, lag ta: Pre 26.0 vs Cooling 30.0 ms, Cooling longer in 13 of 23, P = 0.0155; Post 26.0 vs Cooling 30.0 ms, Cooling longer in 18 of 23, P = 0.0135; Pre 26.0 vs Post 26.0 ms, Post longer in 9 of 23, P = 0.793
per session, pairs b, lag tb: Pre 14.0 vs Cooling 14.0 ms, Cooling longer in 11 of 23, P = 0.671; Post 15.0 vs Cooling 14.0 ms, Cooling longer in 8 of 23, P = 0.369; Pre 14.0 vs Post 15.0 ms, Post longer in 13 of 23, P = 0.634

Result: partially reproduced. Under lag reading (a), pair time lags are longer during cooling than before (27 to 30 ms, signed-rank P = 1.9e-31 over 8506 pairs) and after (P = 9.3e-45), but pre and post also differ (P = 0.034; 0.0082 with pair reading (b)), so no reading gives P >= 0.05 for pre against post. The rank-sum variant over all pairs gives P = 0.16 for pre against post. Pairs share cells and sessions, so the pair tests count dependent values as independent. Over sessions (median |lag| per session and state, 23 sessions), cooling lags are longer than pre (27 against 30 ms, longer in 16 of 23, P = 0.014) and post (P = 0.012), and pre and post do not differ (P = 0.98); pair reading (b) gives P = 0.016, 0.014 and 0.79. Under lag reading (b) the per-session tests give P = 0.23 (pre against cooling), 0.040 (post against cooling, cooling shorter) and 0.95. The criterion fixes the test over pairs, so the outcome stays partial; the per-session variant shows the pattern the paper reports under lag reading (a).

In [53]:
for k, L in list(LAG.items()) + [(k + " without MS13-171130", L[~L.session.isin(BAD_THETA)]) for k, L in LAG.items()]:
    for rd in ("pa", "pb"):
        out = []
        for a_, b_ in [("Pre", "Cooling"), ("Cooling", "Post"), ("Pre", "Post")]:
            x, y = L[f"{rd}_{a_}"].abs(), L[f"{rd}_{b_}"].abs()
            ok = x.notna() & y.notna()
            p, n = mc.signrank(y[ok], x[ok])
            out.append(f"{a_} {x[ok].median():.3f} vs {b_} {y[ok].median():.3f} rad, P = {p:.3g} (n = {n})")
        print(f"pairs {k}, phase lag {rd}: " + "; ".join(out))
pairs a, phase lag pa: Pre 1.414 vs Cooling 1.414 rad, P = 0.373 (n = 8451); Cooling 1.414 vs Post 1.414 rad, P = 0.41 (n = 9199); Pre 1.414 vs Post 1.382 rad, P = 0.503 (n = 8271)
pairs a, phase lag pb: Pre 0.471 vs Cooling 0.503 rad, P = 2.65e-08 (n = 8638); Cooling 0.503 vs Post 0.503 rad, P = 0.626 (n = 9404); Pre 0.471 vs Post 0.503 rad, P = 0.00646 (n = 8435)
pairs b, phase lag pa: Pre 1.382 vs Cooling 1.414 rad, P = 0.0681 (n = 10506); Cooling 1.414 vs Post 1.382 rad, P = 0.0841 (n = 11066); Pre 1.382 vs Post 1.382 rad, P = 0.59 (n = 10426)
pairs b, phase lag pb: Pre 0.408 vs Cooling 0.440 rad, P = 5.12e-09 (n = 10539); Cooling 0.440 vs Post 0.440 rad, P = 0.592 (n = 11101); Pre 0.408 vs Post 0.440 rad, P = 5.71e-05 (n = 10457)
pairs a without MS13-171130, phase lag pa: Pre 1.414 vs Cooling 1.414 rad, P = 0.369 (n = 7995); Cooling 1.414 vs Post 1.382 rad, P = 0.624 (n = 8668); Pre 1.414 vs Post 1.382 rad, P = 0.706 (n = 7820)
pairs a without MS13-171130, phase lag pb: Pre 0.471 vs Cooling 0.503 rad, P = 1.61e-08 (n = 8174); Cooling 0.503 vs Post 0.503 rad, P = 0.292 (n = 8865); Pre 0.471 vs Post 0.503 rad, P = 0.0149 (n = 7973)
pairs b without MS13-171130, phase lag pa: Pre 1.382 vs Cooling 1.414 rad, P = 0.0399 (n = 9989); Cooling 1.414 vs Post 1.382 rad, P = 0.167 (n = 10485); Pre 1.382 vs Post 1.382 rad, P = 0.962 (n = 9914)
pairs b without MS13-171130, phase lag pb: Pre 0.408 vs Cooling 0.440 rad, P = 3.9e-09 (n = 10020); Cooling 0.440 vs Post 0.440 rad, P = 0.246 (n = 10520); Pre 0.408 vs Post 0.440 rad, P = 0.00025 (n = 9943)

Result: reproduced (assumed). Under lag reading (a), the largest peak within pi of zero, phase lags do not differ between any two states (P = 0.37, 0.41 and 0.50 over 8271 to 9199 pairs; 0.068 to 0.59 with pair reading (b)). Under reading (b), the peak nearest zero, pre differs from cooling (P = 2.7e-8). The outcome rests on reading (a). Without MS13-171130 (theta channel marked bad), reading (a) gives P = 0.37, 0.62 and 0.71 with pair reading (a), and P = 0.040 for pre against cooling with pair reading (b).

fig5cg-compression¶

Distance-time compression of place cell pairs (0.54 cm/ms before cooling) decreased during MS cooling (P = 0.02), while distance-phase compression was unchanged (P = 0.92).

The density of Figure 5C: the pairs' smoothed cross-correlograms (each scaled to unit sum) averaged in bins of Ltr (5 cm) at each lag (1 ms), over Ltr of plus and minus 100 cm and lags of plus and minus 400 ms. The surface of the Methods is fitted by least squares (scipy curve_fit), x the distance Ltr and y the lag, reading (a) Z = e (cos(2 pi x / (a b) + 2 pi y / b) + 1) exp(-(x + f y)^2 / 2c^2) exp(-(y - g)^2 / 2d^2) and reading (b) with the +1 inside the cosine. Start values: a from the main lag of each Ltr bin of the pooled pre density (within 40 cm), b the period of the summed cross-correlogram, c 60 cm, d 150 ms (standard choices). The fit's R2 against the density is printed; a negative R2 means the surface fits the density worse than its mean. The compression is |a| (cm/ms on the time axis, cm/rad on the phase axis). Per session the same fit on that session's pairs, control (pre and post) and cooling.

In [54]:
from scipy.optimize import curve_fit


def surf(XY, a, b, c, d, e, f, g, inside=False):
    x, y = XY
    if inside:
        osc = np.cos(2 * np.pi * x / (a * b) + 2 * np.pi * y / b + 1)
    else:
        osc = np.cos(2 * np.pi * x / (a * b) + 2 * np.pi * y / b) + 1
    return e * osc * np.exp(-(x + f * y) ** 2 / (2 * c ** 2)) * np.exp(-(y - g) ** 2 / (2 * d ** 2))


def density(P, states, kind="ccg", lags=LAGS, xbin=5.0, xmax=100.0):
    xb = np.arange(-xmax, xmax + xbin, xbin)
    Z = np.zeros((len(xb) - 1, len(lags)))
    N = np.zeros(len(xb) - 1)
    for s in states:
        ok = (P[f"n_{s}"] >= 20) & P[f"{kind}_{s}"].map(lambda v: isinstance(v, np.ndarray))
        for L, v in zip(P.Ltr[ok], P[f"{kind}_{s}"][ok]):
            i = np.searchsorted(xb, L, side="right") - 1
            if 0 <= i < len(N) and v.sum() > 0:
                Z[i] += v / v.sum()
                N[i] += 1
    with np.errstate(invalid="ignore"):
        Z = Z / N[:, None]
    xc = (xb[:-1] + xb[1:]) / 2
    return xc, Z, N


def a_start(P, states, kind="ccg"):
    """Start value of the compression: from the density, the main lag (largest
    peak within half a theta cycle) of each Ltr bin within 40 cm, regressed on
    Ltr; the ridges of the surface have slope -1/a."""
    lags = LAGS if kind == "ccg" else PH_LAGS
    half = 60.0 if kind == "ccg" else np.pi
    xc, Z, N = density(P, states, kind, lags)
    w = np.abs(lags) <= half
    xs = [xc[i] for i in range(len(xc)) if N[i] >= 5 and abs(xc[i]) <= 40]
    ys = [lags[w][np.argmax(Z[i][w])] for i in range(len(xc)) if N[i] >= 5 and abs(xc[i]) <= 40]
    if len(xs) < 3:
        return np.nan
    return -1 / stats.linregress(xs, ys).slope


def fit_surface(P, states, kind="ccg", inside=False, a0=None, b0=None):
    lags = LAGS if kind == "ccg" else PH_LAGS
    xc, Z, N = density(P, states, kind, lags)
    ok = N > 0
    if ok.sum() < 5:
        return dict(a=np.nan, b=np.nan, ok=False)
    X, Y = np.meshgrid(xc[ok], lags, indexing="ij")
    XY = np.vstack([X.ravel(), Y.ravel()])
    z = Z[ok].ravel()
    z = z - np.nanmin(z)
    d0 = 150.0 if kind == "ccg" else 150.0 * 2 * np.pi / 120.0
    p0 = [a0, b0, 60.0, d0, np.nanmax(z) / 2, 0.0, 0.0]
    sst = np.sum((z - z.mean()) ** 2)
    # the envelope alone (the two Gaussian factors, no oscillation): how much of the density a smooth surface explains
    try:
        pe, _ = curve_fit(lambda XY, c, d, e, f, g: e * np.exp(-(XY[0] + f * XY[1]) ** 2 / (2 * c ** 2)) * np.exp(-(XY[1] - g) ** 2 / (2 * d ** 2)),
                          XY, z, p0=[60.0, d0, np.nanmax(z), 0.0, 0.0], maxfev=3000)
        c, d, e, f, g = pe
        r2_env = 1 - np.sum((z - e * np.exp(-(XY[0] + f * XY[1]) ** 2 / (2 * c ** 2)) * np.exp(-(XY[1] - g) ** 2 / (2 * d ** 2))) ** 2) / sst
    except Exception:
        r2_env = np.nan
    try:
        p, _ = curve_fit(lambda XY, *q: surf(XY, *q, inside=inside), XY, z, p0=p0, maxfev=3000)
        resid = z - surf(XY, *p, inside=inside)
        r2 = 1 - np.sum(resid ** 2) / sst
        return dict(a=abs(p[0]), b=abs(p[1]), r2=r2, r2_env=r2_env, ok=True, p=p, err="")
    except Exception as ex:
        return dict(a=np.nan, b=np.nan, r2=np.nan, r2_env=r2_env, ok=False, err=str(ex))
In [55]:
T0 = time.time()
CMP = {}
for k, P in PAIRS.items():
    L = LAG[k]
    ok = L.ta_Pre.notna()
    ls = stats.linregress(L.ta_Pre[ok], L.Ltr[ok])
    okp = L.pa_Pre.notna()
    lsp = stats.linregress(L.pa_Pre[okp], L.Ltr[okp])
    yP, _ = summed(P, ["Pre"])
    b0 = ccg_period(yP)
    yPp, _ = summed(P[P.session.map(lambda s_: SBYNAME[s_]["has_lfp"])], ["Pre"], "pccg")
    b0p = ccg_period(yPp, "phase")
    a0t = a_start(P, ["Pre"], "ccg")
    a0p = a_start(P[P.session.map(lambda s_: SBYNAME[s_]["has_lfp"])], ["Pre"], "pccg")
    print(f"pairs {k}: start values a {a0t:.3f} cm/ms and {a0p:.2f} cm/rad; least-squares slope of Ltr on the main lag (pre): {ls.slope:.3f} cm/ms (R = {ls.rvalue:.3f}, n = {ok.sum()}); "
          f"on the phase lag {lsp.slope:.2f} cm/rad; summed period {b0:.1f} ms, {b0p / np.pi:.3f} pi")
    for inside in (False, True):
        fT = fit_surface(P, ["Pre"], "ccg", inside, a0=a0t, b0=b0)
        fP = fit_surface(P[P.session.map(lambda s_: SBYNAME[s_]["has_lfp"])], ["Pre"], "pccg", inside, a0=a0p, b0=b0p)
        print(f"   surface reading {'b (+1 inside)' if inside else 'a'}: all pre pairs pooled, time compression {fT['a']:.3f} cm/ms, period b {fT['b']:.1f} ms "
              f"(R2 {fT['r2']:.3f}; envelope alone R2 {fT['r2_env']:.3f}){' failed: ' + fT['err'] if not fT['ok'] else ''}; "
              f"phase compression {fP['a']:.2f} cm/rad, b {fP['b'] / np.pi:.3f} pi (R2 {fP['r2']:.3f}; envelope alone R2 {fP['r2_env']:.3f}){' failed: ' + fP['err'] if not fP['ok'] else ''}")
        if (k, inside) == ("a", False):
            POOLED_FIT = (P, fT)
        rows = []
        for sess, g in P.groupby("session"):
            has_lfp = SBYNAME[sess]["has_lfp"]
            r = dict(session=sess)
            for cond, states in [("control", ["Pre", "Post"]), ("cooling", ["Cooling"])]:
                f1 = fit_surface(g, states, "ccg", inside, a0=a0t, b0=b0)
                r[f"cT_{cond}"], r[f"bT_{cond}"] = f1["a"], f1["b"]
                r[f"r2T_{cond}"], r[f"r2envT_{cond}"], r[f"errT_{cond}"] = f1.get("r2", np.nan), f1.get("r2_env", np.nan), f1.get("err", "")
                r[f"a0_{cond}"] = a_start(g, states, "ccg")
                if has_lfp:
                    f2 = fit_surface(g, states, "pccg", inside, a0=a0p, b0=b0p)
                    r[f"cP_{cond}"] = f2["a"]
                    r[f"okP_{cond}"] = f2["ok"]
                else:
                    r[f"cP_{cond}"] = np.nan
                Lg = L[L.session == sess]
                cols = ["ta_Pre", "ta_Post"] if cond == "control" else ["ta_Cooling"]
                x = np.concatenate([Lg[c_].values for c_ in cols]); y = np.concatenate([Lg.Ltr.values for _ in cols])
                m = np.isfinite(x)
                r[f"ls_{cond}"] = stats.linregress(x[m], y[m]).slope if m.sum() > 5 else np.nan
            rows.append(r)
        CS = pd.DataFrame(rows)
        CMP[(k, inside)] = CS
        p1, n1 = mc.signrank(CS.cT_cooling, CS.cT_control)
        p2, n2 = mc.signrank(CS.cP_cooling, CS.cP_control)
        p3, n3 = mc.signrank(CS.bT_cooling, CS.bT_control)
        p4, n4 = mc.signrank(CS.ls_cooling, CS.ls_control)
        p5, n5 = mc.signrank(CS.a0_cooling.abs(), CS.a0_control.abs())
        fails = pd.concat([CS.errT_control, CS.errT_cooling])
        fails = fails[fails != ""].str.slice(0, 70).value_counts().to_dict()
        print(f"   per-session time fits converged: control {CS.cT_control.notna().sum()} of {len(CS)}, cooling {CS.cT_cooling.notna().sum()} of {len(CS)}; "
              f"median R2 of converged fits control {CS.r2T_control.median():.3f}, cooling {CS.r2T_cooling.median():.3f} (envelope alone {CS.r2envT_control.median():.3f}, "
              f"{CS.r2envT_cooling.median():.3f}); failures: {fails}; phase fits converged: control {int(CS.get('okP_control', pd.Series(dtype=bool)).fillna(False).sum())}, "
              f"cooling {int(CS.get('okP_cooling', pd.Series(dtype=bool)).fillna(False).sum())}")
        print(f"   density ridge slope (start value of a) per session, a variant: control median {CS.a0_control.abs().median():.3f}, cooling {CS.a0_cooling.abs().median():.3f} cm/ms, "
              f"lower in cooling in {int((CS.a0_cooling.abs() < CS.a0_control.abs()).sum())} of {n5}, signed-rank P = {p5:.3g}")
        d1 = (CS.cT_cooling - CS.cT_control)
        print(f"   per session ({n1}): time compression control median {CS.cT_control.median():.3f}, cooling {CS.cT_cooling.median():.3f} cm/ms, "
              f"lower in {(d1 < 0).sum()}, P = {p1:.3g}; phase compression control {CS.cP_control.median():.2f}, cooling {CS.cP_cooling.median():.2f} cm/rad, "
              f"P = {p2:.3g} (n = {n2}); fitted period b control {CS.bT_control.median():.1f}, cooling {CS.bT_cooling.median():.1f} ms, P = {p3:.3g}; "
              f"least-squares slope control {CS.ls_control.median():.3f}, cooling {CS.ls_cooling.median():.3f}, P = {p4:.3g}")
print(f"({time.time() - T0:.0f} s)")
print(CMP[("a", False)].drop(columns=[c for c in CMP[("a", False)] if c.startswith("err")]).round(3).to_string(index=False))
# pooled pre density (pair reading a) and the fitted surface of reading (a)
Pp, fT = POOLED_FIT
xc, Z, N = density(Pp, ["Pre"])
fig, ax = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
ax[0].imshow(Z, aspect="auto", origin="lower", extent=[LAGS[0], LAGS[-1], xc[0], xc[-1]])
ax[0].set_title("pooled pre density"); ax[0].set_xlabel("lag (ms)"); ax[0].set_ylabel("Ltr (cm)")
if fT["ok"]:
    X, Y = np.meshgrid(xc, LAGS, indexing="ij")
    ax[1].imshow(surf(np.vstack([X.ravel(), Y.ravel()]), *fT["p"]).reshape(X.shape), aspect="auto", origin="lower", extent=[LAGS[0], LAGS[-1], xc[0], xc[-1]])
ax[1].set_title(f"fitted surface, reading (a), R2 {fT['r2']:.2f}"); ax[1].set_xlabel("lag (ms)")
plt.tight_layout(); plt.show()
print(f"density: {int((N > 0).sum())} of {len(N)} Ltr bins hold pairs; values {np.nanmin(Z):.2e} to {np.nanmax(Z):.2e}; the full grid is shown")
pairs a: start values a -0.556 cm/ms and -10.32 cm/rad; least-squares slope of Ltr on the main lag (pre): -0.066 cm/ms (R = -0.047, n = 9223); on the phase lag -0.70 cm/rad; summed period 108.1 ms, 1.867 pi
   surface reading a: all pre pairs pooled, time compression 1.393 cm/ms, period b 108.9 ms (R2 -0.135; envelope alone R2 nan); phase compression nan cm/rad, b nan pi (R2 nan; envelope alone R2 nan) failed: Optimal parameters not found: Number of calls to function has reached maxfev = 3000.
   per-session time fits converged: control 9 of 23, cooling 9 of 23; median R2 of converged fits control -0.100, cooling -0.284 (envelope alone 0.684, 0.590); failures: {'Optimal parameters not found: Number of calls to function has reached ': 28}; phase fits converged: control 4, cooling 10
   density ridge slope (start value of a) per session, a variant: control median 0.566, cooling 0.628 cm/ms, lower in cooling in 9 of 19, signed-rank P = 0.623
   per session (5): time compression control median 0.670, cooling 0.674 cm/ms, lower in 3, P = 0.812; phase compression control 11.09, cooling 11.75 cm/rad, P = 0.375 (n = 4); fitted period b control 104.0, cooling 107.6 ms, P = 0.0625; least-squares slope control -0.056, cooling -0.037, P = 0.665
   surface reading b (+1 inside): all pre pairs pooled, time compression nan cm/ms, period b nan ms (R2 nan; envelope alone R2 nan) failed: Optimal parameters not found: Number of calls to function has reached maxfev = 3000.; phase compression nan cm/rad, b nan pi (R2 nan; envelope alone R2 nan) failed: Optimal parameters not found: Number of calls to function has reached maxfev = 3000.
   per-session time fits converged: control 2 of 23, cooling 6 of 23; median R2 of converged fits control -2.292, cooling -2.716 (envelope alone 0.684, 0.590); failures: {'Optimal parameters not found: Number of calls to function has reached ': 38}; phase fits converged: control 1, cooling 4
   density ridge slope (start value of a) per session, a variant: control median 0.566, cooling 0.628 cm/ms, lower in cooling in 9 of 19, signed-rank P = 0.623
   per session (0): time compression control median 0.544, cooling 0.476 cm/ms, lower in 0, P = nan; phase compression control 12.37, cooling 8.85 cm/rad, P = nan (n = 0); fitted period b control 99.8, cooling 115.5 ms, P = nan; least-squares slope control -0.056, cooling -0.037, P = 0.665
pairs b: start values a -0.561 cm/ms and -10.38 cm/rad; least-squares slope of Ltr on the main lag (pre): -0.137 cm/ms (R = -0.099, n = 11141); on the phase lag -2.69 cm/rad; summed period 104.5 ms, 1.826 pi
   surface reading a: all pre pairs pooled, time compression nan cm/ms, period b nan ms (R2 nan; envelope alone R2 0.574) failed: Optimal parameters not found: Number of calls to function has reached maxfev = 3000.; phase compression 11.54 cm/rad, b 1.644 pi (R2 -0.429; envelope alone R2 nan)
   per-session time fits converged: control 12 of 23, cooling 16 of 23; median R2 of converged fits control -0.940, cooling -1.035 (envelope alone 0.483, 0.410); failures: {'Optimal parameters not found: Number of calls to function has reached ': 18}; phase fits converged: control 8, cooling 13
   density ridge slope (start value of a) per session, a variant: control median 0.623, cooling 0.616 cm/ms, lower in cooling in 11 of 19, signed-rank P = 0.709
   per session (10): time compression control median 0.642, cooling 0.623 cm/ms, lower in 7, P = 1; phase compression control 12.42, cooling 11.36 cm/rad, P = 0.578 (n = 7); fitted period b control 101.6, cooling 107.5 ms, P = 0.00195; least-squares slope control -0.123, cooling -0.113, P = 0.36
   surface reading b (+1 inside): all pre pairs pooled, time compression nan cm/ms, period b nan ms (R2 nan; envelope alone R2 0.574) failed: Optimal parameters not found: Number of calls to function has reached maxfev = 3000.; phase compression nan cm/rad, b nan pi (R2 nan; envelope alone R2 nan) failed: Optimal parameters not found: Number of calls to function has reached maxfev = 3000.
   per-session time fits converged: control 2 of 23, cooling 6 of 23; median R2 of converged fits control -3.573, cooling -5.060 (envelope alone 0.483, 0.410); failures: {'Optimal parameters not found: Number of calls to function has reached ': 38}; phase fits converged: control 1, cooling 6
   density ridge slope (start value of a) per session, a variant: control median 0.623, cooling 0.616 cm/ms, lower in cooling in 11 of 19, signed-rank P = 0.709
   per session (0): time compression control median 0.457, cooling 0.484 cm/ms, lower in 0, P = nan; phase compression control 11.81, cooling 8.68 cm/rad, P = nan (n = 0); fitted period b control 97.7, cooling 115.6 ms, P = nan; least-squares slope control -0.123, cooling -0.113, P = 0.36
(371 s)
           session  cT_control  bT_control  r2T_control  r2envT_control  a0_control  cP_control okP_control  ls_control  cT_cooling  bT_cooling  r2T_cooling  r2envT_cooling  a0_cooling  cP_cooling okP_cooling  ls_cooling
MS10-170307-154746         NaN         NaN          NaN             NaN      -0.456         NaN       False       0.096       1.099       115.9       -0.596           0.282         NaN         NaN       False       0.223
MS10-170314-163038         NaN         NaN          NaN             NaN         NaN         NaN       False      -0.465         NaN         NaN          NaN             NaN         NaN       9.752        True       0.102
MS10-170317-153237       0.689       104.8         -0.1           0.447       -0.33       13.87        True       0.088         NaN         NaN          NaN             NaN         NaN       11.85        True       0.127
MS12-170714-122034         NaN         NaN          NaN             NaN      -0.789         NaN       False      -0.011         NaN         NaN          NaN             NaN      -0.556         NaN       False       -0.05
MS12-170715-111545         NaN         NaN          NaN             NaN      -0.737         NaN         NaN      -0.138         NaN         NaN          NaN             NaN      -0.629         NaN         NaN      -0.035
MS12-170716-172307       0.567        99.5       -0.282             NaN      -0.957         NaN       False      -0.062         NaN         NaN          NaN             NaN      -0.938         NaN       False      -0.086
MS12-170717-111614         NaN         NaN          NaN             NaN      -0.495         NaN       False      -0.035         NaN         NaN          NaN             NaN      -0.539         NaN       False       0.018
MS12-170719-095305        0.67         104       -0.551           0.532      -1.359       12.06        True       -0.04       0.641       108.6       -0.884           0.463       -1.08       12.95        True      -0.116
MS13-171128-113924         NaN         NaN          NaN             NaN      -0.465         NaN       False      -0.192         NaN         NaN          NaN             NaN        6.25         NaN       False      -0.193
MS13-171129-105507         NaN         NaN          NaN             NaN       -0.62         NaN       False      -0.078         NaN         NaN          NaN             NaN       -0.65         NaN       False       0.148
MS13-171130-121758         NaN         NaN          NaN            0.73      -0.543         NaN       False      -0.013       0.458       98.63       -0.423           0.686      -0.628         NaN       False       0.038
MS13-171201-130527         NaN         NaN          NaN             NaN      -0.459         NaN       False      -0.074       2.017       114.6        0.028            0.47       -0.37         NaN       False      -0.048
MS21-180625-153927         NaN         NaN          NaN             NaN      -0.565         NaN       False       0.051         NaN         NaN          NaN             NaN      -1.074         NaN       False       0.024
MS21-180627-143449         NaN         NaN          NaN             NaN      -0.507         NaN       False      -0.056         NaN         NaN          NaN             NaN      -0.527       10.84        True      -0.031
MS21-180628-155921       0.526       95.92       -0.136           0.725      -0.587         NaN       False      -0.047       0.584       105.2       -0.229           0.715      -0.634       11.65        True      -0.087
MS21-180629-110332       0.628       96.53       -0.073           0.684      -0.597         NaN       False      -0.067       0.539       99.51       -0.271           0.665      -0.545       10.97        True      -0.026
MS21-180712-103200       0.569       98.46       -0.546             NaN      -0.528       10.12        True      -0.083         NaN         NaN          NaN             NaN      -0.519        14.8        True      -0.194
MS21-180719-155941       0.946       106.9        0.014             NaN      -0.568         NaN       False      -0.179       1.254       107.5        0.087             NaN      -0.627         NaN       False      -0.182
MS22-180628-120341         NaN         NaN          NaN             NaN      -0.669       10.04        True       0.081       0.674       107.6       -0.284           0.741      -0.824        13.7        True      -0.037
MS22-180629-110319       1.507       107.7       -0.017             NaN      -0.699         NaN       False      -0.216         NaN         NaN          NaN             NaN      -0.628         NaN       False      -0.176
MS22-180711-112912       1.364       106.7       -0.088             NaN      -0.561         NaN       False      -0.072        0.86       108.8         -0.5           0.516      -0.791       11.13        True      -0.144
MS22-180719-122813         NaN         NaN          NaN             NaN      -0.345         NaN       False       0.034         NaN         NaN          NaN             NaN         NaN        1518        True      -0.065
MS22-180720-110055         NaN         NaN          NaN             NaN      -0.568         NaN       False       0.023         NaN         NaN          NaN             NaN      -0.552         NaN       False       0.023
density: 20 of 40 Ltr bins hold pairs; values 1.52e-04 to 3.21e-03; the full grid is shown
In [56]:
# bounded, multi-start fit (the verifier's request): b held within 30% of the summed pre period, started from the
# envelope's own fit and from a = 0.3, 0.55 and 1.0 cm/ms of either sign (5, 10 and 20 cm/rad on the phase axis);
# least squares with bounds (scipy least_squares, trust-region reflective), the best of the starts is kept
from scipy.optimize import least_squares
from scipy.ndimage import gaussian_filter1d


def fit_bounded(P, states, kind="ccg", inside=False, b0=None, brange=0.3):
    lags = LAGS if kind == "ccg" else PH_LAGS
    a_starts = (0.3, 0.55, 1.0) if kind == "ccg" else (5.0, 10.0, 20.0)
    xc, Z, N = density(P, states, kind, lags)
    ok = N > 0
    if ok.sum() < 5:
        return dict(a=np.nan, b=np.nan, r2=np.nan, r2_env=np.nan, ok=False)
    X, Y = np.meshgrid(xc[ok], lags, indexing="ij")
    XY = np.vstack([X.ravel(), Y.ravel()])
    z = Z[ok].ravel()
    z = z - np.nanmin(z)
    sst = np.sum((z - z.mean()) ** 2)
    d0 = 150.0 if kind == "ccg" else 150.0 * 2 * np.pi / 120.0
    lo_e = [1.0, 1.0, 0.0, -10.0, -lags.max()]
    hi_e = [1000.0, 10 * lags.max(), 10 * z.max() + 1e-12, 10.0, lags.max()]
    env = lambda q: q[2] * np.exp(-(XY[0] + q[3] * XY[1]) ** 2 / (2 * q[0] ** 2)) * np.exp(-(XY[1] - q[4]) ** 2 / (2 * q[1] ** 2))
    re = least_squares(lambda q: env(q) - z, [60.0, d0, z.max(), 0.0, 0.0], bounds=(lo_e, hi_e))
    r2_env = 1 - np.sum(re.fun ** 2) / sst
    c, d, e, f, g = re.x
    best = None
    for sgn in (-1, 1):
        for a0 in a_starts:
            lo = [-50.0 if sgn < 0 else 0.01, b0 * (1 - brange)] + lo_e
            hi = [-0.01 if sgn < 0 else 50.0, b0 * (1 + brange)] + hi_e
            if inside:
                lo[4] = -hi[4]
            q0 = np.clip([sgn * a0, b0, c, d, e * (0.5 if not inside else 1 / np.cos(1.0)), f, g], np.array(lo) + 1e-9, np.array(hi) - 1e-9)
            r = least_squares(lambda q: surf(XY, *q, inside=inside) - z, q0, bounds=(lo, hi), max_nfev=2000)
            r2 = 1 - np.sum(r.fun ** 2) / sst
            if best is None or r2 > best["r2"]:
                best = dict(a=abs(r.x[0]), b=r.x[1], r2=r2, r2_env=r2_env, ok=True,
                            b_at_bound=bool(min(abs(r.x[1] - lo[1]), abs(r.x[1] - hi[1])) < 1e-3 * b0))
    return best


T0 = time.time()
for k, P in PAIRS.items():
    yP, _ = summed(P, ["Pre"])
    b0 = ccg_period(yP)
    trend = gaussian_filter1d(yP, 50)
    w = np.abs(LAGS) <= 60
    depth = (np.max((yP - trend)[w]) - np.min((yP - trend)[w])) / 2 / trend[LAGS == 0][0]
    xc, Z, N = density(P, ["Pre"])
    Zd = Z[N > 0]
    tz = gaussian_filter1d(Zd, 50, axis=1)
    dz = ((Zd - tz)[:, w].max(1) - (Zd - tz)[:, w].min(1)) / 2 / tz[:, LAGS == 0][:, 0]
    print(f"pairs {k}: theta modulation of the pooled pre density (half the peak-to-trough range of the detrended correlogram within 60 ms, "
          f"over the trend at zero lag): summed {depth:.3f}; per Ltr bin median {np.median(dz):.3f} (range {dz.min():.3f} to {dz.max():.3f}); "
          f"the surface's oscillation term modulates it fully (depth 1)")
    for inside in (False, True):
        fT = fit_bounded(P, ["Pre"], "ccg", inside, b0=b0)
        print(f"   bounded fit, surface reading {'b' if inside else 'a'}, all pre pairs pooled: a {fT['a']:.3f} cm/ms, b {fT['b']:.1f} ms "
              f"(bounds {0.7 * b0:.1f} to {1.3 * b0:.1f}{', at a bound' if fT['b_at_bound'] else ''}); R2 {fT['r2']:.3f}, envelope alone R2 {fT['r2_env']:.3f}")
    if k == "a":
        Pl = P[P.session.map(lambda s_: SBYNAME[s_]["has_lfp"])]
        yp, _ = summed(Pl, ["Pre"], "pccg")
        b0p = ccg_period(yp, "phase")
        fP = fit_bounded(Pl, ["Pre"], "pccg", False, b0=b0p)
        print(f"   bounded fit, surface reading a, phase axis, pooled pre: a {fP['a']:.2f} cm/rad, b {fP['b'] / np.pi:.3f} pi; R2 {fP['r2']:.3f}, "
              f"envelope alone R2 {fP['r2_env']:.3f}")
        rows = []
        for sess, g in P.groupby("session"):
            r = dict(session=sess)
            for cond, states in [("control", ["Pre", "Post"]), ("cooling", ["Cooling"])]:
                f1 = fit_bounded(g, states, "ccg", False, b0=b0)
                r[f"a_{cond}"], r[f"r2_{cond}"], r[f"r2env_{cond}"] = f1["a"], f1["r2"], f1["r2_env"]
            rows.append(r)
        BF = pd.DataFrame(rows)
        p_b, n_b = mc.signrank(BF.a_cooling, BF.a_control)
        r2all = pd.concat([BF.r2_control, BF.r2_cooling])
        print(f"   bounded fits per session, surface reading a, time axis ({len(BF)} sessions, 2 conditions): median R2 control {BF.r2_control.median():.3f}, "
              f"cooling {BF.r2_cooling.median():.3f} (envelope alone {BF.r2env_control.median():.3f}, {BF.r2env_cooling.median():.3f}); "
              f"fits with R2 above 0: {int((r2all > 0).sum())} of {r2all.notna().sum()}, above the envelope: "
              f"{int((r2all > pd.concat([BF.r2env_control, BF.r2env_cooling])).sum())}; a control median {BF.a_control.median():.3f}, "
              f"cooling {BF.a_cooling.median():.3f} cm/ms, P = {p_b:.3g} (n = {n_b})")
print(f"({time.time() - T0:.0f} s)")
pairs a: theta modulation of the pooled pre density (half the peak-to-trough range of the detrended correlogram within 60 ms, over the trend at zero lag): summed 0.067; per Ltr bin median 0.072 (range 0.015 to 0.192); the surface's oscillation term modulates it fully (depth 1)
   bounded fit, surface reading a, all pre pairs pooled: a 1.404 cm/ms, b 109.0 ms (bounds 75.7 to 140.6); R2 -0.138, envelope alone R2 0.799
   bounded fit, surface reading b, all pre pairs pooled: a 3.105 cm/ms, b 122.9 ms (bounds 75.7 to 140.6); R2 -2.580, envelope alone R2 0.799
   bounded fit, surface reading a, phase axis, pooled pre: a 50.00 cm/rad, b 1.860 pi; R2 0.160, envelope alone R2 0.536
   bounded fits per session, surface reading a, time axis (23 sessions, 2 conditions): median R2 control -0.113, cooling -0.230 (envelope alone 0.659, 0.623); fits with R2 above 0: 9 of 46, above the envelope: 0; a control median 0.981, cooling 0.674 cm/ms, P = 0.0522 (n = 23)
pairs b: theta modulation of the pooled pre density (half the peak-to-trough range of the detrended correlogram within 60 ms, over the trend at zero lag): summed 0.043; per Ltr bin median 0.056 (range 0.027 to 0.194); the surface's oscillation term modulates it fully (depth 1)
   bounded fit, surface reading a, all pre pairs pooled: a 1.054 cm/ms, b 106.1 ms (bounds 73.2 to 135.9); R2 -1.456, envelope alone R2 0.574
   bounded fit, surface reading b, all pre pairs pooled: a 27.036 cm/ms, b 127.5 ms (bounds 73.2 to 135.9); R2 -5.843, envelope alone R2 0.574
(185 s)

Result: blocked (methods_underspecified). The surface fit of the Methods fails on this density, under both readings of its equation. With curve_fit (start at the density's ridge slope and the summed period), most fits stop at the evaluation limit (reading (a), pair reading (a): 9 of 23 sessions converge in each condition, 5 in both; reading (b): 2 and 6), and the converged fits explain less than the density's mean (pooled pre R2 -0.135 under reading (a); per session median R2 -0.10 to -5.1). Their envelope alone (the two Gaussian factors without the oscillation) has a per-session median R2 of 0.41 to 0.68, and the surface nests it (as b grows the oscillation term becomes constant), so these fits are stuck short of the best fit and do not show what it would give. A bounded fit with several starts, with b held within 30% of the summed period and started from the envelope's own fit, does no better: pooled pre R2 -0.138 (reading a) and -2.58 (reading b) with pair reading (a), -1.46 and -5.84 with pair reading (b), against 0.80 and 0.57 for the envelope; per session none of the 46 fits reaches the envelope's R2 and 9 exceed 0 (median R2 -0.11 and -0.23). The equation's oscillation term takes the density to zero between its ridges, while the theta modulation of the density is small: half its peak-to-trough range is 6.7% of the trend at zero lag (4.3% with pair reading b; 1.5 to 19% per distance bin). A surface of this form cannot fit the density as built here, and the paper does not say how the density was prepared for the fit (a detrending or a baseline would change it) or give a grid, start values or fitting procedure, so no choice has a defensible basis. As variants, none of which is the criterion's measure: the density's ridge slope is 0.556 cm/ms pooled (0.561 with pair reading b) and does not fall with cooling per session (0.566 against 0.628 cm/ms, P = 0.62; 0.623 against 0.616, P = 0.71); where the curve_fit time fits converge in both conditions, control and cooling do not differ (P = 0.81, 5 sessions; P = 1.0, 10 sessions); the bounded per-session fits give a median a of 0.981 in control and 0.674 cm/ms in cooling (P = 0.052, 23 sessions), from fits below the envelope; the least-squares slope of Ltr on the main lag does not differ (P = 0.67 and 0.36).

fig5-speed-control-cooling¶

In the sessions of Figure 5, mean running speed was 87.3 +- 8.0 in control trials (pre and post combined) and 86.2 +- 9.9 during MS cooling.

In [57]:
fig5_sessions = sorted(set(PAIRS["a"].session[PAIRS["a"].n_Pre >= 20]))
every = sorted(set(PAIRS["a"].session[(PAIRS["a"].n_Pre >= 20) & (PAIRS["a"].n_Cooling >= 20) & (PAIRS["a"].n_Post >= 20)]))
for set_name, names in [("sessions with pairs", fig5_sessions), ("sessions with pairs in every state", every)]:
    for c in ["speed_all", "speed_run"]:
        ctrl, cool = [], []
        for nm in names:
            tr = SBYNAME[nm]["trials"]
            ctrl.append(tr[c][tr.st_lab.isin(["Pre", "Post"])].mean())
            cool.append(tr[c][tr.st_lab == "Cooling"].mean())
        ctrl, cool = np.array(ctrl), np.array(cool)
        print(f"{set_name} (n = {len(names)}), {c}: control {ctrl.mean():.1f} +- {ctrl.std(ddof=1):.1f}, cooling {cool.mean():.1f} +- {cool.std(ddof=1):.1f} cm/s; "
              f"within tolerance: control {abs(ctrl.mean() - 87.3) <= 8.0}, cooling {abs(cool.mean() - 86.2) <= 9.9}")
sessions with pairs (n = 23), speed_all: control 80.3 +- 9.2, cooling 77.1 +- 12.5 cm/s; within tolerance: control True, cooling True
sessions with pairs (n = 23), speed_run: control 81.0 +- 9.2, cooling 78.1 +- 12.1 cm/s; within tolerance: control True, cooling True
sessions with pairs in every state (n = 23), speed_all: control 80.3 +- 9.2, cooling 77.1 +- 12.5 cm/s; within tolerance: control True, cooling True
sessions with pairs in every state (n = 23), speed_run: control 81.0 +- 9.2, cooling 78.1 +- 12.1 cm/s; within tolerance: control True, cooling True

Result: reproduced. In the 23 sessions with place cell pairs, mean speed is 80.3 +- 9.2 cm/s in control trials and 77.1 +- 12.5 cm/s during cooling (81.0 and 78.1 above 10 cm/s), within 79.3 to 95.3 and 76.3 to 96.1.

fig5j-fraction-active-unchanged, fig5k-spikes-per-cycle-unchanged¶

Theta cycles during the trials of the sessions with place cell pairs (as suppl3-theta-cycle-duration). Per cycle, the fraction of the session's place cells (cells with a Figure 5 field) with at least one spike, the same fraction of all curated units (the legend's variant), and the spikes of all curated units.

In [58]:
rows = []
for nm in fig5_sessions:
    S = SBYNAME[nm]
    if not S["has_lfp"]:
        continue
    cyc = S["cycles"]
    sp = S["sp"]
    pcs = set(F5all[F5all.session == nm].u)
    t = sp.t.values
    ci = np.searchsorted(cyc.t0.values, t, side="right") - 1
    ok = (ci >= 0) & (t < cyc.t1.values[np.clip(ci, 0, None)])
    ci, uu = ci[ok], sp.u.values[ok]
    nsp = np.bincount(ci, minlength=len(cyc))
    pair = pd.DataFrame(dict(c=ci, u=uu)).drop_duplicates()
    act_all = np.bincount(pair.c, minlength=len(cyc))
    pp = pair[pair.u.isin(pcs)]
    act_pc = np.bincount(pp.c, minlength=len(cyc))
    st = S["trials"].st_lab.values[cyc.trial.values]
    rows.append(pd.DataFrame(dict(session=nm, state=st, frac_pc=act_pc / max(len(pcs), 1),
                                  frac_all=act_all / len(S["units"]), spikes=nsp)))
CY = pd.concat(rows)
print(f"{len(CY)} cycles in {CY.session.nunique()} sessions; per state {CY.state.value_counts().to_dict()}")
82574 cycles in 22 sessions; per state {'Post': 27782, 'Cooling': 24593, 'Pre': 22607}
In [59]:
for c in ["frac_pc", "frac_all"]:
    out = []
    for a_, b_ in [("Pre", "Cooling"), ("Post", "Cooling"), ("Pre", "Post")]:
        x, y = CY[c][CY.state == a_], CY[c][CY.state == b_]
        out.append(f"{a_} {x.mean():.4f} vs {b_} {y.mean():.4f} (medians {x.median():.4f}, {y.median():.4f}), rank-sum P = {mc.ranksum(x, y):.3g}")
    print(f"{c}: " + "; ".join(out))
per = CY.groupby(["session", "state"]).frac_pc.mean().unstack()
print(f"per session mean fraction, cooling - pre: median {np.median(per.Cooling - per.Pre):.4f}, signed-rank P = {mc.signrank(per.Cooling, per.Pre)[0]:.3g} (n = {len(per)})")
for c in ["frac_pc", "spikes"]:
    per = CY.groupby(["session", "state"])[c].mean().unstack()
    out = []
    for a_, b_ in [("Pre", "Cooling"), ("Post", "Cooling"), ("Pre", "Post")]:
        p, n = mc.signrank(per[b_], per[a_])
        out.append(f"{a_}-{b_} median change {np.median(per[b_] - per[a_]):.4f}, higher in {b_} in {int((per[b_] > per[a_]).sum())} of {n}, P = {p:.3g}")
    print(f"per session means, {c}: " + "; ".join(out))
frac_pc: Pre 0.1891 vs Cooling 0.1998 (medians 0.1791, 0.1875), rank-sum P = 1.64e-25; Post 0.2053 vs Cooling 0.1998 (medians 0.2000, 0.1875), rank-sum P = 6.62e-10; Pre 0.1891 vs Post 0.2053 (medians 0.1791, 0.2000), rank-sum P = 4.05e-65
frac_all: Pre 0.1653 vs Cooling 0.1763 (medians 0.1525, 0.1667), rank-sum P = 2.15e-38; Post 0.1779 vs Cooling 0.1763 (medians 0.1722, 0.1667), rank-sum P = 0.0258; Pre 0.1653 vs Post 0.1779 (medians 0.1525, 0.1722), rank-sum P = 5.94e-58
per session mean fraction, cooling - pre: median -0.0007, signed-rank P = 1 (n = 22)
per session means, frac_pc: Pre-Cooling median change -0.0007, higher in Cooling in 9 of 22, P = 1; Post-Cooling median change -0.0148, higher in Cooling in 4 of 22, P = 0.00285; Pre-Post median change 0.0186, higher in Post in 18 of 22, P = 0.000593
per session means, spikes: Pre-Cooling median change -0.2612, higher in Cooling in 10 of 22, P = 0.799; Post-Cooling median change -1.6528, higher in Cooling in 6 of 22, P = 0.00468; Pre-Post median change 1.6519, higher in Post in 15 of 22, P = 0.00593

Result: not reproduced. Over 82574 theta cycles in 22 sessions, the fraction of place cells active per cycle is higher during cooling than before (0.200 against 0.189, rank-sum P = 1.6e-25). Cycles share cells and sessions, so the rank-sum over cycles counts dependent values as independent. Averaged per session first, pre and cooling do not differ (median change -0.0007, higher in cooling in 9 of 22 sessions, signed-rank P = 1.0, a variant), while post is higher than cooling (P = 0.0029) and pre (P = 0.00059). Under that variant the pre against cooling comparison the criterion judges would hold; the criterion fixes the rank-sum over cycles.

In [60]:
out = []
for a_, b_ in [("Pre", "Cooling"), ("Cooling", "Post"), ("Pre", "Post")]:
    x, y = CY.spikes[CY.state == a_], CY.spikes[CY.state == b_]
    out.append(f"{a_} {x.mean():.2f} vs {b_} {y.mean():.2f} spikes per cycle (medians {x.median():.0f}, {y.median():.0f}), rank-sum P = {mc.ranksum(x, y):.3g}")
print("; ".join(out))
per = CY.groupby(["session", "state"]).spikes.mean().unstack()
print(f"per session mean, cooling - pre: median {np.median(per.Cooling - per.Pre):.3f}, signed-rank P = {mc.signrank(per.Cooling, per.Pre)[0]:.3g} (n = {len(per)})")
Pre 30.79 vs Cooling 31.08 spikes per cycle (medians 22, 24), rank-sum P = 4.86e-07; Cooling 31.08 vs Post 35.19 spikes per cycle (medians 24, 26), rank-sum P = 1.75e-39; Pre 30.79 vs Post 35.19 spikes per cycle (medians 22, 26), rank-sum P = 5.79e-65
per session mean, cooling - pre: median -0.261, signed-rank P = 0.799 (n = 22)

Result: not reproduced. Spikes per theta cycle differ between all pairs of states by rank-sum over cycles (pre 30.8, cooling 31.1, post 35.2; P = 4.9e-7, 1.8e-39 and 5.8e-65). Per session means (a variant, as for fig5j) do not differ from pre to cooling (median change -0.26, P = 0.80) but differ from cooling to post (P = 0.0047) and from pre to post (P = 0.0059), so the claim of absence also fails per session.

suppl1g-waveforms-unchanged¶

The waveforms of hippocampal action potentials were not affected by MS cooling.

The dandiset holds no unit waveforms, only each unit's largest channel. Mean waveforms are taken here from the 20 kHz wide-band signal, high-pass filtered at 300 Hz, on a subset: one session per rat with typed units and the most units (MS10 sessions have few units and are left out), and in each session two 52 s blocks in pre, three in cooling and two in post (mc.unit_waveforms). Trough-to-peak latency is measured on the 20 kHz samples and, as a variant, on the mean waveform interpolated by a cubic spline to 200 kHz. Reading the whole wide-band signal (3 TB) does not fit the run; one block of 16 channels streams in about 1.2 s.

In [61]:
T0 = time.time()
WF_SESS = []
for rat in ["MS12", "MS13", "MS21", "MS22"]:
    cand = [S for S in SESS if S["rat"] == rat and S["has_units"]]
    WF_SESS.append(max(cand, key=lambda S: sum(u["maxch"] >= 0 for u in S["units"])))
WF = pd.concat([mc.unit_waveforms(S) for S in WF_SESS], ignore_index=True)
print(f"sessions {[S['session'] for S in WF_SESS]} in {time.time() - T0:.0f} s")
Ww = WF.pivot_table(index=["session", "u", "cell_type"], columns="cond", values=["trough_to_peak_ms", "trough_to_peak_interp_ms", "p2p_uV", "n"])
Ww = Ww[(Ww[("n", "control")] >= 20) & (Ww[("n", "cooling")] >= 20)]
print(f"units with at least 20 spikes in both conditions: {len(Ww)} of {WF[['session', 'u']].drop_duplicates().shape[0]}")
print("spikes per unit in the waveform blocks, median (range): control", Ww[("n", "control")].median(), f"({Ww[('n', 'control')].min():.0f} to {Ww[('n', 'control')].max():.0f}), cooling",
      Ww[("n", "cooling")].median(), f"({Ww[('n', 'cooling')].min():.0f} to {Ww[('n', 'cooling')].max():.0f})")
for m in ["trough_to_peak_ms", "trough_to_peak_interp_ms", "p2p_uV"]:
    c, k = Ww[(m, "control")], Ww[(m, "cooling")]
    p, n = mc.signrank(k, c)
    print(f"{m}: median control {c.median():.3f}, cooling {k.median():.3f}; median change {np.median(k - c):.3f} "
          f"({100 * np.median((k - c) / c):.2f}%); signed-rank P = {p:.3g} (n = {n})")
    for s_, g in Ww.groupby(level="session"):
        print(f"   {s_}: n = {len(g)}, median change {np.median(g[(m, 'cooling')] - g[(m, 'control')]):.3f}, P = {mc.signrank(g[(m, 'cooling')], g[(m, 'control')])[0]:.3g}")
sessions ['MS12-170715-111545', 'MS13-171130-121758', 'MS21-180627-143449', 'MS22-180629-110319'] in 212 s
units with at least 20 spikes in both conditions: 263 of 401
spikes per unit in the waveform blocks, median (range): control 158.0 (20 to 5572), cooling 115.0 (20 to 3236)
trough_to_peak_ms: median control 0.800, cooling 0.800; median change 0.050 (5.88%); signed-rank P = 1.05e-09 (n = 263)
   MS12-170715-111545: n = 28, median change 0.050, P = 0.0884
   MS13-171130-121758: n = 60, median change 0.025, P = 0.0794
   MS21-180627-143449: n = 94, median change 0.050, P = 0.000399
   MS22-180629-110319: n = 81, median change 0.050, P = 1.46e-06
trough_to_peak_interp_ms: median control 0.790, cooling 0.820; median change 0.035 (4.79%); signed-rank P = 3.12e-11 (n = 263)
   MS12-170715-111545: n = 28, median change 0.018, P = 0.0263
   MS13-171130-121758: n = 60, median change 0.033, P = 0.0433
   MS21-180627-143449: n = 94, median change 0.025, P = 0.000221
   MS22-180629-110319: n = 81, median change 0.050, P = 9.86e-07
p2p_uV: median control 144.738, cooling 146.543; median change 0.649 (0.66%); signed-rank P = 0.0264 (n = 263)
   MS12-170715-111545: n = 28, median change -0.571, P = 0.316
   MS13-171130-121758: n = 60, median change 1.004, P = 0.18
   MS21-180627-143449: n = 94, median change 1.358, P = 0.302
   MS22-180629-110319: n = 81, median change 1.683, P = 0.0202

Result: not reproduced. On the subset of 4 sessions (263 units), the trough-to-peak latency of the mean waveform is longer during cooling (median change +0.05 ms, signed-rank P = 1.1e-9) and the peak-to-peak amplitude differs slightly (+0.65 uV, +0.7%, P = 0.026). The latency change is significant in 2 of the 4 sessions on its own. Measured on the mean waveforms interpolated to 200 kHz, the latency is still longer during cooling (0.79 against 0.82 ms, median change +0.035 ms, P = 3.1e-11; significant in each of the 4 sessions). The units have a median of 158 spikes in the control blocks and 115 in the cooling blocks (at least 20 each).

suppl1-hippocampal-temperature¶

Blocked (data_missing): the control experiment with simultaneous MS and hippocampal temperature (Figure S1H to K) is not in the dandiset. No file holds a hippocampal temperature (the behaviour modules list only MeasuredTemperature or ModelledTemperature of the septal probe; printed below).

In [62]:
print(sorted(set(k for S in SESS for k in ["MeasuredTemperature" if S["temp_kind"] == "measured" else "ModelledTemperature"])))
print("epoch paradigms in the files:", sorted(set(p for S in SESS if "epochs" in S for p in S["epochs"].behavioral_paradigm)))
print(f"notebook run time {(time.time() - T_START) / 60:.1f} min; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
['MeasuredTemperature', 'ModelledTemperature']
epoch paradigms in the files: ['', 'Homecage_Sleep', 'LinearTrack_AlteringSlopes', 'LinearTrack_EndToEnd', 'ThetaMaze_AlternativeRunning', 'Wheelbox_FreeRunning']
notebook run time 24.3 min; peak memory 4.69 GB

Result: blocked (data_missing). The dandiset holds no hippocampal temperature.

Summary¶

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.

claim outcome
session-structure partially reproduced
cooling-time-course partially reproduced
fig2g-theta-freq-temperature partially reproduced
fig2h-theta-power-temperature reproduced
fig2j-frequency-consistent-across-animals reproduced
fig2i-theta-pre-cooling-post reproduced
disc-theta-frequency-12-percent reproduced
fig6d-errors-increase partially reproduced
fig6e-errors-recover reproduced
fig6c-worst-trials-4-to-8 reproduced
fig6f-errors-temperature partially reproduced
fig6g-errors-theta-frequency partially reproduced
fig6h-errors-theta-power reproduced
fig6i-errors-not-speed not reproduced
suppl5j-errors-best-theta-frequency partially reproduced
fig4e-speed-decreases-within-session reproduced
fig5-speed-control-cooling reproduced
suppl2-place-cell-rates-decrease partially reproduced
suppl2ab-rates-correlated reproduced
disc-interneuron-rates-decrease partially reproduced
suppl5gh-rates-follow-temperature reproduced
fig4b-fp-flfp-decrease reproduced
fig4c-fp-flfp-correlation partially reproduced
fig4ac-fp-flfp-difference-preserved not reproduced
fig4a-frequency-temperature-slopes partially reproduced
fig3c-field-size-correlated not reproduced
fig3d-size-fp-negative partially reproduced
fig3e-model-field-size not reproduced
fig3f-information-unchanged not reproduced
fig3hi-population-vector-unchanged reproduced
fig4d-precession-slope-decrease partially reproduced (assumed)
suppl3e-precession-temperature partially reproduced
fig4f-speed-theta-power reproduced
fig4gh-fp-speed partially reproduced
suppl2e-trial-speed-theta-frequency reproduced
suppl3-theta-cycle-duration partially reproduced
fig5d-ccg-period partially reproduced
fig5e-phase-period-below-2pi reproduced
fig5cg-compression blocked (methods_underspecified)
fig5h-time-lags-increase partially reproduced
fig5i-phase-lags-unchanged reproduced (assumed)
fig5j-fraction-active-unchanged not reproduced
fig5k-spikes-per-cycle-unchanged not reproduced
suppl1g-waveforms-unchanged not reproduced
suppl2d-interneuron-oscillation-slows partially reproduced
suppl1-hippocampal-temperature blocked (data_missing)

The outcomes of the 20 tested claims on place fields and pairs rest on an assumption: fields are found on the map over all trials of an arm, states pooled (the attempt record marks them assumed). The two precession claims also rest on the range of the slope search, and fig4d on the fields whose slope sits at its bound.

How the analysis differs from the paper's:

  • Sessions. The dandiset holds 51 sessions of 5 rats; the paper reports 53. Temperature analyses use the 31 sessions with a measured MS temperature (MS10 has none, MS12 two); the others hold a modelled curve. Place cell analyses use the 23 sessions with typed pyramidal cells; the paper's subsets (21, 19, 18 and 10 sessions) are not named and cannot be matched.
  • Place fields of Figures 3 and 4 were drawn by hand in the paper; here they follow the Figure 5 rule with a peak above 10 Hz, on maps over all trials of an arm. This gives 1223 fields and 878 with an fp in every state, against the paper's 365, and 12834 overlapping pairs against 2948.
  • Cooling onset is the dataset's time stamp; states are the dataset's labels, with the 10 and 12 min readings as variants. Thirteen sessions have a second cooling epoch; aligned series stop at it.
  • Theta is measured on the lab's theta channel; for MS13-171130 that channel is marked bad, and the claims that use theta are also shown without that session. The surface fit of Figure 5 fails on the density under either reading of its equation, also when bounded and started from several points, so fig5cg is blocked.
  • The phase precession slope is searched over plus and minus 2 cycles per field, an assumption; the paper gives no range, and a range of 1 cycle pins about 30% of the slopes at its bound.
  • Spatial information is also shown with equal trial numbers, with equal spike numbers per state and with a shuffle correction of its bias.
  • The tests over pairs (fig5h) and over theta cycles (fig5j, fig5k) that the criteria fix are also shown over sessions, as variants.
  • Waveforms were measured on 4 sessions from short blocks of the wide-band signal, as the dandiset holds none.

What was found about the dataset:

  • Measured MS temperature traces hold artefacts, raw values from -1751 C to 1354 C, in 11 sessions outside 5 to 45 C, with no description of them.
  • The 2018-07-19 sessions (MS21, MS22) are labelled as cooled, but their measured temperature does not fall (minimum 37.4 and 35.2 C); theta frequency falls in one (MS22, 8.68 to 8.27 Hz) and rises in the other (MS21, 7.53 to 8.13 Hz).
  • No hippocampal temperature, unit waveforms or place fields are in the dandiset, and the lab's theta channel of MS13-171130 is marked bad. MS12-170715 has no LFP. Epoch environments name a linear track for some theta maze epochs.
  • 28 sessions hold curated units, 23 of them typed; 23 sessions have none.