Plitt & Giocomo (2021) on dandiset 000054, part 1: sessions, behaviour and place cells¶

Paper. Plitt MH, Giocomo LM (2021). Experience-dependent contextual codes in the hippocampus. Nature Neuroscience 24, 705-714. doi:10.1038/s41593-021-00816-6. The claims file was written from the NIH author manuscript in PubMed Central (PMC8893323), with the Methods, the main and Extended Data legends and the supplementary information; it is the accepted manuscript, not the version of record.

Dandiset. DANDI:000054, version 0.260415.1712. The paper's data statement points to the draft and cites no version. Of the six published versions, the three of 2021-08-19 hold 85 files (1.96 TB, raw imaging included) for 10 mice only (F1, F2, F3, F5 and R1 to R6). The three of April 2026 hold processed files for all 16 mice. The most recent, 0.260415.1712 (126 files, 112 GB), is pinned: the protocol asks for the most recent published version, and no earlier one matches the claims file better, as the 2021 versions lack six of the twelve rare and frequent morph mice and all four decision mice. It differs from 0.260409.0433 in mouse R5 only (training sessions 1, 5 and 7 removed and the other R5 files replaced); the cell below lists the difference.

What the files hold. One file per imaging session: the deconvolved activity of every Suite2P cell, the VR behaviour aligned to the imaging frames (imaged trials only), and a JSON annotation with per-trial values. The non-imaged trials, and the sessions without imaging, are not in the dandiset.

Outside input. The authors' "Unprocessed VR data" on figshare (doi:10.6084/m9.figshare.31974756.v1, one zip of 1.09 GB, published 2026-04-09) holds every VR session, imaged or not, with a session database (header M7 of the claims file, answer of 2026-10-22). It is read here by HTTP range requests, file by file, into memory, in part 2 (02_population_inference.ipynb), which tests its link to the dandiset (vr-deposit-link) and training-intermediate-fraction, which uses the deposit alone (data: elsewhere).

This notebook tests the claims on sessions, behaviour and place cells. The population, SF and inference claims are in part 2 (02_population_inference.ipynb), which also holds the summary.

Claim Notebook Status
cells-per-session 1 tested
session-and-trial-counts 1 tested
vr-deposit-link 2 tested (link claim, figshare deposit)
training-intermediate-fraction 2 tested (figshare deposit, data elsewhere)
place-cell-fractions 1 tested
edf4a-fewer-place-cells-frequent 1 tested
edf4a-overlap-above-chance 1 tested
edf4bc-overlap-cells-at-ends-and-reward 1 tested
fig2eh-place-cell-similarity-differs 1 tested
edf5-umap-rare-frequent-separable 1 tested
edf1-licking-before-reward 1 tested
edf6-nmf-confirms-remapping 1 tested
fig3ab, edf7, fig3f, fig4 2 tested
fig6a, fig6bc, fig6d, map-estimate-values, edf9, edf9k, edf9l, edf10, fig7g, edf3 2 tested (priors from the deposit, data with inputs)
fig7-model-reproduces-remapping 2 tested (priors from the deposit, data elsewhere)
edf2-fh-best-predictor - blocked: data missing (renders of the VR scenes)
supp-earlier-morph-studies - blocked: other (uses no data of this paper)
In [1]:
import time
import warnings

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats

import morph as M

warnings.filterwarnings("ignore")
pd.set_option("display.width", 220)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 300)
started = time.time()

assets = M.asset_table()
print(f"dandiset {M.DANDISET_ID} version {M.DANDISET_VERSION}: {len(assets)} NWB files, "
      f"{assets['size'].sum() / 1e9:.1f} GB")
print("asset paths the file-name pattern does not read (left out):", len(assets.attrs["unmatched"]), assets.attrs["unmatched"][:5])
testing_rf = assets[(assets.group != "decision") & (assets.kind == "testing")]
others = assets.drop(testing_rf.index)
place = M.process_many([r for _, r in testing_rf.iterrows()], "place")
print(f"rare and frequent sessions 8 to N, streamed with place cells: {len(place)} in "
      f"{time.time() - started:.0f} s")
meta = M.process_many([r for _, r in others.iterrows()], "meta", workers=8)
print(f"other files, behaviour and trial annotation only: {len(meta)}; total {time.time() - started:.0f} s")
sessions = sorted(place + meta, key=lambda s: (s["group"], s["mouse"], s["day"], s["part"]))
RARE = ["R1", "R2", "R3", "R4", "R5", "R6"]
FREQ = ["F1", "F2", "F3", "F4", "F5", "F6"]
dandiset 000054 version 0.260415.1712: 126 NWB files, 112.0 GB
asset paths the file-name pattern does not read (left out): 0 []
rare and frequent sessions 8 to N, streamed with place cells: 47 in 1619 s
other files, behaviour and trial annotation only: 79; total 1659 s

Data check¶

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

In [2]:
from dandi.dandiapi import DandiAPIClient

with DandiAPIClient() as client:
    prev = {a.path: a.size for a in client.get_dandiset(M.DANDISET_ID, "0.260409.0433").get_assets()}
cur = dict(zip(assets.path, assets["size"]))
print("Difference from version 0.260409.0433 (path: earlier size -> pinned size):")
for p in sorted(set(prev) | set(cur)):
    if prev.get(p) != cur.get(p):
        print(f"  {p}: {prev.get(p)} -> {cur.get(p)}")

info = pd.DataFrame([{
    "mouse": s["mouse"], "group": s["group"], "kind": s["kind"], "day": s["day"], "part": s["part"],
    "json_day": s["json_day"], "session_id": s["session_id"], "frames": s["n_frames"], "cells": s["n_cells"],
    "trials": len(s["trials"]), "sex": s["subject"]["sex"], "genotype": s["subject"]["genotype"],
    "description": s["subject"]["description"], "rate": s["rate"], "imaging_rate": s["imaging_rate"],
    "dt_s": s["dt"], "start_time": s["start_time"][:10], "same_ts": s["same_ts"],
    "starts_match": s["starts_match"], "stops_match": s["stops_match"],
    "trial_numbers_match": s["trial_numbers_match"], "morph_series_match": s["morph_series_match"],
    "fingerprint": s["fingerprint"]} for s in sessions])
print("\nFiles by group and session kind:")
print(pd.crosstab(info.group, info.kind).to_string())
print("\nSessions per mouse by file kind (day as in the file name; .2 for the second file of a day):")
print(info.groupby(["group", "mouse"]).apply(lambda d: pd.Series({
    kind: " ".join(f"{dd}" + (f".{pp}" if pp > 1 else "") for dd, pp in zip(d[d.kind == kind].day, d[d.kind == kind].part))
    for kind in ("training", "testing")})).to_string())
subj = info.drop_duplicates("mouse")[["mouse", "group", "sex", "genotype", "description"]]
print("\nSubjects:")
print(subj.to_string(index=False))
print("Sex counts:", subj.sex.value_counts().to_dict(), "(paper: 16 mice, 9 male and 7 female)")
print("\nFile name day equals the JSON 'day' (or day.part):",
      bool(np.allclose(info.json_day, info.day + (info.part - 1) / 10 + np.where(info.mouse.isin(["R1", "R2", "R3"]) & (info.day == 1), 0.1, 0)))
      or sorted(set(zip(info.day, info.part, info.json_day)))[:6])
print("Imaging rate (Hz), all files:", sorted(set(info.rate.round(4))), "; frame interval (s):",
      sorted(set(info.dt_s.round(5))), "(paper: 15.46 Hz)")
print("Every behaviour series shares one timestamp array:", bool(info.same_ts.all()))
print("Trial starts and teleports of the JSON match the flag series:", bool(info.starts_match.all()),
      bool(info.stops_match.all()), "; trial number series constant within each trial:",
      bool(info.trial_numbers_match.all()), "; morph series equals the JSON morph:", bool(info.morph_series_match.all()))
print("session_start_time dates:", sorted(set(info.start_time)))
dup = info[info.duplicated(["frames", "cells", "fingerprint"], keep=False)]
print("Files sharing frame count, cell count and the sum of activity in frames 1000 to 1009:",
      len(dup), "(none means no recording is deposited twice)")
print(f"Cells per file: {info.cells.min()} to {info.cells.max()}; trials per file: {info.trials.min()} to {info.trials.max()}")
Difference from version 0.260409.0433 (path: earlier size -> pinned size):
  sub-R5/sub-R5_ses-testing-day8_behavior+ophys.nwb: 1502533088 -> 779558200
  sub-R5/sub-R5_ses-testing-day9_behavior+ophys.nwb: 1634472552 -> 958421312
  sub-R5/sub-R5_ses-training-day1_behavior+ophys.nwb: 667394800 -> None
  sub-R5/sub-R5_ses-training-day3_behavior+ophys.nwb: 1025034176 -> 642036592
  sub-R5/sub-R5_ses-training-day5_behavior+ophys.nwb: 941904292 -> None
  sub-R5/sub-R5_ses-training-day7_behavior+ophys.nwb: 1118704648 -> None

Files by group and session kind:
kind      testing  training
group                      
decision       21        16
frequent       21        24
rare           26        18

Sessions per mouse by file kind (day as in the file name; .2 for the second file of a day):
                   training                 testing
group    mouse                                     
decision FD1        1 3 5 7  9 10 11 12 13 14 17 19
         FD2        1 3 5 7         8 9 15 16 22 23
         FD3        1 3 5 7                        
         FD4        1 3 5 7      8 9 15 16 17 22 23
frequent F1         1 3 5 7                  8 9 10
         F2         1 3 5 7               8 9 10 11
         F3         1 3 5 7                       8
         F4         1 3 5 7            8 9 10 11 12
         F5         1 3 5 7            8 9 10 11 12
         F6         1 3 5 7                  8 9 10
rare     R1     1 1.2 3 5 7            8 9 10 11 12
         R2     1 1.2 3 5 7         8 9 10 11 12 13
         R3     1 1.2 3 5 7            8 9 10 11 12
         R4             3 6            8 9 10 11 12
         R5               3                     8 9
         R6                                  8 9 10

Subjects:
mouse    group sex          genotype                                               description
  FD1 decision   M        CaMKII-Cre Frequent morph with decision mouse (Extended Data Fig 10)
  FD2 decision   F        CaMKII-Cre Frequent morph with decision mouse (Extended Data Fig 10)
  FD3 decision   F        CaMKII-Cre Frequent morph with decision mouse (Extended Data Fig 10)
  FD4 decision   F        CaMKII-Cre Frequent morph with decision mouse (Extended Data Fig 10)
   F1 frequent   M        CaMKII-Cre                                      Frequent morph mouse
   F2 frequent   M        CaMKII-Cre                                      Frequent morph mouse
   F3 frequent   M        CaMKII-Cre                                      Frequent morph mouse
   F4 frequent   F  Ai94; CaMKII-Cre                                      Frequent morph mouse
   F5 frequent   F        CaMKII-Cre                                      Frequent morph mouse
   F6 frequent   F        CaMKII-Cre                                      Frequent morph mouse
   R1     rare   M        CaMKII-Cre                                          Rare morph mouse
   R2     rare   M        CaMKII-Cre                                          Rare morph mouse
   R3     rare   M        CaMKII-Cre                                          Rare morph mouse
   R4     rare   F        CaMKII-Cre                                          Rare morph mouse
   R5     rare   M        CaMKII-Cre                                          Rare morph mouse
   R6     rare   M wildtype C57BL/6J                                          Rare morph mouse
Sex counts: {'M': 9, 'F': 7} (paper: 16 mice, 9 male and 7 female)

