Reproducing Mallory, Hardcastle et al. (2021) on dandiset 000053¶

Paper. Mallory CS, Hardcastle K, Campbell MG, Attinger A, Low IIC, Raymond JL, Giocomo LM (2021). Mouse entorhinal cortex encodes a diverse repertoire of self-motion signals. Nature Communications 12, 671. doi:10.1038/s41467-021-20936-8. The claims file (claims/mallory-2021.yaml) was written from the version of record (Europe PMC full text of PMC7844029) with its Methods, legends and Supplementary Information.

Dandiset. DANDI:000053, version 0.210819.0345 (doi:10.48324/dandi.000053/0.210819.0345). The paper cites no DANDI version (its data statement points to figshare). This is the only published version; the draft lists the same 359 assets, so the published version is pinned.

What the dandiset holds. 329 open field files (25 mice, 1200 units, tetrodes) with body position, body speed, azimuthal head direction and azimuthal head velocity, and no pitch or roll; 20 head-fixed Neuropixels files (9 mice, 5120 units) with VR position, speed, eye position and eye velocity, and 10 behaviour-only copies of head-fixed sessions. The paper's head-fixed data are 11 of the 20 files (link claim below); of the other 9, six hold gain and contrast trials and three only gain 1 and contrast 100% (their trial tables are printed after the link).

Outside input. The paper's own deposit, figshare Dataset 3 (doi:10.6084/m9.figshare.13426103.v1), read in place, names which dandiset files are the paper's 11 recordings. It brings in no measurement.

Claims Status
headfixed-session-link (added link claim) tested
fig4f, fig4j, fig4k, fig5a, fig5b, fig5 stability, fig5av, fig5bv, fig6 (four claims), fig7ab, fig7c, fig7e, supp7e tested here
every claim below again with folds assigned at random, open detail (1b) readings_folds_mallory_2021.ipynb
open detail (2b), clipping in place of dropping not run (time: about 45 min per reading)
supp4-eye-ln-conservative, supp5-eye-model-raw-tuning-agree tested here
supp9-eye-correlation-contributions tested here
supp3-eye-low-false-positives blocked: too large (six LN reruns, about 3.3 h)
freely moving claims (fig1b to fig3e and the head parts of supp3, supp4, supp5, supp9) data: elsewhere, on the paper's figshare Datasets 1 and 2: freely_moving_mallory_2021.ipynb
fig8c, fig8e blocked: no file marks a no-landmark track or block (trial tables printed below)
methods-hemispheres-similar blocked: hemisphere not recorded
supp12-no-false-eye-detection too large for this notebook: simulated_eye_mallory_2021.ipynb
In [1]:
import math
import os
import time
import resource
import warnings
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor

import numpy as np
import pandas as pd
from scipy import stats

import mec_ln as L

warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)
STARTED = time.time()
urls = L.asset_urls()
print(f"dandiset {L.DANDISET_ID} version {L.DANDISET_VERSION}: {len(urls)} assets")
dandiset 000053 version 0.210819.0345: 359 assets

Data check¶

In [2]:
# Every file's metadata and array shapes (no data read).
with ThreadPoolExecutor(32) as ex:
    summaries = dict(zip(urls, ex.map(L.file_summary, urls.values())))
rows = []
for path, s in summaries.items():
    rows.append({"path": path, "subject": s["subject_id"], "task": s["session_description"],
                 "arena": s["experiment_description"], "units": s["n_units"], "frames": s.get("n_frames"),
                 "ecephys": s["has_ecephys"], "variables": ",".join(sorted(k.split("/")[-1] for k in s["behavior"]))})
files = pd.DataFrame(rows)
print("Files by task and content:")
print(files.groupby(["task", "ecephys", "variables"]).agg(files=("path", "size"), subjects=("subject", "nunique"),
                                                          units=("units", "sum")).to_string())
units_seen = Counter()
for s in summaries.values():
    for k, (shape, unit) in s["behavior"].items():
        units_seen[(k, unit)] += 1
print("\nStated units of the behaviour series:", dict(units_seen))
names = sorted({k.split("/")[-1] for s in summaries.values() for k in s["behavior"]})
print("Behaviour series names over all files:", names)
print("Any series named for pitch, roll, an IMU or an accelerometer:",
      any(any(w in n.lower() for w in ("pitch", "roll", "imu_", "inertial", "accel")) for n in names))
Files by task and content:
                                                                                                    files  subjects  units
task                            ecephys variables                                                                         
free exploration.               False   azimuthal_head_velocity,body_speed,head_direction,position    329        25   1200
straight track virtual reality. True    body_speed,eye_position,eye_velocity,position                  20         9   5120
straight track.                 False   body_speed,eye velocity,eye_position,position                  10         8   2784

Stated units of the behaviour series: {('EyeTracking/eye_position', 'meters'): 30, ('Position/position', 'meters'): 359, ('body_speed', 'cm/s'): 359, ('eye_velocity', 'unknown'): 20, ('azimuthal_head_velocity', 'radians/s'): 329, ('head_direction', 'radians'): 329, ('eye velocity', 'unknown'): 10}
Behaviour series names over all files: ['azimuthal_head_velocity', 'body_speed', 'eye velocity', 'eye_position', 'eye_velocity', 'head_direction', 'position']
Any series named for pitch, roll, an IMU or an accelerometer: False

The open field files hold body position, body speed, head direction and azimuthal head velocity only (head direction in radians, azimuthal head velocity in radians/s, position in cm with a conversion to metres). The pitch and roll of Cohort 1 (IMU) are not in the dandiset; the paper deposited them on figshare (Dataset 1, doi:10.6084/m9.figshare.13425392.v1). Every freely moving claim of the claims file needs them, or depends on a claim that does, so they are tested on the figshare deposits in freely_moving_mallory_2021.ipynb (data: elsewhere). Below, the open field cohorts are identified only to describe the data.

In [3]:
of = files[files.task == "free exploration."].copy()
of["arena_cm"] = of.arena.str.extract(r"\[([0-9.]+)\]").astype(float)
by_subject = of.groupby("subject").agg(files=("path", "size"), units=("units", "sum"),
                                       arenas=("arena_cm", lambda a: sorted(set(a))))
by_subject["obj_files"] = of.groupby("subject").path.apply(lambda p: int(p.str.contains("_obj-").sum()))
print(by_subject.to_string())
print("\nOpen field: files", len(of), "subjects", of.subject.nunique(), "units", of.units.sum(),
      "(paper: 26 mice, 179 + 1021 = 1200 cells)")
small = by_subject[by_subject.arenas.apply(lambda a: set(a) <= {50.0, 70.0})]
print("Mice recorded only in 50 or 70 cm arenas:", list(small.index), "units", small.units.sum(),
      "(paper, Cohort 1: 6 mice, 179 cells; arenas 50 x 50, 70 x 70 or 70 x 35 cm)")
print("Arena sizes over all files (cm):", sorted(of.arena_cm.unique()), "(paper: 100, 50, 70, 70 x 35)")
              files  units                arenas  obj_files
subject                                                    
Azalea            2     26                [75.0]          0
Barbara          21     73                [91.4]          0
Camelia           2     78                [75.0]          0
Carnation         3      4                [50.0]          0
Case             11     40               [100.0]         10
Crocus            2     29                [75.0]          0
Daisy            14     52          [50.0, 70.0]          0
Dorian           33     90               [100.0]         33
Ella             23     49                [91.4]          0
Flip             13     36  [70.0, 91.44, 100.0]          0
Ford Prefect     29     87               [100.0]         29
Fuschia           4      7          [50.0, 70.0]          0
James            13     63               [100.0]         13
Japie            14     41               [100.0]         14
Jasmine           5     17                [50.0]          0
Lukas            14     28               [100.0]         14
Lupine            1     12                [75.0]          0
Magnolia          4     83                [75.0]          0
Orchid           13     69          [50.0, 70.0]          0
Pinky            14     40               [100.0]         14
Rascal           22     62         [70.0, 100.0]          0
Reeves           22     48               [100.0]          0
Ringo            11     26               [100.0]          0
Rose              6     30                [50.0]          0
Snoopy           33    110               [100.0]          0

Open field: files 329 subjects 25 units 1200 (paper: 26 mice, 179 + 1021 = 1200 cells)
Mice recorded only in 50 or 70 cm arenas: ['Carnation', 'Daisy', 'Fuschia', 'Jasmine', 'Orchid', 'Rose'] units 179 (paper, Cohort 1: 6 mice, 179 cells; arenas 50 x 50, 70 x 70 or 70 x 35 cm)
Arena sizes over all files (cm): [np.float64(50.0), np.float64(70.0), np.float64(75.0), np.float64(91.4), np.float64(91.44), np.float64(100.0)] (paper: 100, 50, 70, 70 x 35)

The 1200 units match the paper's 179 + 1021 cells; 25 subjects against the paper's 26 mice. The six mice recorded only in 50 and 70 cm arenas hold 179 units, the size of Cohort 1, so Cohort 1 is consistent with these mice; the files do not say so. Arenas of 75 and 91.4 cm are not among the sizes the Methods list. Nothing is analysed on these files.

In [4]:
hf = files[files.task != "free exploration."].copy()
hf["device"] = [summaries[p].get("device", "") for p in hf.path]
hf["locations"] = [",".join(summaries[p].get("locations", [])) for p in hf.path]
print(hf[["path", "subject", "task", "units", "frames", "ecephys", "locations"]].sort_values("path").to_string(index=False))
print("\nHead-fixed ecephys files:", int(hf.ecephys.sum()), "units", int(hf[hf.ecephys].units.sum()),
      "subjects", hf.subject.nunique(), "(paper: 11 recordings, 2861 units, 8 mice)")
# Recordings deposited more than once: same subject and frame count, or same subject and unit count.
dups = []
for (subj, fr), g in hf.groupby(["subject", "frames"]):
    if len(g) > 1:
        dups.append(("same frames", subj, fr, list(g.path.str.split("/").str[1])))
for (subj, nu), g in hf[hf.ecephys].groupby(["subject", "units"]):
    if len(g) > 1:
        dups.append(("same units", subj, nu, list(g.path.str.split("/").str[1])))
for d in dups:
    print(d)
                                                           path subject                            task  units  frames  ecephys locations
            sub-npI1/sub-npI1_ses-20190413_behavior+ecephys.nwb    npI1 straight track virtual reality.     77  127222     True   unknown
            sub-npI1/sub-npI1_ses-20190414_behavior+ecephys.nwb    npI1 straight track virtual reality.    156   50940     True   unknown
            sub-npI1/sub-npI1_ses-20190415_behavior+ecephys.nwb    npI1 straight track virtual reality.    173   44061     True   unknown
                    sub-npI1/sub-npI1_ses-20190415_behavior.nwb    npI1                 straight track.    173   44061    False          
            sub-npI1/sub-npI1_ses-20190416_behavior+ecephys.nwb    npI1 straight track virtual reality.    408   78990     True   unknown
                    sub-npI1/sub-npI1_ses-20190416_behavior.nwb    npI1                 straight track.    408   78990    False          
            sub-npI3/sub-npI3_ses-20190420_behavior+ecephys.nwb    npI3 straight track virtual reality.    286  451580     True   unknown
                    sub-npI3/sub-npI3_ses-20190420_behavior.nwb    npI3                 straight track.    286  451580    False          
            sub-npI3/sub-npI3_ses-20190421_behavior+ecephys.nwb    npI3 straight track virtual reality.    424  177707     True   unknown
                    sub-npI4/sub-npI4_ses-20190421_behavior.nwb    npI4                 straight track.    254   84626    False          
sub-npI4/sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb    npI4 straight track virtual reality.    254   84626     True   unknown
sub-npI4/sub-npI4_ses-20190421_obj-1yyd867_behavior+ecephys.nwb    npI4 straight track virtual reality.    254   68744     True   unknown
            sub-npI4/sub-npI4_ses-20190423_behavior+ecephys.nwb    npI4 straight track virtual reality.    537   74852     True   unknown
                    sub-npI4/sub-npI4_ses-20190423_behavior.nwb    npI4                 straight track.    537   74852    False          
            sub-npI5/sub-npI5_ses-20190414_behavior+ecephys.nwb    npI5 straight track virtual reality.    275   77591     True   unknown
            sub-npJ1/sub-npJ1_ses-20190521_behavior+ecephys.nwb    npJ1 straight track virtual reality.    207   67664     True   unknown
            sub-npJ1/sub-npJ1_ses-20190523_behavior+ecephys.nwb    npJ1 straight track virtual reality.    303   75904     True   unknown
                    sub-npJ1/sub-npJ1_ses-20190523_behavior.nwb    npJ1                 straight track.    303   75904    False          
            sub-npJ2/sub-npJ2_ses-20190511_behavior+ecephys.nwb    npJ2 straight track virtual reality.    106  117785     True   unknown
                    sub-npJ2/sub-npJ2_ses-20190511_behavior.nwb    npJ2                 straight track.    106  117785    False          
            sub-npJ2/sub-npJ2_ses-20190512_behavior+ecephys.nwb    npJ2 straight track virtual reality.    216   74451     True   unknown
            sub-npJ3/sub-npJ3_ses-20190504_behavior+ecephys.nwb    npJ3 straight track virtual reality.    210  124590     True   unknown
                    sub-npJ3/sub-npJ3_ses-20190504_behavior.nwb    npJ3                 straight track.    210  124590    False          
            sub-npJ3/sub-npJ3_ses-20190506_behavior+ecephys.nwb    npJ3 straight track virtual reality.    133   47779     True   unknown
            sub-npJ4/sub-npJ4_ses-20190511_behavior+ecephys.nwb    npJ4 straight track virtual reality.    118  117863     True   unknown
                    sub-npJ4/sub-npJ4_ses-20190511_behavior.nwb    npJ4                 straight track.    118  117863    False          
            sub-npJ4/sub-npJ4_ses-20190512_behavior+ecephys.nwb    npJ4 straight track virtual reality.    205   88135     True   unknown
                    sub-npJ5/sub-npJ5_ses-20190505_behavior.nwb    npJ5                 straight track.    389  102281    False          
sub-npJ5/sub-npJ5_ses-20190505_obj-10plzqh_behavior+ecephys.nwb    npJ5 straight track virtual reality.    389  102281     True   unknown
sub-npJ5/sub-npJ5_ses-20190505_obj-1ti12l8_behavior+ecephys.nwb    npJ5 straight track virtual reality.    389   62756     True   unknown

Head-fixed ecephys files: 20 units 5120 subjects 9 (paper: 11 recordings, 2861 units, 8 mice)
('same frames', 'npI1', 44061, ['sub-npI1_ses-20190415_behavior.nwb', 'sub-npI1_ses-20190415_behavior+ecephys.nwb'])
('same frames', 'npI1', 78990, ['sub-npI1_ses-20190416_behavior+ecephys.nwb', 'sub-npI1_ses-20190416_behavior.nwb'])
('same frames', 'npI3', 451580, ['sub-npI3_ses-20190420_behavior.nwb', 'sub-npI3_ses-20190420_behavior+ecephys.nwb'])
('same frames', 'npI4', 74852, ['sub-npI4_ses-20190423_behavior.nwb', 'sub-npI4_ses-20190423_behavior+ecephys.nwb'])
('same frames', 'npI4', 84626, ['sub-npI4_ses-20190421_behavior.nwb', 'sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb'])
('same frames', 'npJ1', 75904, ['sub-npJ1_ses-20190523_behavior.nwb', 'sub-npJ1_ses-20190523_behavior+ecephys.nwb'])
('same frames', 'npJ2', 117785, ['sub-npJ2_ses-20190511_behavior.nwb', 'sub-npJ2_ses-20190511_behavior+ecephys.nwb'])
('same frames', 'npJ3', 124590, ['sub-npJ3_ses-20190504_behavior.nwb', 'sub-npJ3_ses-20190504_behavior+ecephys.nwb'])
('same frames', 'npJ4', 117863, ['sub-npJ4_ses-20190511_behavior.nwb', 'sub-npJ4_ses-20190511_behavior+ecephys.nwb'])
('same frames', 'npJ5', 102281, ['sub-npJ5_ses-20190505_behavior.nwb', 'sub-npJ5_ses-20190505_obj-10plzqh_behavior+ecephys.nwb'])
('same units', 'npI4', 254, ['sub-npI4_ses-20190421_obj-1yyd867_behavior+ecephys.nwb', 'sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb'])
('same units', 'npJ5', 389, ['sub-npJ5_ses-20190505_obj-1ti12l8_behavior+ecephys.nwb', 'sub-npJ5_ses-20190505_obj-10plzqh_behavior+ecephys.nwb'])
In [5]:
# Compare the behaviour of each behaviour-only file with the ecephys file of the same frame count,
# and the spike times of the ecephys pairs that share a unit count.
import h5py, remfile


def head(path, key, n=2000):
    f = h5py.File(remfile.File(urls[path]), "r")
    return f[key][:n]


checks = []
for kind, subj, val, names in dups:
    paths = [p for p in hf.path if p.split("/")[1] in names]
    if kind == "same frames":
        a = head(paths[0], "processing/behavior/Position/position/data")
        b = head(paths[1], "processing/behavior/Position/position/data")
        checks.append((kind, names, "positions identical" if np.array_equal(a, b, equal_nan=True) else "positions differ"))
    else:
        a = head(paths[0], "units/spike_times", 5000)
        b = head(paths[1], "units/spike_times", 5000)
        same_trials = np.array_equal(head(paths[0], "intervals/trials/start_time"), head(paths[1], "intervals/trials/start_time"))
        checks.append((kind, names, f"first 5000 spike times identical: {np.array_equal(a, b)}; "
                                    f"fraction shared: {np.isin(a, b).mean():.3f}; trial tables identical: {same_trials}"))
