Mallory, Hardcastle et al. (2021): every head-fixed LN claim under reading (1b) random folds, (2a) drop¶
Companion to reproduce_mallory_2021.ipynb (dandiset 000053, version 0.210819.0345; the paper, the
claims file, the choice of version and the data check are there). The claims file leaves two details
of the LN pipeline open and asks for both readings of each: (1) how the 10-s sections are assigned to
the 10 folds, (a) in turn as compute_test_train_ind.m does, or (b) at random; (2) whether bins
outside a variable's inner 98% are (a) dropped or (b) clipped to the range. The main notebook runs
(1a, 2a). This one runs open detail (1) under reading (b), 10-s sections of the kept bins assigned to the 10 folds at random (balanced, a seed per session), and open detail (2) under reading (a), bins outside any variable's inner 98% dropped, on the same 11 recordings (selected as in the main notebook's link
claim), and repeats every downstream analysis of the main notebook on its fits, with the same code,
so that each claim's dependence on the reading can be seen. Each claim is judged in the main
notebook; the results here are variants.
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("ecephys")
print(f"dandiset {L.DANDISET_ID} version {L.DANDISET_VERSION}: {len(urls)} assets")
SESSIONS, fsd = L.paper_sessions(urls)
print("Sessions matched to the figshare deposit:", sum(p is not None for p in SESSIONS), "of", len(SESSIONS))
FOLD_MODE, RANGE_MODE = L.FOLDS_RANDOM, L.RANGE_DROP
READING = "(1b) random folds, (2a) drop"
print("Reading:", READING)
dandiset 000053 version 0.210819.0345: 20 assets
Sessions matched to the figshare deposit: 11 of 11 Reading: (1b) random folds, (2a) drop
DATA = {p: L.load_session(urls[p]) for p in SESSIONS}
print(pd.DataFrame([{"session": p.split("/")[1][:40], "mouse": s["subject"], "units": s["counts"].shape[0],
"frames": len(s["t"]), "repaired": len(s["repaired"]), "spikes_outside": int(s["n_outside"].sum())}
for p, s in DATA.items()]).to_string(index=False))
print("Units:", sum(s["counts"].shape[0] for s in DATA.values()))
session mouse units frames repaired spikes_outside sub-npJ5_ses-20190505_obj-10plzqh_behavi npJ5 389 102281 0 0 sub-npI1_ses-20190413_behavior+ecephys.n npI1 77 127222 0 46207 sub-npI1_ses-20190415_behavior+ecephys.n npI1 173 44061 0 0 sub-npI1_ses-20190416_behavior+ecephys.n npI1 408 78990 0 0 sub-npI3_ses-20190420_behavior+ecephys.n npI3 286 451580 1 770029 sub-npI4_ses-20190421_obj-1h2xem6_behavi npI4 254 84626 1 0 sub-npI4_ses-20190423_behavior+ecephys.n npI4 537 74852 0 0 sub-npJ1_ses-20190523_behavior+ecephys.n npJ1 303 75904 0 0 sub-npJ2_ses-20190511_behavior+ecephys.n npJ2 106 117785 0 165111 sub-npJ3_ses-20190504_behavior+ecephys.n npJ3 210 124590 0 180520 sub-npJ4_ses-20190511_behavior+ecephys.n npJ4 118 117863 0 174338 Units: 2861
The LN model under reading (1b) random folds, (2a) drop¶
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, RANGE_MODE)
folds = L.fold_labels(prep["n_keep"], FOLD_MODE, seed=2000 + si)
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%), 193 s
sub-npI1_ses-20190413_behavior+ecephys.n: 77 units, 114479 of 127139 valid bins kept (90.0%), 63 s
sub-npI1_ses-20190415_behavior+ecephys.n: 173 units, 39686 of 43916 valid bins kept (90.4%), 24 s
sub-npI1_ses-20190416_behavior+ecephys.n: 408 units, 70409 of 78548 valid bins kept (89.6%), 153 s
sub-npI3_ses-20190420_behavior+ecephys.n: 286 units, 124446 of 139687 valid bins kept (89.1%), 293 s
sub-npI4_ses-20190421_obj-1h2xem6_behavi: 254 units, 75592 of 82843 valid bins kept (91.2%), 167 s
sub-npI4_ses-20190423_behavior+ecephys.n: 537 units, 65690 of 72728 valid bins kept (90.3%), 198 s
sub-npJ1_ses-20190523_behavior+ecephys.n: 303 units, 62849 of 69506 valid bins kept (90.4%), 111 s
sub-npJ2_ses-20190511_behavior+ecephys.n: 106 units, 105925 of 117415 valid bins kept (90.2%), 86 s
sub-npJ3_ses-20190504_behavior+ecephys.n: 210 units, 109513 of 120926 valid bins kept (90.6%), 171 s
sub-npJ4_ses-20190511_behavior+ecephys.n: 118 units, 105554 of 115999 valid bins kept (91.0%), 70 s LN model: 2861 units in 1531 s; peak memory 1.09 GB Units with no spike in the kept bins (nothing to fit): 3 Units whose selected model failed the final test against 0: 884
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.
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 614 0.215 711 71.1 False
Eh 282 0.099 343 34.3 False
Ev 177 0.062 234 23.4 False
Ehd 231 0.081 244 24.4 True
Evd 99 0.035 135 13.5 False
Per-variable counts within tolerance: 1 of 4
Any variable encoded: 1964 ; B 1814 ; Bs 1092
Variant, the final test on the last model tried, as forward_search_kfold.m does:
count measured fraction paper tol within
eye_any 614 0.215 711 71.1 False
Eh 281 0.098 343 34.3 False
Ev 177 0.062 234 23.4 False
Ehd 231 0.081 244 24.4 True
Evd 101 0.035 135 13.5 False
By mouse (fraction of units encoding any eye variable):
units eye_cells fraction
mouse
npI1 658 111 0.169
npI3 286 140 0.490
npI4 791 155 0.196
npJ1 303 43 0.142
npJ2 106 34 0.321
npJ3 210 55 0.262
npJ4 118 12 0.102
npJ5 389 64 0.165
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 9 0.052
sub-npI1/sub-npI1_ses-20190416_behavior+ecephys.nwb 408 80 0.196
sub-npI3/sub-npI3_ses-20190420_behavior+ecephys.nwb 286 140 0.490
sub-npI4/sub-npI4_ses-20190421_obj-1h2xem6_behavior+ecephys.nwb 254 101 0.398
sub-npI4/sub-npI4_ses-20190423_behavior+ecephys.nwb 537 54 0.101
sub-npJ1/sub-npJ1_ses-20190523_behavior+ecephys.nwb 303 43 0.142
sub-npJ2/sub-npJ2_ses-20190511_behavior+ecephys.nwb 106 34 0.321
sub-npJ3/sub-npJ3_ses-20190504_behavior+ecephys.nwb 210 55 0.262
sub-npJ4/sub-npJ4_ses-20190511_behavior+ecephys.nwb 118 12 0.102
sub-npJ5/sub-npJ5_ses-20190505_obj-10plzqh_behavior+ecephys.nwb 389 64 0.165
Result under this reading: outside tolerance. 614 units encode an eye variable (paper 711, tolerance 71.1): Eh 282, Ev 177, Eh dot 231, Ev dot 99, only the Eh dot count within tolerance. (The first printed line names the main readings because the cell is the main notebook's; the fits above are under (1b, 2a).)
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.
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.964 0.96 0.096 True
eye cells encoding more than one eye variable 0.238 0.28 0.028 False
all cells encoding B alone 0.232 0.23 0.023 True
Eye cells: 614 ; encoding an eye variable alone (no B, no Bs): 22
Most common encoded sets:
encoded
(none) 897
B 664
B,Bs 599
Bs 87
B,Bs,Eh 87
B,Bs,Ehd 84
B,Bs,Ev 82
B,Eh 77
B,Ev 36
B,Bs,Eh,Ehd 30
B,Bs,Evd 21
B,Ehd 19
B,Eh,Ehd 18
B,Bs,Ehd,Evd 16
B,Evd 15
Result under this reading: two of three within tolerance. 0.964 of eye cells also encode B or Bs and 0.232 of all units B alone; 0.238 encode more than one eye variable (paper 0.28, tolerance 0.028).
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.
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: 1964 (paper 2191, tolerance 219.1)
Median llh increase, compute_llh.m (nats per spike x log 2): 0.0534 [0.0231 to 0.1145] (paper 0.05 [0.02 to 0.11], tolerance 0.005)
Variant, in bits per spike (nats / log 2): 0.1110 [0.0480 to 0.2384]
Variant, nats per spike: 0.0770
Range of the plotted quantity: 0.0003 1.3551
By mouse: {'npI1': 0.05, 'npI3': 0.096, 'npI4': 0.0524, 'npJ1': 0.0458, 'npJ2': 0.0737, 'npJ3': 0.0589, 'npJ4': 0.0106, 'npJ5': 0.0435}
Result under this reading: the median within tolerance, the count just outside. 1964 units encode a variable (lower limit 1971.9) with median 0.0534 in compute_llh.m's units.
# 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': 1814, 'Bs': 1092, 'Eh': 282, 'Ehd': 231, 'Ev': 177, 'Evd': 99}
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.52 0.66 0.86 1.0 0.55 0.75 0.9 1.0
Evd 0.91 1.00 1.00 1.0 0.95 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': (282, {0.0: 2, 1.0: 88, 2.0: 139, 3.0: 33, 4.0: 18, 5.0: 2}), 'Ehd': (231, {1.0: 52, 2.0: 154, 3.0: 18, 4.0: 6, 5.0: 1}), 'Ev': (131, {1.0: 30, 2.0: 39, 3.0: 49, 4.0: 11, 5.0: 2}), 'Evd': (99, {1.0: 22, 2.0: 53, 3.0: 2, 4.0: 20, 5.0: 2})}
not explored: {'Eh': 0, 'Ehd': 0, 'Ev': 46, 'Evd': 0}
reading (b) explored: {'Eh': (282, {0.0: 2, 1.0: 88, 2.0: 139, 3.0: 33, 4.0: 18, 5.0: 2}), 'Ehd': (231, {1.0: 52, 2.0: 154, 3.0: 18, 4.0: 6, 5.0: 1}), 'Ev': (131, {1.0: 30, 2.0: 39, 3.0: 49, 4.0: 11, 5.0: 2}), 'Evd': (99, {1.0: 22, 2.0: 53, 3.0: 2, 4.0: 20, 5.0: 2})}
not explored: {'Eh': 0, 'Ehd': 0, 'Ev': 46, '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.
# 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 127 of 282 (0.450), Z = -1.67, binomial P = 0.108
on cells classified under explored reading (a): 127 of 280, P = 0.135
on cells classified under explored reading (b): 127 of 280, P = 0.135
Preference reading (b): nasal-preferring 132 of 282 (0.468), Z = -1.07, binomial P = 0.311
on cells classified under explored reading (a): 131 of 280, P = 0.31
on cells classified under explored reading (b): 131 of 280, P = 0.31
Preference reading (r): nasal-preferring 128 of 282 (0.454), Z = -1.55, binomial P = 0.136
on cells classified under explored reading (a): 127 of 280, P = 0.135
on cells classified under explored reading (b): 127 of 280, P = 0.135
Paper: 170 of 343, Z = 0.11, P = 0.91; ipsilateral 38/87, contralateral 132/256.
By mouse, nasal fraction (reading a): {'npI1': 0.18, 'npI3': 0.45, 'npI4': 0.66, 'npJ1': 0.31, 'npJ2': 0.21, 'npJ3': 0.65, 'npJ4': 0.4, 'npJ5': 0.68}
The hemisphere of each recording is not in the dandiset (electrode location 'unknown'); the two hemisphere tests cannot be run.
Result under this reading: no preference. 127 to 132 of 282 Eh cells prefer nasal positions, P = 0.108 to 0.311 over the three preference readings.
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).
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: 177 Explored reading (a): 131 classified (paper 177, tolerance 17.7) preference reading (a): upward 69 of 131 (0.527), Z = 0.61, P = 0.6 preference reading (b): upward 60 of 131 (0.458), Z = -0.96, P = 0.382 preference reading (r): upward 69 of 131 (0.527), Z = 0.61, P = 0.6 Explored reading (b): 131 classified (paper 177, tolerance 17.7) preference reading (a): upward 69 of 131 (0.527), Z = 0.61, P = 0.6 preference reading (b): upward 60 of 131 (0.458), Z = -0.96, P = 0.382 preference reading (r): upward 69 of 131 (0.527), Z = 0.61, P = 0.6 Paper: 88 of 177, Z = 0, P = 1.
Result under this reading: no preference, the classified count outside tolerance. 131 Ev cells are classified (paper 177, tolerance 17.7); 60 to 69 prefer upward positions, P = 0.38 to 0.60.
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).
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.893, 0.735, 0.966, 282) (paper 0.87), Ev classified (0.62, -0.018, 0.918, 131) (paper 0.72), B (0.721, 0.529, 0.848, 1814) (paper 0.71)
Kruskal-Wallis chi2 = 145.08, P = 3.13e-32 (paper 103.51, 3.3e-23)
Eh vs B rank-sum P = 8.1e-33 (paper 8.6e-25); Ev vs B P = 0.0376 (paper 0.91); alpha 0.0167
Explored reading (b) for the Ev cells:
median [IQR, n]: Eh (0.893, 0.735, 0.966, 282) (paper 0.87), Ev classified (0.62, -0.018, 0.918, 131) (paper 0.72), B (0.721, 0.529, 0.848, 1814) (paper 0.71)
Kruskal-Wallis chi2 = 145.08, P = 3.13e-32 (paper 103.51, 3.3e-23)
Eh vs B rank-sum P = 8.1e-33 (paper 8.6e-25); Ev vs B P = 0.0376 (paper 0.91); alpha 0.0167
Variant, all Ev cells: (0.66, 0.169, 0.902, 177), Ev vs B P = 0.0328
Range of stability values: {'B': (np.float64(-0.52), np.float64(0.99)), 'Bs': (np.float64(-0.89), np.float64(0.99)), 'Eh': (np.float64(-0.97), np.float64(1.0)), 'Ev': (np.float64(-0.92), np.float64(1.0)), 'Ehd': (np.float64(-0.55), 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.79 0.80 0.53 0.71 0.71 0.54 0.78 0.81
Bs 0.83 0.83 0.68 0.83 0.79 0.72 0.61 0.81
Eh 0.87 0.92 0.87 0.90 0.96 0.87 0.87 0.94
Ehd 0.90 0.98 0.93 0.89 0.97 0.96 0.91 0.98
Ev 0.63 0.94 0.46 0.78 0.89 0.77 NaN 0.28
Evd 0.47 0.98 0.92 0.96 NaN 0.94 NaN NaN
Result under this reading: as in the main notebook. Eh (0.893) is more stable than B (0.721), P = 8.1e-33; Ev (0.620) does not differ from B at alpha 0.0167 (P = 0.0376); the Ev median is outside tolerance.
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).
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.95, 0.867, 0.983, 88), quadratic (0.886, 0.744, 0.96, 139), higher (0.778, 0.593, 0.893, 53) Kruskal-Wallis chi2 = 27.35, P = 1.15e-06; rank-sum P: 1 vs 2 0.00036, 1 vs >2 9.82e-07, 2 vs >2 0.00724 (alpha 0.0167) Eh, explored reading (b): linear (0.95, 0.867, 0.983, 88), quadratic (0.886, 0.744, 0.96, 139), higher (0.778, 0.593, 0.893, 53) Kruskal-Wallis chi2 = 27.35, P = 1.15e-06; rank-sum P: 1 vs 2 0.00036, 1 vs >2 9.82e-07, 2 vs >2 0.00724 (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 under this reading: the tests hold. Linear 0.950, quadratic 0.886, higher 0.778; Kruskal-Wallis P = 1.2e-6; linear beats quadratic (P = 0.00036) and higher (P = 9.8e-7); two of three medians within tolerance (higher order is outside 0.66 +- 0.066).
fig5bv-ev-low-order-more-stable¶
Linearly or quadratically tuned vertical eye position cells are more stable than those with greater curvature.
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.855, 0.465, 0.95, 30), quadratic (0.838, 0.521, 0.96, 39), higher (0.266, -0.336, 0.689, 62) Kruskal-Wallis chi2 = 23.80, P = 6.79e-06; rank-sum P: 1 vs 2 0.818, 1 vs >2 0.00024, 2 vs >2 1.73e-05 (alpha 0.0167) Ev, explored reading (b): linear (0.855, 0.465, 0.95, 30), quadratic (0.838, 0.521, 0.96, 39), higher (0.266, -0.336, 0.689, 62) Kruskal-Wallis chi2 = 23.80, P = 6.79e-06; rank-sum P: 1 vs 2 0.818, 1 vs >2 0.00024, 2 vs >2 1.73e-05 (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 under this reading: the tests hold and two of three medians are within tolerance. Linear 0.855, quadratic 0.838, higher 0.266; Kruskal-Wallis P = 6.8e-6; linear and quadratic each beat higher (P = 0.00024 and 1.7e-5).
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).
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: 231 ; Ev dot cells: 99 Explored reading (a): classified Eh dot 231, Ev dot 99 linear Eh dot 52 (paper 43, tol 4.3); nasal-preferring 33 (paper 30, tol 3.0), Z = 1.94, P = 0.0704 (paper Z = 2.44, P = 0.014) linear Ev dot 22 (paper 29, tol 2.9); upward 13, Z = 0.85, P = 0.523 (paper 16/29, P = 0.71) Explored reading (b): classified Eh dot 231, Ev dot 99 linear Eh dot 52 (paper 43, tol 4.3); nasal-preferring 33 (paper 30, tol 3.0), Z = 1.94, P = 0.0704 (paper Z = 2.44, P = 0.014) linear Ev dot 22 (paper 29, tol 2.9); upward 13, Z = 0.85, P = 0.523 (paper 16/29, P = 0.71)
Result under this reading: the nasal test fails. 52 linear Eh dot cells, 33 nasal (P = 0.070); 22 linear Ev dot cells, 13 upward (P = 0.52); the linear counts are outside tolerance.
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.
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 179 41 138 21 1.0000 77 18 59 6 0.2379
a a b 179 41 138 24 0.3489 77 18 59 3 0.0075
a a r 179 41 138 21 1.0000 77 18 59 7 0.4807
a b a 179 84 95 45 0.5856 77 46 31 15 0.0259
a b b 179 84 95 57 0.0014 77 46 31 12 0.0016
a b r 179 84 95 45 0.5856 77 46 31 21 0.6587
b a a 179 41 138 21 1.0000 77 18 59 6 0.2379
b a b 179 41 138 24 0.3489 77 18 59 3 0.0075
b a r 179 41 138 21 1.0000 77 18 59 7 0.4807
b b a 179 84 95 45 0.5856 77 46 31 15 0.0259
b b b 179 84 95 57 0.0014 77 46 31 12 0.0016
b b r 179 84 95 45 0.5856 77 46 31 21 0.6587
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 1 False
b b b 1 False
b b r 1 False
Result under this reading: no combination holds. With the shuffle rule and preference reading (b), 57 of 84 asymmetric Eh dot cells prefer temporal movement (P = 0.0014), but the Ev dot test then finds a preference (P = 0.0016); at most one of the four class counts is 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.
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.959, 0.876, 0.991, 231) (paper 0.93), Ev dot (0.919, 0.686, 0.976, 99) (paper 0.74), Bs (0.791, 0.567, 0.908, 1092) (paper 0.84)
Kruskal-Wallis chi2 = 183.75, P = 1.26e-40 (paper 90.78, 1.9e-20)
Eh dot vs Bs P = 3.29e-40 (paper 6.5e-18); Ev dot vs Bs P = 1e-05 (paper 0.00061); alpha 0.0167
Variant, classified cells only (explored reading a): Eh dot (0.959, 0.876, 0.991, 231), Ev dot (0.919, 0.686, 0.976, 99); KW P = 1.26e-40; Eh dot vs Bs P = 3.29e-40; Ev dot vs Bs P = 1e-05
Variant, classified cells only (explored reading b): Eh dot (0.959, 0.876, 0.991, 231), Ev dot (0.919, 0.686, 0.976, 99); KW P = 1.26e-40; Eh dot vs Bs P = 3.29e-40; Ev dot vs Bs P = 1e-05
Range: {'Ehd': (np.float64(-0.55), np.float64(1.0)), 'Evd': (np.float64(-0.97), np.float64(1.0)), 'Bs': (np.float64(-0.89), np.float64(0.99))}
Result under this reading: Ev dot is more stable than Bs, the opposite of the claim. Eh dot 0.959 and Ev dot 0.919 against Bs 0.791 (P = 3.3e-40 and 1e-5).
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.
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.973 0.95 0.973 0.95 Ehd_nls 0.939 0.955 0.939 0.955 Ehd_n (52, 41, 138) (52, 84, 95) (52, 41, 138) (52, 84, 95) Ehd_KW_P 0.0258 0.388 0.0258 0.388 Ehd_lin_vs_nls_P 0.0957 0.456 0.0957 0.456 Ehd_nlas_vs_nls_P 0.0121 0.428 0.0121 0.428 Evd_lin 0.954 0.954 0.954 0.954 Evd_nlas 0.924 0.866 0.924 0.866 Evd_nls 0.883 0.926 0.883 0.926 Evd_n (22, 18, 59) (22, 46, 31) (22, 18, 59) (22, 46, 31) Evd_KW_P 0.125 0.0977 0.125 0.0977 Evd_lin_vs_nls_P 0.0662 0.639 0.0662 0.639 Evd_nlas_vs_nls_P 0.19 0.158 0.19 0.158 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 under this reading: neither part holds. Eh dot Kruskal-Wallis P = 0.026 or 0.39 and nonlinear asymmetric against symmetric P = 0.012 or 0.43; Ev dot P = 0.13 or 0.098.
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.
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 = 1009.5, P = 5.39e-216 (paper 1.3e3, 5.5e-276)
var median IQR n paper within
B 0.641 (0.338, 0.881) 1150 0.65 True
Bs 0.324 (0.131, 0.603) 1005 0.26 False
Eh 0.112 (0.057, 0.232) 278 0.10 False
Ev 0.141 (0.057, 0.277) 174 0.14 True
Ehd 0.056 (0.022, 0.125) 223 0.05 False
Evd 0.049 (0.02, 0.138) 98 0.04 False
pairwise (first > second, P < 0.0033): [('B', 'Eh', 4.4e-81, True), ('B', 'Ev', 2.3e-51, True), ('B', 'Ehd', 1.4e-93, True), ('B', 'Evd', 5e-46, True), ('Bs', 'Eh', 5.8e-32, True), ('Bs', 'Ev', 2.5e-17, True), ('Bs', 'Ehd', 7.7e-59, True), ('Bs', 'Evd', 6.8e-29, True), ('Eh', 'Ehd', 1.5e-10, True), ('Eh', 'Evd', 1.4e-06, True), ('Ev', 'Ehd', 5.9e-12, True), ('Ev', 'Evd', 5.6e-08, True)]
12 of 12 required comparisons hold; medians within tolerance: 2 of 6
range: {'B': (np.float64(0.0), np.float64(1.77)), 'Bs': (np.float64(0.01), np.float64(1.66)), 'Eh': (np.float64(0.0), np.float64(1.2)), 'Ehd': (np.float64(0.0), np.float64(0.88)), 'Ev': (np.float64(0.01), np.float64(1.34)), 'Evd': (np.float64(0.0), np.float64(0.79))}
Reading (b): Kruskal-Wallis chi2 = 1009.5, P = 5.39e-216 (paper 1.3e3, 5.5e-276) var median IQR n paper within B 0.359 (0.119, 0.662) 1150 0.65 False Bs 0.676 (0.397, 0.869) 1005 0.26 False Eh 0.888 (0.768, 0.943) 278 0.10 False Ev 0.859 (0.723, 0.943) 174 0.14 False Ehd 0.944 (0.875, 0.978) 223 0.05 False Evd 0.951 (0.862, 0.98) 98 0.04 False
pairwise (first > second, P < 0.0033): [('B', 'Eh', 4.4e-81, False), ('B', 'Ev', 2.3e-51, False), ('B', 'Ehd', 1.4e-93, False), ('B', 'Evd', 5e-46, False), ('Bs', 'Eh', 5.8e-32, False), ('Bs', 'Ev', 2.5e-17, False), ('Bs', 'Ehd', 7.7e-59, False), ('Bs', 'Evd', 6.8e-29, False), ('Eh', 'Ehd', 1.5e-10, False), ('Eh', 'Evd', 1.4e-06, False), ('Ev', 'Ehd', 5.9e-12, False), ('Ev', 'Evd', 5.6e-08, False)]
0 of 12 required comparisons hold; medians within tolerance: 0 of 6
range: {'B': (np.float64(-0.77), np.float64(1.0)), 'Bs': (np.float64(-0.66), np.float64(0.99)), 'Eh': (np.float64(-0.2), np.float64(1.0)), 'Ehd': (np.float64(0.12), np.float64(1.0)), 'Ev': (np.float64(-0.34), np.float64(0.99)), 'Evd': (np.float64(0.21), np.float64(1.0))}
Reading (c): Kruskal-Wallis chi2 = 631.3, P = 3.44e-134 (paper 1.3e3, 5.5e-276)
var median IQR n paper within
B 0.613 (0.261, 0.893) 1150 0.65 True
Bs 0.292 (0.085, 0.624) 1005 0.26 False
Eh 0.075 (0.016, 0.219) 278 0.10 False
Ev 0.096 (0.014, 0.238) 174 0.14 False
Ehd 0.034 (0.011, 0.111) 223 0.05 False
Evd 0.031 (0.007, 0.135) 98 0.04 False
pairwise (first > second, P < 0.0033): [('B', 'Eh', 3.4e-52, True), ('B', 'Ev', 2.6e-37, True), ('B', 'Ehd', 1.1e-60, True), ('B', 'Evd', 2e-30, True), ('Bs', 'Eh', 5.1e-21, True), ('Bs', 'Ev', 1.3e-14, True), ('Bs', 'Ehd', 9.9e-35, True), ('Bs', 'Evd', 2e-17, True), ('Eh', 'Ehd', 0.00016, True), ('Eh', 'Evd', 0.0044, True), ('Ev', 'Ehd', 0.00068, True), ('Ev', 'Evd', 0.0088, True)]
10 of 12 required comparisons hold; medians within tolerance: 1 of 6
range: {'B': (np.float64(-23.22), np.float64(225.25)), 'Bs': (np.float64(-205.17), np.float64(20.57)), 'Eh': (np.float64(-54.23), np.float64(14.01)), 'Ehd': (np.float64(-47.39), np.float64(8.49)), 'Ev': (np.float64(-19.0), np.float64(4.3)), 'Evd': (np.float64(-102.96), np.float64(3.48))}
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.613 0.292 0.075 0.096 0.034 0.031 10 1
2 0.655 0.262 0.097 0.135 0.042 0.045 11 4
3 0.633 0.323 0.095 0.133 0.043 0.037 11 4
4 0.671 0.276 0.077 0.112 0.050 0.042 10 4
5 0.648 0.282 0.089 0.090 0.037 0.037 11 3
6 0.668 0.286 0.087 0.072 0.039 0.033 10 2
7 0.603 0.280 0.093 0.094 0.060 0.037 8 4
8 0.601 0.319 0.126 0.113 0.039 0.032 12 1
9 0.584 0.301 0.106 0.076 0.049 0.056 9 2
10 0.607 0.308 0.107 0.165 0.054 0.036 12 3
Result under this reading: the tests hold under reading (a). All 12 comparisons hold with two of six medians within tolerance (B 0.641, Ev 0.141).
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.
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 = 1101.7, P = 5.79e-236 (paper 1.4e3, 5.4e-292)
median [IQR, n]: {'B': (0.37, 0.175, 0.58, 1150), 'Bs': (0.162, 0.069, 0.316, 1005), 'Eh': (0.06, 0.027, 0.124, 278), 'Ev': (0.065, 0.028, 0.121, 174), 'Ehd': (0.023, 0.009, 0.056, 223), 'Evd': (0.024, 0.008, 0.06, 98)}
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.99)), 'Bs': (np.float64(-0.03), np.float64(0.84)), 'Eh': (np.float64(-0.0), np.float64(0.53)), 'Ehd': (np.float64(-0.0), np.float64(0.7)), 'Ev': (np.float64(0.0), np.float64(0.53)), 'Evd': (np.float64(-0.0), np.float64(0.38))}
Reading (b): Kruskal-Wallis chi2 = 1101.7, P = 5.79e-236 (paper 1.4e3, 5.4e-292)
median [IQR, n]: {'B': (0.63, 0.42, 0.825, 1150), 'Bs': (0.838, 0.684, 0.931, 1005), 'Eh': (0.94, 0.876, 0.973, 278), 'Ev': (0.935, 0.879, 0.972, 174), 'Ehd': (0.977, 0.944, 0.991, 223), 'Evd': (0.976, 0.94, 0.992, 98)}
largest: Ehd; 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.01), np.float64(1.0)), 'Bs': (np.float64(0.16), np.float64(1.03)), 'Eh': (np.float64(0.47), np.float64(1.0)), 'Ehd': (np.float64(0.3), np.float64(1.0)), 'Ev': (np.float64(0.47), np.float64(1.0)), 'Evd': (np.float64(0.62), np.float64(1.0))}
Reading (c): Kruskal-Wallis chi2 = 810.2, P = 7.11e-173 (paper 1.4e3, 5.4e-292)
median [IQR, n]: {'B': (0.363, 0.142, 0.606, 1150), 'Bs': (0.154, 0.046, 0.318, 1005), 'Eh': (0.041, 0.005, 0.119, 278), 'Ev': (0.05, 0.011, 0.122, 174), 'Ehd': (0.015, 0.002, 0.058, 223), 'Evd': (0.015, 0.0, 0.065, 98)}
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(-3.23), np.float64(1.58)), 'Bs': (np.float64(-0.52), np.float64(1.27)), 'Eh': (np.float64(-1.03), np.float64(0.73)), 'Ehd': (np.float64(-0.28), np.float64(0.77)), 'Ev': (np.float64(-0.31), np.float64(0.86)), 'Evd': (np.float64(-0.51), np.float64(0.28))}
Cells with a correlation contribution: 1197 ; fold correlations not computable (flat rate or spikes): 0
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.
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 1814 964 0.329 8 0
B Eh 1814 259 0.716 10 0
B Ev 1814 163 0.606 2 0
B Ehd 1814 195 0.578 8 0
B Evd 1814 92 0.271 1 0
Bs B 1092 964 0.411 10 0
Bs Eh 1092 166 0.930 1 0
Bs Ev 1092 121 0.598 8 0
Bs Ehd 1092 172 0.924 10 0
Bs Evd 1092 70 0.264 8 0
Eh B 282 259 0.656 1 0
Eh Bs 282 166 0.028 1 0
Eh Ev 282 30 0.025 1 0
Eh Ehd 282 77 0.018 3 0
Eh Evd 282 29 0.013 1 0
Ev B 177 163 0.532 10 0
Ev Bs 177 121 0.046 1 0
Ev Eh 177 30 0.424 8 0
Ev Ehd 177 21 0.031 1 0
Ev Evd 177 19 0.008 10 0
Ehd B 231 195 0.774 7 0
Ehd Bs 231 172 0.076 1 0
Ehd Eh 231 77 0.001 7 7
Ehd Ev 231 21 0.002 1 1
Ehd Evd 231 30 0.095 2 0
Evd B 99 92 0.083 5 0
Evd Bs 99 70 0.010 10 0
Evd Eh 99 29 0.175 1 0
Evd Ev 99 19 0.094 2 0
Evd Ehd 99 30 0.003 10 1
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 under this reading: clustering found. 3 of 30 combinations reach P < 0.005 at some k (Eh dot with Eh and with Ev, Ev dot with Eh dot).
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.
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: 179 nonlinear cells, 189 peaks or valleys, 146 within half range (paper 170, tol 17.0); binomial Z = 7.49, P = 2.57e-14; median location 0.428, signed-rank P = 0.00141 Evd: 77 nonlinear cells, 97 peaks or valleys, 58 within half range (paper 82, tol 8.2); binomial Z = 1.93, P = 0.0671; median location 0.107, signed-rank P = 0.114 Explored reading (b): Ehd: 179 nonlinear cells, 189 peaks or valleys, 146 within half range (paper 170, tol 17.0); binomial Z = 7.49, P = 2.57e-14; median location 0.428, signed-rank P = 0.00141 Evd: 77 nonlinear cells, 97 peaks or valleys, 58 within half range (paper 82, tol 8.2); binomial Z = 1.93, P = 0.0671; median location 0.107, signed-rank P = 0.114 Paper: horizontal 170/224, Z = 7.68, P = 1e-8; vertical 82/138, Z = 2.13, P = 0.03; medians differ from 0.
Result under this reading: the horizontal part holds. Eh dot 146 of 189 within half range (P = 2.6e-14); Ev dot 58 of 97 (P = 0.067).
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.
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 282 1132 885 0.766 0.766 0.670 True False
Ev 177 771 410 0.655 0.655 0.638 True False
Ehd 231 1309 1158 0.810 0.939 0.926 True True
Evd 99 1178 1024 0.788 0.889 0.899 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 under this reading: within-cell shuffling finds under 90% of the Eh, Ev and Ev dot LN cells (0.766, 0.655, 0.889); Eh dot 0.939.
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.
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.922 (0.75, 0.978) 282 0 0.90 True
Ev 0.934 (0.843, 0.98) 177 0 0.85 True
Ehd 0.833 (0.699, 0.938) 231 0 0.85 True
Evd 0.898 (0.725, 0.955) 99 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.87), np.float64(1.0)), 'Ehd': (np.float64(-0.54), np.float64(0.99)), 'Evd': (np.float64(0.0), np.float64(0.99))}
Result under this reading: four of four within tolerance (0.922, 0.934, 0.833, 0.898).
Summary¶
Under reading (1b, 2a) the eye-cell counts fall to 614 (one of four per-variable counts within tolerance), against 718 under the main readings, so the claims that depend on the counts are judged on reading (1a) in the main notebook. Most downstream results keep their direction: fig5a and fig5b still find no preference; fig5 stability is again partial; fig5av and fig5bv hold their tests, and fig5bv meets two of its medians here, which its criterion would count as reproduced; fig6 linear loses its nasal test; fig6 nonlinear and fig6 stability still fail (Ev dot is more stable than Bs here); fig6v fails in both parts; fig7ab holds its tests under reading (a), but under reading (c), the one recorded, fold 1 gives 10 of 12 comparisons and one of six medians and no fold meets both parts. Four outcomes of the main notebook (fig5bv, fig6 linear, fig6v and fig7ab) thus depend on reading (1) and are marked as resting on reading (1a); supp9-eye keeps its order; fig7e again finds 3 clustered combinations; supp4-eye again falls short of 90% for three variables; supp5-eye holds. Reading (2b), clipping, was not run, for time.
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.
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: 32.7 min; peak memory 1.15 GB