Reproducing Zheng et al. (2024) from dandiset 000552¶

Paper: Zheng, Huszár, Hainmueller, Bartos, Williams and Buzsáki (2024), "Perpetual step-like restructuring of hippocampal circuit dynamics", Cell Reports 43, 114702, doi:10.1016/j.celrep.2024.114702. The claims file (claims/zheng-2024.yaml) was written from the author manuscript in PubMed Central (PMC11485410) with the STAR Methods and the supplement of the version of record.

Dataset: DANDI:000552, "High density CA1 recordings on a figure-8 maze" (Huszár et al. 2022), version 0.261113.1035, streamed from the archive.

Why this version. The paper cites 0.230630.2304. That version's units tables hold spike times only: no putative cell type, which the paper's selection of putative pyramidal cells needs for every claim, and no light-responsive label, which the ChR2 claim needs; its trial tables also mark familiar trials as not familiar in at least one session. Version 0.261113.1035 is a re-conversion of the same sessions from the lab's files (its release notes), with the lab's CellExplorer cell types, the light-responsive label built from the paper's criteria, per-environment position and named epochs. The data-check section shows that the spike times of a session are identical in the two versions and that the cited one lacks the labels. The protocol asks for the cited version; it does not hold the variables the claims need, so the later version is pinned and the departure is recorded.

Code read for method details: the paper's code, github.com/samdeoxys1/within-session-representationl-drift at tag v0.0 (commit 93d6e33d813291e0a5a0dcce39a335fc2d8ce13c, Zenodo doi:10.5281/zenodo.13247193).

Claim Tested
fig1d-pv-decorrelation, fig1e-novel-drift-faster, fig1e-later-lags-no-difference tested
fig1h-rate-decorrelates-location-stable, fig1i-location-mse-increases tested
switch-step-size-filter, fig2d-switch-fractions, fig2e-switch-fraction-by-experience tested
fig3df-step-beats-polynomial-fields, fig3df-polynomial-beats-step-population, figs4g-population-vectors-gradual, fig3k-switch-abrupt, figs5-switchers-drive-drift tested
fig4-glm-deviance, fig4-delay-zone-more-switching, fig4-behavior-not-predictive, fig4di-switching-decreases-with-trial, figs8-speed-no-trend, fig4no-head-scans-not-related tested
figs9-splitter-switching, figs13-btsp-signatures tested
fig5c-switchiness-not-intrinsic, fig5d-nrem-rate-relations, multifield-independent-switching, figs12-stability-after-switch-on tested
fig6-co-switching, fig6f-switching-asynchronous, figs14-preexisting-fields-ephys, figs2-chr2-no-effect tested
fig7-preexisting-across-days, figs15-imaging-not-artifact blocked: the imaging data are not deposited
figs1-not-electrode-drift tested on three sessions (e16_3m1_210201, e16_3m1_210203, e13_26m1_211124); the full test, on the 11 sessions with a raw wide-band file, is too large
In [1]:
import os, time, zlib, json, resource
os.environ.setdefault("OMP_NUM_THREADS", "1")
import numpy as np, pandas as pd
from scipy import stats
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import switching as sw
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 30)
T0 = time.time()
print("dandiset", sw.DANDISET, "version", sw.VERSION)
dandiset 000552 version 0.261113.1035

Data¶

The pipeline below reads every session the paper lists that the dandiset holds, and for each maze task computes per-trial rate maps of the putative pyramidal cells, detects place fields against 1000 circular shuffles, merges the turn-common central-arm fields and runs the switch detection (1000 trial permutations per field). It runs in four processes and takes about five minutes. Where each parameter comes from is given in the helper switching.py.

In [2]:
# PIPELINE: place fields and switches for every session (about five minutes with four processes)
have, missing = sw.all_sessions()
print(len(have), "familiar-list sessions in the dandiset; not in it:", missing)
t = time.time()
res = sw.run_all(have)
print(f"pipeline {time.time() - t:.0f} s")
45 familiar-list sessions in the dandiset; not in it: ['e13_26m1_210913']
pipeline 247 s

Data check¶

Counts by subject, session and environment, the units of the variables used, and checks of the metadata against the data: the cell-type labels against the paper's selection rule, the trial table against the position samples, and a clock check of spikes against position (spatial information falls when spikes are shifted in time against position, so they share the position clock). The trial tables' clock against position is shown by the linearised position at each trial's start, which lies in the delay zone for every familiar trial.

In [3]:
# sanity: counts by subject, session and environment; ranges and units of every variable used
rows = []
for r in res:
    u = r["units"]
    for o in r["tasks"]:
        tr = o["trials"]
        rows.append(dict(animal=r["animal"], session=r["session"], env=o["env"], kind=o["kind"],
                         familiar=o["familiar"], used=o["familiar"] or r["session"] in sw.NOVEL_SESSIONS,
                         n_trials_table=len(tr),
                         n_trials_with_frames=int(sum(len(v) for v in o["trial_types"].values())),
                         per_type=dict(tr.trial_type.value_counts()),
                         n_pyr=int((u.putative_cell_type == "Pyramidal Cell").sum()),
                         n_int=int(u.putative_cell_type.str.contains("Interneuron").sum()),
                         n_light=int(u.light_responsive.sum()),
                         n_bins=o["nbins"], lin_max_cm=round(float(o["edges"][-1]), 1),
                         n_fields=len(o["fields"])))
S = pd.DataFrame(rows)
print(S.to_string())
U = S[S.used]
print("\nanimals", U.animal.nunique(), "| familiar tasks", int(U.familiar.sum()), "| novel tasks", int((~U.familiar).sum()),
      "| novel linear-maze tasks", int(((~U.familiar) & (U.kind == "linearMaze")).sum()))
print("familiar sessions with fewer than 50 putative pyramidal cells:",
      U[U.familiar & (U.n_pyr < 50)][["session", "n_pyr"]].values.tolist())
print("tasks (familiar or novel) with fewer than 7 trials in a turn:",
      [(s, e) for s, e, d in zip(U.session, U.env, U.per_type) if min(d.values()) < 7])
print("tasks where the trials table holds trials outside the position samples:",
      U[U.n_trials_table != U.n_trials_with_frames][["session", "env", "n_trials_table", "n_trials_with_frames"]].values.tolist())
beh = pd.concat([o["beh"].assign(session=r["session"], env=o["env"]) for r, o in sw.iter_tasks(res)])
print("\nper-trial mean forward speed (cm/s): range %.1f to %.1f, median %.1f" % (beh.speed.min(), beh.speed.max(), beh.speed.median()))
nr = np.concatenate([r["nrem_rate"][(r["units"].putative_cell_type == "Pyramidal Cell").values] for r in res])
print("NREM rate of pyramidal cells (Hz): median %.2f, range %.3f to %.1f, NaN %d" % (np.nanmedian(nr), np.nanmin(nr), np.nanmax(nr), np.isnan(nr).sum()))
F = [f for r, o in sw.iter_tasks(res) for f in o["fields"]]
w = np.array([f["end"] - f["start"] for f in F]); pk = np.array([f["avg_peak"] for f in F])
print("fields: width (end - start, bins) %d to %d; trial-averaged peak %.2f to %.1f Hz" % (w.min(), w.max(), pk.min(), pk.max()))
# clock check: spikes against position (spatial information with spikes shifted in time)
cc = pd.DataFrame([dict(session=r["session"], env=o["env"], **{f"SI_shift_{k:g}s": v for k, v in o["clock_check"].items()})
                   for r, o in sw.iter_tasks(res)])
print("\nmean spatial information (bits/spike) of pyramidal cells, spikes shifted against position:")
print(cc.round(3).to_string())
print("tasks where the unshifted value is not the largest:", int((cc.iloc[:, 2:].idxmax(axis=1) != "SI_shift_0s").sum()))
# trial table against position: linearised position at each trial's start
st = []
for r, o in sw.iter_tasks(res):
    if o["familiar"]:
        ft = o["frame_trial"]
        for i in range(len(o["trials"])):
            m = np.nonzero(ft == i)[0]
            if len(m):
                st.append(float(o["lin"][m[0]]))
st = np.array(st)
print("familiar figure-8 trials: linearised position at trial start, %d trials; in the delay zone (0 to 15 or above 202 cm): %d" % (len(st), ((st < 15) | (st > 202)).sum()))
print("tasks where the 5-s and 30-s shifts both lower the value:", int(((cc.SI_shift_5s < cc.SI_shift_0s) & (cc.SI_shift_30s < cc.SI_shift_0s)).sum()), "of", len(cc))
lin_dir = []
for r in res:
    for o in r["tasks"]:
        if o["kind"] == "linearMaze":
            lin_dir.append(pd.crosstab(o["trials"].visited_arm, o["trials"].trial_type))
print("linear mazes, visited_arm against running direction from position (pos = toward higher position):\n", sum(lin_dir).to_string())
# units of x and y per environment, as the files give them (speeds use the linearised position, in cm)
xyu = pd.DataFrame([dict(env=o["env"], xy_unit=o["xy_unit"], description=(o["xy_desc"] or "")[-110:]) for r, o in sw.iter_tasks(res)])
print("\nx and y units by environment (tasks):")
print(xyu.groupby(["env", "xy_unit"]).size().to_string())
for env, g in xyu[xyu.xy_unit != "centimeters"].groupby("env"):
    print(f"   {env}, end of a description: ...{g.description.iloc[0]}")
      animal          session             env         kind  familiar  used  n_trials_table  n_trials_with_frames                   per_type  n_pyr  n_int  n_light  n_bins  lin_max_cm  n_fields
0   e13_16f1  e13_16f1_210302   figure-8 maze  alternation      True  True              22                    22   {'left': 15, 'right': 7}    114     21       12     100       221.9       314
1   e13_16f1  e13_16f1_210312   figure-8 maze  alternation      True  True              21                    21  {'left': 11, 'right': 10}    105     19       12     100       221.6       214
2   e13_16f1  e13_16f1_210314   figure-8 maze  alternation      True  True              25                    25  {'left': 14, 'right': 11}    102     19       10     100       221.7       234
3   e13_16f1  e13_16f1_210317   figure-8 maze  alternation      True  True              25                    25  {'left': 14, 'right': 11}    112     18       10     100       222.0       248
4   e13_16f1  e13_16f1_210319   figure-8 maze  alternation      True  True              26                    26  {'left': 16, 'right': 10}     95     25        8     100       222.0       203
5   e13_16f1  e13_16f1_210322   figure-8 maze  alternation      True  True              25                    25  {'left': 15, 'right': 10}     87     17       10     100       222.0       224
6   e13_16f1  e13_16f1_210328   figure-8 maze  alternation      True  True              21                    21  {'left': 11, 'right': 10}    174     37       27     100       222.0       413
7   e13_16f1  e13_16f1_210331   figure-8 maze  alternation      True  True              22                    22  {'left': 12, 'right': 10}    132     22       24     100       222.0       367
8   e13_26m1  e13_26m1_211019  tmaze_familiar  alternation      True  True              47                    47  {'left': 27, 'right': 20}    228     43        4     100       221.9       457
9   e13_26m1  e13_26m1_211019   tmaze_ipshita  alternation     False  True              33                    33  {'left': 21, 'right': 12}    228     43        4      77       170.0       354
10  e13_26m1  e13_26m1_211116  tmaze_familiar  alternation      True  True              21                    21  {'left': 11, 'right': 10}    173     36       12     100       221.9       339
11  e13_26m1  e13_26m1_211116   linear_thomas   linearMaze     False  True               9                     9       {'neg': 5, 'pos': 4}    173     36       12      45       100.0       135
12  e13_26m1  e13_26m1_211119  tmaze_familiar  alternation      True  True              25                    25  {'left': 13, 'right': 12}    158     33       16     100       221.9       322
13  e13_26m1  e13_26m1_211119     linear_manu   linearMaze     False  True              58                    58     {'pos': 29, 'neg': 29}    158     33       16      49       110.0       163
14  e13_26m1  e13_26m1_211124  tmaze_familiar  alternation      True  True              26                    26  {'right': 13, 'left': 13}    153     29        8     100       221.9       282
15   e14_2m2   e14_2m2_201017   figure-8 maze  alternation      True  True              21                    21   {'right': 12, 'left': 9}     67     19        2     100       222.0       188
16   e14_2m2   e14_2m2_201019   figure-8 maze  alternation      True  True              21                    21  {'right': 11, 'left': 10}     98     15        2     100       222.0       227
17   e14_2m3   e14_2m3_201118   figure-8 maze  alternation      True  True              24                    24  {'left': 14, 'right': 10}     39     15        4     100       222.0       113
18   e14_2m3   e14_2m3_201121   figure-8 maze  alternation      True  True              22                    22  {'left': 12, 'right': 10}     40     16        4     100       221.9       113
19   e14_2m3   e14_2m3_201125   figure-8 maze  alternation      True  True              22                    22  {'left': 12, 'right': 10}     57     17       20     100       222.0       153
20   e14_2m3   e14_2m3_201129   figure-8 maze  alternation      True  True              25                    25  {'left': 15, 'right': 10}     57     15       11     100       222.0       146
21   e14_2m3   e14_2m3_201206   figure-8 maze  alternation      True  True              32                    32  {'left': 17, 'right': 15}     52     11        8     100       222.0       149
22   e14_2m3   e14_2m3_201208   figure-8 maze  alternation      True  True              39                    39  {'left': 22, 'right': 17}     52     11       10     100       222.0       151
23  e15_10m1  e15_10m1_200727   figure-8 maze  alternation      True  True              27                    27  {'left': 16, 'right': 11}     70     27       11     100       221.9       134
24  e15_10m1  e15_10m1_200803   figure-8 maze  alternation      True  True              21                    21  {'left': 11, 'right': 10}     47     28        4     100       222.0       114
25  e15_10m1  e15_10m1_200809   figure-8 maze  alternation      True  True              21                    21   {'left': 12, 'right': 9}    103     23       13     100       222.0       192
26  e15_10m1  e15_10m1_200812   figure-8 maze  alternation      True  True              22                    22   {'left': 13, 'right': 9}    102     23       12     100       222.0       190
27  e15_13f1  e15_13f1_220117  tmaze_familiar  alternation      True  True              32                    32  {'left': 20, 'right': 12}    333     43       11     100       221.9       633
28  e15_13f1  e15_13f1_220118  tmaze_familiar  alternation      True  True              25                    25  {'left': 15, 'right': 10}    318     45       11     100       221.9       663
29  e15_13f1  e15_13f1_220118     linear_manu   linearMaze     False  True              68                    68     {'pos': 34, 'neg': 34}    318     45       11      49       110.0       391
30  e15_13f1  e15_13f1_220119  tmaze_familiar  alternation      True  True              29                    29  {'left': 19, 'right': 10}    288     55       10     100       221.9       618
31  e15_13f1  e15_13f1_220119   tmaze_ipshita  alternation     False  True              32                    32  {'left': 19, 'right': 13}    288     55       10      77       170.0       514
32  e15_13f1  e15_13f1_220120  tmaze_familiar  alternation      True  True              46                    46  {'left': 27, 'right': 19}    248     54       21     100       221.9       526
33  e15_13f1  e15_13f1_220120   linear_thomas   linearMaze     False  True              49                    49     {'neg': 25, 'pos': 24}    248     54       21      45       100.0       256
34   e15_9f1   e15_9f1_200715   figure-8 maze  alternation      True  True              21                    21   {'left': 14, 'right': 7}     42     27        4     100       222.0       103
35   e15_9f1   e15_9f1_200720   figure-8 maze  alternation      True  True              30                    30  {'left': 18, 'right': 12}     49     21        5     100       222.0       152
36   e15_9f1   e15_9f1_200723   figure-8 maze  alternation      True  True              22                    22  {'left': 12, 'right': 10}     62     22        7     100       222.0       155
37   e15_9f1   e15_9f1_200729   figure-8 maze  alternation      True  True              28                    28  {'left': 15, 'right': 13}     98     20       16     100       222.0       254
38   e15_9f1   e15_9f1_200802   figure-8 maze  alternation      True  True              28                    28  {'left': 17, 'right': 11}     51     21       11     100       222.0       127
39   e16_1f1   e16_1f1_200918   figure-8 maze  alternation      True  True              26                    26   {'left': 17, 'right': 9}     52     11        1     100       222.0        73
40   e16_1f1   e16_1f1_200919   figure-8 maze  alternation      True  True              29                    29   {'left': 21, 'right': 8}     52     13        7     100       222.0        73
41   e16_1f1   e16_1f1_200920   figure-8 maze  alternation      True  True              22                    22   {'left': 13, 'right': 9}     62     14        9     100       222.0       129
42   e16_1f1   e16_1f1_200923   figure-8 maze  alternation      True  True              22                    22   {'left': 13, 'right': 9}     50     15        7     100       222.0        94
43   e16_1f1   e16_1f1_201004   figure-8 maze  alternation      True  True              24                    24   {'left': 15, 'right': 9}     66     15        6     100       222.0       122
44   e16_2m1   e16_2m1_201121   figure-8 maze  alternation      True  True              22                    22   {'right': 13, 'left': 9}     48     12        6     100       221.7       126
45   e16_3m1   e16_3m1_210119   figure-8 maze  alternation      True  True              26                    26  {'right': 14, 'left': 12}    121     24       12     100       221.8       307
46   e16_3m1   e16_3m1_210201   figure-8 maze  alternation      True  True              30                    30  {'right': 15, 'left': 15}    144     23       12     100       221.8       278
47   e16_3m1   e16_3m1_210203   figure-8 maze  alternation      True  True              22                    22  {'left': 12, 'right': 10}    160     22        4     100       221.9       327
48   e16_3m2   e16_3m2_211210  tmaze_familiar  alternation      True  True              23                    23  {'right': 12, 'left': 11}    159     36       13     100       221.9       308
49   e16_3m2   e16_3m2_211212  tmaze_familiar  alternation      True  True              29                    29  {'right': 16, 'left': 13}    162     38       13     100       221.9       340
50   e16_3m2   e16_3m2_211212   linear_thomas   linearMaze     False  True              34                    34     {'neg': 17, 'pos': 17}    162     38       13      45       100.0       149
51   e16_3m2   e16_3m2_211213  tmaze_familiar  alternation      True  True              27                    27  {'right': 17, 'left': 10}    163     44       27     100       221.9       351
52   e16_3m2   e16_3m2_211213   tmaze_ipshita  alternation     False  True              29                    29  {'left': 16, 'right': 13}    163     44       27      77       170.0       272

animals 11 | familiar tasks 45 | novel tasks 8 | novel linear-maze tasks 5
familiar sessions with fewer than 50 putative pyramidal cells: [['e14_2m3_201118', 39], ['e14_2m3_201121', 40], ['e15_10m1_200803', 47], ['e15_9f1_200715', 42], ['e15_9f1_200720', 49], ['e16_2m1_201121', 48]]
tasks (familiar or novel) with fewer than 7 trials in a turn: [('e13_26m1_211116', 'linear_thomas')]
tasks where the trials table holds trials outside the position samples: []

per-trial mean forward speed (cm/s): range 1.0 to 25.1, median 8.4
NREM rate of pyramidal cells (Hz): median 0.82, range 0.038 to 26.2, NaN 0
fields: width (end - start, bins) 4 to 34; trial-averaged peak 1.00 to 50.2 Hz

mean spatial information (bits/spike) of pyramidal cells, spikes shifted against position:
            session             env  SI_shift_0s  SI_shift_1s  SI_shift_5s  SI_shift_30s
0   e13_16f1_210302   figure-8 maze        0.608        0.483        0.300         0.143
1   e13_16f1_210312   figure-8 maze        0.794        0.614        0.504         0.309
2   e13_16f1_210314   figure-8 maze        0.760        0.568        0.399         0.276
3   e13_16f1_210317   figure-8 maze        0.780        0.673        0.472         0.359
4   e13_16f1_210319   figure-8 maze        0.711        0.619        0.406         0.287
5   e13_16f1_210322   figure-8 maze        0.679        0.512        0.334         0.196
6   e13_16f1_210328   figure-8 maze        0.816        0.652        0.477         0.323
7   e13_16f1_210331   figure-8 maze        0.834        0.664        0.477         0.299
8   e13_26m1_211019  tmaze_familiar        0.890        0.743        0.498         0.296
9   e13_26m1_211019   tmaze_ipshita        0.644        0.624        0.399         0.204
10  e13_26m1_211116  tmaze_familiar        0.969        0.824        0.604         0.419
11  e13_26m1_211116   linear_thomas        0.655        0.593        0.535         0.379
12  e13_26m1_211119  tmaze_familiar        1.021        0.895        0.550         0.337
13  e13_26m1_211119     linear_manu        0.569        0.528        0.281         0.193
14  e13_26m1_211124  tmaze_familiar        0.999        0.871        0.634         0.416
15   e14_2m2_201017   figure-8 maze        0.754        0.747        0.568         0.379
16   e14_2m2_201019   figure-8 maze        0.537        0.427        0.293         0.242
17   e14_2m3_201118   figure-8 maze        0.480        0.288        0.204         0.118
18   e14_2m3_201121   figure-8 maze        0.941        0.730        0.325         0.225
19   e14_2m3_201125   figure-8 maze        0.738        0.548        0.377         0.239
20   e14_2m3_201129   figure-8 maze        0.606        0.459        0.363         0.200
21   e14_2m3_201206   figure-8 maze        0.743        0.574        0.317         0.178
22   e14_2m3_201208   figure-8 maze        0.717        0.592        0.375         0.185
23  e15_10m1_200727   figure-8 maze        0.826        0.611        0.423         0.190
24  e15_10m1_200803   figure-8 maze        0.626        0.455        0.323         0.188
25  e15_10m1_200809   figure-8 maze        0.806        0.651        0.400         0.316
26  e15_10m1_200812   figure-8 maze        0.760        0.549        0.436         0.297
27  e15_13f1_220117  tmaze_familiar        1.125        0.930        0.631         0.321
28  e15_13f1_220118  tmaze_familiar        1.178        0.986        0.726         0.413
29  e15_13f1_220118     linear_manu        0.823        0.706        0.403         0.362
30  e15_13f1_220119  tmaze_familiar        1.221        0.945        0.612         0.417
31  e15_13f1_220119   tmaze_ipshita        0.995        0.749        0.514         0.299
32  e15_13f1_220120  tmaze_familiar        1.234        0.987        0.663         0.295
33  e15_13f1_220120   linear_thomas        0.651        0.551        0.365         0.224
34   e15_9f1_200715   figure-8 maze        0.988        0.866        0.546         0.251
35   e15_9f1_200720   figure-8 maze        0.776        0.588        0.375         0.195
36   e15_9f1_200723   figure-8 maze        0.870        0.695        0.454         0.293
37   e15_9f1_200729   figure-8 maze        0.764        0.649        0.384         0.295
38   e15_9f1_200802   figure-8 maze        0.697        0.548        0.335         0.130
39   e16_1f1_200918   figure-8 maze        0.921        0.767        0.511         0.333
40   e16_1f1_200919   figure-8 maze        0.878        0.833        0.583         0.298
41   e16_1f1_200920   figure-8 maze        0.776        0.610        0.410         0.278
42   e16_1f1_200923   figure-8 maze        0.867        0.684        0.444         0.295
43   e16_1f1_201004   figure-8 maze        0.856        0.742        0.467         0.346
44   e16_2m1_201121   figure-8 maze        0.728        0.627        0.417         0.212
45   e16_3m1_210119   figure-8 maze        0.747        0.657        0.461         0.330
46   e16_3m1_210201   figure-8 maze        1.029        0.858        0.616         0.412
47   e16_3m1_210203   figure-8 maze        0.991        0.847        0.671         0.465
48   e16_3m2_211210  tmaze_familiar        0.976        0.925        0.709         0.384
49   e16_3m2_211212  tmaze_familiar        1.060        0.913        0.691         0.378
50   e16_3m2_211212   linear_thomas        0.513        0.525        0.303         0.196
51   e16_3m2_211213  tmaze_familiar        0.950        0.834        0.560         0.438
52   e16_3m2_211213   tmaze_ipshita        0.674        0.554        0.369         0.280
tasks where the unshifted value is not the largest: 1
familiar figure-8 trials: linearised position at trial start, 1166 trials; in the delay zone (0 to 15 or above 202 cm): 1166
tasks where the 5-s and 30-s shifts both lower the value: 53 of 53
linear mazes, visited_arm against running direction from position (pos = toward higher position):
 trial_type   neg  pos
visited_arm          
left           0  108
right        110    0

x and y units by environment (tasks):
env             xy_unit    
figure-8 maze   centimeters    34
linear_manu     n.a.            2
linear_thomas   n.a.            3
tmaze_familiar  centimeters    11
tmaze_ipshita   n.a.            3
   linear_manu, end of a description: ... the lab's Behavior.mat, in the lab's units: x 0.01 to 0.20, y 0.00 to 1.00, with no scale given in the source
   linear_thomas, end of a description: ... the lab's Behavior.mat, in the lab's units: x 0.26 to 0.89, y 0.04 to 0.77, with no scale given in the source
   tmaze_ipshita, end of a description: ... the lab's Behavior.mat, in the lab's units: x 0.01 to 0.73, y 0.06 to 0.98, with no scale given in the source

The paper cites version 0.230630.2304. The cell below compares it with the pinned version on one session: the spike times are the same, but the cited version has no cell-type or light-responsive labels and marks 28 of this session's 30 familiar trials as not familiar.

In [4]:
# sanity: the version the paper cites (0.230630.2304) against the pinned one, for one session
import h5py as _h5, remfile as _rf, requests as _rq, pynwb as _pn
def _open_version(path, version):
    a = _rq.get(f"{sw.API}/dandisets/{sw.DANDISET}/versions/{version}/assets/", params={"path": path}, timeout=60).json()["results"][0]
    url = _rq.head(f"{sw.API}/assets/{a['asset_id']}/download/", allow_redirects=True, timeout=60).url
    return _pn.NWBHDF5IO(file=_h5.File(_rf.File(url), "r"), load_namespaces=True).read()
p_ = sw.session_path("e16_3m1_210201")
old, new = _open_version(p_, "0.230630.2304"), _open_version(p_, sw.VERSION)
for name, n_ in (("0.230630.2304", old), (sw.VERSION, new)):
    tr_ = n_.trials.to_dataframe()
    print(name, "| units", len(n_.units), "| unit columns", list(n_.units.colnames), "| trials", len(tr_),
          "| is_familiar_maze True", int(tr_.is_familiar_maze.sum()), "| visited_arm", tr_.visited_arm.value_counts().to_dict())