File name day equals the JSON 'day' (or day.part): True
Imaging rate (Hz), all files: [15.4609] ; frame interval (s): [0.06468] (paper: 15.46 Hz)
Every behaviour series shares one timestamp array: True
Trial starts and teleports of the JSON match the flag series: True True ; trial number series constant within each trial: True ; morph series equals the JSON morph: True
session_start_time dates: ['2026-04-08', '2026-04-13']
Files sharing frame count, cell count and the sum of activity in frames 1000 to 1009: 0 (none means no recording is deposited twice)
Cells per file: 161 to 4103; trials per file: 55 to 125
In [3]:
rng_rows = []
for s in place:
    r = s["ranges"]
    rng_rows.append({"mouse": s["mouse"], "day": s["day"], "pos_min": r["position"][0], "pos_max": r["position"][1],
                     "speed_min": r["speed"][0], "speed_max": r["speed"][1], "licks_max": r["licks"][1],
                     "act_min": s["act_min"], "act_max": s["act_max"], "norm_check": s["norm_check"],
                     "p99_zero": s["p99_zero"], "speed_kept": s["speed_kept"], "act_check": s["act_check"]})
rr = pd.DataFrame(rng_rows)
print("Units:", place[0]["units"])
print(rr.describe().loc[["min", "max"]].round(3).to_string())
tr_all = pd.concat([s["trials"].assign(mouse=s["mouse"], group=s["group"], day=s["day"], kind=s["kind"]) for s in sessions])
print("\nS-tilde values by group and kind:")
print(tr_all.groupby(["group", "kind"]).morph.apply(lambda m: sorted(set(np.round(m, 3)))[:8]
                                                   + (["..."] if m.nunique() > 8 else [])).to_string())
for col in ["wall", "tower", "background"]:
    print(f"{col} jitter range: {tr_all[col].min():.3f} to {tr_all[col].max():.3f} (Methods: -0.1 to 0.1)")
print(f"S = S-tilde + wall jitter: {tr_all.S.min():.3f} to {tr_all.S.max():.3f}; f_h {tr_all.fh.min():.2f} to "
      f"{tr_all.fh.max():.2f}; units {tr_all.unit.min():.3f} to {tr_all.unit.max():.3f}")
print("effective_morph of the JSON equals S:", bool(np.allclose(tr_all.effective_morph, tr_all.S)))
rw = tr_all[tr_all.kind == "testing"].reward_pos
print(f"Reward position, testing sessions: {rw.min():.1f} to {rw.max():.1f} cm, missing on {rw.isna().mean():.1%} "
      f"of trials; omission flag on {tr_all[tr_all.kind == 'testing'].omission.mean():.1%}")
Units: {'background jitter': 'arbitrary', 'licks': 'avg number of licks', 'morph value': 'arbitrary', 'position': '1 cm', 'reward': 'arbitrary', 'speed': 'cm/s', 'teleport': 'arbitrary', 'tower jitter': 'arbitrary', 'trial number': 'arbitrary', 'trial start': 'arbitrary', 'wall jitter': 'arbitrary'}
      day  pos_min  pos_max  speed_min  speed_max  licks_max  act_min    act_max  norm_check  p99_zero  speed_kept
min   8.0   -500.0  450.126    -10.534     46.967        4.0      0.0   5687.369         0.0       0.0       0.671
max  13.0   -500.0  453.685     -1.205    175.516        6.0      0.0  20638.951         0.0       0.0       0.974

