Reproducing Namima et al. (2025) from dandiset 001357¶
Paper. Namima, Kempkes, Zamarashkina, Owen and Pasupathy (2025), "High-Density Recording Reveals Sparse Clusters (But Not Columns) for Shape and Texture Encoding in Macaque V4", J Neurosci 45(5) e1893232024, doi:10.1523/jneurosci.1893-23.2024.
Dataset. DANDI:001357, version 0.261006.2007 (doi:10.48324/dandi.001357/0.261006.2007), streamed from the archive. The paper cites no version of the dataset. This is the only published version, and so the most recent; the draft has the same 159 assets and size, and a draft can change, so the published version is pinned.
Claims. claims/001357/10.1523-jneurosci.1893-23.2024.yaml, written by a reader from the version
of record (main text, Methods and figure legends; the paper has no supplement) and checked by a
second reader.
| Claim | Tested here |
|---|---|
| methods-sessions-and-neurons | tested |
| ex-m2p6-cluster | tested |
| ex-m2p6-pairs | tested |
| ex-m2p6-invariance | tested |
| ex-csd-sinks | blocked: the LF signal is not in the dataset |
| ex-m1p12-no-cluster | tested |
| ex-m1p12-strong-responses | tested |
| pop-significant-isimilarity | tested |
| pop-intercept-slope-correlation | tested |
| pop-dark-bright-consistent | tested |
| pop-contrast-invariance | tested |
| pop-sparse-across-penetrations | tested |
| pop-asymptote-20-percent | tested |
| pop-mean-isimilarity-yield | tested |
| pop-recording-density | tested |
| pop-within-vs-across-sessions | tested |
| orientation-sf-isimilarity | blocked: the shape images are not public |
| orientation-auc-coarse-clusters | tested |
| apc-peaks-sparse-clustering | blocked: the shapes' curvature descriptions are not public |
| apc-example-m2p51 | blocked: as apc-peaks-sparse-clustering |
| gyrus-penetrations-consistent | blocked: the dataset does not identify the 18 gyral penetrations |
| texture-sparse-clusters | tested |
| texture-original-reversed-consistent | tested |
| texture-asymptote-20-percent | tested |
| position-optimal-consistent | tested |
| position-examples-invariant | tested |
| simulation-random-with-domains | blocked: a simulation with unstated parameters, not a test on the data |
Methods and the passage each comes from are in the docstring of v4clusters.py.
import os
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import time
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import v4clusters as V
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)
print("dandiset", V.DANDISET, "version", V.VERSION)
dandiset 001357 version 0.261006.2007
Data check¶
Every file is streamed once and reduced, as it loads, to the spike count of every unit in the 30 to 200 ms window after the photodiode onset of every presentation (and the same count with the onsets moved by -1.3 s, for the clock check). The archive's metadata and the files' own fields are printed and checked against the paper's description.
t0 = time.time()
meta = V.version_metadata()
assets = V.list_assets()
print(meta["name"])
print("version", meta["version"], "| files", meta["assetsSummary"]["numberOfFiles"],
"| subjects", meta["assetsSummary"]["numberOfSubjects"],
"| variables", meta["assetsSummary"]["variableMeasured"])
print(meta["description"][:600])
print()
print(assets.groupby(["subject", "monkey", "kind"]).size().rename("files").to_string())
sess = V.load_many(assets.asset_id.tolist())
for s, (_, row) in zip(sess, assets.iterrows()):
s["asset"] = row.to_dict()
print(f"loaded {len(sess)} files in {time.time() - t0:.0f} s")
High-Density Recording Reveals Sparse Clusters (But Not Columns) for Shape and Texture Encoding in Macaque V4
version 0.261006.2007 | files 159 | subjects 2 | variables ['Units', 'ElectrodeGroup']
We used high-density Neuropixels probes in two awake monkeys (one female and one male) to characterize the shape and texture tuning of dozens of neurons simultaneously. The shape set included 15 simple geometric shapes each presented at eight different rotations in 45° increments, resulting in a total of 120 shape stimuli. Shapes were filled with a uniform color, either darker or brighter than the background luminance. The texture stimulus set was composed of 40 naturalistic grayscale textures. Each texture image was presented in three versions: original, contrast-reversed, or spectrally-match
subject monkey kind
Z08115 M1 SL 30
TX 17
Z11111 M2 SL 44
SP 34
TX 34
loaded 159 files in 114 s
info = pd.DataFrame([{
"monkey": s["asset"]["monkey"], "kind": s["asset"]["kind"], "date": s["asset"]["date"],
"description": s["meta"]["description"], "sex": s["meta"]["sex"], "device": s["meta"]["device"],
"pen": ",".join(sorted(set(s["units"].pen_ID))), "trial_pen": ",".join(sorted(set(s["trials"].pen_ID))),
"trial_ses": ",".join(sorted(set(s["trials"].ses_ID))), "units": len(s["units"]),
"sua": int(s["units"].is_sua.sum()), "presentations": len(s["trials"]),
"depth_min": s["units"].depth.min(), "depth_max": s["units"].depth.max(),
"spikes_sorted": s["meta"]["spikes_sorted"],
"spikes_beyond_trials_s": max(s["meta"]["trial_range"][0] - s["meta"]["spike_range"][0],
s["meta"]["spike_range"][1] - s["meta"]["trial_range"][1], 0),
"onset_minus_start": float((s["trials"].pdOnTS - s["trials"].start_time).median()),
"pd_duration": float((s["trials"].pdOffTS - s["trials"].pdOnTS).median()),
} for s in sess])
print("Files by monkey and test, with good units (is_sua = 1) and presentations:")
print(info.groupby(["monkey", "kind"]).agg(files=("date", "size"), units=("units", "sum"), sua=("sua", "sum"),
presentations=("presentations", "sum"), sexes=("sex", lambda x: set(x)),
descriptions=("description", lambda x: set(x))).to_string())
print()
print("All units are good (is_sua = 1):", bool((info.units == info.sua).all()))
print("One penetration label per file, the same in units and trials:", bool((info.pen == info.trial_pen).all()))
sp_mislabel = info[(info.kind == "SP") & info.trial_ses.str.endswith("SL")]
print(f"Position-test files whose trial table names the session '...SL': {len(sp_mislabel)} of {(info.kind == 'SP').sum()}")
print("Spike times sorted in every file:", bool(info.spikes_sorted.all()),
"| spikes extend beyond the file's trials by up to", round(info.spikes_beyond_trials_s.max(), 1), "s; files with more than 1 s:",
int((info.spikes_beyond_trials_s > 1).sum()))
print("Unit depth, 'distance from the electrode tip' (um): range", info.depth_min.min(), "to", info.depth_max.max())
steps = np.unique(np.concatenate([s["units"].depth.to_numpy() % 20 for s in sess]))
print("Depth values modulo 20 um:", steps)
print("Photodiode onset minus start_time (s): min", info.onset_minus_start.min(), "max", info.onset_minus_start.max())
print("Photodiode ON to OFF (s), median per file: range", info.pd_duration.min().round(3), "to", info.pd_duration.max().round(3))
print()
for kind, col in (("SL", "luminance"), ("TX", "mode"), ("SP", "position")):
vals = pd.concat([s["trials"][col] for s in sess if s["asset"]["kind"] == kind]).value_counts(dropna=False).sort_index()
print(f"{kind} presentations by {col}:", vals.to_dict())
for kind in ("SL", "TX", "SP"):
st = pd.concat([s["trials"].stim_ID for s in sess if s["asset"]["kind"] == kind])
print(f"{kind} stim_ID values:", sorted(st.dropna().unique().astype(int).tolist()))
print("Shape files with luminance 8 presentations:", sum(int((s["trials"].luminance == 8).any()) for s in sess if s["asset"]["kind"] == "SL"),
"of", sum(s["asset"]["kind"] == "SL" for s in sess))
rot = pd.concat([s["trials"].rotation for s in sess if s["asset"]["kind"] == "SL"])
print("SL rotations:", sorted(rot.dropna().unique().tolist()))
# repeats per stimulus
rep = []
for s in sess:
k = s["asset"]["kind"]
if k == "SL":
A = V.shape_arrays(s); rep += [(k, "dark", A["dark"][1].min(), np.median(A["dark"][1])), (k, "bright", A["bright"][1].min(), np.median(A["bright"][1]))]
elif k == "TX":
A = V.texture_arrays(s); rep += [(k, "original", A["original"][1].min(), np.median(A["original"][1])), (k, "reversed", A["reversed"][1].min(), np.median(A["reversed"][1]))]
else:
A = V.position_arrays(s); rep += [(k, "all positions", min(A[p][1].min() for p in range(5)), np.median(A[0][1]))]
rep = pd.DataFrame(rep, columns=["kind", "version", "min_repeats", "median_repeats"])
print()
print("Repeats per stimulus (per file, the minimum and the median):")
print(rep.groupby(["kind", "version"]).agg(min_of_min=("min_repeats", "min"), median_of_median=("median_repeats", "median")).to_string())
Files by monkey and test, with good units (is_sua = 1) and presentations:
files units sua presentations sexes descriptions
monkey kind
M1 SL 30 1167 1167 63337 {F} {V4 shape screen}
TX 17 461 461 15936 {F} {V4 texture screen}
M2 SL 44 1129 1129 94966 {M} {V4 shape screen}
SP 34 888 888 21292 {M} {V4 shape screen. position test}
TX 34 884 884 32179 {M} {V4 texture screen}
All units are good (is_sua = 1): True
One penetration label per file, the same in units and trials: True
Position-test files whose trial table names the session '...SL': 34 of 34
Spike times sorted in every file: True | spikes extend beyond the file's trials by up to 2.0 s; files with more than 1 s: 18
Unit depth, 'distance from the electrode tip' (um): range 20.0 to 3820.0
Depth values modulo 20 um: [0.]
Photodiode onset minus start_time (s): min 0.1499999999996362 max 0.15000000000009095
Photodiode ON to OFF (s), median per file: range 0.196 to 0.228
SL presentations by luminance: {0: 1738, 4: 52486, 8: 51582, 12: 52497}
TX presentations by mode: {0.0: 15501, 1.0: 15496, 2.0: 15504, nan: 1614}
SP presentations by position: {0.0: 4043, 1.0: 4043, 2.0: 4042, 3.0: 4041, 4.0: 4045, nan: 1078}
SL stim_ID values: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
TX stim_ID values: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
SP stim_ID values: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Shape files with luminance 8 presentations: 73 of 74
SL rotations: [0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0]
Repeats per stimulus (per file, the minimum and the median):
min_of_min median_of_median
kind version
SL bright 3 5.0
dark 3 5.0
SP all positions 4 8.0
TX original 4 8.0
reversed 4 8.0
Units shared between files. On days with more than one test (M2), the shape, texture and position
files hold the same units (same unit_ID, same order) with the spikes of their own block. No two
files hold the same spike trains, so no recording is deposited twice; a unit is counted once per
test.
by_date = {}
for s in sess:
by_date.setdefault((s["asset"]["monkey"], s["asset"]["date"]), {})[s["asset"]["kind"]] = s
multi = {k: g for k, g in by_date.items() if len(g) > 1}
same_ids = all((g[x]["units"].unit_ID.to_numpy() == next(iter(g.values()))["units"].unit_ID.to_numpy()).all()
for g in multi.values() for x in g)
print(f"Days with more than one test: {len(multi)}; same unit_IDs in every file of the day: {same_ids}")
sig = pd.Series([(tuple(s["units"].unit_ID), s["meta"]["unit_spikes"]) for s in sess])
print("Files with identical unit ids and spike counts per unit as another file:", int(sig.duplicated(keep=False).sum()))
days = pd.DataFrame([{"monkey": m, "date": d, "tests": "+".join(sorted(g))} for (m, d), g in by_date.items()])
print(days.groupby(["monkey", "tests"]).size().rename("days").to_string())
Days with more than one test: 37; same unit_IDs in every file of the day: True
Files with identical unit ids and spike counts per unit as another file: 0
monkey tests
M1 SL 30
TX 17
M2 SL 7
SL+SP 8
SL+SP+TX 26
SL+TX 3
TX 5
Every column of the files' tables, with its own description, and what the blank presentations
(cond_ID 0) are. The baseline uses cond_ID 0 as the blank; the cross-tabulation shows that those
presentations, and only those, have no stimulus.
for key in ("trial_columns", "unit_columns", "electrode_table_columns"):
for kind in ("SL", "TX", "SP"):
vals = {tuple(sorted(s["meta"][key].items())) for s in sess if s["asset"]["kind"] == kind}
print(f"{kind} {key} ({len(vals)} distinct across files):", dict(vals.pop()) if len(vals) == 1 else vals)
for key in ("intervals", "analysis", "presentation"):
print(key, "groups across files:", sorted({tuple(s["meta"][key]) for s in sess}))
print()
for kind, col in (("SL", "luminance"), ("TX", "mode"), ("SP", "position")):
tr = pd.concat([s["trials"] for s in sess if s["asset"]["kind"] == kind])
blank = tr.cond_ID == 0
print(f"{kind}: {len(tr)} presentations, {int(blank.sum())} with cond_ID 0; on those, {col}:",
tr.loc[blank, col].value_counts(dropna=False).to_dict(), "and stim_ID:", tr.loc[blank, "stim_ID"].value_counts(dropna=False).to_dict())
print(f" cond_ID != 0 with no stim_ID: {int((~blank & tr.stim_ID.isna()).sum())}; {col} values on cond_ID != 0:",
tr.loc[~blank, col].value_counts(dropna=False).sort_index().to_dict(),
f"| cond_ID values: {tr.cond_ID.nunique()} distinct, {int(tr.cond_ID.min())} to {int(tr.cond_ID.max())}")
SL trial_columns (1 distinct across files): {'cond_ID': 'stimulus condition ID', 'id': None, 'luminance': 'luminance (cd/m2)', 'pdOffTS': 'photodiode OFF time', 'pdOnTS': 'photodiode ON time', 'pen_ID': 'penetration ID', 'rotation': 'shape rotation', 'ses_ID': 'session ID', 'start_time': 'Start time of epoch, in seconds', 'stim_ID': 'shape stim ID', 'stop_time': 'Stop time of epoch, in seconds', 'sub_ID': 'subject ID'}
TX trial_columns (1 distinct across files): {'cond_ID': 'stimulus condition ID', 'id': None, 'mode': '0 (normal), 1 (reversed), 2 (spectral noise)', 'pdOffTS': 'photodiode OFF time', 'pdOnTS': 'photodiode ON time', 'pen_ID': 'penetration ID', 'ses_ID': 'session ID', 'start_time': 'Start time of epoch, in seconds', 'stim_ID': 'texture stim ID', 'stop_time': 'Stop time of epoch, in seconds', 'sub_ID': 'subject ID'}
SP trial_columns (1 distinct across files): {'cond_ID': 'stimulus condition ID', 'id': None, 'pdOffTS': 'photodiode OFF time', 'pdOnTS': 'photodiode ON time', 'pen_ID': 'penetration ID', 'position': 'position ID (0-4)', 'ses_ID': 'session ID', 'start_time': 'Start time of epoch, in seconds', 'stim_ID': 'shape stim ID', 'stop_time': 'Stop time of epoch, in seconds', 'sub_ID': 'subject ID'}
SL unit_columns (1 distinct across files): {'best_ch': 'best channel', 'depth': 'distance from the electrode tip', 'id': None, 'is_sua': 'sua = 1, mua = 0', 'pen_ID': 'penetration ID', 'probe_num': 'probe number', 'ses_ID': 'session ID', 'spike_times': 'spike_times', 'spike_times_index': "Index for VectorData 'spike_times'", 'sub_ID': 'subject ID', 'unit_ID': 'unit ID'}
TX unit_columns (1 distinct across files): {'best_ch': 'best channel', 'depth': 'distance from the electrode tip', 'id': None, 'is_sua': 'sua = 1, mua = 0', 'pen_ID': 'penetration ID', 'probe_num': 'probe number', 'ses_ID': 'session ID', 'spike_times': 'spike_times', 'spike_times_index': "Index for VectorData 'spike_times'", 'sub_ID': 'subject ID', 'unit_ID': 'unit ID'}
SP unit_columns (1 distinct across files): {'best_ch': 'best channel', 'depth': 'distance from the electrode tip', 'id': None, 'is_sua': 'sua = 1, mua = 0', 'pen_ID': 'penetration ID', 'probe_num': 'probe number', 'ses_ID': 'session ID', 'spike_times': 'spike_times', 'spike_times_index': "Index for VectorData 'spike_times'", 'sub_ID': 'subject ID', 'unit_ID': 'unit ID'}
SL electrode_table_columns (1 distinct across files): {'group': 'a reference to the ElectrodeGroup this electrode is a part of', 'group_name': 'the name of the ElectrodeGroup this electrode is a part of', 'id': None, 'label': 'label of electrode', 'location': 'the location of channel within the subject e.g. brain region'}
TX electrode_table_columns (1 distinct across files): {'group': 'a reference to the ElectrodeGroup this electrode is a part of', 'group_name': 'the name of the ElectrodeGroup this electrode is a part of', 'id': None, 'label': 'label of electrode', 'location': 'the location of channel within the subject e.g. brain region'}
SP electrode_table_columns (1 distinct across files): {'group': 'a reference to the ElectrodeGroup this electrode is a part of', 'group_name': 'the name of the ElectrodeGroup this electrode is a part of', 'id': None, 'label': 'label of electrode', 'location': 'the location of channel within the subject e.g. brain region'}
intervals groups across files: [('trials',)]
analysis groups across files: [()]
presentation groups across files: [()]
SL: 158303 presentations, 1738 with cond_ID 0; on those, luminance: {0: 1738} and stim_ID: {nan: 1738}
cond_ID != 0 with no stim_ID: 0; luminance values on cond_ID != 0: {4: 52486, 8: 51582, 12: 52497} | cond_ID values: 361 distinct, 0 to 360
TX: 48115 presentations, 1614 with cond_ID 0; on those, mode: {nan: 1614} and stim_ID: {nan: 1614}
cond_ID != 0 with no stim_ID: 0; mode values on cond_ID != 0: {0.0: 15501, 1.0: 15496, 2.0: 15504} | cond_ID values: 121 distinct, 0 to 120
SP: 21292 presentations, 1078 with cond_ID 0; on those, position: {nan: 1078} and stim_ID: {nan: 1078}
cond_ID != 0 with no stim_ID: 0; position values on cond_ID != 0: {0.0: 4043, 1.0: 4043, 2.0: 4042, 3.0: 4041, 4.0: 4045} | cond_ID values: 76 distinct, 0 to 75
Clock check. If spikes and presentations share a clock, many units' counts in the 30 to 200 ms window differ between stimuli (a one-way ANOVA over the stimuli of the file, per unit), and with the onsets moved by -1.3 s, onto other presentations or the gaps, that contrast should fall to the false-positive rate. Per file, the fraction of units with p < 0.01 is compared between true and shifted onsets; the clock is taken as established in a file when the true fraction exceeds 1% with a binomial p < 0.01 and exceeds the shifted fraction. The same cell also counts, per file, the units that fire more on stimulus presentations than on blanks (one-sided Mann-Whitney, p < 0.01), which separates a response to stimulus onset from selectivity among the stimuli.
def stim_key(s):
tr = s["trials"]
k = s["asset"]["kind"]
other = {"SL": "luminance", "TX": "mode", "SP": "position"}[k]
sel = (tr.cond_ID != 0).to_numpy() & tr.stim_ID.notna().to_numpy()
if k == "SL":
sel &= tr.luminance.isin([V.DARK, V.BRIGHT]).to_numpy()
key = tr.stim_ID.astype(str) + "_" + tr[other].astype(str) + ("_" + tr.rotation.astype(str) if k == "SL" else "")
return sel, key.to_numpy()
clock = []
for s in sess:
sel, key = stim_key(s)
groups = [np.flatnonzero(sel & (key == g)) for g in np.unique(key[sel])]
groups = [g for g in groups if len(g) > 1]
fr = {}
for name, cnt in (("true", s["counts"]), ("shifted", s["shifted"])):
with np.errstate(all="ignore"):
p = np.array([stats.f_oneway(*[cnt[u, g] for g in groups]).pvalue for u in range(cnt.shape[0])])
fr[name] = np.nanmean(p < 0.01)
n = s["counts"].shape[0]
# onset response: counts on stimulus presentations against blank presentations, per unit
blank_ = (s["trials"].cond_ID == 0).to_numpy()
with np.errstate(all="ignore"):
p_on = np.array([stats.mannwhitneyu(s["counts"][u, sel], s["counts"][u, blank_], alternative="greater").pvalue
if blank_.sum() > 1 else np.nan for u in range(n)])
clock.append({"kind": s["asset"]["kind"], "date": s["asset"]["date"], "units": n, "true": fr["true"], "shifted": fr["shifted"],
"onset_resp": np.nanmean(p_on < 0.01),
"p_binom": stats.binomtest(int(round(fr["true"] * n)), n, 0.01, alternative="greater").pvalue})
clock = pd.DataFrame(clock)
clock["established"] = (clock.p_binom < 0.01) & (clock.true > clock.shifted)
print("Fraction of units whose counts differ between stimuli (ANOVA p < 0.01), per file:")
print(clock.groupby("kind").agg(files=("date", "size"), true_median=("true", "median"), true_min=("true", "min"),
shifted_median=("shifted", "median"), shifted_max=("shifted", "max"), established=("established", "sum")).to_string())
print("Files where it is not established:", clock[~clock.established][["kind", "date", "units", "true", "shifted"]].round(3).to_dict("records"))
print("Fraction of units responding more to stimuli than to blanks (Mann-Whitney p < 0.01), median per test:",
clock.groupby("kind").onset_resp.median().round(3).to_dict(), "| in the files where the clock is not established:",
clock[~clock.established].set_index(["kind", "date"]).onset_resp.round(3).to_dict())
Fraction of units whose counts differ between stimuli (ANOVA p < 0.01), per file:
files true_median true_min shifted_median shifted_max established
kind
SL 74 0.726965 0.225000 0.0 0.166667 73
SP 34 0.723355 0.259259 0.0 0.142857 33
TX 51 0.730769 0.000000 0.0 0.062500 46
Files where it is not established: [{'kind': 'TX', 'date': '20200715', 'units': 25, 'true': 0.04, 'shifted': 0.0}, {'kind': 'TX', 'date': '20200719', 'units': 20, 'true': 0.0, 'shifted': 0.0}, {'kind': 'TX', 'date': '20200729', 'units': 17, 'true': 0.118, 'shifted': 0.0}, {'kind': 'TX', 'date': '20200730', 'units': 31, 'true': 0.065, 'shifted': 0.0}, {'kind': 'TX', 'date': '20200804', 'units': 22, 'true': 0.045, 'shifted': 0.0}, {'kind': 'SL', 'date': '20210529', 'units': 1, 'true': 1.0, 'shifted': 0.0}, {'kind': 'SP', 'date': '20210529', 'units': 1, 'true': 1.0, 'shifted': 0.0}]
Fraction of units responding more to stimuli than to blanks (Mann-Whitney p < 0.01), median per test: {'SL': 0.398, 'SP': 0.378, 'TX': 0.407} | in the files where the clock is not established: {('TX', '20200715'): 0.28, ('TX', '20200719'): 0.4, ('TX', '20200729'): 0.471, ('TX', '20200730'): 0.387, ('TX', '20200804'): 0.091, ('SL', '20210529'): 0.0, ('SP', '20210529'): 0.0}
Shape analyses for every penetration¶
Responsive neurons, similarity matrices over the 120 dark and the 120 bright shapes with their
bootstrap intervals, Isimilarity and Ssimilarity under both reliability readings, and the tuning
invariance between dark and bright. The neuron table N has one row per responsive neuron.
t0 = time.time()
shape = {}
for s in sess:
if s["asset"]["kind"] != "SL":
continue
A = V.shape_arrays(s)
keep = V.responsive([A["dark"][0], A["bright"][0]], A["blank"])
key = (s["asset"]["monkey"], s["asset"]["date"])
res = {"keep": keep, "pen": s["units"].pen_ID.iloc[0], "good": len(keep), "arrays": A,
"depth0": s["units"].depth0.to_numpy(), "units": s["units"]}
if keep.sum() >= 1:
res.update(V.analyse_pair_sets(A, ("dark", "bright"), keep, res["depth0"], s["meta"]["session_id"]))
shape[key] = res
rows = []
for (mk, d), res in shape.items():
if res["keep"].sum() == 0:
continue
t = V.neuron_table(res, ("dark", "bright"))
t["monkey"], t["date"], t["pen"] = mk, d, res["pen"]
t["n_pen"] = len(t)
rows.append(t)
N = pd.concat(rows, ignore_index=True)
print(f"shape analyses in {time.time() - t0:.0f} s; {len(N)} responsive neurons in {N.date.nunique()} penetrations")
rel_frac = {rd: np.mean([V.reliable(r["dark"]["r"], r["dark"]["lo"], r["dark"]["hi"], rd)[~np.eye(r["keep"].sum(), dtype=bool)].mean()
for r in shape.values() if r["keep"].sum() > 1]) for rd in "ab"}
print("Mean fraction of reliable off-diagonal dark similarities per penetration:", {k: round(v, 3) for k, v in rel_frac.items()})
def readings(N, rd, contrast, slope_rule, suffix=("dark", "bright")):
"""Masks (has a line, counted) for one reading: reliability rd, contrast, slope rule i or ii."""
d, b = suffix
def one(c):
line = N[f"has_line_{c}_{rd}"]
sel = N[f"sig_pos_{c}_{rd}"]
if slope_rule == "ii":
sel = sel & (N[f"slope_{c}_{rd}"] < 0)
return line, sel
if contrast == "either":
(l1, s1), (l2, s2) = one(d), one(b)
return l1 | l2, s1 | s2
return one(contrast)
shape analyses in 91 s; 1869 responsive neurons in 74 penetrations
Mean fraction of reliable off-diagonal dark similarities per penetration: {'a': np.float64(0.748), 'b': np.float64(0.777)}
methods-sessions-and-neurons¶
The shape test was run in 30 sessions in M1 and 44 in M2, the texture test in 17 and 34, and the position control in 33 M2 sessions; the responsiveness criterion excluded 461 and 366 neurons and left 1,850 neurons for shape and 979 for texture analyses.
Texture responsiveness uses the 40 original and 40 contrast-reversed textures (the paper's two "contrast levels" for textures); the files' third version (spectral noise) is left out.
t0 = time.time()
texture = {}
for s in sess:
if s["asset"]["kind"] != "TX":
continue
A = V.texture_arrays(s)
keep = V.responsive([A["original"][0], A["reversed"][0]], A["blank"])
key = (s["asset"]["monkey"], s["asset"]["date"])
res = {"keep": keep, "pen": s["units"].pen_ID.iloc[0], "good": len(keep), "arrays": A,
"depth0": s["units"].depth0.to_numpy()}
if keep.sum() >= 1:
res.update(V.analyse_pair_sets(A, ("original", "reversed"), keep, res["depth0"], s["meta"]["session_id"]))
texture[key] = res
rowsT = []
for (mk, d), res in texture.items():
if res["keep"].sum() == 0:
continue
t = V.neuron_table(res, ("original", "reversed"))
t["monkey"], t["date"], t["pen"] = mk, d, res["pen"]
t["n_pen"] = len(t)
rowsT.append(t)
T = pd.concat(rowsT, ignore_index=True)
print(f"texture analyses in {time.time() - t0:.0f} s")
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
texture analyses in 38 s
ses_counts = assets.groupby(["monkey", "kind"]).size()
good_shape = sum(r["good"] for r in shape.values())
good_tex = sum(r["good"] for r in texture.values())
vals = {
"shape sessions, M1": (ses_counts[("M1", "SL")], 30, 3),
"shape sessions, M2": (ses_counts[("M2", "SL")], 44, 4.4),
"texture sessions, M1": (ses_counts[("M1", "TX")], 17, 1.7),
"texture sessions, M2": (ses_counts[("M2", "TX")], 34, 3.4),
"position control sessions, M2": (ses_counts[("M2", "SP")], 33, 3.3),
"responsive neurons, shape": (len(N), 1850, 185),
"responsive neurons, texture": (len(T), 979, 97.9),
"excluded neurons, shape": (good_shape - len(N), 461, 46.1),
"excluded neurons, texture": (good_tex - len(T), 366, 36.6),
}
tab = pd.DataFrame([{"quantity": k, "measured": v[0], "expected": v[1], "tolerance": v[2],
"within": abs(v[0] - v[1]) <= v[2]} for k, v in vals.items()])
print(tab.to_string(index=False))
print()
print("Good units: shape", good_shape, "(paper 1,850 + 461 = 2,311); texture", good_tex, "(paper 979 + 366 = 1,345)")
print("Responsive by monkey, shape:", N.groupby("monkey").size().to_dict(), "| texture:", T.groupby("monkey").size().to_dict())
print("Penetrations with no responsive shape neuron:", [(k, r["good"]) for k, r in shape.items() if r["keep"].sum() == 0])
sp_dates = set(assets[assets.kind == "SP"].date)
print("Position-test days and their good units:", sorted((d, len(by_date[("M2", d)]["SP"]["units"])) for d in sp_dates))
tx2 = set(assets[(assets.kind == "TX") & (assets.monkey == "M2")].date)
sl2 = set(assets[(assets.kind == "SL") & (assets.monkey == "M2")].date)
print(f"M2 texture days that also have a shape file: {len(tx2 & sl2)} of {len(tx2)}; texture-only days and labels:",
[(d, by_date[("M2", d)]["TX"]["units"].pen_ID.iloc[0]) for d in sorted(tx2 - sl2)])
quantity measured expected tolerance within
shape sessions, M1 30 30 3.0 True
shape sessions, M2 44 44 4.4 True
texture sessions, M1 17 17 1.7 True
texture sessions, M2 34 34 3.4 True
position control sessions, M2 34 33 3.3 True
responsive neurons, shape 1869 1850 185.0 True
responsive neurons, texture 985 979 97.9 True
excluded neurons, shape 427 461 46.1 True
excluded neurons, texture 360 366 36.6 True
Good units: shape 2296 (paper 1,850 + 461 = 2,311); texture 1345 (paper 979 + 366 = 1,345)
Responsive by monkey, shape: {'M1': 954, 'M2': 915} | texture: {'M1': 300, 'M2': 685}
Penetrations with no responsive shape neuron: []
Position-test days and their good units: [('20210412', 37), ('20210413', 19), ('20210416', 19), ('20210417', 20), ('20210418', 24), ('20210421', 27), ('20210422', 6), ('20210423', 27), ('20210503', 14), ('20210504', 17), ('20210505', 22), ('20210506', 16), ('20210507', 24), ('20210512', 65), ('20210513', 97), ('20210517', 53), ('20210518', 26), ('20210523', 7), ('20210528', 10), ('20210529', 1), ('20210531', 42), ('20210605', 26), ('20210608', 22), ('20210609', 18), ('20210610', 17), ('20210611', 59), ('20210614', 45), ('20210615', 10), ('20210619', 19), ('20210620', 28), ('20210624', 16), ('20210625', 25), ('20210626', 9), ('20210627', 21)]
M2 texture days that also have a shape file: 29 of 34; texture-only days and labels: [('20210415', 'p07'), ('20210428', 'p17'), ('20210530', 'p40'), ('20210602', 'p42'), ('20210613', 'p53')]
Result: reproduced. The files hold 30 and 44 shape sessions, 17 and 34 texture sessions and 34 position-test sessions (expected 33 +/- 3.3; one holds a single unit). 1,869 responsive shape neurons (427 excluded) and 985 responsive texture neurons (360 excluded) are all within tolerance. The good units of the texture files sum to the paper's 979 + 366 = 1,345 exactly; the shape files hold 2,296 against the paper's 2,311.
How lenient each reliability reading is¶
The paper reports that only 2 of 1,850 shape neurons had no regression line (n = 1,848) and that 1,847 had one at both contrasts (pop-dark-bright-consistent), and 931 of 979 texture neurons had a line (48 did not) and 905 at both versions. The widths of the bootstrap intervals, and the number of neurons with a line under each reading, are set against these counts.
for name, store, vers in (("shape", shape, ("dark", "bright")), ("texture", texture, ("original", "reversed"))):
for c in vers:
w = np.concatenate([(r[c]["hi"] - r[c]["lo"])[~np.eye(r["keep"].sum(), dtype=bool)] for r in store.values() if r["keep"].sum() > 1])
w = w[np.isfinite(w)]
print(f"{name} {c}: similarity interval width over {len(w)} ordered pairs, percentiles 10/25/50/75/90 "
f"{np.round(np.percentile(w, [10, 25, 50, 75, 90]), 3)}; reliable under (a) {np.mean(w <= 0.5):.1%}, under (b) {np.mean(w <= 1.0):.1%}")
iw = np.concatenate([r["invariance"]["hi"] - r["invariance"]["lo"] for r in store.values() if "invariance" in r])
iw = iw[np.isfinite(iw)]
print(f"{name} invariance interval width: median {np.median(iw):.3f}; reliable under (a) {np.mean(iw <= 0.5):.1%}, under (b) {np.mean(iw <= 1.0):.1%}")
rows = []
for name, tab, (x, y), paper in (("shape", N, ("dark", "bright"), "1,848 of 1,850 (2 without), 1,847 at both"),
("texture", T, ("original", "reversed"), "931 of 979 (48 without), 905 at both")):
for rd in "ab":
lx, ly = tab[f"has_line_{x}_{rd}"], tab[f"has_line_{y}_{rd}"]
rows.append({"test": name, "versions": f"{x}, {y}", "reliability": rd, "neurons": len(tab), "line_first": int(lx.sum()),
"line_second": int(ly.sum()), "line_both": int((lx & ly).sum()), "line_either": int((lx | ly).sum()),
"no_line_first": int((~lx).sum()), "paper, neurons with a line": paper})
print(pd.DataFrame(rows).to_string(index=False))
# why a neuron has no line: the first cause that applies, in this order
cause_rows = []
for name, store, c in (("shape", shape, "dark"), ("texture", texture, "original")):
for key, r in store.items():
k = int(r["keep"].sum())
if k == 0:
continue
R, lo, hi = r[c]["r"], r[c]["lo"], r[c]["hi"]
d_ = r["depth0"][r["keep"]]
for rd in "ab":
rel = V.reliable(R, lo, hi, rd)
for i in range(k):
oth = np.arange(k) != i
fin_r = np.isfinite(R[i]) & oth
fin_ci = fin_r & np.isfinite(hi[i] - lo[i])
rl = rel[i] & oth
if rl.sum() >= 3 and np.ptp(d_[rl]) > 0:
continue
if k - 1 < 3:
why = "fewer than 3 other neurons in the penetration"
elif fin_r.sum() == 0:
why = "every similarity undefined (own bias-corrected variance not positive)"
elif fin_r.sum() < 3:
why = "fewer than 3 defined similarities"
elif fin_ci.sum() < 3:
why = "fewer than 3 defined bootstrap intervals"
elif rl.sum() < 3:
why = "intervals too wide"
else:
why = "all reliable partners at one distance"
cause_rows.append({"test": f"{name} ({c})", "reliability": rd, "cause": why})
print()
print("Neurons without a line, by cause:")
print(pd.DataFrame(cause_rows).groupby(["test", "reliability", "cause"]).size().to_string())
shape dark: similarity interval width over 69078 ordered pairs, percentiles 10/25/50/75/90 [0.239 0.3 0.367 0.432 0.491]; reliable under (a) 91.3%, under (b) 100.0%
shape bright: similarity interval width over 69160 ordered pairs, percentiles 10/25/50/75/90 [0.245 0.305 0.37 0.433 0.491]; reliable under (a) 91.5%, under (b) 100.0%
shape invariance interval width: median 0.390; reliable under (a) 88.1%, under (b) 99.9%
texture original: similarity interval width over 26930 ordered pairs, percentiles 10/25/50/75/90 [0.325 0.401 0.507 0.645 0.814]; reliable under (a) 48.3%, under (b) 97.5%
texture reversed: similarity interval width over 26950 ordered pairs, percentiles 10/25/50/75/90 [0.323 0.403 0.516 0.655 0.814]; reliable under (a) 46.6%, under (b) 97.9%
texture invariance interval width: median 0.585; reliable under (a) 36.6%, under (b) 96.3%
test versions reliability neurons line_first line_second line_both line_either no_line_first paper, neurons with a line
shape dark, bright a 1869 1729 1730 1643 1816 140 1,848 of 1,850 (2 without), 1,847 at both
shape dark, bright b 1869 1805 1799 1757 1847 64 1,848 of 1,850 (2 without), 1,847 at both
texture original, reversed a 985 681 663 624 720 304 931 of 979 (48 without), 905 at both
texture original, reversed b 985 923 941 894 970 62 931 of 979 (48 without), 905 at both
Neurons without a line, by cause:
test reliability cause
shape (dark) a every similarity undefined (own bias-corrected variance not positive) 15
fewer than 3 defined bootstrap intervals 1
fewer than 3 defined similarities 47
fewer than 3 other neurons in the penetration 1
intervals too wide 76
b every similarity undefined (own bias-corrected variance not positive) 15
fewer than 3 defined bootstrap intervals 1
fewer than 3 defined similarities 47
fewer than 3 other neurons in the penetration 1
texture (original) a every similarity undefined (own bias-corrected variance not positive) 6
fewer than 3 defined similarities 11
intervals too wide 287
b every similarity undefined (own bias-corrected variance not positive) 6
fewer than 3 defined similarities 11
intervals too wide 45
Reading (b) (half-width above 0.5, so width above 1.0) keeps nearly every similarity (100% of
shape pairs, 97.5% to 97.9% of texture pairs), and so is close to no filter at all. Under it 64 shape
neurons (dark) and 62 texture neurons (original) have no line, against the paper's 2 and 48; under
reading (a) 140 and 304. The causes table shows why. Under (b), 62 of the 64 shape neurons without a
line have fewer than 3 defined similarities (15 of them none at all, since their own bias-corrected
variance is not positive and nc_corr returns NaN), one has fewer than 3 defined bootstrap intervals
and one is in the penetration with a single neuron; none lacks a line because its intervals are too
wide. For textures under (b), 17 of the 62 have too few defined similarities and 45 too wide
intervals. So the shape gap to the paper's 2 comes mostly from how the estimator treats weakly tuned
neurons (undefined here), not from the reliability rule. Reading (a) adds 76 shape and 287 texture
neurons whose intervals are too wide; these still argue against reading (a), but the paper's 2 cannot
be reached under either reading with this estimator. The question
of the reading is asked of a reader (questions/001357.yaml); the claims file's criteria accept
either reading, so both are still run.
Noise correlations between simultaneously recorded neurons¶
The noise-corrected similarity takes the trial-to-trial noise of two neurons as independent (Pospisil
and Bair). For neurons recorded together this is an assumption. The noise correlation of each pair
(the correlation of their within-stimulus residuals of sqrt counts, dark shapes) is shown by
distance, and the Isimilarity counts are recomputed with nc_corr_shared, which subtracts each pair's
noise covariance (same reliability masks, as a variant).
rows = []
for (mk, d), r in shape.items():
k = r["keep"]
if k.sum() < 2:
continue
arr, nrep = r["arrays"]["dark"]
x = np.sqrt(arr[k])
res_ = (x - np.nanmean(x, axis=2, keepdims=True)).reshape(int(k.sum()), -1)
res_ = res_[:, np.isfinite(res_).all(0)]
with np.errstate(invalid="ignore", divide="ignore"):
cn = np.corrcoef(res_)
iu = np.triu_indices(int(k.sum()), 1)
rows.append(pd.DataFrame({"monkey": mk, "rn": cn[iu], "dist": np.abs(r["depth0"][k][iu[0]] - r["depth0"][k][iu[1]]), "sim": r["dark"]["r"][iu]}))
NCOR = pd.concat(rows).dropna()
NCOR["distance_um"] = pd.cut(NCOR.dist, [-1, 100, 200, 400, 800, 4000], labels=["0-100", "100-200", "200-400", "400-800", ">800"])
print("Noise correlation of pairs of responsive neurons, dark shapes, by distance:")
print(NCOR.groupby("distance_um", observed=True).agg(pairs=("rn", "size"), noise_r_mean=("rn", "mean"), noise_r_median=("rn", "median"),
noise_r_min=("rn", "min"), noise_r_max=("rn", "max"), similarity_mean=("sim", "mean")).round(4).to_string())
print("By monkey, mean noise correlation within 200 um:", NCOR[NCOR.dist <= 200].groupby("monkey").rn.mean().round(4).to_dict())
rs_ = stats.spearmanr(NCOR.rn, NCOR.sim)
print(f"Spearman r of noise correlation with tuning similarity: {rs_[0]:.3f} (p = {rs_[1]:.2g}, n = {len(NCOR)})")
shared = []
for (mk, d), r in shape.items():
k = r["keep"]
if k.sum() < 2:
continue
for c in ("dark", "bright"):
arr, nrep = r["arrays"][c]
radj = V.nc_corr_shared(arr[k], nrep)
for rd in "ab":
rel = V.reliable(r[c]["r"], r[c]["lo"], r[c]["hi"], rd) & np.isfinite(radj)
t_ = V.isimilarity(radj, rel, r["depth0"][k], np.ones(int(k.sum()), bool))
shared.append(pd.DataFrame({"monkey": mk, "date": d, "unit": np.flatnonzero(k), "contrast": c, "rd": rd,
"has_line": t_.has_line.to_numpy(), "sig_pos": t_.sig_pos.to_numpy(),
"sig_any": t_.sig_any.to_numpy(), "slope_neg": (t_.slope < 0).to_numpy()}))
SH = pd.concat(shared, ignore_index=True)
print()
print("Variant with shared noise subtracted: neurons with a significant positive Isimilarity (rule i), against the main analysis")
cmp_ = []
for c in ("dark", "bright"):
for rd in "ab":
s_ = SH[(SH.contrast == c) & (SH.rd == rd)]
g = s_[s_.sig_pos].groupby("monkey").size()
cmp_.append({"contrast": c, "reliability": rd, "main": int(N[f"sig_pos_{c}_{rd}"].sum()), "shared_noise_subtracted": int(s_.sig_pos.sum()),
"M1": int(g.get("M1", 0)), "M2": int(g.get("M2", 0)), "with_negative_slope": int((s_.sig_pos & s_.slope_neg).sum()),
"lines": int(s_.has_line.sum())})
print(pd.DataFrame(cmp_).to_string(index=False), "(paper: 344; 203 in M1, 141 in M2)")
Noise correlation of pairs of responsive neurons, dark shapes, by distance:
pairs noise_r_mean noise_r_median noise_r_min noise_r_max similarity_mean
distance_um
0-100 2650 0.0718 0.0480 -0.4369 1.0000 0.2272
100-200 2298 0.0513 0.0363 -0.4521 0.6139 0.1605
200-400 3904 0.0352 0.0255 -0.5465 0.7426 0.1015
400-800 6041 0.0309 0.0209 -0.4908 0.6912 0.0732
>800 10861 0.0230 0.0157 -0.4354 0.6180 0.0296
By monkey, mean noise correlation within 200 um: {'M1': 0.0639, 'M2': 0.0591}
Spearman r of noise correlation with tuning similarity: 0.289 (p = 0, n = 25754)
Variant with shared noise subtracted: neurons with a significant positive Isimilarity (rule i), against the main analysis
contrast reliability main shared_noise_subtracted M1 M2 with_negative_slope lines
dark a 400 274 157 117 266 1729
dark b 453 296 175 121 291 1805
bright a 386 243 152 91 239 1730
bright b 449 273 176 97 270 1799 (paper: 344; 203 in M1, 141 in M2)
Noise correlations are small but positive, and largest between near neurons (mean 0.072 within 100 um, 0.023 beyond 800 um), and they rise with tuning similarity. Subtracting each pair's noise covariance lowers the counts of significant positive Isimilarity by about a third (dark, reliability a, 400 to 274), so the counts depend on the assumption of independent noise. The paper's method follows Pospisil and Bair, which takes noise as independent, so the main analysis keeps it, and the variant is shown with the claims it bears on.
Finding the example penetrations¶
The claims file's readings: (a) the sixth M2 session in recording order among shape sessions, (b) the sixth among all M2 sessions, (c) the session the dataset labels with the penetration number. The same for M1p12 (twelfth), M2p9, M2p28, M2p51 and M1p5. A reading is accepted when its responsive-neuron count is within 10% of the paper's.
def find_pen(monkey, number, expected):
sl = sorted(assets[(assets.monkey == monkey) & (assets.kind == "SL")].date)
alld = sorted(set(assets[assets.monkey == monkey].date))
cand = {"a": sl[number - 1] if number <= len(sl) else None,
"b": alld[number - 1] if number <= len(alld) else None,
"c": next((d for (m, d), r in shape.items() if m == monkey and r["pen"] == f"p{number:02d}"), None)}
rows = []
for rd, d in cand.items():
n = int(shape[(monkey, d)]["keep"].sum()) if d in sl else None
rows.append({"reading": rd, "date": d, "label": shape[(monkey, d)]["pen"] if d in sl else None,
"responsive": n, "accepted": n is not None and abs(n - expected) <= 0.1 * expected})
return pd.DataFrame(rows)
examples = {"M2p6": ("M2", 6, 24), "M1p12": ("M1", 12, 42), "M2p9": ("M2", 9, 16), "M2p28": ("M2", 28, 55),
"M2p51": ("M2", 51, 33), "M1p5": ("M1", 5, None)}
found = {}
for name, (mk, num, exp) in examples.items():
f = find_pen(mk, num, exp if exp else 1)
print(name, "(paper's count:", exp, ")")
print(f.to_string(index=False))
found[name] = (mk, f.set_index("reading").loc["c", "date"])
M2p6 (paper's count: 24 )
reading date label responsive accepted
a 20210417 p09 18 False
b 20210416 p08 18 False
c 20210414 p06 24 True
M1p12 (paper's count: 42 )
reading date label responsive accepted
a 20191025 p13 13 False
b 20191025 p13 13 False
c 20191024 p12 42 True
M2p9 (paper's count: 16 )
reading date label responsive accepted
a 20210421 p12 16 True
b 20210420 p11 11 False
c 20210417 p09 18 False
M2p28 (paper's count: 55 )
reading date label responsive accepted
a 20210529 p40 1 False
b 20210527 p37 24 False
c 20210512 p28 55 True
M2p51 (paper's count: 33 )
reading date label responsive accepted
a NaN NaN NaN False
b NaN NaN NaN False
c 20210611 p51 48.0 False
M1p5 (paper's count: None )
reading date label responsive accepted
a 20190726 p05 60 False
b 20190726 p05 60 False
c 20190726 p05 60 False
ex-m2p6-cluster¶
In penetration M2p6, 24 well-isolated neurons were recorded over about 2,400 um; a group of superficial neurons (1 to 9, over 540 um) had similar shape tuning at both contrasts, and with dark shapes neurons 1 to 9, 14 and 17 had a significant positive Isimilarity with a negative slope, while most other, deeper neurons did not.
Neurons are numbered by depth from the most superficial (Figure 2A legend); units at the same depth keep the file's order.
key = found["M2p6"]
res = shape[key]
t = N[(N.monkey == key[0]) & (N.date == key[1])].copy()
t["num"] = np.argsort(np.argsort(t.depth0.to_numpy(), kind="stable"), kind="stable") + 1
t = t.sort_values("num")
print("M2p6 =", key, "| responsive neurons", len(t), "| span of depths", np.ptp(t.depth0), "um")
print("Depth of neurons 1 and 9:", t.depth0.iloc[0], t.depth0.iloc[8], "-> extent", t.depth0.iloc[8] - t.depth0.iloc[0], "um")
paper_set = set(range(1, 10)) | {14, 17}
for c in ("dark", "bright"):
for rd in "ab":
sig = t[t[f"sig_pos_{c}_{rd}"]]
got = set(sig.num)
print(f"{c}, reliability {rd}: significant positive Isimilarity, neurons {sorted(got)} ({len(got)}); "
f"slopes negative for {int((sig[f'slope_{c}_{rd}'] < 0).sum())} of {len(sig)}; "
f"missing from the paper's set {sorted(paper_set - got)}, added {sorted(got - paper_set)}; "
f"significant either sign {int(t[f'sig_any_{c}_{rd}'].sum())}")
s_ = SH[(SH.date == key[1]) & (SH.contrast == c) & (SH.rd == rd)].set_index("unit").loc[t.unit]
got_sh = set(t.num[s_.sig_pos.to_numpy()])
print(f" variant with shared noise subtracted: neurons {sorted(got_sh)} ({len(got_sh)}); missing {sorted(paper_set - got_sh)}, added {sorted(got_sh - paper_set)}")
r = res["dark"]["r"]
order = np.argsort(res["depth0"][res["keep"]], kind="stable")
rr = r[np.ix_(order, order)]
print("Mean dark similarity among neurons 1-9 (off-diagonal):", np.round(np.nanmean(rr[:9, :9][~np.eye(9, dtype=bool)]), 3),
"| between 1-9 and 10-24:", np.round(np.nanmean(rr[:9, 9:]), 3), "| among 10-24:",
np.round(np.nanmean(rr[9:, 9:][~np.eye(15, dtype=bool)]), 3))
rb = res["bright"]["r"][np.ix_(order, order)]
print("Same, bright:", np.round(np.nanmean(rb[:9, :9][~np.eye(9, dtype=bool)]), 3), np.round(np.nanmean(rb[:9, 9:]), 3),
np.round(np.nanmean(rb[9:, 9:][~np.eye(15, dtype=bool)]), 3))
print(t[["num", "depth0", "intercept_dark_a", "i_lo_dark_a", "slope_dark_a", "sig_pos_dark_a", "intercept_bright_a", "sig_pos_bright_a"]].round(3).to_string(index=False))
fig, ax = plt.subplots(1, 2, figsize=(9, 4))
for k, (c, m) in enumerate((("dark", rr), ("bright", rb))):
im = ax[k].imshow(m, vmin=-1, vmax=1, cmap="RdBu_r")
ax[k].set_title(f"M2p6 similarity, {c} (range {np.nanmin(m):.2f} to {np.nanmax(m):.2f})")
ax[k].set_xlabel("neuron"); ax[k].set_ylabel("neuron")
plt.colorbar(im, ax=ax); plt.show()
M2p6 = ('M2', '20210414') | responsive neurons 24 | span of depths 2340.0 um
Depth of neurons 1 and 9: 0.0 540.0 -> extent 540.0 um
dark, reliability a: significant positive Isimilarity, neurons [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 14, 21, 22] (13); slopes negative for 13 of 13; missing from the paper's set [17], added [12, 21, 22]; significant either sign 13
variant with shared noise subtracted: neurons [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 14, 21] (12); missing [17], added [12, 21]
dark, reliability b: significant positive Isimilarity, neurons [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 14, 21, 22] (13); slopes negative for 13 of 13; missing from the paper's set [17], added [12, 21, 22]; significant either sign 13
variant with shared noise subtracted: neurons [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 14, 21] (12); missing [17], added [12, 21]
bright, reliability a: significant positive Isimilarity, neurons [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14] (13); slopes negative for 13 of 13; missing from the paper's set [17], added [11, 12, 13]; significant either sign 14
variant with shared noise subtracted: neurons [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 14] (12); missing [17], added [11, 12]
bright, reliability b: significant positive Isimilarity, neurons [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14] (13); slopes negative for 13 of 13; missing from the paper's set [17], added [11, 12, 13]; significant either sign 14
variant with shared noise subtracted: neurons [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 14] (12); missing [17], added [11, 12]
Mean dark similarity among neurons 1-9 (off-diagonal): 0.702 | between 1-9 and 10-24: -0.022 | among 10-24: 0.146
Same, bright: 0.857 -0.018 0.084
num depth0 intercept_dark_a i_lo_dark_a slope_dark_a sig_pos_dark_a intercept_bright_a sig_pos_bright_a
1 0.0 0.791 0.521 -0.000 True 0.925 True
2 160.0 0.717 0.531 -0.000 True 0.785 True
3 220.0 0.768 0.524 -0.001 True 0.775 True
4 260.0 0.573 0.324 -0.000 True 0.517 True
5 280.0 0.690 0.454 -0.000 True 0.723 True
6 340.0 0.776 0.567 -0.001 True 0.830 True
7 400.0 0.531 0.300 -0.000 True 0.691 True
8 480.0 0.512 0.231 -0.000 True 0.645 True
9 540.0 0.623 0.408 -0.000 True 0.679 True
10 920.0 0.153 -0.275 0.000 False 0.026 False
11 1180.0 0.220 -0.145 -0.000 False 0.391 True
12 1180.0 0.328 0.027 -0.000 True 0.335 True
13 1380.0 0.096 -0.211 0.000 False 0.199 True
14 1420.0 0.431 0.157 -0.001 True 0.589 True
15 1460.0 0.272 -0.058 -0.000 False 0.128 False
16 1540.0 0.225 -0.007 -0.000 False 0.131 False
17 1540.0 -0.060 -0.362 0.000 False -0.151 False
18 1740.0 0.118 -0.070 0.000 False 0.058 False
19 1820.0 0.008 -0.275 -0.000 False 0.130 False
20 1980.0 -0.087 -0.393 0.000 False 0.097 False
21 2060.0 0.275 0.063 -0.000 True 0.270 False
22 2060.0 0.557 0.085 -0.000 True 0.032 False
23 2280.0 0.184 -0.153 -0.000 False -0.467 False
24 2340.0 0.005 -0.192 0.000 False -0.008 False
Result: partially reproduced. The penetration the files label p06 of M2 (readings a and b give sessions with 18 responsive neurons) has 24 responsive neurons spanning 2,340 um, and neurons 1 to 9, spread over 540 um, are similarly tuned at both contrasts (mean similarity 0.70 dark and 0.86 bright, against -0.02 with the deeper neurons). With dark shapes 13 neurons have a significant positive Isimilarity under both reliability readings, all with negative slopes, and none has a significant negative one: neurons 1 to 9 and 14, as in the paper, plus 12, 21 and 22, and not 17. The count, 13 against 11 +/- 1.1, and the set are outside the claim's margin. With shared noise subtracted the count is 12 (within tolerance), but the set still lacks 17 and adds 12 and 21.
ex-m2p6-pairs¶
In M2p6, neurons 3 and 8, 260 um apart, have tuning similarity 0.82 at both contrasts, while neurons 18 and 19, 80 um apart, have similarity 0.00 (dark) and -0.25 (bright).
The files give each unit's best-channel position, the contact nearest the waveform's center (Figure 2A legend), which is the claim's main reading of distance; the template center of mass is not in the files, so the variant cannot be run.
idx = np.flatnonzero(res["keep"])[order]
d0 = res["depth0"]
def pair(i, j, c):
k = np.flatnonzero(res["keep"])
a_, b_ = np.searchsorted(k, idx[i - 1]), np.searchsorted(k, idx[j - 1])
return res[c]["r"][a_, b_], res[c]["lo"][a_, b_], res[c]["hi"][a_, b_]
vals = [("similarity 3 and 8, dark", pair(3, 8, "dark")[0], 0.82, 0.082),
("similarity 3 and 8, bright", pair(3, 8, "bright")[0], 0.82, 0.082),
("similarity 18 and 19, dark", pair(18, 19, "dark")[0], 0.0, 0.1),
("similarity 18 and 19, bright", pair(18, 19, "bright")[0], -0.25, 0.025),
("distance 3 and 8 (um)", abs(d0[idx[2]] - d0[idx[7]]), 260, 26),
("distance 18 and 19 (um)", abs(d0[idx[17]] - d0[idx[18]]), 80, 8)]
tab = pd.DataFrame(vals, columns=["quantity", "measured", "expected", "tolerance"])
tab["within"] = (tab.measured - tab.expected).abs() <= tab.tolerance
print(tab.round(3).to_string(index=False))
for (i, j) in ((3, 8), (18, 19)):
for c in ("dark", "bright"):
r_, lo_, hi_ = pair(i, j, c)
k = np.flatnonzero(res["keep"])
a_, b_ = np.searchsorted(k, idx[i - 1]), np.searchsorted(k, idx[j - 1])
p = stats.pearsonr(res[c]["rate"][a_], res[c]["rate"][b_])[0]
print(f"neurons {i} and {j}, {c}: noise-corrected {r_:.3f}, bootstrap interval {lo_:.3f} to {hi_:.3f}; Pearson r of mean rates {p:.3f}")
print("Neighbouring pairs among 17 to 20:", [(a, b, round(pair(a, b, 'bright')[0], 3)) for a, b in ((17, 18), (17, 19), (18, 20), (19, 20))])
quantity measured expected tolerance within
similarity 3 and 8, dark 0.780 0.82 0.082 True
similarity 3 and 8, bright 0.894 0.82 0.082 True
similarity 18 and 19, dark -0.000 0.00 0.100 True
similarity 18 and 19, bright -0.144 -0.25 0.025 False
distance 3 and 8 (um) 260.000 260.00 26.000 True
distance 18 and 19 (um) 80.000 80.00 8.000 True
neurons 3 and 8, dark: noise-corrected 0.780, bootstrap interval 0.510 to 0.705; Pearson r of mean rates 0.579
neurons 3 and 8, bright: noise-corrected 0.894, bootstrap interval 0.587 to 0.787; Pearson r of mean rates 0.653
neurons 18 and 19, dark: noise-corrected -0.000, bootstrap interval -0.190 to 0.058; Pearson r of mean rates -0.048
neurons 18 and 19, bright: noise-corrected -0.144, bootstrap interval -0.245 to 0.012; Pearson r of mean rates -0.038
Neighbouring pairs among 17 to 20: [(17, 18, np.float64(0.514)), (17, 19, np.float64(-0.254)), (18, 20, np.float64(0.0)), (19, 20, np.float64(0.188))]
Result: partially reproduced. Neurons 3 and 8 are 260 um apart with similarity 0.780 (dark) and 0.894 (bright), and neurons 18 and 19 are 80 um apart with a dark similarity of 0.000, all within tolerance. The bright similarity of 18 and 19 is -0.144, outside -0.25 +/- 0.025.
ex-m2p6-invariance¶
In M2p6, shape tuning was contrast-invariant (invariance above 0.5) for 19 of the 24 neurons.
Unreliable invariance counts as not above 0.5 (claims file).
for rd in "ab":
n_hi = int(((t.invariance > 0.5) & t[f"inv_rel_{rd}"]).sum())
print(f"reliability {rd}: {n_hi} of {len(t)} neurons with reliable invariance above 0.5 (expected 19 +/- 1.9); "
f"unreliable {int((~t[f'inv_rel_{rd}']).sum())}")
print("Invariance values above 0.5 regardless of reliability:", int((t.invariance > 0.5).sum()))
print("Invariance by Isimilarity significance (dark, a): median", t.groupby("sig_pos_dark_a").invariance.median().round(3).to_dict())
print(t[["num", "invariance", "inv_rel_a", "inv_rel_b"]].round(3).T.to_string())
reliability a: 20 of 24 neurons with reliable invariance above 0.5 (expected 19 +/- 1.9); unreliable 2
reliability b: 22 of 24 neurons with reliable invariance above 0.5 (expected 19 +/- 1.9); unreliable 0
Invariance values above 0.5 regardless of reliability: 22
Invariance by Isimilarity significance (dark, a): median {False: 0.954, True: 0.955}
1021 1020 1019 1018 1017 1016 1015 1014 1013 1012 1023 1024 1011 1010 1009 1008 1022 1007 1006 1005 1003 1004 1002 1001
num 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
invariance 0.988 0.917 0.955 1.0 0.712 1.0 0.933 1.0 1.0 0.948 1.0 0.858 1.0 0.818 0.695 0.968 0.936 1.0 1.0 0.495 0.814 1.0 -0.0 0.954
inv_rel_a True True True True True True True True True True True True False True True True True True True True True False True True
inv_rel_b True True True True True True True True True True True True True True True True True True True True True True True True
Result: reproduced. Under reliability reading (a), 20 of the 24 neurons have a reliable invariance above 0.5 (19 +/- 1.9); under reading (b) 22, outside tolerance. The criterion asks for one reading. Invariance is high whether or not the neuron has a significant Isimilarity (medians 0.955 and 0.954).
ex-m1p12-no-cluster¶
In penetration M1p12, 42 neurons over 2,580 um showed no clustered shape tuning at either contrast; only one neuron had a significant Isimilarity, although most had high contrast invariance of shape tuning.
key12 = found["M1p12"]
t12 = N[(N.monkey == key12[0]) & (N.date == key12[1])].copy()
print("M1p12 =", key12, "| responsive", len(t12), "| span", np.ptp(t12.depth0), "um")
for c in ("dark", "bright"):
for rd in "ab":
print(f"{c}, reliability {rd}: significant positive Isimilarity {int(t12[f'sig_pos_{c}_{rd}'].sum())}, "
f"significant either sign {int(t12[f'sig_any_{c}_{rd}'].sum())} (negative {int((t12[f'sig_any_{c}_{rd}'] & ~t12[f'sig_pos_{c}_{rd}']).sum())}), "
f"lines {int(t12[f'has_line_{c}_{rd}'].sum())}")
s_ = SH[(SH.date == key12[1]) & (SH.contrast == c) & (SH.rd == rd)]
print(f" variant with shared noise subtracted: significant positive {int(s_.sig_pos.sum())}, either sign {int(s_.sig_any.sum())}")
for rd in "ab":
n_hi = int(((t12.invariance > 0.5) & t12[f"inv_rel_{rd}"]).sum())
print(f"reliability {rd}: reliable invariance above 0.5 for {n_hi} of {len(t12)} ({n_hi / len(t12):.0%}); unreliable {int((~t12[f'inv_rel_{rd}']).sum())}")
print("Median invariance:", round(t12.invariance.median(), 3))
M1p12 = ('M1', '20191024') | responsive 42 | span 2580.0 um
dark, reliability a: significant positive Isimilarity 1, significant either sign 4 (negative 3), lines 42
variant with shared noise subtracted: significant positive 1, either sign 4
dark, reliability b: significant positive Isimilarity 1, significant either sign 4 (negative 3), lines 42
variant with shared noise subtracted: significant positive 1, either sign 4
bright, reliability a: significant positive Isimilarity 4, significant either sign 5 (negative 1), lines 42
variant with shared noise subtracted: significant positive 3, either sign 4
bright, reliability b: significant positive Isimilarity 4, significant either sign 5 (negative 1), lines 42
variant with shared noise subtracted: significant positive 3, either sign 4
reliability a: reliable invariance above 0.5 for 35 of 42 (83%); unreliable 1
reliability b: reliable invariance above 0.5 for 36 of 42 (86%); unreliable 0
Median invariance: 0.847
Result: not reproduced. The penetration labelled p12 of M1 has 42 responsive neurons over 2,580 um, and 35 (reliability a) or 36 (b) of 42 have reliable invariance above 0.5. With dark shapes the intercept is significant, its 95% interval excluding zero (the claims file's definition, and the paper's "significantly different from zero"), for 4 neurons under both reliability readings: 1 positive and 3 negative. The criterion allows at most 2, so the count fails, and with it the criterion's partial rule, which needs the count to hold. Counting only significant positive intercepts gives 1, as in the paper. With bright shapes 5 neurons have a significant intercept (4 positive). Subtracting shared noise leaves the dark counts at 1 positive and 4 of either sign.
ex-m1p12-strong-responses¶
In M1p12, peak responses exceeded 15 spikes/s in 28 neurons for dark and 26 for bright shapes.
r12 = shape[key12]
base = V.baseline(r12["arrays"]["blank"])[r12["keep"]]
for c, exp in (("dark", 28), ("bright", 26)):
peak = r12[c]["rate"].max(1)
print(f"{c}: peak above 15 spikes/s, (a) baseline-subtracted {int((peak - base > 15).sum())}, (b) raw {int((peak > 15).sum())}; "
f"expected {exp} +/- {exp * 0.1:.1f}; peaks {peak.min():.1f} to {peak.max():.1f} spikes/s")
dark: peak above 15 spikes/s, (a) baseline-subtracted 28, (b) raw 29; expected 28 +/- 2.8; peaks 5.0 to 142.0 spikes/s bright: peak above 15 spikes/s, (a) baseline-subtracted 26, (b) raw 31; expected 26 +/- 2.6; peaks 5.0 to 139.5 spikes/s
Result: reproduced. With baseline subtracted (reading a), 28 neurons peak above 15 spikes/s for dark shapes and 26 for bright shapes, the paper's numbers; raw rates (reading b) give 29 and 31.
pop-significant-isimilarity¶
Of 1,850 neurons in 74 sessions (6 to 76 per penetration), a minority, 344 (203 in M1, 141 in M2), had a significantly positive Isimilarity with a negative Ssimilarity; the majority (1,504) had an Isimilarity not significantly above zero.
Readings: contrast (dark, bright, either) x reliability (a, b) x slope rule (i: significant positive intercept; ii: and a negative slope). "Not significant" counts neurons with a line and no significant positive intercept.
P = N.groupby(["monkey", "date"]).size()
print("Responsive neurons per penetration: min", P.min(), "max", P.max(), "| penetrations", len(P))
print("Smallest penetrations:", P.nsmallest(4).to_dict())
rows = []
for c in ("dark", "bright", "either"):
for rd in "ab":
for sr in ("i", "ii"):
line, sel = readings(N, rd, c, sr)
g = N[sel].groupby("monkey").size()
rows.append({"contrast": c, "reliability": rd, "slope": sr, "lines": int(line.sum()), "significant": int(sel.sum()),
"M1": int(g.get("M1", 0)), "M2": int(g.get("M2", 0)), "not_significant": int((line & ~sel).sum())})
R = pd.DataFrame(rows)
exp = {"significant": (344, 34.4), "M1": (203, 20.3), "M2": (141, 14.1), "not_significant": (1504, 150.4)}
for k, (v, tol) in exp.items():
R[f"{k}_ok"] = (R[k] - v).abs() <= tol
R["all_four"] = R[[f"{k}_ok" for k in exp]].all(axis=1)
print(R.to_string(index=False))
print("Fewest and most per penetration within tolerance (6 +/- 0.6, 76 +/- 7.6):", abs(P.min() - 6) <= 0.6, abs(P.max() - 76) <= 7.6)
print("Fraction significant, range over readings:", (R.significant / R.lines).min().round(3), "to", (R.significant / R.lines).max().round(3))
Responsive neurons per penetration: min 1 max 77 | penetrations 74
Smallest penetrations: {('M2', '20210529'): 1, ('M1', '20191114'): 6, ('M1', '20191118'): 6, ('M2', '20210422'): 6}
contrast reliability slope lines significant M1 M2 not_significant significant_ok M1_ok M2_ok not_significant_ok all_four
dark a i 1729 400 233 167 1329 False False False False False
dark a ii 1729 394 228 166 1335 False False False False False
dark b i 1805 453 272 181 1352 False False False False False
dark b ii 1805 447 267 180 1358 False False False True False
bright a i 1730 386 230 156 1344 False False False False False
bright a ii 1730 381 226 155 1349 False False True False False
bright b i 1799 449 265 184 1350 False False False False False
bright b ii 1799 443 261 182 1356 False False False True False
either a i 1816 563 330 233 1253 False False False False False
either a ii 1816 555 323 232 1261 False False False False False
either b i 1847 625 364 261 1222 False False False False False
either b ii 1847 617 358 259 1230 False False False False False
Fewest and most per penetration within tolerance (6 +/- 0.6, 76 +/- 7.6): False True
Fraction significant, range over readings: 0.22 to 0.338
Result: not reproduced. Under every reading a minority of neurons with a line has a significant positive Isimilarity (22% to 34%), nearly all with a negative slope, but no reading puts the four counts within tolerance: the closest, dark shapes under reliability (a) with rule (ii), gives 394 (228 in M1, 166 in M2) against 344 (203, 141), and 1,335 not significant against 1,504. Bright (a) (ii) gives 381 (226, 155) and 1,349. Penetrations hold 1 to 77 responsive neurons (6 +/- 0.6 fails); the one with a single neuron is M2 p40, and the next smallest hold 6. The criterion has no partial rule. With shared noise subtracted the counts fall to 243 to 296 (M1 152 to 176, M2 91 to 121), also outside tolerance.
pop-intercept-slope-correlation¶
Across neurons Isimilarity and Ssimilarity are strongly negatively correlated (r = -0.745), and only one neuron (in M2) had both a significantly positive Isimilarity and a significantly positive Ssimilarity.
rows = []
for c in ("dark", "bright"):
for rd in "ab":
x, y = N[f"intercept_{c}_{rd}"], N[f"slope_{c}_{rd}"]
ok = x.notna() & y.notna()
pr, pp = stats.pearsonr(x[ok], y[ok])
sr_, sp_ = stats.spearmanr(x[ok], y[ok])
both = N[f"sig_pos_{c}_{rd}"] & N[f"slope_sig_pos_{c}_{rd}"]
rows.append({"contrast": c, "reliability": rd, "n": int(ok.sum()), "pearson_r": pr, "pearson_p": pp,
"spearman_r": sr_, "spearman_p": sp_, "both_sig_pos": int(both.sum()),
"both_by_monkey": N[both].groupby("monkey").size().to_dict()})
R = pd.DataFrame(rows)
R["pearson_ok"] = ((R.pearson_r + 0.745).abs() <= 0.0745) & (R.pearson_p < 1e-4) & (R.both_sig_pos <= 2)
R["spearman_ok"] = ((R.spearman_r + 0.745).abs() <= 0.0745) & (R.spearman_p < 1e-4) & (R.both_sig_pos <= 2)
print(R.to_string(index=False))
contrast reliability n pearson_r pearson_p spearman_r spearman_p both_sig_pos both_by_monkey pearson_ok spearman_ok
dark a 1729 -0.768378 0.000000e+00 -0.805778 0.0 0 {} True True
dark b 1805 -0.735464 4.079301e-307 -0.816816 0.0 0 {} True True
bright a 1730 -0.667419 1.676697e-223 -0.776630 0.0 0 {} False True
bright b 1799 -0.652626 7.871065e-219 -0.795809 0.0 0 {} False True
Result: reproduced. With dark shapes Pearson's r between Isimilarity and Ssimilarity is -0.768 (reliability a, n = 1,729) or -0.735 (b, n = 1,805), p far below 0.0001, within -0.745 +/- 0.0745; with bright shapes it is -0.667 and -0.653, outside. No neuron has both a significantly positive Isimilarity and a significantly positive Ssimilarity, where the paper reports one; the criterion allows up to 2.
pop-dark-bright-consistent¶
Isimilarity from dark and from bright shapes is consistent across neurons (Spearman's r = 0.435, n = 1,847).
for rd in "ab":
x, y = N[f"intercept_dark_{rd}"], N[f"intercept_bright_{rd}"]
ok = x.notna() & y.notna()
r_, p_ = stats.spearmanr(x[ok], y[ok])
print(f"reliability {rd}: Spearman r = {r_:.3f}, p = {p_:.2g}, n = {int(ok.sum())}; within 0.435 +/- 0.0435: {abs(r_ - 0.435) <= 0.0435}")
for mk in ("M1", "M2"):
s_ = ok & (N.monkey == mk)
print(f" {mk}: Spearman r = {stats.spearmanr(x[s_], y[s_])[0]:.3f}, n = {int(s_.sum())}")
reliability a: Spearman r = 0.484, p = 2.9e-97, n = 1643; within 0.435 +/- 0.0435: False
M1: Spearman r = 0.463, n = 840
M2: Spearman r = 0.500, n = 803
reliability b: Spearman r = 0.520, p = 2.6e-122, n = 1757; within 0.435 +/- 0.0435: False
M1: Spearman r = 0.506, n = 918
M2: Spearman r = 0.532, n = 839
Result: not reproduced. Isimilarity from dark and bright shapes is positively correlated, more strongly than the paper reports: Spearman's r = 0.484 (reliability a, n = 1,643) and 0.520 (b, n = 1,757), p < 1e-90, both above 0.435 +/- 0.0435. The consistency the claim states holds; the value does not.
pop-contrast-invariance¶
More than half of the neurons are well driven and contrast invariant, with a median correlation between dark and bright responses of 0.64.
rows = []
for rd in "ab":
rel = N[f"inv_rel_{rd}"]
v_left = N.invariance[rel]
v_zero = N.invariance.where(rel, 0.0)
pen_left = N[rel].groupby("date").invariance.median()
pen_zero = N.assign(v=v_zero).groupby("date").v.median()
rows += [{"reliability": rd, "reading": "a, all neurons, unreliable left out", "median": v_left.median(), "n": len(v_left)},
{"reliability": rd, "reading": "a, all neurons, unreliable as 0", "median": v_zero.median(), "n": len(v_zero)},
{"reliability": rd, "reading": "b, per-penetration medians, left out", "median": pen_left.median(), "n": len(pen_left)},
{"reliability": rd, "reading": "b, per-penetration medians, as 0", "median": pen_zero.median(), "n": len(pen_zero)}]
print(f"reliability {rd}: neurons with reliable invariance above 0.5: {int(((N.invariance > 0.5) & rel).sum())} of {len(N)} "
f"({((N.invariance > 0.5) & rel).mean():.1%})")
R = pd.DataFrame(rows)
R["within"] = (R["median"] - 0.64).abs() <= 0.064
print(R.round(3).to_string(index=False))
print("By monkey (all neurons, unreliable under a left out):", N[N.inv_rel_a].groupby("monkey").invariance.median().round(3).to_dict())
reliability a: neurons with reliable invariance above 0.5: 918 of 1869 (49.1%)
reliability b: neurons with reliable invariance above 0.5: 1023 of 1869 (54.7%)
reliability reading median n within
a a, all neurons, unreliable left out 0.766 1384 False
a a, all neurons, unreliable as 0 0.474 1869 False
a b, per-penetration medians, left out 0.764 74 False
a b, per-penetration medians, as 0 0.513 74 False
b a, all neurons, unreliable left out 0.770 1546 False
b a, all neurons, unreliable as 0 0.632 1869 True
b b, per-penetration medians, left out 0.765 74 False
b b, per-penetration medians, as 0 0.619 74 True
By monkey (all neurons, unreliable under a left out): {'M1': 0.738, 'M2': 0.816}
Result: reproduced. Under reliability reading (b), with unreliable values counted as 0, the median invariance is 0.632 over all neurons and 0.619 over the per-penetration medians, both within 0.64 +/- 0.064; 54.7% of neurons have reliable invariance above 0.5. Leaving unreliable values out gives medians of 0.76 to 0.77, and reading (a) with unreliable values as 0 gives 0.474 and 0.513; these readings do not match.
pop-sparse-across-penetrations¶
Neurons with significant Isimilarity occur in 55 of the 74 penetrations; only 28 penetrations have five or more such neurons, and 20 penetrations yielded more than 30 neurons.
over30 = int((P > 30).sum())
rows = []
for c in ("dark", "bright", "either"):
for rd in "ab":
for sr in ("i", "ii"):
line, sel = readings(N, rd, c, sr)
per = N[sel].groupby("date").size()
rows.append({"contrast": c, "reliability": rd, "slope": sr, "pens_with_one": len(per), "pens_five_plus": int((per >= 5).sum()),
"pens_over_30": over30})
R = pd.DataFrame(rows)
R["all_three"] = ((R.pens_with_one - 55).abs() <= 5.5) & ((R.pens_five_plus - 28).abs() <= 2.8) & ((R.pens_over_30 - 20).abs() <= 2)
print(R.to_string(index=False))
contrast reliability slope pens_with_one pens_five_plus pens_over_30 all_three
dark a i 58 27 20 True
dark a ii 58 27 20 True
dark b i 59 29 20 True
dark b ii 59 29 20 True
bright a i 54 29 20 True
bright a ii 54 29 20 True
bright b i 56 29 20 True
bright b ii 56 29 20 True
either a i 62 39 20 False
either a ii 62 39 20 False
either b i 62 41 20 False
either b ii 62 40 20 False
Result: reproduced. Under all eight dark and bright readings, 54 to 59 penetrations have at least one neuron with a significant positive Isimilarity (55 +/- 5.5), 27 to 29 have five or more (28 +/- 2.8), and 20 penetrations have more than 30 responsive neurons. The readings counting either contrast give 62 and 39 to 41 penetrations, outside tolerance.
pop-asymptote-20-percent¶
When more than 30 neurons were recorded, the percentage of neurons with significant Isimilarity levels off at about 20%.
def asymptote(N, P, suffix, pens_min=30):
rows = []
big = P[P > pens_min].index.get_level_values("date")
for c in ("dark", "bright", "either") if suffix == ("dark", "bright") else ("original", "reversed", "either"):
for rd in "ab":
for sr in ("i", "ii"):
line, sel = readings(N, rd, c, sr, suffix)
sub = N.date.isin(big)
per = (sel[sub].groupby(N.date[sub]).mean() * 100)
pooled = sel[sub].mean() * 100
small = (sel[~sub].groupby(N.date[~sub]).mean() * 100)
rows.append({"contrast": c, "reliability": rd, "slope": sr, "pens": len(per), "median_pct": per.median(),
"pooled_pct": pooled, "per_pen_range": f"{per.min():.0f}-{per.max():.0f}",
"small_pens_median": small.median()})
R = pd.DataFrame(rows)
R["a_ok"] = (R.median_pct - 20).abs() <= 2
R["b_ok"] = (R.pooled_pct - 20).abs() <= 2
return R
R = asymptote(N, P, ("dark", "bright"))
print(R.round(1).to_string(index=False))
contrast reliability slope pens median_pct pooled_pct per_pen_range small_pens_median a_ok b_ok
dark a i 20 17.9 21.5 0-41 13.3 False True
dark a ii 20 17.9 21.1 0-41 13.3 False True
dark b i 20 21.0 26.1 0-55 13.8 True False
dark b ii 20 21.0 25.6 0-53 13.8 True False
bright a i 20 16.1 21.4 0-50 13.3 False True
bright a ii 20 16.1 21.1 0-48 13.3 False True
bright b i 20 19.4 25.8 0-60 13.3 True False
bright b ii 20 19.4 25.5 0-60 13.3 True False
either a i 20 29.0 31.3 0-59 24.0 False False
either a ii 20 29.0 30.7 0-56 22.4 False False
either b i 20 33.2 35.6 0-70 25.8 False False
either b ii 20 33.2 35.0 0-67 25.0 False False
Result: reproduced. Over the 20 penetrations with more than 30 neurons, the pooled percentage with a significant positive Isimilarity is 21.1% to 21.5% with dark or bright shapes under reliability (a), and the median per penetration is 19.4% to 21.0% under reliability (b), within 20 +/- 2. Per-penetration values range from 0% to 60%; counting either contrast gives 29% to 36%.
pop-mean-isimilarity-yield¶
In penetrations with few neurons the mean Isimilarity varies widely across penetrations; with more than 30 neurons it levels off.
for c in ("dark", "bright"):
for rd in "ab":
m = N.groupby("date")[f"intercept_{c}_{rd}"].mean()
n = N.groupby("date").size()
big, small = m[n > 30].dropna(), m[n <= 30].dropna()
lev = stats.levene(big, small)
print(f"{c}, {rd}: SD of penetration means, >30 neurons {big.std():.3f} (n = {len(big)}), <=30 {small.std():.3f} (n = {len(small)}); "
f"Levene W = {lev.statistic:.2f}, p = {lev.pvalue:.2g}; ranges {big.min():.3f} to {big.max():.3f} and {small.min():.3f} to {small.max():.3f}")
fig, ax = plt.subplots(figsize=(5, 3.5))
m = N.groupby("date").intercept_dark_a.mean()
n = N.groupby("date").size()
ax.scatter(n, m, s=12, color="k")
ax.set_xlabel("responsive neurons in penetration"); ax.set_ylabel("mean Isimilarity, dark (a)")
ax.set_title(f"y range {m.min():.2f} to {m.max():.2f}; x range {n.min()} to {n.max()}")
plt.show()
dark, a: SD of penetration means, >30 neurons 0.089 (n = 20), <=30 0.204 (n = 52); Levene W = 6.22, p = 0.015; ranges -0.021 to 0.287 and -0.225 to 0.887 dark, b: SD of penetration means, >30 neurons 0.104 (n = 20), <=30 0.201 (n = 52); Levene W = 4.35, p = 0.041; ranges -0.058 to 0.351 and -0.225 to 0.902
bright, a: SD of penetration means, >30 neurons 0.084 (n = 20), <=30 0.127 (n = 52); Levene W = 3.96, p = 0.051; ranges -0.029 to 0.263 and -0.108 to 0.458 bright, b: SD of penetration means, >30 neurons 0.107 (n = 20), <=30 0.133 (n = 53); Levene W = 1.79, p = 0.18; ranges -0.007 to 0.366 and -0.108 to 0.452
Result: reproduced. The SD of the penetration means of Isimilarity is smaller for penetrations with more than 30 neurons than for those with 30 or fewer under all four contrast and reliability readings (dark 0.089 against 0.204 under a, Levene p = 0.015; bright under b 0.107 against 0.133, Levene p = 0.18). No contrast reading reproduces pop-significant-isimilarity, so all are shown.
pop-recording-density¶
The fraction of neurons with significant Isimilarity is only weakly related to the recording density (Pearson's r = 0.236, p = 0.0429).
Penetrations with one responsive neuron have no density and are left out.
span = N.groupby("date").depth0.agg(np.ptp)
n = N.groupby("date").size()
ok = (span > 0)
rows = []
for c in ("dark", "bright", "either"):
for rd in "ab":
for sr in ("i", "ii"):
line, sel = readings(N, rd, c, sr)
pct = sel.groupby(N.date).mean() * 100
for dens_name, dens in (("a, neurons per um", n / span), ("b, um per neuron", span / n)):
r_, p_ = stats.pearsonr(dens[ok], pct[ok])
rows.append({"contrast": c, "reliability": rd, "slope": sr, "density": dens_name, "r": r_, "p": p_, "n": int(ok.sum())})
R = pd.DataFrame(rows)
R["ok"] = ((R.r - 0.236).abs() <= 0.0236) & (R.p < 0.05)
print(R.round(4).to_string(index=False))
contrast reliability slope density r p n ok
dark a i a, neurons per um 0.2571 0.0281 73 True
dark a i b, um per neuron -0.3554 0.0020 73 False
dark a ii a, neurons per um 0.2550 0.0295 73 True
dark a ii b, um per neuron -0.3553 0.0020 73 False
dark b i a, neurons per um 0.3234 0.0053 73 False
dark b i b, um per neuron -0.3907 0.0006 73 False
dark b ii a, neurons per um 0.3158 0.0065 73 False
dark b ii b, um per neuron -0.3922 0.0006 73 False
bright a i a, neurons per um 0.2557 0.0290 73 True
bright a i b, um per neuron -0.3651 0.0015 73 False
bright a ii a, neurons per um 0.2545 0.0298 73 True
bright a ii b, um per neuron -0.3661 0.0014 73 False
bright b i a, neurons per um 0.2960 0.0110 73 False
bright b i b, um per neuron -0.3873 0.0007 73 False
bright b ii a, neurons per um 0.3003 0.0098 73 False
bright b ii b, um per neuron -0.3905 0.0006 73 False
either a i a, neurons per um 0.3213 0.0056 73 False
either a i b, um per neuron -0.4457 0.0001 73 False
either a ii a, neurons per um 0.3154 0.0066 73 False
either a ii b, um per neuron -0.4414 0.0001 73 False
either b i a, neurons per um 0.3362 0.0036 73 False
either b i b, um per neuron -0.4554 0.0001 73 False
either b ii a, neurons per um 0.3300 0.0044 73 False
either b ii b, um per neuron -0.4555 0.0001 73 False
Result: reproduced. With density read as neurons per um (reading a), Pearson's r is 0.254 to 0.257 under the dark and bright readings with reliability (a) (p = 0.028 to 0.030, 73 penetrations), within 0.236 +/- 0.0236; reliability (b) and either contrast give 0.296 to 0.336. Read as um per neuron (the legend's quotient), r is negative (-0.355 to -0.456).
pop-within-vs-across-sessions¶
Neurons within a penetration have slightly more similar shape tuning than neurons from different sessions (mean correlation 0.0582 against 0.0022), and more so within 200 um (0.0918 against 0.0435 further apart).
Readings: (1) coefficient, (a) Pearson's r of mean rates over the 120 shapes, (b) the noise-corrected similarity (point estimates, all pairs, so that same- and different-session pairs are treated alike; same-session pairs restricted to reliable values are shown as a variant); (2) contrast, dark, bright, or both as separate pairs; (3) cross-session pairs from all sessions or within one monkey. Pairs of responsive neurons, each pair once.
def all_pairs(c):
M, S2, INV, RATE, ses, mk, dep = [], [], [], [], [], [], []
for (m_, d), r in shape.items():
if r["keep"].sum() == 0:
continue
arr, nrep = r["arrays"][c]
mx, s2, inv = V._moments(arr[r["keep"]], nrep)
M.append(mx); S2.append(s2); INV.append(np.broadcast_to(inv, mx.shape)); RATE.append(r[c]["rate"])
ses += [d] * len(mx); mk += [m_] * len(mx); dep.append(r["depth0"][r["keep"]])
M, S2, INV, RATE = np.vstack(M), np.concatenate(S2), np.vstack(INV), np.vstack(RATE)
ses, mk, dep = np.array(ses), np.array(mk), np.concatenate(dep)
nc = V.nc_corr(M, S2, INV, M, S2, INV)
pe = V.pearson_rows(RATE, RATE)
iu = np.triu_indices(len(M), 1)
same = ses[iu[0]] == ses[iu[1]]
same_mk = mk[iu[0]] == mk[iu[1]]
dist = np.abs(dep[iu[0]] - dep[iu[1]])
return {"nc": nc[iu], "pearson": pe[iu], "same": same, "same_mk": same_mk, "dist": dist}
pairs = {c: all_pairs(c) for c in ("dark", "bright")}
rows = []
for coef in ("pearson", "nc"):
for c in ("dark", "bright", "both"):
cs = ("dark", "bright") if c == "both" else (c,)
v = np.concatenate([pairs[x][coef] for x in cs]); same = np.concatenate([pairs[x]["same"] for x in cs])
smk = np.concatenate([pairs[x]["same_mk"] for x in cs]); dist = np.concatenate([pairs[x]["dist"] for x in cs])
fin = np.isfinite(v)
for cross in ("all", "within monkey"):
other = fin & ~same & (smk if cross == "within monkey" else True)
w = fin & same
near, far = w & (dist <= 200), w & (dist > 200)
t1 = stats.ttest_ind(v[w], v[other], equal_var=False)
t2 = stats.ttest_ind(v[near], v[far], equal_var=False)
rows.append({"coef": coef, "contrast": c, "cross": cross, "different": v[other].mean(), "same": v[w].mean(),
"near": v[near].mean(), "far": v[far].mean(), "p_same_vs_diff": t1.pvalue, "p_near_vs_far": t2.pvalue,
"n_same": int(w.sum()), "n_diff": int(other.sum()), "n_near": int(near.sum()), "n_far": int(far.sum())})
R = pd.DataFrame(rows)
R["dir_p_ok"] = (R.same > R.different) & (R.near > R.far) & (R.p_same_vs_diff < 1e-4) & (R.p_near_vs_far < 1e-4)
R["means_ok"] = (((R.different - 0.0022).abs() <= 0.00022) & ((R.same - 0.0582).abs() <= 0.00582)
& ((R.near - 0.0918).abs() <= 0.00918) & ((R.far - 0.0435).abs() <= 0.00435))
print(R.round(4).to_string(index=False))
print()
# variant: same-session noise-corrected values restricted to reliable ones
for c in ("dark", "bright"):
for rd in "ab":
vals, dists = [], []
for r in shape.values():
if r["keep"].sum() < 2:
continue
rel = V.reliable(r[c]["r"], r[c]["lo"], r[c]["hi"], rd)
iu = np.triu_indices(r["keep"].sum(), 1)
d = r["depth0"][r["keep"]]
sel = rel[iu]
vals.append(r[c]["r"][iu][sel]); dists.append(np.abs(d[iu[0]] - d[iu[1]])[sel])
v, dd = np.concatenate(vals), np.concatenate(dists)
print(f"variant, reliable same-session pairs only, {c} {rd}: mean {v.mean():.4f} (n = {len(v)}), <=200 um {v[dd <= 200].mean():.4f}, >200 um {v[dd > 200].mean():.4f}")
coef contrast cross different same near far p_same_vs_diff p_near_vs_far n_same n_diff n_near n_far dir_p_ok means_ok
pearson dark all 0.0025 0.0295 0.0732 0.0191 0.0 0.0 34580 1711066 6618 27962 True False
pearson dark within monkey 0.0036 0.0295 0.0732 0.0191 0.0 0.0 34580 838156 6618 27962 True False
pearson bright all 0.0021 0.0317 0.0744 0.0215 0.0 0.0 34580 1711066 6618 27962 True False
pearson bright within monkey 0.0023 0.0317 0.0744 0.0215 0.0 0.0 34580 838156 6618 27962 True False
pearson both all 0.0023 0.0306 0.0738 0.0203 0.0 0.0 69160 3422132 13236 55924 True False
pearson both within monkey 0.0030 0.0306 0.0738 0.0203 0.0 0.0 69160 1676312 13236 55924 True False
nc dark all 0.0059 0.0827 0.1962 0.0557 0.0 0.0 25754 1281542 4948 20806 True False
nc dark within monkey 0.0086 0.0827 0.1962 0.0557 0.0 0.0 25754 627737 4948 20806 True False
nc bright all 0.0069 0.0901 0.1947 0.0655 0.0 0.0 25812 1301494 4916 20896 True False
nc bright within monkey 0.0075 0.0901 0.1947 0.0655 0.0 0.0 25812 639049 4916 20896 True False
nc both all 0.0064 0.0864 0.1955 0.0606 0.0 0.0 51566 2583036 9864 41702 True False
nc both within monkey 0.0081 0.0864 0.1955 0.0606 0.0 0.0 51566 1266786 9864 41702 True False
variant, reliable same-session pairs only, dark a: mean 0.0680 (n = 24354), <=200 um 0.1700, >200 um 0.0446
variant, reliable same-session pairs only, dark b: mean 0.0827 (n = 25740), <=200 um 0.1962, >200 um 0.0557
variant, reliable same-session pairs only, bright a: mean 0.0729 (n = 24425), <=200 um 0.1631, >200 um 0.0525
variant, reliable same-session pairs only, bright b: mean 0.0901 (n = 25799), <=200 um 0.1949, >200 um 0.0655
Result: partially reproduced. Under every reading same-session pairs are more similar than different-session pairs and pairs within 200 um more than pairs further apart (Welch p below 1e-4 throughout). No reading matches all four means: Pearson's r of mean rates gives 0.0021 to 0.0036 across sessions (within 0.0022 +/- 0.00022 for bright shapes and for both contrasts over all sessions) but 0.0295 to 0.0317 within (0.0582 in the paper), 0.073 to 0.074 within 200 um and 0.019 to 0.022 beyond; the noise-corrected values are 0.006 to 0.009, 0.083 to 0.090, 0.195 and 0.056 to 0.066. All means are weak, as the paper says.
orientation-auc-coarse-clusters¶
Assayed at a coarse scale with two orthogonal orientations of the spindle shape, some penetrations consist entirely of neurons preferring horizontal or vertical, and in others the preference switches along the probe.
Shape 1 is taken to be stim_ID 0 (the files number shapes 0 to 14; Figure 1B numbers them 1 to 15),
and rotations 0 and 180 degrees horizontal, 90 and 270 vertical (Materials and Methods, Feature
models). This rests on the dataset's labels following the paper's numbering, which the files do not
document. Per responsive neuron, the AUC of presentation spike counts, vertical against horizontal,
both contrasts pooled; averaged in 100 um depth bins from the most superficial neuron. Bins with a
mean of exactly 0.5 are left out of the classification.
def pen_auc(key, stim=0):
s = by_date[key]["SL"]
tr = s["trials"]
keep = shape[key]["keep"]
lum = tr.luminance.isin([V.DARK, V.BRIGHT])
hor = (lum & (tr.stim_ID == stim) & tr.rotation.isin([0, 180])).to_numpy()
ver = (lum & (tr.stim_ID == stim) & tr.rotation.isin([90, 270])).to_numpy()
au = np.array([V.auc(s["counts"][u, ver], s["counts"][u, hor]) for u in np.flatnonzero(keep)])
d = shape[key]["depth0"][keep]
bins = (d // 100).astype(int)
b = pd.Series(au).groupby(bins).mean().sort_index()
return au, b, int(hor.sum()), int(ver.sum())
def classify(b):
side = np.sign(b.dropna() - 0.5)
side = side[side != 0].to_numpy()
if len(side) == 0:
return "none"
if np.all(side == side[0]):
return "all one"
changes = int((np.diff(side) != 0).sum())
return "switching" if changes == 1 else f"mixed ({changes} changes)"
kinds = {}
for key, r in shape.items():
if r["keep"].sum() == 0:
continue
au, b, nh, nv = pen_auc(key)
kinds[key] = {"class": classify(b), "bins": len(b), "neurons": len(au), "hor_pres": nh, "ver_pres": nv,
"frac_vertical_bins": float((b > 0.5).mean())}
K = pd.DataFrame(kinds).T
print(K["class"].value_counts().to_string())
print("Of these, penetrations with at least 3 occupied bins:", K[K.bins >= 3]["class"].value_counts().to_dict())
for name in ("M2p6", "M1p5"):
key = found[name]
au, b, nh, nv = pen_auc(key)
print(f"{name} {key}: class {classify(b)}, {len(au)} neurons, {len(b)} bins, horizontal/vertical presentations {nh}/{nv}")
print(" bin means (100 um bins from the top):", b.round(2).to_dict())
var = []
for st in range(15):
cls = {name: classify(pen_auc(found[name], st)[1]) for name in ("M2p6", "M1p5")}
allk = pd.Series({k: classify(pen_auc(k, st)[1]) for k, r in shape.items() if r["keep"].sum() > 0})
var.append({"stim_ID": st, **cls, "all_one": int((allk == "all one").sum()), "switching": int((allk == "switching").sum())})
print("Variant, each stim_ID taken as the spindle:")
print(pd.DataFrame(var).to_string(index=False))
fig, ax = plt.subplots(1, 2, figsize=(8, 3.5))
for k, name in enumerate(("M2p6", "M1p5")):
au, b, _, _ = pen_auc(found[name])
ax[k].barh(b.index * 100, b.to_numpy() - 0.5, height=90, left=0.5, color=np.where(b > 0.5, "tab:red", "tab:blue"))
ax[k].axvline(0.5, color="k", lw=0.5); ax[k].invert_yaxis()
ax[k].set_xlabel("mean AUC (vertical > 0.5)"); ax[k].set_ylabel("depth bin (um)")
ax[k].set_title(f"{name}: AUC {b.min():.2f} to {b.max():.2f}")
plt.tight_layout(); plt.show()
class
mixed (5 changes) 12
mixed (3 changes) 11
mixed (2 changes) 10
mixed (7 changes) 7
mixed (4 changes) 7
mixed (8 changes) 6
mixed (10 changes) 5
mixed (9 changes) 4
mixed (6 changes) 4
mixed (12 changes) 2
all one 2
switching 2
mixed (11 changes) 1
mixed (14 changes) 1
Of these, penetrations with at least 3 occupied bins: {'mixed (5 changes)': 12, 'mixed (3 changes)': 11, 'mixed (2 changes)': 10, 'mixed (7 changes)': 7, 'mixed (4 changes)': 7, 'mixed (8 changes)': 6, 'mixed (10 changes)': 5, 'mixed (9 changes)': 4, 'mixed (6 changes)': 4, 'mixed (12 changes)': 2, 'switching': 2, 'mixed (11 changes)': 1, 'all one': 1, 'mixed (14 changes)': 1}
M2p6 ('M2', '20210414'): class mixed (2 changes), 24 neurons, 17 bins, horizontal/vertical presentations 18/19
bin means (100 um bins from the top): {0: 0.17, 1: 0.41, 2: 0.2, 3: 0.36, 4: 0.16, 5: 0.32, 9: 1.0, 11: 0.87, 13: 0.75, 14: 0.69, 15: 0.58, 17: 0.61, 18: 0.73, 19: 0.75, 20: 0.68, 22: 0.37, 23: 0.38}
M1p5 ('M1', '20190726'): class mixed (12 changes), 60 neurons, 25 bins, horizontal/vertical presentations 18/17
bin means (100 um bins from the top): {0: 0.56, 1: 0.81, 2: 0.57, 3: 0.72, 4: 0.5, 5: 0.5, 6: 0.57, 7: 0.54, 8: 0.81, 9: 0.46, 10: 0.67, 11: 0.61, 12: 0.5, 13: 0.47, 14: 0.65, 15: 0.34, 16: 0.82, 17: 0.42, 18: 0.79, 19: 0.6, 20: 0.49, 21: 0.64, 22: 0.65, 23: 0.59, 24: 0.7}
Variant, each stim_ID taken as the spindle:
stim_ID M2p6 M1p5 all_one switching
0 mixed (2 changes) mixed (12 changes) 2 2
1 mixed (5 changes) mixed (10 changes) 2 4
2 mixed (6 changes) mixed (10 changes) 3 4
3 mixed (5 changes) mixed (10 changes) 4 5
4 mixed (8 changes) mixed (10 changes) 2 2
5 mixed (4 changes) mixed (9 changes) 2 4
6 mixed (7 changes) mixed (12 changes) 1 5
7 mixed (6 changes) mixed (8 changes) 1 1
8 mixed (9 changes) mixed (13 changes) 1 2
9 mixed (4 changes) mixed (7 changes) 1 4
10 mixed (7 changes) mixed (15 changes) 2 3
11 mixed (5 changes) mixed (10 changes) 2 0
12 mixed (12 changes) mixed (10 changes) 2 3
13 mixed (3 changes) mixed (7 changes) 1 5
14 mixed (9 changes) mixed (10 changes) 1 3
Result: not reproduced. Taking stim_ID 0 as the spindle, 2 of 74 penetrations are all one preference and 2 switch once, so both kinds exist, but neither M2p6 nor M1p5 is of one kind: M2p6 has bins preferring horizontal at the top (bins 0 to 5, 0 to 599 um), vertical below and horizontal again in its two deepest bins (2 changes), and M1p5 changes side 12 times. No stim_ID taken as the spindle makes either penetration of one kind.
texture-sparse-clusters¶
For textures, of 979 neurons in 51 sessions (6 to 83 per penetration), a small subset (207; 18 in M1, 189 in M2) across 34 of 51 penetrations (7 in M1, 27 in M2) showed clustered selectivity, and 16 penetrations had five or more neurons with significant Isimilarity.
PT = T.groupby(["monkey", "date"]).size()
print("Texture neurons", len(T), "in", len(PT), "penetrations; per penetration", PT.min(), "to", PT.max())
bad_tx = sorted(clock[(clock.kind == "TX") & ~clock.established].date)
print("M1 texture files where the clock is not established (left out in the variant):", bad_tx)
for d in bad_tx:
r_ = texture[("M1", d)]
cl = clock[(clock.kind == "TX") & (clock.date == d)].iloc[0]
b_ = V.baseline(r_["arrays"]["blank"])
pk = np.max([np.nanmax(V.rates(r_["arrays"][v][0]), axis=1) for v in ("original", "reversed")], axis=0)
print(f" {d}: {r_['good']} good units, {int(r_['keep'].sum())} responsive, stimulus-selective {cl.true:.0%}, responding more to stimuli than blanks {cl.onset_resp:.0%}; "
f"median peak minus baseline {np.median(pk - b_):.1f} spikes/s; {int(T[T.date == d].has_line_original_a.sum())} lines (original, a)")
print("Responsive fraction of good units, other M1 texture files (median):",
round(float(np.median([r_["keep"].mean() for (m_, d), r_ in texture.items() if m_ == "M1" and d not in bad_tx])), 2))
def texture_counts(T, PT):
rows = []
for c in ("original", "reversed", "either"):
for rd in "ab":
for sr in ("i", "ii"):
line, sel = readings(T, rd, c, sr, ("original", "reversed"))
g = T[sel].groupby("monkey").size()
per = T[sel].groupby(["monkey", "date"]).size()
pm = per.groupby(level=0).size()
rows.append({"contrast": c, "reliability": rd, "slope": sr, "lines": int(line.sum()), "sig": int(sel.sum()),
"M1": int(g.get("M1", 0)), "M2": int(g.get("M2", 0)), "pens": len(per), "pens_M1": int(pm.get("M1", 0)),
"pens_M2": int(pm.get("M2", 0)), "pens_5plus": int((per >= 5).sum())})
R = pd.DataFrame(rows)
exp = {"sig": (207, 20.7), "M1": (18, 1.8), "M2": (189, 18.9), "pens": (34, 3.4), "pens_M1": (7, 0.7), "pens_M2": (27, 2.7), "pens_5plus": (16, 1.6)}
for k, (v, tol) in exp.items():
R[f"{k}_ok"] = (R[k] - v).abs() <= tol
R["most_ok"] = abs(PT.max() - 83) <= 8.3
R["all"] = R[[f"{k}_ok" for k in exp] + ["most_ok"]].all(axis=1)
R["total_and_pens"] = R[["sig_ok", "pens_ok", "pens_5plus_ok", "most_ok"]].all(axis=1)
R["frac_of_lines"] = (R.sig / R.lines).round(3)
return R.drop(columns=[f"{k}_ok" for k in exp])
print(texture_counts(T, PT).to_string(index=False))
print("Neurons without a line (paper: 48 of 979): original", int((~T.has_line_original_a).sum()), "/", int((~T.has_line_original_b).sum()),
"| reversed", int((~T.has_line_reversed_a).sum()), "/", int((~T.has_line_reversed_b).sum()), "(reliability a / b)")
T_ok = T[~T.date.isin(bad_tx)]
PT_ok = T_ok.groupby(["monkey", "date"]).size()
print()
print(f"Variant without the {len(bad_tx)} files: {len(T_ok)} neurons in {len(PT_ok)} penetrations ({int((T_ok.monkey == 'M1').sum())} M1 neurons in {int((PT_ok.index.get_level_values(0) == 'M1').sum())} penetrations)")
print(texture_counts(T_ok, PT_ok).to_string(index=False))
Texture neurons 985 in 51 penetrations; per penetration 6 to 83
M1 texture files where the clock is not established (left out in the variant): ['20200715', '20200719', '20200729', '20200730', '20200804']
20200715: 25 good units, 14 responsive, stimulus-selective 4%, responding more to stimuli than blanks 28%; median peak minus baseline 7.7 spikes/s; 0 lines (original, a)
20200719: 20 good units, 11 responsive, stimulus-selective 0%, responding more to stimuli than blanks 40%; median peak minus baseline 7.7 spikes/s; 0 lines (original, a)
20200729: 17 good units, 14 responsive, stimulus-selective 12%, responding more to stimuli than blanks 47%; median peak minus baseline 10.5 spikes/s; 0 lines (original, a)
20200730: 31 good units, 24 responsive, stimulus-selective 6%, responding more to stimuli than blanks 39%; median peak minus baseline 11.6 spikes/s; 0 lines (original, a)
20200804: 22 good units, 16 responsive, stimulus-selective 5%, responding more to stimuli than blanks 9%; median peak minus baseline 13.4 spikes/s; 0 lines (original, a)
Responsive fraction of good units, other M1 texture files (median): 0.67
contrast reliability slope lines sig M1 M2 pens pens_M1 pens_M2 pens_5plus most_ok all total_and_pens frac_of_lines
original a i 681 193 12 181 30 4 26 15 True False False 0.283
original a ii 681 185 12 173 29 4 25 15 True False False 0.272
original b i 923 304 50 254 37 10 27 22 True False False 0.329
original b ii 923 276 41 235 37 10 27 20 True False False 0.299
reversed a i 663 198 7 191 27 2 25 15 True False False 0.299
reversed a ii 663 190 7 183 27 2 25 14 True False False 0.287
reversed b i 941 308 57 251 37 12 25 24 True False False 0.327
reversed b ii 941 279 47 232 37 12 25 22 True False False 0.296
either a i 720 259 14 245 31 4 27 19 True False False 0.360
either a ii 720 249 14 235 31 4 27 19 True False False 0.346
either b i 970 395 79 316 42 15 27 28 True False False 0.407
either b ii 970 366 72 294 42 15 27 27 True False False 0.377
Neurons without a line (paper: 48 of 979): original 304 / 62 | reversed 322 / 44 (reliability a / b)
Variant without the 5 files: 906 neurons in 46 penetrations (221 M1 neurons in 12 penetrations)
contrast reliability slope lines sig M1 M2 pens pens_M1 pens_M2 pens_5plus most_ok all total_and_pens frac_of_lines
original a i 681 193 12 181 30 4 26 15 True False False 0.283
original a ii 681 185 12 173 29 4 25 15 True False False 0.272
original b i 856 300 46 254 34 7 27 22 True False False 0.350
original b ii 856 272 37 235 34 7 27 20 True False False 0.318
reversed a i 663 198 7 191 27 2 25 15 True False False 0.299
reversed a ii 663 190 7 183 27 2 25 14 True False False 0.287
reversed b i 871 296 45 251 33 8 25 23 True False False 0.340
reversed b ii 871 267 35 232 33 8 25 21 True False False 0.307
either a i 720 259 14 245 31 4 27 19 True False False 0.360
either a ii 720 249 14 235 31 4 27 19 True False False 0.346
either b i 893 379 63 316 38 11 27 27 True False False 0.424
either b ii 893 350 56 294 38 11 27 26 True False False 0.392
Result: not reproduced. Over 985 texture neurons in 51 penetrations (6 to 83 per penetration), no reading puts the counts within tolerance. The closest, original or reversed textures under reliability (a), give 193 and 198 neurons (207 +/- 20.7) but 30 and 27 penetrations (34 +/- 3.4), 4 and 2 penetrations in M1 (7) and 12 and 7 neurons in M1 (18). Reliability (b) gives 276 to 395 neurons in 37 to 42 penetrations, 41 to 79 of them in M1. Under every reading a minority of the neurons with a line is clustered (27% to 41%). Five M1 texture files fail the clock check: their units respond to stimulus onset (9% to 47% fire more than on blanks, against a median of 41%) but 0% to 12% are selective among the textures, and no neuron in them has a line under reliability (a). Leaving them out leaves the reliability (a) counts unchanged and gives 267 to 379 neurons in 33 to 38 penetrations (7 to 11 in M1) under (b); no reading matches.
texture-original-reversed-consistent¶
Texture Isimilarity from original and contrast-reversed textures is consistent across neurons (Spearman's r = 0.464, n = 905).
for label, tab in (("all files", T), (f"without the {len(bad_tx)} files where the clock is not established", T_ok)):
print(label)
for rd in "ab":
x, y = tab[f"intercept_original_{rd}"], tab[f"intercept_reversed_{rd}"]
ok = x.notna() & y.notna()
r_, p_ = stats.spearmanr(x[ok], y[ok])
print(f" reliability {rd}: Spearman r = {r_:.3f}, p = {p_:.2g}, n = {int(ok.sum())}; r within 0.464 +/- 0.0464: {abs(r_ - 0.464) <= 0.0464}; "
f"n within 905 +/- 90.5: {abs(ok.sum() - 905) <= 90.5}")
all files
reliability a: Spearman r = 0.706, p = 3.4e-95, n = 624; r within 0.464 +/- 0.0464: False; n within 905 +/- 90.5: False
reliability b: Spearman r = 0.642, p = 3.3e-105, n = 894; r within 0.464 +/- 0.0464: False; n within 905 +/- 90.5: True
without the 5 files where the clock is not established
reliability a: Spearman r = 0.706, p = 3.4e-95, n = 624; r within 0.464 +/- 0.0464: False; n within 905 +/- 90.5: False
reliability b: Spearman r = 0.675, p = 9.2e-112, n = 834; r within 0.464 +/- 0.0464: False; n within 905 +/- 90.5: True
Result: not reproduced. Texture Isimilarity from original and reversed textures is positively correlated, more strongly than the paper reports: Spearman's r = 0.706 (reliability a, n = 624) and 0.642 (b, n = 894), against 0.464 +/- 0.0464. The neuron count under (b), 894, is within 905 +/- 90.5. Without the five files where the clock is not established r is 0.706 (a) and 0.675 (b).
texture-asymptote-20-percent¶
For textures as for shapes, the fraction of neurons with a significant intercept levels off at about 20% when many neurons are recorded.
RT = asymptote(T, PT, ("original", "reversed"))
print("Texture penetrations with more than 30 neurons:", int((PT > 30).sum()), "| of them in the files where the clock is not established:",
int(PT[PT > 30].index.get_level_values(1).isin(bad_tx).sum()))
print(RT.round(1).to_string(index=False))
RT_ok = asymptote(T_ok, PT_ok, ("original", "reversed"))
print(f"Variant without the {len(bad_tx)} files: pooled {RT_ok.pooled_pct.min():.1f}% to {RT_ok.pooled_pct.max():.1f}%, median {RT_ok.median_pct.min():.1f}% to {RT_ok.median_pct.max():.1f}%")
Texture penetrations with more than 30 neurons: 7 | of them in the files where the clock is not established: 0 contrast reliability slope pens median_pct pooled_pct per_pen_range small_pens_median a_ok b_ok original a i 7 30.2 26.8 9-34 4.1 False False original a ii 7 28.9 25.6 9-34 2.0 False False original b i 7 45.8 43.8 12-66 14.3 False False original b ii 7 42.2 38.7 12-56 14.3 False False reversed a i 7 33.7 29.1 3-56 0.0 False False reversed a ii 7 31.3 27.5 3-47 0.0 False False reversed b i 7 40.0 40.3 3-69 11.8 False False reversed b ii 7 34.3 34.8 3-56 11.8 False False either a i 7 42.9 37.4 12-62 5.0 False False either a ii 7 39.8 35.5 12-53 5.0 False False either b i 7 51.4 52.1 12-81 28.6 False False either b ii 7 45.7 47.3 12-75 26.6 False False Variant without the 5 files: pooled 25.6% to 52.1%, median 28.9% to 51.4%
Result: not reproduced. Seven texture penetrations have more than 30 neurons, none of them among the five files where the clock is not established. In them the percentage with a significant intercept is 25.6% to 52.1% pooled and 28.9% to 51.4% as a median, above 20 +/- 2 under every reading.
position-optimal-consistent¶
In 33 M2 penetrations (723 neurons), Isimilarity computed from responses at each neuron's optimal stimulus position correlates positively with Isimilarity at the aggregate RF center (r = 0.325).
The files number the five positions 0 to 4 without saying which is the center. The center is taken
to be the position with the largest mean response over the penetration's responsive neurons,
since the aggregate RF center is where the stimuli were centred on the neurons' RFs (an
assumption); how often each position wins is printed. Neurons are those responsive in the main
shape test (the same units, by unit_ID); responsiveness within the position test is a variant.
Penetrations enter with 4 or more neurons, since a line needs 3 other neurons with reliable similarities
(Materials and Methods, Clusters of similarly tuned neurons); this follows from the line rule and is not a separate
choice. Optimal position: the largest variance-to-mean ratio of mean rates over the 15 shapes (Materials
and Methods, RF localization, paragraph 2).
t0 = time.time()
pos = {}
for (mk, d), g in by_date.items():
if "SP" not in g:
continue
s = g["SP"]
A = V.position_arrays(s)
keep_shape = shape[(mk, d)]["keep"]
keep_pos = V.responsive([A[p][0] for p in range(5)], A["blank"])
rates_p = np.stack([V.rates(A[p][0]) for p in range(5)]) # (pos, unit, stim)
pop = np.nanmean(rates_p[:, keep_shape], axis=(1, 2)) if keep_shape.any() else np.full(5, np.nan)
pos[(mk, d)] = {"A": A, "keep_shape": keep_shape, "keep_pos": keep_pos, "rates": rates_p,
"center": int(np.nanargmax(pop)) if np.isfinite(pop).any() else None, "pop": pop,
"depth0": s["units"].depth0.to_numpy()}
centers = pd.Series({k: v["center"] for k, v in pos.items()})
print("Position test files:", len(pos), "| position with the largest population response:", centers.value_counts().to_dict())
def optimal_isim(p, keep, tag):
A, rates_p = p["A"], p["rates"]
with np.errstate(invalid="ignore", divide="ignore"):
disp = np.nanvar(rates_p, axis=2, ddof=1) / np.nanmean(rates_p, axis=2)
best = np.nanargmax(np.nan_to_num(disp, nan=-1), axis=0)
R = max(A[q][0].shape[2] for q in range(5))
pad = {q: np.pad(A[q][0], ((0, 0), (0, 0), (0, R - A[q][0].shape[2])), constant_values=np.nan) for q in range(5)}
nreps = np.stack([A[q][1] for q in range(5)])
# each neuron uses its own position; the repeats per stimulus are taken as the smallest over the
# positions in use, so that every resampled repeat exists (the files have 8 at every position)
nrep = nreps[np.unique(best)].min(0)
arr = np.stack([pad[best[u]][u] for u in range(len(best))])[:, :, : nrep.max()]
for j in range(arr.shape[1]):
arr[:, j, nrep[j]:] = np.nan
r, lo, hi = V.similarity(arr[keep], nrep, tag)
out = {"best": best}
for rd in "ab":
out[rd] = V.isimilarity(r, V.reliable(r, lo, hi, rd), p["depth0"][keep], np.ones(keep.sum(), bool))
return out
def position_isim(p, keep, q, tag):
arr, nrep = p["A"][q]
r, lo, hi = V.similarity(arr[keep], nrep, tag)
return {rd: V.isimilarity(r, V.reliable(r, lo, hi, rd), p["depth0"][keep], np.ones(keep.sum(), bool)) for rd in "ab"} | {"r": r, "lo": lo, "hi": hi}
rows = []
pos_res = {}
for (mk, d), p in pos.items():
for which, keep in (("shape-responsive", p["keep_shape"]), ("position-responsive", p["keep_pos"])):
if keep.sum() < 4:
continue
o = optimal_isim(p, keep, f"{d}-SP-opt-{which}")
cen = position_isim(p, keep, p["center"], f"{d}-SP-center-{which}")
main = N[(N.monkey == mk) & (N.date == d)]
main_units = main.unit.to_numpy()
units = np.flatnonzero(keep)
pos_res[(d, which)] = (o, cen)
for rd in "ab":
for i, u in enumerate(units):
mrow = main[main.unit == u]
rows.append({"date": d, "which": which, "rd": rd, "unit": u, "opt": o[rd].intercept.iloc[i],
"center": cen[rd].intercept.iloc[i],
"main_dark": mrow[f"intercept_dark_{rd}"].iloc[0] if len(mrow) else np.nan})
PR = pd.DataFrame(rows)
print(f"position analyses in {time.time() - t0:.0f} s")
for which in ("shape-responsive", "position-responsive"):
sub = PR[(PR.which == which) & (PR.rd == "a")]
print(f"{which}: {sub.unit.size} neurons in {sub.date.nunique()} penetrations (penetrations with 4 or more)")
out = []
for which in ("shape-responsive", "position-responsive"):
for rd in "ab":
sub = PR[(PR.which == which) & (PR.rd == rd)]
for ref in ("center", "main_dark"):
ok = sub.opt.notna() & sub[ref].notna()
r_, p_ = stats.spearmanr(sub.opt[ok], sub[ref][ok])
out.append({"neurons": which, "reliability": rd, "reference": ref, "spearman_r": r_, "p": p_, "n": int(ok.sum()),
"pens": sub[ok].date.nunique()})
R = pd.DataFrame(out)
R["positive_p"] = (R.spearman_r > 0) & (R.p < 1e-4)
R["r_within"] = (R.spearman_r - 0.325).abs() <= 0.0325
print(R.round(4).to_string(index=False))
# all positions as center, for the assumption, under both reliability readings
alt = []
for q in range(5):
vals = {rd: [] for rd in "ab"}
for (mk, d), p in pos.items():
keep = p["keep_shape"]
if keep.sum() < 4:
continue
cen = position_isim(p, keep, q, f"{d}-SP-pos{q}")
o = pos_res[(d, "shape-responsive")][0]
for rd in "ab":
vals[rd].append(pd.DataFrame({"opt": o[rd].intercept.to_numpy(), "cen": cen[rd].intercept.to_numpy()}))
for rd in "ab":
v = pd.concat(vals[rd]).dropna()
rr_ = stats.spearmanr(v.opt, v.cen)
alt.append({"position_as_center": q, "reliability": rd, "spearman_r": rr_[0], "p": rr_[1], "n": len(v),
"positive_p": (rr_[0] > 0) & (rr_[1] < 1e-4), "r_within": abs(rr_[0] - 0.325) <= 0.0325})
print("Variant, each position taken as the center (shape-responsive neurons):")
print(pd.DataFrame(alt).round(5).to_string(index=False))
Position test files: 34 | position with the largest population response: {1: 12, 2: 11, 4: 5, 0: 3, 3: 3}
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
position analyses in 29 s
shape-responsive: 721 neurons in 33 penetrations (penetrations with 4 or more)
position-responsive: 603 neurons in 33 penetrations (penetrations with 4 or more)
neurons reliability reference spearman_r p n pens positive_p r_within
shape-responsive a center 0.4679 0.0 248 22 True False
shape-responsive a main_dark 0.2968 0.0 378 26 True True
shape-responsive b center 0.4465 0.0 623 33 True False
shape-responsive b main_dark 0.3252 0.0 676 33 True True
position-responsive a center 0.4743 0.0 220 20 True False
position-responsive a main_dark 0.2975 0.0 343 23 True True
position-responsive b center 0.4524 0.0 535 32 True False
position-responsive b main_dark 0.3479 0.0 554 32 True True
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
Variant, each position taken as the center (shape-responsive neurons):
position_as_center reliability spearman_r p n positive_p r_within
0 a 0.35883 0.00000 217 True False
0 b 0.37330 0.00000 594 True False
1 a 0.44744 0.00000 222 True False
1 b 0.37193 0.00000 610 True False
2 a 0.56679 0.00000 222 True False
2 b 0.40649 0.00000 593 True False
3 a 0.44920 0.00000 188 True False
3 b 0.32877 0.00000 565 True True
4 a 0.27871 0.00021 172 False False
4 b 0.27436 0.00000 584 True False
Result: reproduced. In 33 M2 penetrations, 721 shape-responsive neurons (723 in the paper) enter the position test. Isimilarity at each neuron's optimal position correlates positively with Isimilarity in the main shape test with dark shapes (reading b), Spearman's r = 0.297 (reliability a) and 0.325 (b), p < 1e-4, within 0.325 +/- 0.0325. This reading does not use the position labels. Against the position test's center (reading a) r is 0.447 to 0.468 with the inferred center, and 0.274 to 0.567 whichever of the five positions is taken as the center under either reliability reading (p < 1e-4 except position 4 under reliability a, p = 2.1e-4); within tolerance only with position 3 under reliability (b). The criterion needs p < 0.0001 under every reading, so the outcome assumes that the center is not position 4. The files do not label the center, and the inferred center is position 4 in 5 of 34 files.
position-examples-invariant¶
In two example penetrations, the pattern of tuning similarity is the same at all five stimulus positions; a small cluster at every position in M2p9 and none at any position in M2p28.
# Figure 11's n (16, 55) is the neuron count of the similarity matrices (questions/001357.yaml, answered).
# The count of each candidate session under every selection of neurons the files allow:
cnt_rows = []
for name, num, exp in (("M2p9", 9, 16), ("M2p28", 28, 55)):
for _, fr in find_pen("M2", num, exp).iterrows():
p = pos.get(("M2", fr.date))
if p is None:
continue
ks, kp = p["keep_shape"], p["keep_pos"]
cnt_rows.append({"name": name, "reading": fr.reading, "date": fr.date, "label": fr.label, "figure_n": exp,
"good": len(ks), "shape_resp": int(ks.sum()), "position_resp": int(kp.sum()),
"both": int((ks & kp).sum()), "either": int((ks | kp).sum())})
CNT = pd.DataFrame(cnt_rows).drop_duplicates(["name", "date"])
for col in ("good", "shape_resp", "position_resp", "both", "either"):
CNT[f"{col}_within_10pct"] = (CNT[col] - CNT.figure_n).abs() <= 0.1 * CNT.figure_n
print("Neuron counts of the candidate sessions against Figure 11's n:")
print(CNT.to_string(index=False))
m2_sp = [(d, int(p["keep_shape"].sum()), int(p["keep_pos"].sum()), len(p["keep_shape"])) for (mk, d), p in pos.items() if mk == "M2"]
for exp in (16, 55):
print(f"M2 position-test sessions with a count within 10% of {exp}:",
{sel: [d for d, *n in m2_sp if abs(n[i] - exp) <= 0.1 * exp] for i, sel in enumerate(("shape_resp", "position_resp", "good"))})
print()
ex_rows = []
for name, num, exp in (("M2p9", 9, 16), ("M2p28", 28, 55)):
f = find_pen("M2", num, exp)
for _, fr in f.iterrows():
key = ("M2", fr.date)
if key not in pos:
print(f"{name} reading {fr.reading}: {fr.date} has no position test")
continue
p = pos[key]
keep = p["keep_shape"]
print(f"{name} reading {fr.reading}: {key} ({fr.label}), shape-responsive {int(keep.sum())}, position-responsive "
f"{int(p['keep_pos'].sum())}; Figure 11 n = {exp}; accepted: {bool(fr.accepted)}")
per = {q: position_isim(p, keep, q, f"{key[1]}-SP-pos{q}") for q in range(5)}
iu = np.triu_indices(keep.sum(), 1)
for rd in "ab":
rel = {q: V.reliable(per[q]["r"], per[q]["lo"], per[q]["hi"], rd)[iu] for q in range(5)}
cor = {}
for q1 in range(5):
for q2 in range(q1 + 1, 5):
both = rel[q1] & rel[q2]
cor[(q1, q2)] = stats.pearsonr(per[q1]["r"][iu][both], per[q2]["r"][iu][both]) if both.sum() > 2 else (np.nan, np.nan)
# reading (a) for each choice of center: all four correlations with it positive, p < 0.05
a_by_center = {c: all((cor[tuple(sorted((c, q)))][0] > 0) and (cor[tuple(sorted((c, q)))][1] < 0.05) for q in range(5) if q != c)
for c in range(5)}
nsig = {q: int(per[q][rd].sig_pos.sum()) for q in range(5)}
print(f" reliability {rd}: pair correlations " + ", ".join(f"{k[0]}-{k[1]} r={v[0]:.2f} p={v[1]:.2g}" for k, v in cor.items()))
print(f" reliability {rd}: (a) holds with center = {a_by_center}; (b) significant positive Isimilarity per position {nsig}, "
f"lines {[int(per[q][rd].has_line.sum()) for q in range(5)]}; reliable pairs {[int(rel[q].sum()) for q in range(5)]} of {len(iu[0])}")
ex_rows.append({"name": name, "reading": fr.reading, "date": fr.date, "accepted": bool(fr.accepted), "rel": rd,
"a_any_center": any(a_by_center.values()), "a_inferred_center": a_by_center[p["center"]],
**{f"a_center_{q}": a_by_center[q] for q in range(5)},
"nsig_min": min(nsig.values()), "nsig_max": max(nsig.values())})
EX = pd.DataFrame(ex_rows)
EX["b_holds"] = np.where(EX.name == "M2p9", EX.nsig_min >= 2, EX.nsig_max <= 1)
print(EX.to_string(index=False))
Neuron counts of the candidate sessions against Figure 11's n:
name reading date label figure_n good shape_resp position_resp both either good_within_10pct shape_resp_within_10pct position_resp_within_10pct both_within_10pct either_within_10pct
M2p9 a 20210421 p12 16 27 16 14 12 18 False True False False False
M2p9 c 20210417 p09 16 20 18 12 12 18 False False False False False
M2p28 a 20210529 p40 55 1 1 0 0 1 False False False False False
M2p28 c 20210512 p28 55 65 55 44 44 55 False True False False True
M2 position-test sessions with a count within 10% of 16: {'shape_resp': ['20210421', '20210423', '20210504', '20210505', '20210506', '20210609', '20210610', '20210619', '20210627'], 'position_resp': ['20210416', '20210418', '20210507', '20210609', '20210610', '20210620'], 'good': ['20210504', '20210506', '20210610', '20210624']}
M2 position-test sessions with a count within 10% of 55: {'shape_resp': ['20210512'], 'position_resp': ['20210513'], 'good': ['20210517', '20210611']}
M2p9 reading a: ('M2', '20210421') (p12), shape-responsive 16, position-responsive 14; Figure 11 n = 16; accepted: True
reliability a: pair correlations 0-1 r=nan p=nan, 0-2 r=nan p=nan, 0-3 r=nan p=nan, 0-4 r=nan p=nan, 1-2 r=nan p=nan, 1-3 r=nan p=nan, 1-4 r=nan p=nan, 2-3 r=nan p=nan, 2-4 r=nan p=nan, 3-4 r=nan p=nan
reliability a: (a) holds with center = {0: False, 1: False, 2: False, 3: False, 4: False}; (b) significant positive Isimilarity per position {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, lines [0, 0, 0, 0, 0]; reliable pairs [0, 1, 1, 0, 0] of 120
reliability b: pair correlations 0-1 r=nan p=nan, 0-2 r=nan p=nan, 0-3 r=nan p=nan, 0-4 r=-0.75 p=0.46, 1-2 r=-0.50 p=0.67, 1-3 r=0.21 p=0.69, 1-4 r=0.21 p=0.51, 2-3 r=0.90 p=0.1, 2-4 r=0.42 p=0.41, 3-4 r=0.64 p=0.048
reliability b: (a) holds with center = {0: False, 1: False, 2: False, 3: False, 4: False}; (b) significant positive Isimilarity per position {0: 2, 1: 1, 2: 0, 3: 3, 4: 3}, lines [4, 10, 4, 8, 11]; reliable pairs [14, 27, 13, 21, 39] of 120
M2p9 reading b: 20210420 has no position test
M2p9 reading c: ('M2', '20210417') (p09), shape-responsive 18, position-responsive 12; Figure 11 n = 16; accepted: False
/tmp/ipykernel_2496/1274240077.py:44: ConstantInputWarning: An input array is constant; the correlation coefficient is not defined. cor[(q1, q2)] = stats.pearsonr(per[q1]["r"][iu][both], per[q2]["r"][iu][both]) if both.sum() > 2 else (np.nan, np.nan)
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
reliability a: pair correlations 0-1 r=0.89 p=1.4e-06, 0-2 r=0.96 p=2.2e-09, 0-3 r=0.74 p=0.0062, 0-4 r=-0.35 p=0.24, 1-2 r=0.80 p=0.00098, 1-3 r=0.98 p=1.4e-09, 1-4 r=0.92 p=1.9e-05, 2-3 r=-0.29 p=0.36, 2-4 r=0.65 p=0.0087, 3-4 r=-0.26 p=0.46
reliability a: (a) holds with center = {0: False, 1: True, 2: False, 3: False, 4: False}; (b) significant positive Isimilarity per position {0: 5, 1: 3, 2: 6, 3: 6, 4: 4}, lines [9, 10, 10, 9, 9]; reliable pairs [28, 35, 31, 24, 24] of 153
reliability b: pair correlations 0-1 r=0.40 p=0.00034, 0-2 r=0.58 p=5.8e-09, 0-3 r=0.72 p=5.5e-14, 0-4 r=0.37 p=0.00066, 1-2 r=0.55 p=6.3e-08, 1-3 r=0.44 p=2e-05, 1-4 r=0.51 p=5.6e-07, 2-3 r=0.74 p=2.6e-15, 2-4 r=0.48 p=7.9e-07, 3-4 r=0.56 p=1.2e-07
reliability b: (a) holds with center = {0: True, 1: True, 2: True, 3: True, 4: True}; (b) significant positive Isimilarity per position {0: 12, 1: 8, 2: 12, 3: 10, 4: 9}, lines [16, 17, 16, 16, 16]; reliable pairs [91, 116, 110, 105, 104] of 153
M2p28 reading a: ('M2', '20210529') (p40), shape-responsive 1, position-responsive 0; Figure 11 n = 55; accepted: False
reliability a: pair correlations 0-1 r=nan p=nan, 0-2 r=nan p=nan, 0-3 r=nan p=nan, 0-4 r=nan p=nan, 1-2 r=nan p=nan, 1-3 r=nan p=nan, 1-4 r=nan p=nan, 2-3 r=nan p=nan, 2-4 r=nan p=nan, 3-4 r=nan p=nan
reliability a: (a) holds with center = {0: False, 1: False, 2: False, 3: False, 4: False}; (b) significant positive Isimilarity per position {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, lines [0, 0, 0, 0, 0]; reliable pairs [0, 0, 0, 0, 0] of 0
reliability b: pair correlations 0-1 r=nan p=nan, 0-2 r=nan p=nan, 0-3 r=nan p=nan, 0-4 r=nan p=nan, 1-2 r=nan p=nan, 1-3 r=nan p=nan, 1-4 r=nan p=nan, 2-3 r=nan p=nan, 2-4 r=nan p=nan, 3-4 r=nan p=nan
reliability b: (a) holds with center = {0: False, 1: False, 2: False, 3: False, 4: False}; (b) significant positive Isimilarity per position {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, lines [0, 0, 0, 0, 0]; reliable pairs [0, 0, 0, 0, 0] of 0
M2p28 reading b: 20210527 has no position test
M2p28 reading c: ('M2', '20210512') (p28), shape-responsive 55, position-responsive 44; Figure 11 n = 55; accepted: True
/home/runner/work/_temp/executed/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1593: RuntimeWarning: All-NaN slice encountered return fnb._ureduce(a,
reliability a: pair correlations 0-1 r=-0.06 p=0.83, 0-2 r=0.41 p=0.19, 0-3 r=0.84 p=0.0024, 0-4 r=-0.35 p=0.36, 1-2 r=1.00 p=0.00074, 1-3 r=0.89 p=0.017, 1-4 r=0.50 p=0.32, 2-3 r=0.68 p=0.022, 2-4 r=1.00 p=0, 3-4 r=0.81 p=0.1
reliability a: (a) holds with center = {0: False, 1: False, 2: False, 3: False, 4: False}; (b) significant positive Isimilarity per position {0: 2, 1: 0, 2: 0, 3: 0, 4: 0}, lines [13, 15, 8, 10, 9]; reliable pairs [60, 59, 28, 37, 23] of 1485
reliability b: pair correlations 0-1 r=0.15 p=0.0007, 0-2 r=0.12 p=0.02, 0-3 r=0.19 p=0.00022, 0-4 r=0.21 p=6.1e-05, 1-2 r=0.08 p=0.085, 1-3 r=0.06 p=0.21, 1-4 r=0.10 p=0.053, 2-3 r=0.14 p=0.014, 2-4 r=0.01 p=0.83, 3-4 r=0.11 p=0.057
reliability b: (a) holds with center = {0: True, 1: False, 2: False, 3: False, 4: False}; (b) significant positive Isimilarity per position {0: 16, 1: 9, 2: 3, 3: 4, 4: 10}, lines [45, 47, 45, 44, 47]; reliable pairs [703, 806, 623, 639, 592] of 1485
name reading date accepted rel a_any_center a_inferred_center a_center_0 a_center_1 a_center_2 a_center_3 a_center_4 nsig_min nsig_max b_holds
M2p9 a 20210421 True a False False False False False False False 0 0 False
M2p9 a 20210421 True b False False False False False False False 0 3 False
M2p9 c 20210417 False a True True False True False False False 3 6 True
M2p9 c 20210417 False b True True True True True True True 8 12 True
M2p28 a 20210529 False a False False False False False False False 0 0 True
M2p28 a 20210529 False b False False False False False False False 0 0 True
M2p28 c 20210512 True a False False False False False False False 0 2 False
M2p28 c 20210512 True b True False True False False False False 3 16 False
Result: not reproduced. A reader confirmed that Figure 11's n (16 for M2p9, 55 for M2p28) is the neuron count of the similarity matrices. The files' p28 has exactly 55 shape-responsive neurons (44 responsive in the position test), which is consistent with matrices of shape-responsive neurons. No count of the files' p09 gives 16: it has 20 good, 18 shape-responsive and 12 position-responsive neurons, so the 10% rule rejects it. Under the rule M2p9 is reading (a), the files' p12 (16 shape-responsive neurons); there the similarity patterns are not shown to agree across positions (reading a fails for every choice of center) and no position has two or more neurons with significant Isimilarity under reliability (a). Under reliability (a) that is not a test: only 0 or 1 of p12's 120 pairs is reliable at each position and no neuron has a line. Under reliability (b), with 13 to 39 reliable pairs, reading (a) fails for every center and positions have 0 to 3 significant neurons. For M2p28 (the files' p28) reading (b) fails: neurons with significant Isimilarity number up to 2 (reliability a) or 3 to 16 (b) per position, against at most 1. Reading (a) fails for p28 under reliability (a) and holds under reliability (b) with position 0 as the center only. With the files' label p09 for M2p9 (18 neurons), reading (b) holds for M2p9 under both reliability readings, and reading (a) holds under reliability (b) for every center and under reliability (a) only with position 1 as the center. So with p09 as M2p9, position 0 as the center and reliability (b), reading (a) holds for both penetrations while reading (b) fails on M2p28, a case the criterion calls blocked; under every other choice both readings fail. The outcome follows the claims file's rule, which takes p12.
Blocked claims¶
- ex-csd-sinks: the dataset holds spike times only; the assets summary lists Units and
ElectrodeGroup, and no file has an LF series (
acquisitionandprocessingare empty). - orientation-sf-isimilarity, apc-peaks-sparse-clustering, apc-example-m2p51: they need the
shape images or their boundary-curvature descriptions (Pasupathy and Connor 2001) and which
stim_IDis which shape. The dataset holds neither (itsstimulus/templatesis empty). The outlines of the 370 shapes of that set are public at a pinned commit (github.com/deanpospisil/v4cnn, commit b0532e9,img_gen/PC3702001ShapeVerts.mat, 401 vertices each), found after the analysis was verified; the files still do not say which 15 of them the shape test used or whichstim_IDeach is, and the analysis with them is left to a new attempt. - gyrus-penetrations-consistent: the 18 gyral penetrations are identified only by grid location and RF azimuth (Figure 8B), and the files give neither (electrode location is only "V4").
- simulation-random-with-domains: a simulation whose peak amplitudes and progression steps are not given, judged by eye; it uses no recorded data.
print("Assets summary variables:", meta["assetsSummary"]["variableMeasured"])
for f_ in ("acquisition", "processing", "templates", "electrode_columns", "electrode_locations"):
print(f_, "across files:", sorted({tuple(s["meta"][f_]) for s in sess}))
Assets summary variables: ['Units', 'ElectrodeGroup']
acquisition across files: [()]
processing across files: [()]
templates across files: [()]
electrode_columns across files: [('group', 'group_name', 'id', 'label', 'location')]
electrode_locations across files: [('V4',)]
Summary¶
| Claim | Outcome |
|---|---|
| methods-sessions-and-neurons | reproduced |
| ex-m2p6-cluster | partially reproduced |
| ex-m2p6-pairs | partially reproduced |
| ex-m2p6-invariance | reproduced |
| ex-csd-sinks | blocked (data missing) |
| ex-m1p12-no-cluster | not reproduced |
| ex-m1p12-strong-responses | reproduced |
| pop-significant-isimilarity | not reproduced |
| pop-intercept-slope-correlation | reproduced |
| pop-dark-bright-consistent | not reproduced |
| pop-contrast-invariance | reproduced |
| pop-sparse-across-penetrations | reproduced |
| pop-asymptote-20-percent | reproduced |
| pop-mean-isimilarity-yield | reproduced |
| pop-recording-density | reproduced |
| pop-within-vs-across-sessions | partially reproduced |
| orientation-sf-isimilarity | blocked (data missing: shape images) |
| orientation-auc-coarse-clusters | not reproduced |
| apc-peaks-sparse-clustering | blocked (data missing: shape descriptions) |
| apc-example-m2p51 | blocked (data missing: shape descriptions) |
| gyrus-penetrations-consistent | blocked (metadata insufficient) |
| texture-sparse-clusters | not reproduced |
| texture-original-reversed-consistent | not reproduced |
| texture-asymptote-20-percent | not reproduced |
| position-optimal-consistent | reproduced |
| position-examples-invariant | not reproduced |
| simulation-random-with-domains | blocked (methods underspecified) |
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. Depth is the best channel's position in 20 um steps,
as the files give it, not the template center of mass. The noise-corrected correlation is written
here from the Methods' description and Pospisil and Bair (2021), for unequal repeats; the paper's
MATLAB code is not public. The bootstrap interval's level (95%) and the reading of "confidence
limit > 0.5" (width or half-width) are not stated, and both readings are run. The bootstrap of the
corrected estimator sits below the point estimate (resampling with replacement inflates the noise
it corrects for); only its width is used. Example penetrations are found by the files' pen_ID
labels, which give the paper's neuron counts for M2p6, M1p12 and M2p28. The label p09 gives 18
shape-responsive neurons against Figure 11's 16 (a reader confirmed that 16 is the matrices' count),
so the claims file's 10% rule takes the files' p12 as M2p9. The paper's counts of neurons without a regression line (2 of 1,850
shape and 48 of 979 texture neurons) favour the half-width reading of the reliability rule (64 and 62
here) over the width reading (140 and 304); the claims file accepts either, and a reader is asked.
Of the 64 shape neurons without a line under the half-width reading, 62 have too few defined
similarities (the corrected variance is not positive), so the remaining gap to the paper's 2 points
to the estimator's handling of weakly tuned neurons, not to the reliability rule.
The similarity takes the noise of two simultaneously recorded neurons as independent; their noise
correlations are small but largest for near pairs (0.072 within 100 um), and subtracting them lowers
the significant-Isimilarity counts by about a third. The aggregate RF center of the position test is
inferred from the population response; the claims that need it are shown under every choice, and
position-optimal-consistent is reproduced only if the center is not position 4.
What was found about the dataset. The files hold the shape, texture and position tests with
spike times of good units only; no LF signal, no stimulus images, no RF-mapping data and no grid
coordinates. The session counts match the Methods, except a 34th position-test file (one unit).
The shape files hold a third luminance level (8 cd/m2, the background luminance) and the texture
files a third version (spectral noise) that the paper does not use; the trial tables of the
position files name their session ...SL; positions are coded 0 to 4 without saying which is the
center, and shapes 0 to 14 without saying which shape each is; texture rotations are not stored.
The clock check (stimulus tuning at the true onsets, none at shifted onsets) holds in 152 of 159
files; it is not established in five M1 texture files, where 0% to 12% of units are tuned, and
in the two single-unit files of 2021-05-29. The units of the five texture files respond to stimulus onset but are not
selective among the textures, which points to stimulus labels that do not match the presentations;
leaving these files out changes no texture outcome. Blank presentations are exactly those with
cond_ID 0, which carry no stimulus.