Mallory, Hardcastle et al. (2021): simulated data without eye information (Supp. Fig. 12)¶
Companion to reproduce_mallory_2021.ipynb (dandiset 000053, version 0.210819.0345; the paper, the
claims file, the choice of version, the data check and the link of the 11 recordings are there). This
notebook tests one claim, supp12-no-false-eye-detection, which needs the LN pipeline run a second
time, on simulated spike trains, and so does not fit in the main notebook's time limit.
| Claim | Status |
|---|---|
| supp12-no-false-eye-detection | tested here, under readings (1a, 2a) of the LN pipeline, as the main notebook's counts |
Method, from the paper. Methods, "Generating simulated data without eye-encoded information": "we first identified the selected variables of a given cell (i.e. by fitting a series of LN models) and identified the model parameters corresponding to each variable. We then generated a new spiketrain using all parameters except those relating to eye movements ... r = exp(A * w) ... By deleting the relevant entries in A and w that correspond to eye movement information, we generated a new r, and drew from a Poisson distribution with mean given by each element". The LN pipeline is then rerun on the simulated spike trains (the claim's criterion). The legend of Supp. Fig. 12e gives the mutual information of each eye variable with B (four pairs) and of each eye velocity with Bs (two pairs) in each session, against 100 shuffles.
Choices not fixed by the paper. (i) The parameters are those of the selected model fitted to the
whole session (sel_full, the parameters the forward search carries between steps), the reading of
"the model parameters" taken here; the code's param_mean, the mean over folds, is the other. (ii)
Which cells are simulated. The procedure starts from a cell's selected variables, so cells that
encode nothing have no model to simulate from. The main test simulates every cell that encodes an
eye variable (an assumption: these are the cells whose eye tuning the analysis questions; a cell
without eye terms is simulated from its unchanged model, so an eye detection there would be the
ordinary false positive rate of Supp. Fig. 3). A seeded random sample of 300 of the encoding cells
without eye terms is simulated as well, and the count it would add over all such cells is shown.
(iii) Mutual information: 20 equal-width bins over each variable's inner 98% of the kept bins (a
standard choice), shuffles by random permutation of the eye variable over time (the legend's
"shuffled data"), and, as a stricter variant, by circular shifts of more than 20 s, which keep its
autocorrelation.
import os
import time
import resource
import warnings
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)
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))
dandiset 000053 version 0.210819.0345: 20 assets
Sessions matched to the figshare deposit: 11 of 11
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"])} 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 sub-npJ5_ses-20190505_obj-10plzqh_behavi npJ5 389 102281 sub-npI1_ses-20190413_behavior+ecephys.n npI1 77 127222 sub-npI1_ses-20190415_behavior+ecephys.n npI1 173 44061 sub-npI1_ses-20190416_behavior+ecephys.n npI1 408 78990 sub-npI3_ses-20190420_behavior+ecephys.n npI3 286 451580 sub-npI4_ses-20190421_obj-1h2xem6_behavi npI4 254 84626 sub-npI4_ses-20190423_behavior+ecephys.n npI4 537 74852 sub-npJ1_ses-20190523_behavior+ecephys.n npJ1 303 75904 sub-npJ2_ses-20190511_behavior+ecephys.n npJ2 106 117785 sub-npJ3_ses-20190504_behavior+ecephys.n npJ3 210 124590 sub-npJ4_ses-20190511_behavior+ecephys.n npJ4 118 117863 Units: 2861
The LN model on the data, readings (1a, 2a)¶
The forward search alone (no tuning curves or refits), with the same bins, folds and seeds as the main notebook, so the selections are the main notebook's.
SUBSET = int(os.environ.get("MALLORY_SUBSET", "0")) # 0: every unit (develop on a few)
t0 = time.time()
ORIG, PREP = [], {}
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]
res = L.analyse_session(P, Y, processes=4, with_extras=False)
for i, r in enumerate(res):
r.update({"session": p, "si": si, "mouse": s["subject"], "unit": i})
ORIG += res
PREP[p] = (prep, P)
print(f"LN model on the data: {len(ORIG)} units in {time.time() - t0:.0f} s; peak memory "
f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
orig = pd.DataFrame([{"session": r["session"], "unit": r["unit"], "encoded": ",".join(r["encoded"]),
**{v: v in r["encoded"] for v in L.VARS}} for r in ORIG])
orig["eye_any"] = orig[L.EYE].any(axis=1)
orig["any"] = orig.encoded != ""
print("Encoding units:", int(orig["any"].sum()), "of", len(orig), "; eye units:", int(orig.eye_any.sum()))
print("Units per variable:", {v: int(orig[v].sum()) for v in L.VARS})
LN model on the data: 2861 units in 1361 s; peak memory 1.91 GB
Encoding units: 2140 of 2861 ; eye units: 718
Units per variable: {'B': 1938, 'Bs': 1187, 'Eh': 341, 'Ev': 243, 'Ehd': 238, 'Evd': 137}
supp12-no-false-eye-detection¶
Eye variables share information with body position and speed, yet when eye-related contributions are deleted from simulated spike trains, the LN model does not falsely detect eye tuning.
Criterion: spike trains are drawn from each cell's fitted model with eye terms removed and the LN pipeline rerun; mutual information between each eye variable and B or Bs against 100 shuffles. Reproduced when the data mutual information exceeds all shuffles in most sessions and, for each eye variable, the cells detected in the simulated data are at most 10% of those in the original.
Part 1: mutual information of the eye variables with B and Bs, per session, over the kept bins.
rng_mi = np.random.default_rng(1200)
PAIRS = [("Eh", "B"), ("Ev", "B"), ("Ehd", "B"), ("Evd", "B"), ("Ehd", "Bs"), ("Evd", "Bs")]
NB, NSH = 20, 100
def codes(x, lo, hi):
return np.clip(((x - lo) / (hi - lo) * NB).astype(int), 0, NB - 1)
def mi_bits(a, b):
j = np.bincount(a * NB + b, minlength=NB * NB).reshape(NB, NB) / len(a)
pa, pb = j.sum(1, keepdims=True), j.sum(0, keepdims=True)
m = j > 0
return float((j[m] * np.log2(j[m] / (pa @ pb)[m])).sum())
rows = []
for si, p in enumerate(SESSIONS):
prep = PREP[p][0]
cd = {v: codes(prep["vals"][v], *prep["lims"][v]) for v in L.VARS}
n = len(cd["B"])
for e, b in PAIRS:
mi = mi_bits(cd[e], cd[b])
perm = np.array([mi_bits(rng_mi.permutation(cd[e]), cd[b]) for _ in range(NSH)])
shifts = rng_mi.integers(int(20 / L.DT), n - int(20 / L.DT), NSH)
circ = np.array([mi_bits(np.roll(cd[e], k), cd[b]) for k in shifts])
rows.append({"session": si + 1, "pair": f"{e}-{b}", "MI": mi, "perm_max": perm.max(), "circ_max": circ.max(),
"above_perm": mi > perm.max(), "above_circ": mi > circ.max()})
MI = pd.DataFrame(rows)
print(MI.pivot(index="session", columns="pair", values="MI").round(3).to_string())
summ = MI.groupby("pair").agg(sessions=("session", "size"), above_all_permutations=("above_perm", "sum"),
above_all_circular_shifts=("above_circ", "sum"), MI_median=("MI", "median"),
perm_max_median=("perm_max", "median"), circ_max_median=("circ_max", "median"))
print(summ.round(4).to_string())
print("Range of the data MI (bits):", round(MI.MI.min(), 4), "to", round(MI.MI.max(), 4))
pair Eh-B Ehd-B Ehd-Bs Ev-B Evd-B Evd-Bs
session
1 0.084 0.054 0.046 0.016 0.031 0.015
2 0.136 0.166 0.100 0.086 0.059 0.016
3 0.130 0.115 0.064 0.067 0.103 0.046
4 0.093 0.083 0.049 0.054 0.091 0.026
5 0.293 0.035 0.137 0.182 0.023 0.044
6 0.115 0.070 0.027 0.088 0.058 0.028
7 0.178 0.100 0.057 0.067 0.045 0.022
8 0.168 0.061 0.101 0.118 0.037 0.032
9 0.057 0.100 0.024 0.027 0.054 0.010
10 0.033 0.073 0.150 0.087 0.073 0.089
11 0.071 0.101 0.101 0.056 0.060 0.019
sessions above_all_permutations above_all_circular_shifts MI_median perm_max_median circ_max_median
pair
Eh-B 11 11 11 0.1149 0.0036 0.0549
Ehd-B 11 11 11 0.0833 0.0036 0.0211
Ehd-Bs 11 11 11 0.0640 0.0038 0.0119
Ev-B 11 11 10 0.0673 0.0039 0.0277
Evd-B 11 11 11 0.0575 0.0036 0.0180
Evd-Bs 11 11 11 0.0258 0.0037 0.0107
Range of the data MI (bits): 0.0102 to 0.2928
Part 2: simulated spike trains without the eye terms. For each simulated cell the rate is exp of the intercept plus the B and Bs terms of its selected model (fitted on the whole session), over the kept bins, and spikes are drawn from a Poisson distribution with that mean (a seed per session). The forward search is then rerun with the same bins and folds.
rng_pick = np.random.default_rng(1201)
N_NONEYE = 300
noneye = orig[orig["any"] & ~orig.eye_any].index.to_numpy()
pick = set(rng_pick.choice(noneye, min(N_NONEYE, len(noneye)), replace=False).tolist())
SIM_IDX = sorted(set(orig.index[orig.eye_any]) | pick)
print(f"Simulated: {int(orig.eye_any.sum())} eye cells and {len(pick)} of {len(noneye)} encoding cells without eye terms")
t0 = time.time()
SIM = []
for si, p in enumerate(SESSIONS):
prep, P = PREP[p]
idx = [k for k in SIM_IDX if ORIG[k]["si"] == si]
if not idx:
continue
rng_sim = np.random.default_rng(12000 + si)
Ysim = np.zeros((len(idx), prep["n_keep"]))
rates = []
for row, k in enumerate(idx):
r = ORIG[k]
lay = L._layout(prep["blocks"], r["encoded"])
eta = np.full(prep["n_keep"], r["sel_full"][0])
for v in r["encoded"]:
if v not in L.EYE:
eta += prep["blocks"][v] @ r["sel_full"][lay[v]]
lam = np.exp(eta)
Ysim[row] = rng_sim.poisson(lam)
rates.append((lam.mean() / L.DT, r["n_spikes"] / prep["n_keep"] / L.DT))
res = L.analyse_session(P, Ysim, processes=4, with_extras=False)
for k, rr, (sim_hz, data_hz) in zip(idx, res, rates):
SIM.append({"k": k, "session": p, "orig": ORIG[k]["encoded"], "sim": rr["encoded"],
"rate_sim_hz": sim_hz, "rate_data_hz": data_hz, "spikes_sim": rr["n_spikes"]})
print(f"LN model on the simulated data: {len(SIM)} units in {time.time() - t0:.0f} s; peak memory "
f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
sim = pd.DataFrame(SIM)
sim["eye_cell"] = sim.orig.apply(lambda e: any(v in L.EYE for v in e))
print("Mean rate, simulated against data (Hz), median over cells: eye cells",
round(sim[sim.eye_cell].rate_sim_hz.median(), 2), "vs", round(sim[sim.eye_cell].rate_data_hz.median(), 2),
"; other cells", round(sim[~sim.eye_cell].rate_sim_hz.median(), 2), "vs", round(sim[~sim.eye_cell].rate_data_hz.median(), 2))
print("Simulated units encoding nothing:", int((sim.sim.apply(len) == 0).sum()), "of", len(sim))
Simulated: 718 eye cells and 300 of 1422 encoding cells without eye terms
LN model on the simulated data: 1018 units in 392 s; peak memory 2.08 GB Mean rate, simulated against data (Hz), median over cells: eye cells 7.48 vs 4.84 ; other cells 4.26 vs 4.26 Simulated units encoding nothing: 32 of 1018
scale = len(noneye) / max(len(pick), 1)
rows = []
for v in L.VARS:
n_orig = int(orig[v].sum())
se = sim[sim.eye_cell]
so = sim[~sim.eye_cell]
det_eye = int(se.sim.apply(lambda e: v in e).sum())
det_other = int(so.sim.apply(lambda e: v in e).sum())
kept = int(se.apply(lambda r: v in r.orig and v in r.sim, axis=1).sum()) if v in L.EYE else None
rows.append({"variable": v, "original": n_orig, "simulated_eye_cells": det_eye,
"of_which_had_it": kept, "simulated_sample_other": det_other,
"other_scaled_to_all": round(det_other * scale, 1),
"fraction_eye_cells": round(det_eye / n_orig, 3) if n_orig else np.nan,
"fraction_with_scaled_other": round((det_eye + det_other * scale) / n_orig, 3) if n_orig else np.nan,
"at_most_10pct": (det_eye / n_orig <= 0.10) if (n_orig and v in L.EYE) else None,
"at_most_10pct_with_other": ((det_eye + det_other * scale) / n_orig <= 0.10) if (n_orig and v in L.EYE) else None})
T12 = pd.DataFrame(rows)
print(T12.to_string(index=False))
# B and Bs detection among the simulated eye cells that encoded them, as a check that the simulation keeps the body tuning
for v in ("B", "Bs"):
had = sim[sim.eye_cell & sim.orig.apply(lambda e: v in e)]
print(f"{v}: kept in {int(had.sim.apply(lambda e: v in e).sum())} of {len(had)} simulated eye cells that encoded it")
by_s = sim[sim.eye_cell].groupby("session").apply(
lambda d: pd.Series({"eye_cells": len(d), "eye_detected": int(d.sim.apply(lambda e: any(v in L.EYE for v in e)).sum())}))
by_s.index = [SESSIONS.index(p) + 1 for p in by_s.index]
by_s = by_s.sort_index()
print("Per session, simulated eye cells with any eye variable detected:")
print(by_s.T.to_string())
variable original simulated_eye_cells of_which_had_it simulated_sample_other other_scaled_to_all fraction_eye_cells fraction_with_scaled_other at_most_10pct at_most_10pct_with_other
B 1938 635 NaN 281 1331.9 0.328 1.015 None None
Bs 1187 456 NaN 144 682.6 0.384 0.959 None None
Eh 341 0 0.0 0 0.0 0.000 0.000 True True
Ev 243 2 1.0 0 0.0 0.008 0.008 True True
Ehd 238 2 0.0 0 0.0 0.008 0.008 True True
Evd 137 0 0.0 0 0.0 0.000 0.000 True True
B: kept in 635 of 635 simulated eye cells that encoded it
Bs: kept in 456 of 456 simulated eye cells that encoded it
Per session, simulated eye cells with any eye variable detected:
1 2 3 4 5 6 7 8 9 10 11
eye_cells 67 22 13 112 149 125 68 53 36 56 17
eye_detected 0 0 1 1 0 1 1 0 0 0 0
Result: reproduced, under the assumptions stated in the header. The data mutual information exceeds all 100 permutation shuffles in 11 of 11 sessions for each of the six pairs (median 0.026 to 0.115 bits against a median shuffle maximum of 0.004), and all 100 circular shifts in 11 of 11 sessions for five pairs and 10 of 11 for Ev with B. On the simulated spike trains of the 718 eye cells, with the B and Bs terms kept and the eye terms deleted, the rerun LN pipeline detects Eh in 0 cells, Ev in 2, Eh dot in 2 and Ev dot in 0, against 341, 243, 238 and 137 in the data (0.000 to 0.008, all at most 10%). In the sample of 300 encoding cells without eye terms no eye variable is detected, so scaled to all 1422 such cells the count stays 0. B and Bs are kept in 635 of 635 and 456 of 456 simulated eye cells that encoded them. Deleting the eye terms raises the simulated mean rate of the eye cells (median 7.48 Hz against 4.84 Hz in the data), as the Methods' procedure does; a variant that keeps the eye terms' mean was not run.
Summary¶
| Claim | Outcome |
|---|---|
| supp12-no-false-eye-detection | reproduced |
How the analysis differs from the paper's. The LN pipeline is the main notebook's, under readings (1a, 2a). The simulated cells are the 718 eye cells and a random 300 of the 1422 encoding cells without eye terms (an assumption; the paper may have simulated every cell). The spikes are drawn from the selected model fitted on the whole session. Mutual information uses 20 equal-width bins, a standard choice.
What was found about the dataset. Nothing beyond the main notebook.
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: 33.5 min; peak memory 2.08 GB