S-tilde values by group and kind:
group     kind    
decision  testing                           [0.0, 0.25, 0.5, 0.75, 1.0]
          training    [0.0, 0.003, 0.025, 0.026, 0.033, 0.037, 0.04,...
frequent  testing                           [0.0, 0.25, 0.5, 0.75, 1.0]
          training                          [0.0, 0.25, 0.5, 0.75, 1.0]
rare      testing                           [0.0, 0.25, 0.5, 0.75, 1.0]
          training                          [0.0, 0.25, 0.5, 0.75, 1.0]
wall jitter range: -0.100 to 0.100 (Methods: -0.1 to 0.1)
tower jitter range: -0.100 to 0.100 (Methods: -0.1 to 0.1)
background jitter range: -0.100 to 0.100 (Methods: -0.1 to 0.1)
S = S-tilde + wall jitter: -0.100 to 1.100; f_h 5.55 to 38.45; units -0.100 to 1.100
effective_morph of the JSON equals S: True
Reward position, testing sessions: 225.5 to 409.0 cm, missing on 17.4% of trials; omission flag on 13.2%

Behaviour: position runs from 0 to 450 cm in a trial, with -50 cm in the inter-trial tunnel (and a few frames at -500 cm, outside any trial), as described. Speed is in cm/s and is negative on some frames. Deconvolved activity is non-negative. The normalised series matches the description (each cell divided by its 99th percentile; norm_check is the largest difference over a block of 100 frames). The jitters lie in -0.1 to 0.1 and S in -0.1 to 1.1, as in the Methods, and the JSON effective_morph is S. The decision mice FD1's training sessions 1 and 3 hold continuous morph values, not the five S-tilde values.

Metadata against the data and the paper: the imaging rate is 15.4609 Hz, as the paper gives. The session_start_time of every file is the date of conversion in 2026, not of the recording, so calendar days between sessions cannot be read from the files. The files hold imaging sessions 5 and 7 (and R4's session 6), which the paper does not list among imaging sessions (1, 3 and 8 to N). R6 has no training files and R4 and R5 lack session 1, and FD3 has no testing sessions. Rare morph mice see intermediate values only in sessions 3 and 8 to N, as described.

In [4]:
lag = pd.DataFrame([{"mouse": s["mouse"], "day": s["day"], **{f"lag {k}": v for k, v in s["lag_rel"].items()}} for s in place])
best = lag.filter(like="lag").idxmax(axis=1).str.replace("lag ", "").astype(int)
print("Clock check 1: median over the first 300 cells of the odd-even trial map correlation, with activity shifted "
      "by a lag (frames of 65 ms; positive = activity later) against position. Mean over sessions:")
print(lag.filter(like="lag").mean().round(3).to_string())
print("Lag of the maximum, per session:", best.value_counts().sort_index().to_dict())
ls = pd.DataFrame([{"mouse": s["mouse"], "day": s["day"], **s["label_shift"]} for s in place])
print("\nClock check 2: mean SF of S-tilde = 1 minus S-tilde = 0 trials, with the true trial labels and with each "
      "trial given the next trial's label:")
print(ls[["true", "shifted by one trial"]].describe().loc[["min", "50%", "max"]].round(3).to_string())
print("sessions where the true labels give the larger contrast:", int((ls["true"] > ls["shifted by one trial"]).sum()), "of", len(ls))
Clock check 1: median over the first 300 cells of the odd-even trial map correlation, with activity shifted by a lag (frames of 65 ms; positive = activity later) against position. Mean over sessions:
lag -60    0.370
lag -30    0.459
lag -15    0.504
lag -8     0.521
lag -4     0.526
lag -2     0.532
lag 0      0.534
lag 2      0.532
lag 4      0.527
lag 8      0.513
lag 15     0.484
lag 30     0.420
lag 60     0.323
Lag of the maximum, per session: {-15: 2, -8: 3, -4: 5, -2: 9, 0: 12, 2: 9, 4: 4, 8: 2, 15: 1}

Clock check 2: mean SF of S-tilde = 1 minus S-tilde = 0 trials, with the true trial labels and with each trial given the next trial's label:
      true  shifted by one trial
min  0.024                -0.010
50%  0.163                -0.003
max  0.272                 0.015
sessions where the true labels give the larger contrast: 47 of 47
In [5]:
# Verifier's check of the numba shuffle (M.place_cells, M._shuffle_counts): its exceedance counts against a
# plain numpy version (M.shuffle_counts_reference) for the first 50 cells of F3 session 8, with the same
# 1,000 shifts and no early stopping.
chk_row = assets[(assets.mouse == "F3") & (assets.day == 8)].iloc[0]
chk = M.shuffle_check(chk_row.url, n_cells=50, seed=M.session_seed("F3", 8, 1, 1))
print(f"F3 session 8, {chk['cells']} cells, {chk['trials']} trials, {chk['shuffles']} shuffles, both speed readings, 5 S-tilde values:")
print("  counts equal in", int((chk["fast"] == chk["ref"]).sum()), "of", chk["fast"].size, "cell, S-tilde and reading entries;",
      "largest difference", int(np.abs(chk["fast"] - chk["ref"]).max()))
print("  largest difference of the real SI:", float(max(np.nanmax(np.abs(chk["si_fast"][g] - chk["si_ref"][g])) for g in range(2))))
print("  place cells (count at most 50) agree for", int(((chk["fast"] <= 50) == (chk["ref"] <= 50)).sum()), "of", chk["fast"].size)
F3 session 8, 50 cells, 90 trials, 1000 shuffles, both speed readings, 5 S-tilde values:
  counts equal in 500 of 500 cell, S-tilde and reading entries; largest difference 0
  largest difference of the real SI: 8.881784197001252e-16
  place cells (count at most 50) agree for 500 of 500

The numba shuffle used for every place-cell claim gives the same exceedance counts as a plain numpy version of the same procedure (500 of 500 cell, S-tilde and reading entries equal, with the same 1,000 shifts and no early stopping) on the first 50 cells of F3 session 8.

The split-half map correlation is highest within 8 frames (0.5 s) of zero lag in 44 of the 47 sessions and at 15 frames (about 1 s) in the other three (two at -15, one at +15); on average it falls at lags of 1 to 4 s. In every session the S-tilde contrast in the activity is present with the true trial labels and gone when the labels are moved by one trial. So the activity, the position and the trial table are consistent with one shared clock in every session, to within about a second; the map correlation cannot resolve a smaller offset, as the mice run at a similar speed on every trial.

cells-per-session¶

Each imaging session recorded between 161 and 3,657 putative CA1 pyramidal cells.

In [6]:
info["paper_imaging"] = (info.day == 1) | (info.day == 3) | (info.day >= 8)
rows = []
for reading, groups in (("a: R and F", ["rare", "frequent"]), ("b: R, F and FD", ["rare", "frequent", "decision"])):
    for sel_name, sel in (("sessions 1, 3 and 8 to N", info.paper_imaging), ("every file", info.paper_imaging | True)):
        x = info[info.group.isin(groups) & sel]
        rows.append({"reading": reading, "files": sel_name, "n": len(x), "min": x.cells.min(), "max": x.cells.max(),
                     "min_file": f"{x.loc[x.cells.idxmin(), 'mouse']} day {x.loc[x.cells.idxmin(), 'day']}",
                     "max_file": f"{x.loc[x.cells.idxmax(), 'mouse']} day {x.loc[x.cells.idxmax(), 'day']}",
                     "min within 161 +- 16.1": abs(x.cells.min() - 161) <= 16.1,
                     "max within 3657 +- 365.7": abs(x.cells.max() - 3657) <= 365.7})
print(pd.DataFrame(rows).to_string(index=False))
print("\nCells per session, by mouse (all files):")
print(info.groupby("mouse").cells.agg(["min", "max", "size"]).to_string())
       reading                    files   n  min  max min_file max_file  min within 161 +- 16.1  max within 3657 +- 365.7
    a: R and F sessions 1, 3 and 8 to N  70  161 3653 F3 day 8 F6 day 3                    True                      True
    a: R and F               every file  89  161 4103 F3 day 8 F6 day 5                    True                     False
b: R, F and FD sessions 1, 3 and 8 to N  99  161 3653 F3 day 8 F6 day 3                    True                      True
b: R, F and FD               every file 126  161 4103 F3 day 8 F6 day 5                    True                     False

Cells per session, by mouse (all files):
        min   max  size
mouse                  
F1      207   510     7
F2     1799  2154     8
F3      161   305     5
F4     1859  2117     9
F5      257   591     9
F6     2746  4103     7
FD1    1250  1537    12
FD2    1331  2032    10
FD3    1895  2108     4
FD4     924  1497    11
R1     1708  2058    10
R2     1083  1686    11
R3      822  1047    10
R4      886  1267     7
R5     1112  1422     3
R6     1403  2652     3

Result: reproduced. Over the sessions the paper describes as imaged (1, 3 and 8 to N), the rare and frequent morph mice have 161 to 3,653 cells per session (F3 session 8 and F6 session 3), within tolerance of 161 and 3,657; with the decision mice added the range is the same. The dandiset also holds imaging of sessions 5 and 7, which the paper does not describe; with them the maximum is 4,103 cells (F6 session 5), outside the tolerance.

session-and-trial-counts¶

The analyses of sessions 8 to N use 24 rare morph and 21 frequent morph sessions, holding 2,610 and 1,986 trials; the four decision mice contribute 2,460 trials.

In [7]:
late = info[info.day >= 8]
for g in ["rare", "frequent"]:
    x = late[late.group == g]
    print(f"{g}: {len(x)} sessions 8 to N, {x.trials.sum()} trials; per mouse:",
          x.groupby("mouse").agg(sessions=("day", "size"), trials=("trials", "sum")).to_dict("index"))
fd = info[info.group == "decision"]
print(f"decision mice, reading (a) every imaged session: {len(fd)} sessions, {fd.trials.sum()} trials; "
      f"(b) sessions 8 to N: {(fd.day >= 8).sum()} sessions, {fd[fd.day >= 8].trials.sum()} trials")
print("decision mice, per session (file kind, day, trials):")
for m, d in fd.groupby("mouse"):
    print(f"  {m}:", " ".join(f"{k[:2]}{dd}:{t}" for k, dd, t in zip(d.kind, d.day, d.trials)))
fd_c = fd[fd.day >= 5]
print(f"variant (2020 code, SFReg: fd_sfreg = single_mouse_sf_regression(..., first_ind=2), every imaging session from the "
      f"third on, which printed 'trial N 2460'): sessions 5 and later, {len(fd_c)} sessions, {fd_c.trials.sum()} trials")
print("decision mice per mouse:", fd.groupby("mouse").agg(sessions=("day", "size"), trials=("trials", "sum"),
                                                          late=("day", lambda d: int((d >= 8).sum()))).to_dict("index"))
exp = {"rare sessions": (24, 2.4), "frequent sessions": (21, 2.1), "rare trials": (2610, 261),
       "frequent trials": (1986, 198.6), "decision trials": (2460, 246)}
for reading, fdx in (("a", fd), ("b", fd[fd.day >= 8])):
    got = {"rare sessions": (late.group == "rare").sum(), "frequent sessions": (late.group == "frequent").sum(),
           "rare trials": late[late.group == "rare"].trials.sum(), "frequent trials": late[late.group == "frequent"].trials.sum(),
           "decision trials": fdx.trials.sum()}
    print(f"reading {reading}:", {k: (int(v), bool(abs(v - exp[k][0]) <= exp[k][1])) for k, v in got.items()})
rare: 26 sessions 8 to N, 2800 trials; per mouse: {'R1': {'sessions': 5, 'trials': 600}, 'R2': {'sessions': 6, 'trials': 720}, 'R3': {'sessions': 5, 'trials': 600}, 'R4': {'sessions': 5, 'trials': 490}, 'R5': {'sessions': 2, 'trials': 200}, 'R6': {'sessions': 3, 'trials': 190}}
frequent: 21 sessions 8 to N, 1986 trials; per mouse: {'F1': {'sessions': 3, 'trials': 281}, 'F2': {'sessions': 4, 'trials': 425}, 'F3': {'sessions': 1, 'trials': 90}, 'F4': {'sessions': 5, 'trials': 400}, 'F5': {'sessions': 5, 'trials': 510}, 'F6': {'sessions': 3, 'trials': 280}}
decision mice, reading (a) every imaged session: 37 sessions, 3217 trials; (b) sessions 8 to N: 21 sessions, 2022 trials
decision mice, per session (file kind, day, trials):
  FD1: tr1:100 tr3:100 tr5:100 tr7:110 te9:100 te10:100 te11:100 te12:100 te13:100 te14:100 te17:100 te19:120
  FD2: tr1:55 tr3:60 tr5:75 tr7:60 te8:60 te9:102 te15:100 te16:100 te22:100 te23:100
  FD3: tr1:60 tr3:60 tr5:75 tr7:60
  FD4: tr1:60 tr3:60 tr5:90 tr7:70 te8:60 te9:100 te15:100 te16:90 te17:90 te22:100 te23:100
variant (2020 code, SFReg: fd_sfreg = single_mouse_sf_regression(..., first_ind=2), every imaging session from the third on, which printed 'trial N 2460'): sessions 5 and later, 29 sessions, 2662 trials
decision mice per mouse: {'FD1': {'sessions': 12, 'trials': 1230, 'late': 8}, 'FD2': {'sessions': 10, 'trials': 812, 'late': 6}, 'FD3': {'sessions': 4, 'trials': 255, 'late': 0}, 'FD4': {'sessions': 11, 'trials': 920, 'late': 7}}
reading a: {'rare sessions': (26, True), 'frequent sessions': (21, True), 'rare trials': (2800, True), 'frequent trials': (1986, True), 'decision trials': (3217, False)}
reading b: {'rare sessions': (26, True), 'frequent sessions': (21, True), 'rare trials': (2800, True), 'frequent trials': (1986, True), 'decision trials': (2022, False)}

Result: not reproduced. Sessions 8 to N number 26 for the rare morph mice (24 expected, tolerance 2.4) and 21 for the frequent morph mice (21), holding 2,800 trials (2,610 +- 261) and 1,986 trials (1,986): these four counts are within tolerance. The decision mice contribute 3,217 trials over every imaged session (reading a) and 2,022 over sessions 8 to N (reading b), both outside 2,460 +- 246, so no reading has every count within tolerance; the criterion names no partial outcome. FD3 has no session after 7 in the dandiset, and FD1's sessions 1 and 3 hold continuous morph values. The 2020 code's selection for the decision mice (every imaging session from the third on, which is sessions 5 and later here) gives 2,662 trials, within tolerance; it is a variant, not a reading the criterion names, and a question asks a reader whether it should be one (questions/plitt-2021.yaml).

place-cell-fractions¶

Place cells tiled the track in both conditions; 15,829 rare morph place cells (43% of recorded cells; 23% S-tilde = 0 and 21% S-tilde = 1 place cells) and 8,933 frequent morph place cells (30%; 11% and 10%).

Place cells per session and S-tilde, from the spatial information against 1,000 within-trial circular shuffles (helper place_cells). Reading (a) leaves out frames below 2 cm/s, reading (b) keeps all frames. The place cells the authors' 2026 code stored in each file's JSON annotation are shown for comparison; they do not decide.

In [8]:
pc_rows = []
for s in place:
    for g in "ab":
        m = s["pc"][g]["mask"]
        pc_rows.append({"mouse": s["mouse"], "group": s["group"], "day": s["day"], "reading": g, "cells": s["n_cells"],
                        "any": int(m.any(0).sum()), "s0": int(m[0].sum()), "s1": int(m[4].sum()),
                        "both": int((m[0] & m[4]).sum()), **{f"m{k}": int(m[k].sum()) for k in range(5)}})
pcd = pd.DataFrame(pc_rows)
expected = {"rare": (15829, 0.43, 0.23, 0.21), "frequent": (8933, 0.30, 0.11, 0.10)}
tol = {"rare": (1582.9, 0.043, 0.023, 0.021), "frequent": (893.3, 0.03, 0.011, 0.01)}
summary = []
for g in "ab":
    for den in ("pooled", "session mean"):
        row = {"speed reading": g, "denominator": den}
        allok, countok, fracok = True, True, True
        for grp in ("rare", "frequent"):
            x = pcd[(pcd.reading == g) & (pcd.group == grp)]
            if den == "pooled":
                vals = (x["any"].sum(), x["any"].sum() / x.cells.sum(), x.s0.sum() / x.cells.sum(), x.s1.sum() / x.cells.sum())
            else:
                vals = (x["any"].sum(), (x["any"] / x.cells).mean(), (x.s0 / x.cells).mean(), (x.s1 / x.cells).mean())
            ok = [abs(v - e) <= t for v, e, t in zip(vals, expected[grp], tol[grp])]
            row.update({f"{grp} count": int(vals[0]), f"{grp} any": round(vals[1], 3), f"{grp} S0": round(vals[2], 3),
                        f"{grp} S1": round(vals[3], 3)})
            countok &= ok[0]
            fracok &= all(ok[1:])
        row.update({"counts ok": countok, "fractions ok": fracok})
        summary.append(row)
print(pd.DataFrame(summary).to_string(index=False))
print("\nRecorded cells, sessions 8 to N:", pcd[pcd.reading == "a"].groupby("group").cells.sum().to_dict(),
      "(the paper's counts and fractions imply about 36,800 rare and 29,800 frequent)")
print("\nFraction of cells that are place cells for any S-tilde, per mouse (mean over sessions):")
print(pcd.assign(f=pcd["any"] / pcd.cells).pivot_table(index="mouse", columns="reading", values="f").round(3).to_string())
print("\nPlace cells per S-tilde, pooled fraction, reading a:")
print(pcd[pcd.reading == "a"].groupby("group")[[f"m{k}" for k in range(5)]].sum().div(
    pcd[pcd.reading == "a"].groupby("group").cells.sum(), axis=0).round(3).to_string())
pc95_rows = []
for s in place:
    for g in "ab":
        m = s["pc95"][g]["mask"]
        pc95_rows.append({"group": s["group"], "reading": g, "cells": s["n_cells"], "any": int(m.any(0).sum()),
                          "s0": int(m[0].sum()), "s1": int(m[4].sum()), "both": int((m[0] & m[4]).sum())})
pc95 = pd.DataFrame(pc95_rows)
print("\nVariant (verifier's request): signal divided by each cell's 95th percentile, as the 2020 code does for place cells")
print("(PlotAllPlaceCells, S/np.percentile(S, 95, axis=0)); cells with a 95th percentile of 0:", sum(s["p95_zero"] for s in place))
v95 = pc95.groupby(["reading", "group"])[["cells", "any", "s0", "s1", "both"]].sum()
v95 = v95.assign(**{"any frac": v95["any"] / v95.cells, "S0 frac": v95.s0 / v95.cells, "S1 frac": v95.s1 / v95.cells,
                    "both frac": v95.both / v95.cells})
print(v95.round(3).to_string())
agree = np.mean(np.concatenate([(s["pc95"][g]["mask"] == s["pc"][g]["mask"]).ravel() for s in place for g in "ab"]))
print(f"cell and S-tilde pairs with the same decision under the raw and the normalised signal: {agree:.4f}")
print("\nShuffles run per cell (a cell stops once more than 50 shuffles reach its SI for every S-tilde and reading):",
      int(np.median(np.concatenate([s["pc"]["shuffles_run"] for s in place]))), "median")
speed reading  denominator  rare count  rare any  rare S0  rare S1  frequent count  frequent any  frequent S0  frequent S1  counts ok  fractions ok
            a       pooled       25053     0.685    0.392    0.360           17025         0.567        0.240        0.241      False         False
            a session mean       25053     0.699    0.403    0.373           17025         0.552        0.229        0.241      False         False
            b       pooled       21945     0.600    0.310    0.282           14345         0.478        0.178        0.163      False         False
            b session mean       21945     0.611    0.317    0.287           14345         0.462        0.168        0.164      False         False

Recorded cells, sessions 8 to N: {'frequent': 30018, 'rare': 36550} (the paper's counts and fractions imply about 36,800 rare and 29,800 frequent)

Fraction of cells that are place cells for any S-tilde, per mouse (mean over sessions):
reading      a      b
mouse                
F1       0.633  0.456
F2       0.575  0.485
F3       0.410  0.391
F4       0.708  0.586
F5       0.428  0.391
F6       0.430  0.375
R1       0.639  0.540
R2       0.623  0.568
R3       0.760  0.662
R4       0.792  0.683
R5       0.657  0.600
R6       0.723  0.621

Place cells per S-tilde, pooled fraction, reading a:
             m0     m1     m2     m3     m4
group                                      
frequent  0.240  0.202  0.219  0.233  0.241
rare      0.392  0.260  0.264  0.275  0.360

Variant (verifier's request): signal divided by each cell's 95th percentile, as the 2020 code does for place cells
(PlotAllPlaceCells, S/np.percentile(S, 95, axis=0)); cells with a 95th percentile of 0: 0
                  cells    any     s0     s1  both  any frac  S0 frac  S1 frac  both frac
reading group                                                                            
a       frequent  30018  17026   7206   7224  2548     0.567    0.240    0.241      0.085
        rare      36550  25037  14291  13148  5972     0.685    0.391    0.360      0.163
b       frequent  30018  14328   5324   4876  1268     0.477    0.177    0.162      0.042
        rare      36550  21934  11297  10287  3734     0.600    0.309    0.281      0.102
cell and S-tilde pairs with the same decision under the raw and the normalised signal: 0.9991

Shuffles run per cell (a cell stops once more than 50 shuffles reach its SI for every S-tilde and reading): 1000 median
In [9]:
# Place-cell masks of the authors' 2026 code, as stored in the JSON annotation of each file (a comparison).
import h5py, json, remfile  # noqa: E401
jrows = []
def json_masks(url):
    with h5py.File(remfile.File(url), "r") as f:
        pci = json.loads(f["acquisition/trial_data/data"][0])["place_cell_info"]["masks"]
    return np.array([pci[k] for k in ["0.0", "0.25", "0.5", "0.75", "1.0"]], bool)
for s, (_, row) in zip(place, testing_rf.iterrows()):
    jm = json_masks(row.url)
    agree = {g: float((s["pc"][g]["mask"] == jm).mean()) for g in "ab"}
    jrows.append({"group": s["group"], "cells": s["n_cells"], "any": int(jm.any(0).sum()), "s0": int(jm[0].sum()),
                  "s1": int(jm[4].sum()), "agree_a": agree["a"], "agree_b": agree["b"]})
jd = pd.DataFrame(jrows)
for grp, x in jd.groupby("group"):
    print(f"{grp}: 2026-code place cells {x['any'].sum()} ({x['any'].sum() / x.cells.sum():.3f} of cells; S0 "
          f"{x.s0.sum() / x.cells.sum():.3f}, S1 {x.s1.sum() / x.cells.sum():.3f}); agreement of masks with reading a "
          f"{x.agree_a.mean():.3f}, reading b {x.agree_b.mean():.3f}")
frequent: 2026-code place cells 14590 (0.486 of cells; S0 0.186, S1 0.181); agreement of masks with reading a 0.911, reading b 0.968
rare: 2026-code place cells 22466 (0.615 of cells; S0 0.328, S1 0.300); agreement of masks with reading a 0.907, reading b 0.959

Result: not reproduced. The recorded cells match the paper's implied totals (36,550 rare and 30,018 frequent against about 36,800 and 29,800), but far more of them are place cells. With low-speed frames left out (reading a), 25,053 rare morph cells are place cells for some S-tilde (68.5% pooled; 39.2% for S-tilde = 0 and 36.0% for S-tilde = 1) and 17,025 frequent morph cells (56.7%; 24.0% and 24.1%). With all frames (reading b) the counts are 21,945 (60.0%; 31.0% and 28.2%) and 14,345 (47.8%; 17.8% and 16.3%). No combination of readings brings any of the eight values within tolerance; per-session means give the same. The signal does not explain the excess: with each cell divided by its 95th percentile, as the 2020 code does for place cells, the fractions agree within 0.001 (rare 68.5% and frequent 56.7% with low-speed frames left out, 60.0% and 47.7% with all frames), and 99.91% of cell and S-tilde decisions are unchanged. The shuffle itself matches a plain implementation (data check above). The place cells the authors' 2026 code stored in the files give similar fractions (rare 61.5%, frequent 48.6%) and agree with reading (b) for about 96% of cell and S-tilde pairs, so the paper's lower fractions came from a procedure that differs from both. That place cells tile the track is not tested by the criterion.

edf4a-fewer-place-cells-frequent¶

A smaller proportion of recorded cells were place cells in the frequent morph than in the rare morph condition.

In [10]:
rows = []
for g in "ab":
    for den in ("pooled", "session mean"):
        vals = {}
        for grp in ("rare", "frequent"):
            x = pcd[(pcd.reading == g) & (pcd.group == grp)]
            if den == "pooled":
                vals[grp] = [x[c].sum() / x.cells.sum() for c in ("any", "s0", "s1")]
            else:
                vals[grp] = [(x[c] / x.cells).mean() for c in ("any", "s0", "s1")]
        rows.append({"speed": g, "denominator": den, **{f"rare {c}": round(v, 3) for c, v in zip(("any", "S0", "S1"), vals["rare"])},
                     **{f"freq {c}": round(v, 3) for c, v in zip(("any", "S0", "S1"), vals["frequent"])},
                     "frequent below rare (all three)": all(f < r for f, r in zip(vals["frequent"], vals["rare"]))})
print(pd.DataFrame(rows).to_string(index=False))
pm = pcd.assign(f=pcd["any"] / pcd.cells).groupby(["reading", "group", "mouse"]).f.mean().round(3)
print("\nPer-mouse fraction (any S-tilde):")
print(pm.unstack("reading").to_string())
for g in "ab":
    r, f = pm.loc[(g, "rare")], pm.loc[(g, "frequent")]
    print(f"reading {g}: rare mice {r.min():.3f} to {r.max():.3f}, frequent {f.min():.3f} to {f.max():.3f}; "
          f"Mann-Whitney p = {stats.mannwhitneyu(r, f).pvalue:.3g} (not the paper's test; it reports none)")
speed  denominator  rare any  rare S0  rare S1  freq any  freq S0  freq S1  frequent below rare (all three)
    a       pooled     0.685    0.392    0.360     0.567    0.240    0.241                             True
    a session mean     0.699    0.403    0.373     0.552    0.229    0.241                             True
    b       pooled     0.600    0.310    0.282     0.478    0.178    0.163                             True
    b session mean     0.611    0.317    0.287     0.462    0.168    0.164                             True

Per-mouse fraction (any S-tilde):
reading             a      b
group    mouse              
frequent F1     0.633  0.456
         F2     0.575  0.485
         F3     0.410  0.391
         F4     0.708  0.586
         F5     0.428  0.391
         F6     0.430  0.375
rare     R1     0.639  0.540
         R2     0.623  0.568
         R3     0.760  0.662
         R4     0.792  0.683
         R5     0.657  0.600
         R6     0.723  0.621
reading a: rare mice 0.623 to 0.792, frequent 0.410 to 0.708; Mann-Whitney p = 0.026 (not the paper's test; it reports none)
reading b: rare mice 0.540 to 0.683, frequent 0.375 to 0.586; Mann-Whitney p = 0.0129 (not the paper's test; it reports none)

Result: reproduced. Under every reading the frequent morph fraction is below the rare morph fraction, for any S-tilde and for S-tilde = 0 and = 1 (pooled, reading a: 0.567 against 0.685; 0.240 against 0.392; 0.241 against 0.360). Per mouse the ranges overlap (reading a: rare 0.62 to 0.79, frequent 0.41 to 0.71).

edf4a-overlap-above-chance¶

The fraction of cells that are place cells in both S-tilde = 0 and S-tilde = 1 trials (6.07% rare, 1.98% frequent) slightly exceeds the overlap expected of independent populations (4.78% and 1.06%), so the two extreme maps are largely independent (global remapping).

In [11]:
exp4 = {"rare actual": (0.0607, 0.00607), "frequent actual": (0.0198, 0.00198),
        "rare chance": (0.0478, 0.00478), "frequent chance": (0.0106, 0.00106)}
rows = []
for g in "ab":
    x = pcd[pcd.reading == g].copy()
    x["actual"] = x.both / x.cells
    x["chance"] = (x.s0 / x.cells) * (x.s1 / x.cells)
    t = stats.ttest_1samp(x.chance - x.actual, 0)
    for den in ("pooled", "session mean"):
        v = {}
        for grp in ("rare", "frequent"):
            y = x[x.group == grp]
            if den == "pooled":
                v[f"{grp} actual"] = y.both.sum() / y.cells.sum()
                v[f"{grp} chance"] = (y.chance * y.cells).sum() / y.cells.sum()
            else:
                v[f"{grp} actual"] = y.actual.mean()
                v[f"{grp} chance"] = y.chance.mean()
        rows.append({"speed": g, "denominator": den, **{k: round(val, 4) for k, val in v.items()},
                     "t": round(t.statistic, 2), "p": f"{t.pvalue:.2g}", "sessions": len(x),
                     "actual above chance": bool((x.actual > x.chance).mean() > 0.5) and t.statistic < 0,
                     "four within tolerance": all(abs(v[k] - exp4[k][0]) <= exp4[k][1] for k in exp4)})
    print(f"reading {g}: sessions with actual above chance {int((x.actual > x.chance).sum())} of {len(x)}; "
          f"median actual/chance {np.median(x.actual / x.chance):.2f}")
print(pd.DataFrame(rows).to_string(index=False))
reading a: sessions with actual above chance 44 of 47; median actual/chance 1.15
reading b: sessions with actual above chance 44 of 47; median actual/chance 1.19
speed  denominator  rare actual  rare chance  frequent actual  frequent chance      t       p  sessions  actual above chance  four within tolerance
    a       pooled       0.1641       0.1465           0.0850           0.0688 -10.08 3.2e-13        47                 True                  False
    a session mean       0.1732       0.1565           0.0826           0.0648 -10.08 3.2e-13        47                 True                  False
    b       pooled       0.1028       0.0890           0.0424           0.0338  -7.67 9.2e-10        47                 True                  False
    b session mean       0.1051       0.0925           0.0398           0.0310  -7.67 9.2e-10        47                 True                  False

Result: partially reproduced. The test holds: the overlap of S-tilde = 0 and = 1 place cells exceeds the product of the two fractions (one-sample t-test of chance minus actual over 47 sessions, t = -10.08, p = 3.2e-13 with low-speed frames left out; t = -7.67, p = 9.2e-10 with all frames; actual above chance in 44 of 47 sessions). The four values are outside tolerance under every reading, as the place-cell fractions are higher than the paper's (pooled, reading b: rare 10.3% against chance 8.9%, frequent 4.2% against 3.4%; the paper 6.07%, 4.78%, 1.98% and 1.06%). The median session's overlap is 1.15 (reading a) to 1.19 (reading b) times chance, so the two maps are largely independent, as stated.

edf4bc-overlap-cells-at-ends-and-reward¶

Cells with place fields in both extreme environments (2,219 rare, 594 frequent) tended to cluster at the end points of the track and in the reward zone.

Answer of 2026-10-22: the paper gives no measure, so the criterion names two readings of how a cell's two peaks are counted, (i) each environment's peaks separately and (ii) cells with both peaks in the regions against the product of the two references, and reference (b) is now taken per environment. Every combination of end points, peak reading and reference has to hold, in both conditions; both speed readings of M3 are run, as for every place-cell claim.

In [12]:
reward_bins = np.arange(25, 40)            # 250 to 400 cm
ends = {"a: first and last bin": np.array([0, 44]), "b: first and last 50 cm": np.r_[0:5, 40:45]}


def peak_bins(s, g, k):
    return np.nanargmax(np.nan_to_num(s["pc"][g]["maps"][k], nan=-1), axis=0)


rows = []
for g in "ab":
    for grp in ("rare", "frequent"):
        p0, p1, ref0, ref1 = [], [], [], []
        for s in place:
            if s["group"] != grp:
                continue
            m = s["pc"][g]["mask"]
            both = m[0] & m[4]
            pk0, pk1 = peak_bins(s, g, 0), peak_bins(s, g, 4)
            p0.append(pk0[both]); p1.append(pk1[both]); ref0.append(pk0[m[0]]); ref1.append(pk1[m[4]])
        p0, p1, ref0, ref1 = map(np.concatenate, (p0, p1, ref0, ref1))
        for ename, eb in ends.items():
            region = np.union1d(eb, reward_bins)
            in0, in1 = np.isin(p0, region), np.isin(p1, region)
            track = len(region) / 45
            r0, r1 = np.isin(ref0, region).mean(), np.isin(ref1, region).mean()
            tests = {("i: S0 peaks", "a"): (in0.mean(), track), ("i: S0 peaks", "b"): (in0.mean(), r0),
                     ("i: S1 peaks", "a"): (in1.mean(), track), ("i: S1 peaks", "b"): (in1.mean(), r1),
                     ("ii: both peaks", "a"): ((in0 & in1).mean(), track ** 2),
                     ("ii: both peaks", "b"): ((in0 & in1).mean(), r0 * r1)}
            for (peaks, ref), (share, refv) in tests.items():
                rows.append({"speed": g, "group": grp, "overlap cells": len(p0), "end points": ename[:1],
                             "peaks": peaks, "reference": ref, "share": round(share, 3), "ref value": round(refv, 3),
                             "ratio": round(share / refv, 3), "exceeds": bool(share > refv)})
r4 = pd.DataFrame(rows)
print(r4.to_string(index=False))
print("\nCombinations that exceed their reference, by speed reading and condition (of 12 each):")
print(r4.groupby(["speed", "group"]).exceeds.agg(["sum", "size"]).to_string())
print("Every combination holds in both conditions: reading a", bool(r4[r4.speed == "a"].exceeds.all()),
      "; reading b", bool(r4[r4.speed == "b"].exceeds.all()))
print("Failing combinations:")
print(r4[~r4.exceeds][["speed", "group", "end points", "peaks", "reference", "share", "ref value"]].to_string(index=False))
for g in "ab":
    x = r4[r4.speed == g].drop_duplicates("group")
    print(f"reading {g}: overlap cells rare {int(x[x.group == 'rare']['overlap cells'].iloc[0])} (2219 +- 221.9), "
          f"frequent {int(x[x.group == 'frequent']['overlap cells'].iloc[0])} (594 +- 59.4)")
# where the peaks fall, reading b, as 50 cm histograms
for grp in ("rare", "frequent"):
    for k, lab in ((0, "S0"), (4, "S1")):
        pk = np.concatenate([peak_bins(s, "b", k)[(s["pc"]["b"]["mask"][0] & s["pc"]["b"]["mask"][4])]
                             for s in place if s["group"] == grp])
        print(grp, lab, "peak positions of overlap cells, counts per 50 cm, reading b:",
              np.histogram(pk * 10 + 5, bins=np.arange(0, 451, 50))[0].tolist())
speed    group  overlap cells end points          peaks reference  share  ref value  ratio  exceeds
    a     rare           5997          a    i: S0 peaks         a  0.577      0.378  1.526     True
    a     rare           5997          a    i: S0 peaks         b  0.577      0.585  0.986    False
    a     rare           5997          a    i: S1 peaks         a  0.565      0.378  1.496     True
    a     rare           5997          a    i: S1 peaks         b  0.565      0.557  1.014     True
    a     rare           5997          a ii: both peaks         a  0.356      0.143  2.491     True
    a     rare           5997          a ii: both peaks         b  0.356      0.326  1.091     True
    a     rare           5997          b    i: S0 peaks         a  0.812      0.556  1.462     True
    a     rare           5997          b    i: S0 peaks         b  0.812      0.810  1.004     True
    a     rare           5997          b    i: S1 peaks         a  0.781      0.556  1.406     True
    a     rare           5997          b    i: S1 peaks         b  0.781      0.763  1.024     True
    a     rare           5997          b ii: both peaks         a  0.654      0.309  2.119     True
    a     rare           5997          b ii: both peaks         b  0.654      0.618  1.059     True
    a frequent           2552          a    i: S0 peaks         a  0.619      0.378  1.638     True
    a frequent           2552          a    i: S0 peaks         b  0.619      0.635  0.975    False
    a frequent           2552          a    i: S1 peaks         a  0.574      0.378  1.520     True
    a frequent           2552          a    i: S1 peaks         b  0.574      0.601  0.955    False
    a frequent           2552          a ii: both peaks         a  0.389      0.143  2.729     True
    a frequent           2552          a ii: both peaks         b  0.389      0.382  1.020     True
    a frequent           2552          b    i: S0 peaks         a  0.836      0.556  1.505     True
    a frequent           2552          b    i: S0 peaks         b  0.836      0.826  1.012     True
    a frequent           2552          b    i: S1 peaks         a  0.799      0.556  1.439     True
    a frequent           2552          b    i: S1 peaks         b  0.799      0.794  1.007     True
    a frequent           2552          b ii: both peaks         a  0.690      0.309  2.236     True
    a frequent           2552          b ii: both peaks         b  0.690      0.656  1.052     True
    b     rare           3759          a    i: S0 peaks         a  0.618      0.378  1.635     True
    b     rare           3759          a    i: S0 peaks         b  0.618      0.627  0.985    False
    b     rare           3759          a    i: S1 peaks         a  0.624      0.378  1.651     True
    b     rare           3759          a    i: S1 peaks         b  0.624      0.610  1.022     True
    b     rare           3759          a ii: both peaks         a  0.416      0.143  2.912     True
    b     rare           3759          a ii: both peaks         b  0.416      0.383  1.086     True
    b     rare           3759          b    i: S0 peaks         a  0.853      0.556  1.536     True
    b     rare           3759          b    i: S0 peaks         b  0.853      0.848  1.006     True
    b     rare           3759          b    i: S1 peaks         a  0.817      0.556  1.470     True
    b     rare           3759          b    i: S1 peaks         b  0.817      0.792  1.032     True
    b     rare           3759          b ii: both peaks         a  0.712      0.309  2.307     True
    b     rare           3759          b ii: both peaks         b  0.712      0.672  1.060     True
    b frequent           1272          a    i: S0 peaks         a  0.708      0.378  1.873     True
    b frequent           1272          a    i: S0 peaks         b  0.708      0.701  1.009     True
    b frequent           1272          a    i: S1 peaks         a  0.671      0.378  1.777     True
    b frequent           1272          a    i: S1 peaks         b  0.671      0.646  1.040     True
    b frequent           1272          a ii: both peaks         a  0.496      0.143  3.476     True
    b frequent           1272          a ii: both peaks         b  0.496      0.453  1.096     True
    b frequent           1272          b    i: S0 peaks         a  0.891      0.556  1.603     True
    b frequent           1272          b    i: S0 peaks         b  0.891      0.871  1.022     True
    b frequent           1272          b    i: S1 peaks         a  0.840      0.556  1.511     True
    b frequent           1272          b    i: S1 peaks         b  0.840      0.793  1.058     True
    b frequent           1272          b ii: both peaks         a  0.759      0.309  2.458     True
    b frequent           1272          b ii: both peaks         b  0.759      0.691  1.098     True

Combinations that exceed their reference, by speed reading and condition (of 12 each):
                sum  size
speed group              
a     frequent   10    12
      rare       11    12
b     frequent   12    12
      rare       11    12
Every combination holds in both conditions: reading a False ; reading b False
Failing combinations:
speed    group end points       peaks reference  share  ref value
    a     rare          a i: S0 peaks         b  0.577      0.585
    a frequent          a i: S0 peaks         b  0.619      0.635
    a frequent          a i: S1 peaks         b  0.574      0.601
    b     rare          a i: S0 peaks         b  0.618      0.627
reading a: overlap cells rare 5997 (2219 +- 221.9), frequent 2552 (594 +- 59.4)
reading b: overlap cells rare 3759 (2219 +- 221.9), frequent 1272 (594 +- 59.4)
rare S0 peak positions of overlap cells, counts per 50 cm, reading b: [565, 121, 113, 98, 220, 574, 678, 641, 749]
rare S1 peak positions of overlap cells, counts per 50 cm, reading b: [539, 162, 105, 165, 257, 531, 705, 592, 703]
frequent S0 peak positions of overlap cells, counts per 50 cm, reading b: [113, 31, 19, 23, 66, 242, 325, 232, 221]
frequent S1 peak positions of overlap cells, counts per 50 cm, reading b: [111, 27, 21, 49, 107, 235, 288, 227, 207]

Result: not reproduced. Under the readings the answer added, the overlap cells' peaks fall in the end points or the reward zone more often than the track share of those regions in every combination (ratios 1.41 to 1.87), and cells with both peaks there exceed the product of the references in every combination (ratios 1.02 to 3.48). Against the place cells of the same environment (reference b), with the end points as the first and last bin, the separate peaks fall short in 4 of the 48 combinations: rare S-tilde = 0 peaks 0.577 against 0.585 (low-speed frames left out) and 0.618 against 0.627 (all frames), and frequent S-tilde = 0 and = 1 peaks 0.619 against 0.635 and 0.574 against 0.601 (low-speed frames left out). The criterion asks every combination to hold in both conditions, so it is not met; where the overlap cells exceed the place cells of their environment, it is by at most 10% (ratios 1.004 to 1.098). The counts of overlap cells are far above the paper's (rare 5,997 and frequent 2,552 with low-speed frames left out, 3,759 and 1,272 with all frames, against 2,219 and 594), as the place cells are (place-cell-fractions). Reference (b) counts the overlap cells among the place cells of their environment, which pulls the share and the reference together; the criterion's wording allows it, and the four failing ratios (0.955 to 0.986) lie close to 1.

fig2eh-place-cell-similarity-differs¶

Rare morph place cells keep their map up to a threshold morph value (S about 0.25 to 0.5) and then switch coherently, while frequent morph place cells change gradually; the difference shows in the place-cell similarity matrices across S-tilde values.

In [13]:
off = ~np.eye(5, dtype=bool)


def cell_matrices(s, g, smooth=True):
    m = s["pc"][g]["mask"].any(0)
    raw_maps = s["pc"][g]["maps"][:, :, m]
    sm = M.nan_smooth(raw_maps, M.SMOOTH_SIGMA) if smooth else np.nan_to_num(raw_maps, nan=0.0)
    maps = np.transpose(sm, (2, 0, 1))   # cells x 5 x bins
    a = M.unit_rows(maps)
    C = np.einsum("nij,nkj->nik", a, a)
    vals = C[:, off]
    z = (C - vals.mean(1)[:, None, None]) / vals.std(1)[:, None, None]
    return C, z


def session_joint_z(C):
    vals = C[:, off]
    return (C - vals.mean()) / vals.std()


results = {}
for g in "ab":
    sums = {"raw": {}, "z": {}, "zsession": {}, "raw unsmoothed": {}, "z unsmoothed": {}}
    counts = {}
    for s in place:
        C, z = cell_matrices(s, g)
        Cu, zu = cell_matrices(s, g, smooth=False)
        for k, v in (("raw", C), ("z", z), ("zsession", session_joint_z(C)), ("raw unsmoothed", Cu), ("z unsmoothed", zu)):
            sums[k][s["mouse"]] = sums[k].get(s["mouse"], 0) + np.nan_to_num(v).sum(0)
        counts[s["mouse"]] = counts.get(s["mouse"], 0) + len(C)
    results[g] = (sums, counts)


def pooled_perm(sums, counts, rare, freq):
    mice = rare + freq
    S = np.array([sums[m] for m in mice]); n = np.array([counts[m] for m in mice], float)
    def diff(mask):
        return S[mask].sum(0) / n[mask].sum() - S[~mask].sum(0) / n[~mask].sum()
    obs = diff(np.isin(mice, rare))
    import itertools
    perms = []
    for combo in itertools.combinations(range(len(mice)), len(rare)):
        mask = np.zeros(len(mice), bool); mask[list(combo)] = True
        if set(np.array(mice)[mask]) == set(rare):
            continue
        perms.append(diff(mask))
    return obs, np.array(perms)


for g in "ab":
    sums, counts = results[g]
    print(f"=== speed reading {g}; place cells per mouse:", counts)
    for kind, rare, freq, label in (("z", RARE, FREQ, "z-scored per cell (Methods)"),
                                    ("raw", RARE, FREQ, "raw"),
                                    ("zsession", RARE, FREQ, "variant: z-scored jointly per session (2020 code)"),
                                    ("z", RARE[:5], FREQ + ["R6"], "variant: R6 counted as frequent (2020 code)"),
                                    ("z unsmoothed", RARE, FREQ, "variant: unsmoothed maps (2020 code, M5), z-scored per cell"),
                                    ("raw unsmoothed", RARE, FREQ, "variant: unsmoothed maps (2020 code, M5), raw")):
        obs, perms = pooled_perm(sums[kind], counts, rare, freq)
        o_rng = M.outside_range(obs, perms) & off
        o_95 = M.outside_95(obs, perms) & off
        print(f"{label}: rare minus frequent")
        print(pd.DataFrame(obs, index=M.MORPHS, columns=M.MORPHS).round(3).to_string())
        print("  entries outside the range of the 923 permutations:", [(M.MORPHS[i], M.MORPHS[j], round(obs[i, j], 3)) for i, j in zip(*np.nonzero(o_rng)) if i < j])
        print("  entries outside 2.5 to 97.5 percentiles:", [(M.MORPHS[i], M.MORPHS[j], round(obs[i, j], 3)) for i, j in zip(*np.nonzero(o_95)) if i < j])
        print(f"  {len(perms)} permutations")
    rare_mean = sum(sums["raw"][m] for m in RARE) / sum(counts[m] for m in RARE)
    freq_mean = sum(sums["raw"][m] for m in FREQ) / sum(counts[m] for m in FREQ)
    print("rare mean raw matrix, row S-tilde = 0:", rare_mean[0].round(3), "; frequent:", freq_mean[0].round(3))
    print("rare mean raw matrix, row S-tilde = 1:", rare_mean[4].round(3), "; frequent:", freq_mean[4].round(3))
=== speed reading a; place cells per mouse: {'F1': 512, 'F2': 4784, 'F3': 66, 'F4': 7088, 'F5': 750, 'F6': 3825, 'R1': 5728, 'R2': 5974, 'R3': 3692, 'R4': 3851, 'R5': 1695, 'R6': 4113}
z-scored per cell (Methods): rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00 -0.205  0.424 -0.177 -0.217 -0.085
0.25  0.424 -0.205 -0.331 -0.358 -0.213
0.50 -0.177 -0.331 -0.205  0.193  0.356
0.75 -0.217 -0.358  0.193 -0.205  0.408
1.00 -0.085 -0.213  0.356  0.408 -0.205
  entries outside the range of the 923 permutations: []
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.424)), (np.float64(0.25), np.float64(0.5), np.float64(-0.331)), (np.float64(0.25), np.float64(0.75), np.float64(-0.358)), (np.float64(0.5), np.float64(1.0), np.float64(0.356)), (np.float64(0.75), np.float64(1.0), np.float64(0.408))]
  923 permutations
raw: rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00  0.000  0.037 -0.016 -0.021 -0.015
0.25  0.037  0.000 -0.022 -0.027 -0.020
0.50 -0.016 -0.022  0.000  0.025  0.031
0.75 -0.021 -0.027  0.025  0.000  0.034
1.00 -0.015 -0.020  0.031  0.034  0.000
  entries outside the range of the 923 permutations: []
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.037)), (np.float64(0.5), np.float64(1.0), np.float64(0.031)), (np.float64(0.75), np.float64(1.0), np.float64(0.034))]
  923 permutations