for c in checks:
    print(c)
('same frames', ['sub-npI1_ses-20190415_behavior.nwb', 'sub-npI1_ses-20190415_behavior+ecephys.nwb'], 'positions identical')
('same frames', ['sub-npI1_ses-20190416_behavior+ecephys.nwb', 'sub-npI1_ses-20190416_behavior.nwb'], 'positions identical')
('same frames', ['sub-npI3_ses-20190420_behavior.nwb', 'sub-npI3_ses-20190420_behavior+ecephys.nwb'], 'positions identical')
('same frames', ['sub-npI4_ses-20190423_behavior.nwb', 'sub-npI4_ses-20190423_behavior+ecephys.nwb'], 'positions identical')
('same frames', ['sub-npI4_ses-20190421_behavior.nwb', 'sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb'], 'positions identical')
('same frames', ['sub-npJ1_ses-20190523_behavior.nwb', 'sub-npJ1_ses-20190523_behavior+ecephys.nwb'], 'positions identical')
('same frames', ['sub-npJ2_ses-20190511_behavior.nwb', 'sub-npJ2_ses-20190511_behavior+ecephys.nwb'], 'positions identical')
('same frames', ['sub-npJ3_ses-20190504_behavior.nwb', 'sub-npJ3_ses-20190504_behavior+ecephys.nwb'], 'positions identical')
('same frames', ['sub-npJ4_ses-20190511_behavior.nwb', 'sub-npJ4_ses-20190511_behavior+ecephys.nwb'], 'positions identical')
('same frames', ['sub-npJ5_ses-20190505_behavior.nwb', 'sub-npJ5_ses-20190505_obj-10plzqh_behavior+ecephys.nwb'], 'positions identical')
('same units', ['sub-npI4_ses-20190421_obj-1yyd867_behavior+ecephys.nwb', 'sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb'], 'first 5000 spike times identical: False; fraction shared: 0.000; trial tables identical: True')
('same units', ['sub-npJ5_ses-20190505_obj-1ti12l8_behavior+ecephys.nwb', 'sub-npJ5_ses-20190505_obj-10plzqh_behavior+ecephys.nwb'], 'first 5000 spike times identical: False; fraction shared: 0.000; trial tables identical: True')

Each of the 10 behaviour-only files repeats the behaviour of an ecephys file of the same session; they are counted once (the ecephys file is used). The two npI4 files of 2019-04-21 and the two npJ5 files of 2019-05-05 each share a unit count and a trial table but hold different spike trains and behaviour of different lengths: the same probe insertion converted twice over different spans. One of each pair is the paper's (link claim below).

headfixed-session-link¶

Claim (added by the author, kind: link): the paper's 11 head-fixed recordings in its figshare deposit are 11 of the dandiset's 20 ecephys files, matched by subject, unit count and frame count, and the matched files agree on the first unit's spike times and on the behaviour.

In [6]:
with ThreadPoolExecutor(6) as ex:
    fsd = list(ex.map(L.figshare_session, sorted(L.FIGSHARE_FILES)))
ece = hf[hf.ecephys]
match_rows, SESSIONS = [], []
for s in fsd:
    cand = ece[(ece.subject == s["animal"]) & (ece.units == s["n_cells"]) & (ece.frames == s["n_frames"])]
    row = {"figshare": s["session"], "name": s["name"], "cells": s["n_cells"], "frames": s["n_frames"],
           "n_candidates": len(cand)}
    if len(cand) == 1:
        p = cand.path.iloc[0]
        f = h5py.File(remfile.File(urls[p]), "r")
        idx = f["units/spike_times_index"][:2].astype(np.int64)
        raw = f["units/spike_times"][:idx[1]]
        sp_raw = raw[:idx[0]]
        sp = L.split_units(raw, idx)["units"][0]
        b = f["processing/behavior"]
        eye = b["EyeTracking/eye_position/data"][:]
        row.update({"dandiset": p.split("/")[1],
                    "unit0_as_stored_equal": bool(len(sp_raw) == len(s["spikes0"]) and np.allclose(sp_raw, s["spikes0"])),
                    "unit0_repaired_equal": bool(len(sp) == len(s["spikes0"]) and np.allclose(sp, s["spikes0"])),
                    "B_equal": bool(np.allclose(b["Position/position/data"][:].ravel(), s["B"], equal_nan=True)),
                    "Bs_equal": bool(np.allclose(b["body_speed/data"][:].ravel(), s["Bs"], equal_nan=True)),
                    "Eh_equal": bool(np.allclose(eye[:, 0], s["Eh"], equal_nan=True)),
                    "Ev_equal": bool(np.allclose(eye[:, 1], s["Ev"], equal_nan=True))})
        SESSIONS.append(p)
    match_rows.append(row)
link = pd.DataFrame(match_rows)
print(link.to_string(index=False))
print("\nMatched", len(SESSIONS), "of 11; cells", link.cells.sum(), "(paper 2861); mice",
      sorted({p.split("/")[0][4:] for p in SESSIONS}))
checks_cols = [c for c in link.columns if c.endswith("_equal") and c != "unit0_as_stored_equal"]
print("All checks true (unit 0 after the repair of the wrapped index):", bool(link[checks_cols].all().all()))
print("Unit 0 as stored differs from the deposit in:", list(link.loc[~link.unit0_as_stored_equal, "dandiset"]))
print("\nFields of cell_info in figshare Dataset 3 (session 1):", fsd[0]["fields"])
print("Any field naming a hemisphere or side:", [f for f in fsd[0]["fields"] if any(w in f.lower() for w in ("hemi", "side", "left", "right", "lateral"))])
 figshare                 name  cells  frames  n_candidates                                               dandiset  unit0_as_stored_equal  unit0_repaired_equal  B_equal  Bs_equal  Eh_equal  Ev_equal
        1      0505_baseline_1    389  102281             1 sub-npJ5_ses-20190505_obj-10plzqh_behavior+ecephys.nwb                   True                  True     True      True      True      True
        2      0413_baseline_2     77  127222             1             sub-npI1_ses-20190413_behavior+ecephys.nwb                   True                  True     True      True      True      True
        3      0415_baseline_1    173   44061             1             sub-npI1_ses-20190415_behavior+ecephys.nwb                   True                  True     True      True      True      True
        4      0416_baseline_1    408   78990             1             sub-npI1_ses-20190416_behavior+ecephys.nwb                   True                  True     True      True      True      True
        5 0420_baseline_gain_1    286  451580             1             sub-npI3_ses-20190420_behavior+ecephys.nwb                  False                  True     True      True      True      True
        6      0421_baseline_1    254   84626             1 sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb                  False                  True     True      True      True      True
        7      0423_baseline_1    537   74852             1             sub-npI4_ses-20190423_behavior+ecephys.nwb                   True                  True     True      True      True      True
        8      0523_baseline_2    303   75904             1             sub-npJ1_ses-20190523_behavior+ecephys.nwb                   True                  True     True      True      True      True
        9 0511_baseline_gain_1    106  117785             1             sub-npJ2_ses-20190511_behavior+ecephys.nwb                   True                  True     True      True      True      True
       10 0504_baseline_gain_1    210  124590             1             sub-npJ3_ses-20190504_behavior+ecephys.nwb                   True                  True     True      True      True      True
       11 0511_baseline_gain_1    118  117863             1             sub-npJ4_ses-20190511_behavior+ecephys.nwb                   True                  True     True      True      True      True

Matched 11 of 11; cells 2861 (paper 2861); mice ['npI1', 'npI3', 'npI4', 'npJ1', 'npJ2', 'npJ3', 'npJ4', 'npJ5']
All checks true (unit 0 after the repair of the wrapped index): True
Unit 0 as stored differs from the deposit in: ['sub-npI3_ses-20190420_behavior+ecephys.nwb', 'sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb']

Fields of cell_info in figshare Dataset 3 (session 1): ['animal_id', 'body_position', 'body_speed', 'cell_id', 'horizontal_eye_position', 'horiztonal_eye_velocity', 'session_id', 'spike_times', 'time', 'track_length', 'trial_contrast', 'vertical_eye_position', 'vertical_eye_velocity']
Any field naming a hemisphere or side: []

Result: reproduced. Each of the 11 figshare sessions matches exactly one dandiset file by subject, unit count and frame count; in every pair the body position and speed and both eye positions are equal, and so are the first unit's spike times once the wrapped index entry of two files is repaired (next cells). The 11 files hold 2861 units from 8 mice, as the Methods say. Nothing in the dandiset marks these 11 files as the paper's.

In [7]:
# The 9 ecephys files that are not the paper's 11 recordings: their trial tables, which would mark
# the landmark and no-landmark blocks of Figure 8 if they held them.
from itertools import combinations
unused = sorted(p for p in ece.path if p not in SESSIONS)


def trial_table(p):
    f = h5py.File(remfile.File(urls[p]), "r")
    tr = f["intervals/trials"]
    cols = [c.decode() if isinstance(c, bytes) else c for c in tr.attrs["colnames"]]
    out = {"file": p.split("/")[1][:44], "units": int(f["units/id"].shape[0]), "trials": int(tr["id"].shape[0]),
           "columns": ",".join(cols)}
    for c in cols:
        v = tr[c][:]
        if c in ("visual_contrast", "running_wheel_gain"):
            out[c] = sorted(set(np.round(v, 2).tolist()))
        elif c == "reward":
            out[c] = sorted(set(map(str, v)))
    out["intervals"] = ",".join(f["intervals"].keys())
    return out


with ThreadPoolExecutor(9) as ex:
    tt = pd.DataFrame(list(ex.map(trial_table, unused + SESSIONS[:2])))
print(tt.to_string(index=False))
print("(the last two rows are two of the paper's sessions, for comparison)")
u = tt.iloc[:len(unused)]
per_mouse = u.assign(mouse=[p.split("/")[0] for p in unused])
subsets = [c for r in range(1, len(unused) + 1) for c in combinations(range(len(unused)), r)
           if u.units.iloc[list(c)].sum() == 1621]
print("\nSubsets of the unused files whose units sum to 1621 (the Figure 8 count):", len(subsets))
for c in subsets:
    print("  ", [u.file.iloc[j] for j in c], "mice:", len({unused[j].split("/")[0] for j in c}))
print("Subsets of 6 files from 6 different mice among", sum(1 for c in combinations(range(len(unused)), 6)
                                                          if len({unused[j].split("/")[0] for j in c}) == 6),
      "such subsets of the 9 files")
                                        file  units  trials                                                        columns                          visual_contrast running_wheel_gain reward intervals
  sub-npI1_ses-20190414_behavior+ecephys.nwb    156     249 start_time,stop_time,visual_contrast,running_wheel_gain,reward [0.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]         [0.5, 1.0] [True]    trials
  sub-npI3_ses-20190421_behavior+ecephys.nwb    424     249 start_time,stop_time,visual_contrast,running_wheel_gain,reward [0.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]         [0.5, 1.0] [True]    trials
sub-npI4_ses-20190421_obj-1yyd867_behavior+e    254     149 start_time,stop_time,visual_contrast,running_wheel_gain,reward                                  [100.0]              [1.0] [True]    trials
  sub-npI5_ses-20190414_behavior+ecephys.nwb    275     249 start_time,stop_time,visual_contrast,running_wheel_gain,reward [0.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]         [0.5, 1.0] [True]    trials
  sub-npJ1_ses-20190521_behavior+ecephys.nwb    207      59 start_time,stop_time,visual_contrast,running_wheel_gain,reward                                  [100.0]              [1.0] [True]    trials
  sub-npJ2_ses-20190512_behavior+ecephys.nwb    216     269 start_time,stop_time,visual_contrast,running_wheel_gain,reward [0.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]         [0.5, 1.0] [True]    trials
  sub-npJ3_ses-20190506_behavior+ecephys.nwb    133     269 start_time,stop_time,visual_contrast,running_wheel_gain,reward [0.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]         [0.5, 1.0] [True]    trials
  sub-npJ4_ses-20190512_behavior+ecephys.nwb    205     269 start_time,stop_time,visual_contrast,running_wheel_gain,reward [0.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]         [0.5, 1.0] [True]    trials
sub-npJ5_ses-20190505_obj-1ti12l8_behavior+e    389     149 start_time,stop_time,visual_contrast,running_wheel_gain,reward                                  [100.0]              [1.0] [True]    trials
sub-npJ5_ses-20190505_obj-10plzqh_behavior+e    389     149 start_time,stop_time,visual_contrast,running_wheel_gain,reward                                  [100.0]              [1.0] [True]    trials
  sub-npI1_ses-20190413_behavior+ecephys.nwb     77     213 start_time,stop_time,visual_contrast,running_wheel_gain,reward                                  [100.0]         [0.5, 1.0] [True]    trials
(the last two rows are two of the paper's sessions, for comparison)

Subsets of the unused files whose units sum to 1621 (the Figure 8 count): 1
   ['sub-npI3_ses-20190421_behavior+ecephys.nwb', 'sub-npI4_ses-20190421_obj-1yyd867_behavior+e', 'sub-npJ2_ses-20190512_behavior+ecephys.nwb', 'sub-npJ3_ses-20190506_behavior+ecephys.nwb', 'sub-npJ4_ses-20190512_behavior+ecephys.nwb', 'sub-npJ5_ses-20190505_obj-1ti12l8_behavior+e'] mice: 6
Subsets of 6 files from 6 different mice among 84 such subsets of the 9 files

No trial table holds a field for the track, its landmarks or a block: the columns are start and stop time, visual contrast, running wheel gain and reward, in the 9 unused files as in the paper's 11. Six of the unused files hold gain and contrast trials (gains 0.5 and 1, contrasts 0 to 100%), three only gain 1 and contrast 100%. One subset of six of them, from six mice, sums to the 1621 units of Figure 8, which is consistent with these being the Figure 8 sessions but does not show it; even if they are, nothing in the files says which trials ran on the track without landmarks.

In [8]:
# Load the 11 sessions: behaviour at 50 Hz and spike counts in its 20 ms bins.
t0 = time.time()
DATA = {}
for p in SESSIONS:
    DATA[p] = L.load_session(urls[p])
print(f"loaded {len(DATA)} sessions in {time.time() - t0:.0f} s")
rows = []
for p, s in DATA.items():
    t = s["t"]
    dt = np.diff(t)
    row = {"session": p.split("/")[1][:40], "mouse": s["subject"], "units": s["counts"].shape[0],
           "minutes": round((t[-1] - t[0]) / 60, 1), "dt_min": round(dt.min(), 4), "dt_max": round(dt.max(), 4),
           "spikes_outside": int(s["n_outside"].sum()), "max_count_per_bin": s["max_count"],
           "trials": len(s["trials"].get("start_time", [])),
           "gains": sorted(set(np.round(s["trials"]["running_wheel_gain"], 2))),
           "contrasts": sorted(set(s["trials"]["visual_contrast"]))}
    for v in L.VARS:
        x = s["beh"][v]
        row[v + "_nan%"] = round(100 * np.isnan(x).mean(), 2)
        row[v + "_range"] = (round(np.nanmin(x), 2), round(np.nanmax(x), 2))
    rows.append(row)
loaded = pd.DataFrame(rows)
print(loaded.to_string(index=False))
print("\nUnits by mouse:", loaded.groupby("mouse").units.sum().to_dict())
print("Units repaired (index entry wrapped at 2**16; spikes moved back from the next unit):")
for p, s in DATA.items():
    for rep in s["repaired"]:
        print("  ", p.split("/")[1][:40], rep)
print("Peak memory (GB):", round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6, 2))
loaded 11 sessions in 51 s
                                 session mouse  units  minutes  dt_min  dt_max  spikes_outside  max_count_per_bin  trials           gains     contrasts  B_nan%         B_range  Bs_nan%         Bs_range  Eh_nan%          Eh_range  Ev_nan%           Ev_range  Ehd_nan%           Ehd_range  Evd_nan%           Evd_range
