Plitt & Giocomo (2021) on dandiset 000054, part 2: population codes and inference¶

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 its Methods, legends and supplementary information.

Dandiset. DANDI:000054, version 0.260415.1712, the most recent published version; the paper cites only the draft, and the 2021 versions hold 10 of the 16 mice (see part 1, 01_sessions_place_cells.ipynb, for the choice and the data check of every file).

This notebook tests the population similarity, SF, Q estimate and model claims. The priors (M7) need every trial a mouse ran before session 8; the dandiset holds only the imaged trials of the imaging sessions. Following the answer of 2026-10-22 (questions/plitt-2021.yaml), the priors are built from the authors' "Unprocessed VR data" on figshare (doi:10.6084/m9.figshare.31974756.v1), which holds every VR session, read by HTTP range requests into memory, file by file. Its mice are named by alias; the aliases of R1 to F6 are taken from the 2026 code (src/morph_analyses/mouse_metadata.py at commit 9230b0a of https://github.com/GiocomoLab/PlittGiocomo_2021). The link claim vr-deposit-link tests the match of its sessions to the dandiset's files, and training-intermediate-fraction uses the deposit alone (data: elsewhere). Claims whose posteriors or priors use it are data: with_inputs, and fig7-model-reproduces-remapping, which needs nothing else, is data: elsewhere. The earlier run's priors from the dandiset's imaged trials are shown as a variant, to show what the answer changed.

Claim Status
vr-deposit-link tested (link claim)
training-intermediate-fraction tested (deposit, data elsewhere)
fig3ab-block-versus-gradual-similarity tested
edf7-checkerboard-sessions tested
fig3f-zscored-difference-at-025 tested
fig4-sf-stable-along-track tested
fig6a-dkl-sign tested (priors from the deposit)
fig6bc-pooled-dkl tested (priors from the deposit)
fig6d-prior-reconstruction tested (priors from the deposit)
map-estimate-values tested (priors from the deposit)
edf9-early-sessions tested (priors from the deposit)
edf9k-null-models-rare tested (priors from the deposit)
edf9l-null-models-frequent tested (priors from the deposit)
edf10-decision-mice-like-frequent tested (priors from the deposit)
fig7-model-reproduces-remapping tested (priors from the deposit)
fig7g-model-prior-reconstruction tested (priors from the deposit)
edf3-simulated-posterior-population tested (priors from the deposit)

The claims of part 1 and the two blocked claims are listed in the summary at the end.

In [1]:
import time
import warnings
from concurrent.futures import ProcessPoolExecutor

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; paths the file-name pattern "
      f"does not read: {len(assets.attrs['unmatched'])}")
rf = assets.group != "decision"
pop = M.process_many([r for _, r in assets[rf & (assets.kind == "testing")].iterrows()], "population")
print(f"rare and frequent sessions 8 to N: {len(pop)} streamed in {time.time() - started:.0f} s")
sfs = M.process_many([r for _, r in assets[(~rf) | (rf & (assets.kind == "training") & (assets.day == 3))].iterrows()], "sf")
print(f"decision mice (all sessions) and session 3 of rare and frequent mice: {len(sfs)}; {time.time() - started:.0f} s")
meta = M.process_many([r for _, r in assets[rf & (assets.kind == "training") & (assets.day != 3)].iterrows()], "meta", workers=8)
print(f"other training files, trials only: {len(meta)}; total {time.time() - started:.0f} s")
vr_ses, vr_trials = M.vr_deposit()
print(f"VR deposit {M.VR_DEPOSIT['doi']}: {len(vr_ses)} sessions of the 12 mice on {M.VR_TRACK}; total {time.time() - started:.0f} s")
RARE = ["R1", "R2", "R3", "R4", "R5", "R6"]
FREQ = ["F1", "F2", "F3", "F4", "F5", "F6"]
GROUP = {**{m: "rare" for m in RARE}, **{m: "frequent" for m in FREQ}}
dandiset 000054 version 0.260415.1712: 126 NWB files; paths the file-name pattern does not read: 0
rare and frequent sessions 8 to N: 47 streamed in 273 s
decision mice (all sessions) and session 3 of rare and frequent mice: 48; 517 s
other training files, trials only: 31; total 532 s
VR deposit 10.6084/m9.figshare.31974756.v1: 352 sessions of the 12 mice on TwoTower_foraging; total 591 s

Data check¶

In [2]:
allsess = pop + sfs + meta
chk = pd.DataFrame([{"mouse": s["mouse"], "group": s["group"], "kind": s["kind"], "day": s["day"], "part": s["part"],
                     "cells": s["n_cells"], "trials": len(s["trials"]), "frames": s["n_frames"],
                     "S0 trials": int((s["trials"].morph == 0).sum()), "S1 trials": int((s["trials"].morph == 1).sum()),
                     "starts_match": s["starts_match"], "stops_match": s["stops_match"],
                     "norm_check": s.get("norm_check"), "speed_kept": s.get("speed_kept"),
                     "empty_bins": s.get("empty_bins_a")} for s in allsess])
print("Files read, by group and kind:")
print(pd.crosstab(chk.group, chk.kind).to_string())
print("Trial tables match the flag series in every file:", bool(chk.starts_match.all() and chk.stops_match.all()))
print("Largest difference between the file's normalised series and activity / 99th percentile:",
      float(chk.norm_check.max()))
print("Fraction of frames at 2 cm/s or more, per session: "
      f"{chk.speed_kept.min():.3f} to {chk.speed_kept.max():.3f}; empty trial x bin cells after the speed "
      f"exclusion: up to {chk.empty_bins.max():.4f}")
print("\nSessions with fewer than two S-tilde = 0 or = 1 trials (no SF possible):")
print(chk[(chk["S0 trials"] < 2) | (chk["S1 trials"] < 2)][["mouse", "kind", "day", "trials", "S0 trials", "S1 trials"]].to_string(index=False))
tr = pd.concat([s["trials"].assign(mouse=s["mouse"], group=s["group"], day=s["day"]) for s in allsess])
print(f"\nS from {tr.S.min():.3f} to {tr.S.max():.3f}; f_h from {tr.fh.min():.2f} to {tr.fh.max():.2f}; "
      f"grid {M.unit_to_fh(M.GRID[0]):.2f} to {M.unit_to_fh(M.GRID[-1]):.2f} f_h, 1 unit = {M.UNIT_FH:.2f} f_h")
print("S-tilde = 0 and 1 trials map to units", M.wallmorphx(0.0).round(3), "and", M.wallmorphx(1.0).round(3))
sf_all = np.concatenate([s["sf"] for s in pop])
print(f"Whole-trial SF, sessions 8 to N: {np.nanmin(sf_all):.3f} to {np.nanmax(sf_all):.3f}, NaN {np.isnan(sf_all).sum()}")
Files read, by group and kind:
kind      testing  training
group                      
decision       21        16
frequent       21        24
rare           26        18
Trial tables match the flag series in every file: True
Largest difference between the file's normalised series and activity / 99th percentile: 0.0
Fraction of frames at 2 cm/s or more, per session: 0.658 to 0.974; empty trial x bin cells after the speed exclusion: up to 0.2434

Sessions with fewer than two S-tilde = 0 or = 1 trials (no SF possible):
mouse     kind  day  trials  S0 trials  S1 trials
  FD1 training    1     100          0          0
  FD1 training    3     100          0          0

S from -0.100 to 1.100; f_h from 5.55 to 38.45; grid 0.06 to 43.94 f_h, 1 unit = 27.42 f_h
S-tilde = 0 and 1 trials map to units 0.09 and 1.094
Whole-trial SF, sessions 8 to N: 0.326 to 0.673, NaN 0

vr-deposit-link¶

The sessions of the authors' VR deposit on figshare can be matched to the dandiset's imaging sessions of the rare and frequent morph mice, by mouse alias and trial sequence.

A link claim added by this attempt (protocol, Author 1.4): the priors of this notebook and training-intermediate-fraction take the deposit's sessions of each mouse before its session 8, so the deposit's mice and dates have to be those of the dandiset's files.

In [3]:
nwb_rf = [s for s in allsess if s["group"] != "decision"]
named = [s for s in allsess for a in M.ALIAS.values()
         if a in " ".join([str(s["subject"]), s["session_id"], str(s["json_mouse"]), s["description"]])]
print("NWB files whose subject, session id, annotation or description name a deposit alias:", len(named))
link = M.link_sessions(nwb_rf, vr_ses, vr_trials)
print("Deposit, the 12 mice on the task track: files", len(vr_ses), "; listed twice in the session database:",
      int((vr_ses.db_rows > 1).sum()), "; listed but missing from the zip:", int((~vr_ses.in_zip).sum()),
      "; trials without a morph value:", int(vr_ses.trials_no_morph.sum()))
print(vr_ses.groupby("mouse").agg(files=("member", "size"), trials=("trials", "sum"), first=("date", "min"),
                                  last=("date", "max"), imaging_flag=("Imaging", lambda x: int((x == 1).sum()))).to_string())
print("\nEach NWB file against every deposit file (S-tilde and the three jitters within 1e-4, as one contiguous run):")
print(link[["mouse", "kind", "day", "part", "nwb_trials", "matches", "other_mouse_matches", "member", "offset",
            "vr_trials", "max_diff"]].to_string(index=False))
one = (link.matches == 1) & (link.other_mouse_matches == 0)
print(f"\nNWB files of the 12 mice: {len(link)}; matching exactly one file of their own mouse and none of another: "
      f"{int(one.sum())} ({one.mean():.0%})")
print("Matched file holds exactly the NWB trials (offset 0, same count):",
      int(((link.offset == 0) & (link.vr_trials == link.nwb_trials)).sum()), "of", len(link),
      "; largest difference of S-tilde or jitter:", float(link.max_diff.max()))
print("Matched files carry the database's imaging flag:", int((link.imaging == 1).sum()), "of", len(link))
print("Matched files are distinct:", link.member.nunique() == len(link))
d8 = link[link.day == 8].set_index("mouse")[["date", "session_number", "member"]]
print("\nSession 8 of each mouse in the deposit (the NWB file of day 8):")
print(d8.to_string())
img = vr_ses[(vr_ses.Imaging == 1) & ~vr_ses.member.isin(link.member)]
print("\nDeposit files with the imaging flag that match no NWB file:", len(img))
print(img.groupby("mouse").agg(files=("member", "size"), trials=("trials", "sum"),
                               dates=("DateFolder", lambda d: " ".join(sorted(set(d))))).to_string())
NWB files whose subject, session id, annotation or description name a deposit alias: 0
Deposit, the 12 mice on the task track: files 352 ; listed twice in the session database: 1 ; listed but missing from the zip: 0 ; trials without a morph value: 0
       files  trials      first       last  imaging_flag
mouse                                                   
F1        25    2297 2019-04-08 2019-04-18             7
F2        30    2546 2019-04-08 2019-04-19             9
F3        19    1791 2019-04-08 2019-04-15             6
F4        29    2436 2019-06-04 2019-06-18             9
F5        29    2523 2019-04-08 2019-04-19             9
F6        27    2069 2020-03-13 2020-03-22             9
R1        33    2504 2019-02-10 2019-02-24            10
R2        37    2839 2019-02-07 2019-02-22            11
R3        31    2596 2019-02-10 2019-02-24            10
R4        35    2320 2019-08-22 2019-09-06            13
R5        20    1830 2020-03-14 2020-03-22             7
R6        37    2626 2020-01-28 2020-02-11            15