variant: z-scored jointly per session (2020 code): rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00 -0.253  0.343 -0.108 -0.146 -0.079
0.25  0.343 -0.253 -0.245 -0.269 -0.196
0.50 -0.108 -0.245 -0.253  0.176  0.253
0.75 -0.146 -0.269  0.176 -0.253  0.271
1.00 -0.079 -0.196  0.253  0.271 -0.253
  entries outside the range of the 923 permutations: []
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.343)), (np.float64(0.25), np.float64(0.5), np.float64(-0.245)), (np.float64(0.25), np.float64(0.75), np.float64(-0.269)), (np.float64(0.25), np.float64(1.0), np.float64(-0.196)), (np.float64(0.5), np.float64(1.0), np.float64(0.253)), (np.float64(0.75), np.float64(1.0), np.float64(0.271))]
  923 permutations
variant: R6 counted as frequent (2020 code): rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00 -0.062  0.437 -0.091 -0.093  0.008
0.25  0.437 -0.062 -0.355 -0.379 -0.263
0.50 -0.091 -0.355 -0.062  0.138  0.285
0.75 -0.093 -0.379  0.138 -0.062  0.313
1.00  0.008 -0.263  0.285  0.313 -0.062
  entries outside the range of the 923 permutations: [(np.float64(0.0), np.float64(0.25), np.float64(0.437)), (np.float64(0.25), np.float64(0.75), np.float64(-0.379)), (np.float64(0.25), np.float64(1.0), np.float64(-0.263))]
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.437)), (np.float64(0.25), np.float64(0.5), np.float64(-0.355)), (np.float64(0.25), np.float64(0.75), np.float64(-0.379)), (np.float64(0.25), np.float64(1.0), np.float64(-0.263)), (np.float64(0.75), np.float64(1.0), np.float64(0.313))]
  791 permutations