sub-npJ5_ses-20190505_obj-10plzqh_behavi  npJ5    389     34.1    0.02    0.02               0                 11     149           [1.0]       [100.0]     0.0   (0.0, 400.81)      0.0   (-16.87, 74.0)     2.35    (-7.97, 17.15)     2.35    (-34.67, 18.57)      8.37      (-18.02, 29.5)      8.37     (-15.98, 12.71)
sub-npI1_ses-20190413_behavior+ecephys.n  npI1     77     43.8    0.02   82.22           46207                  7     213      [0.5, 1.0]       [100.0]     0.0   (0.0, 400.63)      0.0  (-11.64, 70.88)     0.01    (-4.51, 12.78)     0.01     (-8.02, 24.82)      0.07     (-13.68, 16.79)      0.07       (-7.52, 7.23)
sub-npI1_ses-20190415_behavior+ecephys.n  npI1    173     14.7    0.02    0.02               0                 10      99           [1.0]       [100.0]     0.0   (0.0, 400.78)      0.0  (-11.06, 77.61)     0.06      (-5.4, 7.56)     0.06      (-6.44, 7.21)      0.33     (-11.79, 10.21)      0.33       (-5.85, 4.16)
sub-npI1_ses-20190416_behavior+ecephys.n  npI1    408     26.3    0.02    0.02               0                  8     149           [1.0]       [100.0]     0.0   (0.0, 400.82)      0.0  (-15.66, 86.79)     0.11    (-5.83, 12.35)     0.11      (-6.06, 6.99)      0.56       (-11.4, 10.7)      0.56       (-4.95, 4.73)
sub-npI3_ses-20190420_behavior+ecephys.n  npI3    286    159.3    0.02  307.58          770029                  9     249      [0.5, 1.0]       [100.0]     0.0  (-1.34, 401.1)      0.0  (-21.42, 67.57)    65.96    (-10.08, 33.3)    65.96      (-26.7, 54.2)     69.07     (-40.59, 39.99)     69.07     (-19.38, 14.78)
sub-npI4_ses-20190421_obj-1h2xem6_behavi  npI4    254     28.2    0.02    0.02               0                 10     149           [1.0]       [100.0]     0.0   (0.0, 400.72)      0.0 (-14.13, 124.56)     0.39 (-2868.66, 85.72)     0.39  (-1549.8, 182.89)      2.11 (-1258.21, 1241.54)      2.11   (-684.52, 650.23)
sub-npI4_ses-20190423_behavior+ecephys.n  npI4    537     25.0    0.02    0.02               0                 11     149           [1.0]       [100.0]     0.0 (-0.04, 400.86)      0.0  (-15.87, 107.3)     0.56   (-10.65, 29.79)     0.56   (-15.22, 185.61)      2.84     (-26.06, 22.24)      2.84     (-76.02, 76.53)
sub-npJ1_ses-20190523_behavior+ecephys.n  npJ1    303     25.3    0.02    0.02               0                 10     211 [0.5, 0.8, 1.0] [10.0, 100.0]     0.0 (-0.72, 400.87)      0.0   (-16.26, 93.6)     2.36    (-5.86, 35.21)     2.36   (-112.44, 73.65)      8.43     (-26.68, 39.59)      8.43     (-39.91, 35.43)
sub-npJ2_ses-20190511_behavior+ecephys.n  npJ2    106     42.1    0.02   94.70          165111                  9     227      [0.5, 1.0]       [100.0]     0.0 (-3.98, 400.54)      0.0  (-16.97, 91.61)     0.06   (-23.72, 33.29)     0.06   (-86.86, 213.15)      0.31      (-15.11, 18.3)      0.31     (-97.97, 95.56)
sub-npJ3_ses-20190504_behavior+ecephys.n  npJ3    210     44.0    0.02   74.20          180520                 12     227      [0.5, 1.0]       [100.0]     0.0   (0.0, 400.85)      0.0 (-14.17, 106.77)     0.62  (-35.58, 528.65)     0.62 (-9281.87, 334.45)      2.94   (-197.42, 208.58)      2.94 (-3855.69, 3884.02)
sub-npJ4_ses-20190511_behavior+ecephys.n  npJ4    118     42.2    0.02   93.00          174338                  8     227      [0.5, 1.0]       [100.0]     0.0   (0.0, 400.84)      0.0  (-15.24, 88.52)     0.31    (-6.92, 21.37)     0.31   (-115.61, 57.12)      1.58     (-24.28, 22.64)      1.58     (-28.81, 31.66)

Units by mouse: {'npI1': 658, 'npI3': 286, 'npI4': 791, 'npJ1': 303, 'npJ2': 106, 'npJ3': 210, 'npJ4': 118, 'npJ5': 389}
Units repaired (index entry wrapped at 2**16; spikes moved back from the next unit):
   sub-npI3_ses-20190420_behavior+ecephys.n {'unit': 0, 'moved': 65536, 'index_was': 5852, 'index_now': 71388}
   sub-npI4_ses-20190421_obj-1h2xem6_behavi {'unit': 0, 'moved': 65536, 'index_was': 12175, 'index_now': 77711}
Peak memory (GB): 0.91

Behaviour is sampled every 20 ms, as the Methods' 50 Hz, except for gaps in two sessions (npI1 0413, up to 82 s, and npI3 0420, 217 and 308 s); a spike counts only in the 20 ms after a sample, so spikes in a gap fall in no bin (spikes_outside). In npI3 0420 66% of the eye samples are missing; those bins are left out of the model. In two files the index of unit 0 has wrapped at 2**16, which gives unit 0 too few spikes and unit 1 the rest of unit 0's; the repair restores the deposit's trains (link claim above). The repair is a finding about the files. Position runs from 0 to 400 cm, the 4 m track, and is stored in cm with a conversion of 0.01 to metres, which is right. Eye position is stated in metres and eye velocity in "unknown"; the values (a few units either way, the same as in the paper's deposit) are in % of the eye width, the unit of the Results and the Figure 4 legend. Body speed has small negative values (the mouse stepping back). Some sessions include trials at gain 0.5 (and npJ1 0523 at 0.8 and contrast 10); the paper does not mention them and its deposit holds the whole sessions, so the whole sessions are used here, as in the deposit.

In [9]:
# Clock check: spikes and behaviour share a clock if position tuning is strongest with no shift.
# For each session, the mean over units of the fraction of spike count variance explained by 40
# position bins, with the spike counts shifted circularly by each lag.
lags_s = [-10, -2, -0.5, -0.1, 0, 0.1, 0.5, 2, 10]
rows = []
for p, s in DATA.items():
    B = s["beh"]["B"]
    ok = np.isfinite(B)
    bins = np.clip((B[ok] / 400 * 40).astype(int), 0, 39)
    C = s["counts"][:, ok].astype(float)
    nb = np.bincount(bins, minlength=40)
    row = {"session": p.split("/")[1][:22]}
    for lag in lags_s:
        Cs = np.roll(C, int(round(lag / L.DT)), axis=1)
        means = np.stack([np.bincount(bins, weights=c, minlength=40) for c in Cs]) / np.maximum(nb, 1)
        between = (means ** 2 * nb).sum(1) / nb.sum() - Cs.mean(1) ** 2
        row[lag] = float(np.nanmean(between / np.maximum(Cs.var(1), 1e-12)))
    rows.append(row)
clock = pd.DataFrame(rows).set_index("session")
print((clock * 1000).round(3).to_string())
print("\nLag of the maximum per session (s):", clock.idxmax(axis=1).to_dict())
                          -10      -2    -0.5    -0.1       0     0.1     0.5       2     10
session                                                                                     
sub-npJ5_ses-20190505_  2.020   5.837  10.022  10.613  10.451  10.117   8.634   5.177  1.868
sub-npI1_ses-20190413_  6.098  17.908  25.215  26.711  26.785  26.653  24.521  17.344  6.256
sub-npI1_ses-20190415_  4.265   9.371  11.747  12.222  12.257  12.288  11.783   8.984  4.289
sub-npI1_ses-20190416_  5.100  12.349  15.416  16.129  16.083  15.941  14.802  11.182  4.705
sub-npI3_ses-20190420_  1.208   3.671   8.425  10.960  11.320  11.436   9.748   4.125  1.253
sub-npI4_ses-20190421_  3.369   7.601  11.140  12.851  13.037  13.073  11.203   6.489  3.131
sub-npI4_ses-20190423_  5.344   9.488  13.105  14.367  14.576  14.595  13.149   8.998  5.147
sub-npJ1_ses-20190523_  3.192   6.868  11.733  13.173  13.153  12.860  10.923   6.466  3.111
sub-npJ2_ses-20190511_  1.737   7.119  11.505  13.329  13.846  14.165  13.470   7.900  1.604
sub-npJ3_ses-20190504_  1.812   3.793   6.323   7.225   7.352   7.309   6.389   4.016  1.753
sub-npJ4_ses-20190511_  1.491   3.282   4.508   4.542   4.443   4.480   4.133   2.943  1.384

Lag of the maximum per session (s): {'sub-npJ5_ses-20190505_': -0.1, 'sub-npI1_ses-20190413_': 0, 'sub-npI1_ses-20190415_': 0.1, 'sub-npI1_ses-20190416_': -0.1, 'sub-npI3_ses-20190420_': 0.1, 'sub-npI4_ses-20190421_': 0.1, 'sub-npI4_ses-20190423_': 0.1, 'sub-npJ1_ses-20190523_': -0.1, 'sub-npJ2_ses-20190511_': 0.1, 'sub-npJ3_ses-20190504_': 0, 'sub-npJ4_ses-20190511_': -0.1}

In every session position explains most spike variance at a lag of 0 (printed: variance explained x 1000), falling at 0.5 s and more, so spikes and behaviour share the clock. Eye traces share the behaviour timestamps in the files; that they share the spikes' clock is consistent with this check, not shown by it.

fig4f-eye-movement-distributions¶

Head-fixed mice in VR move their eyes considerably; the inner 98% of horizontal eye position spans about -3.5 to 5.3% of eye width and of vertical position -2.7 to 1.6%; that of horizontal eye velocity -6.2 to 6.9% of eye width per s and of vertical eye velocity -2.8 to 3.2% per s.

Criterion: percentiles per session, about the mean position, averaged per mouse, mean over 8 mice, with the legend's sem across mice as tolerance; reproduced when at least seven of eight are within it.

In [10]:
EXPECTED_4F = {("Eh", 1): (-3.50, 0.61), ("Eh", 99): (5.28, 0.87), ("Ev", 1): (-2.74, 0.64), ("Ev", 99): (1.60, 0.21),
               ("Ehd", 1): (-6.19, 0.74), ("Ehd", 99): (6.87, 0.66), ("Evd", 1): (-2.83, 0.55), ("Evd", 99): (3.15, 0.68)}
rows = []
for p, s in DATA.items():
    for centred in (True, False):
        row = {"session": p.split("/")[1][:22], "mouse": s["subject"], "centred": centred}
        for v in L.EYE:
            x = s["beh"][v][np.isfinite(s["beh"][v])]
            if centred:
                x = x - x.mean()
            row[f"{v}_1"], row[f"{v}_99"] = np.percentile(x, [1, 99])
        rows.append(row)
pct = pd.DataFrame(rows)
for centred in (True, False):
    per_mouse = pct[pct.centred == centred].groupby("mouse").mean(numeric_only=True)
    res = []
    for (v, q), (val, tol) in EXPECTED_4F.items():
        m = per_mouse[f"{v}_{q}"]
        res.append({"value": f"{v} {q}th", "paper": val, "tol": tol, "mean_over_mice": round(m.mean(), 2),
                    "sem": round(m.sem(), 2), "within": abs(m.mean() - val) <= tol})
    res = pd.DataFrame(res)
    print(("Centred on each session's mean (the criterion's reading for positions):" if centred else
           "Not centred (variant):"), f"{int(res.within.sum())} of 8 within tolerance; mice: {len(per_mouse)}")
    print(res.to_string(index=False))
print("\nPer mouse, centred:")
print(pct[pct.centred].groupby("mouse").mean(numeric_only=True).round(2).to_string())
Centred on each session's mean (the criterion's reading for positions): 8 of 8 within tolerance; mice: 8
   value  paper  tol  mean_over_mice  sem  within
  Eh 1th  -3.50 0.61           -3.49 0.62    True
 Eh 99th   5.28 0.87            5.18 0.88    True
  Ev 1th  -2.74 0.64           -2.57 0.62    True
 Ev 99th   1.60 0.21            1.65 0.20    True
 Ehd 1th  -6.19 0.74           -6.04 0.78    True
Ehd 99th   6.87 0.66            6.83 0.69    True
 Evd 1th  -2.83 0.55           -2.66 0.54    True
Evd 99th   3.15 0.68            2.97 0.66    True
Not centred (variant): 8 of 8 within tolerance; mice: 8
   value  paper  tol  mean_over_mice  sem  within
  Eh 1th  -3.50 0.61           -3.44 0.62    True
 Eh 99th   5.28 0.87            5.23 0.88    True
  Ev 1th  -2.74 0.64           -2.69 0.65    True
 Ev 99th   1.60 0.21            1.53 0.20    True
 Ehd 1th  -6.19 0.74           -6.05 0.78    True
Ehd 99th   6.87 0.66            6.82 0.69    True
 Evd 1th  -2.83 0.55           -2.63 0.52    True
Evd 99th   3.15 0.68            3.00 0.67    True

Per mouse, centred:
       centred  Eh_1  Eh_99  Ev_1  Ev_99  Ehd_1  Ehd_99  Evd_1  Evd_99
mouse                                                                 
npI1       1.0 -2.73   2.61 -1.08   1.24  -3.73    4.70  -1.58    1.87
npI3       1.0 -7.65  10.96 -6.22   2.28 -10.85   11.23  -6.01    7.20
npI4       1.0 -2.26   4.70 -1.87   1.93  -5.65    6.21  -3.00    3.03
npJ1       1.0 -2.99   4.64 -3.98   2.29  -5.07    5.74  -3.03    3.44
npJ2       1.0 -2.34   4.27 -1.05   1.05  -4.72    6.11  -1.48    1.67
npJ3       1.0 -3.20   5.45 -2.76   2.07  -7.40    7.46  -2.91    3.14
npJ4       1.0 -2.88   3.88 -1.71   0.83  -5.38    6.39  -1.69    1.95
npJ5       1.0 -3.85   4.97 -1.87   1.51  -5.56    6.76  -1.59    1.49

Result: reproduced. All eight percentiles, averaged per mouse over the 8 mice, are within the legend's sem: horizontal position -3.49 and 5.18, vertical position -2.57 and 1.65, horizontal velocity -6.04 and 6.83, vertical velocity -2.66 and 2.97 % of eye width (per s). Without centring all eight are also within.

The LN model, under the main readings¶

The forward search of the claims file's LN pipeline is run for every unit of the 11 sessions, with open detail (1) under reading (a), 10-s sections assigned to folds in turn (compute_test_train_ind.m), and open detail (2) under reading (a), bins outside any variable's inner 98% dropped. The other reading of detail (1) is run, with every downstream analysis, in readings_folds_mallory_2021.ipynb; reading (2b) was not run, for lack of time. For each encoding cell the reduced models (one variable removed, 10 folds), the model-derived tuning curves (Methods eq. 10, M = 200) and the half-session refits for stability are computed in the same pass.

In [11]:
# The conventions of the linked code (github.com/khardcastle/spline-lnp-model, commit 34b470f) that the
# pipeline follows, printed from the repository: the log 2 factor of compute_llh.m, the -5 baseline and
# the final test of forward_search_kfold.m, and the fold assignment of compute_test_train_ind.m, which
# create_glm.m applies after dropping the excluded bins.
import requests
REPO = "https://raw.githubusercontent.com/khardcastle/spline-lnp-model/34b470f/"
for name, keys in (("compute_llh.m", ("log_llh", "meanFR")), ("forward_search_kfold.m", ("baseModel =", "final_pval", "signrank")),
                   ("compute_test_train_ind.m", ("numSeg", "oneSeg", "new_ind")), ("create_glm.m", ("isnan_all", "compute_test_train_ind"))):
    text = requests.get(REPO + name, timeout=60).text.splitlines()
    print(f"--- {name}")
    for k, line in enumerate(text, 1):
        if any(w in line for w in keys):
            print(f"{k:4d}: {line.rstrip()}")
--- compute_llh.m
   1: function [log_llh] = compute_llh(A,n,param)
   3: r = exp(A * param); n = reshape(n,numel(n),1); meanFR = nanmean(n);
   5: log_llh_model = nansum(r-n.*log(r)+log(factorial(n)))/sum(n);
   6: log_llh_mean = nansum(meanFR-n.*log(meanFR)+log(factorial(n)))/sum(n);
   7: log_llh = (-log_llh_model + log_llh_mean);
   8: log_llh = log(2)*log_llh;
--- forward_search_kfold.m
   1: function [allModelFits, allModelTrainFits, bestModels, bestModelFits, parameters, pvals, final_pval] = forward_search_kfold(A,spiketrain,train_ind,test_ind)
  23: baseModel = -5*ones(numFolds,1);
  70:     pval = signrank(topModel_noNaN,baseModel_noNaN,'tail','right');
  86:     baseModel = topModel;
  93: final_pval = signrank(topModel_noNaN,zeros(size(topModel_noNaN)),'tail','right');
--- compute_test_train_ind.m
   3: numSeg = ceil(T/(numFolds*numPts));
   4: oneSeg = ones(numPts,1)*(1:numFolds);
   5: new_ind = repmat(oneSeg(:),numSeg,1);
   6: new_ind = new_ind(1:T);
  11:     test_ind{k} = find(new_ind == k);
--- create_glm.m
  25: isnan_all = [isnan_x; isnan_y; isnan_h; isnan_s];
  27: spiketrain(isnan_all) = [];
  28: x(isnan_all) = [];
  29: y(isnan_all) = [];
  30: head_direction(isnan_all) = [];
  31: speed(isnan_all) = [];
 132: [train_ind,test_ind] = compute_test_train_ind(numFolds,numPts,T);
