Reproducing Kim & Shin (2025) on dandiset 000248: the OpenScope Illusion dataΒΆ

Paper: Kim, J. H. & Shin, H. (2025). "Neural variability structure in primary visual cortex is optimal for robust representation of visual similarity", bioRxiv doi:10.1101/2025.06.30.662469 (preprint of July 2025, the text the claims file was written from; the registry lists the later title "Intrinsic geometry of trial-to-trial variability in primary visual cortex is optimal for robust representation of visual similarity").

Dataset: DANDI 000248, "Allen Institute Openscope - Illusion project", version 0.240502.2344, streamed from the archive. The paper cites the dandiset without a version. This is the only published version, so it is pinned. The paper's code read a post-processed copy dated 2024-01-30 ("OpenScopeData_00248_v240130_postprocessed"), before this version was published on 2024-05-02; no other published version exists to compare with.

The paper uses this dandiset only for the Isomap pictures of Figures 1C, 3A, 3E and 3F and for one sentence of the Methods. Its main analyses are on the Allen Visual Coding Neuropixels data, which are tested in the second notebook of this entry (reproduce_kim_2025_allen.ipynb).

Claim Data Tested here
illusion-data-link with_labels yes
illusion-fig1c-isomap-geometry dataset yes
illusion-fig3a-orthogonal-variance-example dataset yes
illusion-geometry-similar-across-datasets dataset yes
all other claims elsewhere (Allen Visual Coding Neuropixels) second notebook

No result here depends on random draws (Isomap uses its dense eigensolver, and the decoding check uses unshuffled folds), so no seed is needed.

InΒ [1]:
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import wilcoxon, spearmanr
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import StratifiedKFold, cross_val_score

import kim2025 as K

T0 = time.time()
pd.set_option("display.width", 200)
NAMES = K.ILLUSION_NAMES
paths = [p for p in K.asset_paths() if p.endswith("_ogen.nwb")]
print(f"dandiset {K.DANDISET_ID} version {K.DANDISET_VERSION}: {len(K.asset_paths())} assets, "
      f"{len(paths)} session files (*_ogen.nwb)")
for p in paths:
    print(" ", p)
dandiset 000248 version 0.240502.2344: 78 assets, 12 session files (*_ogen.nwb)
  sub-619293/sub-619293_ses-1184980079_ogen.nwb
  sub-619296/sub-619296_ses-1187930705_ogen.nwb
  sub-620333/sub-620333_ses-1188137866_ogen.nwb
  sub-620334/sub-620334_ses-1189887297_ogen.nwb
  sub-625545/sub-625545_ses-1182865981_ogen.nwb
  sub-625554/sub-625554_ses-1181330601_ogen.nwb
  sub-625555/sub-625555_ses-1183070926_ogen.nwb
  sub-630506/sub-630506_ses-1192952695_ogen.nwb
  sub-631510/sub-631510_ses-1196157974_ogen.nwb
  sub-631570/sub-631570_ses-1194857009_ogen.nwb
  sub-633229/sub-633229_ses-1199247593_ogen.nwb
  sub-637484/sub-637484_ses-1208667752_ogen.nwb

Data checkΒΆ

Every session file is opened; the V1 units (location containing VISp and not VISpm) are kept, with a flag for the Allen quality criteria, and spikes are counted in the 400 ms from the onset of each trial of the ICwcfg1 block.

InΒ [2]:
sessions = {}
for p in paths:
    subj = p.split("/")[0].replace("sub-", "")
    X, lab, mask, rep = K.illusion_session(p)
    sessions[subj] = dict(X=X, labels=lab, mask=mask, rep=rep, path=p)
rows = []
for subj, s in sessions.items():
    r = s["rep"]
    rows.append(dict(subject=subj, in_code_list=subj in K.CODE_SUBJECTS,
                     presentations=r["presentations"], lead_gray=r["leading_gray"],
                     trail_gray=r["trailing_gray"], trial_slots=r["slots"],
                     nongray_off_slot=r["non_gray_outside_slots"],
                     first_slot=r["first_slot"], blank_trials=r["counts_per_code"].get(0),
                     n_codes_400=len(r["codes_with_400"]), units=r["units_total"],
                     v1_units=r["v1_units"], v1_quality=r["v1_quality"],
                     v1_good_label=r["v1_good_label"], first_onset_s=round(r["first_onset"], 2),
                     total_spikes=r["total_spikes"],
                     dur_min=round(r["duration_range_s"][0], 4), dur_max=round(r["duration_range_s"][1], 4)))
summary = pd.DataFrame(rows).set_index("subject")
print(summary.to_string())
print("\nrepeats per image code (example session):", sessions[K.EXAMPLE_SUBJECT]["rep"]["counts_per_code"])
print("codes with 400 repeats in every session:",
      sorted(set.intersection(*[set(s["rep"]["codes_with_400"]) for s in sessions.values()])))
