Henry & Kohn (2022) from CRCNS v4-2: pseudo-populations¶

Paper. Henry CA, Kohn A (2022). Feature representation under crowding in macaque V1 and V4 neuronal populations. Current Biology 32, 5126-5137. doi:10.1016/j.cub.2022.10.049; claims file claims/henry-2022.yaml, written from the version of record.

Dataset. CRCNS v4-2 (doi:10.6080/K0736P4H), streamed from v4-2/live/ in the public S3 bucket crcnsarchive. CRCNS data sets are not versioned and the paper cites only the DOI, so the version is the one published under live/, recorded as unversioned; data.zip has MD5 bdd60f999b997523151b9ae24a42b837 in the data set's checksums.md5, checked below.

Claim Tested here
figs3-pseudo-populations yes

Every other claim is in reproduce_henry_2022.ipynb, with the full data check.

In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
os.environ.setdefault("MKL_NUM_THREADS", "1")
import resource
import time
import warnings

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from scipy import stats

import crowding as cw

warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 160)
pd.set_option("display.max_columns", 30)
T0 = time.time()
print(cw.DATASET)
D = cw.load()
print("MD5 of data.zip as read:", D["md5"], "; checksums.md5 gives", cw.DATA_MD5,
      "; match:", D["md5"] == cw.DATA_MD5)
S, O = D["separation"], D["orientation"]
SP = cw.SPACINGS
SPL = {1.32: "1.3", 1.64: "1.6", 2.04: "2.1", 2.56: "2.6"}
AREAS = ("V1", "V4")


def pops(area, exp=None):
    return [p for p in (exp or S) if p["area"] == area]


def ttest_1s_greater(a, b, equal_var=True):
    return stats.ttest_ind(a, b, equal_var=equal_var, alternative="greater")
CRCNS v4-2 (doi:10.6080/K0736P4H), version unversioned, file live/data.zip
MD5 of data.zip as read: bdd60f999b997523151b9ae24a42b837 ; checksums.md5 gives bdd60f999b997523151b9ae24a42b837 ; match: True

Data check¶

The full check of the data against its description is in reproduce_henry_2022.ipynb; this notebook repeats the counts it uses.

In [2]:
info = pd.DataFrame([dict(area=p["area"], animal=p["animal"], session=p["session"], orange=p["orange"],
                          neurons=p["counts"].shape[0], epochs=p["counts"].shape[1]) for p in S])
print(info.groupby(["area", "animal"]).agg(populations=("session", "size"), neurons=("neurons", "sum"),
                                           epochs=("epochs", "sum")).to_string())
for area in AREAS:
    n_min = {f"{kind} {'' if s is None else s} ori {o}": min(int(cw.stim_mask(p, kind, s, o).sum()) for p in pops(area))
             for kind, s in [("alone", None)] + [("crowd", s) for s in SP] for o in range(4)}
    print(area, "smallest trial count of a stimulus over populations:", min(n_min.values()), "to", max(n_min.values()))
             populations  neurons  epochs
area animal                              
V1   AL               14      264   15975
     CA                8      132    7456
V4   AL               14      288   15975
     CA                8      403    7456
V1 smallest trial count of a stimulus over populations: 19 to 24
V4 smallest trial count of a stimulus over populations: 19 to 24

Recorded populations¶

The decoding and threshold elevation of the recorded populations, as in reproduce_henry_2022.ipynb (main run, same seeds), are recomputed here as the reference for the pseudo-populations. Only the estimate and its bootstrap SEM are needed here, so the permutation test is not run, and only the held-out trial count is used: the two binomial trial counts of the main notebook give the same estimate of k, since the likelihood differs only by a constant factor (they differ only in the bootstrap SEM).

In [3]:
PAIRS = [(0, 1), (1, 2), (2, 3), (0, 2), (1, 3), (0, 3)]
CONDS = [("alone", None)] + [("crowd", s) for s in SP]
MODES = {"main": (10, 10)}