In [12]:
SUBSET = int(os.environ.get("MALLORY_SUBSET", "0"))   # 0: every unit (develop on a few)
t0 = time.time()
RESULTS, PREPS = [], {}
for si, p in enumerate(SESSIONS):
    s = DATA[p]
    prep = L.prepare(s, L.RANGE_DROP)
    folds = L.fold_labels(prep["n_keep"], L.FOLDS_TURN)
    P = L.by_fold(prep, folds)
    P["seed"] = 1000 + si
    Y = s["counts"][:, prep["keep"]]
    if SUBSET:
        Y = Y[:SUBSET]
    t1 = time.time()
    res = L.analyse_session(P, Y, processes=4)
    for i, r in enumerate(res):
        r.update({"session": p, "mouse": s["subject"], "unit": i})
    RESULTS += res
    PREPS[p] = {k: P[k] for k in ("lims", "cpts", "n_keep", "n_valid")}
    PREPS[p]["vals"] = {v: P["vals"][v] for v in L.VARS}
    PREPS[p]["order"], PREPS[p]["keep"] = P["order"], prep["keep"]
    print(f"{p.split('/')[1][:40]}: {len(res)} units, {prep['n_keep']} of {prep['n_valid']} valid bins kept "
          f"({100 * prep['n_keep'] / prep['n_valid']:.1f}%), {time.time() - t1:.0f} s")