print("V1 locations, example session:", sessions[K.EXAMPLE_SUBJECT]["rep"]["v1_locations"])
allX = np.concatenate([s["X"].ravel() for s in sessions.values()])
print(f"spike counts per 400 ms trial: min {allX.min():.0f}, max {allX.max():.0f}, mean {allX.mean():.2f}")
print("first V1 unit's spike times sorted, per session:", {k: s["rep"]["first_unit_sorted"] for k, s in sessions.items()})
print("duplicate check: distinct total spike counts", summary.total_spikes.nunique(), "of", len(summary),
      "; distinct first onsets", summary.first_onset_s.nunique())
         in_code_list  presentations  lead_gray  trail_gray  trial_slots  nongray_off_slot  first_slot  blank_trials  n_codes_400  units  v1_units  v1_quality  v1_good_label  first_onset_s  total_spikes  dur_min  dur_max
subject                                                                                                                                                                                                                     
619293          False          10720         60          61         5300                 0          60           400           12   2136       102          23             74         262.24     103597302   0.4000   0.4007
619296           True          10720         60          61         5300                 0          60           400           12   1918       204          89            165          86.31     102057384   0.4001   0.4005
620333           True          10720         60          61         5300                 0          60           400           12   2593       129          61            114          90.29     126846487   0.4001   0.4006
620334           True          10720         62          61         5300                 0          60           400           12   2092        85          30             71          86.52     114809764   0.3999   0.4012
625545           True          10720         62          61         5300                 0          60           400           12   2793       223          78            182          87.07     123324100   0.4000   0.4007
625554           True          10720         60          61         5300                 0          60           400           12   2930       200         101            183         123.26     157987916   0.4001   0.4005
625555           True          10720         62          61         5300                 0          60           400           12   2621       364         143            317          86.76      99099973   0.4002   0.4005
630506           True          10720         60          61         5300                 0          60           400           12   2517        75          22             50          86.97     107649788   0.4000   0.4007
631510           True          10720         60          61         5300                 0          60           400           12   2386       168          46            149         147.06     113678233   0.4000   0.4007
631570           True          10720         60          61         5300                 0          60           400           12   1789       164          75            143          86.91      81507260   0.4001   0.4006
633229           True          10720         60          61         5300                 0          60           400           12   3026       228         124            204          87.84     137061818   0.4000   0.4006
637484           True          10720         60          61         5300                 0          60           400           12   2373       218          90            186         157.17     120502980   0.4000   0.4007

repeats per image code (example session): {0: 400, 1: 400, 2: 400, 3: 400, 4: 400, 5: 400, 6: 400, 7: 400, 8: 50, 9: 50, 10: 400, 11: 400, 12: 400, 13: 400, 14: 50, 15: 50, 16: 50, 17: 50, 18: 50, 19: 50, 20: 50, 21: 50}
codes with 400 repeats in every session: [0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13]
V1 locations, example session: {np.str_('VISp5'): np.int64(32), np.str_('VISp6a'): np.int64(21), np.str_('VISp2/3'): np.int64(13), np.str_('VISp4'): np.int64(7), np.str_('VISp6b'): np.int64(2)}
spike counts per 400 ms trial: min 0, max 117, mean 1.78
first V1 unit's spike times sorted, per session: {'619293': True, '619296': True, '620333': True, '620334': True, '625545': True, '625554': True, '625555': True, '630506': True, '631510': True, '631570': True, '633229': True, '637484': True}
duplicate check: distinct total spike counts 12 of 12 ; distinct first onsets 12

Clock check. The gray inter-trial frame shows the same image as the Blank stimulus (template 0, four disks), so a Blank trial changes nothing on the screen while the other images do. If spikes and the trial table share a clock, the V1 population rate should rise some tens of ms after the onset of image trials and not after Blank trials, and the image identity should be decodable from counts in the 400 ms after onset and not from counts in the 400 ms before it (the previous inter-trial frame).

InΒ [3]:
bins, ps = K.illusion_psth(sessions[K.EXAMPLE_SUBJECT]["path"])
centers = (bins[:-1] + bins[1:]) / 2
base = ps["image"][centers < 0].mean()
print(f"example session, rate (spikes/s/unit) before onset {base:.2f}; peak after image onset "
      f"{ps['image'].max():.2f} at {1000 * centers[ps['image'].argmax()]:.0f} ms; Blank trials peak "
      f"{ps['blank'][(centers > 0) & (centers < 0.2)].max():.2f}")
lat = centers[(centers > 0) & (ps["image"] > base + 0.5 * (ps["image"].max() - base))][0]
print(f"first 10 ms bin above half the peak response: {1000 * lat:.0f} ms after onset")
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(1000 * centers, ps["image"], label="image trials")
ax.plot(1000 * centers, ps["blank"], label="Blank trials")
ax.axvline(0, color="k", lw=0.5); ax.set_xlabel("ms from onset"); ax.set_ylabel("spikes/s per unit"); ax.legend()
print(f"plotted range: image {ps['image'].min():.2f} to {ps['image'].max():.2f}, blank {ps['blank'].min():.2f} to {ps['blank'].max():.2f}")
plt.show()
example session, rate (spikes/s/unit) before onset 5.35; peak after image onset 10.99 at 85 ms; Blank trials peak 4.91
first 10 ms bin above half the peak response: 75 ms after onset
plotted range: image 3.98 to 10.99, blank 4.09 to 6.29
No description has been provided for this image
InΒ [4]:
def decode_shift(path, shift):
    f = K.open_nwb(path)
    units = K.units_table(f)
    rows_ = np.where(K.is_v1(units.location))[0]
    onsets, codes, _ = K.illusion_trials(f)
    keep = np.isin(codes, sessions[K.EXAMPLE_SUBJECT]["rep"]["codes_with_400"])
    C = K.spike_counts(f, rows_, onsets[keep] + shift, K.ILLUSION_WINDOW)
    f.close()
    cv = StratifiedKFold(5, shuffle=False)
    return cross_val_score(LinearDiscriminantAnalysis(), C, codes[keep], cv=cv).mean()