st_old = np.sort(np.concatenate([old.units["spike_times"][i] for i in range(len(old.units))]))
st_new = np.sort(new.units["spike_times"].target.data[:])
print("all spike times identical between versions:", len(st_old) == len(st_new) and bool(np.allclose(st_old, st_new)))
0.230630.2304 | units 167 | unit columns ['spike_times', 'unit_name', 'clu_id', 'group_id'] | trials 30 | is_familiar_maze True 2 | visited_arm {'left': 15, 'right': 15}
0.261113.1035 | units 167 | unit columns ['unit_name', 'cluster_id', 'shank_id', 'max_electrode', 'putative_cell_type', 'trough_to_peak', 'acg_tau_rise', 'firing_rate', 'opto_p_salt', 'opto_h_reliable', 'opto_int_ratemod', 'opto_int_ratemod_pval', 'light_responsive', 'spike_times', 'electrodes', 'electrode_group', 'waveform_mean'] | trials 30 | is_familiar_maze True 30 | visited_arm {'right': 15, 'left': 15}
all spike times identical between versions: True

What the checks show:

  • 45 of the paper's 46 familiar sessions are in the dandiset; e13_26m1_210913 is not. All 8 novel sessions are there (3 on a second figure-8 maze, tmaze_ipshita, and 5 on linear mazes).
  • The paper requires 50 putative pyramidal cells per session; under the files' CellExplorer labels six of its familiar sessions have fewer (39 to 49). They are kept, as the paper's list includes them.
  • Every trial in the trial tables of the analysed tasks falls inside the position samples, and every familiar trial starts in the delay zone of the linearised track.
  • The mean spatial information of the pyramidal cells is largest with the spike times as they are in 52 of 53 tasks, and falls when spikes are shifted against position by 5 or 30 s in all 53. In e16_3m2_211212 (linear maze) a 1-s shift gives a slightly higher value (0.525 against 0.513), so an offset of up to about a second could not be ruled out there; the 5-s and 30-s shifts fall (0.303, 0.196).
  • On the linear mazes the files' visited_arm codes running direction: in every trial right runs toward lower linearised position and left toward higher. Direction is taken here from the position.
  • The x and y of the novel figure-8 maze carry no scale: their unit is n.a. and the description says "with no scale given in the source" (printed above); speeds and forward locomotion use the linearised position, in cm, in every environment.
  • Per-trial mean forward speed is 1.0 to 25.1 cm/s; NREM rates of pyramidal cells 0.038 to 26.2 Hz.
  • One task has fewer than 7 trials in a turn: the novel linear maze of e13_26m1_211116 (9 trials), which the co-switching test leaves out as the paper does.
  • The wide-band files of e16_3m1_210201, e16_3m1_210203 and e13_26m1_211124 share the clock of the spike times: the raw signal averaged at each unit's spike times shows its waveform (median peak-to-trough 143.5 to 151.3 uV), which falls to 25.5 to 27.4 uV with the spikes shifted by 0.5 s (figs1-not-electrode-drift). Every unit's largest-waveform electrode lies in its own shank's electrode group (167 of 167, 182 of 182 and 182 of 182).

Claims¶

fig1d-pv-decorrelation¶

The correlation between population vectors of place cells decreases with the lag between trials, in both familiar and novel environments (within-session drift).

Paper (Results, Within-session representational drift, paragraph 1; Figure 1C and 1D): "The correlation decreased as a function of the lag between trials, suggesting drift within both the familiar and the novel environment"

Units are session by turn (figure-8) or running direction (linear maze). Place cells are the pyramidal cells with a field in that turn or a merged central-arm field. The criterion gives the rest.

In [5]:
# claim:fig1d-pv-decorrelation, fig1e-novel-drift-faster, fig1e-later-lags-no-difference
pv_rows, pv_pairs = [], {}
for r, o in sw.iter_tasks(res):
    for tt, tidx in o["trial_types"].items():
        cells = sw.place_cells(o, tt)
        if len(cells) < 2 or len(tidx) < 3:
            continue
        lags, c = sw.pv_corr(o["maps"][tt], cells)
        pv_pairs[(r["session"], o["env"], tt)] = (lags, c)
        d = dict(session=r["session"], animal=r["animal"], env=o["env"], familiar=o["familiar"], turn=tt,
                 n_trials=len(tidx), n_place_cells=len(cells))
        for lo, hi in [(1, 10), (11, 20), (21, 30)]:
            d[f"slope_{lo}_{hi}"] = sw.lag_slope(lags, c, lo, hi)
        pv_rows.append(d)
PV = pd.DataFrame(pv_rows)
print("session and turn units:", len(PV), "| familiar", int(PV.familiar.sum()), "| novel", int((~PV.familiar).sum()))
print("place cells per unit: %d to %d" % (PV.n_place_cells.min(), PV.n_place_cells.max()))
allc = np.concatenate([v[1] for v in pv_pairs.values()])
print("PV correlations range %.3f to %.3f" % (np.nanmin(allc), np.nanmax(allc)))
# mean correlation per lag, familiar and novel
for fam in (True, False):
    keys = [k for k in pv_pairs if PV.set_index(["session", "env", "turn"]).loc[k, "familiar"] == fam]
    lg = np.concatenate([pv_pairs[k][0] for k in keys]); cc = np.concatenate([pv_pairs[k][1] for k in keys])
    m = pd.Series(cc).groupby(lg).agg(["mean", "count"])
    print("familiar" if fam else "novel", "mean PV correlation at lags 1, 5, 10, 20:",
          [round(m["mean"].get(l, np.nan), 3) for l in (1, 5, 10, 20)])
print()
for fam, g in PV.groupby("familiar"):
    s = g.slope_1_10.dropna().astype(float)
    w = stats.wilcoxon(s)
    print("familiar" if fam else "novel", f"lags 1-10: n = {len(s)}, median slope = {s.median():.4f}, negative {int((s < 0).sum())}/{len(s)}, Wilcoxon signed-rank p = {w.pvalue:.2g}")
print("\nby animal (familiar, lags 1-10): median slope and n")
print(PV[PV.familiar].groupby("animal").slope_1_10.agg(["median", "count"]).round(4).to_string())
session and turn units: 106 | familiar 90 | novel 16
place cells per unit: 19 to 236
PV correlations range -0.014 to 0.911
familiar mean PV correlation at lags 1, 5, 10, 20: [np.float64(0.71), np.float64(0.639), np.float64(0.572), np.float64(0.489)]
novel mean PV correlation at lags 1, 5, 10, 20: [np.float64(0.696), np.float64(0.583), np.float64(0.505), np.float64(0.42)]

novel lags 1-10: n = 14, median slope = -0.0252, negative 14/14, Wilcoxon signed-rank p = 0.00012
familiar lags 1-10: n = 90, median slope = -0.0170, negative 90/90, Wilcoxon signed-rank p = 1.7e-16

by animal (familiar, lags 1-10): median slope and n
          median  count
animal                 
e13_16f1 -0.0205     16
e13_26m1 -0.0232      8
e14_2m2  -0.0217      4
e14_2m3  -0.0138     12
e15_10m1 -0.0163      8
e15_13f1 -0.0146      8
e15_9f1  -0.0154     10
e16_1f1  -0.0173     10
e16_2m1  -0.0146      2
e16_3m1  -0.0167      6
e16_3m2  -0.0199      6

Result: Reproduced. All 90 familiar units and all 14 novel units with at least five lags have a negative slope over lags 1 to 10 (median -0.0170 and -0.0252 per lag), Wilcoxon signed-rank p = 1.7e-16 and p = 0.00012. Mean PV correlation falls from 0.71 at lag 1 to 0.57 at lag 10 in familiar units and from 0.70 to 0.51 in novel ones, and the slope is negative in every animal.

fig1e-novel-drift-faster¶

Over trial lags 1 to 10, population vectors decorrelate faster (a more negative slope) in novel than in familiar environments.

Paper (Results, Within-session representational drift, paragraph 1; Figure 1E): "Linear regression revealed that drift was significantly faster in novel environments (larger negative slope) within the first 1-10 trial lags"

Slopes from the previous section. Units need at least five lags in the window (code). Cohen's d is familiar minus novel, so a more negative novel slope gives a positive d.

In [6]:
# claim:fig1e-novel-drift-faster, fig1e-later-lags-no-difference
fig1e = {}
for lo, hi in [(1, 10), (11, 20), (21, 30)]:
    col = f"slope_{lo}_{hi}"
    a = PV[PV.familiar][col].dropna().astype(float); b = PV[~PV.familiar][col].dropna().astype(float)
    if len(a) and len(b):
        p = stats.ranksums(a, b).pvalue
        d = sw.cohen_d(a, b)  # familiar minus novel: positive when novel slopes are more negative
    else:
        p, d = np.nan, np.nan
    fig1e[(lo, hi)] = dict(n=len(a) + len(b), n_fam=len(a), n_nov=len(b), med_fam=a.median(), med_nov=b.median(), p=p, d=d)
    print(f"lags {lo}-{hi}: n = {len(a) + len(b)} ({len(a)} familiar, {len(b)} novel); median slope familiar {a.median():.4f}, novel {b.median():.4f}; rank-sum p = {p:.3g}; Cohen's d (familiar - novel) = {d:.2f}")
# variant: lags 1-10 by session (turns averaged) to remove the pairing of turns
g = PV.groupby(["session", "env", "familiar"]).slope_1_10.mean().reset_index()
a, b = g[g.familiar].slope_1_10.dropna(), g[~g.familiar].slope_1_10.dropna()
print(f"variant, turns averaged per session: {len(a)} familiar, {len(b)} novel, rank-sum p = {stats.ranksums(a, b).pvalue:.3g}, d = {sw.cohen_d(a, b):.2f}")
lags 1-10: n = 104 (90 familiar, 14 novel); median slope familiar -0.0170, novel -0.0252; rank-sum p = 0.0148; Cohen's d (familiar - novel) = 0.51
lags 11-20: n = 28 (17 familiar, 11 novel); median slope familiar -0.0144, novel -0.0133; rank-sum p = 0.76; Cohen's d (familiar - novel) = 0.03
lags 21-30: n = 6 (2 familiar, 4 novel); median slope familiar -0.0361, novel -0.0140; rank-sum p = 0.0641; Cohen's d (familiar - novel) = -2.87
variant, turns averaged per session: 45 familiar, 7 novel, rank-sum p = 0.0587, d = 0.69

Result: Reproduced. Over lags 1 to 10, novel slopes are more negative (median -0.0252 against -0.0170), rank-sum p = 0.0148, with 104 units (expected 106, within tolerance). Cohen's d is 0.51, just outside the expected 0.58 +- 0.058; the criterion reports d without requiring it. With the two turns of a session averaged (45 familiar, 7 novel), p = 0.0587 and d = 0.69.

fig1e-later-lags-no-difference¶

Over trial lags 11 to 20 and 21 to 30 no significant difference in decorrelation slope between novel and familiar environments was detected.

Paper (Results, Within-session representational drift, paragraph 1; Figure 1E): "we failed to detect a significant difference between novel and familiar environments over a range of 11-20 or 21-30 trial lags"

A claim of absence, judged on the rank-sum test of the previous cell.

The cell of the previous section prints the numbers for this claim.

Result: Reproduced. Neither later window differs: lags 11 to 20, 28 units (17 familiar, 11 novel), p = 0.76, d = 0.03; lags 21 to 30, 6 units (2 and 4), p = 0.0641, d = -2.87. The paper had 26 and 8 units. With 2 familiar units the last window has almost no power, and its effect size is large.

fig1h-rate-decorrelates-location-stable¶

The vector of within-field peak firing rates of all place fields decorrelates with trial lag, whereas the vector of field peak locations stays correlated.

Paper (Results, Within-session representational drift, paragraph 2; Figure 1G and 1H): "We found the vector of the peak firing rate of all place fields decorrelated as a function of trial lag, whereas the vector of the field locations remained stable"

Each field is a series over its turn's trials. Merged turn-common fields are split back into their two turn parts. Vectors at within-turn trial index k join both turns, up to the shorter turn's trial count (code get_plot_pf_param_population_corr_vs_lag).

In [7]:
# claim:fig1h-rate-decorrelates-location-stable, fig1i-location-mse-increases
h_rows, h_lag = [], []
for r, o in sw.iter_tasks(res):
    parts = sw.split_parts(o["fields"])
    types = list(o["trial_types"])
    nmin = min(len(o["trial_types"][t]) for t in types)
    if nmin < 3 or len(parts) < 3:
        continue
    # vectors over fields at within-turn trial index k, turns concatenated (code get_plot_pf_param_population_corr_vs_lag)
    R = np.array([f["rate"][:nmin] for f in parts])
    Lc = np.array([f["loc"][:nmin] for f in parts])
    i, j = np.triu_indices(nmin, 1)
    lags = j - i
    cr = np.array([stats.pearsonr(R[:, a], R[:, b])[0] for a, b in zip(i, j)])
    cl = np.array([stats.pearsonr(Lc[:, a], Lc[:, b])[0] for a, b in zip(i, j)])
    mse = np.array([np.mean((Lc[:, a] - Lc[:, b]) ** 2) for a, b in zip(i, j)])
    h_rows.append(dict(session=r["session"], env=o["env"], familiar=o["familiar"], n_fields=len(parts), n_k=nmin,
                       slope_rate=sw.lag_slope(lags, cr, 1, 10), slope_loc=sw.lag_slope(lags, cl, 1, 10),
                       slope_mse=sw.lag_slope(lags, mse, 1, 10),
                       rate_lag1=cr[lags == 1].mean(), loc_lag1=cl[lags == 1].mean()))
    for l in np.unique(lags):
        h_lag.append(dict(session=r["session"], env=o["env"], familiar=o["familiar"], lag=l,
                          rate=cr[lags == l].mean(), loc=cl[lags == l].mean(), mse=mse[lags == l].mean()))
H = pd.DataFrame(h_rows); HL = pd.DataFrame(h_lag)
# main: the criterion's slope of the per-lag averages on lag (lags 1 to 10, at least five lags);
# variant: the slope over all trial pairs (the first version of this notebook)
for col in ("rate", "loc", "mse"):
    H[f"lagavg_{col}"] = [sw.lag_slope(g.lag.values, g[col].values, 1, 10) for _, g in HL.groupby(["session", "env"], sort=False)]
print("units (session and environment):", len(H), "| fields per unit %d to %d" % (H.n_fields.min(), H.n_fields.max()))
print("mean correlation at lag 1: rate %.3f, location %.3f" % (H.rate_lag1.mean(), H.loc_lag1.mean()))
print(HL.groupby("lag")[["rate", "loc", "mse"]].mean().loc[[1, 2, 5, 10, 15, 20]].round(3).to_string())
for lab, cr_, cl_ in (("per-lag averages (main)", "lagavg_rate", "lagavg_loc"), ("variant, all trial pairs", "slope_rate", "slope_loc")):
    print(lab + ":")
    for col in (cr_, cl_):
        s = H[col].dropna().astype(float)
        print(f"   {col}: n = {len(s)}, median {s.median():.5f}, negative {int((s < 0).sum())}/{len(s)}, Wilcoxon p = {stats.wilcoxon(s).pvalue:.2g}")
        for fam, g in H.groupby("familiar"):
            s2 = g[col].dropna().astype(float)
            print("      ", "familiar" if fam else "novel", f"n = {len(s2)}, median {s2.median():.5f}, Wilcoxon p = {stats.wilcoxon(s2).pvalue:.2g}")
    mr, ml = H[cr_].dropna().median(), H[cl_].dropna().median()
    print(f"   ratio of median slopes, rate / location = {mr / ml:.2f}")
units (session and environment): 53 | fields per unit 79 to 711
mean correlation at lag 1: rate 0.681, location 0.984
      rate    loc     mse
lag                      
1    0.681  0.984  19.962
2    0.642  0.983  20.983
5    0.567  0.983  22.582
10   0.433  0.975  26.128
15   0.414  0.946  32.990
20   0.358  0.915  35.267
per-lag averages (main):
   lagavg_rate: n = 52, median -0.02927, negative 52/52, Wilcoxon p = 3.5e-10
       novel n = 7, median -0.02833, Wilcoxon p = 0.016
       familiar n = 45, median -0.03013, Wilcoxon p = 5.7e-14
   lagavg_loc: n = 52, median -0.00037, negative 50/52, Wilcoxon p = 7e-10
       novel n = 7, median -0.00114, Wilcoxon p = 0.016
       familiar n = 45, median -0.00034, Wilcoxon p = 4e-12
   ratio of median slopes, rate / location = 80.04
variant, all trial pairs:
   slope_rate: n = 52, median -0.02976, negative 52/52, Wilcoxon p = 3.5e-10
       novel n = 7, median -0.02847, Wilcoxon p = 0.016
       familiar n = 45, median -0.02998, Wilcoxon p = 5.7e-14
   slope_loc: n = 52, median -0.00036, negative 51/52, Wilcoxon p = 3.7e-10
       novel n = 7, median -0.00101, Wilcoxon p = 0.016
       familiar n = 45, median -0.00033, Wilcoxon p = 1.1e-13
   ratio of median slopes, rate / location = 83.35