Each NWB file against every deposit file (S-tilde and the three jitters within 1e-4, as one contiguous run):
mouse     kind  day  part  nwb_trials  matches  other_mouse_matches                                                        member  offset  vr_trials  max_diff
   F1  testing    8     1          95        1                    0 morph_vr_data/4222153.1/15_04_2019/TwoTower_foraging_2.sqlite       0         95       0.0
   F1  testing    9     1         100        1                    0 morph_vr_data/4222153.1/16_04_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   F1  testing   10     1          86        1                    0 morph_vr_data/4222153.1/17_04_2019/TwoTower_foraging_2.sqlite       0         86       0.0
   F2  testing    8     1         120        1                    0 morph_vr_data/4222153.2/15_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F2  testing    9     1         120        1                    0 morph_vr_data/4222153.2/16_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F2  testing   10     1         100        1                    0 morph_vr_data/4222153.2/17_04_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   F2  testing   11     1          85        1                    0 morph_vr_data/4222153.2/18_04_2019/TwoTower_foraging_3.sqlite       0         85       0.0
   F3  testing    8     1          90        1                    0 morph_vr_data/4222153.3/15_04_2019/TwoTower_foraging_2.sqlite       0         90       0.0
   F4  testing    8     1          75        1                    0 morph_vr_data/4222174.1/13_06_2019/TwoTower_foraging_2.sqlite       0         75       0.0
   F4  testing    9     1          85        1                    0 morph_vr_data/4222174.1/14_06_2019/TwoTower_foraging_2.sqlite       0         85       0.0
   F4  testing   10     1          90        1                    0 morph_vr_data/4222174.1/15_06_2019/TwoTower_foraging_3.sqlite       0         90       0.0
   F4  testing   11     1          70        1                    0 morph_vr_data/4222174.1/17_06_2019/TwoTower_foraging_2.sqlite       0         70       0.0
   F4  testing   12     1          80        1                    0 morph_vr_data/4222174.1/18_06_2019/TwoTower_foraging_2.sqlite       0         80       0.0
   F5  testing    8     1         120        1                    0 morph_vr_data/4222154.1/15_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F5  testing    9     1         100        1                    0 morph_vr_data/4222154.1/16_04_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   F5  testing   10     1         100        1                    0 morph_vr_data/4222154.1/17_04_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   F5  testing   11     1          90        1                    0 morph_vr_data/4222154.1/18_04_2019/TwoTower_foraging_2.sqlite       0         90       0.0
   F5  testing   12     1         100        1                    0 morph_vr_data/4222154.1/19_04_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   F6  testing    8     1         100        1                    0 morph_vr_data/4343702.1/20_03_2020/TwoTower_foraging_3.sqlite       0        100       0.0
   F6  testing    9     1          80        1                    0 morph_vr_data/4343702.1/21_03_2020/TwoTower_foraging_2.sqlite       0         80       0.0
   F6  testing   10     1         100        1                    0 morph_vr_data/4343702.1/22_03_2020/TwoTower_foraging_3.sqlite       0        100       0.0
   R1  testing    8     1         120        1                    0 morph_vr_data/4139265.3/19_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R1  testing    9     1         120        1                    0 morph_vr_data/4139265.3/21_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R1  testing   10     1         120        1                    0 morph_vr_data/4139265.3/22_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R1  testing   11     1         120        1                    0 morph_vr_data/4139265.3/23_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R1  testing   12     1         120        1                    0 morph_vr_data/4139265.3/24_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R2  testing    8     1         120        1                    0 morph_vr_data/4139265.4/17_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R2  testing    9     1         120        1                    0 morph_vr_data/4139265.4/18_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R2  testing   10     1         120        1                    0 morph_vr_data/4139265.4/19_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R2  testing   11     1         120        1                    0 morph_vr_data/4139265.4/20_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R2  testing   12     1         120        1                    0 morph_vr_data/4139265.4/21_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R2  testing   13     1         120        1                    0 morph_vr_data/4139265.4/22_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R3  testing    8     1         120        1                    0 morph_vr_data/4139265.5/19_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R3  testing    9     1         120        1                    0 morph_vr_data/4139265.5/21_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R3  testing   10     1         120        1                    0 morph_vr_data/4139265.5/22_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R3  testing   11     1         120        1                    0 morph_vr_data/4139265.5/23_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R3  testing   12     1         120        1                    0 morph_vr_data/4139265.5/24_02_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   R4  testing    8     1          90        1                    0 morph_vr_data/4222168.1/02_09_2019/TwoTower_foraging_3.sqlite       0         90       0.0
   R4  testing    9     1         100        1                    0 morph_vr_data/4222168.1/03_09_2019/TwoTower_foraging_4.sqlite       0        100       0.0
   R4  testing   10     1         100        1                    0 morph_vr_data/4222168.1/04_09_2019/TwoTower_foraging_3.sqlite       0        100       0.0
   R4  testing   11     1         100        1                    0 morph_vr_data/4222168.1/05_09_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   R4  testing   12     1         100        1                    0 morph_vr_data/4222168.1/06_09_2019/TwoTower_foraging_3.sqlite       0        100       0.0
   R5  testing    8     1         100        1                    0 morph_vr_data/4343703.1/21_03_2020/TwoTower_foraging_2.sqlite       0        100       0.0
   R5  testing    9     1         100        1                    0 morph_vr_data/4343703.1/22_03_2020/TwoTower_foraging_2.sqlite       0        100       0.0
   R6  testing    8     1          70        1                    0   morph_vr_data/4343706/09_02_2020/TwoTower_foraging_2.sqlite       0         70       0.0
   R6  testing    9     1          60        1                    0   morph_vr_data/4343706/10_02_2020/TwoTower_foraging_3.sqlite       0         60       0.0
   R6  testing   10     1          60        1                    0   morph_vr_data/4343706/11_02_2020/TwoTower_foraging_3.sqlite       0         60       0.0
   F1 training    3     1          92        1                    0 morph_vr_data/4222153.1/10_04_2019/TwoTower_foraging_2.sqlite       0         92       0.0
   F2 training    3     1          80        1                    0 morph_vr_data/4222153.2/10_04_2019/TwoTower_foraging_3.sqlite       0         80       0.0
   F3 training    3     1         120        1                    0 morph_vr_data/4222153.3/10_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F4 training    3     1          90        1                    0 morph_vr_data/4222174.1/06_06_2019/TwoTower_foraging_2.sqlite       0         90       0.0
   F5 training    3     1         120        1                    0 morph_vr_data/4222154.1/10_04_2019/TwoTower_foraging_4.sqlite       0        120       0.0
   F6 training    3     1         100        1                    0 morph_vr_data/4343702.1/15_03_2020/TwoTower_foraging_4.sqlite       0        100       0.0
   R1 training    3     1          90        1                    0 morph_vr_data/4139265.3/12_02_2019/TwoTower_foraging_2.sqlite       0         90       0.0
   R2 training    3     1          60        1                    0 morph_vr_data/4139265.4/10_02_2019/TwoTower_foraging_2.sqlite       0         60       0.0
   R3 training    3     1          90        1                    0 morph_vr_data/4139265.5/12_02_2019/TwoTower_foraging_2.sqlite       0         90       0.0
   R4 training    3     1          60        1                    0 morph_vr_data/4222168.1/25_08_2019/TwoTower_foraging_3.sqlite       0         60       0.0
   R5 training    3     1         100        1                    0 morph_vr_data/4343703.1/16_03_2020/TwoTower_foraging_2.sqlite       0        100       0.0
   F1 training    1     1         120        1                    0 morph_vr_data/4222153.1/08_04_2019/TwoTower_foraging_1.sqlite       0        120       0.0
   F1 training    5     1         100        1                    0 morph_vr_data/4222153.1/12_04_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   F1 training    7     1         100        1                    0 morph_vr_data/4222153.1/14_04_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   F2 training    1     1          85        1                    0 morph_vr_data/4222153.2/08_04_2019/TwoTower_foraging_1.sqlite       0         85       0.0
   F2 training    5     1         100        1                    0 morph_vr_data/4222153.2/12_04_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   F2 training    7     1         120        1                    0 morph_vr_data/4222153.2/14_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F3 training    1     1         120        1                    0 morph_vr_data/4222153.3/08_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F3 training    5     1         125        1                    0 morph_vr_data/4222153.3/12_04_2019/TwoTower_foraging_2.sqlite       0        125       0.0
   F3 training    7     1         120        1                    0 morph_vr_data/4222153.3/14_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F4 training    1     1          80        1                    0 morph_vr_data/4222174.1/04_06_2019/TwoTower_foraging_1.sqlite       0         80       0.0
   F4 training    5     1          85        1                    0 morph_vr_data/4222174.1/08_06_2019/TwoTower_foraging_2.sqlite       0         85       0.0
   F4 training    7     1          80        1                    0 morph_vr_data/4222174.1/11_06_2019/TwoTower_foraging_2.sqlite       0         80       0.0
   F5 training    1     1         120        1                    0 morph_vr_data/4222154.1/08_04_2019/TwoTower_foraging_1.sqlite       0        120       0.0
   F5 training    5     1         120        1                    0 morph_vr_data/4222154.1/12_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F5 training    7     1         120        1                    0 morph_vr_data/4222154.1/14_04_2019/TwoTower_foraging_2.sqlite       0        120       0.0
   F6 training    1     1          80        1                    0 morph_vr_data/4343702.1/13_03_2020/TwoTower_foraging_1.sqlite       0         80       0.0
   F6 training    5     1         100        1                    0 morph_vr_data/4343702.1/17_03_2020/TwoTower_foraging_2.sqlite       0        100       0.0
   F6 training    7     1          75        1                    0 morph_vr_data/4343702.1/19_03_2020/TwoTower_foraging_2.sqlite       0         75       0.0
   R1 training    1     1          60        1                    0 morph_vr_data/4139265.3/10_02_2019/TwoTower_foraging_1.sqlite       0         60       0.0
   R1 training    1     2          60        1                    0 morph_vr_data/4139265.3/10_02_2019/TwoTower_foraging_3.sqlite       0         60       0.0
   R1 training    5     1          90        1                    0 morph_vr_data/4139265.3/15_02_2019/TwoTower_foraging_4.sqlite       0         90       0.0
   R1 training    7     1         100        1                    0 morph_vr_data/4139265.3/17_02_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   R2 training    1     1          60        1                    0 morph_vr_data/4139265.4/07_02_2019/TwoTower_foraging_2.sqlite       0         60       0.0
   R2 training    1     2          60        1                    0 morph_vr_data/4139265.4/07_02_2019/TwoTower_foraging_4.sqlite       0         60       0.0
   R2 training    5     1         100        1                    0 morph_vr_data/4139265.4/12_02_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   R2 training    7     1         100        1                    0 morph_vr_data/4139265.4/15_02_2019/TwoTower_foraging_3.sqlite       0        100       0.0
   R3 training    1     1          60        1                    0 morph_vr_data/4139265.5/10_02_2019/TwoTower_foraging_1.sqlite       0         60       0.0
   R3 training    1     2          60        1                    0 morph_vr_data/4139265.5/10_02_2019/TwoTower_foraging_3.sqlite       0         60       0.0
   R3 training    5     1         100        1                    0 morph_vr_data/4139265.5/15_02_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   R3 training    7     1         100        1                    0 morph_vr_data/4139265.5/17_02_2019/TwoTower_foraging_2.sqlite       0        100       0.0
   R4 training    6     1          80        1                    0 morph_vr_data/4222168.1/28_08_2019/TwoTower_foraging_2.sqlite       0         80       0.0

NWB files of the 12 mice: 89; matching exactly one file of their own mouse and none of another: 89 (100%)
Matched file holds exactly the NWB trials (offset 0, same count): 89 of 89 ; largest difference of S-tilde or jitter: 0.0
Matched files carry the database's imaging flag: 89 of 89
Matched files are distinct: True

Session 8 of each mouse in the deposit (the NWB file of day 8):
            date  session_number                                                         member
mouse                                                                                          
F1    2019-04-15               2  morph_vr_data/4222153.1/15_04_2019/TwoTower_foraging_2.sqlite
F2    2019-04-15               2  morph_vr_data/4222153.2/15_04_2019/TwoTower_foraging_2.sqlite
F3    2019-04-15               2  morph_vr_data/4222153.3/15_04_2019/TwoTower_foraging_2.sqlite
F4    2019-06-13               2  morph_vr_data/4222174.1/13_06_2019/TwoTower_foraging_2.sqlite
F5    2019-04-15               2  morph_vr_data/4222154.1/15_04_2019/TwoTower_foraging_2.sqlite
F6    2020-03-20               3  morph_vr_data/4343702.1/20_03_2020/TwoTower_foraging_3.sqlite
R1    2019-02-19               2  morph_vr_data/4139265.3/19_02_2019/TwoTower_foraging_2.sqlite
R2    2019-02-17               2  morph_vr_data/4139265.4/17_02_2019/TwoTower_foraging_2.sqlite
R3    2019-02-19               2  morph_vr_data/4139265.5/19_02_2019/TwoTower_foraging_2.sqlite
R4    2019-09-02               3  morph_vr_data/4222168.1/02_09_2019/TwoTower_foraging_3.sqlite
R5    2020-03-21               2  morph_vr_data/4343703.1/21_03_2020/TwoTower_foraging_2.sqlite
R6    2020-02-09               2    morph_vr_data/4343706/09_02_2020/TwoTower_foraging_2.sqlite

Deposit files with the imaging flag that match no NWB file: 26
       files  trials                                                                         dates
mouse                                                                                             
F2         1       0                                                                    10_04_2019
F3         1      50                                                                    15_04_2019
F6         2      44                                                         15_03_2020 20_03_2020
R4         6      65                        02_09_2019 03_09_2019 06_09_2019 25_08_2019 30_08_2019
R5         4     290                                              14_03_2020 18_03_2020 20_03_2020
R6        12     597  04_02_2020 06_02_2020 07_02_2020 08_02_2020 10_02_2020 11_02_2020 29_01_2020
In [4]:
# Session numbers (verifier's request for edf7): the file name's day against the ordinal of the matched
# deposit file's date among the mouse's dates on the task track in the deposit (one session a day).
dates = {m: sorted(vr_ses[vr_ses.mouse == m].date.unique()) for m in RARE + FREQ}
link["date_ordinal"] = [dates[r.mouse].index(r.date) + 1 for r in link.itertuples()]
link["sessions_that_date"] = [int(((vr_ses.mouse == r.mouse) & (vr_ses.date == r.date)).sum()) for r in link.itertuples()]
print("File day against the ordinal of its deposit date, per mouse (day:ordinal; * where they differ):")
for m, d in link.sort_values(["mouse", "day", "part"]).groupby("mouse"):
    print(f"  {m}:", " ".join(f"{dd}:{o}" + ("*" if dd != o else "") for dd, o in zip(d.day, d.date_ordinal)))
print("files whose day equals the date ordinal:", int((link.day == link.date_ordinal).sum()), "of", len(link),
      "; matched files on a date with more than one task-track file in the deposit:", int((link.sessions_that_date > 1).sum()))
print("task-track dates in the deposit before each mouse's first NWB file of day 8 that have no NWB file:",
      {m: int(sum(1 for dt in dates[m] if dt < link[(link.mouse == m) & (link.day == 8)].date.iloc[0]
                  and dt not in set(link[link.mouse == m].date))) for m in RARE + FREQ})
# The 2020 code's sessions 8 to N (SFReg: imaging sessions of the mouse, region CA1 or empty, from index first_sessions on,
# 5 5 5 3 5 2 for R1 to R6 and 4 for the frequent mice), found in the deposit's database and matched to the NWB files.
first_ind = dict(zip(RARE + FREQ, [5, 5, 5, 3, 5, 2] + [4] * 6))
code_rows = []
for m in RARE + FREQ:
    im = vr_ses[(vr_ses.mouse == m) & (vr_ses.Imaging == 1)]
    if "ImagingRegion" in im:
        im = im[im.ImagingRegion.fillna("").isin(["CA1", ""])]
    im = im.sort_values(["date", "SessionNumber"]).iloc[first_ind[m]:]
    for r in im.itertuples():
        hit = link[link.member == r.member]
        code_rows.append({"mouse": m, "member": r.member, "nwb_day": int(hit.day.iloc[0]) if len(hit) else None,
                          "nwb_trials": int(hit.nwb_trials.iloc[0]) if len(hit) else None})
code_s = pd.DataFrame(code_rows)
ours = link[link.kind == "testing"]
for g, mice in (("rare", RARE), ("frequent", FREQ)):
    cs = code_s[code_s.mouse.isin(mice)]
    print(f"{g}: the 2020 code's selection holds {len(cs)} sessions, {cs.nwb_day.notna().sum()} with an NWB file "
          f"({int(cs.nwb_trials.sum())} trials; the code printed 2540 rare and 1986 frequent); days of those with a file:",
          cs.dropna().groupby("mouse").nwb_day.apply(lambda d: [int(x) for x in d]).to_dict())
    o = ours[ours.mouse.isin(mice)]
    extra = o[~o.member.isin(cs.member)]
    print(f"   NWB sessions 8 to N not in the code's selection: {[(r.mouse, r.day) for r in extra.itertuples()]}")
File day against the ordinal of its deposit date, per mouse (day:ordinal; * where they differ):
  F1: 1:1 3:3 5:5 7:7 8:8 9:9 10:10
  F2: 1:1 3:3 5:5 7:7 8:8 9:9 10:10 11:11
  F3: 1:1 3:3 5:5 7:7 8:8
  F4: 1:1 3:3 5:5 7:7 8:9* 9:10* 10:11* 11:12* 12:13*
  F5: 1:1 3:3 5:5 7:7 8:8 9:9 10:10 11:11 12:12
  F6: 1:1 3:3 5:5 7:7 8:8 9:9 10:10
  R1: 1:1 1:1 3:3 5:5 7:7 8:9* 9:10* 10:11* 11:12* 12:13*
  R2: 1:1 1:1 3:3 5:5 7:7 8:9* 9:10* 10:11* 11:12* 12:13* 13:14*
  R3: 1:1 1:1 3:3 5:5 7:7 8:9* 9:10* 10:11* 11:12* 12:13*
  R4: 3:3 6:6 8:9* 9:10* 10:11* 11:12* 12:13*
  R5: 3:3 8:8 9:9
  R6: 8:10* 9:11* 10:12*
files whose day equals the date ordinal: 60 of 89 ; matched files on a date with more than one task-track file in the deposit: 89
task-track dates in the deposit before each mouse's first NWB file of day 8 that have no NWB file: {'R1': 4, 'R2': 4, 'R3': 4, 'R4': 6, 'R5': 6, 'R6': 9, 'F1': 3, 'F2': 3, 'F3': 3, 'F4': 4, 'F5': 3, 'F6': 3}
rare: the 2020 code's selection holds 33 sessions, 27 with an NWB file (2880 trials; the code printed 2540 rare and 1986 frequent); days of those with a file: {'R1': [8, 9, 10, 11, 12], 'R2': [8, 9, 10, 11, 12, 13], 'R3': [8, 9, 10, 11, 12], 'R4': [6, 8, 9, 10, 11, 12], 'R5': [8, 9], 'R6': [8, 9, 10]}
   NWB sessions 8 to N not in the code's selection: []
frequent: the 2020 code's selection holds 24 sessions, 23 with an NWB file (2181 trials; the code printed 2540 rare and 1986 frequent); days of those with a file: {'F1': [8, 9, 10], 'F2': [7, 8, 9, 10, 11], 'F3': [8], 'F4': [8, 9, 10, 11, 12], 'F5': [8, 9, 10, 11, 12], 'F6': [7, 8, 9, 10]}
   NWB sessions 8 to N not in the code's selection: []

Result: reproduced. All 89 NWB files of the 12 rare and frequent morph mice match exactly one deposit file of their own mouse, under the 2026 code's alias, and no file of another mouse; in every one the deposit file holds exactly the NWB trials (offset 0, same count), with S-tilde and the three jitters identical, and every matched file carries the database's imaging flag. So the deposit's aliases and dates are those of the dandiset's mice and sessions, and session 8 of each mouse has a date in the deposit. The deposit holds more than the dandiset: every session without imaging, R6's sessions before session 8, and further files with the imaging flag that match no NWB file (table above). No NWB file names a deposit alias, so the mapping of the aliases to the mice comes from the 2026 code alone; the trial sequences confirm it.

Session numbers (the cell after the result). The file name's day equals the ordinal of the matched file's date among the mouse's task-track dates in the deposit for 60 of the 89 files. For R1 to R4, R6 and F4 the imaging sessions 8 to N fall one date later (two for R6): the deposit holds eight task-track dates before session 8 for these mice (nine for R6), one more than sessions 1 to 7 (two more for R6). The paper's session numbers are read as the file days, which equal the annotation's day; the date ordinal is a second numbering, and the deposit does not say which the paper used. The 2020 code's selection of sessions 8 to N, rebuilt from the deposit's imaging flags, holds every NWB session 8 to N and more sessions with the flag (33 rare, 24 frequent), and its NWB trials (2,880 and 2,181) do not match the code's printed 2,540 and 1,986, so it does not identify the two extra rare sessions the dandiset holds against the paper's 24.

training-intermediate-fraction¶

Before session 8, rare morph mice had fewer than 4% of trials with intermediate morph values, while frequent morph mice had 60%.

Answer of 2026-10-22: the trials come from the figshare deposit (data: elsewhere), which holds every session. Trials before session 8 are those of every session on the task track on a date before the date of session 8 (vr-deposit-link), and of the earlier session numbers of that date. The variants do not decide: the 2026 code's two choices (sessions with more than 40 rewards; the sessions within 8 calendar days of the mouse's first), and the imaged trials the dandiset holds, which decided nothing in the earlier run either.

In [5]:
def before8(m):
    return M.sessions_before(vr_ses, m, d8.loc[m, "date"], d8.loc[m, "session_number"])