for shift in (0.0, -0.4):
    print(f"window shifted by {shift:+.1f} s: 12-way LDA accuracy {decode_shift(sessions[K.EXAMPLE_SUBJECT]['path'], shift):.3f} (chance {1/12:.3f})")
window shifted by +0.0 s: 12-way LDA accuracy 0.576 (chance 0.083)
window shifted by -0.4 s: 12-way LDA accuracy 0.089 (chance 0.083)

illusion-data-linkΒΆ

Dandiset 000248 holds the OpenScope Illusion recordings the paper used for its Isomap pictures, an ICwcfg1 block in which stimuli are repeated 400 times, with V1 units, in the example session the paper's code uses.

The dandiset gives the image codes 0 to 21 and an image template for each, but no names. The names come from the code's map (claims file header). The templates are drawn below so that the map can be checked against what each image shows.

InΒ [5]:
f = K.open_nwb(sessions[K.EXAMPLE_SUBJECT]["path"])
g = f["stimulus/templates/ICwcfg1_presentations"]
tab = f["intervals/ICwcfg1_presentations"]
print("ICwcfg1 table description:", tab.attrs.get("description"))
print("stimulus_name values:", sorted(set(K._str(tab["stimulus_name"][:]))))
print("columns:", list(tab.keys()))
fig, axes = plt.subplots(4, 6, figsize=(15, 6))
for k in range(22):
    im = g[f"ICwcfg1_presentations{k}"][::8, ::8]
    axes.flat[k].imshow(im, cmap="gray", vmin=0, vmax=255)
    axes.flat[k].set_title(f"{k}: {NAMES[k]}", fontsize=9)
for a in axes.flat:
    a.axis("off")
plt.tight_layout(); plt.show()
f.close()
ex = sessions[K.EXAMPLE_SUBJECT]
print("(i) sub-630506 present:", K.EXAMPLE_SUBJECT in sessions,
      "| ICwcfg1 block present | stimuli with 400 repeats:", len(ex["rep"]["codes_with_400"]),
      [NAMES[c] for c in ex["rep"]["codes_with_400"]])
print("(ii) Ic1, Lc1, Tre1, Tre2 among them:",
      all(c in ex["rep"]["codes_with_400"] for c in (3, 4, 10, 11)), "(codes 3, 4, 10, 11 by the code's map)")