print(f"LN model: {len(RESULTS)} units in {time.time() - t0:.0f} s; peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
cells = pd.DataFrame([{"session": r["session"], "mouse": r["mouse"], "unit": r["unit"], "n_spikes": r["n_spikes"],
                       "selected": ",".join(r["selected"]), "encoded": ",".join(r["encoded"]),
                       "final_p": r["final_p"], **{v: v in r["encoded"] for v in L.VARS}} for r in RESULTS])
print("Units with no spike in the kept bins (nothing to fit):", int((cells.n_spikes == 0).sum()))
print("Units whose selected model failed the final test against 0:",
      int(((cells.selected != "") & (cells.encoded == "")).sum()))
sub-npJ5_ses-20190505_obj-10plzqh_behavi: 389 units, 84505 of 93718 valid bins kept (90.2%), 202 s
sub-npI1_ses-20190413_behavior+ecephys.n: 77 units, 114479 of 127139 valid bins kept (90.0%), 64 s
sub-npI1_ses-20190415_behavior+ecephys.n: 173 units, 39686 of 43916 valid bins kept (90.4%), 25 s
sub-npI1_ses-20190416_behavior+ecephys.n: 408 units, 70409 of 78548 valid bins kept (89.6%), 166 s
sub-npI3_ses-20190420_behavior+ecephys.n: 286 units, 124446 of 139687 valid bins kept (89.1%), 292 s
sub-npI4_ses-20190421_obj-1h2xem6_behavi: 254 units, 75592 of 82843 valid bins kept (91.2%), 178 s
sub-npI4_ses-20190423_behavior+ecephys.n: 537 units, 65690 of 72728 valid bins kept (90.3%), 208 s
sub-npJ1_ses-20190523_behavior+ecephys.n: 303 units, 62849 of 69506 valid bins kept (90.4%), 107 s
sub-npJ2_ses-20190511_behavior+ecephys.n: 106 units, 105925 of 117415 valid bins kept (90.2%), 85 s
sub-npJ3_ses-20190504_behavior+ecephys.n: 210 units, 109513 of 120926 valid bins kept (90.6%), 175 s
sub-npJ4_ses-20190511_behavior+ecephys.n: 118 units, 105554 of 115999 valid bins kept (91.0%), 76 s
LN model: 2861 units in 1581 s; peak memory 3.92 GB
Units with no spike in the kept bins (nothing to fit): 3
Units whose selected model failed the final test against 0: 707

fig4j-eye-encoding-cells¶

Of 2861 MEC cells in head-fixed mice, 711 (25%) carry eye movement signals; 343 (12%) encode horizontal eye position, 234 (9%) vertical eye position, 244 (9%) horizontal eye velocity and 135 (5%) vertical eye velocity.

Criterion: reproduced when, under one reading of open details (1) and (2), the count of eye cells and at least three of the four per-variable counts are within tolerance; partially when the total alone is.

In [13]:
N_ALL = len(cells)
cells["eye_any"] = cells[L.EYE].any(axis=1)
cells["n_eye"] = cells[L.EYE].sum(axis=1)
EXPECTED_4J = {"eye_any": (711, 71.1), "Eh": (343, 34.3), "Ev": (234, 23.4), "Ehd": (244, 24.4), "Evd": (135, 13.5)}


def count_table(c):
    out = []
    for k, (val, tol) in EXPECTED_4J.items():
        n = int(c[k].sum())
        out.append({"count": k, "measured": n, "fraction": round(n / len(c), 3), "paper": val, "tol": tol,
                    "within": abs(n - val) <= tol})
    return pd.DataFrame(out)


t4j = count_table(cells)
print(f"Main readings (folds in turn, out-of-range bins dropped), {N_ALL} units:")
print(t4j.to_string(index=False))
print("Per-variable counts within tolerance:", int(t4j.within[1:].sum()), "of 4")
print("\nAny variable encoded:", int((cells.encoded != "").sum()), "; B", int(cells.B.sum()), "; Bs", int(cells.Bs.sum()))
code_cells = pd.DataFrame([{v: v in r["encoded_code"] for v in L.VARS} for r in RESULTS])
code_cells["eye_any"] = code_cells[L.EYE].any(axis=1)
print("\nVariant, the final test on the last model tried, as forward_search_kfold.m does:")
print(count_table(code_cells).to_string(index=False))
print("\nBy mouse (fraction of units encoding any eye variable):")
print(cells.groupby("mouse").agg(units=("unit", "size"), eye_cells=("eye_any", "sum"),
                                 fraction=("eye_any", "mean")).round(3).to_string())
print("\nBy session:")
print(cells.groupby("session").agg(units=("unit", "size"), eye_cells=("eye_any", "sum"),
                                   fraction=("eye_any", "mean")).round(3).to_string())
Main readings (folds in turn, out-of-range bins dropped), 2861 units:
  count  measured  fraction  paper  tol  within
eye_any       718     0.251    711 71.1    True
     Eh       341     0.119    343 34.3    True
     Ev       243     0.085    234 23.4    True
    Ehd       238     0.083    244 24.4    True
    Evd       137     0.048    135 13.5    True
Per-variable counts within tolerance: 4 of 4

Any variable encoded: 2140 ; B 1938 ; Bs 1187

Variant, the final test on the last model tried, as forward_search_kfold.m does:
  count  measured  fraction  paper  tol  within
eye_any       720     0.252    711 71.1    True
     Eh       340     0.119    343 34.3    True
     Ev       245     0.086    234 23.4    True
    Ehd       238     0.083    244 24.4    True
    Evd       139     0.049    135 13.5    True

By mouse (fraction of units encoding any eye variable):
       units  eye_cells  fraction
mouse                            
npI1     658        147     0.223
npI3     286        149     0.521
npI4     791        193     0.244
npJ1     303         53     0.175
npJ2     106         36     0.340
npJ3     210         56     0.267
npJ4     118         17     0.144
npJ5     389         67     0.172

By session:
                                                                 units  eye_cells  fraction
session                                                                                    
sub-npI1/sub-npI1_ses-20190413_behavior+ecephys.nwb                 77         22     0.286
sub-npI1/sub-npI1_ses-20190415_behavior+ecephys.nwb                173         13     0.075
sub-npI1/sub-npI1_ses-20190416_behavior+ecephys.nwb                408        112     0.275
sub-npI3/sub-npI3_ses-20190420_behavior+ecephys.nwb                286        149     0.521
sub-npI4/sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb    254        125     0.492
sub-npI4/sub-npI4_ses-20190423_behavior+ecephys.nwb                537         68     0.127
sub-npJ1/sub-npJ1_ses-20190523_behavior+ecephys.nwb                303         53     0.175
sub-npJ2/sub-npJ2_ses-20190511_behavior+ecephys.nwb                106         36     0.340
sub-npJ3/sub-npJ3_ses-20190504_behavior+ecephys.nwb                210         56     0.267
sub-npJ4/sub-npJ4_ses-20190511_behavior+ecephys.nwb                118         17     0.144
sub-npJ5/sub-npJ5_ses-20190505_obj-10plzqh_behavior+ecephys.nwb    389         67     0.172

Result: reproduced. Under the main readings 718 of 2861 units (25.1%) encode an eye variable (paper 711): Eh 341, Ev 243, Eh dot 238, Ev dot 137 (paper 343, 234, 244, 135), all five within tolerance. With the code's own final test the counts are 720, 340, 245, 238 and 139. With folds assigned at random (readings_folds_mallory_2021.ipynb) 614 units encode an eye variable, outside the tolerance, with one of four per-variable counts within it; the claim holds under one reading, as the criterion allows. The fraction ranges from 0.144 (npJ4) to 0.521 (npI3) across mice.

fig4k-eye-conjunctive¶

Most eye movement cells (96%) also encode body position or speed, 28% encode more than one eye parameter, and few cells encode an eye variable alone; 23% of cells encode body position alone.

In [14]:
eye_cells = cells[cells.eye_any]
f_bbs = (eye_cells.B | eye_cells.Bs).mean()
f_multi = (eye_cells.n_eye > 1).mean()
f_b_alone = (cells.encoded == "B").mean()
t4k = pd.DataFrame([
    {"value": "eye cells also encoding B or Bs", "measured": round(f_bbs, 3), "paper": 0.96, "tol": 0.096,
     "within": abs(f_bbs - 0.96) <= 0.096},
    {"value": "eye cells encoding more than one eye variable", "measured": round(f_multi, 3), "paper": 0.28,
     "tol": 0.028, "within": abs(f_multi - 0.28) <= 0.028},
    {"value": "all cells encoding B alone", "measured": round(f_b_alone, 3), "paper": 0.23, "tol": 0.023,
     "within": abs(f_b_alone - 0.23) <= 0.023}])
print(t4k.to_string(index=False))
print("\nEye cells:", len(eye_cells), "; encoding an eye variable alone (no B, no Bs):",
      int((~(eye_cells.B | eye_cells.Bs)).sum()))
print("Most common encoded sets:")
print(cells.encoded.replace("", "(none)").value_counts().head(15).to_string())
                                        value  measured  paper   tol  within
              eye cells also encoding B or Bs     0.955   0.96 0.096    True
eye cells encoding more than one eye variable     0.272   0.28 0.028    True
                   all cells encoding B alone     0.242   0.23 0.023    True

Eye cells: 718 ; encoding an eye variable alone (no B, no Bs): 32
Most common encoded sets:
encoded
(none)          721
B               691
B,Bs            612
Bs              119
B,Bs,Eh          96
B,Bs,Ev          90
B,Eh             88
B,Bs,Ehd         73
B,Ev             49
B,Bs,Eh,Ehd      31
B,Bs,Evd         24
B,Evd            23
B,Ehd            22
Bs,Ehd           18
B,Bs,Ehd,Evd     17

Result: reproduced. Of the 718 eye cells 0.955 also encode B or Bs (paper 0.96) and 0.272 encode more than one eye variable (paper 0.28); 0.242 of all units encode B alone (paper 0.23). All three are within tolerance. 32 eye cells encode no B or Bs.

fig7c-head-fixed-model-fit¶

Over 2191 head-fixed cells that encode at least one variable, the held-out log-likelihood increase has median 0.05 bits per spike.

Criterion: fold mean of the selected model's log-likelihood increase as compute_llh.m computes it.

In [15]:
enc_results = [r for r in RESULTS if r["encoded"]]
perf = np.array([np.nanmean(r["sel_fits"]) for r in enc_results])
print("Cells encoding at least one variable:", len(enc_results), "(paper 2191, tolerance 219.1)")
print(f"Median llh increase, compute_llh.m (nats per spike x log 2): {np.median(perf):.4f} "
      f"[{np.percentile(perf, 25):.4f} to {np.percentile(perf, 75):.4f}] (paper 0.05 [0.02 to 0.11], tolerance 0.005)")
print(f"Variant, in bits per spike (nats / log 2): {np.median(perf) / L.LOG2 ** 2:.4f} "
      f"[{np.percentile(perf, 25) / L.LOG2 ** 2:.4f} to {np.percentile(perf, 75) / L.LOG2 ** 2:.4f}]")
print(f"Variant, nats per spike: {np.median(perf) / L.LOG2:.4f}")
print("Range of the plotted quantity:", perf.min().round(4), perf.max().round(4))
print("By mouse:", pd.Series(perf).groupby([r["mouse"] for r in enc_results]).median().round(4).to_dict())
Cells encoding at least one variable: 2140 (paper 2191, tolerance 219.1)
Median llh increase, compute_llh.m (nats per spike x log 2): 0.0513 [0.0215 to 0.1128] (paper 0.05 [0.02 to 0.11], tolerance 0.005)
Variant, in bits per spike (nats / log 2): 0.1068 [0.0448 to 0.2347]
Variant, nats per spike: 0.0740
Range of the plotted quantity: 0.0003 1.3673
By mouse: {'npI1': 0.0522, 'npI3': 0.0953, 'npI4': 0.0499, 'npJ1': 0.0443, 'npJ2': 0.0768, 'npJ3': 0.0588, 'npJ4': 0.0117, 'npJ5': 0.0429}

Result: reproduced. 2140 units encode at least one variable (paper 2191, tolerance 219.1), and the median held-out log-likelihood increase as compute_llh.m computes it is 0.0513 [0.0215 to 0.1128] (paper 0.05 [0.02 to 0.11]). Converted to bits per spike it would be 0.107, so the paper's values are in the code's units.

In [16]:
# Shape measures of every encoded eye variable's tuning curve, and the stability of every encoded
# variable (B, Bs and the eye variables).
feat_rows, CURVES = [], {}
for r in enc_results:
    pp = PREPS[r["session"]]
    for v in r["encoded"]:
        if v in L.EYE:
            f = L.curve_features(r, v, pp["lims"], pp["vals"][v])
            CURVES[(r["session"], r["unit"], v)] = (f.pop("x"), f.pop("curve"))
        else:
            f = {"stability": r["stability"].get(v, np.nan)}
        feat_rows.append({"session": r["session"], "mouse": r["mouse"], "unit": r["unit"], "var": v,
                          "others": ",".join(w for w in r["encoded"] if w != v), **f})
feat = pd.DataFrame(feat_rows)
eyef = feat[feat["var"].isin(L.EYE)].copy()
for col in ("sym_a", "sym_pos_a", "sym_b", "sym_pos_b"):
    if col not in eyef:
        eyef[col] = False
print("Encoded variable instances:", feat["var"].value_counts().to_dict())
print("Stability not computable (flat curve or no overlap):", int(feat.stability.isna().sum()))
print("\nExplored fraction of the preset range, by variable (reading a, reading b), quartiles:")
print(eyef.groupby("var")[["explored_a", "explored_b"]].quantile([0.0, 0.25, 0.5, 1.0]).round(2).unstack().to_string())
print("\nVisualizing ranges by session (% of eye width):")
print(pd.DataFrame({p.split("/")[1][:22]: {v: tuple(round(x, 2) for x in L.vis_range(v, PREPS[p]["lims"]))
                                           for v in L.EYE} for p in SESSIONS}).T.to_string())


def classified(df, reading):
    """Cells whose curve is classified: the range explored (open detail 4) and an order of 1 to 5."""
    col = "explored_a" if reading == "a" else "explored_b"
    return df[(df[col] >= L.EXPLORED_MIN) & (df.order > 0)]


print("\nClass counts (order 1 to 5; 0 = not fit by order 5) among explored curves:")
for rd in ("a", "b"):
    col = "explored_a" if rd == "a" else "explored_b"
    ex = eyef[eyef[col] >= L.EXPLORED_MIN]
    print(f" reading ({rd}) explored: ", {v: (len(g), dict(sorted(Counter(g.order).items()))) for v, g in ex.groupby("var")})
    print(f"   not explored: ", (eyef[col] < L.EXPLORED_MIN).groupby(eyef["var"]).sum().to_dict())


def binom(k, n):
    return stats.binomtest(int(k), int(n), 0.5).pvalue if n else np.nan


def zbin(k, n):
    return (k - n / 2) / math.sqrt(n / 4) if n else np.nan
Encoded variable instances: {'B': 1938, 'Bs': 1187, 'Eh': 341, 'Ev': 243, 'Ehd': 238, 'Evd': 137}
Stability not computable (flat curve or no overlap): 0

Explored fraction of the preset range, by variable (reading a, reading b), quartiles:
    explored_a                  explored_b                
          0.00  0.25  0.50 1.00       0.00  0.25 0.50 1.00
var                                                       
Eh        0.82  0.88  0.99  1.0       0.85  0.90  1.0  1.0
Ehd       1.00  1.00  1.00  1.0       1.00  1.00  1.0  1.0
Ev        0.43  0.66  0.86  1.0       0.50  0.75  0.9  1.0
Evd       0.79  1.00  1.00  1.0       0.85  1.00  1.0  1.0

Visualizing ranges by session (% of eye width):
                                   Eh             Ev           Ehd            Evd
sub-npJ5_ses-20190505_    (-3.0, 3.0)  (-0.88, 1.59)   (-3.0, 3.0)  (-1.59, 1.48)
sub-npI1_ses-20190413_  (-2.43, 2.88)  (-1.21, 0.52)  (-2.97, 3.0)   (-0.95, 1.1)
sub-npI1_ses-20190415_   (-3.0, 2.62)  (-1.46, 1.07)   (-3.0, 3.0)   (-1.77, 2.0)
sub-npI1_ses-20190416_  (-2.62, 2.31)  (-1.42, 1.24)   (-3.0, 3.0)    (-2.0, 2.0)
sub-npI3_ses-20190420_    (-3.0, 3.0)    (-2.0, 2.0)   (-3.0, 3.0)    (-2.0, 2.0)
sub-npI4_ses-20190421_   (-2.26, 3.0)   (-2.0, 1.46)   (-3.0, 3.0)    (-2.0, 2.0)
sub-npI4_ses-20190423_   (-2.31, 3.0)   (-0.6, 1.46)   (-3.0, 3.0)   (-1.66, 2.0)
sub-npJ1_ses-20190523_   (-2.93, 3.0)    (-2.0, 2.0)   (-3.0, 3.0)    (-2.0, 2.0)
sub-npJ2_ses-20190511_   (-2.23, 3.0)  (-1.35, 0.72)   (-3.0, 3.0)  (-1.48, 1.67)
sub-npJ3_ses-20190504_   (-2.95, 3.0)   (-2.0, 1.31)   (-3.0, 3.0)    (-2.0, 2.0)
sub-npJ4_ses-20190511_   (-2.88, 3.0)  (-0.91, 0.96)   (-3.0, 3.0)  (-1.68, 1.97)

Class counts (order 1 to 5; 0 = not fit by order 5) among explored curves:
 reading (a) explored:  {'Eh': (341, {0.0: 2, 1.0: 102, 2.0: 159, 3.0: 49, 4.0: 22, 5.0: 7}), 'Ehd': (238, {1.0: 56, 2.0: 153, 3.0: 23, 4.0: 5, 5.0: 1}), 'Ev': (172, {1.0: 43, 2.0: 70, 3.0: 51, 4.0: 6, 5.0: 2}), 'Evd': (134, {1.0: 36, 2.0: 60, 3.0: 6, 4.0: 31, 5.0: 1})}
   not explored:  {'Eh': 0, 'Ehd': 0, 'Ev': 71, 'Evd': 3}
 reading (b) explored:  {'Eh': (341, {0.0: 2, 1.0: 102, 2.0: 159, 3.0: 49, 4.0: 22, 5.0: 7}), 'Ehd': (238, {1.0: 56, 2.0: 153, 3.0: 23, 4.0: 5, 5.0: 1}), 'Ev': (172, {1.0: 43, 2.0: 70, 3.0: 51, 4.0: 6, 5.0: 2}), 'Evd': (137, {1.0: 36, 2.0: 61, 3.0: 6, 4.0: 33, 5.0: 1})}
   not explored:  {'Eh': 0, 'Ehd': 0, 'Ev': 71, 'Evd': 0}

fig5a-eh-nasal-temporal-similar¶

Among horizontal eye position cells, similar proportions fire most for nasal and temporal positions (170 of 343 nasal), also in each hemisphere.

Criterion: a claim of absence; preference under open detail (5) on all Eh cells; reproduced when none of the three binomial tests (all cells, ipsilateral, contralateral) gives P < 0.05. Positive horizontal eye values are nasal: the Methods ("Comparison between LN and shuffling-based methods") pair velocities below 0 with temporal and above 0 with nasal rotations, and Supplementary Fig. 4 labels the negative end T and the positive end N.

In [17]:
# Preference readings: (a) slope sign for linear curves, side of the maximum otherwise; (b) the side with
# the larger absolute slope of the lines fitted either side of 0, as the claims file words it; (r) a
# variant, the side with the steeper rise away from 0 (the round-1 reading of (b)).
eh = eyef[eyef["var"] == "Eh"]
for rd in ("a", "b", "r"):
    k = int((eh[f"pref_{rd}"] > 0).sum())
    n = len(eh)
    print(f"Preference reading ({rd}): nasal-preferring {k} of {n} ({k / n:.3f}), Z = {zbin(k, n):.2f}, "
          f"binomial P = {binom(k, n):.3g}")
    for rd2 in ("a", "b"):
        c = classified(eh, rd2)
        k2 = int((c[f"pref_{rd}"] > 0).sum())
        print(f"   on cells classified under explored reading ({rd2}): {k2} of {len(c)}, P = {binom(k2, len(c)):.3g}")
print("Paper: 170 of 343, Z = 0.11, P = 0.91; ipsilateral 38/87, contralateral 132/256.")
print("By mouse, nasal fraction (reading a):", eh.groupby("mouse").pref_a.apply(lambda s: round((s > 0).mean(), 2)).to_dict())
print("The hemisphere of each recording is not in the dandiset (electrode location 'unknown'); the two "
      "hemisphere tests cannot be run.")
Preference reading (a): nasal-preferring 158 of 341 (0.463), Z = -1.35, binomial P = 0.194
   on cells classified under explored reading (a): 157 of 339, P = 0.192
   on cells classified under explored reading (b): 157 of 339, P = 0.192
Preference reading (b): nasal-preferring 155 of 341 (0.455), Z = -1.68, binomial P = 0.104
   on cells classified under explored reading (a): 154 of 339, P = 0.103
   on cells classified under explored reading (b): 154 of 339, P = 0.103
Preference reading (r): nasal-preferring 158 of 341 (0.463), Z = -1.35, binomial P = 0.194
   on cells classified under explored reading (a): 158 of 339, P = 0.232
   on cells classified under explored reading (b): 158 of 339, P = 0.232
Paper: 170 of 343, Z = 0.11, P = 0.91; ipsilateral 38/87, contralateral 132/256.
By mouse, nasal fraction (reading a): {'npI1': 0.25, 'npI3': 0.39, 'npI4': 0.72, 'npJ1': 0.35, 'npJ2': 0.32, 'npJ3': 0.66, 'npJ4': 0.71, 'npJ5': 0.63}
The hemisphere of each recording is not in the dandiset (electrode location 'unknown'); the two hemisphere tests cannot be run.

Result: partially reproduced. Over all 341 Eh cells 158 prefer nasal positions (0.463), binomial P = 0.194, under preference reading (a); 155 (P = 0.104) under the literal reading (b), the larger absolute slope, and 158 (P = 0.194) under variant (r). No reading of preference or explored range finds a preference. The two per-hemisphere tests cannot be run: the dandiset does not record the hemisphere, nor does figshare Dataset 3 (its fields are printed in the link cell).

fig5b-ev-up-down-similar¶

Of 234 vertical eye position cells 177 are classified by shape, and similar proportions of them fire most for upward and downward positions (88 of 177 upward).

In [18]:
ev = eyef[eyef["var"] == "Ev"]
print("Ev cells:", len(ev))
for rd2 in ("a", "b"):
    c = classified(ev, rd2)
    print(f"Explored reading ({rd2}): {len(c)} classified (paper 177, tolerance 17.7)")
    for rd in ("a", "b", "r"):
        k = int((c[f"pref_{rd}"] > 0).sum())
        print(f"   preference reading ({rd}): upward {k} of {len(c)} ({k / max(len(c), 1):.3f}), Z = {zbin(k, len(c)):.2f}, "
              f"P = {binom(k, len(c)):.3g}")
print("Paper: 88 of 177, Z = 0, P = 1.")
Ev cells: 243
Explored reading (a): 172 classified (paper 177, tolerance 17.7)
   preference reading (a): upward 84 of 172 (0.488), Z = -0.30, P = 0.819
   preference reading (b): upward 82 of 172 (0.477), Z = -0.61, P = 0.594
   preference reading (r): upward 81 of 172 (0.471), Z = -0.76, P = 0.493
Explored reading (b): 172 classified (paper 177, tolerance 17.7)
   preference reading (a): upward 84 of 172 (0.488), Z = -0.30, P = 0.819
   preference reading (b): upward 82 of 172 (0.477), Z = -0.61, P = 0.594
   preference reading (r): upward 81 of 172 (0.471), Z = -0.76, P = 0.493
Paper: 88 of 177, Z = 0, P = 1.

Result: reproduced. 172 of 243 Ev cells are classified (paper 177, tolerance 17.7), and 84 of them prefer upward positions (P = 0.819); 82 (P = 0.594) under the literal preference reading (b) and 81 (P = 0.493) under variant (r). Both readings of explored range give 172.

Stability claims¶

Stability is the Pearson correlation of model-derived tuning curves from the selected model refitted on the first and second halves of the kept bins, on the visualizing range and the part of it both halves visited (the curves share one grid, so no up-sampling is needed; a standard choice).

In [19]:
def med(x):
    x = np.asarray(x, float)
    x = x[np.isfinite(x)]
    if len(x) == 0:
        return (np.nan, np.nan, np.nan, 0)
    return (round(float(np.median(x)), 3), round(float(np.percentile(x, 25)), 3), round(float(np.percentile(x, 75)), 3), len(x))


def ranksum(a, b):
    a, b = np.asarray(a, float), np.asarray(b, float)
    a, b = a[np.isfinite(a)], b[np.isfinite(b)]
    return stats.ranksums(a, b).pvalue if len(a) and len(b) else np.nan


class _NoTest:
    statistic = np.nan
    pvalue = np.nan


def kruskal(*groups):
    g = [np.asarray(x, float)[np.isfinite(np.asarray(x, float))] for x in groups]
    g = [x for x in g if len(x)]
    return stats.kruskal(*g) if len(g) >= 2 else _NoTest()


stab = {v: feat[feat["var"] == v].stability.values for v in L.VARS}
for rd2 in ("a", "b"):
    ev_c = classified(ev, rd2).stability.values
    kw = kruskal(stab["Eh"], ev_c, stab["B"])
    print(f"Explored reading ({rd2}) for the Ev cells:")
    print(f"  median [IQR, n]: Eh {med(stab['Eh'])} (paper 0.87), Ev classified {med(ev_c)} (paper 0.72), "
          f"B {med(stab['B'])} (paper 0.71)")
    print(f"  Kruskal-Wallis chi2 = {kw.statistic:.2f}, P = {kw.pvalue:.3g} (paper 103.51, 3.3e-23)")
    print(f"  Eh vs B rank-sum P = {ranksum(stab['Eh'], stab['B']):.3g} (paper 8.6e-25); Ev vs B P = "
          f"{ranksum(ev_c, stab['B']):.3g} (paper 0.91); alpha 0.0167")
print(f"Variant, all Ev cells: {med(stab['Ev'])}, Ev vs B P = {ranksum(stab['Ev'], stab['B']):.3g}")
print("Range of stability values:", {v: (round(np.nanmin(x), 2), round(np.nanmax(x), 2)) for v, x in stab.items() if len(x)})
print("Median stability by mouse:", feat.groupby(["var", "mouse"]).stability.median().unstack().round(2).to_string())
Explored reading (a) for the Ev cells:
  median [IQR, n]: Eh (0.875, 0.688, 0.957, 341) (paper 0.87), Ev classified (0.603, -0.024, 0.897, 172) (paper 0.72), B (0.713, 0.51, 0.84, 1938) (paper 0.71)
  Kruskal-Wallis chi2 = 133.61, P = 9.7e-30 (paper 103.51, 3.3e-23)
  Eh vs B rank-sum P = 7.72e-30 (paper 8.6e-25); Ev vs B P = 0.0168 (paper 0.91); alpha 0.0167
Explored reading (b) for the Ev cells:
  median [IQR, n]: Eh (0.875, 0.688, 0.957, 341) (paper 0.87), Ev classified (0.603, -0.024, 0.897, 172) (paper 0.72), B (0.713, 0.51, 0.84, 1938) (paper 0.71)
  Kruskal-Wallis chi2 = 133.61, P = 9.7e-30 (paper 103.51, 3.3e-23)
  Eh vs B rank-sum P = 7.72e-30 (paper 8.6e-25); Ev vs B P = 0.0168 (paper 0.91); alpha 0.0167
Variant, all Ev cells: (0.616, 0.045, 0.878, 243), Ev vs B P = 0.0118
Range of stability values: {'B': (np.float64(-0.62), np.float64(0.99)), 'Bs': (np.float64(-0.89), np.float64(0.99)), 'Eh': (np.float64(-0.85), np.float64(1.0)), 'Ev': (np.float64(-0.93), np.float64(1.0)), 'Ehd': (np.float64(-0.58), np.float64(1.0)), 'Evd': (np.float64(-0.97), np.float64(1.0))}
Median stability by mouse: mouse  npI1  npI3  npI4  npJ1  npJ2  npJ3  npJ4  npJ5
var                                                  
B      0.78  0.80  0.51  0.70  0.70  0.51  0.77  0.80
Bs     0.83  0.82  0.65  0.83  0.79  0.71  0.63  0.81
Eh     0.85  0.89  0.77  0.92  0.91  0.84  0.90  0.93
Ehd    0.90  0.98  0.96  0.92  0.97  0.94  0.96  0.99
Ev     0.55  0.90  0.33  0.88  0.90  0.82   NaN  0.35
Evd    0.47  0.97  0.87  0.96  0.66  0.94   NaN   NaN

Result: partially reproduced. Eh tuning (median 0.875, n = 341) is more stable than B tuning (0.713, n = 1938), rank-sum P = 7.7e-30, and Ev (classified cells, 0.603, n = 172) does not differ from B at alpha 0.0167 (P = 0.0168, a margin of 0.0001). The Eh and B medians are within tolerance, and the Ev median is not (paper 0.72, tolerance 0.072). Kruskal-Wallis P = 9.7e-30.

fig5av-eh-linear-most-stable¶

Linearly tuned horizontal eye position cells are more stable than those with greater curvature (medians 0.93, 0.87 and 0.66 for linear, quadratic and higher order).

In [20]:
def class_stability(df, rd2, title):
    c = classified(df, rd2)
    g1, g2, g3 = (c[c.order == 1].stability, c[c.order == 2].stability, c[c.order > 2].stability)
    kw = kruskal(g1, g2, g3)
    print(f"{title}, explored reading ({rd2}): linear {med(g1)}, quadratic {med(g2)}, higher {med(g3)}")
    print(f"   Kruskal-Wallis chi2 = {kw.statistic:.2f}, P = {kw.pvalue:.3g}; rank-sum P: 1 vs 2 {ranksum(g1, g2):.3g}, "
          f"1 vs >2 {ranksum(g1, g3):.3g}, 2 vs >2 {ranksum(g2, g3):.3g} (alpha 0.0167)")
    return g1, g2, g3


for rd2 in ("a", "b"):
    class_stability(eh, rd2, "Eh")
print("Paper: 0.93, 0.87, 0.66; chi2 = 69.59, P = 7.7e-16; 1 vs 2 P = 2.6e-5, 1 vs >2 1.8e-15, 2 vs >2 4.1e-8.")
Eh, explored reading (a): linear (0.933, 0.844, 0.971, 102), quadratic (0.883, 0.739, 0.954, 159), higher (0.686, 0.44, 0.884, 78)
   Kruskal-Wallis chi2 = 43.18, P = 4.2e-10; rank-sum P: 1 vs 2 0.00148, 1 vs >2 4.51e-10, 2 vs >2 4.24e-06 (alpha 0.0167)
Eh, explored reading (b): linear (0.933, 0.844, 0.971, 102), quadratic (0.883, 0.739, 0.954, 159), higher (0.686, 0.44, 0.884, 78)
   Kruskal-Wallis chi2 = 43.18, P = 4.2e-10; rank-sum P: 1 vs 2 0.00148, 1 vs >2 4.51e-10, 2 vs >2 4.24e-06 (alpha 0.0167)
Paper: 0.93, 0.87, 0.66; chi2 = 69.59, P = 7.7e-16; 1 vs 2 P = 2.6e-5, 1 vs >2 1.8e-15, 2 vs >2 4.1e-8.

Result: reproduced. Linear Eh cells (median 0.933, n = 102) are more stable than quadratic (0.883, n = 159; P = 0.00148) and higher order cells (0.686, n = 78; P = 4.5e-10), Kruskal-Wallis P = 4.2e-10; all three medians are within tolerance.

fig5bv-ev-low-order-more-stable¶

Linearly or quadratically tuned vertical eye position cells are more stable than those with greater curvature.

In [21]:
for rd2 in ("a", "b"):
    class_stability(ev, rd2, "Ev")
print("Paper: 0.86, 0.86, 0.56; chi2 = 17.17, P = 1.9e-4; 1 vs >2 P = 0.012, 2 vs >2 P = 0.0001, 1 vs 2 P = 0.87.")
Ev, explored reading (a): linear (0.826, 0.469, 0.941, 43), quadratic (0.732, 0.122, 0.926, 70), higher (0.109, -0.287, 0.691, 59)
   Kruskal-Wallis chi2 = 18.82, P = 8.2e-05; rank-sum P: 1 vs 2 0.394, 1 vs >2 0.000102, 2 vs >2 0.000421 (alpha 0.0167)
Ev, explored reading (b): linear (0.826, 0.469, 0.941, 43), quadratic (0.732, 0.122, 0.926, 70), higher (0.109, -0.287, 0.691, 59)
   Kruskal-Wallis chi2 = 18.82, P = 8.2e-05; rank-sum P: 1 vs 2 0.394, 1 vs >2 0.000102, 2 vs >2 0.000421 (alpha 0.0167)
Paper: 0.86, 0.86, 0.56; chi2 = 17.17, P = 1.9e-4; 1 vs >2 P = 0.012, 2 vs >2 P = 0.0001, 1 vs 2 P = 0.87.

Result: partially reproduced. Linear (median 0.826, n = 43) and quadratic (0.732, n = 70) Ev cells are each more stable than higher order cells (0.109, n = 59; P = 1.0e-4 and 4.2e-4), Kruskal-Wallis P = 8.2e-5, and linear and quadratic do not differ (P = 0.394). Only the linear median is within tolerance, where the criterion asks for two (quadratic 0.732 against 0.86, higher 0.109 against 0.56).

fig6-eye-velocity-linear-nasal¶

A small subpopulation of eye velocity cells is linear (43 of 244 horizontal, 29 of 131 vertical); linear horizontal cells prefer nasal-directed movement (30 of 43), and linear vertical cells show no up or down preference (16 of 29 upward).

Preference is the sign of the linear fit; positive horizontal velocity is nasal and positive vertical velocity upward (Methods, as above).

In [22]:
ehd = eyef[eyef["var"] == "Ehd"].copy()
evd = eyef[eyef["var"] == "Evd"].copy()
for df in (ehd, evd):
    for col in ("sym_a", "sym_pos_a", "sym_b", "sym_pos_b"):
        df[col] = df[col].fillna(False).astype(bool)
print("Eh dot cells:", len(ehd), "; Ev dot cells:", len(evd))
for rd2 in ("a", "b"):
    ch, cv = classified(ehd, rd2), classified(evd, rd2)
    lh, lv = ch[ch.order == 1], cv[cv.order == 1]
    kh, kv = int((lh.slope > 0).sum()), int((lv.slope > 0).sum())
    print(f"Explored reading ({rd2}): classified Eh dot {len(ch)}, Ev dot {len(cv)}")
    print(f"   linear Eh dot {len(lh)} (paper 43, tol 4.3); nasal-preferring {kh} (paper 30, tol 3.0), "
          f"Z = {zbin(kh, len(lh)):.2f}, P = {binom(kh, len(lh)):.3g} (paper Z = 2.44, P = 0.014)")
    print(f"   linear Ev dot {len(lv)} (paper 29, tol 2.9); upward {kv}, Z = {zbin(kv, len(lv)):.2f}, "
          f"P = {binom(kv, len(lv)):.3g} (paper 16/29, P = 0.71)")
Eh dot cells: 238 ; Ev dot cells: 137
Explored reading (a): classified Eh dot 238, Ev dot 134
   linear Eh dot 56 (paper 43, tol 4.3); nasal-preferring 36 (paper 30, tol 3.0), Z = 2.14, P = 0.044 (paper Z = 2.44, P = 0.014)
   linear Ev dot 36 (paper 29, tol 2.9); upward 21, Z = 1.00, P = 0.405 (paper 16/29, P = 0.71)
Explored reading (b): classified Eh dot 238, Ev dot 137
   linear Eh dot 56 (paper 43, tol 4.3); nasal-preferring 36 (paper 30, tol 3.0), Z = 2.14, P = 0.044 (paper Z = 2.44, P = 0.014)
   linear Ev dot 36 (paper 29, tol 2.9); upward 21, Z = 1.00, P = 0.405 (paper 16/29, P = 0.71)

Result: partially reproduced. Linear Eh dot cells prefer nasal movement, 36 of 56 (Z = 2.14, P = 0.044), and linear Ev dot cells show no preference (21 of 36 upward, P = 0.405), so both tests hold. The linear counts, 56 and 36, are above the paper's 43 and 29 and outside tolerance, as is the nasal count 36 (paper 30).

fig6-eye-velocity-nonlinear-temporal¶

Most eye velocity cells are nonlinear (201 of 244 horizontal, 102 of 131 vertical), split into asymmetric (147 and 68) and symmetric (54 and 34) cells; asymmetric horizontal cells prefer temporal movement (87 of 147) and asymmetric vertical cells show no preference.

In [23]:
rows = []
for rd2 in ("a", "b"):
    ch, cv = classified(ehd, rd2), classified(evd, rd2)
    for rd6 in ("a", "b"):
        for rd5 in ("a", "b", "r"):
            row = {"explored": rd2, "symmetric_rule": rd6, "preference": rd5}
            for name, c in (("Ehd", ch), ("Evd", cv)):
                nl = c[c.order > 1]
                sym = nl[nl[f"sym_{rd6}"]]
                asy = nl[~nl[f"sym_{rd6}"]]
                k = int((asy[f"pref_{rd5}"] < 0).sum())   # temporal (horizontal) or downward (vertical)
                row.update({f"{name}_nonlinear": len(nl), f"{name}_asym": len(asy), f"{name}_sym": len(sym),
                            f"{name}_neg_pref": k, f"{name}_P": round(binom(k, len(asy)), 4)})
            rows.append(row)
t6n = pd.DataFrame(rows)
print(t6n.to_string(index=False))
print("Paper: Eh dot nonlinear 201, asymmetric 147 (tol 14.7), symmetric 54 (5.4), temporal 87/147, Z = 2.22, "
      "P = 0.026; Ev dot nonlinear 102, asymmetric 68 (6.8), symmetric 34 (3.4), downward Z = -0.61, P = 0.54.")
t6n["counts_within"] = ((abs(t6n.Ehd_asym - 147) <= 14.7).astype(int) + (abs(t6n.Ehd_sym - 54) <= 5.4).astype(int)
                        + (abs(t6n.Evd_asym - 68) <= 6.8).astype(int) + (abs(t6n.Evd_sym - 34) <= 3.4).astype(int))
t6n["tests_hold"] = (t6n.Ehd_P < 0.05) & (t6n.Ehd_neg_pref > t6n.Ehd_asym / 2) & (t6n.Evd_P >= 0.05)
print(t6n[["explored", "symmetric_rule", "preference", "counts_within", "tests_hold"]].to_string(index=False))
explored symmetric_rule preference  Ehd_nonlinear  Ehd_asym  Ehd_sym  Ehd_neg_pref  Ehd_P  Evd_nonlinear  Evd_asym  Evd_sym  Evd_neg_pref  Evd_P
       a              a          a            182        39      143            21 0.7493             98        20       78             6 0.1153
       a              a          b            182        39      143            21 0.7493             98        20       78             3 0.0026
       a              a          r            182        39      143            21 0.7493             98        20       78             6 0.1153
       a              b          a            182        78      104            41 0.7343             98        61       37            27 0.4426
       a              b          b            182        78      104            47 0.0888             98        61       37            19 0.0044
       a              b          r            182        78      104            39 1.0000             98        61       37            32 0.7982
       b              a          a            182        39      143            21 0.7493            101        21       80             6 0.0784
       b              a          b            182        39      143            21 0.7493            101        21       80             4 0.0072
       b              a          r            182        39      143            21 0.7493            101        21       80             6 0.0784
       b              b          a            182        78      104            41 0.7343            101        64       37            28 0.3817
       b              b          b            182        78      104            47 0.0888            101        64       37            22 0.0169
       b              b          r            182        78      104            39 1.0000            101        64       37            32 1.0000
Paper: Eh dot nonlinear 201, asymmetric 147 (tol 14.7), symmetric 54 (5.4), temporal 87/147, Z = 2.22, P = 0.026; Ev dot nonlinear 102, asymmetric 68 (6.8), symmetric 34 (3.4), downward Z = -0.61, P = 0.54.
explored symmetric_rule preference  counts_within  tests_hold
       a              a          a              0       False
       a              a          b              0       False
       a              a          r              0       False
       a              b          a              1       False
       a              b          b              1       False
       a              b          r              1       False
       b              a          a              0       False
       b              a          b              0       False
       b              a          r              0       False
       b              b          a              2       False
       b              b          b              2       False
       b              b          r              2       False

Result: not reproduced. Under none of the 12 combinations of readings do the tests hold: nonlinear asymmetric Eh dot cells prefer temporal movement in 21 of 39 (P = 0.749) under the slope-sign rule, and 39 to 47 of 78 (P = 0.089 to 1.0) under the shuffle rule, the highest with the literal preference reading (b), where the Ev dot test then finds a preference (P = 0.0044). 182 of 238 Eh dot cells are nonlinear (paper 201), with 39 or 78 asymmetric against the paper's 147; at most two of the four class counts are within tolerance.

fig6-eye-velocity-stability¶

Tuning to horizontal eye velocity (median 0.93) is significantly more stable than tuning to virtual body speed (0.84), and tuning to vertical eye velocity (0.74) is significantly less stable.

In [24]:
kw = kruskal(stab["Ehd"], stab["Evd"], stab["Bs"])
print(f"Median [IQR, n]: Eh dot {med(stab['Ehd'])} (paper 0.93), Ev dot {med(stab['Evd'])} (paper 0.74), "
      f"Bs {med(stab['Bs'])} (paper 0.84)")
print(f"Kruskal-Wallis chi2 = {kw.statistic:.2f}, P = {kw.pvalue:.3g} (paper 90.78, 1.9e-20)")
print(f"Eh dot vs Bs P = {ranksum(stab['Ehd'], stab['Bs']):.3g} (paper 6.5e-18); Ev dot vs Bs P = "
      f"{ranksum(stab['Evd'], stab['Bs']):.3g} (paper 0.00061); alpha 0.0167")
for rd2 in ("a", "b"):
    evd_c = classified(evd, rd2).stability.values
    ehd_c = classified(ehd, rd2).stability.values
    kw2 = kruskal(ehd_c, evd_c, stab["Bs"])
    print(f"Variant, classified cells only (explored reading {rd2}): Eh dot {med(ehd_c)}, Ev dot {med(evd_c)}; "
          f"KW P = {kw2.pvalue:.3g}; Eh dot vs Bs P = {ranksum(ehd_c, stab['Bs']):.3g}; Ev dot vs Bs P = {ranksum(evd_c, stab['Bs']):.3g}")
print("Range:", {v: (round(np.nanmin(stab[v]), 2), round(np.nanmax(stab[v]), 2)) for v in ("Ehd", "Evd", "Bs") if len(stab[v])})
Median [IQR, n]: Eh dot (0.965, 0.884, 0.991, 238) (paper 0.93), Ev dot (0.823, 0.471, 0.963, 137) (paper 0.74), Bs (0.772, 0.544, 0.9, 1187) (paper 0.84)
Kruskal-Wallis chi2 = 204.24, P = 4.46e-45 (paper 90.78, 1.9e-20)
Eh dot vs Bs P = 3.1e-47 (paper 6.5e-18); Ev dot vs Bs P = 0.0358 (paper 0.00061); alpha 0.0167
Variant, classified cells only (explored reading a): Eh dot (0.965, 0.884, 0.991, 238), Ev dot (0.831, 0.473, 0.964, 134); KW P = 4.11e-45; Eh dot vs Bs P = 3.1e-47; Ev dot vs Bs P = 0.0292
Variant, classified cells only (explored reading b): Eh dot (0.965, 0.884, 0.991, 238), Ev dot (0.823, 0.471, 0.963, 137); KW P = 4.46e-45; Eh dot vs Bs P = 3.1e-47; Ev dot vs Bs P = 0.0358
Range: {'Ehd': (np.float64(-0.58), np.float64(1.0)), 'Evd': (np.float64(-0.97), np.float64(1.0)), 'Bs': (np.float64(-0.89), np.float64(0.99))}

Result: not reproduced. Eh dot tuning (median 0.965, n = 238) is more stable than Bs tuning (0.772, n = 1187), P = 3.1e-47, but Ev dot tuning (0.823, n = 137) is not less stable than Bs: its median is higher, and P = 0.0358 is above alpha 0.0167. Kruskal-Wallis P = 4.5e-45. On the 134 Ev dot cells classified under explored reading (a), as the paper's 131 presumably are, the median is 0.831 and P = 0.0292, the same result.

fig6v-asymmetric-more-stable¶

Asymmetric eye velocity cells are more stable than symmetric ones; for horizontal eye velocity both linear and nonlinear asymmetric cells exceed symmetric cells, for vertical eye velocity nonlinear asymmetric cells exceed symmetric cells.

In [25]:
rows = []
for rd2 in ("a", "b"):
    for rd6 in ("a", "b"):
        row = {"explored": rd2, "symmetric_rule": rd6}
        for name, df in (("Ehd", ehd), ("Evd", evd)):
            c = classified(df, rd2)
            lin = c[c.order == 1].stability
            nla = c[(c.order > 1) & ~c[f"sym_{rd6}"]].stability
            nls = c[(c.order > 1) & c[f"sym_{rd6}"]].stability
            kw = kruskal(lin, nla, nls)
            row.update({f"{name}_lin": med(lin)[0], f"{name}_nlas": med(nla)[0], f"{name}_nls": med(nls)[0],
                        f"{name}_n": (len(lin), len(nla), len(nls)), f"{name}_KW_P": float(f"{kw.pvalue:.3g}"),
                        f"{name}_lin_vs_nls_P": float(f"{ranksum(lin, nls):.3g}"),
                        f"{name}_nlas_vs_nls_P": float(f"{ranksum(nla, nls):.3g}")})
        rows.append(row)
t6v = pd.DataFrame(rows)
print(t6v.T.to_string())
print("Paper: Eh dot 0.96, 0.94, 0.86, KW P = 6.4e-5, Las vs NLs P = 0.00028, NLas vs NLs P = 0.00012; "
      "Ev dot NLas 0.85, NLs 0.38, KW P = 0.0034, NLas vs NLs P = 0.0014 (alpha 0.0167).")
                               0              1              2              3
explored                       a              a              b              b
symmetric_rule                 a              b              a              b
Ehd_lin                    0.968          0.968          0.968          0.968
Ehd_nlas                    0.98          0.956           0.98          0.956
Ehd_nls                    0.955          0.966          0.955          0.966
Ehd_n              (56, 39, 143)  (56, 78, 104)  (56, 39, 143)  (56, 78, 104)
Ehd_KW_P                  0.0837          0.409         0.0837          0.409
Ehd_lin_vs_nls_P            0.19          0.726           0.19          0.726
Ehd_nlas_vs_nls_P         0.0401          0.283         0.0401          0.283
Evd_lin                    0.911          0.911          0.911          0.911
Evd_nlas                   0.953          0.712          0.951          0.712
Evd_nls                    0.609          0.698          0.609          0.698
Evd_n               (36, 20, 78)   (36, 61, 37)   (36, 21, 80)   (36, 64, 37)
Evd_KW_P                0.000149         0.0406       0.000087         0.0318
Evd_lin_vs_nls_P        0.000953          0.164        0.00067          0.164
Evd_nlas_vs_nls_P        0.00114          0.339       0.000768          0.313
Paper: Eh dot 0.96, 0.94, 0.86, KW P = 6.4e-5, Las vs NLs P = 0.00028, NLas vs NLs P = 0.00012; Ev dot NLas 0.85, NLs 0.38, KW P = 0.0034, NLas vs NLs P = 0.0014 (alpha 0.0167).

Result: partially reproduced. The vertical part holds under the slope-sign rule for symmetric cells: Ev dot nonlinear asymmetric cells (median 0.953, n = 20) are more stable than symmetric ones (0.609, n = 78), P = 0.00114, Kruskal-Wallis P = 1.5e-4 (P = 0.000768 and 8.7e-5 with explored reading b). The horizontal part does not: Eh dot classes do not differ (Kruskal-Wallis P = 0.084; linear 0.968, asymmetric 0.98, symmetric 0.955). Under the shuffle rule neither part holds.

fig7ab-eye-contributions¶

Body position and speed influence MEC spiking more than eye movement signals, and eye position contributes more than eye velocity.

Contribution, for cells encoding the variable and at least one other, under open detail (3): (a) (full - reduced) / full, (b) 1 - (full - reduced) / full, performance the mean over the 10 folds; (c) as (a) on one held-out section (fold 1), as compute_llh_increase.m uses one test section.

In [26]:
EXPECTED_7A = {"B": (0.65, 0.065), "Bs": (0.26, 0.026), "Eh": (0.10, 0.010), "Ev": (0.14, 0.014),
               "Ehd": (0.05, 0.005), "Evd": (0.04, 0.004)}


def contributions(reading):
    out = defaultdict(list)
    for r in enc_results:
        for v, (full, red) in r.get("contrib", {}).items():
            if reading == "c":
                f_, d_ = full[0], red[0]
            else:
                f_, d_ = np.nanmean(full), np.nanmean(red)
            a = (f_ - d_) / f_ if f_ != 0 else np.nan
            out[v].append(a if reading in ("a", "c") else 1 - a)
    return {v: np.array(x) for v, x in out.items()}


for rd in ("a", "b", "c"):
    con = contributions(rd)
    kw = kruskal(*[con.get(v, []) for v in L.VARS])
    print(f"Reading ({rd}): Kruskal-Wallis chi2 = {kw.statistic:.1f}, P = {kw.pvalue:.3g} (paper 1.3e3, 5.5e-276)")
    tab = pd.DataFrame([{"var": v, "median": med(con.get(v, [np.nan]))[0], "IQR": med(con.get(v, [np.nan]))[1:3],
                         "n": len(con.get(v, [])), "paper": EXPECTED_7A[v][0],
                         "within": abs(med(con.get(v, [np.nan]))[0] - EXPECTED_7A[v][0]) <= EXPECTED_7A[v][1]} for v in L.VARS])
    print(tab.to_string(index=False))
    tests = []
    for hi_ in ("B", "Bs"):
        for lo_ in L.EYE:
            tests.append((hi_, lo_, ranksum(con.get(hi_, []), con.get(lo_, [])), med(con.get(hi_, []))[0] > med(con.get(lo_, []))[0]))
    for hi_ in ("Eh", "Ev"):
        for lo_ in ("Ehd", "Evd"):
            tests.append((hi_, lo_, ranksum(con.get(hi_, []), con.get(lo_, [])), med(con.get(hi_, []))[0] > med(con.get(lo_, []))[0]))
    ok = [p < 0.0033 and d for _, _, p, d in tests]
    print("   pairwise (first > second, P < 0.0033):", [(a, b, float(f"{p:.2g}"), d) for a, b, p, d in tests])
    print(f"   {sum(ok)} of {len(ok)} required comparisons hold; medians within tolerance: {int(tab.within.sum())} of 6")
    print("   range:", {v: (round(np.nanmin(x), 2), round(np.nanmax(x), 2)) for v, x in con.items() if len(x)})

# Variant of reading (c): each of the 10 folds in turn as the one held-out section
rows = []
for k in range(10):
    con = defaultdict(list)
    for r in enc_results:
        for v, (full, red) in r.get("contrib", {}).items():
            con[v].append((full[k] - red[k]) / full[k] if full[k] != 0 else np.nan)
    con = {v: np.array(x) for v, x in con.items()}
    ok = sum(ranksum(con[a], con[b]) < 0.0033 and med(con[a])[0] > med(con[b])[0]
             for a, b in [(h, l) for h in ("B", "Bs") for l in L.EYE] + [(h, l) for h in ("Eh", "Ev") for l in ("Ehd", "Evd")])
    rows.append({"fold": k + 1, **{v: med(con[v])[0] for v in L.VARS}, "tests_hold": ok,
                 "medians_within": sum(abs(med(con[v])[0] - EXPECTED_7A[v][0]) <= EXPECTED_7A[v][1] for v in L.VARS)})
print("\nReading (c) with each fold as the held-out section (medians; comparisons holding of 12; medians within tolerance of 6):")
print(pd.DataFrame(rows).to_string(index=False))
Reading (a): Kruskal-Wallis chi2 = 1212.5, P = 5.83e-260 (paper 1.3e3, 5.5e-276)
var  median            IQR    n  paper  within
  B   0.625 (0.352, 0.853) 1247   0.65    True
 Bs   0.305 (0.131, 0.579) 1068   0.26   False
 Eh   0.102 (0.053, 0.233)  333   0.10    True
 Ev   0.106 (0.047, 0.234)  239   0.14   False
Ehd   0.060 (0.023, 0.129)  230   0.05   False
Evd   0.046 (0.023, 0.099)  136   0.04   False
   pairwise (first > second, P < 0.0033): [('B', 'Eh', 1.4e-100, True), ('B', 'Ev', 1.8e-75, True), ('B', 'Ehd', 3e-95, True), ('B', 'Evd', 1.9e-65, True), ('Bs', 'Eh', 1.4e-39, True), ('Bs', 'Ev', 9.1e-30, True), ('Bs', 'Ehd', 2.5e-57, True), ('Bs', 'Evd', 1.4e-43, True), ('Eh', 'Ehd', 3.6e-08, True), ('Eh', 'Evd', 8.3e-10, True), ('Ev', 'Ehd', 1.1e-07, True), ('Ev', 'Evd', 2.4e-09, True)]
   12 of 12 required comparisons hold; medians within tolerance: 2 of 6
   range: {'B': (np.float64(0.02), np.float64(1.73)), 'Ehd': (np.float64(0.0), np.float64(0.92)), 'Eh': (np.float64(0.0), np.float64(1.33)), 'Bs': (np.float64(0.01), np.float64(1.59)), 'Ev': (np.float64(0.0), np.float64(1.18)), 'Evd': (np.float64(0.0), np.float64(0.89))}
Reading (b): Kruskal-Wallis chi2 = 1212.5, P = 5.83e-260 (paper 1.3e3, 5.5e-276)
var  median            IQR    n  paper  within
  B   0.375 (0.147, 0.648) 1247   0.65   False
 Bs   0.695 (0.421, 0.869) 1068   0.26   False
 Eh   0.898 (0.767, 0.947)  333   0.10   False
 Ev   0.894 (0.766, 0.953)  239   0.14   False
Ehd   0.940 (0.871, 0.977)  230   0.05   False
Evd   0.954 (0.901, 0.977)  136   0.04   False
   pairwise (first > second, P < 0.0033): [('B', 'Eh', 1.4e-100, False), ('B', 'Ev', 1.8e-75, False), ('B', 'Ehd', 3e-95, False), ('B', 'Evd', 1.9e-65, False), ('Bs', 'Eh', 1.4e-39, False), ('Bs', 'Ev', 9.1e-30, False), ('Bs', 'Ehd', 2.5e-57, False), ('Bs', 'Evd', 1.4e-43, False), ('Eh', 'Ehd', 3.6e-08, False), ('Eh', 'Evd', 8.3e-10, False), ('Ev', 'Ehd', 1.1e-07, False), ('Ev', 'Evd', 2.4e-09, False)]
   0 of 12 required comparisons hold; medians within tolerance: 0 of 6
   range: {'B': (np.float64(-0.73), np.float64(0.98)), 'Ehd': (np.float64(0.08), np.float64(1.0)), 'Eh': (np.float64(-0.33), np.float64(1.0)), 'Bs': (np.float64(-0.59), np.float64(0.99)), 'Ev': (np.float64(-0.18), np.float64(1.0)), 'Evd': (np.float64(0.11), np.float64(1.0))}
Reading (c): Kruskal-Wallis chi2 = 825.1, P = 4.29e-176 (paper 1.3e3, 5.5e-276)
var  median            IQR    n  paper  within
  B   0.638 (0.305, 0.886) 1247   0.65    True
 Bs   0.283 (0.088, 0.625) 1068   0.26    True
 Eh   0.106  (0.017, 0.26)  333   0.10    True
 Ev   0.110  (0.025, 0.24)  239   0.14   False
Ehd   0.053 (0.015, 0.134)  230   0.05    True
Evd   0.036 (0.009, 0.115)  136   0.04   False
   pairwise (first > second, P < 0.0033): [('B', 'Eh', 1.3e-71, True), ('B', 'Ev', 6.8e-57, True), ('B', 'Ehd', 1.1e-68, True), ('B', 'Evd', 1.9e-50, True), ('Bs', 'Eh', 2.5e-22, True), ('Bs', 'Ev', 5.3e-18, True), ('Bs', 'Ehd', 7.3e-32, True), ('Bs', 'Evd', 2.9e-27, True), ('Eh', 'Ehd', 0.0013, True), ('Eh', 'Evd', 1.7e-05, True), ('Ev', 'Ehd', 0.00058, True), ('Ev', 'Evd', 6.3e-06, True)]
   12 of 12 required comparisons hold; medians within tolerance: 4 of 6
   range: {'B': (np.float64(-20.36), np.float64(45.58)), 'Ehd': (np.float64(-0.73), np.float64(2.8)), 'Eh': (np.float64(-8.32), np.float64(4.53)), 'Bs': (np.float64(-6.21), np.float64(9.64)), 'Ev': (np.float64(-26.9), np.float64(7.33)), 'Evd': (np.float64(-1.62), np.float64(1.02))}
Reading (c) with each fold as the held-out section (medians; comparisons holding of 12; medians within tolerance of 6):
 fold     B    Bs    Eh    Ev   Ehd   Evd  tests_hold  medians_within
    1 0.638 0.283 0.106 0.110 0.053 0.036          12               4
    2 0.622 0.311 0.069 0.077 0.053 0.026          10               2
    3 0.606 0.285 0.079 0.115 0.043 0.031          12               2
    4 0.604 0.294 0.084 0.099 0.042 0.040          10               2
    5 0.639 0.284 0.098 0.107 0.039 0.029          12               3
    6 0.613 0.294 0.084 0.099 0.047 0.032          12               2
    7 0.635 0.300 0.091 0.071 0.051 0.037          11               4
    8 0.647 0.279 0.092 0.068 0.040 0.039          10               4
    9 0.614 0.295 0.078 0.093 0.038 0.033          12               1
   10 0.636 0.284 0.066 0.069 0.065 0.037           8               3

Result: reproduced. Under reading (c), one held-out section, B (median 0.638) and Bs (0.283) each exceed every eye variable and Eh (0.106) and Ev (0.110) each exceed Eh dot (0.053) and Ev dot (0.036), all 12 comparisons at P < 0.0033, and four of six medians are within tolerance. Under reading (a), the fold mean, the same 12 comparisons hold with two medians within tolerance (B 0.625, Eh 0.102); reading (b), the Methods' literal wording, inverts the order (B 0.375, Eh dot 0.940) and matches nothing. With each of the 10 folds as the held-out section, all 12 comparisons hold in 5 folds and four or more medians are within tolerance in 3 (folds 1, 7, 8); both hold together only in fold 1, so the outcome rests on the single-section reading with fold 1. Under reading (1b), random folds, it does not hold: reading (c) with fold 1 gives 10 of 12 comparisons and one of six medians, and no fold meets both parts (readings_folds_mallory_2021.ipynb). The outcome is therefore marked as resting on reading (1a) of the folds as well.

supp9-eye-correlation-contributions¶

Measured by correlation coefficients, in head-fixed mice body position (median 0.38) and speed (0.13) contribute more than the eye variables.

Contribution as in fig7ab-eye-contributions with the Pearson correlation of the spike train smoothed with gausswin over 20 bins and the model rate on each held-out fold as the performance (Methods, "Computing contribution to model performance"), from the same selected and reduced models (mec_ln.fit_kfold). Readings of open detail (3) as for fig7ab: (a) (full - reduced) / full of the fold means, (b) 1 minus that, (c) fold 1 alone.

In [27]:
EXPECTED_S9 = {"B": (0.38, 0.038), "Bs": (0.13, 0.013)}


def contributions_corr(reading):
    out = defaultdict(list)
    for r in enc_results:
        for v, (full, red) in r.get("contrib_corr", {}).items():
            if full is None or red is None:
                continue
            f_, d_ = (full[0], red[0]) if reading == "c" else (np.nanmean(full), np.nanmean(red))
            a = (f_ - d_) / f_ if f_ != 0 else np.nan
            out[v].append(a if reading in ("a", "c") else 1 - a)
    return {v: np.array(x) for v, x in out.items()}


for rd in ("a", "b", "c"):
    con = contributions_corr(rd)
    kw = kruskal(*[con.get(v, []) for v in L.VARS])
    meds = {v: med(con.get(v, [np.nan])) for v in L.VARS}
    print(f"Reading ({rd}): Kruskal-Wallis chi2 = {kw.statistic:.1f}, P = {kw.pvalue:.3g} (paper 1.4e3, 5.4e-292)")
    print("   median [IQR, n]:", meds)
    largest = max(L.VARS, key=lambda v: meds[v][0] if np.isfinite(meds[v][0]) else -np.inf)
    exceed = all(meds[h][0] > meds[e][0] for h in ("B", "Bs") for e in L.EYE)
    within = {v: bool(abs(meds[v][0] - e) <= t) for v, (e, t) in EXPECTED_S9.items()}
    print(f"   largest: {largest}; B and Bs exceed every eye variable: {exceed}; medians within tolerance: {within} "
          f"(paper B 0.38, Bs 0.13)")
    print("   range:", {v: (round(np.nanmin(x), 2), round(np.nanmax(x), 2)) for v, x in con.items() if np.isfinite(x).any()})
print("Cells with a correlation contribution:", sum(1 for r in enc_results if r.get("contrib_corr")),
      "; fold correlations not computable (flat rate or spikes):",
      int(sum(np.isnan(r["contrib_corr"][v][1]).sum() for r in enc_results for v in r.get("contrib_corr", {}))))
Reading (a): Kruskal-Wallis chi2 = 1284.2, P = 1.71e-275 (paper 1.4e3, 5.4e-292)
   median [IQR, n]: {'B': (0.37, 0.185, 0.578, 1247), 'Bs': (0.159, 0.07, 0.317, 1068), 'Eh': (0.058, 0.024, 0.118, 333), 'Ev': (0.061, 0.022, 0.127, 239), 'Ehd': (0.028, 0.01, 0.056, 230), 'Evd': (0.024, 0.01, 0.05, 136)}
   largest: B; B and Bs exceed every eye variable: True; medians within tolerance: {'B': True, 'Bs': False} (paper B 0.38, Bs 0.13)
   range: {'B': (np.float64(-0.0), np.float64(0.98)), 'Ehd': (np.float64(-0.0), np.float64(0.7)), 'Eh': (np.float64(-0.01), np.float64(0.57)), 'Bs': (np.float64(-0.01), np.float64(1.01)), 'Ev': (np.float64(-0.0), np.float64(0.61)), 'Evd': (np.float64(-0.01), np.float64(0.31))}
Reading (b): Kruskal-Wallis chi2 = 1284.2, P = 1.71e-275 (paper 1.4e3, 5.4e-292)
   median [IQR, n]: {'B': (0.63, 0.422, 0.815, 1247), 'Bs': (0.841, 0.683, 0.93, 1068), 'Eh': (0.942, 0.882, 0.976, 333), 'Ev': (0.939, 0.873, 0.978, 239), 'Ehd': (0.972, 0.944, 0.99, 230), 'Evd': (0.976, 0.95, 0.99, 136)}
   largest: Evd; B and Bs exceed every eye variable: False; medians within tolerance: {'B': False, 'Bs': False} (paper B 0.38, Bs 0.13)
   range: {'B': (np.float64(0.02), np.float64(1.0)), 'Ehd': (np.float64(0.3), np.float64(1.0)), 'Eh': (np.float64(0.43), np.float64(1.01)), 'Bs': (np.float64(-0.01), np.float64(1.01)), 'Ev': (np.float64(0.39), np.float64(1.0)), 'Evd': (np.float64(0.69), np.float64(1.01))}
Reading (c): Kruskal-Wallis chi2 = 932.7, P = 2.25e-199 (paper 1.4e3, 5.4e-292)
   median [IQR, n]: {'B': (0.393, 0.171, 0.592, 1247), 'Bs': (0.152, 0.049, 0.345, 1068), 'Eh': (0.061, 0.01, 0.15, 333), 'Ev': (0.056, 0.014, 0.155, 239), 'Ehd': (0.026, 0.005, 0.074, 230), 'Evd': (0.018, 0.004, 0.064, 136)}
   largest: B; B and Bs exceed every eye variable: True; medians within tolerance: {'B': True, 'Bs': False} (paper B 0.38, Bs 0.13)
   range: {'B': (np.float64(-2.35), np.float64(1.43)), 'Ehd': (np.float64(-0.14), np.float64(0.58)), 'Eh': (np.float64(-0.49), np.float64(0.77)), 'Bs': (np.float64(-0.86), np.float64(1.32)), 'Ev': (np.float64(-0.17), np.float64(1.01)), 'Evd': (np.float64(-0.15), np.float64(5.79))}
Cells with a correlation contribution: 1309 ; fold correlations not computable (flat rate or spikes): 2

Result: partially reproduced. Under reading (a), Kruskal-Wallis P = 1.7e-275, B is the largest contributor (median 0.370, within 0.38 +- 0.038) and B and Bs (0.159) exceed every eye variable (Eh 0.058, Ev 0.061, Eh dot 0.028, Ev dot 0.024); the Bs median is outside 0.13 +- 0.013. Reading (c) gives the same order (B 0.393, Bs 0.152); reading (b), the literal wording, inverts it.

fig7e-eye-no-clustering¶

Cells with similar tuning to eye position or velocity do not tend to encode similar additional variables.

Criterion: for each primary variable, model-derived tuning curves (50 bins on the visualizing range), rows mean-subtracted and scaled to unit range, projected on two principal components; for each secondary variable, the mean distance from each labelled cell to its k nearest labelled neighbours, k = 1 to 10, against 1000 label scrambles (a standard number; the Methods give none), P the fraction of scrambled distances smaller than observed; reproduced when no combination and k gives P < 0.005.

In [28]:
rng_7e = np.random.default_rng(7)
N_SCRAMBLE = 1000


def knn_mean(D, idx, k):
    sub = D[np.ix_(idx, idx)]
    np.fill_diagonal(sub, np.inf)
    kk = min(k, len(idx) - 1)
    return float(np.mean(np.sort(sub, axis=1)[:, :kk])) if kk > 0 else np.nan


rows = []
for prim in L.VARS:
    rs = [r for r in enc_results if prim in r["encoded"]]
    if len(rs) < 5:
        continue
    M = []
    for r in rs:
        g, c = r["curves"][prim]
        lo, hi = L.vis_range(prim, PREPS[r["session"]]["lims"])
        x = np.linspace(lo, hi, 50)
        M.append(np.interp(x, g, c))
    M = np.array(M)
    M = M - M.mean(1, keepdims=True)
    M = M / np.maximum(np.ptp(M, axis=1, keepdims=True), 1e-12)
    M = M - M.mean(0)
    U, S, Vt = np.linalg.svd(M, full_matrices=False)
    Z = M @ Vt[:2].T
    D = np.sqrt(((Z[:, None, :] - Z[None, :, :]) ** 2).sum(-1))
    for sec in L.VARS:
        if sec == prim:
            continue
        lab = np.array([sec in r["encoded"] for r in rs])
        n_lab = int(lab.sum())
        if n_lab < 2 or n_lab == len(rs):   # nothing to compare: too few labelled, or every cell labelled
            rows.append({"primary": prim, "secondary": sec, "n_cells": len(rs), "n_labelled": n_lab, "min_P": np.nan})
            continue
        obs = [knn_mean(D, np.flatnonzero(lab), k) for k in range(1, 11)]
        null = np.zeros((N_SCRAMBLE, 10))
        kmax = min(10, n_lab - 1)
        for i in range(N_SCRAMBLE):
            idx = rng_7e.choice(len(rs), n_lab, replace=False)
            sub = D[np.ix_(idx, idx)]
            np.fill_diagonal(sub, np.inf)
            part = np.sort(np.partition(sub, kmax - 1, axis=1)[:, :kmax], axis=1)
            for k in range(1, 11):
                null[i, k - 1] = part[:, :min(k, kmax)].mean()
        P = [(null[:, k] < obs[k]).mean() for k in range(10)]
        rows.append({"primary": prim, "secondary": sec, "n_cells": len(rs), "n_labelled": n_lab,
                     "min_P": min(P), "k_of_min": int(np.argmin(P)) + 1, "n_k_below_0.005": int(sum(p < 0.005 for p in P))})
t7e = pd.DataFrame(rows)
print(t7e.to_string(index=False))
print("Combinations not testable (fewer than 2 labelled cells, or every cell labelled):", int(t7e.min_P.isna().sum()))
print("Combinations with any k at P < 0.005:", int((t7e.min_P < 0.005).sum()), "of", int(t7e.min_P.notna().sum()))
print("Eye primaries only:", int((t7e[t7e.primary.isin(L.EYE)].min_P < 0.005).sum()), "of",
      int(t7e[t7e.primary.isin(L.EYE)].min_P.notna().sum()))
primary secondary  n_cells  n_labelled  min_P  k_of_min  n_k_below_0.005
      B        Bs     1938        1017  0.489        10                0
      B        Eh     1938         304  0.291         1                0
      B        Ev     1938         223  0.950         1                0
      B       Ehd     1938         192  0.711        10                0
      B       Evd     1938         128  0.818         2                0
     Bs         B     1187        1017  0.353        10                0
     Bs        Eh     1187         196  0.902         4                0
     Bs        Ev     1187         158  0.475        10                0
     Bs       Ehd     1187         181  0.792         1                0
     Bs       Evd     1187          94  0.199         2                0
     Eh         B      341         304  0.603         4                0
     Eh        Bs      341         196  0.368        10                0
     Eh        Ev      341          58  0.529         2                0
     Eh       Ehd      341          83  0.000        10                6
     Eh       Evd      341          42  0.673         2                0
     Ev         B      243         223  0.530        10                0
     Ev        Bs      243         158  0.034         2                0
     Ev        Eh      243          58  0.005        10                0
     Ev       Ehd      243          33  0.343        10                0
     Ev       Evd      243          38  0.566         1                0
    Ehd         B      238         192  0.723         7                0
    Ehd        Bs      238         181  0.153         2                0
    Ehd        Eh      238          83  0.092         3                0
    Ehd        Ev      238          33  0.011         2                0
    Ehd       Evd      238          38  0.130         2                0
    Evd         B      137         128  0.395         5                0
    Evd        Bs      137          94  0.000         6                8
    Evd        Eh      137          42  0.320         1                0
    Evd        Ev      137          38  0.050         1                0
    Evd       Ehd      137          38  0.000         1                2
Combinations not testable (fewer than 2 labelled cells, or every cell labelled): 0
Combinations with any k at P < 0.005: 3 of 30
Eye primaries only: 3 of 20

Result: not reproduced. 3 of the 30 combinations give P < 0.005 at some k: Eh cells that also encode Eh dot (6 of 10 k), Ev dot cells that also encode Bs (8 of 10 k) and Ev dot cells that also encode Eh dot (2 of 10 k), each with P below 0.001. The other 27 show no clustering.

supp7e-eye-velocity-extrema-near-zero¶

Peaks and valleys of nonlinear eye velocity tuning curves lie mostly near 0 (170 of 224 horizontal, 82 of 138 vertical within half the range), although their medians differ from 0.

Criterion: as fig2c-velocity-extrema-near-zero, the half range halfway between 0 and the maximum or minimum velocity of the range; reproduced when both binomial tests give P < 0.05 with a majority within half range and both counts are within tolerance.

In [29]:
for rd2 in ("a", "b"):
    print(f"Explored reading ({rd2}):")
    for name, df, exp in (("Ehd", ehd, 170), ("Evd", evd, 82)):
        c = classified(df, rd2)
        nl = c[c.order > 1]
        locs, within = [], []
        for _, row in nl.iterrows():
            x, cv = CURVES[(row.session, row.unit, name)]
            lo, hi = x.min(), x.max()
            for xp in L.peaks_valleys(x, cv):
                locs.append(xp)
                within.append((xp >= 0 and xp < hi / 2) or (xp < 0 and xp > lo / 2))
        k, n = int(sum(within)), len(within)
        wp = stats.wilcoxon(locs).pvalue if n > 1 else np.nan
        print(f"   {name}: {len(nl)} nonlinear cells, {n} peaks or valleys, {k} within half range "
              f"(paper {exp}, tol {exp * 0.1:.1f}); binomial Z = {zbin(k, n):.2f}, P = {binom(k, n):.3g}; "
              f"median location {np.median(locs) if n else np.nan:.3f}, signed-rank P = {wp:.3g}")
print("Paper: horizontal 170/224, Z = 7.68, P = 1e-8; vertical 82/138, Z = 2.13, P = 0.03; medians differ from 0.")
Explored reading (a):
   Ehd: 182 nonlinear cells, 192 peaks or valleys, 145 within half range (paper 170, tol 17.0); binomial Z = 7.07, P = 7.97e-13; median location 0.417, signed-rank P = 0.00253
   Evd: 98 nonlinear cells, 125 peaks or valleys, 72 within half range (paper 82, tol 8.2); binomial Z = 1.70, P = 0.107; median location 0.085, signed-rank P = 0.7
Explored reading (b):
   Ehd: 182 nonlinear cells, 192 peaks or valleys, 145 within half range (paper 170, tol 17.0); binomial Z = 7.07, P = 7.97e-13; median location 0.417, signed-rank P = 0.00253
   Evd: 101 nonlinear cells, 129 peaks or valleys, 74 within half range (paper 82, tol 8.2); binomial Z = 1.67, P = 0.113; median location 0.085, signed-rank P = 0.832
Paper: horizontal 170/224, Z = 7.68, P = 1e-8; vertical 82/138, Z = 2.13, P = 0.03; medians differ from 0.

Result: partially reproduced. For Eh dot, 145 of 192 peaks or valleys lie within half the range (Z = 7.07, P = 8.0e-13), and their median (0.417) differs from 0 (P = 0.0025), as in the paper. For Ev dot the majority within half range is not significant (72 of 125, P = 0.107), and its median does not differ from 0 (P = 0.70). Both counts are outside tolerance (paper 170 and 82).

supp4-eye-ln-conservative¶

For the four eye variables in the head-fixed data, shuffle-based significance tests (within-cell and pooled) identify far more cells than the LN model, and nearly all LN model cells are also found by shuffling, so the LN model is a conservative estimate.

Pearson correlation of the eye variable with the spike count over the kept bins, against 500 circular shifts of the spike train by more than 20 s (Methods, "Comparison between LN and shuffling-based methods"); significant below the 2.5th or above the 97.5th percentile of the unit's own shifts (within-cell) or of all units' shifts pooled (pooled). LN cells are the units encoding the variable, all classes.

In [30]:
rng_s4 = np.random.default_rng(41)
SH4 = {v: [] for v in L.EYE}
for r in RESULTS:
    pp = PREPS[r["session"]]
    inv = np.argsort(pp["order"])
    y = DATA[r["session"]]["counts"][r["unit"], pp["keep"]].astype(float)
    for v in L.EYE:
        rr, sh = L.shuffle_corr(pp["vals"][v][inv], y, rng_s4)
        SH4[v].append((rr, sh, v in r["encoded"], r["mouse"]))
rows = []
for v, lst in SH4.items():
    r_ = np.array([a for a, _, _, _ in lst])
    shm = np.vstack([b for _, b, _, _ in lst])
    ln = np.array([c for _, _, c, _ in lst])
    within = (r_ < np.nanpercentile(shm, 2.5, axis=1)) | (r_ > np.nanpercentile(shm, 97.5, axis=1))
    plo, phi = np.nanpercentile(shm, [2.5, 97.5])
    pooled = (r_ < plo) | (r_ > phi)
    lin_w, lin_p = within.copy(), pooled.copy()
    if v in ("Ehd", "Evd"):
        # the Methods' symmetric test: correlations below and above 0 beyond the 5th and 95th percentiles
        # of their shuffles in opposite directions (V or inverted V), within the cell or pooled
        sides = [r.get("side", {}).get(v) for r in RESULTS]
        pn = np.nanpercentile(np.concatenate([s[2] for s in sides if s is not None]), [5, 95])
        pq = np.nanpercentile(np.concatenate([s[3] for s in sides if s is not None]), [5, 95])
        sym_w, sym_p = np.zeros(len(sides), bool), np.zeros(len(sides), bool)
        for j, s in enumerate(sides):
            if s is None:
                continue
            rn, rp, shn, shp = s
            a5, a95, b5, b95 = np.nanpercentile(shn, 5), np.nanpercentile(shn, 95), np.nanpercentile(shp, 5), np.nanpercentile(shp, 95)
            sym_w[j] = (rn < a5 and rp > b95) or (rn > a95 and rp < b5)
            sym_p[j] = (rn < pn[0] and rp > pq[1]) or (rn > pn[1] and rp < pq[0])
        within, pooled = within | sym_w, pooled | sym_p
    rows.append({"var": v, "LN cells": int(ln.sum()), "within-cell": int(within.sum()), "pooled": int(pooled.sum()),
                 "LN found, linear test only": round(float(lin_w[ln].mean()), 3),
                 "LN found by within-cell": round(float(within[ln].mean()), 3), "LN found by pooled": round(float(pooled[ln].mean()), 3),
                 "both > LN": bool(within.sum() > ln.sum() and pooled.sum() > ln.sum()),
                 ">= 90% by within-cell": bool(within[ln].mean() >= 0.9)})
t4e = pd.DataFrame(rows)
print(t4e.to_string(index=False))
print("Units:", len(RESULTS), "; units with no spike (r undefined):", int(np.isnan([a for a, _, _, _ in SH4["Eh"]]).sum()))
print("Pooled thresholds (2.5th, 97.5th):", {v: tuple(np.round(np.nanpercentile(np.vstack([b for _, b, _, _ in l]), [2.5, 97.5]), 4)) for v, l in SH4.items()})
var  LN cells  within-cell  pooled  LN found, linear test only  LN found by within-cell  LN found by pooled  both > LN  >= 90% by within-cell
 Eh       341         1132     885                       0.718                    0.718               0.642       True                  False
 Ev       243          771     410                       0.609                    0.609               0.638       True                  False
Ehd       238         1309    1158                       0.794                    0.933               0.916       True                   True
Evd       137         1178    1024                       0.781                    0.891               0.898       True                  False
Units: 2861 ; units with no spike (r undefined): 3
Pooled thresholds (2.5th, 97.5th): {'Eh': (np.float64(-0.0196), np.float64(0.0199)), 'Ev': (np.float64(-0.0305), np.float64(0.031)), 'Ehd': (np.float64(-0.0111), np.float64(0.0113)), 'Evd': (np.float64(-0.0106), np.float64(0.0108))}

Result: not reproduced. Each shuffle method finds more units than the LN model for every eye variable (within-cell 1132, 771, 1309 and 1178 units, pooled 885, 410, 1158 and 1024, against 341, 243, 238 and 137 LN cells for Eh, Ev, Eh dot and Ev dot; the velocity counts include the Methods' symmetric test), but within-cell shuffling finds only 0.718 and 0.609 of the Eh and Ev LN cells and 0.891 of the Ev dot cells, below the 90% the criterion takes for "nearly all"; Eh dot reaches 0.933. Without the symmetric test the velocity fractions are 0.794 and 0.781.

supp5-eye-model-raw-tuning-agree¶

Model-derived and raw tuning curves are highly correlated for the eye variables (median 0.85 to 0.90).

Raw tuning curves in 20 bins of the visualizing range over the kept bins, spikes over occupancy, smoothed with rlowess over 7 bins (Methods, "Raw tuning curves"); Pearson correlation with the model-derived curve resampled at the raw curve's bin centres. All LN cells of each eye variable.

In [31]:
EXP5E = {"Eh": (0.90, 0.090), "Ev": (0.85, 0.085), "Ehd": (0.85, 0.085), "Evd": (0.87, 0.087)}
cor5 = {v: [] for v in EXP5E}
for r in enc_results:
    pp = PREPS[r["session"]]
    inv = np.argsort(pp["order"])
    y = DATA[r["session"]]["counts"][r["unit"], pp["keep"]].astype(float)
    for v in EXP5E:
        if v in r["encoded"]:
            lo, hi = L.vis_range(v, pp["lims"])
            c, raw = L.raw_tuning(pp["vals"][v][inv], y, lo, hi)
            g, mc = r["curves"][v]
            cor5[v].append(L.model_raw_corr(g, mc, c, raw))
rows = []
for v, (val, tol) in EXP5E.items():
    m = med(cor5[v])
    rows.append({"var": v, "median": m[0], "IQR": m[1:3], "n": len(cor5[v]), "not computable": int(np.isnan(cor5[v]).sum()),
                 "paper": val, "within": bool(abs(m[0] - val) <= tol)})
t5e = pd.DataFrame(rows)
print(t5e.to_string(index=False))
print("Medians within tolerance:", int(t5e.within.sum()), "of 4 (three needed)")
print("Range:", {v: (round(np.nanmin(x), 2), round(np.nanmax(x), 2)) for v, x in cor5.items() if np.isfinite(x).any()})
var  median            IQR   n  not computable  paper  within
 Eh   0.911 (0.776, 0.972) 341               0   0.90    True
 Ev   0.930 (0.842, 0.976) 243               0   0.85    True
Ehd   0.850 (0.683, 0.936) 238               0   0.85    True
Evd   0.896 (0.708, 0.949) 137               0   0.87    True
Medians within tolerance: 4 of 4 (three needed)
Range: {'Eh': (np.float64(-0.89), np.float64(1.0)), 'Ev': (np.float64(-0.51), np.float64(1.0)), 'Ehd': (np.float64(-0.77), np.float64(0.99)), 'Evd': (np.float64(-0.23), np.float64(0.99))}

Result: reproduced. The median correlation of model-derived and raw tuning curves is 0.911 for Eh (n = 341), 0.930 for Ev (243), 0.850 for Eh dot (238) and 0.896 for Ev dot (137), all four within tolerance of the paper's 0.90, 0.85, 0.85 and 0.87.

Summary¶

Claim Outcome
headfixed-session-link (link) reproduced
fig4f-eye-movement-distributions reproduced
fig4j-eye-encoding-cells reproduced
fig4k-eye-conjunctive reproduced
fig5a-eh-nasal-temporal-similar partially reproduced (hemispheres not testable)
fig5b-ev-up-down-similar reproduced
fig5-eye-position-stability partially reproduced
fig5av-eh-linear-most-stable reproduced
fig5bv-ev-low-order-more-stable partially reproduced (assumed: folds in turn; reproduced under random folds)
fig6-eye-velocity-linear-nasal partially reproduced (assumed: folds in turn)
fig6-eye-velocity-nonlinear-temporal not reproduced
fig6-eye-velocity-stability not reproduced
fig6v-asymmetric-more-stable partially reproduced (assumed: folds in turn)
fig7ab-eye-contributions reproduced (reading c, fold 1, folds in turn; assumed, fails under random folds)
fig7c-head-fixed-model-fit reproduced
fig7e-eye-no-clustering not reproduced
supp7e-eye-velocity-extrema-near-zero partially reproduced
supp4-eye-ln-conservative not reproduced
supp5-eye-model-raw-tuning-agree reproduced
supp9-eye-correlation-contributions partially reproduced
supp3-eye-low-false-positives blocked, too large
freely moving claims see freely_moving_mallory_2021.ipynb (on figshare Datasets 1 and 2)
fig8c, fig8e blocked, data missing (no file marks a no-landmark track)
methods-hemispheres-similar blocked, metadata insufficient
supp12-no-false-eye-detection reproduced (in simulated_eye_mallory_2021.ipynb)

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

How the analysis differs from the paper's. The LN pipeline is reimplemented in Python from the paper's Methods and the spline code it links (Newton fits in place of fminunc, same objective). Open details are run under the readings the claims file names, and reading (1b) of the folds is run through every claim in readings_folds_mallory_2021.ipynb. Four outcomes hold only under reading (1a), folds in turn, and are marked as resting on it: fig7ab, fig5bv (which would be reproduced under (1b)), fig6-eye-velocity-linear-nasal and fig6v; the reading (2b), clipping each variable in place of dropping bins, was not run for lack of time. Preference reading (b) follows the claims file's wording (the larger absolute slope), with the round-1 reading kept as variant (r). Positive horizontal eye values are taken as nasal and positive vertical values as upward, from the Methods.

What was found about the dataset. The open field files lack the pitch and roll of Cohort 1, which the paper deposited on figshare. The dandiset does not say which 11 of its 20 head-fixed files are the paper's; the paper's figshare deposit does. In two files the spike index of unit 0 wrapped at 2**16. No trial table marks a track or its landmarks, so the Figure 8 blocks cannot be found. Eye position is labelled metres and eye velocity "unknown"; both are in % of eye width. The hemisphere of each recording is not recorded. Ten behaviour-only files repeat head-fixed sessions, and two insertions were converted twice.

In [32]:
print(f"Notebook time: {(time.time() - STARTED) / 60:.1f} min; peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
Notebook time: 41.2 min; peak memory 3.92 GB