Result: Reproduced. In 53 session and environment units (fields per unit 79 to 711), 52 of which have at least five lags, the slope of the per-lag mean peak-rate correlation on lag 1 to 10 (the criterion's averaging) is negative in 52 of 52, median -0.0293 per lag, Wilcoxon p = 3.5e-10. The location correlation is 0.984 at lag 1 and 0.975 at lag 10, with a median slope of -0.00037, so the peak-rate slope is 80 times steeper (the criterion asks for at least 2). Fitted over all trial pairs, the medians are -0.0298 and -0.00036 (ratio 83). The location slopes are also below zero (50 of 52 negative, p = 7e-10), which the next claim takes up.

fig1i-location-mse-increases¶

The mean squared distance between field-location vectors still increases significantly with trial lag, so field locations do change.

Paper (Results, Within-session representational drift, paragraph 2; Figure 1I): "In fact, the average squared Euclidean distance as a function of trial lag increased significantly"

Squared distance between location vectors divided by the number of fields (bins squared), per lag.

In [8]:
# claim:fig1i-location-mse-increases
for lab, col in (("per-lag averages", "lagavg_mse"), ("variant, all trial pairs", "slope_mse")):
    s = H[col].dropna().astype(float)
    print(f"(a) per-unit slope of MSE on lag (lags 1-10), {lab}: n = {len(s)}, median {s.median():.4f} bins^2/lag, positive {int((s > 0).sum())}/{len(s)}, Wilcoxon p = {stats.wilcoxon(s).pvalue:.2g}")
    for fam, g in H.groupby("familiar"):
        s2 = g[col].dropna().astype(float)
        print("   ", "familiar" if fam else "novel", f"n = {len(s2)}, median {s2.median():.4f}, Wilcoxon p = {stats.wilcoxon(s2).pvalue:.2g}")
import statsmodels.api as smapi
med = HL[HL.lag <= 30].groupby("lag").mse.median()
ols = smapi.OLS(med.values, smapi.add_constant(med.index.values.astype(float))).fit()
print(f"(b) OLS of the median MSE over units on lag 1-30: slope {ols.params[1]:.4f}, p = {ols.pvalues[1]:.2g}; MSE at lag 1 {med.loc[1]:.2f}, at lag 10 {med.loc[10]:.2f} bins^2")
(a) per-unit slope of MSE on lag (lags 1-10), per-lag averages: n = 52, median 0.6189 bins^2/lag, positive 50/52, Wilcoxon p = 5e-10
    novel n = 7, median 0.6291, Wilcoxon p = 0.016
    familiar n = 45, median 0.5435, Wilcoxon p = 8e-13
(a) per-unit slope of MSE on lag (lags 1-10), variant, all trial pairs: n = 52, median 0.5957 bins^2/lag, positive 51/52, Wilcoxon p = 3.7e-10
    novel n = 7, median 0.6973, Wilcoxon p = 0.016
    familiar n = 45, median 0.5827, Wilcoxon p = 1.1e-13
(b) OLS of the median MSE over units on lag 1-30: slope 0.7651, p = 1.2e-10; MSE at lag 1 19.55, at lag 10 24.18 bins^2

Result: Reproduced. (a) The slope of the per-lag mean distance on lag 1 to 10 is positive in 50 of 52 units (median 0.619 bins squared per lag), Wilcoxon p = 5e-10, and in familiar (p = 8e-13) and novel (p = 0.016) units alone; over all trial pairs, 51 of 52, p = 3.7e-10. (b) An OLS fit of the median distance on lag 1 to 30 gives a slope of 0.765, p = 1.2e-10.

switch-step-size-filter¶

Requiring change points to change the firing rate by at least 40% of the maximum removes only 7% of putative switching fields (212 of 3,184).

Paper (Results, Within-session representational drift, paragraph 3): "This restriction ruled out only 7% of the putative switching fields (n = 212/3,184)"

A putative switching field has a significant change point by the shuffle test. It is removed when no change point passes the 40% step filter.

The significance bound and the tie rule are the code's (tag v0.0, place_variability/code/test_change_point.py), which is not under paper/; the lines are quoted here so that they can be checked:

def get_n_cpd(row,alpha=0.05):
    pval = row.loc[slice(None),'pval']
    ntest = len(pval.dropna())
    alpha_bc = alpha / ntest
    anysig = (pval <= alpha_bc).sum()
    if anysig == 0:
        n = 0
    else:
        n = pval.idxmin()
    return n

pval is indexed by K in increasing order, and pandas' idxmin returns the first index of the minimum, so a tie goes to the smaller K.

In [9]:
# claim:switch-step-size-filter, fig2d-switch-fractions
frows = []
for r, o in sw.iter_tasks(res):
    for f in o["fields"]:
        s = f["sw"]
        frows.append(dict(session=r["session"], animal=r["animal"], env=o["env"], familiar=o["familiar"],
                          unit=f["unit"], trial_type=f["trial_type"], merged=f["merged"], splitter=f["splitter"],
                          n_trials=len(f["rate"]), sig=s["sig"], K=s["K"],
                          on=bool(s["on"]), off=bool(s["off"]), sw=bool(s["on"] or s["off"]),
                          on_raw=bool(s["on_raw"]), off_raw=bool(s["off_raw"]), sw_raw=bool(s["on_raw"] or s["off_raw"])))
FD = pd.DataFrame(frows)
print("fields:", len(FD), "| merged turn-common fields:", int(FD.merged.sum()), "| splitter fields:", int(FD.splitter.sum()))
print("fields with too few trials for any K (fewer than 4):", int((FD.n_trials < 4).sum()))
print("best K among significant fields:", FD[FD.sig].K.value_counts().sort_index().to_dict())
for name, g in [("both environments", FD), ("familiar only", FD[FD.familiar])]:
    for norm, col in [("fitted maximum (code)", "sw"), ("raw maximum", "sw_raw")]:
        put = int(g.sig.sum()); kept = int(g[col].sum())
        print(f"{name}, step / {norm}: putative switching fields {put}, removed by the 40% filter {put - kept} ({(put - kept) / put:.1%})")
# variant: ties of the smallest p across K broken toward the larger K (the code takes the smaller, pval.idxmin)
FD["K_tieL"] = [f["sw"]["K_tieL"] for r, o in sw.iter_tasks(res) for f in o["fields"]]
FD["on_tieL"] = [bool(f["sw"]["on_tieL"]) for r, o in sw.iter_tasks(res) for f in o["fields"]]
FD["off_tieL"] = [bool(f["sw"]["off_tieL"]) for r, o in sw.iter_tasks(res) for f in o["fields"]]
FD["sw_tieL"] = FD.on_tieL | FD.off_tieL
sig = FD[FD.sig]
print(f"significant fields whose smallest p is tied over several K: {int((sig.K != sig.K_tieL).sum())} of {len(sig)}; best K with ties to the larger K:", sig.K_tieL.value_counts().sort_index().to_dict())
print(f"variant, ties to the larger K, both environments: putative {len(sig)}, removed by the 40% filter {int(len(sig) - sig.sw_tieL.sum())}")
# per-session counts (the code's stored outputs give only the totals, 12311 and 2310 familiar, 2127 and 662 novel)
ps = FD.groupby(["session", "familiar"]).agg(fields=("sw", "size"), putative=("sig", "sum"), switching=("sw", "sum"), on=("on", "sum"), off=("off", "sum"))
print("per session and environment:\n" + ps.to_string())
fields: 13480 | merged turn-common fields: 961 | splitter fields: 1624
fields with too few trials for any K (fewer than 4): 0
best K among significant fields: {1: 1630, 2: 772, 3: 295, 4: 89, 5: 39}
both environments, step / fitted maximum (code): putative switching fields 2825, removed by the 40% filter 194 (6.9%)
both environments, step / raw maximum: putative switching fields 2825, removed by the 40% filter 600 (21.2%)
familiar only, step / fitted maximum (code): putative switching fields 2105, removed by the 40% filter 175 (8.3%)
familiar only, step / raw maximum: putative switching fields 2105, removed by the 40% filter 480 (22.8%)
significant fields whose smallest p is tied over several K: 647 of 2825; best K with ties to the larger K: {1: 1185, 2: 793, 3: 377, 4: 177, 5: 293}
variant, ties to the larger K, both environments: putative 2825, removed by the 40% filter 230
per session and environment:
                          fields  putative  switching   on  off
session         familiar                                       
e13_16f1_210302 True         314        65         59   44   30
e13_16f1_210312 True         214        44         38   31   11
e13_16f1_210314 True         234        42         35   28   13
e13_16f1_210317 True         248        23         21   16    9
e13_16f1_210319 True         203        32         31   26   10
e13_16f1_210322 True         224        47         44   38   11
e13_16f1_210328 True         413        61         56   51   16
e13_16f1_210331 True         367        39         33   25   13
e13_26m1_211019 False        354       121        120  105   61
                True         457       116        111   72   78
e13_26m1_211116 False        135        25         22    8   14
                True         339        66         63   46   25
e13_26m1_211119 False        163        87         87   72   47
                True         322        80         75   57   26
e13_26m1_211124 True         282        58         49   38   24
e14_2m2_201017  True         188        29         28    7   23
e14_2m2_201019  True         227        37         36   33    5
e14_2m3_201118  True         113        25         24   18   10
e14_2m3_201121  True         113        18         18   17    7
e14_2m3_201125  True         153        18         16   12    7
e14_2m3_201129  True         146        25         22   16   11
e14_2m3_201206  True         149        25         20   18   12
e14_2m3_201208  True         151        25         24   15   15
e15_10m1_200727 True         134        32         26   18   15
e15_10m1_200803 True         114        21         17   15    8
e15_10m1_200809 True         192        20         18   13    8
e15_10m1_200812 True         190        25         23   18    9
e15_13f1_220117 True         633       158        154  124   72
e15_13f1_220118 False        391       172        163  131   90
                True         663       116        107   85   38
e15_13f1_220119 False        514       110        107   82   51
                True         618       133        123  101   56
e15_13f1_220120 False        256        88         86   68   45
                True         526       136        127  113   47
e15_9f1_200715  True         103        24         20   14    8
e15_9f1_200720  True         152        29         24   19   10
e15_9f1_200723  True         155        23         17    9   10
e15_9f1_200729  True         254        22         20   11   14
e15_9f1_200802  True         127        21         18   10   11
e16_1f1_200918  True          73        16         15   12    7
e16_1f1_200919  True          73         7          7    6    5
e16_1f1_200920  True         129        17         14   10    9
e16_1f1_200923  True          94        19         18   13   12
e16_1f1_201004  True         122        18         16    9   10
e16_2m1_201121  True         126        15         14   11    5
e16_3m1_210119  True         307        60         54   41   24
e16_3m1_210201  True         278        53         50   41   29
e16_3m1_210203  True         327        42         37   27   19
e16_3m2_211210  True         308        72         63   45   26
e16_3m2_211212  False        149        40         39   33   15
                True         340        76         71   49   39
e16_3m2_211213  False        272        77         77   54   40
                True         351        75         74   41   48

Result: Not reproduced. Over both environments the shuffle test finds 2825 putative switching fields, below the expected 3184 +- 318, and the code's filter (step over the fitted maximum) removes 194 (6.9%), within the expected 212 +- 21. Familiar only gives 2105 and 175. With the raw maximum as the norm the filter removes 600 (21.2%). The share removed matches the paper's 7%, but no reading puts both counts within tolerance. The smallest p is tied over several K in 647 of 2825 significant fields; the code breaks ties toward the smaller K, as here, and breaking them toward the larger K would remove 230. The per-session counts are printed; the code's stored outputs give only the totals, so they cannot be compared session by session.

fig2d-switch-fractions¶

In the familiar environment 19% of place fields (2,310 of 12,311) switch significantly (14% ON, 9% OFF); in the novel environment 31% (662 of 2,127; 25% ON, 18% OFF).

Paper (Results, Within-session representational drift, paragraph 3; Figure 2D): "Overall, 19% (2,310/12,311) of the place fields showed significant switching (14% ON, 9% OFF) in the familiar environment (Figure 2D) and 31% (662/2,127; 25% ON, 18% OFF) in the novel environment"

Fields after merging of turn-common central-arm fields; a switching field has at least one switch ON or OFF after the 40% filter (code normalisation).

In [10]:
# claim:fig2d-switch-fractions
for fam, g in FD.groupby("familiar"):
    print("familiar" if fam else "novel", f"fields {len(g)}, switching {int(g.sw.sum())} ({g.sw.mean():.3f}), ON {g.on.mean():.3f}, OFF {g.off.mean():.3f}",
          f"| raw-maximum variant: switching {int(g.sw_raw.sum())} ({g.sw_raw.mean():.3f}), ON {g.on_raw.mean():.3f}, OFF {g.off_raw.mean():.3f}")
for fam, g in FD.groupby("familiar"):
    print("variant, ties to the larger K,", "familiar" if fam else "novel", f"switching {int(g.sw_tieL.sum())} ({g.sw_tieL.mean():.3f}), ON {g.on_tieL.mean():.3f}, OFF {g.off_tieL.mean():.3f}")
print("\nby animal:")
print(FD.groupby(["familiar", "animal"]).agg(fields=("sw", "size"), switching=("sw", "mean"), on=("on", "mean"), off=("off", "mean")).round(3).to_string())
novel fields 2234, switching 701 (0.314), ON 0.248, OFF 0.162 | raw-maximum variant: switching 600 (0.269), ON 0.207, OFF 0.129
familiar fields 11246, switching 1930 (0.172), ON 0.130, OFF 0.080 | raw-maximum variant: switching 1625 (0.144), ON 0.107, OFF 0.062
variant, ties to the larger K, novel switching 687 (0.308), ON 0.248, OFF 0.180
variant, ties to the larger K, familiar switching 1908 (0.170), ON 0.129, OFF 0.082

by animal:
                   fields  switching     on    off
familiar animal                                   
False    e13_26m1     652      0.351  0.284  0.187
         e15_13f1    1161      0.307  0.242  0.160
         e16_3m2      421      0.276  0.207  0.131
True     e13_16f1    2217      0.143  0.117  0.051
         e13_26m1    1400      0.213  0.152  0.109
         e14_2m2      415      0.154  0.096  0.067
         e14_2m3      825      0.150  0.116  0.075
         e15_10m1     630      0.133  0.102  0.063
         e15_13f1    2440      0.209  0.173  0.087
         e15_9f1      791      0.125  0.080  0.067
         e16_1f1      491      0.143  0.102  0.088
         e16_2m1      126      0.111  0.087  0.040
         e16_3m1      912      0.155  0.120  0.079
         e16_3m2      999      0.208  0.135  0.113

Result: Not reproduced. Familiar: 11246 fields (within 12311 +- 1231), 1930 switching (below 2310 +- 231), 17.2%, ON 0.130 (within 0.14 +- 0.014), OFF 0.0796 (below 0.09 +- 0.009, by 0.0014). Novel: 2234 fields, 701 switching (both within tolerance), 31.4%, ON 0.248 and OFF 0.1625 (both within, OFF at the edge of 0.162). Six of eight values are within tolerance; one of the four ON and OFF fractions is not, so neither the full nor the partial criterion holds. Under the four other seeds the familiar OFF fraction is 0.0783 to 0.0801, always below. Switching is about twice as common in the novel environment, as the paper reports. With ties of the best K broken toward the larger K the four fractions are 0.129, 0.082, 0.248 and 0.180, all within tolerance, while familiar switching (1908) stays low; the code breaks ties toward the smaller K. With the trial-averaged map (the Methods' wording) familiar switching is 1884 and the novel OFF fraction 0.158, below. With the raw maximum as the norm the fractions are lower (familiar 14.4%, novel 26.9%).

fig2e-switch-fraction-by-experience¶

The fraction of switching fields per session is lowest in animals that experienced only the familiar maze (median 0.15), higher in familiar sessions of animals that also experienced a novel environment that day (0.22) and highest in novel sessions (0.3).

Paper (Results, Within-session representational drift, paragraph 3; Figure 2E): "These animals had higher fractions of switching fields ("Familiar" in Figure 2E) than the "Familiar only" animals"

"Familiar" sessions are the familiar-maze sessions of e13_26m1, e15_13f1 and e16_3m2; 11 here, as e13_26m1_210913 is not in the dandiset.

In [11]:
# claim:fig2e-switch-fraction-by-experience
SF = FD.groupby(["session", "animal", "env", "familiar"]).sw.mean().reset_index()
SF["group"] = np.where(~SF.familiar, "Novel", np.where(SF.animal.isin(sw.NOVEL_ANIMALS), "Familiar", "Familiar only"))
print(SF.groupby("group").sw.agg(["count", "median", "min", "max"]).round(3).to_string())
grp = {k: g.sw.values for k, g in SF.groupby("group")}
for a, b in [("Familiar only", "Familiar"), ("Familiar", "Novel"), ("Familiar only", "Novel")]:
    print(f"{a} against {b}: rank-sum p = {stats.ranksums(grp[a], grp[b]).pvalue:.2g}, medians {np.median(grp[a]):.3f} and {np.median(grp[b]):.3f}")
               count  median    min    max
group                                     
Familiar          11   0.209  0.161  0.243
Familiar only     34   0.149  0.079  0.212
Novel              8   0.310  0.163  0.534
Familiar only against Familiar: rank-sum p = 4.8e-05, medians 0.149 and 0.209
Familiar against Novel: rank-sum p = 0.021, medians 0.209 and 0.310
Familiar only against Novel: rank-sum p = 6.2e-05, medians 0.149 and 0.310

Result: Reproduced. Median fractions of switching fields are 0.149 for Familiar only (34 sessions), 0.209 for Familiar (11) and 0.310 for Novel (8), all within tolerance of 0.15, 0.22 and 0.3. Rank-sum tests: Familiar only against Familiar p = 4.8e-05, Familiar against Novel p = 0.021, Familiar only against Novel p = 6.2e-05, each in the stated direction. Under the four other seeds the medians are 0.139 to 0.151, 0.204 to 0.214 and 0.295 to 0.310, and every p is at most 0.026. With the trial-averaged map (the variant pipeline) the medians are 0.153, 0.212 and 0.283 and the Familiar against Novel test gives p = 0.058, which would make the outcome partially reproduced.

fig3df-step-beats-polynomial-fields¶

For more than 96% of place fields, a change-point model explains more variance of the per-trial peak rate than a polynomial regression with the same number of parameters, at every model complexity.

Paper (Results, Within-session representational drift, paragraph 5; Figure 3D to 3F, left): "The change-point models explained more variance for more than 96% of the place fields across all model complexities"

Each field's per-trial peak rate; a K-change-point model needs at least 2(K + 1) trials.

In [12]:
# claim:fig3df-step-beats-polynomial-fields
r2rows = []
for r, o in sw.iter_tasks(res):
    for f in o["fields"]:
        x = f["rate"]
        d = dict(session=r["session"], familiar=o["familiar"], n=len(x))
        for K in (1, 2, 3):
            if len(x) >= 2 * (K + 1) and np.ptp(x) > 0:
                d[f"cpm{K}"] = sw.r2_step(x, K); d[f"poly{K}"] = sw.r2_poly(x, K)
        r2rows.append(d)
R2 = pd.DataFrame(r2rows)
for K in (1, 2, 3):
    m = R2[f"cpm{K}"].notna()
    better = (R2.loc[m, f"cpm{K}"] > R2.loc[m, f"poly{K}"])
    print(f"K = {K}: fields {int(m.sum())}, change-point model better for {better.mean():.4f}; median R2 cpm {R2.loc[m, f'cpm{K}'].median():.3f}, poly {R2.loc[m, f'poly{K}'].median():.3f}",
          "| familiar %.4f, novel %.4f" % (better[R2.loc[m, "familiar"]].mean(), better[~R2.loc[m, "familiar"]].mean()))
print("fields with constant rate (no fit):", int((R2.cpm1.isna()).sum()))
K = 1: fields 13480, change-point model better for 0.9660; median R2 cpm 0.303, poly 0.110 | familiar 0.9677, novel 0.9575
K = 2: fields 13345, change-point model better for 0.9508; median R2 cpm 0.489, poly 0.238 | familiar 0.9431, novel 0.9919
K = 3: fields 13157, change-point model better for 0.9077; median R2 cpm 0.572, poly 0.338 | familiar 0.8949, novel 0.9752
fields with constant rate (no fit): 0

Result: Partially reproduced. The change-point model explains more variance than a polynomial of the same order for 0.966 of 13480 fields at K = 1, above the paper's bound of 0.96, but for 0.951 of 13345 at K = 2 and 0.908 of 13157 at K = 3, below it. All three exceed 0.90, the criterion's partial level. In novel fields alone the fractions are 0.958, 0.992 and 0.975.

fig3df-polynomial-beats-step-population¶

For the decay of population-vector correlation with trial lag, a polynomial regression explains more variance than the change-point model.

Paper (Results, Within-session representational drift, paragraph 5; Figure 3D to 3F, right, and Figure 3G): "In contrast, polynomial regression explained more variance than the change-point model for the population vector decorrelation"

Per session and turn, the mean PV correlation at each lag (all lags), fitted against lag.

In [13]:
# claim:fig3df-polynomial-beats-step-population
prow = []
for (sess_, env_, tt), (lags, c) in pv_pairs.items():
    m = pd.Series(c).groupby(lags).mean()
    y = m.values
    d = dict(session=sess_, env=env_, turn=tt, n_lags=len(y))
    for K in (1, 2, 3):
        if len(y) >= 2 * (K + 1):
            d[f"cpm{K}"] = sw.r2_step(y, K); d[f"poly{K}"] = sw.r2_poly(y, K)
    prow.append(d)
PR = pd.DataFrame(prow)
pop3 = {}
for K in (1, 2, 3):
    g = PR.dropna(subset=[f"cpm{K}"])
    diff = g[f"cpm{K}"] - g[f"poly{K}"]
    w = stats.wilcoxon(diff)
    pop3[K] = dict(n=len(g), frac_poly=(diff < 0).mean(), med=diff.median(), p=w.pvalue)
    print(f"K = {K}: units {len(g)}, polynomial better for {(diff < 0).mean():.3f}; median R2(CPM) - R2(poly) = {diff.median():.4f}; Wilcoxon p = {w.pvalue:.2g}")
K = 1: units 105, polynomial better for 0.867; median R2(CPM) - R2(poly) = -0.1771; Wilcoxon p = 4.7e-14
K = 2: units 104, polynomial better for 0.827; median R2(CPM) - R2(poly) = -0.0727; Wilcoxon p = 1.9e-10
K = 3: units 101, polynomial better for 0.861; median R2(CPM) - R2(poly) = -0.0472; Wilcoxon p = 2.2e-12

Result: Reproduced. The polynomial explains more variance for 0.867 (K = 1, 105 units), 0.827 (K = 2, 104) and 0.861 (K = 3, 101) of units, and the paired difference R2(CPM) - R2(poly) is below zero (medians -0.177, -0.073, -0.047; Wilcoxon p = 4.7e-14, 1.9e-10, 2.2e-12).

figs4g-population-vectors-gradual¶

Fitted to the population vectors themselves (after PCA), the gradual and step models are comparable, with 60% to 70% of sessions better explained by the gradual model and the distribution of R2 differences significantly biased toward the polynomial model.

Paper (Results, Within-session representational drift, paragraph 6; Figure S4G): "We found that the two models were largely comparable at explaining the data, with more sessions (60%-70%) better explained by the gradual model and the distribution of R2 significantly biased toward continuous models"

Per session and turn, the trial by (cell x position) matrix of place cells, reduced by PCA to the first components holding just above 95% of the variance (a median of 10 features, two fewer than trials, as the Methods say is usual).

In [14]:
# claim:figs4g-population-vectors-gradual
s4 = []
for r, o in sw.iter_tasks(res):
    for tt, tidx in o["trial_types"].items():
        cells = sw.place_cells(o, tt)
        if len(cells) < 2 or len(tidx) < 4:
            continue
        X = o["maps"][tt][cells].transpose(1, 0, 2).reshape(len(tidx), -1).astype(float)
        Xc = X - X.mean(0)
        U_, S_, Vt = np.linalg.svd(Xc, full_matrices=False)
        ev = np.cumsum(S_ ** 2) / (S_ ** 2).sum()
        nf = int(np.searchsorted(ev, 0.95) + 1)  # just above 95% of the variance (Methods)
        Y = U_[:, :nf] * S_[:nf]
        d = dict(session=r["session"], familiar=o["familiar"], turn=tt, n_trials=len(tidx), n_feat=nf)
        for K in (1, 2, 3):
            if len(tidx) >= 2 * (K + 1):
                d[f"cpm{K}"] = sw.vector_cpm_r2(Y, K); d[f"poly{K}"] = sw.vector_poly_r2(Y, K)
        s4.append(d)
S4 = pd.DataFrame(s4)
print("units:", len(S4), "| features kept: median", int(S4.n_feat.median()), "trials minus features: median", int((S4.n_trials - S4.n_feat).median()))
s4res = {}
for K in (1, 2, 3):
    g = S4.dropna(subset=[f"cpm{K}"])
    diff = g[f"cpm{K}"] - g[f"poly{K}"]
    w = stats.wilcoxon(diff)
    s4res[K] = dict(n=len(g), frac=(diff < 0).mean(), p=w.pvalue, d=diff.mean() / diff.std(ddof=1))
    print(f"order {K}: units {len(g)}, polynomial better for {(diff < 0).mean():.3f}; mean R2 difference {diff.mean():.4f}, Cohen's d {diff.mean() / diff.std(ddof=1):.2f}; Wilcoxon p = {w.pvalue:.2g}")
units: 106 | features kept: median 10 trials minus features: median 2
order 1: units 106, polynomial better for 0.434; mean R2 difference 0.0051, Cohen's d 0.20; Wilcoxon p = 0.096
order 2: units 104, polynomial better for 0.510; mean R2 difference 0.0050, Cohen's d 0.16; Wilcoxon p = 0.17
order 3: units 102, polynomial better for 0.402; mean R2 difference 0.0038, Cohen's d 0.08; Wilcoxon p = 0.073

Result: Not reproduced. The polynomial is better for 0.434 (order 1, 106 units), 0.510 (order 2, 104) and 0.402 (order 3, 102) of units, all three below the expected 0.54 to 0.77. The mean difference R2(CPM) - R2(poly) is slightly positive at every order (0.0051, 0.0050, 0.0038; Cohen's d 0.20, 0.16, 0.08), the opposite sign to the paper's, and not significant (Wilcoxon p = 0.096, 0.17, 0.073). The two models are about equally good, as the paper says, without its bias toward the gradual model.

fig3k-switch-abrupt¶

75% to 77% of first passage times after a change point are under two trials, and the distribution of switch durations resembles a negative binomial with two successes and p = 0.5, as expected for an instantaneous step.

Paper (Results, Within-session representational drift, paragraph 7; Figure 3H to 3K): "Empirically, we found that 75%-77% of first passage times happened in fewer than two trials, and the distribution of passage times resembled the expected negative binomial distribution"

Switches of the switching fields, with the step fit of the field's best K. A passage is missing when no crossing occurs within the segment (30 post and 43 pre of 3430 switches).

In [15]:
# claim:fig3k-switch-abrupt
pt = []
for r, o in sw.iter_tasks(res):
    for f in o["fields"]:
        if f["sw"]["on"] or f["sw"]["off"]:
            for d in sw.passage_times(f):
                pt.append(dict(familiar=o["familiar"], **d))
PT = pd.DataFrame(pt)
print("switches:", len(PT), PT.kind.value_counts().to_dict())
print("missing crossings (no crossing within the segment): post", int(PT.post.isna().sum()), "pre", int(PT.pre.isna().sum()))
for kind, g in PT.groupby("kind"):
    fpt = pd.concat([g.post.dropna(), g.pre.dropna()]).astype(int)
    dur = (g.post + g.pre).dropna().astype(int)
    print(f"{kind.upper()}: (a) passage times n = {len(fpt)}, fraction under two trials {(fpt < 2).mean():.3f} (post {(g.post.dropna() < 2).mean():.3f}, pre {(g.pre.dropna() < 2).mean():.3f});"
          f" (b) durations n = {len(dur)}, fraction under two {(dur < 2).mean():.3f}")
    hist = dur.value_counts().sort_index()
    k = np.arange(0, 8)
    exp = stats.nbinom.pmf(k, 2, 0.5)
    obs = np.array([hist.get(i, 0) for i in k[:-1]] + [hist[hist.index >= 7].sum()])
    expn = np.append(exp[:-1], 1 - exp[:-1].sum()) * len(dur)
    chi = stats.chisquare(obs, expn)
    print("   durations 0..6, 7+:", obs.tolist(), "| negative binomial (k = 2, p = 0.5) expects", np.round(expn, 1).tolist(), f"| chi-squared p = {chi.pvalue:.2g}")
    hp = fpt.value_counts().sort_index()
    print("   passage times 0..4:", [int(hp.get(i, 0)) for i in range(5)], "| geometric (p = 0.5) expects", np.round(0.5 ** np.arange(1, 6) * len(fpt), 1).tolist())
switches: 3512 {'on': 2159, 'off': 1353}
missing crossings (no crossing within the segment): post 31 pre 44
OFF: (a) passage times n = 2675, fraction under two trials 0.814 (post 0.791, pre 0.836); (b) durations n = 1322, fraction under two 0.541
   durations 0..6, 7+: [265, 450, 344, 141, 62, 33, 18, 9] | negative binomial (k = 2, p = 0.5) expects [330.5, 330.5, 247.9, 165.2, 103.3, 62.0, 36.1, 46.5] | chi-squared p = 1.4e-32
   passage times 0..4: [1221, 956, 360, 86, 32] | geometric (p = 0.5) expects [1337.5, 668.8, 334.4, 167.2, 83.6]
ON: (a) passage times n = 4274, fraction under two trials 0.808 (post 0.830, pre 0.786); (b) durations n = 2115, fraction under two 0.525
   durations 0..6, 7+: [411, 700, 493, 299, 115, 60, 18, 19] | negative binomial (k = 2, p = 0.5) expects [528.8, 528.8, 396.6, 264.4, 165.2, 99.1, 57.8, 74.4] | chi-squared p = 1.4e-41
   passage times 0..4: [1889, 1564, 536, 185, 64] | geometric (p = 0.5) expects [2137.0, 1068.5, 534.2, 267.1, 133.6]

Result: Reproduced under reading (a). Of individual first passage times, 0.808 (ON, 4274) and 0.814 (OFF, 2675) are under two trials, within the expected 0.675 to 0.847. Under reading (b), switch durations, the fractions are 0.525 and 0.541, outside it. The durations differ from the negative binomial with two successes by a chi-squared test (p = 1.4e-41 ON, 1.4e-32 OFF): there are fewer zero-length and more one-trial durations than it expects (ON 411 and 700 against 529 and 529), and fewer long ones. 31 post and 44 pre passages had no crossing within the segment and are left out.

figs5-switchers-drive-drift¶

Population vectors of switching place cells decorrelate faster with trial lag than those of size-matched non-switching cells, in familiar and novel environments.

Paper (Results, Within-session representational drift, paragraph 8; Figure S5): "The population vector of the switching population decorrelated faster than that of the non-switching population in both familiar and novel environments"

Switchers are place cells with a switching field; non-switchers are sampled to the switchers' number ten times, with replacement when they are fewer (code pv_corr_analysis.py), and slopes averaged. Per session, the median PV correlation at each lag over pairs from both turns ("pooled turns", the code) or per turn, and its linear regression on lag. Seed: the claim's.

In [16]:
# claim:figs5-switchers-drive-drift
rng = np.random.default_rng(sw.seed("figs5-switchers-drive-drift"))
def s5_slopes(rng):
    rows = []
    for r, o in sw.iter_tasks(res):
        swc = {f["cell"] for f in o["fields"] if sw.has_switch(f)}
        per_turn = {}
        for tt, tidx in o["trial_types"].items():
            cells = sw.place_cells(o, tt)
            s_ = [c for c in cells if c in swc]; n_ = [c for c in cells if c not in swc]
            if len(s_) < 2 or len(n_) < 2 or len(tidx) < 3:
                continue
            ls, cs = sw.pv_corr(o["maps"][tt], s_)
            draws = []
            for _ in range(10):  # ten size-matched samples of non-switchers (Methods)
                # with replacement when non-switchers are fewer (code pv_corr_analysis.py, divide_category_by_quantile)
                sub = sorted(rng.choice(n_, len(s_), replace=len(n_) < len(s_)))
                draws.append(sw.pv_corr(o["maps"][tt], sub)[1])
            per_turn[tt] = (ls, cs, draws)
        if not per_turn:
            continue
        def slope_of(keys, which):
            L = np.concatenate([per_turn[k][0] for k in keys])
            if which == "s":
                C = np.concatenate([per_turn[k][1] for k in keys]); med = pd.Series(C).groupby(L).median()
                return np.polyfit(med.index, med.values, 1)[0] if len(med) > 1 else np.nan
            out = []
            for d in range(10):
                C = np.concatenate([per_turn[k][2][d] for k in keys]); med = pd.Series(C).groupby(L).median()
                out.append(np.polyfit(med.index, med.values, 1)[0] if len(med) > 1 else np.nan)
            return np.nanmean(out)
        rows.append(dict(session=r["session"], familiar=o["familiar"], reading="pooled turns",
                         s=slope_of(list(per_turn), "s"), n=slope_of(list(per_turn), "n")))
        for k in per_turn:
            rows.append(dict(session=r["session"], familiar=o["familiar"], reading="per turn", turn=k,
                             s=slope_of([k], "s"), n=slope_of([k], "n")))
    return pd.DataFrame(rows)
S5 = s5_slopes(rng)
for (rd, fam), g in S5.groupby(["reading", "familiar"]):
    g = g.dropna(subset=["s", "n"]); d = g.s - g.n
    print(f"{rd}, {'familiar' if fam else 'novel'}: n = {len(g)}, median difference (switch - no switch) = {d.median():.4f}, switchers steeper in {int((d < 0).sum())}/{len(g)}, Wilcoxon p = {stats.wilcoxon(d).pvalue:.2g}")
# seed sensitivity: the claim's seed plus 1000 to 4000
for k in (1000, 2000, 3000, 4000):
    S5k = s5_slopes(np.random.default_rng(sw.seed("figs5-switchers-drive-drift") + k))
    out = []
    for (rd, fam), g in S5k[S5k.reading == "pooled turns"].groupby(["reading", "familiar"]):
        g = g.dropna(subset=["s", "n"]); d = g.s - g.n
        out.append(f"{'familiar' if fam else 'novel'} median {d.median():.4f} p {stats.wilcoxon(d).pvalue:.2g}")
    print(f"seed + {k}, pooled turns:", "; ".join(out))
per turn, novel: n = 16, median difference (switch - no switch) = -0.0101, switchers steeper in 14/16, Wilcoxon p = 0.00021
per turn, familiar: n = 90, median difference (switch - no switch) = -0.0088, switchers steeper in 77/90, Wilcoxon p = 1.2e-12
pooled turns, novel: n = 8, median difference (switch - no switch) = -0.0106, switchers steeper in 8/8, Wilcoxon p = 0.0078
pooled turns, familiar: n = 45, median difference (switch - no switch) = -0.0065, switchers steeper in 38/45, Wilcoxon p = 5.8e-09
seed + 1000, pooled turns: novel median -0.0103 p 0.0078; familiar median -0.0073 p 2e-09
seed + 2000, pooled turns: novel median -0.0104 p 0.0078; familiar median -0.0074 p 6.7e-08
seed + 3000, pooled turns: novel median -0.0104 p 0.0078; familiar median -0.0064 p 2.9e-09
seed + 4000, pooled turns: novel median -0.0107 p 0.0078; familiar median -0.0074 p 2.9e-09

Result: Reproduced. Pooled turns: switchers' PV decorrelates faster in 38 of 45 familiar sessions (median difference -0.0065, Wilcoxon p = 5.8e-09) and in 8 of 8 novel sessions (-0.0106, p = 0.0078). Per turn: 77 of 90 (p = 1.2e-12) and 14 of 16 (p = 0.00021). The familiar median is smaller than the expected -0.009 and outside its tolerance; the novel median is within -0.011 +- 0.0011. Under the four other seeds the familiar medians are -0.0064 to -0.0074 (p up to 6.7e-08) and the novel -0.0103 to -0.0107 (p = 0.0078), the same outcome.

Seed sensitivity of the field and switch pipeline¶

Place fields come from circular shuffles and switches from trial permutations. The cell below runs the whole pipeline again under four more seeds and prints the main counts under each, for the claims that rest on fields and switches; the outcomes above are under the claim's own seed.

In [17]:
# Seed sensitivity of the field and switch pipeline: the whole pipeline again under the seed of
# fig2d-switch-fractions plus 1000, 2000, 3000 and 4000 (about five minutes each)
def pipeline_summary(rs):
    d = {}
    F = [(o["familiar"], f) for r, o in sw.iter_tasks(rs) for f in o["fields"]]
    for fam in (True, False):
        g = [f for fm, f in F if fm == fam]
        e = "fam" if fam else "nov"
        d[f"{e}_fields"] = len(g)
        d[f"{e}_switching"] = sum(sw.has_switch(f) for f in g)
        d[f"{e}_on"] = round(np.mean([bool(f["sw"]["on"]) for f in g]), 4)
        d[f"{e}_off"] = round(np.mean([bool(f["sw"]["off"]) for f in g]), 4)
    d["putative"] = sum(f["sw"]["sig"] for _, f in F)
    d["removed"] = d["putative"] - sum(sw.has_switch(f) for _, f in F)
    sf = pd.DataFrame([dict(fam=o["familiar"], animal=r["animal"], fr=np.mean([sw.has_switch(f) for f in o["fields"]]))
                       for r, o in sw.iter_tasks(rs)])
    sf["group"] = np.where(~sf.fam, "Novel", np.where(sf.animal.isin(sw.NOVEL_ANIMALS), "Familiar", "Familiar only"))
    for gname, g in sf.groupby("group"):
        d["median " + gname] = round(g.fr.median(), 3)
    gg = {k: g.fr.values for k, g in sf.groupby("group")}
    d["p FO-F"] = stats.ranksums(gg["Familiar only"], gg["Familiar"]).pvalue
    d["p F-N"] = stats.ranksums(gg["Familiar"], gg["Novel"]).pvalue
    d["p FO-N"] = stats.ranksums(gg["Familiar only"], gg["Novel"]).pvalue
    for K in (1, 2, 3):
        b = [sw.r2_step(f["rate"], K) > sw.r2_poly(f["rate"], K) for _, f in F if len(f["rate"]) >= 2 * (K + 1) and np.ptp(f["rate"]) > 0]
        d[f"cpm better K{K}"] = round(np.mean(b), 4)
    sl = []
    for r, o in sw.iter_tasks(rs):
        for tt, tidx in o["trial_types"].items():
            cells = sw.place_cells(o, tt)
            if len(cells) >= 2 and len(tidx) >= 3:
                lg, c = sw.pv_corr(o["maps"][tt], cells)
                sl.append((o["familiar"], sw.lag_slope(lg, c, 1, 10)))
    sl = pd.DataFrame(sl, columns=["fam", "s"]).dropna()
    d["fig1e p"] = stats.ranksums(sl[sl.fam].s.astype(float), sl[~sl.fam].s.astype(float)).pvalue
    d["fig1e d"] = round(sw.cohen_d(sl[sl.fam].s.astype(float), sl[~sl.fam].s.astype(float)), 3)
    return d
seed_rows = [dict(seed="claim seed", **pipeline_summary(res))]
for k in (1000, 2000, 3000, 4000):
    t = time.time()
    rk = sw.run_all(have, claim_seed=sw.seed("fig2d-switch-fractions") + k)
    seed_rows.append(dict(seed=f"+{k}", **pipeline_summary(rk)))
    del rk
    print(f"seed +{k}: {time.time() - t:.0f} s")
SEEDS = pd.DataFrame(seed_rows).set_index("seed").T
print(SEEDS.to_string())
seed +1000: 249 s
seed +2000: 248 s
seed +3000: 253 s
seed +4000: 247 s
seed                    claim seed         +1000         +2000         +3000         +4000
fam_fields            11246.000000  11264.000000  11253.000000  11248.000000  11235.000000
fam_switching          1930.000000   1911.000000   1909.000000   1933.000000   1921.000000
fam_on                    0.130100      0.128400      0.128500      0.129100      0.130000
fam_off                   0.079600      0.078500      0.078300      0.080100      0.078500
nov_fields             2234.000000   2240.000000   2237.000000   2232.000000   2237.000000
nov_switching           701.000000    703.000000    693.000000    680.000000    687.000000
nov_on                    0.247500      0.251300      0.247200      0.241000      0.245400
nov_off                   0.162500      0.162500      0.155600      0.153700      0.152000
putative               2825.000000   2813.000000   2794.000000   2808.000000   2816.000000
removed                 194.000000    199.000000    192.000000    195.000000    208.000000
median Familiar           0.209000      0.204000      0.214000      0.205000      0.209000
median Familiar only      0.149000      0.139000      0.147000      0.151000      0.149000
median Novel              0.310000      0.310000      0.299000      0.303000      0.295000
p FO-F                    0.000048      0.000034      0.000036      0.000067      0.000093
p F-N                     0.020776      0.016639      0.025784      0.016639      0.025784
p FO-N                    0.000062      0.000054      0.000071      0.000041      0.000093
cpm better K1             0.966000      0.965300      0.965800      0.965400      0.966400
cpm better K2             0.950800      0.951000      0.950900      0.950700      0.951000
cpm better K3             0.907700      0.907200      0.907700      0.907200      0.907000
fig1e p                   0.014765      0.014005      0.012929      0.016395      0.012929
fig1e d                   0.508000      0.512000      0.518000      0.511000      0.520000

The Methods detect fields on "the trial-averaged ratemap"; the code pools spike counts and occupancy over trials before dividing. The cell below runs the whole pipeline once more with the map taken as the mean of the per-trial maps, for the data and the shuffles, and prints the same counts beside the main ones.

In [18]:
# Variant of the field map: the Methods' "trial-averaged ratemap" read as the mean of the per-trial
# maps, for the data and for each shuffle (sw.trialavg_map_and_null), under the claim's seed (about four minutes)
def mf_counts(rs):
    n = same = 0
    for r, o in sw.iter_tasks(rs):
        swf = [f for f in o["fields"] if sw.has_switch(f)]
        for a in range(len(swf)):
            for b in range(a + 1, len(swf)):
                fa, fb = swf[a], swf[b]
                if fa["unit"] == fb["unit"] and (fa["trial_type"] == fb["trial_type"] or "both" in (fa["trial_type"], fb["trial_type"])):
                    n += 1
                    ta = set(sw.switch_trials(fa, "on")) | set(sw.switch_trials(fa, "off"))
                    tb = set(sw.switch_trials(fb, "on")) | set(sw.switch_trials(fb, "off"))
                    same += bool(ta & tb)
    return n, same
t = time.time()
rv = sw.run_all(have, field_map="trialavg")
VAR = pd.DataFrame({"pooled map (main)": pipeline_summary(res), "trial-averaged map": pipeline_summary(rv)})
for name, rs in (("pooled map (main)", res), ("trial-averaged map", rv)):
    VAR.loc["same-neuron pairs (same turn)", name], VAR.loc["  of which same trial", name] = mf_counts(rs)
print(f"trial-averaged pipeline {time.time() - t:.0f} s")
print(VAR.to_string())
del rv
trial-averaged pipeline 232 s
                               pooled map (main)  trial-averaged map
fam_fields                          11246.000000        10842.000000
fam_switching                        1930.000000         1884.000000
fam_on                                  0.130100            0.130100
fam_off                                 0.079600            0.082800
nov_fields                           2234.000000         2177.000000
nov_switching                         701.000000          653.000000
nov_on                                  0.247500            0.233300
nov_off                                 0.162500            0.157600
putative                             2825.000000         2716.000000
removed                               194.000000          179.000000
median Familiar                         0.209000            0.212000
median Familiar only                    0.149000            0.153000
median Novel                            0.310000            0.283000
p FO-F                                  0.000048            0.000053
p F-N                                   0.020776            0.057543
p FO-N                                  0.000062            0.000426
cpm better K1                           0.966000            0.964400
cpm better K2                           0.950800            0.949100
cpm better K3                           0.907700            0.905800
fig1e p                                 0.014765            0.012587
fig1e d                                 0.508000            0.501000
same-neuron pairs (same turn)         283.000000          262.000000
  of which same trial                  37.000000           32.000000

fig4-glm-deviance¶

A Poisson GLM of switch counts per arm and trial explains 20% of the deviance for switching ON and 14% for switching OFF, with animal identity, maze segment and the number of place fields the most important predictors.

Paper (Results, Factors that affect the rate of switching, paragraph 1; Figure 4A and 4F): "The model explained 20% of the deviance for switching ON and 14% for switching OFF ... We found that the variables that explained most of the variance were the animal labels (i.e., individual differences), the maze corridors, and the number of place fields"

Rows are familiar trial by maze segment, trials from the fourth on (code). A switch counts in the segment holding its field's peak, on the trial of the change point; N_field counts the fields of the trial's turn (and merged fields) with their peak in the segment. Speed and CV of speed are of the absolute smoothed velocity of linearised position within the segment on the trial. Held-out explained deviance is 1 minus the Poisson deviance of the test rows over that of the training mean. Folds are drawn under the claim's seed.

In [19]:
# claim:fig4-glm-deviance
import statsmodels.formula.api as smf
import statsmodels.api as smapi
SEGS = ["delay", "central", "choice", "return_side", "pre_delay"]
def seg_of_bin(o, b):
    cm = (o["edges"][b] + o["edges"][b + 1]) / 2
    return sw.SEGMENT_NAMES[min(np.searchsorted(sw.SEGMENT_CUTS, cm, side="right") - 1, len(sw.SEGMENT_NAMES) - 1)]
glm_rows = []
for r, o in sw.iter_tasks(res):
    if not o["familiar"]:
        continue
    tr = o["trials"]; beh = o["beh"].set_index("trial")
    n = len(tr)
    fseg = [(f, seg_of_bin(o, f["peak_bin"])) for f in o["fields"]]
    for t in range(3, n):  # trials from the fourth on (code behavior_and_switching.py)
        if t not in beh.index or not np.isfinite(beh.loc[t, "speed"]):
            continue
        tt = tr.trial_type[t]
        for s in SEGS:
            fl = [f for f, sg in fseg if sg == s and f["trial_type"] in (tt, "both")]
            glm_rows.append(dict(session=r["session"], Animal=r["animal"], Position=s, trial=t,
                                 N_field=len(fl),
                                 on=sum(t in sw.switch_trials(f, "on") for f in fl),
                                 off=sum(t in sw.switch_trials(f, "off") for f in fl),
                                 Speed=beh.loc[t, f"speed_{s}"], CV_speed=beh.loc[t, f"cv_{s}"],
                                 Correct=tr.visited_matched_expected[t], Prev_correct=tr.visited_matched_expected[t - 1]))
G = pd.DataFrame(glm_rows)
G["Trial"] = G.groupby("session").trial.transform(lambda x: (x - x.mean()) / x.std())
G["Speed_raw"] = G.Speed
G["Speed"] = G.groupby("session").Speed.transform(lambda x: (x - x.mean()) / x.std())
n0 = len(G)
G = G.dropna(subset=["Speed", "CV_speed", "Correct", "Prev_correct"]).reset_index(drop=True)
G["Position"] = pd.Categorical(G.Position, categories=SEGS)
print(f"arm x trial rows: {len(G)} ({n0 - len(G)} dropped for a missing speed or choice) from {G.session.nunique()} sessions and {G.Animal.nunique()} animals")
print("switch ON per row: total", int(G.on.sum()), "| OFF", int(G.off.sum()), "| N_field range", G.N_field.min(), "to", G.N_field.max())
FULL = "C(Animal) + C(Position) + N_field + Trial + Speed + CV_speed + C(Correct) + C(Prev_correct)"
TERMS = {"Animal": "C(Animal)", "Position": "C(Position)", "N_field": "N_field", "Trial": "Trial", "Speed": "Speed",
         "CV_speed": "CV_speed", "Correct": "C(Correct)", "Prev_correct": "C(Prev_correct)"}
def poisson_dev(y, mu):
    y = np.asarray(y, float); mu = np.clip(np.asarray(mu, float), 1e-12, None)
    with np.errstate(divide="ignore", invalid="ignore"):  # the y = 0 terms are masked
        return 2 * np.sum(np.where(y > 0, y * np.log(y / mu), 0) - (y - mu))
def fit(y, formula, data):
    return smf.glm(f"{y} ~ {formula}", data=data, family=smapi.families.Poisson()).fit()
def cv_splits(kind, rng):
    animals = G.Animal.values
    if kind == "kfold":  # 5-fold stratified by animal, repeated 10 times (Methods)
        for rep in range(10):
            fold = np.empty(len(G), int)
            for a in np.unique(animals):
                idx = np.nonzero(animals == a)[0]; rng.shuffle(idx)
                fold[idx] = np.arange(len(idx)) % 5
            for k in range(5):
                yield fold != k, fold == k
    else:  # code: StratifiedShuffleSplit, 5 splits, 10% held out
        for rep in range(5):
            test = np.zeros(len(G), bool)
            for a in np.unique(animals):
                idx = np.nonzero(animals == a)[0]
                test[rng.choice(idx, max(1, int(round(0.1 * len(idx)))), replace=False)] = True
            yield ~test, test
def cv_table(y, kind, seed_):
    rng = np.random.default_rng(seed_)
    out = []
    for tr_m, te_m in cv_splits(kind, rng):
        tr_d, te_d = G[tr_m], G[te_m]
        null = poisson_dev(te_d[y], np.full(len(te_d), tr_d[y].mean()))
        row = {"full": 1 - poisson_dev(te_d[y], fit(y, FULL, tr_d).predict(te_d)) / null}
        for name, term in TERMS.items():
            f_ = " + ".join(t for t in TERMS.values() if t != term)
            row[name] = row["full"] - (1 - poisson_dev(te_d[y], fit(y, f_, tr_d).predict(te_d)) / null)
        out.append(row)
    return pd.DataFrame(out)
glm = {}
for y in ("on", "off"):
    full = fit(y, FULL, G)
    insample = 1 - full.deviance / full.null_deviance
    cvk = cv_table(y, "kfold", sw.seed("fig4-glm-deviance") + (0 if y == "on" else 1))
    glm[y] = dict(fit=full, insample=insample, cv=cvk)
    drops = cvk.drop(columns="full").median().sort_values(ascending=False)
    print(f"\nswitch {y.upper()}: explained deviance (a) cross-validated held-out median {cvk.full.median():.3f} (range {cvk.full.min():.3f} to {cvk.full.max():.3f}); (b) in-sample {insample:.3f}")
    print("   median drop in held-out explained deviance when a predictor is left out:", drops.round(4).to_dict())
    print("   three largest:", list(drops.index[:3]))
arm x trial rows: 5117 (38 dropped for a missing speed or choice) from 45 sessions and 11 animals
switch ON per row: total 1517 | OFF 898 | N_field range 0 to 111
switch ON: explained deviance (a) cross-validated held-out median 0.192 (range 0.132 to 0.238); (b) in-sample 0.202
   median drop in held-out explained deviance when a predictor is left out: {'Position': 0.0184, 'Animal': 0.0138, 'N_field': 0.006, 'Speed': 0.0019, 'Prev_correct': 0.0007, 'Trial': 0.0007, 'Correct': 0.0002, 'CV_speed': 0.0}
   three largest: ['Position', 'Animal', 'N_field']
switch OFF: explained deviance (a) cross-validated held-out median 0.128 (range 0.049 to 0.178); (b) in-sample 0.145
   median drop in held-out explained deviance when a predictor is left out: {'Trial': 0.0141, 'N_field': 0.0089, 'Animal': 0.0041, 'Position': 0.0015, 'Prev_correct': 0.0014, 'Speed': 0.0003, 'CV_speed': -0.0002, 'Correct': -0.0005}
   three largest: ['Trial', 'N_field', 'Animal']
In [20]:
# claim:fig4-glm-deviance (variants and seeds)
for y in ("on", "off"):
    ss = cv_table(y, "shuffle", sw.seed("fig4-glm-deviance") + 2 + (0 if y == "on" else 1))
    drops = ss.drop(columns="full").median().sort_values(ascending=False)
    print(f"code variant (5 stratified shuffle splits, 10% held out), {y.upper()}: held-out explained deviance median {ss.full.median():.3f}; three largest drops {list(drops.index[:3])}")
for y in ("on", "off"):
    vals = []
    for k in (1000, 2000, 3000, 4000):
        rng = np.random.default_rng(sw.seed("fig4-glm-deviance") + (0 if y == "on" else 1) + k)
        v = []
        for tr_m, te_m in cv_splits("kfold", rng):
            tr_d, te_d = G[tr_m], G[te_m]
            null = poisson_dev(te_d[y], np.full(len(te_d), tr_d[y].mean()))
            v.append(1 - poisson_dev(te_d[y], fit(y, FULL, tr_d).predict(te_d)) / null)
        vals.append(np.median(v))
    print(f"{y.upper()}: held-out explained deviance under seeds + 1000 to + 4000:", np.round(vals, 3).tolist())
code variant (5 stratified shuffle splits, 10% held out), ON: held-out explained deviance median 0.167; three largest drops ['Position', 'N_field', 'Animal']
code variant (5 stratified shuffle splits, 10% held out), OFF: held-out explained deviance median 0.099; three largest drops ['Position', 'N_field', 'Trial']
ON: held-out explained deviance under seeds + 1000 to + 4000: [0.193, 0.194, 0.194, 0.19]
OFF: held-out explained deviance under seeds + 1000 to + 4000: [0.114, 0.117, 0.121, 0.118]

Result: Partially reproduced. There are 5117 rows (expected 5131). Held out under repeated 5-fold cross-validation, explained deviance is 0.192 ON and 0.128 OFF, both within tolerance of 0.20 and 0.14 (reading a); in-sample it is 0.202 and 0.145, also within (reading b). The three largest held-out drops are position, animal and number of fields for ON, as the paper says, but trial, number of fields and animal for OFF, with position fourth (0.0015). The values hold and the ranking holds for ON only. The criterion's full condition fails on the OFF ranking, and its partial clause ("only the ranking holds") does not name this case; partially reproduced is a judgment here, as the verifier's, and the outcome is marked as resting on it. Under four other seeds the held-out values are 0.190 to 0.194 ON and 0.114 to 0.121 OFF (below 0.126), so the held-out OFF value is within tolerance only under the claim's seed; the in-sample values (reading b) involve no random draw and are within tolerance, so the values hold under every seed. The code's split (5 shuffle splits, 10% held out) gives 0.167 and 0.099, with position, number of fields and trial first for OFF.

fig4-delay-zone-more-switching¶

Consistently more switching ON and OFF occurs in the delay zone than in other parts of the maze.

Paper (Results, Factors that affect the rate of switching, paragraph 1; Figure 4B, 4E, 4G and 4J): "consistently more ON/OFF switching occurred in the delay zone"

Coefficients of the full GLM fitted on all rows, relative to the delay zone.

In [21]:
# claim:fig4-delay-zone-more-switching, fig4-behavior-not-predictive
for y in ("on", "off"):
    f_ = glm[y]["fit"]; ci = f_.conf_int()
    print(f"switch {y.upper()}, full GLM on all rows: position coefficients relative to the delay zone (95% CI from the Fisher information)")
    for s in SEGS[1:]:
        k = f"C(Position)[T.{s}]"
        print(f"   {s:12s} {f_.params[k]: .3f} [{ci.loc[k, 0]: .3f}, {ci.loc[k, 1]: .3f}]")
    for k in ("C(Correct)[T.1.0]", "C(Prev_correct)[T.1.0]", "Speed", "CV_speed", "Trial", "N_field"):
        print(f"   {k:24s} {f_.params[k]: .4f} [{ci.loc[k, 0]: .4f}, {ci.loc[k, 1]: .4f}] p = {f_.pvalues[k]:.2g}")
    cvk = glm[y]["cv"]
    for p_ in ("Speed", "CV_speed"):
        print(f"   held-out drop leaving out {p_}: median {cvk[p_].median():.5f}, SD over splits {cvk[p_].std():.5f}, above zero in {int((cvk[p_] > 0).sum())}/{len(cvk)} splits")
# per-session switches normalised by fields per arm (Figure 4E, 4J)
ns = G.groupby(["session", "Position"], observed=True)[["on", "off", "N_field"]].sum()
ns = ns[ns.N_field > 0]
nr = (ns[["on", "off"]].div(ns.N_field, axis=0)).groupby(level="Position", observed=True).median()
print("\nmedian over sessions of switches per field in each segment:\n", nr.round(4).to_string())
# segment boundaries on the linearised track (code behavior_and_switching.py) and field peaks per segment
o0 = [o for r, o in sw.iter_tasks(res) if o["familiar"]][0]
segb = pd.Series([seg_of_bin(o0, b) for b in range(o0["nbins"])])
print("\nsegment cut points (cm):", [int(x) for x in sw.SEGMENT_CUTS], "| bins per segment on a 100-bin track:",
      {s_: [int(segb[segb == s_].index.min()), int(segb[segb == s_].index.max()), int((segb == s_).sum())] for s_ in SEGS}, "(first bin, last bin, count; the delay zone wraps)")
pk = pd.Series([seg_of_bin(o, f["peak_bin"]) for r, o in sw.iter_tasks(res) if o["familiar"] for f in o["fields"]]).value_counts()
pk_sw = pd.Series([seg_of_bin(o, f["peak_bin"]) for r, o in sw.iter_tasks(res) if o["familiar"] for f in o["fields"] if sw.has_switch(f)]).value_counts()
print("familiar field peaks per segment:", pk.reindex(SEGS).to_dict(), "| of switching fields:", pk_sw.reindex(SEGS).to_dict(),
      "| per bin:", (pk.reindex(SEGS) / segb.value_counts().reindex(SEGS)).round(1).to_dict())
switch ON, full GLM on all rows: position coefficients relative to the delay zone (95% CI from the Fisher information)
   central       0.288 [ 0.085,  0.491]
   choice        0.628 [ 0.455,  0.802]
   return_side   0.767 [ 0.577,  0.957]
   pre_delay    -0.322 [-0.585, -0.058]
   C(Correct)[T.1.0]         0.0696 [-0.0586,  0.1978] p = 0.29
   C(Prev_correct)[T.1.0]   -0.1291 [-0.2515, -0.0067] p = 0.039
   Speed                     0.1166 [ 0.0291,  0.2040] p = 0.009
   CV_speed                  0.0716 [-0.0547,  0.1979] p = 0.27
   Trial                    -0.0579 [-0.1087, -0.0071] p = 0.026
   N_field                   0.0134 [ 0.0086,  0.0181] p = 3.5e-08
   held-out drop leaving out Speed: median 0.00185, SD over splits 0.00397, above zero in 31/50 splits
   held-out drop leaving out CV_speed: median 0.00002, SD over splits 0.00107, above zero in 26/50 splits
switch OFF, full GLM on all rows: position coefficients relative to the delay zone (95% CI from the Fisher information)
   central       0.415 [ 0.170,  0.661]
   choice        0.281 [ 0.064,  0.498]
   return_side   0.213 [-0.026,  0.452]
   pre_delay    -0.206 [-0.525,  0.112]
   C(Correct)[T.1.0]         0.0178 [-0.1464,  0.1819] p = 0.83
   C(Prev_correct)[T.1.0]   -0.1607 [-0.3182, -0.0031] p = 0.046
   Speed                    -0.0746 [-0.1931,  0.0439] p = 0.22
   CV_speed                  0.0736 [-0.0931,  0.2403] p = 0.39
   Trial                    -0.2431 [-0.3102, -0.1760] p = 1.2e-12
   N_field                   0.0208 [ 0.0144,  0.0272] p = 1.8e-10
   held-out drop leaving out Speed: median 0.00031, SD over splits 0.00207, above zero in 29/50 splits
   held-out drop leaving out CV_speed: median -0.00020, SD over splits 0.00163, above zero in 22/50 splits

median over sessions of switches per field in each segment:
                  on     off
Position                   
delay        0.0083  0.0049
central      0.0103  0.0060
choice       0.0122  0.0058
return_side  0.0106  0.0057
pre_delay    0.0076  0.0054

segment cut points (cm): [0, 15, 74, 111, 185, 202, 222] | bins per segment on a 100-bin track: {'delay': [0, 99, 16], 'central': [7, 32, 26], 'choice': [33, 49, 17], 'return_side': [50, 82, 33], 'pre_delay': [83, 90, 8]} (first bin, last bin, count; the delay zone wraps)
familiar field peaks per segment: {'delay': 2331, 'central': 1985, 'choice': 2583, 'return_side': 3459, 'pre_delay': 888} | of switching fields: {'delay': 255, 'central': 426, 'choice': 478, 'return_side': 630, 'pre_delay': 141} | per bin: {'delay': 145.7, 'central': 76.3, 'choice': 151.9, 'return_side': 104.8, 'pre_delay': 111.0}

Result: Not reproduced. Relative to the delay zone, switching ON is more likely in the central arm (0.288, CI 0.085 to 0.491), choice arm (0.628) and return side arm (0.767), and less likely only in the pre-delay zone (-0.322, CI -0.585 to -0.058). Switching OFF is more likely in the central (0.415) and choice (0.281) arms, with intervals excluding zero; the return side (0.213) and pre-delay (-0.206) intervals include zero. Normalised per field, the median switch-ON count in the delay zone (0.0083) is below the central, choice and return side arms (0.0103 to 0.0122) and above the pre-delay zone (0.0076); for OFF the delay zone is lowest (0.0049 against 0.0054 to 0.0060). The delay zone has less switching than most of the maze, not more. The segments are cut at 0, 15, 74, 111, 185, 202 and 222 cm (the code); the delay zone spans 16 bins at both ends of the track and holds 2331 familiar field peaks (145.7 per bin, as dense as the choice arm, 151.9) but the peaks of only 255 of the 1930 familiar switching fields.

fig4-behavior-not-predictive¶

Correct or incorrect choice on the current or previous trial does not predict switching, and leaving out speed or the CV of speed does not reduce the model's prediction of held-out data.

Paper (Results, Factors that affect the rate of switching, paragraph 1; Figure 4A, 4C, 4F, 4H): "Correct or incorrect arm choice on the current or previous trial did not predict the occurrence of switching (Figures 4C and 4H). Leaving out locomotion speed or coefficient of variation (CV) of speed did not reduce the model's ability to predict held-out data"

A claim of absence, on the coefficients and held-out drops of the GLM printed in the previous cell.

The cell of the previous section prints the numbers for this claim.

Result: Not reproduced. The current-trial choice coefficient includes zero for ON (0.070, CI -0.059 to 0.198) and OFF (0.018, CI -0.146 to 0.182), but a correct previous trial lowers switching ON (-0.129, CI -0.252 to -0.007, p = 0.039) and OFF (-0.161, CI -0.318 to -0.003, p = 0.046). Leaving out speed or its CV does not reduce prediction by more than the spread over splits: median drops 0.00185 (SD 0.00397) and 0.00002 for ON, 0.00031 (SD 0.00207) and -0.00020 for OFF. The speed part holds; both previous-choice intervals exclude zero.

fig4di-switching-decreases-with-trial¶

The number of switches normalised by the number of fields decreases with trial number, for ON and OFF, in familiar and novel environments.

Paper (Results, Factors that affect the rate of switching, paragraph 1; Figure 4D and 4I): "As expected, switching probability decreased as a function of the trial number"

Per session and environment, the number of switches ON (OFF) on each trial divided by the number of fields, against the trial number z-scored within session, pooled. Which trials enter is not stated. Two readings are run: (i) all trials; (ii) trials from the fourth on, as in the GLM of the code. Reading (ii) gives 1031 familiar and 288 novel trials, close to the legend's 1029 and 281, while (i) gives 1166 and 312; reading (ii) is adopted as an assumption.

In [22]:
# claim:fig4di-switching-decreases-with-trial, figs8-speed-no-trend
tr_rows = []
for r, o in sw.iter_tasks(res):
    nF = len(o["fields"])
    ons = pd.Series([t for f in o["fields"] for t in sw.switch_trials(f, "on")]).value_counts()
    offs = pd.Series([t for f in o["fields"] for t in sw.switch_trials(f, "off")]).value_counts()
    n = len(o["trials"])
    beh = o["beh"].set_index("trial")
    for t in range(n):
        tr_rows.append(dict(session=r["session"], familiar=o["familiar"], trial=t, on=ons.get(t, 0) / nF, off=offs.get(t, 0) / nF,
                            speed=beh.speed.get(t, np.nan)))
TR = pd.DataFrame(tr_rows)
TR["trial_z"] = TR.groupby(["session", "familiar"]).trial.transform(lambda x: (x - x.mean()) / x.std())
TR["speed_z"] = TR.groupby(["session", "familiar"]).speed.transform(lambda x: (x - x.mean()) / x.std())
for fam, g in TR.groupby("familiar"):
    for k in ("on", "off"):
        pr = stats.pearsonr(g.trial_z, g[k]); sr = stats.spearmanr(g.trial_z, g[k])
        print(f"{'familiar' if fam else 'novel'} {k.upper()}: trials {len(g)}, Pearson r = {pr[0]:.3f} (p = {pr[1]:.2g}); Spearman variant rho = {sr[0]:.3f} (p = {sr[1]:.2g})")
print("trials per session: %d to %d" % (TR.groupby(["session", "familiar"]).size().min(), TR.groupby(["session", "familiar"]).size().max()))
# variant: change points need two trials per segment in each turn, so the first trials of a session cannot hold a switch;
# the same correlation over trials from the fourth on (as the GLM, code behavior_and_switching.py)
for fam, g in TR[TR.trial >= 3].groupby("familiar"):
    g = g.copy(); g["tz"] = g.groupby("session").trial.transform(lambda x: (x - x.mean()) / x.std())
    for k in ("on", "off"):
        pr = stats.pearsonr(g.tz, g[k])
        print(f"variant, trials from the fourth on, {'familiar' if fam else 'novel'} {k.upper()}: trials {len(g)}, r = {pr[0]:.3f} (p = {pr[1]:.2g})")
# a change point also cannot fall on a turn's last trial, so the last trials of a session hold few switches too
TR["n_sess"] = TR.groupby(["session", "familiar"]).trial.transform("size")
for fam, g in TR.groupby("familiar"):
    print(f"{'familiar' if fam else 'novel'}: switches per field on the last two trials of a session, ON {g[g.trial >= g.n_sess - 2].on.mean():.4f}, OFF {g[g.trial >= g.n_sess - 2].off.mean():.4f}; on other trials from the fourth on, ON {g[(g.trial >= 3) & (g.trial < g.n_sess - 2)].on.mean():.4f}, OFF {g[(g.trial >= 3) & (g.trial < g.n_sess - 2)].off.mean():.4f}")
for fam, g in TR[(TR.trial >= 3) & (TR.trial < TR.n_sess - 2)].groupby("familiar"):
    g = g.copy(); g["tz"] = g.groupby("session").trial.transform(lambda x: (x - x.mean()) / x.std())
    for k in ("on", "off"):
        pr = stats.pearsonr(g.tz, g[k])
        print(f"variant, trials from the fourth to the third from last, {'familiar' if fam else 'novel'} {k.upper()}: trials {len(g)}, r = {pr[0]:.3f} (p = {pr[1]:.2g})")
novel ON: trials 312, Pearson r = 0.051 (p = 0.37); Spearman variant rho = 0.044 (p = 0.44)
novel OFF: trials 312, Pearson r = -0.021 (p = 0.71); Spearman variant rho = -0.057 (p = 0.32)
familiar ON: trials 1166, Pearson r = 0.072 (p = 0.014); Spearman variant rho = 0.074 (p = 0.011)
familiar OFF: trials 1166, Pearson r = -0.002 (p = 0.94); Spearman variant rho = 0.013 (p = 0.65)
trials per session: 9 to 68
variant, trials from the fourth on, novel ON: trials 288, r = -0.083 (p = 0.16)
variant, trials from the fourth on, novel OFF: trials 288, r = -0.145 (p = 0.014)
variant, trials from the fourth on, familiar ON: trials 1031, r = -0.065 (p = 0.037)
variant, trials from the fourth on, familiar OFF: trials 1031, r = -0.125 (p = 6e-05)
novel: switches per field on the last two trials of a session, ON 0.0002, OFF 0.0005; on other trials from the fourth on, ON 0.0080, OFF 0.0053
familiar: switches per field on the last two trials of a session, ON 0.0009, OFF 0.0003; on other trials from the fourth on, ON 0.0059, OFF 0.0037
variant, trials from the fourth to the third from last, novel ON: trials 272, r = 0.026 (p = 0.67)
variant, trials from the fourth to the third from last, novel OFF: trials 272, r = -0.055 (p = 0.37)
variant, trials from the fourth to the third from last, familiar ON: trials 941, r = 0.051 (p = 0.12)
variant, trials from the fourth to the third from last, familiar OFF: trials 941, r = -0.051 (p = 0.12)

Result: Partially reproduced, resting on an assumption. Under reading (ii), trials from the fourth on, the correlations are negative for familiar ON (r = -0.065, p = 0.037), familiar OFF (-0.125, p = 6e-05) and novel OFF (-0.145, p = 0.014), and not significant for novel ON (-0.083, p = 0.16): three of four, all smaller than the expected r (-0.15, -0.2, -0.18, -0.23). Under reading (i), all trials, none is negative and significant (familiar ON r = 0.072, p = 0.014; OFF -0.002; novel 0.051 and -0.021), as change points cannot fall in the first trials of a turn. The trial counts (1031 and 288 against the legend's 1029 and 281) favour reading (ii). A change point cannot fall on a turn's last trial either: the last two trials of a session hold 0.0002 to 0.0009 switches per field, against 0.0037 to 0.0080 on the other trials from the fourth on, and with the last two trials also left out no correlation is significant (familiar ON r = 0.051, OFF -0.051, both p = 0.12; novel 0.026 and -0.055). The decrease under reading (ii) rests on these structural zeros at the end of the session.

figs8-speed-no-trend¶

Average locomotion speed does not change as a function of trial, and there is no clear linear relationship between speed and the normalised switching count.

Paper (Results, Factors that affect the rate of switching, paragraph 1; Figure S8A to S8C): "By contrast, average locomotion speed did not change as a function of trial (Figure S8C) ... Nor did we find a clear linear relationship between speed and the normalized (i.e., divided by the number of fields) switching count"

Speed per trial is the mean absolute smoothed velocity of linearised position over forward-locomotion frames; a variant uses all frames of the trial.

In [23]:
# claim:figs8-speed-no-trend
# The paper gives familiar r = 0.01 with p = 3e-11, which needs about 4 x 10^5 samples, and novel
# r = -0.02 with p = 0.78, about 200; the unit of the correlation is not stated. Readings run here:
# (i) per trial, mean speed over forward frames (a variant; the first version's reading);
# (ii) per arm and trial, the GLM's z-scored Speed against its z-scored Trial (familiar only);
# (iii) per trial and position bin, mean speed over forward frames;
# (iv) per frame, forward frames and all trial frames (forward frames: the reading adopted, as the familiar
#      p = 3e-11 with r = 0.01 needs about 4 x 10^5 samples).
# Speed is from the linearised position in every environment; for the familiar maze also from x and y
# (Methods, Behavior segmentation), as the novel figure-8 maze's x and y have no scale.
def zs(x):
    return (x - x.mean()) / x.std()
for fam, g in TR.dropna(subset=["speed_z"]).groupby("familiar"):
    pr = stats.pearsonr(g.trial_z, g.speed_z)
    print(f"(i) {'familiar' if fam else 'novel'}: speed (z-scored) against trial, trials {len(g)}, Pearson r = {pr[0]:.3f}, p = {pr[1]:.2g}; speed range {g.speed.min():.1f} to {g.speed.max():.1f} cm/s")
pr = stats.pearsonr(G.Trial, G.Speed)
print(f"(ii) familiar, arm x trial rows of the GLM ({len(G)}, trials from the fourth on): r = {pr[0]:.3f}, p = {pr[1]:.2g}")
fr_rows = []
for r, o in sw.iter_tasks(res):
    ft = o["frame_trial"]; m = ft >= 0
    sp = np.abs(o["v"]).astype(float)
    d = pd.DataFrame(dict(trial=ft[m], fwd=o["forward"][m], bin=o["pbin"][m], sp=sp[m]))
    if "xy" in o:
        ok = np.all(np.isfinite(o["xy"]), 1)
        sxy = sw.xy_speed(o["t"], np.where(ok[:, None], o["xy"], 0).astype(float))
        d["sp_xy"] = np.where(ok, sxy, np.nan)[m]
    d["session"] = r["session"]; d["familiar"] = o["familiar"]
    fr_rows.append(d)
FR = pd.concat(fr_rows, ignore_index=True)

res_s8 = []
for fam, g in FR.groupby("familiar"):
    lab = "familiar" if fam else "novel"
    for name, sel in (("forward frames", g.fwd.values), ("all trial frames", np.ones(len(g), bool))):
        h = g[sel].copy()
        h["tz"] = h.groupby("session").trial.transform(zs)
        for col in (["sp", "sp_xy"] if fam else ["sp"]):
            h2 = h.dropna(subset=[col]).copy()
            h2["z"] = h2.groupby("session")[col].transform(zs)
            pr = stats.pearsonr(h2.tz, h2.z)
            print(f"(iv) {lab}, per frame, {name}, speed from {'x and y' if col == 'sp_xy' else 'linearised position'}: frames {len(h2)}, r = {pr[0]:.3f}, p = {pr[1]:.2g}")
            res_s8.append(dict(reading="frame " + name, env=lab, speed=col, n=len(h2), r=pr[0], p=pr[1]))
    h = g[g.fwd.values]
    for col in (["sp", "sp_xy"] if fam else ["sp"]):
        tb = h.groupby(["session", "trial", "bin"])[col].mean().reset_index().dropna()
        tb["tz"] = tb.groupby("session").trial.transform(zs); tb["z"] = tb.groupby("session")[col].transform(zs)
        pr = stats.pearsonr(tb.tz, tb.z)
        print(f"(iii) {lab}, per trial and position bin, forward frames, speed from {'x and y' if col == 'sp_xy' else 'linearised position'}: {len(tb)} trial-bins, r = {pr[0]:.3f}, p = {pr[1]:.2g}")
        res_s8.append(dict(reading="trial x bin", env=lab, speed=col, n=len(tb), r=pr[0], p=pr[1]))
    if fam:
        tm = h.groupby(["session", "trial"]).sp_xy.mean().reset_index().dropna()
        tm["tz"] = tm.groupby("session").trial.transform(zs); tm["z"] = tm.groupby("session").sp_xy.transform(zs)
        pr = stats.pearsonr(tm.tz, tm.z)
        print(f"(i) familiar, per trial, speed from x and y over forward frames: trials {len(tm)}, r = {pr[0]:.3f}, p = {pr[1]:.2g}")
        res_s8.append(dict(reading="trial", env=lab, speed="sp_xy", n=len(tm), r=pr[0], p=pr[1]))
S8 = pd.DataFrame(res_s8)
print("readings with r within the tolerance (familiar 0.01 +- 0.05, novel -0.02 +- 0.05):")
S8["in_tol"] = np.where(S8.env == "familiar", (S8.r - 0.01).abs() <= 0.05, (S8.r + 0.02).abs() <= 0.05)
print(S8.round(4).to_string())
# speed against the normalised switch count (Figure S8A, S8B)
g = G[G.N_field > 0].copy()
for k in ("on", "off"):
    g[k + "_norm"] = g[k] / g.N_field
    pr = stats.pearsonr(g.Speed_raw, g[k + "_norm"])
    print(f"familiar arm x trial rows with fields ({len(g)}): normalised switch {k.upper()} against mean speed in the arm, Pearson r = {pr[0]:.3f}, p = {pr[1]:.2g}")
# variant: speed over all frames of the trial (not only forward locomotion), per trial
sa = []
for r, o in sw.iter_tasks(res):
    b = o["beh"].copy(); b["familiar"] = o["familiar"]; b["session"] = r["session"]
    sa.append(b)
SA = pd.concat(sa)
SA["trial_z"] = SA.groupby(["session", "familiar"]).trial.transform(zs)
SA["sp_z"] = SA.groupby(["session", "familiar"]).speed_all.transform(zs)
for fam, g in SA.dropna(subset=["sp_z"]).groupby("familiar"):
    pr = stats.pearsonr(g.trial_z, g.sp_z)
    print(f"variant, per trial, speed over all trial frames, {'familiar' if fam else 'novel'}: r = {pr[0]:.3f}, p = {pr[1]:.2g}")
(i) novel: speed (z-scored) against trial, trials 312, Pearson r = -0.148, p = 0.0086; speed range 2.4 to 25.1 cm/s
(i) familiar: speed (z-scored) against trial, trials 1166, Pearson r = 0.154, p = 1.3e-07; speed range 1.0 to 22.1 cm/s
(ii) familiar, arm x trial rows of the GLM (5117, trials from the fourth on): r = 0.006, p = 0.67
(iv) novel, per frame, forward frames, speed from linearised position: frames 130271, r = -0.052, p = 6.1e-78
(iv) novel, per frame, all trial frames, speed from linearised position: frames 308509, r = -0.105, p = 0
(iii) novel, per trial and position bin, forward frames, speed from linearised position: 15528 trial-bins, r = -0.035, p = 1.3e-05
(iv) familiar, per frame, forward frames, speed from linearised position: frames 953688, r = 0.042, p = 0
(iv) familiar, per frame, forward frames, speed from x and y: frames 953688, r = 0.038, p = 9.5e-295
(iv) familiar, per frame, all trial frames, speed from linearised position: frames 2279173, r = -0.024, p = 8.5e-294
(iv) familiar, per frame, all trial frames, speed from x and y: frames 2279173, r = -0.033, p = 0
(iii) familiar, per trial and position bin, forward frames, speed from linearised position: 104782 trial-bins, r = 0.031, p = 2.3e-24
(iii) familiar, per trial and position bin, forward frames, speed from x and y: 104782 trial-bins, r = 0.027, p = 5.5e-19
(i) familiar, per trial, speed from x and y over forward frames: trials 1166, r = 0.136, p = 3.4e-06
readings with r within the tolerance (familiar 0.01 +- 0.05, novel -0.02 +- 0.05):
                  reading       env  speed        n       r    p  in_tol
0    frame forward frames     novel     sp   130271 -0.0517  0.0    True
1  frame all trial frames     novel     sp   308509 -0.1046  0.0   False
2             trial x bin     novel     sp    15528 -0.0350  0.0    True
3    frame forward frames  familiar     sp   953688  0.0417  0.0    True
4    frame forward frames  familiar  sp_xy   953688  0.0376  0.0    True
5  frame all trial frames  familiar     sp  2279173 -0.0243  0.0    True
6  frame all trial frames  familiar  sp_xy  2279173 -0.0328  0.0    True
7             trial x bin  familiar     sp   104782  0.0315  0.0    True
8             trial x bin  familiar  sp_xy   104782  0.0275  0.0    True
9                   trial  familiar  sp_xy     1166  0.1355  0.0   False
familiar arm x trial rows with fields (5104): normalised switch ON against mean speed in the arm, Pearson r = -0.015, p = 0.29
familiar arm x trial rows with fields (5104): normalised switch OFF against mean speed in the arm, Pearson r = -0.031, p = 0.025
variant, per trial, speed over all trial frames, novel: r = -0.261, p = 2.8e-06
variant, per trial, speed over all trial frames, familiar: r = -0.082, p = 0.005

Result: Reproduced, resting on an assumption: the unit of the speed-trial correlation. The paper's familiar r = 0.01 with p = 3e-11 needs about 4 x 10^5 samples, which fits a correlation over position samples and not over trials (its novel p = 0.78 fits about 200 samples, so the paper's two values do not agree on a unit). Per frame of forward locomotion, the reading adopted, r = 0.042 (953688 frames) in familiar and -0.052 (130271) in novel sessions, both within the tolerance of 0.01 +- 0.05 and -0.02 +- 0.05; with speed from x and y in familiar sessions, r = 0.038. Per trial and position bin, r = 0.031 and -0.035, also within; per arm and trial (the GLM rows, familiar), r = 0.006. Per trial, as in the first version, r = 0.154 (1166 trials) and -0.148 (312), outside, and per frame over all trial frames novel r = -0.105, outside. The second part holds under every reading: the normalised switch count per arm and trial is not clearly related to speed (ON r = -0.015, p = 0.29; OFF r = -0.031, p = 0.025; both below 0.1 in size).

fig4no-head-scans-not-related¶

Most head scans occur in the reward area and few in the central arm, and there is no reliable relationship between field switching and the incidence of head scanning.

Paper (Results, Factors that affect the rate of switching, paragraph 2; Figure 4L to 4O): "most head scans were detected in the reward area (position 50, between green and red sections), while head scans in the central arm were rare (Figures 4N and 4O). We found no reliable relationship between field switching and incidence of head scanning"

Head scans as in the Methods, with one track per turn for the distance to the track (both turns share the linearised coordinate; with one averaged track the side arms all read as off-track). Per position bin, the number of trials with a head scan starting in the bin and the number with a switch of a field peaking in the bin.

In [24]:
# claim:fig4no-head-scans-not-related
hs_rows, sw_rows = [], []
for r, o in sw.iter_tasks(res):
    if not o["familiar"] or "xy" not in o:
        continue
    turn = np.where(o["frame_trial"] >= 0, o["trials"].trial_type.values[np.clip(o["frame_trial"], 0, None)], "none")
    ev = sw.head_scans(o["t"], o["xy"].astype(float), o["lin"].astype(float), o["frame_trial"], turn)
    nb = o["nbins"]
    for a, b in ev:
        tri = int(o["frame_trial"][a])
        if tri < 0:
            continue
        pb = int(np.clip(np.searchsorted(o["edges"], o["lin"][a]) - 1, 0, nb - 1))
        hs_rows.append(dict(session=r["session"], trial=tri, bin=pb, dur=o["t"][b] - o["t"][a]))
    for f in o["fields"]:
        for kind in ("on", "off"):
            for t in sw.switch_trials(f, kind):
                sw_rows.append(dict(session=r["session"], trial=t, bin=f["peak_bin"], kind=kind))
HS = pd.DataFrame(hs_rows); SWp = pd.DataFrame(sw_rows)
print("head scans:", len(HS), "in", HS.session.nunique(), "sessions; duration median %.2f s" % HS.dur.median())
hs_tr = HS.drop_duplicates(["session", "trial", "bin"]).groupby("bin").size().reindex(range(100), fill_value=0)
seg = pd.Series([seg_of_bin(res[0]["tasks"][0], b) for b in range(100)], index=range(100))
print("bin with most head-scan trials:", int(hs_tr.idxmax()), f"({hs_tr.max()} trials, at {sw.BIN_CM * (hs_tr.idxmax() + 0.5):.0f} cm, segment {seg[hs_tr.idxmax()]})")
by_seg = hs_tr.groupby(seg).sum()
per_bin = hs_tr.groupby(seg).sum() / seg.value_counts()
print("head-scan trials per segment:", by_seg.to_dict(), "| bins per segment:", seg.value_counts().to_dict(), "| per bin:", per_bin.round(2).to_dict())
print("central arm below every other segment: in totals", bool((by_seg.drop("central") > by_seg["central"]).all()), "| per bin", bool((per_bin.drop("central") > per_bin["central"]).all()))
for kind in ("on", "off"):
    st = SWp[SWp.kind == kind].drop_duplicates(["session", "trial", "bin"]).groupby("bin").size().reindex(range(100), fill_value=0)
    pr = stats.pearsonr(hs_tr.values, st.values)
    print(f"switch {kind.upper()} trials per bin against head-scan trials per bin: r = {pr[0]:.3f}, p = {pr[1]:.2g}")
    # same trial and bin (within 5 bins) coincidences
    m = SWp[SWp.kind == kind].merge(HS, on=["session", "trial"], suffixes=("_sw", "_hs"))
    print(f"   switches with a head scan on the same trial within 5 bins: {int(((m.bin_sw - m.bin_hs).abs() <= 5).groupby([m.session, m.trial, m.bin_sw]).any().sum())} of {len(SWp[SWp.kind == kind])}")
head scans: 3149 in 45 sessions; duration median 2.47 s
bin with most head-scan trials: 50 (289 trials, at 111 cm, segment return_side)
head-scan trials per segment: {'central': 253, 'choice': 579, 'delay': 160, 'pre_delay': 346, 'return_side': 1538} | bins per segment: {'return_side': 33, 'central': 26, 'choice': 17, 'delay': 16, 'pre_delay': 8} | per bin: {'central': 9.73, 'choice': 34.06, 'delay': 10.0, 'pre_delay': 43.25, 'return_side': 46.61}
central arm below every other segment: in totals False | per bin True
switch ON trials per bin against head-scan trials per bin: r = 0.262, p = 0.0085
   switches with a head scan on the same trial within 5 bins: 345 of 1552
switch OFF trials per bin against head-scan trials per bin: r = 0.099, p = 0.33
   switches with a head scan on the same trial within 5 bins: 239 of 948

Result: Partially reproduced, resting on an assumption: that the central arm's head scans are compared per position bin. 3149 head scans were found in 45 familiar sessions. The bin with most head-scan trials is bin 50 (111 cm, 289 trials), the paper's "position 50, between green and red sections"; it is the first bin past the 111 cm cut, in the return side arm (cell above), just past the end of the choice arm. Per bin, the central arm has the fewest head-scan trials (9.73 against 10.0 in the delay zone and 34.1 to 46.6 elsewhere); in totals it has 253, more than the delay zone's 160, as the central arm spans 26 bins and the delay zone 16. Figure 4N plots counts per bin, and the segments differ in length, so the comparison per bin is adopted; the margin is small (9.73 against 10.0). Per-bin counts of switch-ON trials are positively correlated with those of head-scan trials (r = 0.262, p = 0.0085; OFF r = 0.099, p = 0.33), so the part on no relationship does not hold. 345 of 1552 switch-ON events have a head scan within 5 bins on the same trial.

figs9-splitter-switching¶

Choice-predicting (splitter) fields on the central arm also switch ON and OFF.

Paper (Results, Factors that affect the rate of switching, paragraph 3; Figure S9): "We found that the splitter feature of hippocampal neurons could also switch ON and OFF at any trial of the session, similar to place fields"

Splitter fields are central-arm fields not merged across turns.

In [25]:
# claim:figs9-splitter-switching
sp = FD.copy()
print(sp.groupby(["familiar", "splitter"]).agg(fields=("sw", "size"), switching=("sw", "mean"), on=("on", "mean"), off=("off", "mean")).round(3).to_string())
thirds = []
for r, o in sw.iter_tasks(res):
    n = len(o["trials"])
    for f in o["fields"]:
        if f["splitter"]:
            for kind in ("on", "off"):
                for t in sw.switch_trials(f, kind):
                    thirds.append(dict(kind=kind, third=min(int(3 * t / n), 2)))
TH = pd.DataFrame(thirds)
print("splitter switches by third of the session:", TH.groupby(["kind", "third"]).size().unstack().to_dict("index"))
                   fields  switching     on    off
familiar splitter                                 
False    False       1986      0.319  0.256  0.165
         True         248      0.270  0.181  0.141
True     False       9870      0.175  0.135  0.078
         True        1376      0.147  0.093  0.089
splitter switches by third of the session: {'off': {0: 72, 1: 44, 2: 46}, 'on': {0: 33, 1: 64, 2: 82}}

Result: Reproduced. Of 1376 familiar splitter fields 14.7% switch (ON 9.3%, OFF 8.9%; other fields 17.5%), and of 248 novel splitter fields 27.0% (other fields 31.9%). Splitter switches fall in every third of the session (ON 33, 64 and 82; OFF 72, 44 and 46).

figs13-btsp-signatures¶

On the switch-ON trial, place field width correlates with running speed; the field peak on the following trial shifts backward in the familiar but not significantly in the novel environment; peak rate on the switch trial is not higher than on the next trial; and a significant ramp in rate precedes switch ON.

Paper (Results, Switching exhibits signatures of BTSP, paragraphs 1 and 2; Figure S13A to S13D): "We observed a significant correlation between the place field width and the running speed on the trial when the field switched ON (Figure S13A) ... the distribution skewed toward backward (Figure S13C), although it is not significant in the novel environment"

First switch ON of each field; speed is the trial's mean forward speed; backward is against the running direction.

In [26]:
# claim:figs13-btsp-signatures
s13 = []
for r, o in sw.iter_tasks(res):
    beh = o["beh"].set_index("trial")
    rm = sw.trial_rowmap(o)
    for f in o["fields"]:
        if not f["sw"]["on"]:
            continue
        c = f["sw"]["on"][0]  # first switch ON of the field
        t0 = int(f["trials"][c])
        tt, k = rm[t0]
        prof = o["maps"][tt][f["cell"], k, f["start"]:f["end"] + 1].astype(float)
        pk = int(np.argmax(prof)); half = prof >= prof[pk] / 2
        a = pk
        while a > 0 and half[a - 1]: a -= 1
        b = pk
        while b < len(prof) - 1 and half[b + 1]: b += 1
        sign = 1.0
        if o["kind"] == "linearMaze" and tt == "neg":
            sign = -1.0  # running toward lower positions: backward is a positive change
        d = dict(familiar=o["familiar"], speed=beh.speed.get(t0, np.nan), width_field=f["end"] - f["start"] + 1,
                 width_half=b - a + 1, peak_bin=f["peak_bin"], nbins=o["nbins"],
                 pk_shift=sign * (f["loc"][c + 1] - f["loc"][c]) if c + 1 < len(f["loc"]) else np.nan)
        x = np.asarray(f["rate"], float)
        for lab, norm in (("max", x.max()), ("mean", x.mean())):
            for rel in range(-3, 3):
                d[f"{lab}_{rel}"] = x[c + rel] / norm if 0 <= c + rel < len(x) and norm > 0 else np.nan
        s13.append(d)
S13 = pd.DataFrame(s13)
print("first switch-ON events:", S13.groupby("familiar").size().to_dict())
for fam, g in S13.groupby("familiar"):
    g = g.dropna(subset=["speed"])
    for wcol in ("width_field", "width_half"):
        pr = stats.pearsonr(g.speed, g[wcol])
        print(f"(1) {'familiar' if fam else 'novel'} width ({wcol}) against speed on the switch trial: n = {len(g)}, r = {pr[0]:.3f}, p = {pr[1]:.2g}")
gf = S13[S13.familiar].dropna(subset=["speed"]).copy()
gf["sbin"] = pd.cut(gf.peak_bin / gf.nbins, 10, labels=False)
rr = []
for b_, g in gf.groupby("sbin"):
    if len(g) > 3:
        pr = stats.pearsonr(g.speed, g.width_half); rr.append((int(b_), len(g), round(pr[0], 3), round(pr[1], 3)))
print("   familiar, within ten spatial bins (bin, n, r, p) for the half-peak width:", rr)
for fam, g in S13.groupby("familiar"):
    s = g.pk_shift.dropna()
    print(f"(2) {'familiar' if fam else 'novel'} peak shift on the next trial (positive = forward): n = {len(s)}, median {s.median():.2f} bins, mean {s.mean():.2f}, backward {int((s < 0).sum())}, forward {int((s > 0).sum())}, Wilcoxon p = {stats.wilcoxon(s[s != 0]).pvalue:.2g}")
for lab in ("max", "mean"):
    cols = [f"{lab}_{k}" for k in range(-3, 3)]
    g = S13.dropna(subset=cols)
    print(f"(3) rate normalised by the field's {lab}, fields with trials -3 to 2: n = {len(g)}; means", g[cols].mean().round(3).tolist())
    for a_, b_ in [(-3, -2), (-2, -1), (-1, 0), (0, 1), (1, 2)]:
        w = stats.wilcoxon(g[f"{lab}_{a_}"], g[f"{lab}_{b_}"])
        print(f"    trial {a_} against {b_}: p = {w.pvalue:.2g}, median difference {(g[f'{lab}_{b_}'] - g[f'{lab}_{a_}']).median():.3f}")
first switch-ON events: {False: 553, True: 1463}
(1) novel width (width_field) against speed on the switch trial: n = 553, r = 0.255, p = 1.2e-09
(1) novel width (width_half) against speed on the switch trial: n = 553, r = 0.003, p = 0.94
(1) familiar width (width_field) against speed on the switch trial: n = 1463, r = 0.064, p = 0.014
(1) familiar width (width_half) against speed on the switch trial: n = 1463, r = 0.075, p = 0.0043
   familiar, within ten spatial bins (bin, n, r, p) for the half-peak width: [(0, 131, np.float64(0.033), np.float64(0.706)), (1, 129, np.float64(0.212), np.float64(0.016)), (2, 120, np.float64(-0.039), np.float64(0.672)), (3, 179, np.float64(-0.023), np.float64(0.764)), (4, 232, np.float64(0.016), np.float64(0.807)), (5, 174, np.float64(-0.117), np.float64(0.123)), (6, 115, np.float64(0.036), np.float64(0.699)), (7, 143, np.float64(0.214), np.float64(0.01)), (8, 140, np.float64(0.099), np.float64(0.243)), (9, 100, np.float64(0.108), np.float64(0.283))]
(2) novel peak shift on the next trial (positive = forward): n = 553, median 0.00 bins, mean -0.23, backward 243, forward 184, Wilcoxon p = 0.013
(2) familiar peak shift on the next trial (positive = forward): n = 1463, median 0.00 bins, mean -0.25, backward 640, forward 487, Wilcoxon p = 0.00021
(3) rate normalised by the field's max, fields with trials -3 to 2: n = 1640; means [0.21, 0.217, 0.238, 0.732, 0.733, 0.672]
    trial -3 against -2: p = 0.056, median difference 0.000
    trial -2 against -1: p = 1.1e-11, median difference 0.021
    trial -1 against 0: p = 3.2e-269, median difference 0.470
    trial 0 against 1: p = 0.44, median difference 0.005
    trial 1 against 2: p = 4.4e-10, median difference -0.039
(3) rate normalised by the field's mean, fields with trials -3 to 2: n = 1640; means [0.473, 0.496, 0.55, 1.947, 1.947, 1.707]
    trial -3 against -2: p = 0.054, median difference 0.000
    trial -2 against -1: p = 1.4e-11, median difference 0.047
    trial -1 against 0: p = 3.2e-269, median difference 1.124
    trial 0 against 1: p = 0.57, median difference 0.015
    trial 1 against 2: p = 2.7e-10, median difference -0.089

Result: Partially reproduced. Of the five parts, three hold. (1) Width and speed on the switch trial correlate in familiar fields (1463 events; half-peak width r = 0.075, p = 0.0043; field width r = 0.064, p = 0.014); within ten spatial bins 2 of 10 are significant. (2) The next-trial peak shift is backward in familiar fields (640 backward, 487 forward, p = 0.00021), but also in novel ones (243 against 184, p = 0.013), where the paper finds no significant shift. (3) The rate on trial 0 does not differ from trial 1 (p = 0.44 normalised by the maximum, 0.57 by the mean), and it rises from trial -2 to -1 (p = 1.1e-11), but not significantly from -3 to -2 (p = 0.056 and 0.054).

fig5c-switchiness-not-intrinsic¶

Across familiar and novel environments, a neuron's switchiness is not correlated, whereas its CV of within-field peak rate and its lap-to-lap rate map correlation are, after regressing out NREM firing rate.

Paper (Results, Switching, neuron or circuit property, paragraph 1; Figure 5C): "The residuals are significantly correlated across environments for CV of within-field peak firing rate (left, standardized linear regression coefficients t = 4.8, R2 = 0.02, p < 10-5) and lap-lap rate map correlation (middle, t = 7.9, R2 = 0.06; p < 10-14), but not for the explained variance ratio from the change-point model (right, t = 0.9, R2 = 0.0008, p = 0.37)"

Neurons with fields in the familiar and the novel maze of the same session. Each metric is regressed on log10 NREM rate per environment, and the novel residual on the familiar residual, standardised.

In [27]:
# claim:fig5c-switchiness-not-intrinsic, fig5d-nrem-rate-relations
def neuron_metrics(o):
    """Per neuron: noisiness (CV of per-trial peak rate, mean over fields), shiftiness (rate-map
    correlation between trial pairs within a turn, averaged; the code's median as a variant),
    switchiness (R2 of the one-change-point model, mean over fields) (Methods, Metrics of variability)."""
    out = {}
    by_unit = {}
    for f in o["fields"]:
        by_unit.setdefault(f["unit"], []).append(f)
    cell_of = {f["unit"]: f["cell"] for f in o["fields"]}
    for u_, fl in by_unit.items():
        cv = np.mean([np.std(f["rate"]) / np.mean(f["rate"]) for f in fl if np.mean(f["rate"]) > 0])
        swi = np.nanmean([sw.r2_step(f["rate"], 1) for f in fl if np.ptp(f["rate"]) > 0])
        cors = []
        for tt in o["trial_types"]:
            M = o["maps"][tt][cell_of[u_]].astype(float)
            ok = M.std(1) > 0
            if ok.sum() >= 2:
                C = np.corrcoef(M[ok]); cors.append(C[np.triu_indices(ok.sum(), 1)])
        cors = np.concatenate(cors) if cors else np.array([np.nan])
        out[u_] = dict(noisy=cv, shifty=np.nanmean(cors), shifty_median=np.nanmedian(cors), switchy=swi)
    return out
m5 = []
for r in res:
    if r["session"] not in sw.NOVEL_SESSIONS:
        continue
    fam = [o for o in r["tasks"] if o["familiar"]]; nov = [o for o in r["tasks"] if not o["familiar"]]
    mf_, mn_ = neuron_metrics(fam[0]), neuron_metrics(nov[0])
    for u_ in set(mf_) & set(mn_):
        m5.append(dict(session=r["session"], unit=u_, nrem=r["nrem_rate"][u_],
                       **{k + "_fam": v for k, v in mf_[u_].items()}, **{k + "_nov": v for k, v in mn_[u_].items()}))
M5 = pd.DataFrame(m5)
print("neurons with fields in both environments:", len(M5), "| NREM rate zero or missing:", int((~(M5.nrem > 0)).sum()))
M5 = M5[M5.nrem > 0].copy()
M5["lognrem"] = np.log10(M5.nrem)
def stdreg(x, y):
    x = (x - x.mean()) / x.std(); y = (y - y.mean()) / y.std()
    f_ = smapi.OLS(y, smapi.add_constant(x)).fit()
    return f_.tvalues.iloc[1], f_.rsquared, f_.pvalues.iloc[1]
print("neurons used:", len(M5))
for k in ("noisy", "shifty", "switchy", "shifty_median"):
    d = M5.dropna(subset=[k + "_fam", k + "_nov"])
    res_f = smapi.OLS(d[k + "_fam"], smapi.add_constant(d.lognrem)).fit().resid
    res_n = smapi.OLS(d[k + "_nov"], smapi.add_constant(d.lognrem)).fit().resid
    t_, r2_, p_ = stdreg(res_f, res_n)
    print(f"fig5c {k}: n = {len(d)}, novel residual on familiar residual t = {t_:.2f}, R2 = {r2_:.4f}, p = {p_:.2g}")
print()
for k in ("noisy", "shifty", "switchy"):
    for env in ("fam", "nov"):
        d = M5.dropna(subset=[k + "_" + env])
        t_, r2_, p_ = stdreg(d.lognrem, d[k + "_" + env])
        print(f"fig5d {k} {env}: n = {len(d)}, t = {t_:.2f}, p = {p_:.2g}")
neurons with fields in both environments: 1006 | NREM rate zero or missing: 0
neurons used: 1006
fig5c noisy: n = 1006, novel residual on familiar residual t = 6.63, R2 = 0.0419, p = 5.6e-11
fig5c shifty: n = 1006, novel residual on familiar residual t = 9.20, R2 = 0.0777, p = 2e-19
fig5c switchy: n = 1006, novel residual on familiar residual t = 1.31, R2 = 0.0017, p = 0.19
fig5c shifty_median: n = 1006, novel residual on familiar residual t = 9.12, R2 = 0.0765, p = 4e-19

fig5d noisy fam: n = 1006, t = -12.12, p = 1.2e-31
fig5d noisy nov: n = 1006, t = -11.95, p = 7.5e-31
fig5d shifty fam: n = 1006, t = -1.00, p = 0.32
fig5d shifty nov: n = 1006, t = -5.63, p = 2.3e-08
fig5d switchy fam: n = 1006, t = 0.59, p = 0.55
fig5d switchy nov: n = 1006, t = -0.82, p = 0.41

Result: Reproduced. In 1006 neurons (expected 955 +- 96), residual switchiness is not correlated across environments (t = 1.31, R2 = 0.0017, p = 0.19), while noisiness (t = 6.63, R2 = 0.042, p = 5.6e-11) and shiftiness (t = 9.20, R2 = 0.078, p = 2e-19; with the code's median 9.12) are. The two t values are larger than the expected 4.8 and 7.9 and outside their tolerances; the criterion is on significance.

fig5d-nrem-rate-relations¶

Noisiness decreases with log NREM firing rate in both environments, shiftiness is related to it in the novel environment only, and switchiness is not related to it.

Paper (Figure 5D): "noisy: familiar, t = -11.1, p = 3.6 × 10-27; novel, t = -12.6, p = 1.5 × 10-33; shifty: familiar, t = -0.8, p = 0.4; novel, t = -3.6, p = 0.000326; switchy: familiar, t = 0.9, p = 0.4; novel, t = -0.6, p = 0.5"

The same 1006 neurons, each metric regressed on log10 NREM rate.

The cell of the previous section prints the numbers for this claim.

Result: Reproduced. All six regressions match the paper in sign and significance: noisiness familiar t = -12.12 (p = 1.2e-31) and novel -11.95 (p = 7.5e-31); shiftiness familiar -1.00 (p = 0.32) and novel -5.63 (p = 2.3e-08); switchiness familiar 0.59 (p = 0.55) and novel -0.82 (p = 0.41).

multifield-independent-switching¶

Of 781 pairs of switching place fields belonging to the same place cell, only 41 (5%) switched on the same trial.

Paper (Results, Switching, neuron or circuit property, paragraph 2; Figure 5E): "Of 781 place field pairs that belonged to the same place cell and both switched, only 41 (5%) switched on the same trial"

Pairs of switching fields of the same neuron in the same session and turn (merged fields pair with either turn); same trial means a switch of each on the same trial.

In [28]:
# claim:multifield-independent-switching
mf = []
for r, o in sw.iter_tasks(res):
    swf = [f for f in o["fields"] if sw.has_switch(f)]
    for a in range(len(swf)):
        for b in range(a + 1, len(swf)):
            fa, fb = swf[a], swf[b]
            if fa["unit"] != fb["unit"]:
                continue
            if not (fa["trial_type"] == fb["trial_type"] or "both" in (fa["trial_type"], fb["trial_type"])):
                continue
            on_a, on_b = set(sw.switch_trials(fa, "on")), set(sw.switch_trials(fb, "on"))
            off_a, off_b = set(sw.switch_trials(fa, "off")), set(sw.switch_trials(fb, "off"))
            mf.append(dict(familiar=o["familiar"], same_any=bool((on_a | off_a) & (on_b | off_b)),
                           same_type=bool((on_a & on_b) | (off_a & off_b))))
MF = pd.DataFrame(mf)
for name, g in [("familiar and novel", MF), ("familiar only", MF[MF.familiar])]:
    print(f"{name}: pairs {len(g)}, same trial (any switch) {int(g.same_any.sum())} ({g.same_any.mean():.3f}), same trial and type {int(g.same_type.sum())} ({g.same_type.mean():.3f})")
# variant: pairs of switching fields of the same neuron anywhere in the maze task (turns not required to match)
mf2 = []
for r, o in sw.iter_tasks(res):
    swf = [f for f in o["fields"] if sw.has_switch(f)]
    for a in range(len(swf)):
        for b in range(a + 1, len(swf)):
            if swf[a]["unit"] == swf[b]["unit"]:
                ta = set(sw.switch_trials(swf[a], "on")) | set(sw.switch_trials(swf[a], "off"))
                tb = set(sw.switch_trials(swf[b], "on")) | set(sw.switch_trials(swf[b], "off"))
                mf2.append(dict(familiar=o["familiar"], same=bool(ta & tb)))
MF2 = pd.DataFrame(mf2)
print(f"variant, any turn: pairs {len(MF2)}, same trial {int(MF2.same.sum())} ({MF2.same.mean():.3f}); familiar only {int(MF2.familiar.sum())} pairs")
familiar and novel: pairs 283, same trial (any switch) 37 (0.131), same trial and type 22 (0.078)
familiar only: pairs 229, same trial (any switch) 33 (0.144), same trial and type 20 (0.087)
variant, any turn: pairs 637, same trial 37 (0.058); familiar only 447 pairs

Result: Not reproduced. There are 283 such pairs (229 familiar), against the expected 781 +- 78, and 37 (13.1%) switch on the same trial (22 with the same type), against 41 +- 4. Pairing fields of a neuron across turns as well gives 637 pairs, 37 (5.8%) on the same trial. The paper's share of 5% is close to the variant's, but neither count is within tolerance under a reading. With the trial-averaged map there are 262 pairs and 32 on the same trial.

figs12-stability-after-switch-on¶

Fields that switched ON have a lower CV of peak rate over the five trials after the switch than non-switching fields over five trials from the start or middle of the session, in familiar and novel environments; their peak location is also less jittery, except against the middle window in the novel environment (p = 0.4).

Paper (Results, Switching, neuron or circuit property, paragraph 2; Figure S12A, S12B, S12D, S12E): "Specifically, switch-ON fields had lower CV of firing rates within the five trials after the switch, relative to trial-to-trial variability in non-switching fields over five trials taken either from the beginning or from the middle of the session"

Place cells with spatial information above 0.5 bit/spike in the field's turn; fields with a per-trial peak above 1 Hz on 90% of the trials used (the five post-switch trials for switch-ON fields, all trials for non-switching fields); switch-ON fields with one switch and no OFF; location in bins.

The code's stored outputs that the code_mismatch finding on the windows rests on (tag v0.0, place_variability/jupyter/[fig] stability after pop up.ipynb, not under paper/): the cell with nosw_start_frac = 0.5 prints the non-switching familiar medians peak_std 2.049390 and fr_peak_cv 0.365340, and the cell with nosw_start_frac = 0 prints 2.280351 and 0.402153. In stability_analysis.get_sw_no_sw_pf_par_var_control_ntrial, min_size = int(len(row_dropna) * nosw_start_frac) is the trial the non-switching window starts at, so 0.5 starts it at the middle trial and 0 at the first. The legend gives 0.365 and 2.05 for the start of the session and 0.40 and 2.28 for the middle.

In [29]:
# claim:figs12-stability-after-switch-on
# Selections. (S1) the first version of this notebook: switched ON once and never OFF, all five
# trials after the switch above 1 Hz; non-switching fields have no switch, peak above 1 Hz on at
# least 90% of trials and at least 10 trials (an assumption of the first version). (S2) the code's
# (stability_analysis.get_sw_no_sw_pf_par_var_control_ntrial): exactly one switch ON, OFF allowed,
# no rate filter on the switch-ON fields; non-switching fields have no switch ON (OFF allowed) and
# a peak above 1 Hz on more than 90% of trials; a window that does not fit is dropped. (S3) as S2
# with non-switching fields that have no switch of either kind (the legend's "non-switching").
# Place cells with spatial information above 0.5 bit/spike (Figure S12 legend) in all three.
# Windows for non-switching fields: start (trials 0 to 4), middle (a) centred on the midpoint,
# middle (b) from the midpoint int(n / 2) (the code's nosw_start_frac = 0.5).
s12 = []
for r, o in sw.iter_tasks(res):
    for f in o["fields"]:
        tts = [f["trial_type"]] if f["trial_type"] != "both" else list(o["trial_types"])
        si = max(o["si"][t][f["cell"]] for t in tts)
        if si <= 0.5:
            continue
        x, loc, n = f["rate"], f["loc"], len(f["rate"])
        s = f["sw"]
        def add(sel, group, w):
            s12.append(dict(sel=sel, familiar=o["familiar"], group=group, cv=x[w].std() / x[w].mean(), sd=loc[w].std()))
        if len(s["on"]) == 1:
            c = max(s["on"][0], 2)
            if c + 5 <= n:
                if not s["off"] and (x[c:c + 5] > 1).mean() >= 0.9:
                    add("S1", "switch ON", slice(c, c + 5))
                add("S2", "switch ON", slice(c, c + 5)); add("S3", "switch ON", slice(c, c + 5))
        wins = [("start", 0), ("middle (a) centred", n // 2 - 2), ("middle (b) from midpoint", n // 2)]
        if not (s["on"] or s["off"]) and n >= 10 and (x > 1).mean() >= 0.9:
            for name, a in wins:
                if a + 5 <= n: add("S1", name, slice(a, a + 5))
        if not s["on"] and (x > 1).mean() > 0.9:
            for name, a in wins:
                if a + 5 <= n:
                    add("S2", name, slice(a, a + 5))
                    if not s["off"]: add("S3", name, slice(a, a + 5))
S12 = pd.DataFrame(s12)
print(S12.groupby(["sel", "familiar", "group"]).agg(n=("cv", "size"), median_cv=("cv", "median"), median_sd=("sd", "median")).round(3).to_string())
for (sel, fam), g in S12.groupby(["sel", "familiar"]):
    on = g[g.group == "switch ON"]
    for name in ("start", "middle (a) centred", "middle (b) from midpoint"):
        ns_ = g[g.group == name]
        print(f"{sel} {'familiar' if fam else 'novel'}, switch ON against non-switching {name}: CV rank-sum p = {stats.ranksums(on.cv, ns_.cv).pvalue:.2g} (ON lower: {on.cv.median() < ns_.cv.median()}),"
              f" location SD p = {stats.ranksums(on.sd, ns_.sd).pvalue:.2g} (ON lower: {on.sd.median() < ns_.sd.median()})")
# medians against the expected values, under each selection and middle reading, and with the
# windows swapped (the code's stored outputs give the legend's "start" medians, 0.365 and 2.05,
# from nosw_start_frac = 0.5, and its "middle" medians, 0.40 and 2.28, from the first trials)
exp = {("start", True): (0.365, 2.05), ("start", False): (0.37, 2.4), ("middle", True): (0.40, 2.28), ("middle", False): (0.46, 2.68),
       ("switch ON", True): (0.283, 1.64), ("switch ON", False): (0.33, 1.95)}
rows = []
for sel in ("S1", "S2", "S3"):
    for mid in ("middle (a) centred", "middle (b) from midpoint"):
        for swap in (False, True):
            k_in = 0
            for fam in (True, False):
                g = S12[(S12.sel == sel) & (S12.familiar == fam)]
                for lab, grp in (("switch ON", "switch ON"), ("start", mid if swap else "start"), ("middle", "start" if swap else mid)):
                    h = g[g.group == grp]
                    for j, col in enumerate(("cv", "sd")):
                        e = exp[(lab, fam)][j]
                        k_in += abs(h[col].median() - e) <= 0.1 * e
            rows.append(dict(selection=sel, middle=mid, windows_swapped=swap, medians_within_tolerance=f"{k_in}/12"))
print(pd.DataFrame(rows).to_string())
                                          n  median_cv  median_sd
sel familiar group                                               
S1  False    middle (a) centred         317      0.402      1.939
             middle (b) from midpoint   317      0.376      1.855
             start                      317      0.443      2.417
             switch ON                  129      0.292      1.673
    True     middle (a) centred        2662      0.342      1.673
             middle (b) from midpoint  2662      0.349      1.625
             start                     2662      0.396      2.040
             switch ON                  408      0.233      1.356
S2  False    middle (a) centred         374      0.394      1.939
             middle (b) from midpoint   351      0.381      1.855
             start                      374      0.413      2.366
             switch ON                  226      0.325      1.720
    True     middle (a) centred        2747      0.336      1.673
             middle (b) from midpoint  2701      0.342      1.625
             start                     2747      0.380      2.040
             switch ON                  623      0.263      1.356
S3  False    middle (a) centred         338      0.393      1.939
             middle (b) from midpoint   317      0.376      1.855
             start                      338      0.434      2.482
             switch ON                  226      0.325      1.720
    True     middle (a) centred        2637      0.334      1.673
             middle (b) from midpoint  2595      0.342      1.625
             start                     2637      0.384      2.040
             switch ON                  623      0.263      1.356
S1 novel, switch ON against non-switching start: CV rank-sum p = 4.8e-17 (ON lower: True), location SD p = 9e-11 (ON lower: True)
S1 novel, switch ON against non-switching middle (a) centred: CV rank-sum p = 4.9e-10 (ON lower: True), location SD p = 0.0058 (ON lower: True)
S1 novel, switch ON against non-switching middle (b) from midpoint: CV rank-sum p = 9.5e-08 (ON lower: True), location SD p = 0.046 (ON lower: True)
S1 familiar, switch ON against non-switching start: CV rank-sum p = 2.4e-79 (ON lower: True), location SD p = 6.2e-24 (ON lower: True)
S1 familiar, switch ON against non-switching middle (a) centred: CV rank-sum p = 8.1e-50 (ON lower: True), location SD p = 1.2e-08 (ON lower: True)
S1 familiar, switch ON against non-switching middle (b) from midpoint: CV rank-sum p = 1.4e-53 (ON lower: True), location SD p = 2.7e-08 (ON lower: True)
S2 novel, switch ON against non-switching start: CV rank-sum p = 8.8e-09 (ON lower: True), location SD p = 1.9e-10 (ON lower: True)
S2 novel, switch ON against non-switching middle (a) centred: CV rank-sum p = 1.3e-05 (ON lower: True), location SD p = 0.0062 (ON lower: True)
S2 novel, switch ON against non-switching middle (b) from midpoint: CV rank-sum p = 0.00039 (ON lower: True), location SD p = 0.079 (ON lower: True)
S2 familiar, switch ON against non-switching start: CV rank-sum p = 1.1e-49 (ON lower: True), location SD p = 3.3e-32 (ON lower: True)
S2 familiar, switch ON against non-switching middle (a) centred: CV rank-sum p = 4.8e-26 (ON lower: True), location SD p = 1.1e-11 (ON lower: True)
S2 familiar, switch ON against non-switching middle (b) from midpoint: CV rank-sum p = 9.3e-29 (ON lower: True), location SD p = 1.6e-11 (ON lower: True)
S3 novel, switch ON against non-switching start: CV rank-sum p = 3.5e-11 (ON lower: True), location SD p = 1.2e-11 (ON lower: True)
S3 novel, switch ON against non-switching middle (a) centred: CV rank-sum p = 4.1e-05 (ON lower: True), location SD p = 0.0077 (ON lower: True)
S3 novel, switch ON against non-switching middle (b) from midpoint: CV rank-sum p = 0.0017 (ON lower: True), location SD p = 0.14 (ON lower: True)
S3 familiar, switch ON against non-switching start: CV rank-sum p = 1.1e-51 (ON lower: True), location SD p = 9.4e-33 (ON lower: True)
S3 familiar, switch ON against non-switching middle (a) centred: CV rank-sum p = 5e-25 (ON lower: True), location SD p = 1.2e-11 (ON lower: True)
S3 familiar, switch ON against non-switching middle (b) from midpoint: CV rank-sum p = 3.3e-28 (ON lower: True), location SD p = 3.6e-11 (ON lower: True)
   selection                    middle  windows_swapped medians_within_tolerance
0         S1        middle (a) centred            False                     3/12
1         S1        middle (a) centred             True                     5/12
2         S1  middle (b) from midpoint            False                     3/12
3         S1  middle (b) from midpoint             True                     5/12
4         S2        middle (a) centred            False                     5/12
5         S2        middle (a) centred             True                     5/12
6         S2  middle (b) from midpoint            False                     5/12
7         S2  middle (b) from midpoint             True                     5/12
8         S3        middle (a) centred            False                     5/12
9         S3        middle (a) centred             True                     7/12
10        S3  middle (b) from midpoint            False                     5/12
11        S3  middle (b) from midpoint             True                     7/12

Result: Partially reproduced. Under every selection, switch-ON fields have lower CV and lower location SD than non-switching fields against every window, in familiar and novel sessions. Under S1 (the first version), familiar 408 against 2662 fields (CV p = 2.4e-79 start, 8.1e-50 and 1.4e-53 middle) and novel 129 against 317 (CV p = 4.8e-17, 4.9e-10, 9.5e-08); the novel middle-window location test, expected not significant, is significant (p = 0.0058 and 0.046). Under the code's selection (S2: one switch ON, OFF allowed, no rate filter on the switch-ON fields) the switch-ON groups are 623 and 226 fields, about half the legend's 1230 and 402, and the novel middle-(b) location test is not significant (p = 0.079), as the paper's p = 0.4. The medians do not match: 3 of 12 are within tolerance under S1, 5 under S2, and at most 7 under S3 with the two non-switching windows swapped (the code's stored outputs give the legend's "start" medians from its middle window). Switch-ON CV is 0.233 (S1) or 0.263 (S2) familiar against 0.283, and 0.292 or 0.325 novel against 0.33.

fig6-co-switching¶

Place fields co-switch on the same trial more than expected by chance in a subset of sessions, 17% (ON) and 20% (OFF) of familiar and 57% (ON) and 29% (OFF) of novel sessions.

Paper (Results, Switching, neuron or circuit property, paragraph 3; Figure 6D and 6E): "found that 17% (20%) of the familiar sessions and 57% (29%) of the novel sessions showed at least one trial with significant co-switching ON (OFF)"

45 familiar and 7 novel sessions (e13_26m1_211116 novel left out, under 7 trials per turn). The statistic is the number of field pairs switching on the same trial (all field pairs), against 1000 circular shifts of each field's switch trials within trials 2 to n - 2. Seed: the claim's.

In [30]:
# claim:fig6-co-switching, fig6f-switching-asynchronous
def coswitch_tests(rng, nshuf=1000, within_turn=True):
    """Per session, pairs of fields switching ON (OFF) on the same trial (lag 0) and within one
    trial (lag 0 or 1, the code's window variant), against shuffles that shift each field's switch
    trials circularly and independently. within_turn: the shift runs over the field's own trials
    (its turn's trials, or all trials for a merged field), leaving out the first two and the last,
    as the code (test_co_switch.gen_circular_shuffle_trialtype_seperated, which applies
    change_point_analysis.gen_circular_shuffle to each trial type; shift drawn from 0 to span - 2).
    Otherwise the shift runs over all session trials (the first version of this notebook)."""
    out = []
    for r, o in sw.iter_tasks(res):
        tt_n = [len(v) for v in o["trial_types"].values()]
        if min(tt_n) < 7:  # code ntrials_mask; leaves out the novel session with too few trials
            continue
        n = len(o["trials"])
        d = dict(session=r["session"], familiar=o["familiar"], n_trials=n)
        for kind in ("on", "off"):
            ev = []  # per field: (session trials of the field, positions of its switches, lo, hi)
            for f in o["fields"]:
                trs = np.asarray(f["trials"]); nf = len(trs)
                lo, hi = (2, nf - 1) if within_turn else (2, n - 1)
                pos = np.array([c for c in f["sw"][kind] if lo <= c < hi]) if within_turn else \
                      np.array([t for t in sw.switch_trials(f, kind) if lo <= t < hi])
                if len(pos):
                    ev.append((trs if within_turn else np.arange(n), pos, lo, hi))
            m = np.zeros(n, int)
            for trs, pos, lo, hi in ev:
                np.add.at(m, trs[pos], 1)
            pairs = m * (m - 1) // 2
            lag1 = pairs.sum() + int((m[:-1] * m[1:]).sum())
            M = np.zeros((nshuf, n), int)
            for trs, pos, lo, hi in ev:
                span = hi - lo
                sh = rng.integers(max(span - 1, 1), size=nshuf)
                newpos = lo + (pos[None, :] - lo + sh[:, None]) % span
                np.add.at(M, (np.repeat(np.arange(nshuf), len(pos)), trs[newpos].ravel()), 1)
            P = M * (M - 1) // 2
            P1 = P.sum(1) + (M[:, :-1] * M[:, 1:]).sum(1)
            d[f"{kind}_pairs"] = int(pairs.sum())
            d[f"{kind}_p_session"] = float((P.sum(1) >= pairs.sum()).mean())
            d[f"{kind}_pairs_lag1"] = int(lag1)
            d[f"{kind}_p_lag1"] = float((P1 >= lag1).mean())
            pt = (P >= pairs[None]).mean(0)
            d[f"{kind}_sig_session"] = d[f"{kind}_p_session"] < 0.05
            d[f"{kind}_sig_lag1"] = d[f"{kind}_p_lag1"] < 0.05
            d[f"{kind}_sig_trial"] = bool(((pt < 0.05) & (pairs > 0)).any())
        out.append(d)
    return pd.DataFrame(out)
def cs_summary(c):
    return {("fam" if f else "nov"): (int(g.on_sig_session.sum()), int(g.off_sig_session.sum()), int(g.on_sig_trial.sum()), int(g.off_sig_trial.sum()),
                                      int(g.on_sig_lag1.sum()), int(g.off_sig_lag1.sum())) for f, g in c.groupby("familiar")}
CS = coswitch_tests(np.random.default_rng(sw.seed("fig6-co-switching")))
print("sessions:", CS.groupby("familiar").size().to_dict())
for fam, g in CS.groupby("familiar"):
    print(("familiar" if fam else "novel") + ":",
          f"(a) session test: ON {g.on_sig_session.mean():.3f} ({int(g.on_sig_session.sum())}/{len(g)}), OFF {g.off_sig_session.mean():.3f} ({int(g.off_sig_session.sum())}/{len(g)});",
          f"(b) any trial: ON {g.on_sig_trial.mean():.3f} ({int(g.on_sig_trial.sum())}), OFF {g.off_sig_trial.mean():.3f} ({int(g.off_sig_trial.sum())});",
          f"variant, lag 0 or 1, session test: ON {int(g.on_sig_lag1.sum())}, OFF {int(g.off_sig_lag1.sum())}")
print(CS[["session", "familiar", "on_pairs", "on_p_session", "on_p_lag1", "off_pairs", "off_p_session", "off_p_lag1"]].to_string())
print("counts per seed as (a) ON, (a) OFF, (b) ON, (b) OFF, lag-1 ON, lag-1 OFF:")
for k in (1000, 2000, 3000, 4000):
    c = coswitch_tests(np.random.default_rng(sw.seed("fig6-co-switching") + k))
    print(f"   seed + {k}:", cs_summary(c))
# the first version's null, shifts over all session trials, for comparison
CS_all = coswitch_tests(np.random.default_rng(sw.seed("fig6-co-switching") + 1), within_turn=False)
print("variant, shifts over all session trials (turns not respected):", cs_summary(CS_all))
# false-positive rate of each null on synthetic sessions with independent, turn-confined switches
rng_fp = np.random.default_rng(sw.seed("fig6-co-switching") + 2)
def fp_rate(within_turn, nsess=200, nshuf=200):
    hits = 0
    for _ in range(nsess):
        n = 30; trials = {"L": np.arange(0, n, 2), "R": np.arange(1, n, 2)}
        m = np.zeros(n, int); evs = []
        for k in range(60):
            trs = trials["L" if k % 2 else "R"]; nf = len(trs)
            pos = np.array([rng_fp.integers(2, nf - 1)]) if rng_fp.random() < 0.3 else np.array([], int)
            if len(pos):
                evs.append((trs, pos)); m[trs[pos]] += 1
        stat = (m * (m - 1) // 2).sum()
        M = np.zeros((nshuf, n), int)
        for trs, pos in evs:
            lo, hi = (2, len(trs) - 1) if within_turn else (2, n - 1)
            base = pos if within_turn else trs[pos]
            span = hi - lo; sh = rng_fp.integers(span - 1, size=nshuf)
            newp = lo + (base[None, :] - lo + sh[:, None]) % span
            idx = trs[newp] if within_turn else newp
            np.add.at(M, (np.repeat(np.arange(nshuf), len(pos)), idx.ravel()), 1)
        hits += ((M * (M - 1) // 2).sum(1) >= stat).mean() < 0.05
    return hits / nsess
print(f"false-positive rate at 0.05 on 200 synthetic sessions (30 alternating trials, 60 fields, independent switches confined to their turn): within-turn shifts {fp_rate(True):.3f}, shifts over all trials {fp_rate(False):.3f}")
sessions: {False: 7, True: 45}
novel: (a) session test: ON 0.429 (3/7), OFF 0.429 (3/7); (b) any trial: ON 1.000 (7), OFF 0.857 (6); variant, lag 0 or 1, session test: ON 3, OFF 2
familiar: (a) session test: ON 0.222 (10/45), OFF 0.222 (10/45); (b) any trial: ON 0.756 (34), OFF 0.622 (28); variant, lag 0 or 1, session test: ON 7, OFF 9
            session  familiar  on_pairs  on_p_session  on_p_lag1  off_pairs  off_p_session  off_p_lag1
0   e13_16f1_210302      True        64         0.577      0.851         27          0.384       0.151
1   e13_16f1_210312      True        30         0.759      0.795          4          0.513       0.274
2   e13_16f1_210314      True        30         0.071      0.042          8          0.231       0.634
3   e13_16f1_210317      True        10         0.124      0.452          2          0.710       0.999
4   e13_16f1_210319      True        24         0.059      0.275          1          0.963       0.567
5   e13_16f1_210322      True        42         0.124      0.064          2          0.884       0.787
6   e13_16f1_210328      True       104         0.160      0.092          7          0.639       0.370
7   e13_16f1_210331      True        17         0.659      0.308          6          0.255       0.872
8   e13_26m1_211019      True       101         0.022      0.012        396          0.000       0.000
9   e13_26m1_211019     False       315         0.001      0.000         98          0.004       0.001
10  e13_26m1_211116      True        83         0.248      0.499         25          0.275       0.967
11  e13_26m1_211119      True        74         0.898      0.609         16          0.724       0.483
12  e13_26m1_211119     False        69         0.311      0.854         24          0.595       0.298
13  e13_26m1_211124      True        50         0.111      0.449         12          0.736       0.891
14   e14_2m2_201017      True         4         0.059      0.127        137          0.000       0.000
15   e14_2m2_201019      True        34         0.776      0.681          0          1.000       0.937
16   e14_2m3_201118      True         7         0.856      0.887          7          0.014       0.106
17   e14_2m3_201121      True         8         0.624      0.318          0          1.000       0.936
18   e14_2m3_201125      True        10         0.010      0.149          0          1.000       0.752
19   e14_2m3_201129      True         8         0.198      0.800          4          0.247       0.323
20   e14_2m3_201206      True         6         0.444      0.359         13          0.000       0.000
21   e14_2m3_201208      True         9         0.016      0.073          5          0.230       0.244
22  e15_10m1_200727      True        11         0.190      0.797          7          0.398       0.198
23  e15_10m1_200803      True         5         0.971      0.776          6          0.018       0.001
24  e15_10m1_200809      True         4         0.806      0.205          3          0.455       0.608
25  e15_10m1_200812      True        15         0.072      0.295          3          0.610       0.676
26  e15_13f1_220117      True       349         0.404      0.706        104          0.487       0.073
27  e15_13f1_220118      True       274         0.001      0.003         43          0.303       0.547
28  e15_13f1_220118     False       219         0.001      0.000         99          0.057       0.004
29  e15_13f1_220119      True       313         0.000      0.000         80          0.279       0.046
30  e15_13f1_220119     False       139         0.505      0.441         82          0.002       0.289
31  e15_13f1_220120      True       195         0.042      0.260         49          0.024       0.166
32  e15_13f1_220120     False        68         0.210      0.098         29          0.565       0.480
33   e15_9f1_200715      True         7         0.271      0.090          4          0.197       0.542
34   e15_9f1_200720      True        11         0.292      0.081          2          0.547       0.246
35   e15_9f1_200723      True         3         0.241      0.911          2          0.745       0.182
36   e15_9f1_200729      True         5         0.350      0.222          8          0.088       0.111
37   e15_9f1_200802      True         3         0.901      0.967          1          0.942       0.698
38   e16_1f1_200918      True        10         0.007      0.572          1          0.628       0.523
39   e16_1f1_200919      True         0         1.000      0.689          3          0.027       0.005
40   e16_1f1_200920      True         4         0.490      0.562          5          0.075       0.073
41   e16_1f1_200923      True         4         0.912      0.910          2          0.946       0.778
42   e16_1f1_201004      True         2         0.602      0.190          7          0.056       0.375
43   e16_2m1_201121      True         4         0.573      0.569          0          1.000       0.467
44   e16_3m1_210119      True        48         0.404      0.218         24          0.021       0.006
45   e16_3m1_210201      True        47         0.092      0.169         16          0.607       0.852
46   e16_3m1_210203      True        25         0.395      0.184         17          0.183       0.053
47   e16_3m2_211210      True        73         0.041      0.010         30          0.025       0.022
48   e16_3m2_211212      True       120         0.000      0.007         48          0.078       0.099
49   e16_3m2_211212     False        32         0.057      0.157          5          0.546       0.629
50   e16_3m2_211213      True        87         0.003      0.000         75          0.005       0.029
51   e16_3m2_211213     False        95         0.016      0.005         62          0.019       0.450
counts per seed as (a) ON, (a) OFF, (b) ON, (b) OFF, lag-1 ON, lag-1 OFF:
   seed + 1000: {'nov': (4, 3, 7, 5, 3, 2), 'fam': (10, 10, 35, 28, 7, 9)}
   seed + 2000: {'nov': (3, 3, 7, 5, 3, 2), 'fam': (11, 10, 34, 26, 7, 9)}
   seed + 3000: {'nov': (3, 3, 7, 7, 3, 2), 'fam': (10, 11, 34, 27, 7, 9)}
   seed + 4000: {'nov': (3, 3, 7, 5, 3, 2), 'fam': (10, 11, 36, 29, 7, 9)}
variant, shifts over all session trials (turns not respected): {'nov': (4, 4, 7, 5, 4, 2), 'fam': (18, 14, 37, 29, 11, 14)}
false-positive rate at 0.05 on 200 synthetic sessions (30 alternating trials, 60 fields, independent switches confined to their turn): within-turn shifts 0.035, shifts over all trials 0.060

Result: Not reproduced. With each field's switch trials shifted within its own turn's trials, as the code does, reading (a), the session test, gives 10 of 45 familiar sessions (0.222) co-switching ON and 10 (0.222) OFF, against the expected 0.17 and 0.20 (about 8 and 9 sessions); novel 3 of 7 for each, against 4 and 2. The familiar OFF and both novel fractions are within one session of the expected count; familiar ON is two sessions above it. Reading (b), any significant trial, gives higher fractions (familiar 0.756 and 0.622; novel 7 and 6 of 7). Under the four other seeds reading (a) gives 10 to 11 familiar sessions ON, the same outcome. The code's lag-1 window, a variant, gives 7 and 9 familiar and 3 and 2 novel sessions, all within one session of the expected counts. The first version's null, shifts over all session trials, gave 18 and 14 familiar sessions here; on synthetic sessions with independent switches confined to their turn it rejects at 0.060 at the 0.05 level, against 0.035 for the within-turn shifts.

fig6f-switching-asynchronous¶

On each trial only a small subset of place fields, up to 5%, switch ON or OFF, so switching is largely asynchronous.

Paper (Results, Switching, neuron or circuit property, paragraph 3; Figure 6F): "We found that in each trial, a small subset of the place fields (up to 5%) switched ON/OFF"

Trials 2 to n - 3 of each session and environment.

In [31]:
# claim:fig6f-switching-asynchronous
ff = []
for r, o in sw.iter_tasks(res):
    n = len(o["trials"]); nF = len(o["fields"])
    for kind in ("on", "off"):
        c = pd.Series([t for f in o["fields"] for t in sw.switch_trials(f, kind)]).value_counts()
        for t in range(2, n - 2):  # leaving out the first and last two trials (Figure 6F legend)
            ff.append(dict(familiar=o["familiar"], kind=kind, frac=c.get(t, 0) / nF))
FF = pd.DataFrame(ff)
print(FF.groupby(["familiar", "kind"]).frac.agg(n="size", mean="mean", p95=lambda x: x.quantile(0.95), max="max").round(4).to_string())
                 n    mean     p95     max
familiar kind                             
False    off   280  0.0052  0.0156  0.0667
         on    280  0.0078  0.0226  0.0367
True     off   986  0.0036  0.0129  0.0904
         on    986  0.0058  0.0183  0.0548

Result: Reproduced. The 95th percentile over trials of the fraction of fields switching is 0.0183 ON and 0.0129 OFF in familiar sessions (986 trials) and 0.0226 and 0.0156 in novel (280), all below 0.055. The largest single-trial fractions are 0.055 and 0.090 (familiar) and 0.037 and 0.067 (novel).

figs14-preexisting-fields-ephys¶

For fields whose rate before switching ON (after switching OFF) is below the detection threshold (60% of ON and 20% of OFF switches), within-field firing is already elevated over the surrounding rate before emergence and stays elevated after disappearance, for most neurons.

Paper (Results, Pre-existing dynamics bias switching, paragraph 2; Figure S14): "Indeed, we found that, even before the emergence of the new place field, the firing rates within the future place fields were already elevated relative to the mean rate recorded outside of the future place field for the majority of the neurons ... Similarly, the firing rates remained elevated within the previous place field after the field had switched OFF"

Threshold: the field's 95th-percentile shuffle map averaged within the field. This is an assumption: the paper does not say how the bin-wise threshold is reduced to one value for a field. Pre-ON trials are those before the first ON; post-OFF trials those from the last OFF. Outside region: 10% of the track's bins on each side, stopped at the track end or another field of the cell.

In [32]:
# claim:figs14-preexisting-fields-ephys
s14 = []
for r, o in sw.iter_tasks(res):
    rm = sw.trial_rowmap(o)
    nb = o["nbins"]; ext = int(round(0.1 * nb))  # 10% of the track length (Methods, Quantification of pre-existing constraint)
    for f in o["fields"]:
        s = f["sw"]
        for kind in ("on", "off"):
            if not s[kind]:
                continue
            c = s["on"][0] if kind == "on" else s["off"][-1]
            trials = f["trials"][:c] if kind == "on" else f["trials"][c:]
            if len(trials) == 0:
                continue
            thr = float(np.mean(f["thr"]))
            # other fields of the same cell in the same trial type bound the outside region
            others = [g for g in o["fields"] if g["unit"] == f["unit"] and g is not f and (g["trial_type"] in (f["trial_type"], "both") or f["trial_type"] == "both")]
            lo, hi = max(0, f["start"] - ext), min(nb - 1, f["end"] + ext)
            for g in others:
                if g["end"] < f["start"]: lo = max(lo, g["end"] + 1)
                if g["start"] > f["end"]: hi = min(hi, g["start"] - 1)
            outside = list(range(lo, f["start"])) + list(range(f["end"] + 1, hi + 1))
            within_mean, outside_mean = [], []
            for t in trials:
                tt, k = rm[int(t)]
                m = o["maps"][tt][f["cell"], k].astype(float)
                within_mean.append(m[f["start"]:f["end"] + 1].mean())
                outside_mean.append(m[outside].mean() if outside else np.nan)
            idx = np.arange(c) if kind == "on" else np.arange(c, len(f["rate"]))
            s14.append(dict(session=r["session"], familiar=o["familiar"], kind=kind,
                            below_mean=np.mean(within_mean) < thr,
                            below_peak=np.mean(np.asarray(f["rate"])[idx]) < thr,
                            diff=np.nanmean(np.array(within_mean) - np.array(outside_mean)),
                            within=np.mean(within_mean), outside=np.nanmean(outside_mean)))
S14 = pd.DataFrame(s14)
for kind, g in S14.groupby("kind"):
    print(f"{kind.upper()}: fields {len(g)}, below threshold by mean within-field rate {g.below_mean.mean():.3f}, by mean within-field peak rate {g.below_peak.mean():.3f}")
for sel in ("below_mean", "below_peak"):
    print(f"\nselection {sel}:")
    for (kind, fam), g in S14[S14[sel]].groupby(["kind", "familiar"]):
        g = g.dropna(subset=["diff"])
        ss = g.groupby("session")[["within", "outside"]].mean()
        p = stats.wilcoxon(ss.within, ss.outside).pvalue if len(ss) > 1 else np.nan
        print(f"  {kind.upper()} {'familiar' if fam else 'novel'}: fields {len(g)}, within above outside {(g['diff'] > 0).mean():.3f}, median difference {g['diff'].median():.3f} Hz; sessions {len(ss)}, session-level Wilcoxon p = {p:.2g}")
OFF: fields 1258, below threshold by mean within-field rate 0.436, by mean within-field peak rate 0.247
ON: fields 2016, below threshold by mean within-field rate 0.654, by mean within-field peak rate 0.422

selection below_mean:
  OFF novel: fields 150, within above outside 0.800, median difference 0.283 Hz; sessions 8, session-level Wilcoxon p = 0.0078
  OFF familiar: fields 398, within above outside 0.837, median difference 0.476 Hz; sessions 44, session-level Wilcoxon p = 3.5e-11
  ON novel: fields 417, within above outside 0.671, median difference 0.158 Hz; sessions 8, session-level Wilcoxon p = 0.0078
  ON familiar: fields 902, within above outside 0.752, median difference 0.416 Hz; sessions 45, session-level Wilcoxon p = 1.1e-13

selection below_peak:
  OFF novel: fields 80, within above outside 0.675, median difference 0.142 Hz; sessions 8, session-level Wilcoxon p = 0.0078
  OFF familiar: fields 231, within above outside 0.749, median difference 0.244 Hz; sessions 43, session-level Wilcoxon p = 5.6e-09
  ON novel: fields 278, within above outside 0.576, median difference 0.054 Hz; sessions 8, session-level Wilcoxon p = 0.0078
  ON familiar: fields 573, within above outside 0.649, median difference 0.172 Hz; sessions 45, session-level Wilcoxon p = 1.6e-09

Result: Partially reproduced, resting on an assumption (the shuffle threshold averaged over the field's bins). Below threshold by the mean within-field rate (the legend's reading) are 0.654 of 2016 switch-ON fields (within 0.6 +- 0.06) and 0.436 of 1258 switch-OFF fields (expected 0.2 +- 0.02); by mean within-field peak rate (the Results' reading) 0.422 and 0.247. Under the legend's reading, within-field rate exceeds the outside rate for 0.752 (ON, familiar), 0.671 (ON, novel), 0.837 (OFF, familiar) and 0.800 (OFF, novel) of fields, and the session-level test gives p = 1.1e-13 (ON) and 3.5e-11 (OFF) in familiar sessions. The majorities and the test hold under both readings; the OFF fraction is off under both.

figs2-chr2-no-effect¶

The proportions of neurons with different switching properties do not differ between opto-tagged (ChR2-expressing) and non-tagged neurons.

Paper (Results, Within-session representational drift, paragraph 4; Figure S2): "Furthermore, switching was not related to the expression of channelrhodopsin (ChR) in a small subset of the neurons in the dataset"

Pyramidal place cells per session (cells with a field in any analysed task of the session), by switching property, against the files' light_responsive label.

In [33]:
# claim:figs2-chr2-no-effect
cr = []
for r in res:
    u = r["units"]
    cats = {}
    for o in r["tasks"]:
        if not (o["familiar"] or r["session"] in sw.NOVEL_SESSIONS):
            continue
        for f in o["fields"]:
            c = cats.setdefault(f["unit"], [False, False])
            c[0] |= bool(f["sw"]["on"]); c[1] |= bool(f["sw"]["off"])
    for i in np.nonzero((u.putative_cell_type == "Pyramidal Cell").values)[0]:
        c = cats.get(i)
        cat = "not a place cell" if c is None else {(False, False): "no switch", (True, False): "ON only", (False, True): "OFF only", (True, True): "both"}[tuple(c)]
        cr.append(dict(session=r["session"], unit=i, light=bool(u.light_responsive[i]), cat=cat))
CR = pd.DataFrame(cr)
print("pyramidal neurons (per session):", len(CR), "| light-responsive:", int(CR.light.sum()))
pc = CR[CR["cat"] != "not a place cell"]
for name, d in [("place cells, four categories", pc.assign(c=pc["cat"])),
                ("place cells, switching against not", pc.assign(c=pc["cat"] != "no switch")),
                ("all pyramidal, five categories", CR.assign(c=CR["cat"]))]:
    tab = pd.crosstab(d.c, d.light)
    chi = stats.chi2_contingency(tab)
    print(f"{name}: n = {len(d)}, chi-squared = {chi[0]:.2f}, dof {chi[2]}, p = {chi[1]:.3g}")
    print(tab.to_string())
pyramidal neurons (per session): 5145 | light-responsive: 467
place cells, four categories: n = 4243, chi-squared = 3.89, dof 3, p = 0.273
light      False  True 
c                      
OFF only     309     40
ON only      735     84
both         627     56
no switch   2140    252
place cells, switching against not: n = 4243, chi-squared = 0.66, dof 1, p = 0.415
light  False  True 
c                  
False   2140    252
True    1671    180
all pyramidal, five categories: n = 5145, chi-squared = 40.10, dof 4, p = 4.13e-08
light             False  True 
c                             
OFF only            309     40
ON only             735     84
both                627     56
no switch          2140    252
not a place cell    867     35

Result: Reproduced. Among 4243 place cells (expected 4486 +- 449), 432 light-responsive, switching category is independent of light responsiveness: four categories chi-squared = 3.89, p = 0.273; switching against not, p = 0.415. Including the 902 pyramidal cells without fields as a fifth category gives p = 4.1e-08, as fewer light-responsive cells lack fields (35 of 467); that comparison is outside the claim.

figs1-not-electrode-drift¶

Spike amplitudes of neighbouring neurons recorded on the same shank as a switching neuron do not change across its switch, arguing against electrode drift.

The wide-band signal is only in the raw files of 11 sessions; the first cell sizes the full test. The second runs the test on three familiar sessions: e16_3m1_210201, the smallest raw file (52 GB), and, added in the second revision, e16_3m1_210203 (same animal) and e13_26m1_211124 (a second animal), the sessions with the fewest switches. The paper's code reads the raw signal within 1 ms of each spike on the unit's largest-waveform channel, for every unit on the switching unit's shank, 20 s before and after the switch (extract_waveform_script.py), and its switch time is when the animal is at the field's peak on the switch trial (process_central_arm.py).

Two details are open. The switch time: the criterion names two readings, the trial's start (a) and the animal's entry into the field (b); the code's time, the animal at the field's peak, is a third, and it is the one adopted (an assumption). The amplitude of a mean waveform is taken as its peak-to-trough difference (an assumption: the paper does not define it); the trough depth is shown as a variant. All three switch times are run. The criterion pools neighbour-switch pairs; as the same neighbours enter every switch on their shank, the pairs are not independent, and the third cell also tests one value per switch and one per neighbour.

In [34]:
# figs1-not-electrode-drift: size of the wide-band data the test would need
raw = [p for p in sw.assets() if p.endswith("raw_ecephys.nwb")]
raw_sess = {p.split("_ses-")[1].replace("-raw_ecephys.nwb", "").replace("-", "_") for p in raw}
print("raw wide-band files:", len(raw), "| sizes %.0f to %.0f GB" % (min(sw.assets()[p]["size"] for p in raw) / 1e9, max(sw.assets()[p]["size"] for p in raw) / 1e9))
n_sw = n_sw_raw = 0
for r, o in sw.iter_tasks(res):
    k = sum(len(f["sw"]["on"]) + len(f["sw"]["off"]) for f in o["fields"])
    n_sw += k
    n_sw_raw += k if r["session"] in raw_sess else 0
mb = 40 * 16 * 30000 * 2 / 1e6
print(f"switches {n_sw}, of which {n_sw_raw} in sessions with a raw file; 40 s of one 16-channel shank at 30 kHz is {mb:.0f} MB, so about {n_sw_raw * mb / 1e3:.0f} GB to stream")
raw wide-band files: 11 | sizes 52 to 175 GB
switches 3512, of which 2041 in sessions with a raw file; 40 s of one 16-channel shank at 30 kHz is 38 MB, so about 78 GB to stream
In [35]:
# claim:figs1-not-electrode-drift (on three sessions with a wide-band file)
import h5py, remfile, requests
# e16_3m1_210201 is the smallest wide-band file (52 GB) of a familiar session; e16_3m1_210203 (62 GB, the
# same animal) and e13_26m1_211124 (127 GB, a second animal) were added in the second revision as the
# sessions with the fewest switches (48 and 67), to keep the streaming within the notebook's time.
S1_SESSIONS = ["e16_3m1_210201", "e16_3m1_210203", "e13_26m1_211124"]
def open_raw(session):
    animal = session.rsplit("_", 1)[0].replace("_", "-")
    p = f"sub-{animal}/sub-{animal}_ses-{session.replace('_', '-')}-raw_ecephys.nwb"
    a = sw.assets()[p]
    url = requests.head(f"{sw.API}/assets/{a['asset_id']}/download/", allow_redirects=True, timeout=60).url
    return h5py.File(remfile.File(url), "r")
def mean_wave(sig, t0, st, ch, FS, HALF, UV):
    i = np.round((st - t0) * FS).astype(int)
    i = i[(i >= HALF) & (i < sig.shape[0] - HALF)]
    if len(i) == 0:
        return None, 0
    w = sig[i[:, None] + np.arange(-HALF, HALF + 1)[None, :], ch].astype(float) * UV
    w -= w.mean(1, keepdims=True)
    return w.mean(0), len(i)
def amp(w):
    return float(w.max() - w.min())
READINGS = ("t_peak", "t_start", "t_field")
def figs1_session(session, max_switches=None):
    t_s1 = time.time()
    hr = open_raw(session)
    es = hr["acquisition/ElectricalSeries"]
    FS = float(es["starting_time"].attrs["rate"]); T_START = float(es["starting_time"][()]); UV = float(es["data"].attrs["conversion"]) * 1e6
    rec = [r for r in res if r["session"] == session][0]
    o1 = [o for o in rec["tasks"] if o["familiar"]][0]
    sess1 = sw.load_session(session)  # spike times of every unit
    nwb_p, io_p = sw.open_nwb(sw.session_path(session))
    max_el = np.asarray(nwb_p.units["max_electrode"].data[:]).astype(int)
    grp_names = np.array([str(x) for x in nwb_p.electrodes["group_name"].data[:]])
    io_p.close()
    shank = rec["units"].shank_id.values.astype(int)
    print(f"{session}: wide-band {es['data'].shape} at {FS:.0f} Hz, starting time {T_START} s, {UV:.3f} uV per bit; units {len(shank)}")
    print("   units whose largest-waveform electrode lies in their own shank's group:", int(np.mean([g.endswith(f" {s}") for g, s in zip(grp_names[max_el], shank)]) * len(shank)), "of", len(shank))
    HALF = int(round(0.001 * FS))  # +-1 ms around each spike on the unit's largest-waveform channel (code extract_waveform_script.py)
    # switch events of the session's fields, with the three readings of the switch time
    ev = []
    for f in o1["fields"]:
        for kind in ("on", "off"):
            for c in f["sw"][kind]:
                t = int(f["trials"][c])
                tstart = float(o1["trials"].start_time[t])
                m = np.nonzero((o1["frame_trial"] == t) & (o1["pbin"] >= f["start"]) & (o1["pbin"] <= f["end"]))[0]
                tfield = float(o1["t"][m[0]]) if len(m) else np.nan
                # the code's switch time: median time of the trial's forward frames in each position bin,
                # interpolated at the field's peak location on the switch trial (process_central_arm.py,
                # get_trial_pos_info and get_all_switch_times_combined)
                mf = (o1["frame_trial"] == t) & o1["forward"]
                bt = pd.Series(o1["t"][mf]).groupby(o1["pbin"][mf]).median()
                tpeak = float(np.interp(f["loc"][c], bt.index.values, bt.values)) if len(bt) else np.nan
                ev.append(dict(unit=f["unit"], kind=kind, trial=t, t_peak=tpeak, t_start=tstart, t_field=tfield))
    EV = pd.DataFrame(ev)
    print(f"   switches: ON {int((EV.kind == 'on').sum())}, OFF {int((EV.kind == 'off').sum())}; without a frame in the field on the switch trial: {int(EV.t_field.isna().sum())}")
    rows, nread = [], 0
    for sid, e in EV.iterrows():
        if max_switches is not None and nread >= max_switches:
            break
        nb_units = [u for u in np.nonzero(shank == shank[e.unit])[0] if u != e.unit]
        chs = sorted({int(max_el[u]) for u in nb_units})
        times = [e[k] for k in READINGS if np.isfinite(e[k])]
        if not chs or not times:
            continue
        # one read per switch covering the 20 s on each side of every reading's switch time
        a = int((min(times) - 20.0 - T_START) * FS) - HALF; b = int((max(times) + 20.0 - T_START) * FS) + HALF
        t0, sig = a / FS + T_START, es["data"][a:b, chs]; nread += 1
        for reading in READINGS:
            tsw = e[reading]
            if not np.isfinite(tsw):
                continue
            for u in nb_units:
                st = sess1["spikes"][u]
                ci = chs.index(int(max_el[u]))
                pre = st[(st >= tsw - 20) & (st <= tsw - 0.01)]; post = st[(st >= tsw + 0.01) & (st <= tsw + 20)]
                wp, npre = mean_wave(sig, t0, pre, ci, FS, HALF, UV); wq, npost = mean_wave(sig, t0, post, ci, FS, HALF, UV)
                if npre >= 1 and npost >= 1:  # neighbours with spikes in both windows (code: common_uid)
                    # control for the clock: the same spikes shifted by 0.5 s should show no waveform
                    ws, _ = mean_wave(sig, t0, pre + 0.5, ci, FS, HALF, UV)
                    rows.append(dict(session=session, switch=sid, reading=reading, kind=e.kind, ref=e.unit, neighbour=u,
                                     pre=amp(wp), post=amp(wq), pre_trough=-float(wp.min()), post_trough=-float(wq.min()),
                                     shifted=amp(ws) if ws is not None else np.nan, n_pre=npre, n_post=npost))
    hr.close()
    print(f"   windows read: {nread}; time {time.time() - t_s1:.0f} s")
    return pd.DataFrame(rows)
S1 = pd.concat([figs1_session(s) for s in S1_SESSIONS], ignore_index=True)
S1["diff"] = S1.post - S1.pre
S1["diff_trough"] = S1.post_trough - S1.pre_trough
S1["rel"] = S1["diff"] / S1.pre
print("clock check, median amplitude of the mean waveform at the spike times and with the spikes shifted by 0.5 s (uV):")
print(S1[S1.reading == "t_peak"].groupby("session")[["pre", "shifted"]].median().round(1).to_string())
e16_3m1_210201: wide-band (526542720, 64) at 30000 Hz, starting time 0.0 s, 0.195 uV per bit; units 167
   units whose largest-waveform electrode lies in their own shank's group: 167 of 167
   switches: ON 44, OFF 30; without a frame in the field on the switch trial: 3
   windows read: 74; time 512 s
e16_3m1_210203: wide-band (627940800, 64) at 30000 Hz, starting time 0.0 s, 0.195 uV per bit; units 182
   units whose largest-waveform electrode lies in their own shank's group: 182 of 182
   switches: ON 27, OFF 21; without a frame in the field on the switch trial: 0
   windows read: 48; time 527 s
e13_26m1_211124: wide-band (667103040, 128) at 30000 Hz, starting time 0.0 s, 0.195 uV per bit; units 182
   units whose largest-waveform electrode lies in their own shank's group: 182 of 182
   switches: ON 42, OFF 25; without a frame in the field on the switch trial: 2
   windows read: 67; time 224 s
clock check, median amplitude of the mean waveform at the spike times and with the spikes shifted by 0.5 s (uV):
                   pre  shifted
session                        
e13_26m1_211124  151.3     27.4
e16_3m1_210201   150.4     26.6
e16_3m1_210203   143.5     25.5
In [36]:
# claim:figs1-not-electrode-drift: tests by switch-time reading, pooled over the sessions and per session.
# Switch time readings: t_peak, the animal at the field's peak on the switch trial (the code); t_start,
# the trial's start (the criterion's reading a); t_field, its entry into the field (reading b).
# The criterion's test pools neighbour-switch pairs. The pairs are not independent: the same neighbours
# enter every switch of their shank. Two variants test one value per independent-ish unit: per switch,
# the median change over its neighbours (Wilcoxon over switches); per neighbour, the median change over
# the switches it enters (Wilcoxon over session and neighbour).
def s1_tests(g):
    w = stats.wilcoxon(g["diff"]).pvalue
    g5 = g[(g.n_pre >= 5) & (g.n_post >= 5)]
    ps = g.groupby(["session", "switch"])["diff"].median()
    pn = g.groupby(["session", "neighbour"])["diff"].median()
    return dict(pairs=len(g), switches=len(ps), neighbours=len(pn), ref_units=g.groupby("session").ref.nunique().sum(),
                median_uV=round(g["diff"].median(), 2), median_pre_uV=round(g.pre.median(), 1),
                median_rel=round(g.rel.median(), 4), p_pairs=w,
                p_trough=stats.wilcoxon(g["diff_trough"]).pvalue,
                p_5spikes=stats.wilcoxon(g5["diff"]).pvalue if len(g5) else np.nan,
                p_per_switch=stats.wilcoxon(ps).pvalue if len(ps) > 1 else np.nan,
                p_per_neighbour=stats.wilcoxon(pn).pvalue if len(pn) > 1 else np.nan)
T1 = pd.DataFrame([dict(sessions="pooled", reading=rd, kind=k.upper(), **s1_tests(g)) for (rd, k), g in S1.groupby(["reading", "kind"])]
                  + [dict(sessions=s, reading=rd, kind=k.upper(), **s1_tests(g)) for (s, rd, k), g in S1.groupby(["session", "reading", "kind"])])
with pd.option_context("display.float_format", lambda v: f"{v:.2g}"):
    print(T1.to_string())
for name, sub in (("pooled", T1[T1.sessions == "pooled"]), ("e16_3m1_210201 alone", T1[T1.sessions == "e16_3m1_210201"])):
    for rd in READINGS:
        s = sub[sub.reading == rd]
        print(f"{name}, {rd}: no test of the criterion (pairs, peak-to-trough) gives p < 0.05 -> {bool((s.p_pairs >= 0.05).all())}; with the trough depth -> {bool((s.p_trough >= 0.05).all())}")
print(f"largest median relative change over readings, kinds and sessions: {T1.median_rel.abs().max():.4f}; smallest {T1.median_rel.abs().min():.4f}")
           sessions  reading kind  pairs  switches  neighbours  ref_units  median_uV  median_pre_uV  median_rel  p_pairs  p_trough  p_5spikes  p_per_switch  p_per_neighbour
0            pooled  t_field  OFF   1990        73         455         60       0.82        1.5e+02      0.0074  0.00081      0.12       0.42          0.29            0.019
1            pooled  t_field   ON   3046       111         455         88      -0.79        1.5e+02     -0.0066     0.26      0.55    0.00069          0.12              0.1
2            pooled   t_peak  OFF   2058        76         457         62      -0.05        1.5e+02     -0.0004     0.24      0.81       0.57          0.91             0.15
3            pooled   t_peak   ON   3093       113         453         89      -0.89        1.5e+02     -0.0077    0.019     0.029    4.2e-06          0.07            0.026
4            pooled  t_start  OFF   2046        76         453         62      -0.08        1.5e+02     -0.0004     0.13       0.3       0.74          0.25            0.028
5            pooled  t_start   ON   3138       113         460         89         -1        1.5e+02     -0.0082    0.012      0.34      0.013         0.017             0.72
6   e13_26m1_211124  t_field  OFF    461        24         168         21      -0.84        1.5e+02     -0.0068     0.15      0.17       0.14          0.29             0.38
7   e13_26m1_211124  t_field   ON    819        41         163         32      -0.59        1.5e+02     -0.0044     0.31      0.53       0.31          0.34            0.037
8   e13_26m1_211124   t_peak  OFF    483        25         171         22      -0.54        1.6e+02     -0.0043     0.94      0.87       0.36          0.73             0.64
9   e13_26m1_211124   t_peak   ON    839        42         164         33      -0.33        1.5e+02     -0.0024     0.44      0.19       0.18          0.72             0.18
10  e13_26m1_211124  t_start  OFF    481        25         166         22          1        1.6e+02      0.0062     0.21      0.27       0.23          0.13             0.27
11  e13_26m1_211124  t_start   ON    843        42         166         33       0.92        1.5e+02      0.0073     0.62     0.083       0.16           0.8              0.9
12   e16_3m1_210201  t_field  OFF    864        28         144         22        1.6        1.5e+02       0.012  0.00023     0.031       0.28         0.099           0.0063
13   e16_3m1_210201  t_field   ON   1363        43         144         32      -0.86        1.6e+02      -0.007     0.26       0.9     0.0044          0.22              0.3
14   e16_3m1_210201   t_peak  OFF    914        30         145         23       0.03        1.5e+02      0.0003     0.31      0.82       0.87          0.89             0.26
15   e16_3m1_210201   t_peak   ON   1382        44         140         32       -1.8        1.5e+02      -0.012   0.0034      0.11    0.00021         0.032            0.066
16   e16_3m1_210201  t_start  OFF    909        30         144         23      -0.85        1.5e+02      -0.008     0.88      0.57      0.099          0.48             0.92
17   e16_3m1_210201  t_start   ON   1411        44         143         32      -0.89        1.6e+02     -0.0078     0.32      0.55      0.066        0.0089             0.54
18   e16_3m1_210203  t_field  OFF    665        21         143         17        1.5        1.4e+02       0.011   0.0052      0.15       0.16           0.1            0.011
19   e16_3m1_210203  t_field   ON    864        27         148         24       -0.9        1.5e+02     -0.0079     0.76      0.72      0.073          0.59             0.69
20   e16_3m1_210203   t_peak  OFF    661        21         141         17        0.2        1.4e+02       0.002     0.33      0.36       0.99          0.97             0.33
21   e16_3m1_210203   t_peak   ON    872        27         149         24      -0.68        1.5e+02     -0.0043     0.96      0.41     0.0072          0.53             0.47
22   e16_3m1_210203  t_start  OFF    656        21         143         17       0.06        1.4e+02      0.0009    0.064      0.13        0.7          0.16           0.0074
23   e16_3m1_210203  t_start   ON    884        27         151         24       -3.2        1.5e+02      -0.027  7.4e-05   2.9e-05    0.00027        0.0077              0.2
pooled, t_peak: no test of the criterion (pairs, peak-to-trough) gives p < 0.05 -> False; with the trough depth -> False
pooled, t_start: no test of the criterion (pairs, peak-to-trough) gives p < 0.05 -> False; with the trough depth -> True
pooled, t_field: no test of the criterion (pairs, peak-to-trough) gives p < 0.05 -> False; with the trough depth -> True
e16_3m1_210201 alone, t_peak: no test of the criterion (pairs, peak-to-trough) gives p < 0.05 -> False; with the trough depth -> True
e16_3m1_210201 alone, t_start: no test of the criterion (pairs, peak-to-trough) gives p < 0.05 -> True; with the trough depth -> True
e16_3m1_210201 alone, t_field: no test of the criterion (pairs, peak-to-trough) gives p < 0.05 -> False; with the trough depth -> False
largest median relative change over readings, kinds and sessions: 0.0267; smallest 0.0003

Result: Not reproduced, on three sessions of the eleven with a wide-band file, and resting on an assumption (the amplitude is the peak-to-trough of the mean waveform). In all three sessions the spike times and the raw signal share a clock: the mean waveform at the spike times has a median amplitude of 143.5 to 151.3 uV, against 25.5 to 27.4 uV with the spikes shifted by 0.5 s. Pooled over the three sessions (at the code's time, 113 switches ON and 76 OFF with neighbours, from 89 and 62 switching units), the criterion's test of the neighbour-switch pairs gives p < 0.05 under every switch time: at the trial's start (reading a) ON p = 0.012 (median -1.0 uV, 3138 pairs), OFF p = 0.13; at the entry into the field (reading b) ON p = 0.26, OFF p = 0.00081 (median +0.82 uV); at the code's time, the animal at the field's peak, ON p = 0.019 (median -0.89 uV), OFF p = 0.24. On e16_3m1_210201 alone, the only session of the first revision, the trial's start gave no significant change (p = 0.32 and 0.88) and the other two times did, so the outcome there depended on the switch time; with three sessions it does not. It depends on the amplitude: with the trough depth, the trial's start (p = 0.34 and 0.30) and the entry into the field (p = 0.55 and 0.12) give no significant change, and only the code's time does (ON p = 0.029). The pairs reuse the same neighbours across switches and are not independent; with one value per switch only the trial's start ON gives p < 0.05 (0.017), and with one value per neighbour, the code's time ON (0.026), the trial's start OFF (0.028) and the entry OFF (0.019). The changes are small: pooled medians are at most 0.8% of the amplitude (relative -0.0082), and per session and reading at most 2.7% (e16_3m1_210203, trial's start, ON). The full test, on the 2041 switches of the 11 sessions with a raw file, needs about 78 GB of wide-band data and was not run; the other 34 sessions have no wide-band signal in the dandiset.

Blocked claims¶

fig7-preexisting-across-days and figs15-imaging-not-artifact¶

These rest on the two-photon imaging of 14 experiments in 11 mice (Hainmueller and Bartos 2018). The paper says the imaging data are "available from Marlene Bartos upon request" (Data and code availability); they are not in dandiset 000552, which holds the electrophysiology only, and no public deposit is named. Blocked: data missing.

Summary¶

Claim Outcome
fig1d-pv-decorrelation reproduced
fig1e-novel-drift-faster reproduced
fig1e-later-lags-no-difference reproduced
fig1h-rate-decorrelates-location-stable reproduced
fig1i-location-mse-increases reproduced
switch-step-size-filter not reproduced
fig2d-switch-fractions not reproduced
fig2e-switch-fraction-by-experience reproduced
fig3df-step-beats-polynomial-fields partially reproduced
fig3df-polynomial-beats-step-population reproduced
figs4g-population-vectors-gradual not reproduced
fig3k-switch-abrupt reproduced
figs5-switchers-drive-drift reproduced
fig4-glm-deviance partially reproduced (assumption: the partial clause covers values holding with the ranking for ON only)
fig4-delay-zone-more-switching not reproduced
fig4-behavior-not-predictive not reproduced
fig4di-switching-decreases-with-trial partially reproduced (assumption: trials from the fourth on)
figs8-speed-no-trend reproduced (assumption: speed correlated with trial per frame of forward locomotion)
fig4no-head-scans-not-related partially reproduced (assumption: head scans per position bin)
figs9-splitter-switching reproduced
figs13-btsp-signatures partially reproduced
fig5c-switchiness-not-intrinsic reproduced
fig5d-nrem-rate-relations reproduced
multifield-independent-switching not reproduced
figs12-stability-after-switch-on partially reproduced
fig6-co-switching not reproduced
fig6f-switching-asynchronous reproduced
figs14-preexisting-fields-ephys partially reproduced (assumption: shuffle threshold averaged over the field's bins)
figs2-chr2-no-effect reproduced
figs1-not-electrode-drift not reproduced (three sessions; assumption: peak-to-trough amplitude)
fig7-preexisting-across-days blocked (data missing)
figs15-imaging-not-artifact blocked (data missing)

A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.

How the analysis differs from the paper's:

  • Version 0.261113.1035 in place of the cited 0.230630.2304, which lacks the cell-type and light-responsive labels; spike times are the same.
  • 45 of the 46 familiar sessions (e13_26m1_210913 is not in the dandiset).
  • Putative pyramidal cells are the files' CellExplorer labels; six listed sessions have fewer than the 50 the paper requires.
  • Forward locomotion and speed come from the smoothed velocity of the linearised position (above 1 cm/s in the running direction), as the code's directed speed does, with the Methods' smoothing of 10 samples in place of the code's filter. Speed from x and y, as the Methods say, is shown for the familiar maze in figs8-speed-no-trend.
  • Field detection compares the trial-pooled map with shuffles pooled the same way (the code), where the Methods say "trial-averaged"; the pipeline is also run with the mean of per-trial maps, which gives 10842 and 2177 fields and lower switching counts; under it the Familiar against Novel test of fig2e-switch-fraction-by-experience gives p = 0.058. Only the counts of the switch filter, the switch fractions, the medians and tests of fig2e-switch-fraction-by-experience, the change-point model fractions of fig3df-step-beats-polynomial-fields, the fig1e-novel-drift-faster test and the same-neuron pairs of multifield-independent-switching were run under this variant; among them only the fig2e-switch-fraction-by-experience outcome would differ. The other claims were not run under it.
  • Switch detection follows the code's rule (get_n_cpd): significant when the smallest p is at most 0.05 over the number of K, and ties of the smallest p over K go to the smaller K. Ties to the larger K are shown.
  • Turn-common central-arm fields take each trial's value from its own turn's field.
  • The co-switching null shifts each field's switch trials within its own turn's trials, as the code does.
  • The electrode-drift test is run on three sessions (e16_3m1_210201, e16_3m1_210203, e13_26m1_211124) of the eleven with a wide-band file.
  • Each claim's open details are named in its section; the record lists them.

What was found about the dataset:

  • The cited version has no putative cell types or light-responsive labels, and marks 28 of 30 familiar trials of e16_3m1_210201 as not familiar; the pinned version corrects both and its spike times are identical.
  • One familiar session of the paper, e13_26m1_210913, is not in the dandiset.
  • On the linear mazes visited_arm holds the running direction (left toward higher position in 108 trials, right toward lower in 110) without saying so.
  • Six of the paper's familiar sessions have fewer than 50 pyramidal cells by the files' labels.
  • Spikes share the position clock in every analysed task, to about a second in one linear-maze task, and the wide-band signal of the three sessions tested shares the spikes' clock.
  • Only 11 sessions have a wide-band file; the others hold no signal from which spike waveforms around a switch can be measured.
In [37]:
print(f"notebook time {(time.time() - T0) / 60:.1f} min; peak memory of this process {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
notebook time 47.6 min; peak memory of this process 6.69 GB