print("(iii) V1 units in sub-630506:", ex["rep"]["v1_units"], "; passing the Allen quality criteria:", ex["rep"]["v1_quality"])
print("code's 11 subjects present:", [s for s in K.CODE_SUBJECTS if s in sessions], "missing:", [s for s in K.CODE_SUBJECTS if s not in sessions])
print("sessions in the dandiset but not in the code's list:", [s for s in sessions if s not in K.CODE_SUBJECTS])
print("400-repeat stimuli per session:", {k: len(s["rep"]["codes_with_400"]) for k, s in sessions.items()})
ICwcfg1 table description: Presentation times and stimuli details for 'ICwcfg1' stimuli. 
Note: image_name references control_description in stimulus/templates
stimulus_name values: [np.str_('ICwcfg1')]
columns: ['frame', 'id', 'start_time', 'stimulus_block', 'stimulus_index', 'stimulus_name', 'stop_time', 'tags', 'tags_index', 'timeseries', 'timeseries_index']
No description has been provided for this image
(i) sub-630506 present: True | ICwcfg1 block present | stimuli with 400 repeats: 12 ['Blank', 'X', 'Tc1', 'Ic1', 'Lc1', 'Tc2', 'Lc2', 'Ic2', 'Tre1', 'Tre2', 'Xre1', 'Xre2']
(ii) Ic1, Lc1, Tre1, Tre2 among them: True (codes 3, 4, 10, 11 by the code's map)
(iii) V1 units in sub-630506: 75 ; passing the Allen quality criteria: 22
code's 11 subjects present: ['619296', '620333', '620334', '625545', '625554', '625555', '630506', '631510', '631570', '633229', '637484'] missing: []
sessions in the dandiset but not in the code's list: ['619293']
400-repeat stimuli per session: {'619293': 12, '619296': 12, '620333': 12, '620334': 12, '625545': 12, '625554': 12, '625555': 12, '630506': 12, '631510': 12, '631570': 12, '633229': 12, '637484': 12}

Result: reproduced. Session sub-630506 is in the dandiset with an ICwcfg1 block whose 12 stimuli with 400 repeats are the 11 image codes 1 to 7 and 10 to 13 and the Blank trials (code 0 in a trial slot), as the code expects; Ic1, Lc1, Tre1 and Tre2 (codes 3, 4, 10, 11) are among them; and it has 75 V1 units (22 by the Allen quality criteria). The dandiset names no code: the names come from the code's map, and the templates drawn above agree with it in kind (codes 8 to 13 carry a real bar, 14 to 21 a single inducer at the named corner, pointing in or out). All 11 subjects of the code are present, and a twelfth session (sub-619293) is in the dandiset but not in the code's list. Every session has 400 Blank trials and 12 stimuli with 400 repeats.

illusion-fig1c-isomap-geometryΒΆ

In an example session of the Illusion data, three stimulus manifolds of V1 activity appear continuous with little overlap in the as-is data, discontinuous at slope 0 and heavily overlapping at slope 2.

Session sub-630506, the 12 stimuli with 400 repeats, slopes changed by residual rescaling (M2) after an M1 fit on these stimuli. Among Ic1, Lc1 and Tre1: (i) at slope 0 not one strongly connected component, (ii) as-is one, (iii) mean of the six directed overlaps larger at slope 2 than as-is, and as-is than at slope 0. Readings: the full N-neuron space and the 2D Isomap coordinates (claims file); the overlap threshold over distinct pairs (Methods, main) and over the full self-distance matrix with <= (code, variant); units all VISp (O3 a, main) and with the Allen quality criteria (O3 b). Test (i) is computed on the graph among the three stimuli, as "among" in the criterion reads; trio_one_scc_via_12 also shows whether the three lie in one strongly connected component of the graph over all 12 stimuli, where a path may pass through the others.

InΒ [6]:
TRIO = (3, 4, 10)  # Ic1, Lc1, Tre1

def conditions(X, lab, slopes=(0, 1, 2)):
    fits = K.fit_slopes(X, lab)
    out = {"as-is": X}
    for s in slopes:
        out[f"slope {s}"] = K.manipulate(X, lab, s, fits)
    return out, fits

def trio_tests(conds, lab, space, variant):
    res = {}
    embeds = {}
    for name, Y in conds.items():
        if space == "isomap2d":
            E = K.isomap_embed(Y, 2)
            embeds[name] = E
            Y = E
        O, stims = K.overlap_matrix(Y, lab, variant)
        nodes = [list(stims).index(c) for c in TRIO]
        res[name] = dict(scc_trio=K.largest_scc(O, nodes), trio_one_scc_via_12=K.in_one_scc(O, nodes),
                         mean_overlap_trio=K.mean_offdiag(O, nodes),
                         scc_all12=K.largest_scc(O), mean_overlap_all12=K.mean_offdiag(O))
    r = pd.DataFrame(res).T
    i_ = r.loc["slope 0", "scc_trio"] < 3
    ii = r.loc["as-is", "scc_trio"] == 3
    iii = r.loc["slope 2", "mean_overlap_trio"] > r.loc["as-is", "mean_overlap_trio"] > r.loc["slope 0", "mean_overlap_trio"]
    return r, (bool(i_), bool(ii), bool(iii)), embeds

fig1c = {}
for units in ("all VISp", "quality"):
    X = ex["X"] if units == "all VISp" else ex["X"][:, ex["mask"]]
    conds, fits = conditions(X, ex["labels"])
    print(f"--- units: {units} ({X.shape[1]}); M1 slopes of the 12 stimuli {fits.slope.min():.3f} to {fits.slope.max():.3f}")
    for space in ("N-space", "isomap2d"):
        for variant in ("methods", "code"):
            r, tests, emb = trio_tests(conds, ex["labels"], space, variant)
            fig1c[(units, space, variant)] = (r, tests, emb)
            print(f"[{space}, threshold {variant}] tests (i, ii, iii) = {tests}, {sum(tests)} of 3")
            print(r.round(4).to_string())
--- units: all VISp (75); M1 slopes of the 12 stimuli 1.079 to 1.124
[N-space, threshold methods] tests (i, ii, iii) = (True, True, True), 3 of 3
        scc_trio trio_one_scc_via_12 mean_overlap_trio scc_all12 mean_overlap_all12
as-is          3                True           0.22125        12           0.358428
slope 0        1               False               0.0         7           0.083655
slope 1        3                True          0.184167        12           0.323845
slope 2        3                True            0.3175        12           0.467443
[N-space, threshold code] tests (i, ii, iii) = (True, True, True), 3 of 3
        scc_trio trio_one_scc_via_12 mean_overlap_trio scc_all12 mean_overlap_all12
as-is          3                True           0.21875        12           0.353087
slope 0        1               False               0.0         7           0.081326
slope 1        3                True          0.180833        12           0.316989
slope 2        3                True          0.304583        12           0.457746
[isomap2d, threshold methods] tests (i, ii, iii) = (True, True, True), 3 of 3
        scc_trio trio_one_scc_via_12 mean_overlap_trio scc_all12 mean_overlap_all12
as-is          3                True          0.177083        12           0.426174
slope 0        1               False               0.0         7           0.183845
slope 1        3                True               0.1        12           0.364034
slope 2        3                True          0.669167        12           0.752992
[isomap2d, threshold code] tests (i, ii, iii) = (True, True, True), 3 of 3
        scc_trio trio_one_scc_via_12 mean_overlap_trio scc_all12 mean_overlap_all12
as-is          3                True          0.173333        12           0.422708
slope 0        1               False               0.0         7           0.182708
slope 1        3                True          0.099167        12           0.360246
slope 2        3                True          0.665833        12           0.749337
--- units: quality (22); M1 slopes of the 12 stimuli 1.071 to 1.181
[N-space, threshold methods] tests (i, ii, iii) = (True, True, True), 3 of 3
        scc_trio trio_one_scc_via_12 mean_overlap_trio scc_all12 mean_overlap_all12
as-is          3                True          0.329167        12           0.439527
slope 0        1               False          0.005833         9           0.163087
slope 1        3                True              0.28        12           0.405758
slope 2        3                True          0.412917        12           0.534489
[N-space, threshold code] tests (i, ii, iii) = (True, True, True), 3 of 3
        scc_trio trio_one_scc_via_12 mean_overlap_trio scc_all12 mean_overlap_all12
as-is          3                True             0.325        12           0.435739
slope 0        1               False          0.005417         9           0.159716
slope 1        3                True          0.272083        12           0.400019
slope 2        3                True          0.403333        12           0.526364
/home/runner/work/encore/encore/executed/kim-2025/.venv/lib/python3.13/site-packages/sklearn/manifold/_isomap.py:386: UserWarning: The number of connected components of the neighbors graph is 2 > 1. Completing the graph to fit Isomap might be slow. Increase the number of neighbors to avoid this issue.
  self._fit_transform(X)
/home/runner/work/encore/encore/executed/kim-2025/.venv/lib/python3.13/site-packages/scipy/sparse/_index.py:174: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil and dok are more efficient.
  self._set_intXint(row, col, x.flat[0])
[isomap2d, threshold methods] tests (i, ii, iii) = (True, True, True), 3 of 3
        scc_trio trio_one_scc_via_12 mean_overlap_trio scc_all12 mean_overlap_all12
as-is          3                True              0.38        12           0.545455
slope 0        2               False            0.0025         9           0.237992
slope 1        3                True          0.264583        12           0.471742
slope 2        3                True          0.609167        12           0.697008
/home/runner/work/encore/encore/executed/kim-2025/.venv/lib/python3.13/site-packages/sklearn/manifold/_isomap.py:386: UserWarning: The number of connected components of the neighbors graph is 2 > 1. Completing the graph to fit Isomap might be slow. Increase the number of neighbors to avoid this issue.
  self._fit_transform(X)
/home/runner/work/encore/encore/executed/kim-2025/.venv/lib/python3.13/site-packages/scipy/sparse/_index.py:174: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil and dok are more efficient.
  self._set_intXint(row, col, x.flat[0])
[isomap2d, threshold code] tests (i, ii, iii) = (True, True, True), 3 of 3
        scc_trio trio_one_scc_via_12 mean_overlap_trio scc_all12 mean_overlap_all12
as-is          3                True             0.375        12           0.540871
slope 0        2               False            0.0025         9           0.236269
slope 1        3                True              0.26        12           0.467292
slope 2        3                True          0.602917        12           0.692803
InΒ [7]:
r, tests, emb = fig1c[("all VISp", "isomap2d", "methods")]
cols = {3: "tab:green", 4: "tab:orange", 10: "tab:blue"}
fig, axes = plt.subplots(1, 4, figsize=(16, 4))
lab = ex["labels"]
for a, (name, E) in zip(axes, emb.items()):
    for c in TRIO:
        a.scatter(E[lab == c, 0], E[lab == c, 1], s=3, c=cols[c], label=NAMES[c])
    a.set_title(name); a.set_aspect("equal")
    print(f"{name}: Isomap ranges x {E[:, 0].min():.1f} to {E[:, 0].max():.1f}, y {E[:, 1].min():.1f} to {E[:, 1].max():.1f}")
axes[0].legend(markerscale=4)
plt.tight_layout(); plt.show()
as-is: Isomap ranges x -100.8 to 133.1, y -64.1 to 142.1
slope 0: Isomap ranges x -126.9 to 188.5, y -71.6 to 115.6
slope 1: Isomap ranges x -94.4 to 118.6, y -68.6 to 148.6
slope 2: Isomap ranges x -241.3 to 270.0, y -231.9 to 288.2
No description has been provided for this image

Other sessions (variant): the same three tests in the N-neuron space, Methods threshold, all VISp units.

InΒ [8]:
rows = []
for subj, s in sessions.items():
    conds, _ = conditions(s["X"], s["labels"])
    r, tests, _ = trio_tests(conds, s["labels"], "N-space", "methods")
    rows.append(dict(subject=subj, units=s["X"].shape[1], i=tests[0], ii=tests[1], iii=tests[2],
                     slope0_trio_one_scc_via_12=bool(r.loc["slope 0", "trio_one_scc_via_12"]),
                     **{f"ov_{k}": round(v, 3) for k, v in r.mean_overlap_trio.items()},
                     **{f"scc12_{k}": v for k, v in r.scc_all12.items()}))
other = pd.DataFrame(rows).set_index("subject")
print(other.to_string())
print("sessions with all three tests holding:", int((other.i & other.ii & other.iii).sum()), "of", len(other))
         units      i    ii   iii  slope0_trio_one_scc_via_12  ov_as-is  ov_slope 0  ov_slope 1  ov_slope 2  scc12_as-is  scc12_slope 0  scc12_slope 1  scc12_slope 2
subject                                                                                                                                                              
619293     102  False  True  True                        True     0.797       0.595       0.781       0.840           12             12             12             12
619296     204   True  True  True                       False     0.268       0.000       0.238       0.580           12              4             12             12
620333     129  False  True  True                        True     0.459       0.131       0.421       0.672           12             12             12             12
620334      85   True  True  True                       False     0.207       0.000       0.170       0.320           12              5             12             12
625545     223   True  True  True                       False     0.464       0.115       0.435       0.643           12             10             12             12
625554     200   True  True  True                        True     0.537       0.130       0.489       0.777           12              6             12             12
625555     364   True  True  True                        True     0.478       0.117       0.435       0.728           12             12             12             12
630506      75   True  True  True                       False     0.221       0.000       0.184       0.317           12              7             12             12
631510     168   True  True  True                       False     0.303       0.000       0.276       0.494           12              7             12             12
631570     164  False  True  True                        True     0.538       0.137       0.504       0.740           12             12             12             12
633229     228   True  True  True                       False     0.302       0.000       0.263       0.463           12              9             12             12
637484     218   True  True  True                       False     0.336       0.092       0.280       0.512           12              9             12             12
sessions with all three tests holding: 9 of 12

Result: reproduced. Among Ic1, Lc1 and Tre1 in sub-630506, at slope 0 the largest strongly connected component has 1 member (no overlap between the three), as-is it has all 3, and the mean directed overlap is 0.000 at slope 0, 0.221 as-is and 0.318 at slope 2. All three tests hold in every reading: the N-neuron space and the 2D Isomap coordinates, the Methods and the code thresholds, all VISp units and the units passing the quality criteria (in the 2D Isomap of the quality units the slope-0 component has 2 members, still fewer than 3). Read on the graph over all 12 stimuli, where a path may pass through the others, the three also do not lie in one strongly connected component at slope 0 in this session, under every reading (trio_one_scc_via_12 False). Over the other sessions (variant), all three tests hold in 9 of 12; in the other 3 the three stimuli still overlap at slope 0, while the overlap rises with slope in all 12.

illusion-fig3a-orthogonal-variance-exampleΒΆ

In the example session of the Illusion data, the Lc1 manifold has larger orthogonal variance toward the faraway Ic1 manifold than toward the nearby Tre2 manifold.

As-is data of sub-630506, the 12 stimuli. Geodesic distance between centroids by M5; orthogonal variance as the Methods define it.

InΒ [9]:
LC1, IC1, TRE2 = 4, 3, 11
for units in ("all VISp", "quality"):
    X = ex["X"] if units == "all VISp" else ex["X"][:, ex["mask"]]
    D, stims = K.centroid_geodesics(X, ex["labels"])
    st = list(stims)
    g_ic, g_tre = D[st.index(LC1), st.index(IC1)], D[st.index(LC1), st.index(TRE2)]
    ov_ic = K.orthogonal_variance(X, ex["labels"], LC1, IC1)
    ov_tre = K.orthogonal_variance(X, ex["labels"], LC1, TRE2)
    geo, ov = [], []
    for a in stims:
        for b in stims:
            if a != b:
                geo.append(D[st.index(a), st.index(b)]); ov.append(K.orthogonal_variance(X, ex["labels"], a, b))
    rho, p = spearmanr(geo, ov)
    print(f"units {units} ({X.shape[1]}): geodesic Lc1-Ic1 {g_ic:.2f}, Lc1-Tre2 {g_tre:.2f}; "
          f"orthogonal variance of Lc1 toward Ic1 {ov_ic:.4f}, toward Tre2 {ov_tre:.4f} (ratio {ov_ic / ov_tre:.2f})")
    print(f"   Ic1 farther: {g_ic > g_tre}; variance larger toward Ic1: {ov_ic > ov_tre}; "
          f"variant, Spearman over {len(geo)} ordered pairs rho = {rho:.3f}, p = {p:.2g}; finite geodesics {np.isfinite(D).all()}")
units all VISp (75): geodesic Lc1-Ic1 60.02, Lc1-Tre2 17.63; orthogonal variance of Lc1 toward Ic1 0.0270, toward Tre2 0.0161 (ratio 1.67)
   Ic1 farther: True; variance larger toward Ic1: True; variant, Spearman over 132 ordered pairs rho = 0.151, p = 0.084; finite geodesics True
units quality (22): geodesic Lc1-Ic1 40.08, Lc1-Tre2 25.83; orthogonal variance of Lc1 toward Ic1 0.0436, toward Tre2 0.0295 (ratio 1.48)
   Ic1 farther: True; variance larger toward Ic1: True; variant, Spearman over 132 ordered pairs rho = 0.162, p = 0.063; finite geodesics True

Result: reproduced. In sub-630506 the geodesic distance from Lc1 to Ic1 (60.0) is larger than to Tre2 (17.6), and the orthogonal variance of Lc1 toward Ic1 (0.0270) is larger than toward Tre2 (0.0161). The same holds with the quality units (40.1 against 25.8; 0.0436 against 0.0295). Over all 132 ordered pairs of the 12 stimuli the Spearman correlation between geodesic distance and orthogonal variance is weakly positive and not significant (0.150, p = 0.086; 0.163, p = 0.061 with the quality units).

illusion-geometry-similar-across-datasetsΒΆ

The changes in manifold geometry that come with changing the slope are qualitatively the same in the Illusion data as in the natural scenes data.

Every session with an ICwcfg1 block (12), V1 units, the 12 stimuli with 400 repeats, M2 at slopes 0 to 2. Per session, effective dimensionality averaged over stimuli and overlap (M3, Methods threshold) averaged over the 132 ordered pairs. Reproduced when the across-session mean dimensionality decreases and the mean overlap increases by the O2 reading, with the Wilcoxon signed-rank test (slopes 0 and 2 against as-is, across sessions, p < 0.05).

InΒ [10]:
t = time.time()
geom = {}
for units in ("all VISp", "quality"):
    dims, ovs = {}, {}
    for subj, s in sessions.items():
        X = s["X"] if units == "all VISp" else s["X"][:, s["mask"]]
        fits = K.fit_slopes(X, s["labels"])
        d, o = {"as-is": K.effective_dimensionality(X, s["labels"]).mean()}, {"as-is": K.mean_offdiag(K.overlap_matrix(X, s["labels"])[0])}
        for sl in K.TARGET_SLOPES:
            Y = K.manipulate(X, s["labels"], sl, fits)
            d[sl] = K.effective_dimensionality(Y, s["labels"]).mean()
            o[sl] = K.mean_offdiag(K.overlap_matrix(Y, s["labels"])[0])
        dims[subj], ovs[subj] = d, o
    geom[units] = (pd.DataFrame(dims).T, pd.DataFrame(ovs).T)
print(f"computed in {time.time() - t:.0f} s")

def o2(df, direction):
    m = df.mean()
    a0, a1, a2 = m[0.0], m[1.0], m[2.0]
    order = (a2 < a1 < a0) if direction == "decrease" else (a2 > a1 > a0)
    p0 = wilcoxon(df[0.0], df["as-is"]).pvalue
    p2 = wilcoxon(df[2.0], df["as-is"]).pvalue
    side0 = (m[0.0] > m["as-is"]) if direction == "decrease" else (m[0.0] < m["as-is"])
    side2 = (m[2.0] < m["as-is"]) if direction == "decrease" else (m[2.0] > m["as-is"])
    steps = np.diff(m[list(K.TARGET_SLOPES)].to_numpy())
    strict = bool(np.all(steps < 0)) if direction == "decrease" else bool(np.all(steps > 0))
    return dict(mean_slope0=a0, mean_slope1=a1, mean_slope2=a2, mean_asis=m["as-is"], order=order,
                p_slope0=p0, p_slope2=p2, direction_0_2_vs_asis=bool(side0 and side2), strict_every_step=strict,
                holds=bool(order and p0 < 0.05 and p2 < 0.05 and side0 and side2))

for units, (dim, ov) in geom.items():
    print(f"--- units {units}, n = {len(dim)} sessions")
    print("dimensionality (decrease):", {k: (round(v, 4) if isinstance(v, float) else v) for k, v in o2(dim, "decrease").items()})
    print("overlap (increase):", {k: (round(v, 4) if isinstance(v, float) else v) for k, v in o2(ov, "increase").items()})
    print("sessions where dimensionality at slope 2 < slope 0:", int((dim[2.0] < dim[0.0]).sum()),
          "; overlap at slope 2 > slope 0:", int((ov[2.0] > ov[0.0]).sum()))

dim, ov = geom["all VISp"]
print("\nper-session values, all VISp units (as-is, slopes 0, 1, 2):")
print(pd.concat({"dim": dim[["as-is", 0.0, 1.0, 2.0]], "overlap": ov[["as-is", 0.0, 1.0, 2.0]]}, axis=1).round(3).to_string())
print("\nexample session alone (variant):", dict(dim=dim.loc[K.EXAMPLE_SUBJECT, ["as-is", 0.0, 1.0, 2.0]].round(3).to_dict(),
                                           overlap=ov.loc[K.EXAMPLE_SUBJECT, ["as-is", 0.0, 1.0, 2.0]].round(3).to_dict()))
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))
for a, df, name in ((axes[0], dim, "effective dimensionality"), (axes[1], ov, "mean overlap")):
    m = df[list(K.TARGET_SLOPES)]
    a.errorbar(K.TARGET_SLOPES, m.mean(), m.sem(), marker="o"); a.axhline(df["as-is"].mean(), color="k", ls="--", label="as-is")
    a.set_xlabel("slope"); a.set_title(name); a.legend()
    print(f"{name}: plotted means {m.mean().min():.3f} to {m.mean().max():.3f}")