def first8(m):
    s = vr_ses[vr_ses.mouse == m]
    return s[(s.date - s.date.min()).dt.days < 8]


variants = {"every trial before session 8": before8,
            "code: more than 40 rewards": lambda m: before8(m)[before8(m).RewardCount > 40],
            "code 2026: within 8 days of the first": first8}
rows = []
for vname, f in variants.items():
    for m in RARE + FREQ:
        b = f(m)
        t = pd.concat([vr_trials[x] for x in b.member]).dropna(subset=["morph"])
        rows.append({"variant": vname, "group": "rare" if m in RARE else "frequent", "mouse": m, "sessions": len(b),
                     "days": b.date.nunique(), "trials": len(t), "intermediate": int(t.morph.isin([0.25, 0.5, 0.75]).sum())})
tf = pd.DataFrame(rows)
tf["fraction"] = (tf.intermediate / tf.trials).round(4)
early = tr[(tr.day < 8) & (tr.group != "decision")]
for m in RARE + FREQ:
    t = early[early.mouse == m]
    rows.append({"variant": "dandiset imaged trials", "group": "rare" if m in RARE else "frequent", "mouse": m,
                 "sessions": t.day.nunique(), "days": t.day.nunique(), "trials": len(t),
                 "intermediate": int(((t.morph > 0.01) & (t.morph < 0.99)).sum())})
tf = pd.DataFrame(rows)
tf["fraction"] = np.where(tf.trials > 0, tf.intermediate / tf.trials.clip(lower=1), np.nan).round(4)
print("Per mouse, sessions, days, trials and fraction with S-tilde 0.25, 0.5 or 0.75 before session 8:")
print(tf.pivot(index="mouse", columns="variant", values="fraction").loc[RARE + FREQ].to_string())
print(tf[tf.variant == "every trial before session 8"][["mouse", "sessions", "days", "trials", "intermediate"]].to_string(index=False))
print("\nS-tilde values in the deposit trials before session 8:",
      sorted(set(pd.concat([vr_trials[x] for m in RARE + FREQ for x in before8(m).member]).morph.dropna())))
res = []
for vname in tf.variant.unique():
    x = tf[tf.variant == vname]
    for g in ("rare", "frequent"):
        y = x[(x.group == g) & (x.trials > 0)]
        res.append({"variant": vname, "group": g, "a: pooled": round(y.intermediate.sum() / y.trials.sum(), 4),
                    "b: lowest mouse": y.fraction.min(), "b: highest mouse": y.fraction.max()})
res = pd.DataFrame(res)
print("\n" + res.to_string(index=False))
for vname in tf.variant.unique():
    r = res[res.variant == vname].set_index("group")
    ok_a = r.loc["rare", "a: pooled"] < 0.04 and abs(r.loc["frequent", "a: pooled"] - 0.6) <= 0.06
    ok_b = r.loc["rare", "b: highest mouse"] < 0.04 and abs(r.loc["frequent", "b: lowest mouse"] - 0.6) <= 0.06 \
        and abs(r.loc["frequent", "b: highest mouse"] - 0.6) <= 0.06
    print(f"{vname}: reading (a) holds {ok_a}; reading (b) holds {ok_b}")
Per mouse, sessions, days, trials and fraction with S-tilde 0.25, 0.5 or 0.75 before session 8:
variant  code 2026: within 8 days of the first  code: more than 40 rewards  dandiset imaged trials  every trial before session 8
mouse                                                                                                                           
R1                                      0.0352                      0.0340                  0.1125                        0.0295
R2                                      0.0270                      0.0205                  0.0789                        0.0185
R3                                      0.0328                      0.0308                  0.1098                        0.0276
R4                                      0.0228                      0.0219                  0.2143                        0.0412
R5                                      0.0571                      0.0326                  0.4800                        0.0315
R6                                      0.0000                      0.0566                     NaN                        0.0566
F1                                      0.5978                      0.5990                  0.5947                        0.5977
F2                                      0.5935                      0.5897                  0.5974                        0.5920
F3                                      0.5952                      0.5941                  0.6000                        0.5925
F4                                      0.5983                      0.6005                  0.6000                        0.6005
F5                                      0.6010                      0.5996                  0.6000                        0.6010
F6                                      0.6054                      0.6073                  0.6028                        0.6059
mouse  sessions  days  trials  intermediate
   R1        20     9    1524            45
   R2        20     9    1625            30
   R3        17     9    1631            45
   R4        18     9    1506            62
   R5        16     8    1522            48
   R6        22    10    1945           110
   F1        15     8    1581           945
   F2        16     8    1549           917
   F3        16     8    1578           935
   F4        16     9    1692          1016
   F5        17     8    1564           940
   F6        18     8    1563           947

S-tilde values in the deposit trials before session 8: [0.0, 0.25, 0.5, 0.75, 1.0]

                              variant    group  a: pooled  b: lowest mouse  b: highest mouse
         every trial before session 8     rare     0.0349           0.0185            0.0566
         every trial before session 8 frequent     0.5983           0.5920            0.6059
           code: more than 40 rewards     rare     0.0341           0.0205            0.0566
           code: more than 40 rewards frequent     0.5984           0.5897            0.6073
code 2026: within 8 days of the first     rare     0.0319           0.0000            0.0571
code 2026: within 8 days of the first frequent     0.5985           0.5935            0.6054
               dandiset imaged trials     rare     0.1385           0.0789            0.4800
               dandiset imaged trials frequent     0.5991           0.5947            0.6028
every trial before session 8: reading (a) holds True; reading (b) holds False
code: more than 40 rewards: reading (a) holds True; reading (b) holds False
code 2026: within 8 days of the first: reading (a) holds True; reading (b) holds False
dandiset imaged trials: reading (a) holds False; reading (b) holds False

Result: reproduced. From every trial the deposit holds before session 8, 3.49% of the rare morph mice's trials pooled (340 of 9,753) and 59.8% of the frequent morph mice's (5,700 of 9,527) are intermediate, so reading (a) holds: below 4%, and within 0.06 of 60%. Reading (b) does not, as R4 (4.1%) and R6 (5.7%) are above 4%; the frequent morph mice range from 59.2% to 60.6%. The 2026 code's variants give the same under reading (a) (3.41% and 3.19% rare, 59.8% and 59.8% frequent). The imaged trials the dandiset holds give 13.8% for the rare morph mice, as the earlier run found; the answer replaced them with the deposit.

Priors and posteriors (M7, M8)¶

Priors (M7): every trial each mouse ran before session 8, from the authors' VR deposit on figshare (answer of 2026-10-22). The deposit's sessions are matched to the dandiset's files as in vr-deposit-link above; session 8's date and session number in the deposit mark the end of the trials that enter the prior.

In [6]:
vr_before8 = {m: pd.concat([vr_trials[x] for x in M.sessions_before(vr_ses, m, d8.loc[m, "date"], d8.loc[m, "session_number"]).member])
              .dropna(subset=["morph"]) for m in RARE + FREQ}
print("Deposit trials before session 8, per mouse (S-tilde counts):")
print(pd.DataFrame({m: t.morph.value_counts() for m, t in vr_before8.items()}).T.fillna(0).astype(int).to_string())
mouse_prior = {m: M.prior_from_units(t.unit.to_numpy()) for m, t in vr_before8.items()}
prior = {"rare": M.group_prior([mouse_prior[m] for m in RARE]),
         "frequent": M.group_prior([mouse_prior[m] for m in FREQ])}
# 2020 code variant: the group prior is the last mouse's prior
prior_last = {"rare": mouse_prior["R6"], "frequent": mouse_prior["F6"]}
# the earlier run's priors, from the imaged trials before session 8 that the dandiset holds (R6 has none)
before8 = tr[(tr.day < 8) & tr.group.isin(["rare", "frequent"])]
mouse_prior_img = {m: M.prior_from_units(before8[before8.mouse == m].unit.to_numpy()) for m in before8.mouse.unique()}
prior_img = {"rare": M.group_prior([mouse_prior_img[m] for m in RARE if m in mouse_prior_img]),
             "frequent": M.group_prior([mouse_prior_img[m] for m in FREQ if m in mouse_prior_img])}
POST = {(lik, g): M.posterior(prior[g], lik) for lik in M.LIKELIHOODS for g in ("rare", "frequent")}
POST_LAST = {g: M.posterior(prior_last[g]) for g in ("rare", "frequent")}
POST_IMG = {g: M.posterior(prior_img[g]) for g in ("rare", "frequent")}
mass = lambda p: {f"{lo}-{hi}": round(float(p[(M.GRID >= lo) & (M.GRID < hi)].sum()), 3) for lo, hi in ((-0.3, 0.15), (0.15, 0.85), (0.85, 1.3))}
print("Prior mass by unit range (low extreme, intermediate, high extreme):")
print("deposit (main):", {g: mass(p) for g, p in prior.items()})
print("dandiset imaged trials (earlier run):", {g: mass(p) for g, p in prior_img.items()})
fig, ax = plt.subplots(1, 2, figsize=(10, 3))
ax[0].plot(M.unit_to_fh(M.GRID), prior["rare"], label="rare"); ax[0].plot(M.unit_to_fh(M.GRID), prior["frequent"], label="frequent")
ax[0].plot(M.unit_to_fh(M.GRID), prior_img["rare"], "--", label="rare, dandiset trials")
ax[0].set_xlabel("f_h"); ax[0].legend(); ax[0].set_title("group priors")
ax[1].imshow(POST[("methods var 8.23", "rare")], origin="lower", aspect="auto", extent=[M.GRID[0], M.GRID[-1]] * 2)
ax[1].set_title("rare posterior (rows fhat)")
plt.show()
print("prior ranges:", {g: (float(p.min()), float(p.max())) for g, p in prior.items()},
      "; dandiset-trial rare prior up to", float(prior_img["rare"].max()))
Deposit trials before session 8, per mouse (S-tilde counts):
morph  0.0  0.25  0.5  0.75  1.0
R1     742    15   15    15  737
R2     805    10   10    10  790
R3     801    15   15    15  785
R4     727    17   23    22  717
R5     733    16   16    16  741
R6     901    36   39    35  934
F1     313   321  317   307  323
F2     318   292  323   302  314
F3     318   300  317   318  325
F4     327   338  336   342  349
F5     299   312  318   310  325
F6     302   332  307   308  314
Prior mass by unit range (low extreme, intermediate, high extreme):
deposit (main): {'rare': {'-0.3-0.15': 0.321, '0.15-0.85': 0.183, '0.85-1.3': 0.496}, 'frequent': {'-0.3-0.15': 0.129, '0.15-0.85': 0.411, '0.85-1.3': 0.459}}
dandiset imaged trials (earlier run): {'rare': {'-0.3-0.15': 0.263, '0.15-0.85': 0.256, '0.85-1.3': 0.481}, 'frequent': {'-0.3-0.15': 0.129, '0.15-0.85': 0.419, '0.85-1.3': 0.451}}
No description has been provided for this image
prior ranges: {'rare': (4.659412802359882e-06, 0.004382102304823482), 'frequent': (1.90002840214078e-06, 0.0029282060686000293)} ; dandiset-trial rare prior up to 0.003922307940125002

Every NWB file of the 12 mice matches one deposit file of its mouse, so session 8 has a date in the deposit for every mouse, R6 included (its training sessions are in the deposit, not the dandiset). Over all trials before session 8, 3.5% of the rare morph mice's trials are intermediate (training-intermediate-fraction above), and the rare prior holds 0.183 of its mass between 0.15 and 0.85 units, against 0.256 for the prior from the dandiset's imaged trials that the earlier run used. The frequent prior hardly changes (0.411 against 0.419). The earlier run's priors are kept as a variant labelled "earlier run", to show what the answer changed; they do not decide.

In [7]:
# Per-session Q estimates and Delta D_KL (M9 to M11), for the readings the claims use.
def session_q(sf, trials, anchors=M.MAP_ANCHORS_FH):
    t = M.transform_sf(sf, trials["morph"].to_numpy(), anchors)
    return M.q_unnorm(t, trials["unit"].to_numpy())


def can_sf(s):
    return (s["trials"].morph == 0).sum() >= 2 and (s["trials"].morph == 1).sum() >= 2


for s in pop + [x for x in sfs if can_sf(x)]:
    s["qu"] = session_q(s["sf"], s["trials"])
    s["q"] = M.normalise_rows(s["qu"])
    s["dkl"] = {lik: M.delta_dkl(s["q"], POST[(lik, "rare")], POST[(lik, "frequent")]) for lik in M.LIKELIHOODS}
    s["dkl_last"] = M.delta_dkl(s["q"], POST_LAST["rare"], POST_LAST["frequent"])
    s["dkl_img"] = M.delta_dkl(s["q"], POST_IMG["rare"], POST_IMG["frequent"])
    if "sf_norm" in s:
        s["q_norm"] = M.normalise_rows(session_q(s["sf_norm"], s["trials"]))
        s["dkl_norm"] = M.delta_dkl(s["q_norm"], POST[("methods var 8.23", "rare")], POST[("methods var 8.23", "frequent")])
bad = sum(M.dkl_rows(POST[("methods var 8.23", g)][M.ROWS], s["q"][M.ROWS])[1] for s in pop for g in ("rare", "frequent"))
print("grid points left out for Q = 0 where P > 0:", bad)
grid points left out for Q = 0 where P > 0: 0

fig3ab-block-versus-gradual-similarity¶

Single-session population trial-by-trial similarity matrices show two blocks in the rare morph condition and a gradual transition between the extremes in the frequent morph condition.

In [8]:
Bm = {m: np.nanmean([s["C_raw"] for s in pop if s["mouse"] == m], axis=0) for m in RARE + FREQ}
share = {m: M.step_share(B) for m, B in Bm.items()}
for g, mice in (("rare", RARE), ("frequent", FREQ)):
    print(g, "step share per mouse:", {m: round(share[m], 3) for m in mice})
    print(f"  mean binned similarity, rows S-tilde = 0 and = 1:\n", np.round(np.mean([Bm[m] for m in mice], axis=0)[[0, 4]], 3))
obs, perms = M.mouse_permutation(share, RARE, FREQ)
print(f"rare mean {np.mean([share[m] for m in RARE]):.3f}, frequent {np.mean([share[m] for m in FREQ]):.3f}; "
      f"difference {obs:.3f}; 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))}")
print("mouse rows with a step share above 1:", sum(M.row_step_share(B, r) > 1 for B in Bm.values() for r in (0, 4)))
share_c = {m: float(np.mean([min(M.row_step_share(B, r), 1.0) for r in (0, 4)])) for m, B in Bm.items()}
o_c, p_c = M.mouse_permutation(share_c, RARE, FREQ)
print(f"variant, each row's share clipped at 1: difference {o_c:.3f}; 2.5 to 97.5 percentiles {np.percentile(p_c, 2.5):.3f} "
      f"to {np.percentile(p_c, 97.5):.3f}; outside: {bool(M.outside_95(o_c, p_c))}")
fig, ax = plt.subplots(1, 2, figsize=(9, 4))
for a, (m, d) in zip(ax, (("R2", 13), ("F4", 10))):
    s = [x for x in pop if x["mouse"] == m and x["day"] == d][0]
    a.imshow(s["C_full_sorted"], cmap="magma"); a.set_title(f"{m} session {d}, trials sorted by S")
plt.show()
print("similarity range in the two panels:", [(float(np.min(x["C_full_sorted"])), float(np.max(x["C_full_sorted"])))
                                              for x in pop if (x["mouse"], x["day"]) in (("R2", 13), ("F4", 10))])
rare step share per mouse: {'R1': 0.569, 'R2': 0.611, 'R3': 0.792, 'R4': 0.63, 'R5': 0.485, 'R6': 0.541}
  mean binned similarity, rows S-tilde = 0 and = 1:
 [[0.504 0.439 0.339 0.33  0.33 ]
 [0.33  0.359 0.461 0.486 0.491]]
frequent step share per mouse: {'F1': 0.511, 'F2': 0.545, 'F3': 0.625, 'F4': 0.51, 'F5': 0.749, 'F6': 0.434}
  mean binned similarity, rows S-tilde = 0 and = 1:
 [[0.384 0.346 0.322 0.319 0.317]
 [0.317 0.335 0.356 0.365 0.37 ]]
rare mean 0.605, frequent 0.563; difference 0.042; 2.5 to 97.5 percentiles -0.116 to 0.116; outside: False
mouse rows with a step share above 1: 0
variant, each row's share clipped at 1: difference 0.042; 2.5 to 97.5 percentiles -0.116 to 0.116; outside: False
No description has been provided for this image
similarity range in the two panels: [(0.2726265490055084, 1.0), (0.23384399712085724, 1.0)]