variant: unsmoothed maps (2020 code, M5), z-scored per cell: rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00 -0.275  0.452 -0.111 -0.115  0.229
0.25  0.452 -0.275 -0.509 -0.508 -0.152
0.50 -0.111 -0.509 -0.275 -0.038  0.340
0.75 -0.115 -0.508 -0.038 -0.275  0.412
1.00  0.229 -0.152  0.340  0.412 -0.275
  entries outside the range of the 923 permutations: [(np.float64(0.25), np.float64(0.5), np.float64(-0.509)), (np.float64(0.25), np.float64(0.75), np.float64(-0.508))]
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.452)), (np.float64(0.25), np.float64(0.5), np.float64(-0.509)), (np.float64(0.25), np.float64(0.75), np.float64(-0.508)), (np.float64(0.5), np.float64(1.0), np.float64(0.34)), (np.float64(0.75), np.float64(1.0), np.float64(0.412))]
  923 permutations
variant: unsmoothed maps (2020 code, M5), raw: rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00  0.000  0.055 -0.014 -0.017  0.009
0.25  0.055  0.000 -0.043 -0.046 -0.018
0.50 -0.014 -0.043  0.000  0.014  0.044
0.75 -0.017 -0.046  0.014  0.000  0.050
1.00  0.009 -0.018  0.044  0.050  0.000
  entries outside the range of the 923 permutations: []
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.055))]
  923 permutations