plt.tight_layout(); plt.show()
print(f"notebook time so far {(time.time() - T0) / 60:.1f} min")
computed in 542 s
--- units all VISp, n = 12 sessions
dimensionality (decrease): {'mean_slope0': np.float64(0.2425), 'mean_slope1': np.float64(0.0812), 'mean_slope2': np.float64(0.0333), 'mean_asis': np.float64(0.0728), 'order': np.True_, 'p_slope0': np.float64(0.0005), 'p_slope2': np.float64(0.0005), 'direction_0_2_vs_asis': True, 'strict_every_step': True, 'holds': True}
overlap (increase): {'mean_slope0': np.float64(0.142), 'mean_slope1': np.float64(0.3981), 'mean_slope2': np.float64(0.603), 'mean_asis': np.float64(0.4293), 'order': np.True_, 'p_slope0': np.float64(0.0005), 'p_slope2': np.float64(0.0005), 'direction_0_2_vs_asis': True, 'strict_every_step': True, 'holds': True}
sessions where dimensionality at slope 2 < slope 0: 12 ; overlap at slope 2 > slope 0: 12
--- units quality, n = 12 sessions
dimensionality (decrease): {'mean_slope0': np.float64(0.3842), 'mean_slope1': np.float64(0.1482), 'mean_slope2': np.float64(0.076), 'mean_asis': np.float64(0.1372), 'order': np.True_, 'p_slope0': np.float64(0.0005), 'p_slope2': np.float64(0.0005), 'direction_0_2_vs_asis': True, 'strict_every_step': True, 'holds': True}
overlap (increase): {'mean_slope0': np.float64(0.191), 'mean_slope1': np.float64(0.4554), 'mean_slope2': np.float64(0.6533), 'mean_asis': np.float64(0.4837), 'order': np.True_, 'p_slope0': np.float64(0.0005), 'p_slope2': np.float64(0.0005), 'direction_0_2_vs_asis': True, 'strict_every_step': True, 'holds': True}
sessions where dimensionality at slope 2 < slope 0: 12 ; overlap at slope 2 > slope 0: 12