def decode_population(pi, mode):
    p = S[pi]
    outer, inner = MODES[mode]
    rng = np.random.default_rng([7, pi, 0])
    rows = []
    for a, b in PAIRS:
        for kind, s in CONDS:
            X, y = cw.pair_trials(p, kind, s, a, b)
            if mode == "shuffled_all":
                perf = cw.decode(cw.shuffle_within(X, y, rng), y, rng, outer, inner)
            elif mode == "shuffled_train":
                perf = cw.decode_shuffled_train(X, y, rng, outer, inner)
            else:
                perf = cw.decode(X, y, rng, outer, inner)
            rows.append(dict(mode=mode, area=p["area"], animal=p["animal"], session=p["session"], orange=p["orange"],
                             a=a, b=b, sep_deg=6 * (b - a), cond="alone" if s is None else s, perf=perf, n=len(y),
                             n_test=len(y) / outer))
    return rows


t0 = time.time()
DEC = []
for mode in MODES:
    t1 = time.time()
    res = Parallel(n_jobs=4)(delayed(decode_population)(pi, mode) for pi in range(len(S)))
    DEC += [r for rr in res for r in rr]
    print(f"{mode}: {len(S) * len(PAIRS) * len(CONDS)} decoders in {time.time() - t1:.0f} s")