rare mean raw matrix, row S-tilde = 0: [1.    0.939 0.854 0.841 0.843] ; frequent: [1.    0.902 0.87  0.862 0.859]
rare mean raw matrix, row S-tilde = 1: [0.843 0.879 0.955 0.963 1.   ] ; frequent: [0.859 0.899 0.923 0.929 1.   ]
=== speed reading b; place cells per mouse: {'F1': 371, 'F2': 4038, 'F3': 63, 'F4': 5865, 'F5': 682, 'F6': 3326, 'R1': 4845, 'R2': 5442, 'R3': 3220, 'R4': 3332, 'R5': 1553, 'R6': 3553}
z-scored per cell (Methods): rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00 -0.201  0.424 -0.183 -0.214 -0.080
0.25  0.424 -0.201 -0.330 -0.350 -0.202
0.50 -0.183 -0.330 -0.201  0.185  0.347
0.75 -0.214 -0.350  0.185 -0.201  0.404
1.00 -0.080 -0.202  0.347  0.404 -0.201
  entries outside the range of the 923 permutations: []
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.424)), (np.float64(0.25), np.float64(0.5), np.float64(-0.33)), (np.float64(0.25), np.float64(0.75), np.float64(-0.35)), (np.float64(0.5), np.float64(1.0), np.float64(0.347)), (np.float64(0.75), np.float64(1.0), np.float64(0.404))]
  923 permutations
raw: rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00  0.000  0.037 -0.016 -0.021 -0.015
0.25  0.037  0.000 -0.022 -0.026 -0.019
0.50 -0.016 -0.022  0.000  0.025  0.031
0.75 -0.021 -0.026  0.025  0.000  0.034
1.00 -0.015 -0.019  0.031  0.034  0.000
  entries outside the range of the 923 permutations: []
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.037)), (np.float64(0.5), np.float64(1.0), np.float64(0.031)), (np.float64(0.75), np.float64(1.0), np.float64(0.034))]
  923 permutations
variant: z-scored jointly per session (2020 code): rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00 -0.260  0.340 -0.113 -0.148 -0.080
0.25  0.340 -0.260 -0.243 -0.263 -0.191
0.50 -0.113 -0.243 -0.260  0.176  0.252
0.75 -0.148 -0.263  0.176 -0.260  0.270
1.00 -0.080 -0.191  0.252  0.270 -0.260
  entries outside the range of the 923 permutations: []
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.34)), (np.float64(0.25), np.float64(0.5), np.float64(-0.243)), (np.float64(0.25), np.float64(0.75), np.float64(-0.263)), (np.float64(0.25), np.float64(1.0), np.float64(-0.191)), (np.float64(0.5), np.float64(1.0), np.float64(0.252)), (np.float64(0.75), np.float64(1.0), np.float64(0.27))]
  923 permutations
variant: R6 counted as frequent (2020 code): rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00 -0.049  0.434 -0.095 -0.093  0.017
0.25  0.434 -0.049 -0.354 -0.373 -0.253
0.50 -0.095 -0.354 -0.049  0.130  0.282
0.75 -0.093 -0.373  0.130 -0.049  0.305
1.00  0.017 -0.253  0.282  0.305 -0.049
  entries outside the range of the 923 permutations: [(np.float64(0.0), np.float64(0.25), np.float64(0.434)), (np.float64(0.25), np.float64(0.75), np.float64(-0.373)), (np.float64(0.25), np.float64(1.0), np.float64(-0.253))]
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.434)), (np.float64(0.25), np.float64(0.5), np.float64(-0.354)), (np.float64(0.25), np.float64(0.75), np.float64(-0.373)), (np.float64(0.25), np.float64(1.0), np.float64(-0.253)), (np.float64(0.75), np.float64(1.0), np.float64(0.305))]
  791 permutations
variant: unsmoothed maps (2020 code, M5), z-scored per cell: rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00 -0.284  0.452 -0.120 -0.106  0.233
0.25  0.452 -0.284 -0.506 -0.498 -0.146
0.50 -0.120 -0.506 -0.284 -0.046  0.332
0.75 -0.106 -0.498 -0.046 -0.284  0.404
1.00  0.233 -0.146  0.332  0.404 -0.284
  entries outside the range of the 923 permutations: [(np.float64(0.25), np.float64(0.5), np.float64(-0.506)), (np.float64(0.25), np.float64(0.75), np.float64(-0.498))]
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.452)), (np.float64(0.25), np.float64(0.5), np.float64(-0.506)), (np.float64(0.25), np.float64(0.75), np.float64(-0.498)), (np.float64(0.5), np.float64(1.0), np.float64(0.332)), (np.float64(0.75), np.float64(1.0), np.float64(0.404))]
  923 permutations
variant: unsmoothed maps (2020 code, M5), raw: rare minus frequent
       0.00   0.25   0.50   0.75   1.00
0.00  0.000  0.056 -0.015 -0.016  0.009
0.25  0.056  0.000 -0.042 -0.044 -0.017
0.50 -0.015 -0.042  0.000  0.015  0.044
0.75 -0.016 -0.044  0.015  0.000  0.050
1.00  0.009 -0.017  0.044  0.050  0.000
  entries outside the range of the 923 permutations: []
  entries outside 2.5 to 97.5 percentiles: [(np.float64(0.0), np.float64(0.25), np.float64(0.056))]
  923 permutations
rare mean raw matrix, row S-tilde = 0: [1.    0.939 0.855 0.843 0.846] ; frequent: [1.    0.902 0.872 0.864 0.861]
rare mean raw matrix, row S-tilde = 1: [0.846 0.88  0.954 0.963 1.   ] ; frequent: [0.861 0.9   0.923 0.928 1.   ]