per-session values, all VISp units (as-is, slopes 0, 1, 2):
          dim                      overlap                     
        as-is    0.0    1.0    2.0   as-is    0.0    1.0    2.0
619293  0.141  0.302  0.154  0.081   0.781  0.604  0.768  0.828
619296  0.067  0.247  0.072  0.035   0.286  0.022  0.252  0.554
620333  0.050  0.261  0.064  0.018   0.483  0.171  0.442  0.696
620334  0.111  0.367  0.126  0.042   0.353  0.099  0.321  0.466
625545  0.043  0.192  0.049  0.021   0.381  0.072  0.353  0.523
625554  0.079  0.232  0.084  0.032   0.285  0.061  0.264  0.607
625555  0.042  0.166  0.048  0.018   0.541  0.199  0.505  0.732
630506  0.116  0.311  0.129  0.048   0.358  0.084  0.324  0.467
631510  0.060  0.191  0.064  0.029   0.365  0.041  0.337  0.545
631570  0.067  0.277  0.076  0.024   0.519  0.129  0.487  0.736
633229  0.052  0.184  0.057  0.029   0.383  0.047  0.349  0.526
637484  0.048  0.181  0.054  0.023   0.415  0.175  0.376  0.555

example session alone (variant): {'dim': {'as-is': 0.116, np.float64(0.0): 0.311, np.float64(1.0): 0.129, np.float64(2.0): 0.048}, 'overlap': {'as-is': 0.358, np.float64(0.0): 0.084, np.float64(1.0): 0.324, np.float64(2.0): 0.467}}
effective dimensionality: plotted means 0.033 to 0.243
mean overlap: plotted means 0.142 to 0.603
No description has been provided for this image
notebook time so far 13.9 min