DEC = pd.DataFrame(DEC)
print(f"decoding total {time.time() - t0:.0f} s; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
print(DEC.groupby(["mode", "area", "cond"]).perf.agg(["count", "mean", "min", "max"]).round(3).to_string())


def paired_points(mode, area, s, animal_=None):
    d = DEC[(DEC["mode"] == mode) & (DEC.area == area)]
    if animal_ is not None:
        d = d[d.animal == animal_]
    al = d[d.cond == "alone"].set_index(["session", "orange", "a", "b"])
    cr = d[d.cond == s].set_index(["session", "orange", "a", "b"])
    j = al.add_suffix("_alone").join(cr.add_suffix("_crowd"))
    return j.reset_index()
main: 1320 decoders in 750 s
decoding total 750 s; peak memory 0.28 GB
                 count   mean    min    max
mode area cond                             
main V1   1.32     132  0.576  0.400  0.950
          1.64     132  0.582  0.382  0.945
          2.04     132  0.575  0.370  0.900
          2.56     132  0.576  0.370  0.961
          alone    132  0.584  0.395  0.973
     V4   1.32     132  0.521  0.372  0.748
          1.64     132  0.550  0.343  0.827
          2.04     132  0.553  0.370  0.827
          2.56     132  0.570  0.397  0.820
          alone    132  0.638  0.420  0.962
In [4]:
def elevation(mode, area, s, ntrials, rng, n_boot=1000, n_perm=1000):
    ests, boots, perms, used = [], [], [], []
    for an in ("AL", "CA"):
        j = paired_points(mode, area, s, an)
        n = j.n_test_crowd.values if ntrials == "fold" else j.n_crowd.values
        pa, pc = j.perf_alone.values, j.perf_crowd.values
        ests.append(cw.fit_k(pa, pc, n))
        boots.append(cw.boot_k(pa, pc, n, rng, n_boot) if n_boot else None)
        perms.append(cw.perm_k(pa, pc, n, rng, n_perm) if n_perm else None)
        used.append(f"{int(cw.usable(pa).sum())}/{len(pa)}")
    out = dict(mode=mode, area=area, spacing=SPL[s], ntrials=ntrials, k_AL=ests[0], k_CA=ests[1], k=np.mean(ests),
               points_used=" ".join(used))
    if n_boot:
        out["sem"] = np.std((boots[0] + boots[1]) / 2, ddof=1)
    if n_perm:
        null = (perms[0] + perms[1]) / 2
        out["p_perm"] = (1 + np.sum(null >= out["k"])) / (1 + len(null))
    return out


t0 = time.time()
rng = np.random.default_rng(8)
TE_ROWS = [elevation(mode, area, s, nt, rng, n_perm=0) for mode in ("main",) for nt in ("fold",)
           for area in AREAS for s in SP]
TH = pd.DataFrame(TE_ROWS)
print(f"threshold fits in {time.time() - t0:.0f} s")
print(TH.to_string(float_format=lambda v: f"{v:.4g}"))
threshold fits in 31 s
   mode area spacing ntrials  k_AL  k_CA     k  points_used    sem
0  main   V1     1.3    fold 1.888 1.483 1.685  62/84 34/48 0.3533
1  main   V1     1.6    fold 1.595 1.405   1.5  62/84 34/48 0.1682
2  main   V1     2.1    fold 1.529 1.607 1.568  62/84 34/48 0.1669
3  main   V1     2.6    fold 2.062 1.277 1.669  62/84 34/48 0.3165
4  main   V4     1.3    fold 3.738 10.87 7.302  74/84 42/48  2.495
5  main   V4     1.6    fold 2.176 18.52 10.35  74/84 42/48  2.449
6  main   V4     2.1    fold 2.218 7.234 4.726  74/84 42/48  1.971
7  main   V4     2.6    fold 1.831 3.383 2.607  74/84 42/48 0.2938

figs3-pseudo-populations¶

Pseudo-populations built by combining neurons across sessions give a broader range of decoding performance and similar estimates of threshold elevation.

Per area, neurons pooled over all populations of both animals. For each draw, each population contributes a random subset of its trials of each stimulus, as many as the smallest count of that stimulus over all populations (the same trials for all its neurons, so that within-session correlations stay), and trials are matched by index across populations. Sizes 25, 50, 75 and 100% of the neurons of the area; at each size the neurons are drawn without replacement. Decoders as in main; threshold elevation pooled over sizes and draws, per area and spacing; its SEM from 200 bootstrap samples. Draws: 20 per size, the claims file's standard choice (480 points per area and spacing).

In [5]:
def pseudo_trials(area, rng):
    """Dict (kind, sep, oi) -> neurons x trials array over all neurons of the area."""
    ps = pops(area)
    out = {}
    for kind, s in CONDS:
        for o in range(4):
            n_min = min(int(cw.stim_mask(p, kind, s, o).sum()) for p in ps)
            blocks = []
            for p in ps:
                idx = np.flatnonzero(cw.stim_mask(p, kind, s, o))
                blocks.append(p["counts"][:, rng.choice(idx, n_min, replace=False)])
            out[(kind, s, o)] = np.concatenate(blocks, 0)
    return out


def pseudo_draw(area, frac, draw, outer=10, inner=10):
    rng = np.random.default_rng([11, AREAS.index(area), int(frac * 100), draw])
    tr = pseudo_trials(area, rng)
    n_all = tr[("alone", None, 0)].shape[0]
    cells = np.sort(rng.choice(n_all, int(round(frac * n_all)), replace=False))
    rows = []
    for a, b in PAIRS:
        for kind, s in CONDS:
            Xa, Xb = tr[(kind, s, a)][cells].T, tr[(kind, s, b)][cells].T
            X = np.concatenate([Xa, Xb]).astype(float)
            y = np.r_[np.zeros(len(Xa), int), np.ones(len(Xb), int)]
            perf = cw.decode(X, y, rng, outer, inner)
            rows.append(dict(area=area, frac=frac, draw=draw, a=a, b=b, cond="alone" if s is None else s,
                             perf=perf, n=len(y), n_test=len(y) / outer, n_cells=len(cells)))
    return rows


t0 = time.time()
jobs = [(area, frac, draw) for area in AREAS for frac in (0.25, 0.5, 0.75, 1.0) for draw in range(20)]
PS = pd.DataFrame([r for rr in Parallel(n_jobs=4)(delayed(pseudo_draw)(*j) for j in jobs) for r in rr])
print(f"{len(jobs)} pseudo-population draws, {len(PS)} decoders, in {time.time() - t0:.0f} s; peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
print(PS.groupby(["area", "frac", "cond"]).perf.mean().unstack().round(3).to_string())
160 pseudo-population draws, 4800 decoders, in 2424 s; peak memory 0.30 GB
cond        1.32   1.64   2.04   2.56  alone
area frac                                   
V1   0.25  0.633  0.662  0.662  0.659  0.658
     0.50  0.686  0.710  0.706  0.720  0.733
     0.75  0.704  0.724  0.705  0.769  0.758
     1.00  0.735  0.767  0.749  0.797  0.805
V4   0.25  0.532  0.569  0.597  0.605  0.734
     0.50  0.563  0.603  0.602  0.651  0.773
     0.75  0.558  0.616  0.638  0.684  0.807
     1.00  0.543  0.631  0.650  0.702  0.807
In [6]:
rng = np.random.default_rng(12)
rows = []
for area in AREAS:
    al = PS[(PS.area == area) & (PS.cond == "alone")].set_index(["frac", "draw", "a", "b"])
    rec = DEC[(DEC["mode"] == "main") & (DEC.area == area) & (DEC.cond == "alone")]
    for s in SP:
        cr = PS[(PS.area == area) & (PS.cond == s)].set_index(["frac", "draw", "a", "b"])
        j = al.add_suffix("_alone").join(cr.add_suffix("_crowd"))
        for nt in ("fold",):
            n = j.n_test_crowd.values if nt == "fold" else j.n_crowd.values
            k = cw.fit_k(j.perf_alone.values, j.perf_crowd.values, n)
            kb = cw.boot_k(j.perf_alone.values, j.perf_crowd.values, n, rng, 200)
            o = TH[(TH["mode"] == "main") & (TH.ntrials == nt) & (TH.area == area) & (TH.spacing == SPL[s])].iloc[0]
            rows.append(dict(area=area, spacing=SPL[s], ntrials=nt, k_pseudo=k, sem_pseudo=kb.std(ddof=1), k_recorded=o.k,
                             sem_recorded=o["sem"], within_2sem=abs(k - o.k) <= 2 * o["sem"],
                             points_used=f"{int(cw.usable(j.perf_alone.values).sum())}/{len(j)}"))
    print(f"{area}: target-alone performance, pseudo-populations {PS[(PS.area == area) & (PS.cond == 'alone')].perf.min():.3f} "
          f"to {PS[(PS.area == area) & (PS.cond == 'alone')].perf.max():.3f} (SD {PS[(PS.area == area) & (PS.cond == 'alone')].perf.std():.3f}); "
          f"recorded populations {rec.perf.min():.3f} to {rec.perf.max():.3f} (SD {rec.perf.std():.3f})")
P3 = pd.DataFrame(rows)
print(P3.to_string(float_format=lambda v: f"{v:.3f}"))
for nt, d in P3.groupby("ntrials", sort=False):
    print(f"n = {nt}: pseudo-population estimate within twice the recorded SEM at {int(d.within_2sem.sum())} of 8")
V1: target-alone performance, pseudo-populations 0.343 to 1.000 (SD 0.170); recorded populations 0.395 to 0.973 (SD 0.117)
V4: target-alone performance, pseudo-populations 0.370 to 1.000 (SD 0.173); recorded populations 0.420 to 0.963 (SD 0.123)
  area spacing ntrials  k_pseudo  sem_pseudo  k_recorded  sem_recorded  within_2sem points_used
0   V1     1.3    fold     1.638       0.066       1.685         0.353         True     402/480
1   V1     1.6    fold     1.301       0.034       1.500         0.168         True     402/480
2   V1     2.1    fold     1.454       0.040       1.568         0.167         True     402/480
3   V1     2.6    fold     1.151       0.030       1.669         0.317         True     402/480
4   V4     1.3    fold     7.096       0.634       7.302         2.495         True     413/480
5   V4     1.6    fold     3.502       0.195      10.349         2.449        False     413/480
6   V4     2.1    fold     3.027       0.148       4.726         1.971         True     413/480
7   V4     2.6    fold     2.168       0.074       2.607         0.294         True     413/480
n = fold: pseudo-population estimate within twice the recorded SEM at 7 of 8

Result: reproduced. Pseudo-populations give a broader range of target-alone performance (0.343 to 1.000 in V1 and 0.370 to 1.000 in V4, SD 0.170 and 0.173) than the recorded populations (0.395 to 0.973 and 0.420 to 0.963, SD 0.117 and 0.123), and with 20 draws per size their threshold elevations lie within twice the recorded SEM at 7 of 8 area and spacing pairs (all but V4 at 1.6 degrees, 3.50 against 10.35 +/- 2.45). The closest pass is V1 at 2.6 degrees (1.15 against 1.67 +/- 0.32, a difference of 0.52 against a margin of 0.63). The comparison is with this attempt's recorded estimates, which differ from the paper's (fig2f claims).

Summary¶

Claim Outcome
figs3-pseudo-populations reproduced

The other claims are in reproduce_henry_2022.ipynb. Pseudo-populations use 20 draws per size, the claims file's standard choice.