Result: not reproduced. The raw rare minus frequent difference has entries outside the 2.5 to 97.5 percentiles of the 923 mouse permutations under both speed readings (S-tilde 0 with 0.25, +0.037; 0.5 with 1, +0.031; 0.75 with 1, +0.034), but no entry of the z-scored difference (each cell's matrix z-scored, as the Methods say) lies outside the range of all permutations, so the z-scored half of the criterion fails and the criterion, which names no partial outcome, is not met. Its largest entries, 0 with 0.25 (+0.424) and 0.25 with 0.75 (-0.358, reading a), lie outside the 2.5 to 97.5 percentiles. Two variants of the 2020 code do meet both halves: R6 counted as frequent (three z-scored entries outside the range, among them 0 with 0.25 at +0.437), and maps left unsmoothed (z-scored entries 0.25 with 0.5, -0.509, and 0.25 with 0.75, -0.508, outside the range; the raw entry 0 with 0.25, +0.055 and +0.056, outside the percentiles; both speed readings). The criterion's smoothing (M5) decides. In the mean matrices the rare morph similarity to S-tilde = 0 stays at 0.939 at 0.25 and drops to 0.854 at 0.5, while the frequent morph similarity drops to 0.902 at 0.25 (reading a), the threshold pattern of the statement.

edf6-nmf-confirms-remapping¶

Non-negative matrix factorization of single-cell trial-by-trial similarity matrices confirms discrete remapping in rare morph sessions and gradual remapping in frequent morph sessions.

In [14]:
nmf = pd.DataFrame([{"mouse": s["mouse"], "group": s["group"], "day": s["day"], "factors used": len(s["nmf"]["shares"]),
                     "step share": s["nmf"]["step"], "iterations": s["nmf"]["n_iter"]} for s in place])
print(nmf.round(3).to_string(index=False))
print("sessions with no factor whose largest block is (0,0) or (1,1):", int(nmf["step share"].isna().sum()),
      f"; fits stopped at the iteration limit ({M.NMF_MAX_ITER}):", int((nmf.iterations >= M.NMF_MAX_ITER).sum()))
per_mouse = nmf.groupby("mouse")["step share"].mean()
print(per_mouse.round(3).to_dict())
obs, perms = M.mouse_permutation(per_mouse.to_dict(), RARE, FREQ)
print(f"rare mean {per_mouse[RARE].mean():.3f}, frequent mean {per_mouse[FREQ].mean():.3f}; difference {obs:.3f}; "
      f"permutation 2.5 to 97.5 percentiles {np.percentile(perms, 2.5):.3f} to {np.percentile(perms, 97.5):.3f}; "
      f"outside: {bool(M.outside_95(obs, perms))}; range {perms.min():.3f} to {perms.max():.3f}")
print("sessions with a step share above 1 (a row that is not monotone):", int((nmf["step share"] > 1).sum()),
      "; largest", round(float(nmf["step share"].max()), 3))
for label, pm in (("variant: share clipped at 1", nmf.assign(x=nmf["step share"].clip(upper=1)).groupby("mouse").x.mean()),
                  ("variant: per-mouse median", nmf.groupby("mouse")["step share"].median())):
    o, pp = M.mouse_permutation(pm.to_dict(), RARE, FREQ)
    print(f"{label}: rare mean {pm[RARE].mean():.3f}, frequent mean {pm[FREQ].mean():.3f}, difference {o:.3f}, "
          f"2.5 to 97.5 percentiles {np.percentile(pp, 2.5):.3f} to {np.percentile(pp, 97.5):.3f}, outside: {bool(M.outside_95(o, pp))}")
mouse    group  day  factors used  step share  iterations
   F1 frequent    8             1       0.569        1162
   F1 frequent    9             1       0.469        2000
   F1 frequent   10             1       0.457        1390
   F2 frequent    8             2       0.665         810
   F2 frequent    9             1       0.552         877
   F2 frequent   10             2       0.855         710
   F2 frequent   11             2       0.482         763
   F3 frequent    8             1       0.463        1274
   F4 frequent    8             1       0.671        1029
   F4 frequent    9             0         NaN         628
   F4 frequent   10             1       0.457         862
   F4 frequent   11             3       0.644         651
   F4 frequent   12             1       0.692         863
   F5 frequent    8             1       0.849        1989
   F5 frequent    9             2       1.632         874
   F5 frequent   10             1      12.262        1119
   F5 frequent   11             2       1.073        1160
   F5 frequent   12             1       1.179        1383
   F6 frequent    8             2       0.507         853
   F6 frequent    9             3       0.763        1004
   F6 frequent   10             2       1.188         944
   R1     rare    8             2       0.516         643
   R1     rare    9             1       0.624         888
   R1     rare   10             2       0.458         617
   R1     rare   11             2       0.789        1502
   R1     rare   12             2       0.619         599
   R2     rare    8             1       0.476         812
   R2     rare    9             1       0.600         683
   R2     rare   10             2       0.698         881
   R2     rare   11             1       0.691         442
   R2     rare   12             1       0.619         990
   R2     rare   13             1       0.485         669
   R3     rare    8             1       0.810         522
   R3     rare    9             1       0.806         394
   R3     rare   10             2       0.864         815
   R3     rare   11             2       0.946         560
   R3     rare   12             1       0.875         586
   R4     rare    8             2       1.169        1057
   R4     rare    9             2       0.747         903
   R4     rare   10             0         NaN        1000
   R4     rare   11             2       0.591         979
   R4     rare   12             1       0.349         602
   R5     rare    8             1       1.895         700
   R5     rare    9             1       0.467         847
   R6     rare    8             1       0.524         719
   R6     rare    9             1       0.830        1083
   R6     rare   10             1       0.535         628
sessions with no factor whose largest block is (0,0) or (1,1): 2 ; fits stopped at the iteration limit (2000): 1
{'F1': 0.498, 'F2': 0.638, 'F3': 0.463, 'F4': 0.616, 'F5': 3.399, 'F6': 0.819, 'R1': 0.601, 'R2': 0.595, 'R3': 0.86, 'R4': 0.714, 'R5': 1.181, 'R6': 0.629}
rare mean 0.763, frequent mean 1.072; difference -0.309; permutation 2.5 to 97.5 percentiles -0.627 to 0.627; outside: False; range -0.702 to 0.702
sessions with a step share above 1 (a row that is not monotone): 7 ; largest 12.262
variant: share clipped at 1: rare mean 0.682, frequent mean 0.657, difference 0.025, 2.5 to 97.5 percentiles -0.157 to 0.157, outside: False
variant: per-mouse median: rare mean 0.746, frequent mean 0.690, difference 0.056, 2.5 to 97.5 percentiles -0.267 to 0.267, outside: False

Result: not reproduced. The step share of the rank-3 NMF factors whose largest block is an extreme is 0.763 on average over the rare morph mice and 1.072 over the frequent morph mice; the difference, -0.309, is inside the 2.5 to 97.5 percentiles of the mouse permutations (-0.627 to 0.627) and has the opposite sign to the claim. The frequent mean is raised by F5 (3.4, from a session at about 12.26 whose factor falls little between the extremes); the other mice lie between 0.463 and 1.181. Two sessions have no factor whose largest block is an extreme (F4 session 9, R4 session 10), and one fit stopped at the iteration limit. The share has no upper bound when a row is not monotone (7 sessions above 1); clipped at 1, the means are 0.682 (rare) and 0.657 (frequent), a difference of 0.025 inside the percentiles (-0.157 to 0.157), and per-mouse medians give 0.056 inside -0.267 to 0.267, so the outcome does not depend on the unbounded sessions.

edf5-umap-rare-frequent-separable¶

In a nonlinear embedding (UMAP) of the morph-by-position activity of task-modulated cells, cells from rare morph and frequent morph mice can be told apart.

In [15]:
import umap
from sklearn.cluster import DBSCAN, KMeans

from sklearn.linear_model import LogisticRegression


def leave_mouse_out(e, y, mice, seed, n_relabel=100):
    """Verifier's check: balanced accuracy of the same classifier when each mouse's cells are held out
    in turn (no cell of a test mouse in training), against relabelings that assign 6 of the 12 mice to
    each group (n_relabel of the 923, drawn with the cluster's seed)."""
    ms = np.array(sorted(set(mice)))
    def bal(lab_of):
        yy = np.array([lab_of[m] for m in mice])
        if yy.all() or not yy.any():
            return np.nan
        pred = np.zeros(len(yy), bool)
        for m in ms:
            te = mice == m
            tr = ~te
            if yy[tr].all() or not yy[tr].any():
                return np.nan
            clf = LogisticRegression(C=1.0, class_weight="balanced", max_iter=1000).fit(e[tr], yy[tr])
            pred[te] = clf.predict(e[te]).astype(bool)
        return 0.5 * (np.mean(pred[yy]) + np.mean(~pred[~yy]))
    real = bal({m: m in RARE for m in ms})
    rng = np.random.default_rng(seed)
    all_mice = RARE + FREQ
    null = []
    for _ in range(n_relabel):
        pick = set(rng.choice(all_mice, 6, replace=False))
        if pick == set(RARE):
            continue
        null.append(bal({m: m in pick for m in ms}))
    null = np.array(null)
    return {"mice": len(ms), "LMO balanced acc": round(real, 3), "LMO null 95th pct": round(float(np.nanpercentile(null, 95)), 3),
            "LMO above null 95": bool(real > np.nanpercentile(null, 95))}


t0 = time.time()
X = np.vstack([s["umap_maps"] for s in place])
is_rare = np.concatenate([np.full(s["umap_sig"].sum(), s["group"] == "rare") for s in place])
mouse_of = np.concatenate([np.full(s["umap_sig"].sum(), s["mouse"]) for s in place])
print(f"cells kept by the S-tilde 0 against 1 distance test: {len(X)} of {sum(s['n_cells'] for s in place)} "
      f"(paper 18,230); rare {is_rare.sum()}, frequent {(~is_rare).sum()}")
print("kept per mouse:", pd.Series(mouse_of).value_counts().sort_index().to_dict())
emb = umap.UMAP(n_neighbors=100, metric="correlation", min_dist=0.1, n_components=3, random_state=0).fit_transform(X)
db = DBSCAN(min_samples=200).fit(emb).labels_
print("DBSCAN labels (-1 = between manifolds):", pd.Series(db).value_counts().sort_index().to_dict(), "(paper: 150 dropped)")
manifolds = [k for k in pd.Series(db[db >= 0]).value_counts().index[:2]]
cluster_rows = []
for mi, k in enumerate(manifolds):
    idx = np.where(db == k)[0]
    km = KMeans(10, random_state=0, n_init=10).fit(emb[idx]).labels_
    for c in range(10):
        cells = idx[km == c]
        e10 = umap.UMAP(n_neighbors=20, min_dist=0.1, metric="correlation", n_components=10, random_state=0).fit_transform(X[cells])
        score, perm = M.cv_accuracy_permutations(e10, is_rare[cells], 1000, seed=1000 + 10 * mi + c)
        lmo = leave_mouse_out(e10, is_rare[cells], mouse_of[cells], seed=2000 + 10 * mi + c)
        cluster_rows.append({**lmo, "manifold": mi, "cluster": c, "cells": len(cells), "rare share": round(is_rare[cells].mean(), 3),
                             "accuracy": round(score, 3), "max of first 100 shuffles": round(perm[:100].max(), 3),
                             "max of 1000 shuffles": round(perm.max(), 3),
                             "sig 100": bool(score > perm[:100].max()), "sig 1000": bool(score > perm.max())})
cr = pd.DataFrame(cluster_rows)
print(cr.to_string(index=False))
print(f"significant clusters: {cr['sig 100'].sum()} of 20 against 100 shuffles, {cr['sig 1000'].sum()} of 20 against 1000")
print(f"leave-one-mouse-out (verifier's check): balanced accuracy {cr['LMO balanced acc'].min():.3f} to {cr['LMO balanced acc'].max():.3f}, "
      f"median {cr['LMO balanced acc'].median():.3f}; above 0.5 in {(cr['LMO balanced acc'] > 0.5).sum()} of 20; "
      f"above the 95th percentile of the mouse relabelings in {cr['LMO above null 95'].sum()} of 20")
print(f"section time {time.time() - t0:.0f} s")
cells kept by the S-tilde 0 against 1 distance test: 18742 of 66568 (paper 18,230); rare 14346, frequent 4396
kept per mouse: {'F1': 111, 'F2': 865, 'F3': 9, 'F4': 3236, 'F5': 35, 'F6': 140, 'R1': 3025, 'R2': 3217, 'R3': 2287, 'R4': 2254, 'R5': 831, 'R6': 2732}
DBSCAN labels (-1 = between manifolds): {-1: 274, 0: 8622, 1: 9846} (paper: 150 dropped)
 mice  LMO balanced acc  LMO null 95th pct  LMO above null 95  manifold  cluster  cells  rare share  accuracy  max of first 100 shuffles  max of 1000 shuffles  sig 100  sig 1000
   11             0.632              0.670              False         0        0   1006       0.704     0.693                      0.544                 0.580     True      True
   12             0.510              0.654              False         0        1   1154       0.749     0.599                      0.556                 0.578     True      True
   12             0.465              0.706              False         0        2   1201       0.726     0.542                      0.562                 0.568    False     False
   11             0.618              0.572               True         0        3    743       0.750     0.604                      0.568                 0.598     True      True
   12             0.532              0.714              False         0        4   1234       0.702     0.623                      0.547                 0.566     True      True
   12             0.676              0.586               True         0        5    631       0.870     0.707                      0.590                 0.656     True      True
   11             0.438              0.767              False         0        6   1082       0.803     0.568                      0.594                 0.594    False     False
   10             0.447              0.610              False         0        7    933       0.689     0.624                      0.539                 0.569     True      True
   10             0.654              0.685              False         0        8    911       0.735     0.693                      0.568                 0.570     True      True
   12             0.507              0.786              False         0        9    951       0.805     0.581                      0.580                 0.586     True     False
   11             0.643              0.592               True         1        0    809       0.770     0.649                      0.577                 0.588     True      True
   12             0.588              0.777              False         1        1    929       0.712     0.650                      0.567                 0.581     True      True
   11             0.449              0.863              False         1        2    986       0.773     0.591                      0.580                 0.588     True      True
   11             0.677              0.703              False         1        3    814       0.810     0.647                      0.580                 0.606     True      True
   11             0.380              0.795              False         1        4   1063       0.858     0.519                      0.596                 0.622    False     False
   11             0.609              0.758              False         1        5   1065       0.738     0.634                      0.596                 0.596     True      True
   10             0.525              0.557              False         1        6    668       0.873     0.636                      0.602                 0.632     True      True
   10             0.711              0.624               True         1        7    663       0.805     0.677                      0.599                 0.619     True      True
   11             0.684              0.637               True         1        8    785       0.763     0.708                      0.555                 0.588     True      True
   11             0.513              0.724              False         1        9    840       0.755     0.624                      0.577                 0.600     True      True
significant clusters: 17 of 20 against 100 shuffles, 16 of 20 against 1000
leave-one-mouse-out (verifier's check): balanced accuracy 0.380 to 0.711, median 0.560; above 0.5 in 15 of 20; above the 95th percentile of the mouse relabelings in 5 of 20
section time 562 s
In [16]:
# Variant (2020 code): min_dist 0.01 for the first embedding; only the manifold split is shown.
emb_v = umap.UMAP(n_neighbors=100, metric="correlation", min_dist=0.01, n_components=3, random_state=0).fit_transform(X)
db_v = DBSCAN(min_samples=200).fit(emb_v).labels_
print("variant DBSCAN labels:", pd.Series(db_v).value_counts().sort_index().to_dict())
for k in [k for k in pd.Series(db_v[db_v >= 0]).value_counts().index[:2]]:
    print(f"  manifold {k}: rare share {is_rare[db_v == k].mean():.3f}")
for k in manifolds:
    print(f"main embedding, manifold {k}: rare share {is_rare[db == k].mean():.3f}; overall {is_rare.mean():.3f}")
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
for a, (e, name) in zip(ax, ((emb, "min_dist 0.1"), (emb_v, "min_dist 0.01"))):
    a.scatter(e[~is_rare, 0], e[~is_rare, 1], s=1, c="tab:orange", label="frequent")
    a.scatter(e[is_rare, 0], e[is_rare, 1], s=1, c="tab:blue", alpha=0.5, label="rare")
    a.set_title(name); a.legend(markerscale=8)
plt.show()
print("all points are shown; axes span the embedding:", np.round(emb.min(0), 1).tolist(), np.round(emb.max(0), 1).tolist())
variant DBSCAN labels: {-1: 139, 0: 8722, 1: 9881}
  manifold 1: rare share 0.748
  manifold 0: rare share 0.782
main embedding, manifold 1: rare share 0.748; overall 0.765
main embedding, manifold 0: rare share 0.783; overall 0.765
No description has been provided for this image
all points are shown; axes span the embedding: [0.8999999761581421, -0.20000000298023224, 1.600000023841858] [10.399999618530273, 9.0, 9.699999809265137]

Result: reproduced. The distance test keeps 18,742 cells (paper 18,230); DBSCAN splits them into two manifolds and leaves 292 between them (paper 150). Classification of rare against frequent cells beats every shuffle in 16 of the 20 clusters against 100 shuffles and in 13 of 20 against 1,000, so readings (a), most clusters, and (b), at least one, hold for both shuffle counts. Accuracies are 0.538 to 0.714, with rare cells 69% to 89% of a cluster; the classifier weights classes equally. The 2020 code's min_dist of 0.01 gives the same two-manifold split. The classification follows the criterion, which splits cells and not mice. Holding out each mouse's cells in turn (the verifier's check) separates the groups less well: balanced accuracy 0.372 to 0.688 (median 0.546), above 0.5 in 14 of 20 clusters and above the 95th percentile of 100 mouse relabelings in 5 of 20. So the separation within a cluster may in part reflect which mouse a cell came from; this check does not decide the outcome.

The embeddings, and so the clusters and these counts, differ between runs although every seed is fixed: the kept cells are the same (18,742), but small numerical differences in the input change the UMAP layout. The run after the first verification round gave 17 of 20 clusters against 100 shuffles and 16 against 1,000, the copy the second verifier read gave 16 against 100, and this run gives 16 and 13, so both readings hold in each run seen. The numbers above are those of this run.

edf1-licking-before-reward¶

Well-trained mice ran steadily down the first half of the track and began licking as they approached the reward.

In [17]:
centers = np.arange(45) * 10 + 5
rbins = [(250, 300), (300, 350), (350, 400)]
for g in "ab":
    print(f"=== speed reading {g} ({'frames below 2 cm/s left out' if g == 'a' else 'all frames'})")
    per_mouse = {}
    first_half = {}
    for s in place:
        lk = s[f"licks_{g}"] * s["rate"]            # licks per frame to licks per second
        rp = s["trials"].reward_pos.to_numpy()
        for (lo, hi) in rbins:
            sel = (rp >= lo) & (rp < hi)
            if sel.any():
                per_mouse.setdefault((s["mouse"], lo), []).append(lk[sel])
        first_half.setdefault(s["mouse"], []).append(lk)
    rows = []
    for (lo, hi) in rbins:
        curves = np.array([np.nanmean(np.vstack(per_mouse[(m, lo)]), axis=0) for m in RARE + FREQ if (m, lo) in per_mouse])
        mean = np.nanmean(curves, axis=0)
        pre = (centers >= lo - 50) & (centers < lo)
        slope = np.polyfit(centers[pre], mean[pre], 1)[0]
        peak = centers[np.nanargmax(mean)]
        rows.append({"reward bin": f"{lo}-{hi}", "mice": len(curves), "rate 50 cm before (first, last bin)":
                     (round(mean[pre][0], 3), round(mean[pre][-1], 3)), "slope per cm": round(slope, 5),
                     "rises": bool(slope > 0 and mean[pre][-1] > mean[pre][0]), "peak at cm": int(peak),
                     "peak within 50 cm": bool(lo - 50 <= peak < hi + 50)})
    print(pd.DataFrame(rows).to_string(index=False))
    fh = {m: np.nanmean(np.vstack(v), axis=0) for m, v in first_half.items()}
    comp = pd.DataFrame({m: {"0-225 cm": np.nanmean(v[centers < 225]), "250-400 cm": np.nanmean(v[(centers >= 250) & (centers < 400)])}
                         for m, v in fh.items()}).T
    comp["lower before"] = comp["0-225 cm"] < comp["250-400 cm"]
    print(comp.round(3).to_string())
    print("mice with lower licking over 0-225 cm:", int(comp["lower before"].sum()), "of", len(comp))
spd = {m: np.nanmean(np.vstack([s["speed_b"] for s in place if s["mouse"] == m]), axis=0) for m in RARE + FREQ}
print("\nMean speed (cm/s) by 50 cm of track, all frames, across mice:",
      np.round([np.mean([spd[m][(centers >= lo) & (centers < lo + 50)].mean() for m in spd]) for lo in range(0, 450, 50)], 1).tolist())
lick_range = np.concatenate([s["licks_b"].ravel() for s in place]) * place[0]["rate"]
print(f"lick rate range over trials and bins: {np.nanmin(lick_range):.2f} to {np.nanmax(lick_range):.2f} licks/s")
=== speed reading a (frames below 2 cm/s left out)
reward bin  mice rate 50 cm before (first, last bin)  slope per cm  rises  peak at cm  peak within 50 cm
   250-300    12                      (1.196, 3.617)       0.05935   True         255               True
   300-350    12                      (2.608, 3.968)       0.03197   True         305               True
   350-400    12                      (3.616, 6.027)       0.06082   True         355               True
    0-225 cm  250-400 cm  lower before
F1     0.027       0.944          True
F2     0.129       1.725          True
F3     0.520       4.398          True
F4     0.012       1.006          True
F5     0.359       2.533          True
F6     0.842       3.347          True
R1     0.506       2.503          True
R2     1.171       4.824          True
R3     0.066       1.641          True
R4     0.101       1.905          True
R5     0.038       1.209          True
R6     0.015       0.471          True
mice with lower licking over 0-225 cm: 12 of 12
=== speed reading b (all frames)
reward bin  mice rate 50 cm before (first, last bin)  slope per cm  rises  peak at cm  peak within 50 cm
   250-300    12                      (1.211, 3.701)       0.06077   True         265               True
   300-350    12                      (2.605, 4.141)       0.03549   True         305               True
   350-400    12                      (3.616, 6.342)       0.06717   True         355               True
    0-225 cm  250-400 cm  lower before
F1     0.033       1.543          True
F2     0.135       2.017          True
F3     0.520       4.671          True
F4     0.013       1.038          True
F5     0.365       2.918          True
F6     0.847       3.527          True
R1     0.507       3.201          True
R2     1.171       5.274          True
R3     0.066       2.038          True
R4     0.103       1.913          True
R5     0.045       1.341          True
R6     0.014       0.391          True
mice with lower licking over 0-225 cm: 12 of 12

Mean speed (cm/s) by 50 cm of track, all frames, across mice: [47.0, 54.2, 52.9, 47.6, 36.1, 28.2, 31.4, 40.7, 40.6]
lick rate range over trials and bins: 0.00 to 68.03 licks/s

Result: reproduced. In the across-mouse mean for each 50 cm reward-location bin, lick rate rises over the 50 cm before the reward location and peaks within 50 cm of it, and every mouse licks less over 0 to 225 cm than over 250 to 400 cm, under both speed readings (tables above). The running part of the statement is not judged; mean speed by position is printed.

Blocked here¶

edf2-fh-best-predictor. It uses screenshots of the Unity scenes for the range of morph settings, which are not in the dandiset and not published elsewhere.

supp-earlier-morph-studies. A simulation with priors proposed for other laboratories' experiments; it uses no data of this paper.

The summary of all claims is at the end of part 2.

In [18]:
print(f"notebook run time {(time.time() - started) / 60:.1f} min")
notebook run time 39.2 min