Result: reproduced. Across the 12 sessions, the mean effective dimensionality falls from 0.243 at slope 0 to 0.081 at slope 1 and 0.033 at slope 2 (as-is 0.073), and the mean overlap rises from 0.142 to 0.398 and 0.603 (as-is 0.429), in every 0.1 step; slopes 0 and 2 differ from as-is by the Wilcoxon signed-rank test (p = 0.0005 each). The directions at slopes 0, 1 and 2 against as-is hold in each of the 12 sessions (table above) and with the quality units; the step-by-step change is shown for the across-session mean only. These are the directions the paper reports for Figures 1D and 2A of the natural scenes data.

SummaryΒΆ

Claim Outcome Rests on
illusion-data-link reproduced the code's names for the image codes (the dandiset has none); Blank trials recovered from the trial sequence
illusion-fig1c-isomap-geometry reproduced every reading
illusion-fig3a-orthogonal-variance-example reproduced every reading
illusion-geometry-similar-across-datasets reproduced every reading

How the analysis differs from the paper's: the paper's code read a post-processed MATLAB copy of the dandiset ("v240130") that is not public. Here the counts are made from the NWB spike times, and the Blank trials are recovered from the alternation of trials and gray inter-trial frames. The code applies no unit filter, and the quality-filtered units are run as a second reading. The claims on the 2D Isomap picture are judged with the paper's overlap and connectivity measures, as the claims file sets out.

What was found about the dataset: the ICwcfg1 table lists every 400 ms frame, including the inter-trial gray frames, which show the same image as the Blank stimulus (template 0), under one column frame. Nothing marks which gray frames are Blank trials, and the image codes have no names. The trial structure can be recovered: 60 leading gray frames, then trials and gray frames alternating, with 400 Blank trials in every session. The spikes share the clock of the table: the V1 response rises 75 ms after image onsets and not after Blank onsets, and the image identity is decodable from the 400 ms after onset (0.576, chance 0.083) and not from the 400 ms before (0.089). The units table describes none of its columns ("no description"). No session is deposited twice. Twelve sessions hold the block; the paper's code lists 11 and leaves out sub-619293.