Result: not reproduced. The step share (the largest fall between neighbouring S-tilde values over the whole fall, mean of the S-tilde = 0 and = 1 rows of each mouse's binned matrix) is 0.605 for rare morph mice (0.485 to 0.792) and 0.563 for frequent morph mice (0.434 to 0.749); the difference, 0.042, lies inside the 2.5 to 97.5 percentiles of the mouse permutations (-0.116 to 0.116). No mouse row has a share above 1, so clipping the share changes nothing. The rare morph rows fall mostly between S-tilde 0.25 and 0.5 (0.439 to 0.339) and the frequent morph rows fall more evenly, but the measure the criterion names does not separate the groups.

edf7-checkerboard-sessions¶

In six named rare morph sessions, trials near S-tilde = 0.25 randomly take one extreme representation or the other, seen as checkerboard bands in the sorted similarity matrices.

In [9]:
named = [("R1", 8), ("R2", 13), ("R3", 9), ("R4", 11), ("R5", 8), ("R6", 10)]
ok_all = True
for m, d in named:
    s = [x for x in pop if x["mouse"] == m and x["day"] == d][0]
    sf = s["sf"][s["trials"].morph == 0.25]
    ok = (sf > 0.5).any() and (sf < 0.5).any()
    ok_all &= ok
    lk = link[(link.mouse == m) & (link.day == d)].iloc[0]
    print(f"   file day {d}: deposit date {lk.date.date()}, ordinal of that date among the mouse's task-track dates "
          f"{lk.date_ordinal}, session number {lk.session_number}")
    print(f"{m} session {d}: {len(sf)} S-tilde = 0.25 trials, SF above 0.5: {(sf > 0.5).sum()}, below: {(sf < 0.5).sum()}, "
          f"range {sf.min():.3f} to {sf.max():.3f}")
print("criterion met in all six:", ok_all)
others = [x for x in pop if x["group"] == "rare" and (x["mouse"], x["day"]) not in named]
print("other rare sessions with S-tilde = 0.25 SF on both sides of 0.5:",
      sum(((x["sf"][x["trials"].morph == 0.25] > 0.5).any() and (x["sf"][x["trials"].morph == 0.25] < 0.5).any()) for x in others),
      "of", len(others))
   file day 8: deposit date 2019-02-19, ordinal of that date among the mouse's task-track dates 9, session number 2
R1 session 8: 20 S-tilde = 0.25 trials, SF above 0.5: 5, below: 15, range 0.375 to 0.598
   file day 13: deposit date 2019-02-22, ordinal of that date among the mouse's task-track dates 14, session number 2
R2 session 13: 20 S-tilde = 0.25 trials, SF above 0.5: 3, below: 17, range 0.403 to 0.571
   file day 9: deposit date 2019-02-21, ordinal of that date among the mouse's task-track dates 10, session number 2
R3 session 9: 20 S-tilde = 0.25 trials, SF above 0.5: 1, below: 19, range 0.391 to 0.599
   file day 11: deposit date 2019-09-05, ordinal of that date among the mouse's task-track dates 12, session number 2
R4 session 11: 16 S-tilde = 0.25 trials, SF above 0.5: 1, below: 15, range 0.384 to 0.535
   file day 8: deposit date 2020-03-21, ordinal of that date among the mouse's task-track dates 8, session number 2
R5 session 8: 16 S-tilde = 0.25 trials, SF above 0.5: 0, below: 16, range 0.424 to 0.465
   file day 10: deposit date 2020-02-11, ordinal of that date among the mouse's task-track dates 12, session number 3
R6 session 10: 9 S-tilde = 0.25 trials, SF above 0.5: 4, below: 5, range 0.375 to 0.638
criterion met in all six: False
other rare sessions with S-tilde = 0.25 SF on both sides of 0.5: 18 of 20

Result: not reproduced. In five of the six named sessions the S-tilde = 0.25 trials include SF values on both sides of 0.5 (R1 session 8: 5 above and 15 below; R2 session 13: 3 and 17; R3 session 9: 1 and 19; R4 session 11: 1 and 15; R6 session 10: 4 and 5). In R5 session 8 all 16 lie below 0.5 (0.424 to 0.465). The criterion asks all six and names no partial outcome, so it is not met. The session numbers are the file days. R5's file of day 8 is also the 8th task-track date of R5 in the deposit, so it is R5's session 8 under either numbering (vr-deposit-link); for the other five mice the date ordinal is one or two higher than the file day. Most other rare sessions (18 of 20) also have S-tilde = 0.25 trials on both sides.

fig3f-zscored-difference-at-025¶

After z-scoring within session, trial-by-trial population similarity differs significantly between rare and frequent morph mice for S-tilde = 0.25 trials.

In [10]:
def zdiff(key, mouse_z=False, rare=RARE, freq=FREQ):
    if mouse_z:
        per = {m: M.zscore_matrix(np.nanmean([s[key] for s in pop if s["mouse"] == m], axis=0)) for m in rare + freq}
    else:
        per = {m: np.nanmean([M.zscore_matrix(s[key]) for s in pop if s["mouse"] == m], axis=0) for m in rare + freq}
    return M.mouse_permutation(per, rare, freq)


fig3f = {}
for label, key, mz in (("main: smoothed deconvolved, z-scored per session", "C_raw", False),
                       ("variant: 99th-percentile normalised signal", "C_norm", False),
                       ("variant: unsmoothed (2020 code)", "C_unsmoothed", False),
                       ("variant: z-scored mouse means (2026 code)", "C_raw", True)):
    obs, perms = zdiff(key, mz)
    sig = M.outside_95(obs, perms)
    fig3f[label] = (obs, perms, sig)
    print(label)
    print(pd.DataFrame(obs, index=M.MORPHS, columns=M.MORPHS).round(3).to_string())
    lo, hi = np.percentile(perms, [2.5, 97.5], axis=0)
    print("  S-tilde = 0.25 row: difference", obs[1].round(3), "\n  2.5 pct", lo[1].round(3), "\n  97.5 pct", hi[1].round(3))
    print("  significant entries of the 0.25 row:", [(M.MORPHS[j], round(obs[1, j], 3)) for j in range(5) if sig[1, j]])
    print("  all significant entries:", [(M.MORPHS[i], M.MORPHS[j], round(obs[i, j], 3)) for i, j in zip(*np.nonzero(sig)) if i <= j])
main: smoothed deconvolved, z-scored per session
       0.00   0.25   0.50   0.75   1.00
0.00 -0.413  0.281 -0.081 -0.103  0.011
0.25  0.281  0.181 -0.409 -0.427 -0.367
0.50 -0.081 -0.409  0.225  0.229  0.282
0.75 -0.103 -0.427  0.229  0.322  0.324
1.00  0.011 -0.367  0.282  0.324  0.208
  S-tilde = 0.25 row: difference [ 0.281  0.181 -0.409 -0.427 -0.367] 
  2.5 pct [-0.29  -0.482 -0.39  -0.514 -0.316] 
  97.5 pct [0.29  0.482 0.397 0.514 0.32 ]
  significant entries of the 0.25 row: [(np.float64(0.5), np.float64(-0.409)), (np.float64(1.0), np.float64(-0.367))]
  all significant entries: [(np.float64(0.25), np.float64(0.5), np.float64(-0.409)), (np.float64(0.25), np.float64(1.0), np.float64(-0.367))]
variant: 99th-percentile normalised signal
       0.00   0.25   0.50   0.75   1.00
0.00 -0.480  0.196 -0.075 -0.044  0.004
0.25  0.196  0.091 -0.444 -0.439 -0.393
0.50 -0.075 -0.444  0.275  0.308  0.282
0.75 -0.044 -0.439  0.308  0.435  0.371
1.00  0.004 -0.393  0.282  0.371  0.148
  S-tilde = 0.25 row: difference [ 0.196  0.091 -0.444 -0.439 -0.393] 
  2.5 pct [-0.324 -0.461 -0.353 -0.5   -0.318] 
  97.5 pct [0.324 0.461 0.357 0.5   0.318]
  significant entries of the 0.25 row: [(np.float64(0.5), np.float64(-0.444)), (np.float64(1.0), np.float64(-0.393))]
  all significant entries: [(np.float64(0.25), np.float64(0.5), np.float64(-0.444)), (np.float64(0.25), np.float64(1.0), np.float64(-0.393)), (np.float64(0.75), np.float64(1.0), np.float64(0.371))]
variant: unsmoothed (2020 code)
       0.00   0.25   0.50   0.75   1.00
0.00 -0.147  0.447 -0.002 -0.008  0.076
0.25  0.447  0.153 -0.432 -0.449 -0.409
0.50 -0.002 -0.432  0.174  0.098  0.205
0.75 -0.008 -0.449  0.098  0.227  0.212
1.00  0.076 -0.409  0.205  0.212  0.119
  S-tilde = 0.25 row: difference [ 0.447  0.153 -0.432 -0.449 -0.409] 
  2.5 pct [-0.377 -0.526 -0.376 -0.419 -0.338] 
  97.5 pct [0.374 0.526 0.383 0.421 0.339]
  significant entries of the 0.25 row: [(np.float64(0.0), np.float64(0.447)), (np.float64(0.5), np.float64(-0.432)), (np.float64(0.75), np.float64(-0.449)), (np.float64(1.0), np.float64(-0.409))]
  all significant entries: [(np.float64(0.0), np.float64(0.25), np.float64(0.447)), (np.float64(0.25), np.float64(0.5), np.float64(-0.432)), (np.float64(0.25), np.float64(0.75), np.float64(-0.449)), (np.float64(0.25), np.float64(1.0), np.float64(-0.409))]
variant: z-scored mouse means (2026 code)
       0.00   0.25   0.50   0.75   1.00
0.00 -0.592  0.272 -0.018 -0.069  0.099
0.25  0.272  0.102 -0.458 -0.467 -0.349
0.50 -0.018 -0.458  0.234  0.248  0.339
0.75 -0.069 -0.467  0.248  0.257  0.310
1.00  0.099 -0.349  0.339  0.310  0.187
  S-tilde = 0.25 row: difference [ 0.272  0.102 -0.458 -0.467 -0.349] 
  2.5 pct [-0.323 -0.543 -0.385 -0.546 -0.306] 
  97.5 pct [0.323 0.543 0.389 0.546 0.31 ]
  significant entries of the 0.25 row: [(np.float64(0.5), np.float64(-0.458)), (np.float64(1.0), np.float64(-0.349))]
  all significant entries: [(np.float64(0.25), np.float64(0.5), np.float64(-0.458)), (np.float64(0.25), np.float64(1.0), np.float64(-0.349))]

Result: reproduced. In the S-tilde = 0.25 row of the z-scored rare minus frequent difference, the entries with S-tilde = 0.5 (-0.409) and 1.0 (-0.367) lie outside the 2.5 to 97.5 percentiles of the 923 mouse permutations: rare morph 0.25 trials are less similar to 0.5 and 1.0 trials than frequent morph ones. The entry with S-tilde = 0 is +0.281 against a 97.5 percentile of 0.290. The variants (normalised signal, no smoothing, z-scoring the mouse means) also find significant entries in the 0.25 row.

fig4-sf-stable-along-track¶

Position-wise SF shows stable clustered representations along the whole track in rare morph mice and a spectrum in frequent morph mice; remapping happens soon after the trial starts and stays as the mouse runs.

In [11]:
curves = {}
for m in RARE + FREQ:
    per_sess = []
    for s in pop:
        if s["mouse"] != m:
            continue
        mor = s["trials"].morph.to_numpy()
        per_sess.append(np.array([np.nanmean(s["sf_pos"][mor == v], axis=0) for v in M.MORPHS]))
    curves[m] = np.nanmean(per_sess, axis=0)            # 5 x bins
res4 = {}
for g, mice in (("rare", RARE), ("frequent", FREQ)):
    c = np.array([curves[m] for m in mice])
    mean, sem = c.mean(0), c.std(0, ddof=1) / np.sqrt(len(mice))
    res4[g] = (mean, sem)
    sep = np.abs(mean[0] - mean[4]) > sem[0] + sem[4]
    print(f"{g}: S-tilde 0 and 1 separated by more than the summed s.e.m. in {sep[1:].sum()} of 44 bins after the first")
    print("  mean SF by S-tilde, every 5th bin:\n", np.round(mean[:, ::5], 3))
mean, sem = res4["rare"]
ov = np.abs(mean[3] - mean[4]) <= sem[3] + sem[4]
near0 = np.abs(mean[1] - mean[0]) < np.abs(mean[1] - mean[4])
print(f"rare: 0.75 and 1.0 overlap within s.e.m. in {ov.sum()} of 45 bins; 0.25 nearer 0 than 1 in {near0.sum()} of 45 "
      f"bins ({near0[1:].sum()} of 44 after the first)")
mean, sem = res4["frequent"]
between = (np.minimum(mean[0], mean[2]) < mean[1]) & (mean[1] < np.maximum(mean[0], mean[2]))
print(f"frequent: 0.25 between 0 and 0.5 in {between.sum()} of 45 bins")
fig, ax = plt.subplots(1, 2, figsize=(10, 3.5), sharey=True)
for a, g in zip(ax, ("rare", "frequent")):
    mean, sem = res4[g]
    for k, v in enumerate(M.MORPHS):
        a.plot(np.arange(45) * 10 + 5, mean[k], color=plt.cm.cool(v), label=str(v))
        a.fill_between(np.arange(45) * 10 + 5, mean[k] - sem[k], mean[k] + sem[k], color=plt.cm.cool(v), alpha=0.3)
    a.set_title(g); a.set_xlabel("position (cm)")
ax[0].set_ylabel("SF"); ax[0].legend()
plt.show()
print("plotted range:", {g: (float((res4[g][0] - res4[g][1]).min()), float((res4[g][0] + res4[g][1]).max())) for g in res4})
rare: S-tilde 0 and 1 separated by more than the summed s.e.m. in 44 of 44 bins after the first
  mean SF by S-tilde, every 5th bin:
 [[0.394 0.399 0.401 0.406 0.406 0.426 0.43  0.413 0.394]
 [0.457 0.444 0.452 0.461 0.463 0.471 0.466 0.458 0.446]
 [0.576 0.568 0.571 0.57  0.568 0.553 0.552 0.567 0.584]
 [0.602 0.594 0.594 0.593 0.592 0.57  0.569 0.584 0.605]
 [0.607 0.601 0.599 0.595 0.592 0.573 0.569 0.584 0.603]]
frequent: S-tilde 0 and 1 separated by more than the summed s.e.m. in 44 of 44 bins after the first
  mean SF by S-tilde, every 5th bin:
 [[0.458 0.463 0.463 0.459 0.466 0.473 0.47  0.468 0.443]
 [0.484 0.494 0.495 0.499 0.495 0.496 0.499 0.497 0.49 ]
 [0.512 0.521 0.527 0.53  0.523 0.514 0.518 0.522 0.532]
 [0.52  0.531 0.536 0.539 0.528 0.52  0.524 0.528 0.546]
 [0.534 0.535 0.534 0.538 0.532 0.525 0.526 0.528 0.552]]
rare: 0.75 and 1.0 overlap within s.e.m. in 45 of 45 bins; 0.25 nearer 0 than 1 in 45 of 45 bins (44 of 44 after the first)
frequent: 0.25 between 0 and 0.5 in 45 of 45 bins
No description has been provided for this image
plotted range: {'rare': (0.36158147975466237, 0.6367642849620645), 'frequent': (0.4063935689220909, 0.596552187711664)}

Result: reproduced. In both conditions the S-tilde = 0 and = 1 curves of position-wise SF are separated by more than their summed s.e.m. in all 44 bins after the first. In rare morph mice the S-tilde 0.75 and 1.0 curves overlap within s.e.m. in all 45 bins and the 0.25 curve lies nearer the S-tilde 0 curve in all 45. In frequent morph mice the 0.25 curve lies between the 0 and 0.5 curves in all 45 bins. The curves are flat along the track (printed every 5th bin).

fig6a-dkl-sign¶

Delta D_KL of each session's Q estimate took the expected sign (negative for rare, positive for frequent) in 41 of 45 sessions and in every session of 9 of 12 mice; across mice, rare -0.88 +- 0.23 and frequent 0.50 +- 0.11 (mean +- s.e.m.), a significant difference.

In [12]:
def fig6a_summary(values, label):
    d = pd.DataFrame([{"mouse": s["mouse"], "group": s["group"], "day": s["day"], "dkl": v} for s, v in zip(pop, values)])
    d["expected"] = np.where(d.group == "rare", d.dkl < 0, d.dkl > 0)
    per = d.groupby("mouse").dkl.mean()
    every = d.groupby("mouse").expected.all()
    obs, perms = M.mouse_permutation(per.to_dict(), RARE, FREQ)
    r, f = per[RARE], per[FREQ]
    out = {"reading": label, "sessions expected sign": f"{int(d.expected.sum())} of {len(d)}",
           "mice every session": int(every.sum()), "rare mean": round(r.mean(), 3), "rare sem": round(r.sem(), 3),
           "frequent mean": round(f.mean(), 3), "frequent sem": round(f.sem(), 3), "difference": round(obs, 3),
           "perm range": (round(perms.min(), 3), round(perms.max(), 3)), "outside range": bool(M.outside_range(obs, perms))}
    return out, d


rows = []
main6a, d6a = fig6a_summary([s["dkl"]["methods var 8.23"] for s in pop], "main: Methods likelihood")
rows.append(main6a)
for lik in ("code 0.3 units", "code 0.4 units"):
    rows.append(fig6a_summary([s["dkl"][lik] for s in pop], f"variant: likelihood {lik}")[0])
rows.append(fig6a_summary([s["dkl_last"] for s in pop], "variant: last mouse's prior (2020 code)")[0])
rows.append(fig6a_summary([s["dkl_norm"] for s in pop], "variant: normalised signal")[0])
rows.append(fig6a_summary([s["dkl_img"] for s in pop], "earlier run: priors from dandiset trials")[0])
print(pd.DataFrame(rows).to_string(index=False))
print("\nExpected: 41 of 45 sessions (+-4.1), 9 mice (+-0.9), rare -0.88 +- 0.23, frequent 0.50 +- 0.11")
print("\nPer session, main reading:")
print(d6a.pivot_table(index="mouse", columns="day", values="dkl").round(2).to_string())
m = d6a.groupby("mouse").dkl.mean()
print("per mouse:", m.round(3).to_dict())
print(f"\nwithin tolerance: sessions {abs(int(d6a.expected.sum()) - 41) <= 4.1}, mice {abs(main6a['mice every session'] - 9) <= 0.9}, "
      f"rare {abs(main6a['rare mean'] + 0.88) <= 0.23}, frequent {abs(main6a['frequent mean'] - 0.50) <= 0.11}")
                                 reading sessions expected sign  mice every session  rare mean  rare sem  frequent mean  frequent sem  difference      perm range  outside range
                main: Methods likelihood               43 of 47                   8     -0.660     0.104          0.158         0.052      -0.817 (-0.727, 0.817)           True
      variant: likelihood code 0.3 units               44 of 47                  10     -0.848     0.254          0.701         0.132      -1.549 (-1.466, 1.549)           True
      variant: likelihood code 0.4 units               40 of 47                  10     -0.866     0.302          0.778         0.157      -1.644 (-1.626, 1.644)           True
 variant: last mouse's prior (2020 code)               42 of 47                   8     -0.577     0.085          0.105         0.045      -0.682 (-0.606, 0.682)           True
              variant: normalised signal               45 of 47                  11     -0.657     0.105          0.200         0.034      -0.857 (-0.722, 0.857)           True
earlier run: priors from dandiset trials               37 of 47                   7     -0.354     0.046          0.007         0.025      -0.361 (-0.321, 0.361)           True

Expected: 41 of 45 sessions (+-4.1), 9 mice (+-0.9), rare -0.88 +- 0.23, frequent 0.50 +- 0.11

Per session, main reading:
day      8     9     10    11    12    13
mouse                                    
F1     0.12 -0.04  0.04   NaN   NaN   NaN
F2     0.20  0.12  0.19  0.21   NaN   NaN
F3    -0.01   NaN   NaN   NaN   NaN   NaN
F4     0.42  0.01 -0.22  0.48  0.16   NaN
F5     0.35  0.10  0.44  0.24 -0.02   NaN
F6     0.35  0.30  0.39   NaN   NaN   NaN
R1    -0.22 -0.42 -0.36 -0.47 -0.62   NaN
R2    -0.11 -0.33 -0.08 -0.47 -0.24 -0.46
R3    -0.86 -1.03 -0.75 -0.93 -0.83   NaN
R4    -1.03 -0.81 -0.52 -0.51 -0.49   NaN
R5    -0.80 -0.93   NaN   NaN   NaN   NaN
R6    -0.35 -0.58 -1.59   NaN   NaN   NaN
per mouse: {'F1': 0.041, 'F2': 0.18, 'F3': -0.011, 'F4': 0.169, 'F5': 0.22, 'F6': 0.346, 'R1': -0.417, 'R2': -0.282, 'R3': -0.88, 'R4': -0.674, 'R5': -0.867, 'R6': -0.838}

within tolerance: sessions True, mice False, rare True, frequent False

Result: partially reproduced. With the deposit's priors and the likelihood of the Methods, Delta D_KL has the expected sign in 43 of 47 sessions (41 +- 4.1 expected) and the difference between groups, -0.817, lies outside the range of the 923 permutations (-0.727 to 0.817; the largest permutation is the swapped grouping). The rare mean, -0.660 +- 0.104, is within tolerance (-0.88 +- 0.23); the frequent mean, 0.158 +- 0.052, has the expected sign but is below 0.50 +- 0.11, and 8 mice have the expected sign in every session (9 +- 0.9 expected). The test and the signs hold and two values are outside tolerance. The priors from the dandiset's imaged trials, used in the earlier run, gave 37 of 47 sessions, 7 mice, rare -0.354 and frequent 0.007. With the code's likelihood widths, variants, 40 to 44 sessions, 10 mice, rare -0.848 and -0.866, frequent 0.701 and 0.778.

fig6bc-pooled-dkl¶

Q estimates pooled over all sessions and mice approximate the posterior of the matching condition (Delta D_KL rare -0.44, frequent 0.42).

In [13]:
def group_q(mice, reading, sess=pop):
    qs = []
    for m in mice:
        ss = [s for s in sess if s["mouse"] == m and "q" in s]
        if not ss:
            continue
        if reading == "a":
            qm = M.normalise_rows(np.mean([s["q"] for s in ss], axis=0))
        else:
            qm = M.normalise_rows(np.sum([s["qu"] for s in ss], axis=0))
        qs.append(qm)
    return M.normalise_rows(np.sum(qs, axis=0)), len(qs)


for reading in "ab":
    out = {}
    for g, mice in (("rare", RARE), ("frequent", FREQ)):
        q, n = group_q(mice, reading)
        out[g] = {lik: round(M.delta_dkl(q, POST[(lik, "rare")], POST[(lik, "frequent")]), 3) for lik in M.LIKELIHOODS}
    print(f"reading {reading} ({'mean of session Q' if reading == 'a' else 'one Q from all trials of a mouse'}):", out)
out = {g: round(M.delta_dkl(group_q(mice, "a")[0], POST_IMG["rare"], POST_IMG["frequent"]), 3)
       for g, mice in (("rare", RARE), ("frequent", FREQ))}
print("earlier run, priors from dandiset trials, reading a:", out)
print("expected rare -0.44 +- 0.044, frequent 0.42 +- 0.042 (main likelihood decides)")
reading a (mean of session Q): {'rare': {'methods var 8.23': -0.464, 'code 0.3 units': -0.348, 'code 0.4 units': -0.259}, 'frequent': {'methods var 8.23': 0.125, 'code 0.3 units': 0.595, 'code 0.4 units': 0.646}}
reading b (one Q from all trials of a mouse): {'rare': {'methods var 8.23': -0.469, 'code 0.3 units': -0.36, 'code 0.4 units': -0.268}, 'frequent': {'methods var 8.23': 0.118, 'code 0.3 units': 0.59, 'code 0.4 units': 0.644}}
earlier run, priors from dandiset trials, reading a: {'rare': -0.266, 'frequent': -0.0}
expected rare -0.44 +- 0.044, frequent 0.42 +- 0.042 (main likelihood decides)

Result: partially reproduced. With the deposit's priors, pooling the Q estimates gives rare -0.464 and frequent 0.125 when each mouse's Q is the mean of its session Q estimates (reading a), and -0.469 and 0.118 when each mouse's Q comes from all its trials (reading b), against -0.44 +- 0.044 and 0.42 +- 0.042. The rare value is within tolerance under both readings; the frequent value has the expected sign but is far below 0.42, so only the signs hold. The earlier run's priors from the dandiset's imaged trials gave rare -0.266 and frequent -0.000. With the code's likelihood widths, variants, the frequent value is 0.590 to 0.646 and the rare -0.259 to -0.360.

fig6d-prior-reconstruction¶

Priors reconstructed from each mouse's neural data alone are closer to the ideal prior of the mouse's own condition (Delta D_KL rare -0.46 +- 0.12, frequent 0.46 +- 0.07, mean +- s.e.m. across mice), a significant group difference.

In [14]:
def prior_dkl(qu, lik="methods var 8.23", priors=prior, code=False):
    R = M.reconstruct_prior(qu, lik, code=code)
    return M.dkl(priors["rare"], R) - M.dkl(priors["frequent"], R), R


recon = {}
rows = []
for lik in M.LIKELIHOODS:
    vals = {}
    for m in RARE + FREQ:
        qu = np.sum([s["qu"] for s in pop if s["mouse"] == m], axis=0)
        vals[m], R = prior_dkl(qu, lik)
        if lik == "methods var 8.23":
            recon[m] = R
    obs, perms = M.mouse_permutation(vals, RARE, FREQ)
    r, f = pd.Series({m: vals[m] for m in RARE}), pd.Series({m: vals[m] for m in FREQ})
    rows.append({"likelihood": lik, "rare mean": round(r.mean(), 3), "rare sem": round(r.sem(), 3),
                 "frequent mean": round(f.mean(), 3), "frequent sem": round(f.sem(), 3), "difference": round(obs, 3),
                 "outside range": bool(M.outside_range(obs, perms)), "rare signs negative": int((r < 0).sum()),
                 "frequent signs positive": int((f > 0).sum())})
    if lik == "methods var 8.23":
        fig6d_vals = vals
        print("per mouse (main):", {k: round(v, 3) for k, v in vals.items()})
print(pd.DataFrame(rows).to_string(index=False))
vals_img = {m: prior_dkl(np.sum([s["qu"] for s in pop if s["mouse"] == m], axis=0), priors=prior_img)[0] for m in RARE + FREQ}
print("earlier run, priors from dandiset trials: rare mean", round(np.mean([vals_img[m] for m in RARE]), 3),
      "frequent mean", round(np.mean([vals_img[m] for m in FREQ]), 3))
print("expected rare -0.46 +- 0.12, frequent 0.46 +- 0.07")
fig, ax = plt.subplots(figsize=(6, 3))
for m in RARE + FREQ:
    ax.plot(M.unit_to_fh(M.GRID), recon[m], color="tab:blue" if m in RARE else "tab:orange", lw=0.8)
ax.plot(M.unit_to_fh(M.GRID), prior["rare"], "k--"); ax.plot(M.unit_to_fh(M.GRID), prior["frequent"], "k:")
ax.set_xlabel("f_h"); plt.show()
print("reconstructed prior range:", float(min(r.min() for r in recon.values())), float(max(r.max() for r in recon.values())))
per mouse (main): {'R1': 0.494, 'R2': 0.622, 'R3': -0.033, 'R4': 0.209, 'R5': 0.211, 'R6': -0.166, 'F1': 0.919, 'F2': 1.054, 'F3': 1.085, 'F4': 1.015, 'F5': 1.436, 'F6': 1.242}
      likelihood  rare mean  rare sem  frequent mean  frequent sem  difference  outside range  rare signs negative  frequent signs positive
methods var 8.23      0.223     0.122          1.125         0.076      -0.902           True                    2                        6
  code 0.3 units      0.517     0.122          1.379         0.063      -0.862           True                    0                        6
  code 0.4 units      0.480     0.121          1.285         0.061      -0.804           True                    0                        6
earlier run, priors from dandiset trials: rare mean -0.02 frequent mean 0.633
expected rare -0.46 +- 0.12, frequent 0.46 +- 0.07
No description has been provided for this image
reconstructed prior range: 1.862813731368349e-09 0.004545099831295539
In [15]:
# Variant: the code's computation of R (M.reconstruct_prior, code=True; SFReg.plot_sfreg at dca5a57, which
# printed -0.476 +- 0.132 rare and 0.453 +- 0.074 frequent, and similarity_fraction.py at 9230b0a): Z taken at
# the grid point f itself and not inside the sum over fhat.
rows = []
for lik in M.LIKELIHOODS:
    for pri_name, pri in (("group priors", prior), ("2020 code: last mouse's prior", prior_last)):
        if pri_name != "group priors" and lik != "code 0.3 units":
            continue
        v = {m: prior_dkl(np.sum([s["qu"] for s in pop if s["mouse"] == m], axis=0), lik, pri, code=True)[0] for m in RARE + FREQ}
        o, pp = M.mouse_permutation(v, RARE, FREQ)
        r_, f_ = pd.Series({m: v[m] for m in RARE}), pd.Series({m: v[m] for m in FREQ})
        rows.append({"likelihood": lik, "priors": pri_name, "rare mean": round(r_.mean(), 3), "rare sem": round(r_.sem(), 3),
                     "frequent mean": round(f_.mean(), 3), "frequent sem": round(f_.sem(), 3), "difference": round(o, 3),
                     "outside range": bool(M.outside_range(o, pp)), "rare negative": int((r_ < 0).sum()),
                     "frequent positive": int((f_ > 0).sum())})
        if lik == "methods var 8.23" and pri_name == "group priors":
            fig6d_code_vals = v
print("variant, the code's computation of R:")
print(pd.DataFrame(rows).to_string(index=False))
print("per mouse (code computation, Methods likelihood):", {k: round(x, 3) for k, x in fig6d_code_vals.items()})

# Verifier's check: an ideal observer. For each mouse, its own trials of sessions 8 to N (their fhat), each
# trial's estimate drawn 20 times from the rare or the frequent posterior (Methods likelihood); Q from these
# estimates (M10 kernel); then the Q-based Delta D_KL (M11) and the reconstructed-prior Delta D_KL, with
# the criterion's formula and with the code's computation.
io_rows = []
for m in RARE + FREQ:
    fh = np.concatenate([s["trials"].unit.to_numpy() for s in pop if s["mouse"] == m])
    for g in ("rare", "frequent"):
        qu_io = M.ideal_observer_q(fh, POST[("methods var 8.23", g)], seed=4100 + 10 * (RARE + FREQ).index(m) + (g == "frequent"))
        io_rows.append({"mouse": m, "observer": g, "trials": len(fh),
                        "Q Delta D_KL": M.delta_dkl(M.normalise_rows(qu_io), POST[("methods var 8.23", "rare")], POST[("methods var 8.23", "frequent")]),
                        "prior Delta D_KL (criterion)": prior_dkl(qu_io)[0],
                        "prior Delta D_KL (code)": prior_dkl(qu_io, code=True)[0]})
io = pd.DataFrame(io_rows)
print("\nideal observer on each mouse's trial design (mean over the 12 mice, and range):")
print(io.groupby("observer")[["Q Delta D_KL", "prior Delta D_KL (criterion)", "prior Delta D_KL (code)"]]
      .agg(["mean", "min", "max"]).round(3).to_string())
print("expected for a measure that tells the posteriors apart: negative for the rare observer, positive for the frequent")
variant, the code's computation of R:
      likelihood                        priors  rare mean  rare sem  frequent mean  frequent sem  difference  outside range  rare negative  frequent positive
methods var 8.23                  group priors     -0.288     0.127          0.638         0.078      -0.925           True              4                  6
  code 0.3 units                  group priors     -0.340     0.127          0.585         0.078      -0.925           True              5                  6
  code 0.3 units 2020 code: last mouse's prior     -0.421     0.123          0.500         0.077      -0.921           True              6                  6
  code 0.4 units                  group priors     -0.363     0.127          0.562         0.078      -0.925           True              5                  6
per mouse (code computation, Methods likelihood): {'R1': 0.029, 'R2': 0.111, 'R3': -0.538, 'R4': -0.325, 'R5': -0.316, 'R6': -0.686, 'F1': 0.439, 'F2': 0.544, 'F3': 0.627, 'F4': 0.517, 'F5': 0.975, 'F6': 0.725}
ideal observer on each mouse's trial design (mean over the 12 mice, and range):
         Q Delta D_KL               prior Delta D_KL (criterion)               prior Delta D_KL (code)              
                 mean    min    max                         mean    min    max                    mean    min    max
observer                                                                                                            
frequent        0.366  0.342  0.389                        1.003  0.829  1.181                   0.502  0.309  0.694
rare           -0.303 -0.349 -0.259                        0.547  0.380  0.741                   0.047 -0.141  0.268
expected for a measure that tells the posteriors apart: negative for the rare observer, positive for the frequent

Result: not reproduced. The reconstructed priors still separate the groups: the difference of across-mouse means, -0.902, lies outside the range of all permutations, and all six frequent morph mice are positive (1.125 +- 0.076, expected 0.46 +- 0.07). But with the deposit's priors the rare morph mean is positive, 0.223 +- 0.122 (expected -0.46 +- 0.12), with only R3 (-0.033) and R6 (-0.166) negative, so the sign of the rare mean fails and the criterion's partial outcome (the test and the signs) is not met either. The earlier run's priors from the dandiset's imaged trials gave rare -0.020 and frequent 0.633; the code's likelihood widths, variants, give rare 0.480 and 0.517, frequent 1.285 and 1.379.

The ideal-observer check (the verifier's request) shows that the criterion's formula cannot give the rare sign on this design: an observer whose estimates are drawn from the rare posterior, on each mouse's own trials, gives a reconstructed-prior Delta D_KL of +0.547 on average (0.380 to 0.741), while its Q estimate gives -0.303 as expected. The paper's code computes R differently, taking Z at the grid point f and not inside the sum over fhat (SFReg at dca5a57, which printed -0.476 +- 0.132 and 0.453 +- 0.074, and the 2026 code). With that computation, a variant, the rare ideal observer gives +0.047 (-0.141 to 0.268) and the frequent one +0.502, and the data give rare -0.288 +- 0.127 (4 of 6 mice negative) and frequent 0.638 +- 0.078, the difference outside every permutation. With the 2020 code's other settings as well (likelihood width 0.3 units and the last mouse's prior), rare -0.421 +- 0.123 and frequent 0.500 +- 0.077, both within tolerance, with every mouse of the expected sign. The criterion fixes the formula of the Methods, so the outcome stays not reproduced; a question asks a reader whether the claim should follow the code (questions/plitt-2021.yaml).

map-estimate-values¶

The average MAP estimate of f_h for S-tilde = 0 trials is 11.08 under the rare and 10.64 under the frequent posterior, and for S-tilde = 1 trials 38.13 and 37.30.

In [16]:
exp_map = {("rare", 0): 11.08, ("frequent", 0): 10.64, ("rare", 1): 38.13, ("frequent", 1): 37.30}
ttr = pd.concat([s["trials"].assign(group=s["group"]) for s in pop])
for lik in M.LIKELIHOODS:
    for reading in ("a: all sessions", "b: own group's sessions"):
        vals = {}
        for (g, v), e in exp_map.items():
            x = ttr[ttr.morph == v] if reading.startswith("a") else ttr[(ttr.morph == v) & (ttr.group == g)]
            vals[(g, v)] = float(np.mean(M.unit_to_fh(M.map_estimate(POST[(lik, g)], x.unit.to_numpy()))))
        ok = all(abs(vals[k] - e) <= 0.1 * e for k, e in exp_map.items())
        print(f"{lik:18s} {reading}: " + ", ".join(f"{g} S{v} {vals[(g, v)]:.2f}" for (g, v) in exp_map) + f"; all within 10%: {ok}")
vals_last = {(g, v): float(np.mean(M.unit_to_fh(M.map_estimate(POST_LAST[g], ttr[ttr.morph == v].unit.to_numpy())))) for (g, v) in exp_map}
vals_img = {(g, v): float(np.mean(M.unit_to_fh(M.map_estimate(POST_IMG[g], ttr[ttr.morph == v].unit.to_numpy())))) for (g, v) in exp_map}
print("earlier run, priors from dandiset trials, reading a:", {f"{g} S{v}": round(x, 2) for (g, v), x in vals_img.items()})
print("variant last-mouse prior, reading a:", {f"{g} S{v}": round(x, 2) for (g, v), x in vals_last.items()})
print("f_h of the S-tilde = 0 and 1 trials themselves: means",
      round(float(ttr[ttr.morph == 0].fh.mean()), 2), round(float(ttr[ttr.morph == 1].fh.mean()), 2))
methods var 8.23   a: all sessions: rare S0 10.62, frequent S0 10.69, rare S1 38.19, frequent S1 37.62; all within 10%: True
methods var 8.23   b: own group's sessions: rare S0 10.53, frequent S0 10.86, rare S1 38.18, frequent S1 37.63; all within 10%: True
code 0.3 units     a: all sessions: rare S0 10.76, frequent S0 10.88, rare S1 38.18, frequent S1 37.35; all within 10%: True
code 0.3 units     b: own group's sessions: rare S0 10.70, frequent S0 10.99, rare S1 38.18, frequent S1 37.35; all within 10%: True
code 0.4 units     a: all sessions: rare S0 10.86, frequent S0 11.13, rare S1 38.18, frequent S1 37.28; all within 10%: True
code 0.4 units     b: own group's sessions: rare S0 10.81, frequent S0 11.26, rare S1 38.18, frequent S1 37.28; all within 10%: True
earlier run, priors from dandiset trials, reading a: {'rare S0': 10.67, 'frequent S0': 10.72, 'rare S1': 38.09, 'frequent S1': 37.62}
variant last-mouse prior, reading a: {'rare S0': 10.73, 'frequent S0': 10.61, 'rare S1': 38.18, 'frequent S1': 37.62}
f_h of the S-tilde = 0 and 1 trials themselves: means 10.55 38.19

Result: reproduced. With the deposit's priors and the Methods likelihood the mean MAP estimates over all S-tilde = 0 and = 1 trials of sessions 8 to N are 10.62 and 10.69 (rare and frequent posterior) and 38.19 and 37.62, all within 10% of 11.08, 10.64, 38.13 and 37.30; each group's own trials (reading b) and the code's likelihood widths give values within 10% as well. The earlier run's priors gave 10.67, 10.72, 38.09 and 37.62.

edf9-early-sessions¶

The rare versus frequent remapping patterns were stable over sessions and emerged early in training (session 3) in most animals.

In [17]:
s3 = [s for s in sfs if s["day"] == 3 and s["group"] in ("rare", "frequent") and "q" in s]
# reading (b): every deposit trial before session 3 (the date and session number of the day 3 file)
d3 = link[link.day == 3].set_index("mouse")
mp3, n3 = {}, {}
for m in d3.index:
    b3 = M.sessions_before(vr_ses, m, d3.loc[m, "date"], d3.loc[m, "session_number"])
    t3 = pd.concat([vr_trials[x] for x in b3.member]).dropna(subset=["morph"])
    mp3[m], n3[m] = M.prior_from_units(t3.unit.to_numpy()), (len(b3), len(t3), round(float(t3.morph.isin([0.25, 0.5, 0.75]).mean()), 3))
prior3 = {"rare": M.group_prior([mp3[m] for m in RARE if m in mp3]), "frequent": M.group_prior([mp3[m] for m in FREQ if m in mp3])}
post3 = {g: M.posterior(prior3[g]) for g in prior3}
print("deposit sessions, trials and intermediate fraction before session 3, per mouse:", n3)
rows = []
for s in s3:
    a = s["dkl"]["methods var 8.23"]
    b = M.delta_dkl(s["q"], post3["rare"], post3["frequent"])
    exp_sign = (lambda v: v < 0) if s["group"] == "rare" else (lambda v: v > 0)
    rows.append({"mouse": s["mouse"], "group": s["group"], "dkl a": round(a, 3), "dkl b": round(b, 3),
                 "expected a": exp_sign(a), "expected b": exp_sign(b)})
r9 = pd.DataFrame(rows)
print(r9.to_string(index=False))
print(f"session 3 with the expected sign: reading a {int(r9['expected a'].sum())} of {len(r9)}, reading b {int(r9['expected b'].sum())} of {len(r9)}")
cons = d6a.groupby("mouse").apply(lambda d: max((d.dkl < 0).mean(), (d.dkl > 0).mean()))
print("sessions 8 to N, share of each mouse's sessions with its majority sign:", cons.round(2).to_dict())
print("every mouse has one sign in most of its sessions:", bool((cons > 0.5).all()))
deposit sessions, trials and intermediate fraction before session 3, per mouse: {'F1': (4, 407, 0.6), 'F2': (5, 388, 0.606), 'F3': (5, 386, 0.593), 'F4': (4, 427, 0.602), 'F5': (6, 378, 0.608), 'F6': (6, 505, 0.596), 'R1': (5, 320, 0.0), 'R2': (7, 350, 0.0), 'R3': (5, 326, 0.0), 'R4': (4, 490, 0.0), 'R5': (4, 517, 0.0)}
mouse    group  dkl a  dkl b  expected a  expected b
   F1 frequent  0.491  1.292        True        True
   F2 frequent -0.513 -0.435       False       False
   F3 frequent  0.134  0.612        True        True
   F4 frequent  0.161  0.685        True        True
   F5 frequent  0.658  1.380        True        True
   F6 frequent  0.323  1.043        True        True
   R1     rare  0.299  1.105       False       False
   R2     rare -0.827 -1.375        True        True
   R3     rare -0.325 -0.275        True        True
   R4     rare -0.874 -1.119        True        True
   R5     rare  0.069  0.524       False       False
session 3 with the expected sign: reading a 8 of 11, reading b 8 of 11
sessions 8 to N, share of each mouse's sessions with its majority sign: {'F1': 0.67, 'F2': 1.0, 'F3': 1.0, 'F4': 0.8, 'F5': 0.8, 'F6': 1.0, 'R1': 1.0, 'R2': 1.0, 'R3': 1.0, 'R4': 1.0, 'R5': 1.0, 'R6': 1.0}
every mouse has one sign in most of its sessions: True

Result: reproduced. Session 3 Delta D_KL has the expected sign in 8 of 11 mice with the group posteriors of sessions 8 to N built from the deposit (reading a), and in 8 of 11 with posteriors from every deposit trial before session 3 (reading b; all 11 mice with a session 3 have such trials in the deposit, 320 to 517 each, none intermediate for the rare morph mice). The same three mice (F2, R1, R5) have the other sign under both readings. In sessions 8 to N every mouse's values have one sign in most of its sessions (67% to 100%).

edf9k-null-models-rare and edf9l-null-models-frequent¶

For rare (frequent) morph sessions, Q estimates are fit worse by the other condition's, uniform, Gaussian and multimodal prior posteriors and by a uniform posterior than by the matching posterior.

In [18]:
unif = np.ones_like(M.GRID) / len(M.GRID)
gauss = np.exp(-((M.GRID - 0.5) / 0.2) ** 2); gauss /= gauss.sum()
multi = sum(w * np.exp(-((M.GRID - M.wallmorphx(sv)) / 0.08) ** 2) for w, sv in zip((1, 1, 10, 1, 1), M.MORPHS)); multi /= multi.sum()
for lik in M.LIKELIHOODS:
  nulls = {"uniform prior": M.posterior(unif, lik), "Gaussian prior": M.posterior(gauss, lik), "multimodal prior": M.posterior(multi, lik),
           "uniform posterior": np.full((len(M.GRID), len(M.GRID)), 1 / len(M.GRID))}
  print(f"##### likelihood {lik}" + (" (main)" if lik == "methods var 8.23" else " (variant)"))
  for g, other in (("rare", "frequent"), ("frequent", "rare")):
    ss = [s for s in pop if s["group"] == g]
    own = np.array([M.mean_dkl(s["q"], POST[(lik, g)]) for s in ss])
    print(f"=== {g} sessions ({len(ss)}); mean D_KL to own posterior {own.mean():.3f}")
    allok = True
    for name, P in {f"{other} posterior": POST[(lik, other)], **nulls}.items():
        d = np.array([M.mean_dkl(s["q"], P) for s in ss])
        w = stats.wilcoxon(d - own)
        ok = w.pvalue < 0.05 and np.median(d - own) > 0
        allok &= ok
        print(f"  {name:20s}: mean D_KL {d.mean():.3f}, median null minus own {np.median(d - own):.3f}, "
              f"sessions with own closer {int((d > own).sum())} of {len(ss)}, Wilcoxon p = {w.pvalue:.2g}, holds {ok}")
    print(f"  all five hold: {allok}")
##### likelihood methods var 8.23 (main)
=== rare sessions (26); mean D_KL to own posterior 1.010
  frequent posterior  : mean D_KL 1.617, median null minus own 0.516, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  uniform prior       : mean D_KL 1.646, median null minus own 0.603, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  Gaussian prior      : mean D_KL 2.892, median null minus own 1.823, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  multimodal prior    : mean D_KL 2.342, median null minus own 1.198, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  uniform posterior   : mean D_KL 7.524, median null minus own 6.719, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  all five hold: True
=== frequent sessions (21); mean D_KL to own posterior 1.037
  rare posterior      : mean D_KL 1.218, median null minus own 0.191, sessions with own closer 17 of 21, Wilcoxon p = 0.00051, holds True
  uniform prior       : mean D_KL 1.031, median null minus own -0.018, sessions with own closer 5 of 21, Wilcoxon p = 0.12, holds False
  Gaussian prior      : mean D_KL 1.681, median null minus own 0.642, sessions with own closer 21 of 21, Wilcoxon p = 9.5e-07, holds True
  multimodal prior    : mean D_KL 1.454, median null minus own 0.462, sessions with own closer 20 of 21, Wilcoxon p = 1.3e-05, holds True
  uniform posterior   : mean D_KL 6.353, median null minus own 4.947, sessions with own closer 20 of 21, Wilcoxon p = 1.9e-06, holds True
  all five hold: False
##### likelihood code 0.3 units (variant)
=== rare sessions (26); mean D_KL to own posterior 0.484
  frequent posterior  : mean D_KL 1.200, median null minus own 0.667, sessions with own closer 23 of 26, Wilcoxon p = 9.1e-06, holds True
  uniform prior       : mean D_KL 1.274, median null minus own 0.767, sessions with own closer 23 of 26, Wilcoxon p = 4.1e-06, holds True
  Gaussian prior      : mean D_KL 3.798, median null minus own 3.140, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  multimodal prior    : mean D_KL 2.932, median null minus own 2.086, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  uniform posterior   : mean D_KL 7.524, median null minus own 7.204, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  all five hold: True
=== frequent sessions (21); mean D_KL to own posterior 0.608
  rare posterior      : mean D_KL 1.365, median null minus own 0.875, sessions with own closer 21 of 21, Wilcoxon p = 9.5e-07, holds True
  uniform prior       : mean D_KL 0.597, median null minus own -0.079, sessions with own closer 6 of 21, Wilcoxon p = 0.18, holds False
  Gaussian prior      : mean D_KL 2.015, median null minus own 1.268, sessions with own closer 21 of 21, Wilcoxon p = 9.5e-07, holds True
  multimodal prior    : mean D_KL 1.540, median null minus own 1.028, sessions with own closer 20 of 21, Wilcoxon p = 4.8e-06, holds True
  uniform posterior   : mean D_KL 6.353, median null minus own 5.679, sessions with own closer 21 of 21, Wilcoxon p = 9.5e-07, holds True
  all five hold: False
##### likelihood code 0.4 units (variant)
=== rare sessions (26); mean D_KL to own posterior 0.775
  frequent posterior  : mean D_KL 1.472, median null minus own 0.676, sessions with own closer 19 of 26, Wilcoxon p = 0.00022, holds True
  uniform prior       : mean D_KL 1.541, median null minus own 0.791, sessions with own closer 21 of 26, Wilcoxon p = 2.3e-05, holds True
  Gaussian prior      : mean D_KL 4.226, median null minus own 3.287, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  multimodal prior    : mean D_KL 3.808, median null minus own 2.712, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  uniform posterior   : mean D_KL 7.524, median null minus own 6.840, sessions with own closer 26 of 26, Wilcoxon p = 3e-08, holds True
  all five hold: True
=== frequent sessions (21); mean D_KL to own posterior 0.797
  rare posterior      : mean D_KL 1.656, median null minus own 1.022, sessions with own closer 21 of 21, Wilcoxon p = 9.5e-07, holds True
  uniform prior       : mean D_KL 0.785, median null minus own -0.115, sessions with own closer 7 of 21, Wilcoxon p = 0.29, holds False
  Gaussian prior      : mean D_KL 2.284, median null minus own 1.297, sessions with own closer 21 of 21, Wilcoxon p = 9.5e-07, holds True
  multimodal prior    : mean D_KL 2.075, median null minus own 1.411, sessions with own closer 20 of 21, Wilcoxon p = 1.9e-06, holds True
  uniform posterior   : mean D_KL 6.353, median null minus own 5.475, sessions with own closer 21 of 21, Wilcoxon p = 9.5e-07, holds True
  all five hold: False

Result: edf9k reproduced; edf9l not reproduced. With the deposit's priors and the Methods likelihood, for the 26 rare morph sessions every null (frequent posterior, uniform, Gaussian and multimodal priors, uniform posterior) fits worse than the rare posterior in all 26 sessions (Wilcoxon p = 3e-08 for each). For the 21 frequent morph sessions four nulls fit worse than the frequent posterior: the rare posterior (17 of 21 sessions, p = 0.00051), the Gaussian prior (p = 9.5e-07), the multimodal prior (p = 1.3e-05) and the uniform posterior (p = 1.9e-06). The uniform prior does not (the frequent posterior is closer in 5 of 21 sessions, p = 0.12), and the criterion asks all five and names no partial outcome. The code's likelihood widths, variants, give the same outcomes: every rare test holds (p at most 0.00022), and for the frequent sessions the uniform prior again fails (p = 0.18 and 0.29; frequent posterior closer in 6 and 7 of 21) while the other four hold.

edf10-decision-mice-like-frequent¶

Frequent morph mice trained to report whether S was above or below 0.5 by where they licked (FD1 to FD4) remapped like frequent morph mice without the task.

In [19]:
fdm = ["FD1", "FD2", "FD3", "FD4"]
fds = [s for s in sfs if s["group"] == "decision"]
print("decision sessions with an SF (S-tilde 0 and 1 trials present):", sum("q" in s for s in fds), "of", len(fds),
      "; without:", [(s["mouse"], s["day"]) for s in fds if "q" not in s])
for reading, sel in (("a: every imaged session", lambda s: True), ("b: sessions 8 to N", lambda s: s["day"] >= 8),
                     ("variant (2020 code, first_ind=2): sessions 5 and later", lambda s: s["day"] >= 5)):
    ss = [s for s in fds if "q" in s and sel(s)]
    q, n = group_q(fdm, "a", ss)
    pooled = {lik: round(M.delta_dkl(q, POST[(lik, "rare")], POST[(lik, "frequent")]), 3) for lik in M.LIKELIHOODS}
    recs = {}
    for m in fdm:
        mm = [s for s in ss if s["mouse"] == m]
        if mm:
            recs[m] = (round(prior_dkl(np.sum([s["qu"] for s in mm], axis=0))[0], 3),
                       round(prior_dkl(np.sum([s["qu"] for s in mm], axis=0), code=True)[0], 3))
    per_sess = [round(s["dkl"]["methods var 8.23"], 2) for s in ss]
    print(f"{reading}: {n} mice, {len(ss)} sessions; pooled Q Delta D_KL {pooled}; reconstructed prior Delta D_KL per mouse (criterion, code's computation) {recs}")
    print(f"   per-session Delta D_KL (main): {per_sess}; positive in {sum(v > 0 for v in per_sess)} of {len(per_sess)}")
decision sessions with an SF (S-tilde 0 and 1 trials present): 35 of 37 ; without: [('FD1', 1), ('FD1', 3)]
a: every imaged session: 4 mice, 35 sessions; pooled Q Delta D_KL {'methods var 8.23': 0.042, 'code 0.3 units': 0.569, 'code 0.4 units': 0.661}; reconstructed prior Delta D_KL per mouse (criterion, code's computation) {'FD1': (1.082, 0.578), 'FD2': (0.933, 0.465), 'FD3': (0.942, 0.433), 'FD4': (1.019, 0.503)}
   per-session Delta D_KL (main): [-0.74, 0.3, 0.24, 0.29, 0.67, 0.29, 0.27, 0.33, 0.2, 0.23, -0.34, 0.06, 0.25, 0.07, 0.16, -0.76, 0.28, -0.08, 0.29, 0.04, -0.08, 0.24, -0.25, -0.81, 0.03, 0.26, 0.01, -0.48, -0.75, -0.07, 0.03, 0.04, 0.6, 0.38, 0.33]; positive in 25 of 35
b: sessions 8 to N: 3 mice, 21 sessions; pooled Q Delta D_KL {'methods var 8.23': 0.125, 'code 0.3 units': 0.729, 'code 0.4 units': 0.82}; reconstructed prior Delta D_KL per mouse (criterion, code's computation) {'FD1': (1.128, 0.627), 'FD2': (0.97, 0.46), 'FD4': (1.018, 0.503)}
   per-session Delta D_KL (main): [0.24, 0.29, 0.67, 0.29, 0.27, 0.33, 0.2, 0.23, 0.16, -0.76, 0.28, -0.08, 0.29, 0.04, -0.75, -0.07, 0.03, 0.04, 0.6, 0.38, 0.33]; positive in 17 of 21
variant (2020 code, first_ind=2): sessions 5 and later: 4 mice, 29 sessions; pooled Q Delta D_KL {'methods var 8.23': 0.005, 'code 0.3 units': 0.492, 'code 0.4 units': 0.558}; reconstructed prior Delta D_KL per mouse (criterion, code's computation) {'FD1': (1.082, 0.578), 'FD2': (0.974, 0.471), 'FD3': (0.727, 0.154), 'FD4': (1.008, 0.492)}
   per-session Delta D_KL (main): [-0.74, 0.3, 0.24, 0.29, 0.67, 0.29, 0.27, 0.33, 0.2, 0.23, 0.25, 0.07, 0.16, -0.76, 0.28, -0.08, 0.29, 0.04, -0.25, -0.81, 0.01, -0.48, -0.75, -0.07, 0.03, 0.04, 0.6, 0.38, 0.33]; positive in 21 of 29

Result: reproduced. With the deposit's priors both readings hold. (a) The Q estimate pooled over the decision mice has Delta D_KL 0.042 over every imaged session and 0.125 over sessions 8 to N, so it is closer to the frequent posterior (with the earlier run's priors these were -0.042 and -0.006); the code's likelihood widths, variants, give 0.569 to 0.820. (b) Each decision mouse's reconstructed prior is closer to the frequent morph prior (0.933 to 1.082 over every imaged session, 0.970 to 1.128 over sessions 8 to N). Reading (b) carries little evidence with the criterion's formula, which is positive even for an ideal rare observer (fig6d-prior-reconstruction); with the code's computation, under which the ideal rare observer gives +0.047 and the frequent one +0.502, the decision mice give 0.433 to 0.578 over every imaged session and 0.460 to 0.627 over sessions 8 to N, near the frequent observer. The 2020 code's sessions (5 and later), a variant, give a pooled value of 0.005 and reconstructions of 0.727 to 1.082. The per-session values are positive in 25 of 35 sessions. FD1's sessions 1 and 3 have no S-tilde = 0 or 1 trials and give no SF, and FD3 has no session after 7.

fig7-model-reproduces-remapping and fig7g-model-prior-reconstruction¶

A Hebbian network with radial basis inputs and k-winners-take-all competition, trained on stimuli drawn from the rare or frequent morph prior, gives Q estimates that match the matching posterior.

Priors reconstructed from the model's Q estimates are closer to the prior of the matching condition, though less closely matched than for the neural data.

Answer of 2026-10-22: the model runs in the code's unit (1 unit = 27.42 f_h), with input width sigma = 0.15 units (4.11 f_h, so a denominator of 0.0225 units^2), input centres from -0.1 to 1.1 units, stimulus, output and weight noise as in the code, in training and testing alike, and testing on the f_h of 1,000 evenly spaced S from -0.3 to 1.3. The earlier run's readings (no weight noise, no test noise, centres over the whole grid, the width read in f_h) are dropped. The priors are those of M7 from the deposit. fig7-model-reproduces-remapping is data: elsewhere, as it needs only the priors; fig7g-model-prior-reconstruction is data: with_inputs.

In [20]:
THETA_IN = np.linspace(-0.1, 1.1, 100)          # input centres, units (code THETA)
S_TEST = np.linspace(-0.3, 1.3, 1000)            # test morph values (code)
U_TEST = M.wallmorphx(S_TEST)                     # their stimulus values, units
KW = dict(N=100, K=20, c_y=0.01, eta=0.1, tau=0.001, w_max=5.0, sigma=0.15, stim_noise=0.1, act_noise=0.01, dw_noise=0.05)


def kwta_respond(u, W, rng, p=KW):
    """Inputs and outputs for stimuli u (units): Gaussian tuning exp(-(mu - x)^2 / sigma^2) of the
    stimulus plus noise; z = W x plus 0.01 N(0,1); the K largest z give c_y z; every other output
    0.01 times the (K+1)-th largest z times N(0,1); all rectified at 0."""
    u = np.atleast_1d(u)
    s = u + p["stim_noise"] * rng.standard_normal(u.shape)
    x = np.exp(-((THETA_IN[None, :] - s[:, None]) ** 2) / p["sigma"] ** 2)
    z = x @ W.T + p["act_noise"] * rng.standard_normal((len(u), p["N"]))
    order = np.argsort(-z, axis=1)
    zk1 = np.take_along_axis(z, order[:, p["K"]:p["K"] + 1], axis=1)
    y = p["act_noise"] * zk1 * rng.standard_normal(z.shape)
    win = np.zeros_like(z, dtype=bool)
    np.put_along_axis(win, order[:, :p["K"]], True, axis=1)
    y[win] = p["c_y"] * z[win]
    return x, np.maximum(y, 0)


def hebbian_model(prior_g, rng, p=KW):
    """Methods, Hebbian learning model, with the code's scale and noise (criterion of
    fig7-model-reproduces-remapping). Returns the unnormalised Q of the test stimuli, the number of
    test stimuli without an SF, and the mean and largest weight after training."""
    W = rng.uniform(0, 0.1, (p["N"], len(THETA_IN)))       # outputs x inputs
    for u in rng.choice(M.GRID, size=1000, p=prior_g):
        x, y = kwta_respond(u, W, rng, p)
        dW = p["eta"] * y.T @ x + p["dw_noise"] * rng.standard_normal(W.shape) - p["tau"]
        W = np.clip(W + dW, 0, p["w_max"])
    _, Y = kwta_respond(U_TEST, W, rng, p)
    c0, c1 = Y[U_TEST < 0.05].mean(0), Y[U_TEST > 0.9].mean(0)
    n = np.linalg.norm(Y, axis=1)
    with np.errstate(invalid="ignore", divide="ignore"):
        g0 = Y @ c0 / (n * np.linalg.norm(c0)); g1 = Y @ c1 / (n * np.linalg.norm(c1))
        sf = g1 / (g0 + g1)
    m0 = np.nanmedian(sf[(S_TEST >= -0.1) & (S_TEST <= 0.1)]); m1 = np.nanmedian(sf[(S_TEST >= 0.9) & (S_TEST <= 1.1)])
    t = np.clip((sf - m0) / (m1 - m0) * (1.073 - 0.094) + 0.094, M.GRID[0], M.GRID[-1])
    return M.q_unnorm(t, U_TEST.copy()), int(np.isnan(sf).sum()), float(W.mean()), float(W.max())


print("test stimuli span", round(float(U_TEST.min()), 3), "to", round(float(U_TEST.max()), 3), "units (",
      round(float(M.unit_to_fh(U_TEST.min())), 2), "to", round(float(M.unit_to_fh(U_TEST.max())), 2), "f_h ); input centres",
      round(float(M.unit_to_fh(THETA_IN[0])), 2), "to", round(float(M.unit_to_fh(THETA_IN[-1])), 2), "f_h; width",
      round(KW["sigma"] * M.UNIT_FH, 2), "f_h")
t0 = time.time()
model = {}
for pname, pri in (("deposit priors (main)", prior), ("earlier run: priors from dandiset trials", prior_img)):
    for gi, g in enumerate(("rare", "frequent")):
        rng = np.random.default_rng(7100 + 10 * (pname != "deposit priors (main)") + gi)
        model[(pname, g)] = [hebbian_model(pri[g], rng) for _ in range(50)]
rows = []
for (pname, g), runs in model.items():
    for lik in M.LIKELIHOODS:
        d = [M.delta_dkl(M.normalise_rows(r[0]), POST[(lik, "rare")], POST[(lik, "frequent")]) for r in runs]
        rows.append({"priors": pname, "likelihood": lik, "trained on": g, "median Delta D_KL": round(float(np.median(d)), 3),
                     "IQR": (round(float(np.percentile(d, 25)), 3), round(float(np.percentile(d, 75)), 3)),
                     "models below 0": int(np.sum(np.array(d) < 0)),
                     "models with NaN SF points": sum(r[1] > 0 for r in runs),
                     "mean weight": round(float(np.mean([r[2] for r in runs])), 3),
                     "largest weight": round(float(np.max([r[3] for r in runs])), 3)})
fig7 = pd.DataFrame(rows)
print(fig7.to_string(index=False))
for pname in fig7.priors.unique():
    for lik in M.LIKELIHOODS:
        x = fig7[(fig7.priors == pname) & (fig7.likelihood == lik)].set_index("trained on")["median Delta D_KL"]
        print(f"{pname}, {lik}: rare median below 0 {x['rare'] < 0}, frequent median above 0 {x['frequent'] > 0}")
print(f"model time {time.time() - t0:.0f} s")
test stimuli span -0.301 to 1.1 units ( 0.04 to 38.45 f_h ); input centres 5.55 to 38.45 f_h; width 4.11 f_h
                                  priors       likelihood trained on  median Delta D_KL              IQR  models below 0  models with NaN SF points  mean weight  largest weight
                   deposit priors (main) methods var 8.23       rare             -0.564 (-0.614, -0.529)              50                          0        2.246             5.0
                   deposit priors (main)   code 0.3 units       rare             -0.697 (-0.813, -0.623)              50                          0        2.246             5.0
                   deposit priors (main)   code 0.4 units       rare             -0.792 (-0.929, -0.731)              50                          0        2.246             5.0
                   deposit priors (main) methods var 8.23   frequent              0.093     (0.031, 0.2)              10                          0        2.772             5.0
                   deposit priors (main)   code 0.3 units   frequent              0.774   (0.586, 0.936)               1                          0        2.772             5.0
                   deposit priors (main)   code 0.4 units   frequent              1.003   (0.784, 1.175)               1                          0        2.772             5.0
earlier run: priors from dandiset trials methods var 8.23       rare             -0.529 (-0.587, -0.465)              50                          0        2.280             5.0
earlier run: priors from dandiset trials   code 0.3 units       rare             -0.564 (-0.682, -0.451)              50                          0        2.280             5.0
earlier run: priors from dandiset trials   code 0.4 units       rare             -0.612 (-0.754, -0.515)              50                          0        2.280             5.0
earlier run: priors from dandiset trials methods var 8.23   frequent              0.101    (0.009, 0.17)              12                          0        2.769             5.0
earlier run: priors from dandiset trials   code 0.3 units   frequent              0.713   (0.538, 0.953)               0                          0        2.769             5.0
earlier run: priors from dandiset trials   code 0.4 units   frequent              0.917   (0.708, 1.178)               0                          0        2.769             5.0
deposit priors (main), methods var 8.23: rare median below 0 True, frequent median above 0 True
deposit priors (main), code 0.3 units: rare median below 0 True, frequent median above 0 True
deposit priors (main), code 0.4 units: rare median below 0 True, frequent median above 0 True
earlier run: priors from dandiset trials, methods var 8.23: rare median below 0 True, frequent median above 0 True
earlier run: priors from dandiset trials, code 0.3 units: rare median below 0 True, frequent median above 0 True
earlier run: priors from dandiset trials, code 0.4 units: rare median below 0 True, frequent median above 0 True
model time 48 s
In [21]:
neural = {g: abs(np.mean([fig6d_vals[m] for m in mice])) for g, mice in (("rare", RARE), ("frequent", FREQ))}
print("neural across-mouse mean magnitude (fig6d, main):", {g: round(v, 3) for g, v in neural.items()})
for (pname, g), runs in model.items():
    pri = prior if pname.startswith("deposit") else prior_img
    R = np.mean([M.reconstruct_prior(r[0]) for r in runs], axis=0)
    R = R / R.sum()
    v = M.dkl(pri["rare"], R) - M.dkl(pri["frequent"], R)
    v_nats = v * np.log(2)
    ok_sign = v < 0 if g == "rare" else v > 0
    print(f"{pname}, trained on {g}: averaged reconstructed prior Delta D_KL {v:.3f} bits ({v_nats:.3f} nats; "
          f"expected sign {ok_sign}; magnitude below neural {abs(v) < neural[g]})")
    Rc = np.mean([M.reconstruct_prior(r[0], code=True) for r in runs], axis=0)
    Rc = Rc / Rc.sum()
    vc = M.dkl(pri["rare"], Rc) - M.dkl(pri["frequent"], Rc)
    print(f"   variant, the code's computation of R: {vc:.3f} bits; neural mean under the same computation "
          f"{np.mean([fig6d_code_vals[m] for m in (RARE if g == 'rare' else FREQ)]):.3f}")
neural across-mouse mean magnitude (fig6d, main): {'rare': np.float64(0.223), 'frequent': np.float64(1.125)}
deposit priors (main), trained on rare: averaged reconstructed prior Delta D_KL -0.098 bits (-0.068 nats; expected sign True; magnitude below neural True)
   variant, the code's computation of R: -0.349 bits; neural mean under the same computation -0.288
deposit priors (main), trained on frequent: averaged reconstructed prior Delta D_KL 0.626 bits (0.434 nats; expected sign True; magnitude below neural True)
   variant, the code's computation of R: 0.378 bits; neural mean under the same computation 0.638
earlier run: priors from dandiset trials, trained on rare: averaged reconstructed prior Delta D_KL -0.188 bits (-0.130 nats; expected sign True; magnitude below neural True)
   variant, the code's computation of R: -0.380 bits; neural mean under the same computation -0.288
earlier run: priors from dandiset trials, trained on frequent: averaged reconstructed prior Delta D_KL 0.264 bits (0.183 nats; expected sign True; magnitude below neural True)
   variant, the code's computation of R: 0.073 bits; neural mean under the same computation 0.638

Result: fig7 reproduced; fig7g reproduced. With the code's scale and noise that the answer fixed, the network learns: the weights end with a mean of 2.25 (rare-trained) and 2.77 (frequent-trained) and reach the cap of 5. The median Delta D_KL of the 50 rare-trained models is -0.564 (interquartile range -0.614 to -0.529; all 50 below 0) and that of the 50 frequent-trained models 0.093 (0.031 to 0.200; 40 of 50 above 0), so the criterion holds; the code's likelihood widths, variants, give the same signs (rare -0.697 and -0.792, frequent 0.774 and 1.003), and so do the earlier run's priors from the dandiset's trials (-0.529 and 0.101). The test stimuli, the f_h of S from -0.3 to 1.3 as the code computes it, span 0.04 to 38.45 f_h, not 5.5 to 38.5 as the criterion says, since f_h falls again for S below -0.1 (a question asks a reader about it).

For fig7g, the averaged reconstructed prior has Delta D_KL -0.098 bits for the rare-trained and 0.626 bits for the frequent-trained models (-0.068 and 0.434 nats), both of the expected sign, and both smaller in magnitude than the neural across-mouse means of fig6d-prior-reconstruction (0.223 and 1.125), so the criterion's test passes as written. But the rare neural mean has the wrong sign: the neural reconstructions of the rare morph mice do not match the rare prior at all, so "less closely matched than for the neural data" is not shown for the rare condition. With the code's computation of R, a variant, the rare-trained models give -0.349 against a neural rare mean of -0.288, a larger magnitude, and the frequent-trained models 0.378 against 0.638. The signs hold under both computations and the comparison with the neural data holds only for the frequent condition, so the outcome was given as partially reproduced after the first verification round.

The second verification round found that label inconsistent: the criterion names no partial outcome, and the attempt applies that rule to four other claims (session-and-trial-counts, fig2eh, edf7 and edf9l). Its test as written passes on the values above: both signs as expected, and 0.098 below 0.223 and 0.626 below 1.125. Reproduced was proposed for a third round, and the third round agreed, so the outcome is reproduced. The rare half of the comparison carries little evidence: the rare neural yardstick has the wrong sign, and the Methods formula gives an ideal rare observer +0.547 on this design (ideal-observer check above).

edf3-simulated-posterior-population¶

A simulated population that stochastically encodes samples from the rare or frequent morph posterior reproduces the recorded remapping patterns.

Answer of 2026-10-22: the neurons' centres are evenly spaced over the M6 grid (0.06 to 43.9 f_h), as the earlier run already had them, and the simulated difference is that of the mean over the 1,000 simulations, with each simulation's trial-by-trial matrix z-scored over its off-diagonal entries before averaging; the mean z-scored matrices are then averaged within the S-tilde blocks. The earlier run z-scored each session's 5 x 5 block matrix instead; that is kept as a variant. The posteriors are those of the deposit's priors.

In [22]:
FH_GRID = M.unit_to_fh(M.GRID)
SIM_POST = {g: POST[("methods var 8.23", g)] for g in ("rare", "frequent")}
SIM_SESSIONS = []
for s_ in pop:
    rows_ = np.abs(M.GRID[None, :] - s_["trials"].unit.to_numpy()[:, None]).argmin(1)
    cdf_ = np.cumsum(SIM_POST[s_["group"]][rows_], axis=1)
    cdf_ /= cdf_[:, -1:]
    flat_ = (cdf_ + np.arange(len(rows_))[:, None]).ravel()        # rows stacked into one increasing array
    SIM_SESSIONS.append((s_["mouse"], s_["n_cells"], flat_, s_["trials"].morph.to_numpy()))


def _one_thread():
    from threadpoolctl import threadpool_limits
    threadpool_limits(1)


def simulate(args):
    """Sum over simulations of the binned similarity per mouse, for one reading: of the trial
    matrix z-scored over its off-diagonal entries (main), and the earlier run's z-scored 5 x 5
    block matrix (variant).

    Reading a: one sample per trial and the session's cell count; b: 45 samples (one per position
    bin) and 100 neurons. Each trial's samples come from the group posterior at the trial's f_h by
    inverse transform sampling on the grid; neuron activity is gamma(kappa, 1)."""
    reading, n_sims, seed = args
    rng = np.random.default_rng(seed)
    acc, acc_v, cnt = {}, {}, {}
    for _ in range(n_sims):
        per_mouse = {}
        for mouse, ncells, flat, morph in SIM_SESSIONS:
            T = len(morph)
            n_samp, n_neur = (1, ncells) if reading == "a" else (45, 100)
            mu = np.linspace(FH_GRID[0], FH_GRID[-1], n_neur)
            u = rng.random((T, n_samp)) + np.arange(T)[:, None]
            k = np.searchsorted(flat, u) - np.arange(T)[:, None] * len(M.GRID)
            s_fh = FH_GRID[np.clip(k, 0, len(M.GRID) - 1)]
            kappa = 2 * np.exp(-((s_fh[:, :, None] - mu[None, None, :]) ** 2) / 4.11 ** 2)
            y = rng.gamma(np.maximum(kappa, 1e-300), 1.0).reshape(T, -1)
            yn = M.unit_rows(y)
            S = yn @ yn.T
            off = ~np.eye(T, dtype=bool)
            Z = (S - S[off].mean()) / S[off].std()           # trial matrix z-scored over its off-diagonal entries
            per_mouse.setdefault(mouse, []).append((M.binned_similarity(Z, morph),
                                                    M.zscore_matrix(M.binned_similarity(S, morph))))
        for mouse, Bs in per_mouse.items():
            acc[mouse] = acc.get(mouse, 0) + np.mean([b[0] for b in Bs], axis=0)
            acc_v[mouse] = acc_v.get(mouse, 0) + np.mean([b[1] for b in Bs], axis=0)
            cnt[mouse] = cnt.get(mouse, 0) + 1
    return acc, acc_v, cnt


t0 = time.time()
sim = {}
for reading in "ab":
    jobs = [(reading, 250, 9000 + 10 * (reading == "b") + k) for k in range(4)]
    with ProcessPoolExecutor(4, initializer=_one_thread) as ex:
        parts = list(ex.map(simulate, jobs))
    n_done = sum(p[2]["R1"] for p in parts)
    for k, name in ((0, ""), (1, " variant")):
        per = {m: sum(p[k][m] for p in parts) / sum(p[2][m] for p in parts) for m in RARE + FREQ}
        diff = np.mean([per[m] for m in RARE], axis=0) - np.mean([per[m] for m in FREQ], axis=0)
        sim[reading + name] = diff
    print(f"reading {reading}: {n_done} simulations; simulated rare minus frequent, trial matrices z-scored (main):")
    print(pd.DataFrame(sim[reading], index=M.MORPHS, columns=M.MORPHS).round(3).to_string())
    print(f"  variant, block matrices z-scored (earlier run): S-tilde = 0.25 row {sim[reading + ' variant'][1].round(3)}")
obs, perms, sig = fig3f["main: smoothed deconvolved, z-scored per session"]
sig_entries = [j for j in range(5) if sig[1, j]]
print("recorded significant entries of the S-tilde = 0.25 row (fig3f):", [(M.MORPHS[j], round(obs[1, j], 3)) for j in sig_entries])
for reading in ("a", "b", "a variant", "b variant"):
    same = [bool(np.sign(sim[reading][1, j]) == np.sign(obs[1, j])) for j in sig_entries]
    print(f"reading {reading}: values {[round(float(sim[reading][1, j]), 3) for j in sig_entries]}, same sign {same}")
print(f"simulation time {time.time() - t0:.0f} s")
reading a: 1000 simulations; simulated rare minus frequent, trial matrices z-scored (main):
       0.00   0.25   0.50   0.75   1.00
0.00 -0.001  0.254 -0.024 -0.012 -0.012
0.25  0.254 -0.442 -0.410 -0.091 -0.036
0.50 -0.024 -0.410 -0.187  0.225  0.375
0.75 -0.012 -0.091  0.225  0.073  0.066
1.00 -0.012 -0.036  0.375  0.066 -0.036
  variant, block matrices z-scored (earlier run): S-tilde = 0.25 row [ 0.324 -0.576 -0.485 -0.076 -0.006]
reading b: 1000 simulations; simulated rare minus frequent, trial matrices z-scored (main):
       0.00   0.25   0.50   0.75   1.00
0.00 -0.087  0.326  0.049  0.063  0.064
0.25  0.326 -0.571 -0.444 -0.039  0.030
0.50  0.049 -0.444 -0.293  0.206  0.399
0.75  0.063 -0.039  0.206 -0.032 -0.042
1.00  0.064  0.030  0.399 -0.042 -0.172
  variant, block matrices z-scored (earlier run): S-tilde = 0.25 row [ 0.328 -0.579 -0.486 -0.074 -0.004]
recorded significant entries of the S-tilde = 0.25 row (fig3f): [(np.float64(0.5), np.float64(-0.409)), (np.float64(1.0), np.float64(-0.367))]
reading a: values [-0.41, -0.036], same sign [True, True]
reading b: values [-0.444, 0.03], same sign [True, False]
reading a variant: values [-0.485, -0.006], same sign [True, True]
reading b variant: values [-0.486, -0.004], same sign [True, True]
simulation time 496 s

Result: not reproduced. The recorded S-tilde = 0.25 row has two significant entries (fig3f-zscored-difference-at-025), with S-tilde 0.5 (-0.409) and 1.0 (-0.367). With the deposit's posteriors and each simulation's trial matrix z-scored before averaging, as the answer fixed, the simulated rare minus frequent difference over 1,000 simulations has the same sign at 0.5 under both readings (-0.410 with one sample per trial and the session's cell count, -0.444 with 45 samples and 100 neurons). At 1.0 it is near zero: -0.036 under reading (a), the recorded sign, and +0.030 under reading (b). The criterion asks for both readings, so it is not met. The earlier run's z-scoring of the block matrices, kept as a variant, gives -0.006 and -0.004 at 1.0 with the deposit's posteriors (the earlier run had +0.009 under both readings with the dandiset's priors).

Summary¶

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

Claim Notebook Outcome
cells-per-session 1 reproduced
session-and-trial-counts 1 not reproduced
vr-deposit-link (link) 2 reproduced
training-intermediate-fraction 2 reproduced (data elsewhere)
place-cell-fractions 1 not reproduced
edf4a-fewer-place-cells-frequent 1 reproduced
edf4a-overlap-above-chance 1 partially reproduced
edf4bc-overlap-cells-at-ends-and-reward 1 not reproduced
fig2eh-place-cell-similarity-differs 1 not reproduced
edf6-nmf-confirms-remapping 1 not reproduced
edf5-umap-rare-frequent-separable 1 reproduced
edf1-licking-before-reward 1 reproduced
fig3ab-block-versus-gradual-similarity 2 not reproduced
edf7-checkerboard-sessions 2 not reproduced
fig3f-zscored-difference-at-025 2 reproduced
fig4-sf-stable-along-track 2 reproduced
fig6a-dkl-sign 2 partially reproduced
fig6bc-pooled-dkl 2 partially reproduced
fig6d-prior-reconstruction 2 not reproduced
map-estimate-values 2 reproduced
edf9-early-sessions 2 reproduced
edf9k-null-models-rare 2 reproduced
edf9l-null-models-frequent 2 not reproduced
edf10-decision-mice-like-frequent 2 reproduced
fig7-model-reproduces-remapping 2 reproduced (data elsewhere)
fig7g-model-prior-reconstruction 2 reproduced
edf3-simulated-posterior-population 2 not reproduced
edf2-fh-best-predictor - blocked: data missing
supp-earlier-morph-studies - blocked: other

How the analysis differs from the paper's. The priors of every posterior-based claim come from the authors' figshare deposit of all VR sessions (answer of 2026-10-22), matched to the dandiset's files through the 2026 code's mouse aliases and the trial sequences (vr-deposit-link); the fig6a, fig6bc, fig6d, map-estimate-values, edf9, edf9k, edf9l, edf10, fig7g and edf3 results are counted as with_inputs, and training-intermediate-fraction and fig7 as elsewhere. The dandiset holds 26 rare morph sessions 8 to N, two more than the paper's 24. Where the claims file leaves a reading open, every reading it names is run (speed exclusion, denominators, likelihood widths, shuffle counts, decision-mouse sessions, peak readings of edf4bc). Choices not fixed by the claims file are standard ones, named where they are made: smoothing of empty position bins by normalised convolution, the 99.9th percentile of the shuffles for the UMAP filter, an NMF iteration limit of 2,000, and the operational test of "rises" (edf1). The Hebbian model follows the parameters and noise of the paper's code, as the answer fixed; the claims file's statement that its test stimuli lie between 5.5 and 38.5 f_h does not hold for S below -0.1 (fig7 conclusion).

After the first verification round. Where a criterion names no partial outcome, a claim that holds only in part is now not reproduced (session-and-trial-counts, fig2eh, edf7, edf9l). The prior reconstruction of fig6d, edf10 and fig7g follows the Methods formula as the claims file gives it; an ideal-observer check shows that this formula gives a positive Delta D_KL even for an observer that samples the rare posterior (+0.547 on average), so it cannot show the rare sign on this design. The paper's code computes R differently (Z at the grid point f), and with the 2020 code's settings it gives values within the paper's tolerances (fig6d conclusion); this is a variant, and a question asks a reader whether the claims should follow it. Other variants added: place cells with the 2020 code's 95th-percentile signal (99.91% of decisions unchanged), a plain implementation of the shuffle (identical counts), unsmoothed place-cell similarity matrices (fig2eh passes under them), the step share clipped at 1 and per-mouse medians (edf6, fig3ab), leave-one-mouse-out classification for edf5, all three likelihoods for edf9k and edf9l, the 2020 code's decision-mouse sessions (2,662 trials, within tolerance), and the mapping of file days onto the deposit's dates (vr-deposit-link).

After the second verification round. No outcome changes. For fig7g the verifier found the partial outcome inconsistent with the rule above, since its criterion names no partial outcome and its test passes as written; the verified outcome stayed, and reproduced was proposed for a third round (fig7 and fig7g conclusion). The edf5 counts vary between runs, as the UMAP layout does, and both readings hold in each run seen (edf5 conclusion). Text that quoted an earlier run is corrected.

After the third verification round. The verifier agreed with the proposal, so fig7g is reproduced. Its rare half carries little evidence, since the rare neural yardstick has the wrong sign (fig7 and fig7g conclusion).

What was found about the dataset. The version pinned holds all 16 mice; the 2021 versions hold 10. Every file holds only the imaged trials; the non-imaged trials and the sessions without imaging (2, 4 and 6) are not in the dandiset, though the paper's priors and its training statistics need them. The authors' figshare deposit holds them, but neither the dandiset nor the paper names it; its sessions link to the dandiset's files exactly, through the mouse aliases of the 2026 code, which the dandiset does not record. The deposit also holds sessions with the imaging flag that have no file in the dandiset (26 for the 12 mice, 12 of them R6's). The files hold imaging sessions 5 and 7 (and R4's session 6), which the paper does not describe, and F6's session 5 has 4,103 cells, above the paper's range. FD3 has no session after 7, so the decision-mouse counts cannot match the paper's under the claims file's readings. For R1 to R4, R6 and F4 the deposit holds one more task-track date before session 8 than sessions 1 to 7 (two more for R6), so the file day is one or two lower than the ordinal of the session's date in the deposit. session_start_time is the date of conversion (2026), not of the recording. FD1's sessions 1 and 3 hold continuous morph values. The place cells stored in the JSON annotation (the authors' 2026 code) give fractions like this attempt's and far above the paper's. No recording is deposited twice, and the activity shares the clock of the position in every session.

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