Reproducing Henry & Kohn (2022) from CRCNS v4-2¶

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. The claims file claims/henry-2022.yaml was written from the version of record (main text, STAR Methods and Supplemental Information, as extracted from the PDF).

Dataset. CRCNS v4-2, "Simultaneous extracellular recordings from visual areas V1 and V4 from macaque monkeys viewing crowded displays" (doi:10.6080/K0736P4H), the paper's deposit. Files are streamed from the public S3 bucket crcnsarchive under v4-2/live/; the zip is opened in place and nothing is written to disk.

Version. CRCNS data sets are not versioned (docs/archives.md), and the paper cites the data set by its DOI only, so the version pinned is the one published under v4-2/live/ (the bucket holds no other), recorded as unversioned. Its data description is version 0.7 (9 Nov 2022). The MD5 sums from the data set's checksums.md5 for the files read are: data.zip bdd60f999b997523151b9ae24a42b837 (checked against the bytes read, below) and docs/crcns_v4-2_data_description.pdf 40f2f30456a87ad3999e8a929a424220.

What the data set holds. Spike counts (0 to 0.25 s after each stimulus onset) of the populations analysed in the paper: the separation experiment (11 sessions, 22 populations per area, 396 V1 and 691 V4 units) and the distractor-orientation experiment (4 sessions, Figure 6E). It holds no receptive-field mapping sessions, no per-session coarse mapping of targets and single distractors, and no waveforms.

The pseudo-population analysis (figs3-pseudo-populations) is in the second notebook, pseudo_populations.ipynb, to keep each notebook within the run time limit.

Claim Tested here
data-populations yes
fig1b-v4-rf-larger blocked, data_missing (no mapping sessions)
fig2a-v1-single-neuron-near, fig2b-v4-single-neuron-near yes
fig2c-farthest-spacing-slopes, fig2c-v4-worse-all-spacings yes
fig2de-population-decoding-example yes
fig2f-v1-threshold-elevation, fig2f-v4-threshold-elevation yes
figs3-pseudo-populations yes, in pseudo_populations.ipynb
fig3ab-correlations-reduced yes
fig3c-shuffled-threshold-elevation yes
fig3d-v1-fano-closest, fig3e-v4-fano-all-spacings yes
fig4a-v1-modulation-indices, fig4b-v4-modulation-indices yes
fig4c-modulation-strength-significant, fig4c-v4-stronger-than-v1, fig4c-v4-maintained-v1-weaker-far yes
figs4-rf-alignment blocked, data_missing (no coarse mapping of each distractor alone)
figs5-additive-vs-multiplicative yes
fig5bc-tuning-model-terms, fit-quality, fig5-terms-covary, fig5-negative-multiplicative yes
fig5de-simulated-discriminability yes
fig6c-tuning-correlation-near, fig6d-tuning-correlation-spacing, fig6e-tuning-correlation-configuration yes
fig6-well-isolated blocked, data_missing (no waveform SNR)
fig7cd-fixed-decoder-generalization yes
figs6-common-neuron-pool yes

Method details the claims file leaves to the paper are cited in the helper crowding.py and in each section. All analyses use every deposited unit: the deposit holds exactly the paper's 396 and 691 units, and the selection rule of the Methods does not regenerate them (data-populations).

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¶

Each check of the description against the values is stated under its output.

In [2]:
rows = []
for exp, ps in (("separation", S), ("orientation", O)):
    for p in ps:
        k = p["p"].kind.value_counts()
        rows.append(dict(experiment=exp, area=p["area"], animal=p["animal"], session=p["session"],
                         orange=p["orange"], neurons=p["counts"].shape[0], epochs=p["counts"].shape[1],
                         blank=k.get("blank", 0), dist_only=k.get("dist", 0), alone=k.get("alone", 0),
                         crowd=k.get("crowd", 0), reference=p["ref"],
                         target_rel=" ".join(f"{x:g}" for x in p["oris"] - p["ref"]),
                         count_min=p["counts"].min(), count_max=p["counts"].max()))
info = pd.DataFrame(rows)
print(info.to_string())
print()
print("Populations, sessions and neurons by experiment, area and animal:")
print(info.groupby(["experiment", "area", "animal"]).agg(populations=("session", "size"),
      sessions=("session", "nunique"), neurons=("neurons", "sum"), epochs=("epochs", "sum")).to_string())
print()
for exp, ps in (("separation", S), ("orientation", O)):
    allp = pd.concat([p["p"] for p in ps])
    print(exp, "spacings:", sorted(allp.sep.dropna().unique()), "; target contrast:",
          sorted(allp.target_contrast.unique()), "; distractor contrast:", sorted(allp.distractor_contrast.unique()))
    combos = set()
    for p in ps:
        d = p["p"][p["p"].kind == "crowd"]
        combos |= set(map(tuple, (d[[f"distractor{i}_ori" for i in range(1, 5)]].values - p["ref"]).astype(int)))
    print("   distractor orientations relative to the reference (d1, d2, d3, d4):", sorted(combos))
print()
per_cond = pd.concat([p["p"].assign(area=p["area"], pop=i % 22).query("kind in ['alone','crowd']")
                      .groupby(["area", "pop", "kind", "sep", "oi"], dropna=False).size()
                      for i, p in enumerate(S)])
print("Separation experiment, epochs per stimulus condition: min", per_cond.min(), "median",
      per_cond.median(), "max", per_cond.max())
print("Spike counts: integers from", min(p["counts"].min() for p in S + O), "to",
      max(p["counts"].max() for p in S + O), "spikes per 0.25 s epoch")
     experiment area animal  session  orange  neurons  epochs  blank  dist_only  alone  crowd  reference          target_rel  count_min  count_max
0    separation   V1     AL        1       1       30    1057     43        170    169    675       90.0           -9 -3 3 9          0         34
1    separation   V1     AL        1       2       33    1045     43        162    164    676      180.0           -9 -3 3 9          0         35
2    separation   V1     AL        2       1       31    1125     45        178    180    722       45.0           -9 -3 3 9          0         25
3    separation   V1     AL        2       2       31    1125     46        182    175    722      135.0           -9 -3 3 9          0         29
4    separation   V1     AL        3       1       19    1232     50        196    197    789        0.0           -9 -3 3 9          0         27
5    separation   V1     AL        3       2       19    1240     50        198    200    792       90.0           -9 -3 3 9          0         24
6    separation   V1     AL        4       1       21    1098     43        176    175    704       45.0           -9 -3 3 9          0         27
7    separation   V1     AL        4       2       18    1111     44        179    177    711      135.0           -9 -3 3 9          0         26
8    separation   V1     AL        5       1       11     997     38        163    158    638      180.0           -9 -3 3 9          0         18
9    separation   V1     AL        5       2       11     994     41        161    162    630      270.0           -9 -3 3 9          0         16
10   separation   V1     AL        6       1        8    1207     49        195    193    770      225.0           -9 -3 3 9          0         15
11   separation   V1     AL        6       2        8    1208     48        193    195    772      315.0           -9 -3 3 9          0         18
12   separation   V1     AL        7       1       12    1273     48        205    209    811      225.0           -9 -3 3 9          0         21
13   separation   V1     AL        7       2       12    1263     50        200    201    812      315.0           -9 -3 3 9          0         18
14   separation   V1     CA        8       1       19     545     21         84     88    352      120.0           -9 -3 3 9          0         43
15   separation   V1     CA        8       2       20     546     21         84     91    350      210.0           -9 -3 3 9          0         38
16   separation   V1     CA        9       1       21    1154     45        186    186    737        0.0           -9 -3 3 9          0         37
17   separation   V1     CA        9       2       25    1142     45        183    185    729       90.0           -9 -3 3 9          0         43
18   separation   V1     CA       10       1       14     968     38        156    156    618       45.0           -9 -3 3 9          0         30
19   separation   V1     CA       10       2        7     967     38        152    156    621      135.0           -9 -3 3 9          0         20
20   separation   V1     CA       11       1       14    1064     42        170    169    683       80.0           -9 -3 3 9          0         30
21   separation   V1     CA       11       2       12    1070     42        172    170    686      170.0           -9 -3 3 9          0         37
22   separation   V4     AL        1       1       29    1057     43        170    169    675       90.0           -9 -3 3 9          0         27
23   separation   V4     AL        1       2       31    1045     43        162    164    676      180.0           -9 -3 3 9          0         24
24   separation   V4     AL        2       1       30    1125     45        178    180    722       45.0           -9 -3 3 9          0         21
25   separation   V4     AL        2       2       30    1125     46        182    175    722      135.0           -9 -3 3 9          0         24
26   separation   V4     AL        3       1       22    1232     50        196    197    789        0.0           -9 -3 3 9          0         20
27   separation   V4     AL        3       2       18    1240     50        198    200    792       90.0           -9 -3 3 9          0         18
28   separation   V4     AL        4       1       19    1098     43        176    175    704       45.0           -9 -3 3 9          0         22
29   separation   V4     AL        4       2       16    1111     44        179    177    711      135.0           -9 -3 3 9          0         23
30   separation   V4     AL        5       1       14     997     38        163    158    638      180.0           -9 -3 3 9          0         20
31   separation   V4     AL        5       2       14     994     41        161    162    630      270.0           -9 -3 3 9          0         16
32   separation   V4     AL        6       1       18    1207     49        195    193    770      225.0           -9 -3 3 9          0         24
33   separation   V4     AL        6       2       18    1208     48        193    195    772      315.0           -9 -3 3 9          0         21
34   separation   V4     AL        7       1       14    1273     48        205    209    811      225.0           -9 -3 3 9          0         17
35   separation   V4     AL        7       2       15    1263     50        200    201    812      315.0           -9 -3 3 9          0         18
36   separation   V4     CA        8       1       52     545     21         84     88    352      120.0           -9 -3 3 9          0         55
37   separation   V4     CA        8       2       54     546     21         84     91    350      210.0           -9 -3 3 9          0         56
38   separation   V4     CA        9       1       52    1154     45        186    186    737        0.0           -9 -3 3 9          0         38
39   separation   V4     CA        9       2       56    1142     45        183    185    729       90.0           -9 -3 3 9          0         33
40   separation   V4     CA       10       1       45     968     38        156    156    618       45.0           -9 -3 3 9          0         47
41   separation   V4     CA       10       2       50     967     38        152    156    621      135.0           -9 -3 3 9          0         48
42   separation   V4     CA       11       1       46    1064     42        170    169    683       80.0           -9 -3 3 9          0         34
43   separation   V4     CA       11       2       48    1070     42        172    170    686      170.0           -9 -3 3 9          0         35
44  orientation   V1     AL        1       1       31    1100     45         91    324    640        0.0  -12 -8 -4 0 4 8 12          0         30
45  orientation   V1     AL        1       2       26    1101     44         93    325    639       90.0  -12 -8 -4 0 4 8 12          0         28
46  orientation   V1     AL        2       1       14    1235     52        106    358    719       75.0  -12 -8 -4 0 4 8 12          0         33
47  orientation   V1     AL        2       2       17    1238     51        102    363    722      165.0  -12 -8 -4 0 4 8 12          0         30
48  orientation   V1     CA        3       1       21    1192     50         99    350    693        0.0  -12 -8 -4 0 4 8 12          0         37
49  orientation   V1     CA        3       2       13    1191     50        100    346    695       90.0  -12 -8 -4 0 4 8 12          0         28
50  orientation   V1     CA        4       1       15    1140     48         94    331    667      150.0  -12 -8 -4 0 4 8 12          0         32
51  orientation   V1     CA        4       2       18    1135     47         94    331    663      240.0  -12 -8 -4 0 4 8 12          0         35
52  orientation   V4     AL        1       1       39    1100     45         91    324    640        0.0  -12 -8 -4 0 4 8 12          0         30
53  orientation   V4     AL        1       2       36    1101     44         93    325    639       90.0  -12 -8 -4 0 4 8 12          0         28
54  orientation   V4     AL        2       1       23    1235     52        106    358    719       75.0  -12 -8 -4 0 4 8 12          0         18
55  orientation   V4     AL        2       2       24    1238     51        102    363    722      165.0  -12 -8 -4 0 4 8 12          0         25
56  orientation   V4     CA        3       1       55    1192     50         99    350    693        0.0  -12 -8 -4 0 4 8 12          0         47
57  orientation   V4     CA        3       2       55    1191     50        100    346    695       90.0  -12 -8 -4 0 4 8 12          0         40
58  orientation   V4     CA        4       1       52    1140     48         94    331    667      150.0  -12 -8 -4 0 4 8 12          0         55
59  orientation   V4     CA        4       2       52    1135     47         94    331    663      240.0  -12 -8 -4 0 4 8 12          0         56

Populations, sessions and neurons by experiment, area and animal:
                         populations  sessions  neurons  epochs
experiment  area animal                                        
orientation V1   AL                4         2       88    4674
                 CA                4         2       67    4658
            V4   AL                4         2      122    4674
                 CA                4         2      214    4658
separation  V1   AL               14         7      264   15975
                 CA                8         4      132    7456
            V4   AL               14         7      288   15975
                 CA                8         4      403    7456

separation spacings: [np.float64(1.32), np.float64(1.64), np.float64(2.04), np.float64(2.56)] ; target contrast: [np.float64(0.0), np.float64(0.5)] ; distractor contrast: [np.float64(0.0), np.float64(0.5)]
   distractor orientations relative to the reference (d1, d2, d3, d4): [(np.int64(10), np.int64(-10), np.int64(10), np.int64(-10))]
orientation spacings: [np.float64(0.0)] ; target contrast: [np.float64(0.0), np.float64(0.5)] ; distractor contrast: [np.float64(0.0), np.float64(0.5)]
   distractor orientations relative to the reference (d1, d2, d3, d4): [(np.int64(-10), np.int64(10), np.int64(-10), np.int64(10)), (np.int64(10), np.int64(-10), np.int64(10), np.int64(-10))]

Separation experiment, epochs per stimulus condition: min 19 median 44.0 max 54
Spike counts: integers from 0 to 56 spikes per 0.25 s epoch

The description says 15 sessions in two files, populations per area and orientation range, spike counts per stimulus epoch (neurons x epochs) and fields for session and animal; the values agree: 11 sessions (7 from AL, 4 from CA) and 22 populations per area in the separation file, 4 sessions (2 per animal) and 8 populations per area in the orientation file. The paper's design is there: four target orientations at -9, -3, +3 and +9 degrees from the reference, isolated or with four distractors at +/-10 degrees alternating around the target, at four spacings (stored as 1.32, 1.64, 2.04 and 2.56 degrees, printed in the paper as 1.3, 1.6, 2.1 and 2.6), and two references 90 degrees apart per session. The files also hold blank epochs and distractor-only epochs, which the description does not mention; blank epochs are taken as the spontaneous condition. The orientation experiment has seven target orientations (-12 to +12 degrees in steps of 4), alone or with one of two distractor configurations whose orientations are swapped (+10/-10 against -10/+10), at one spacing that the file does not state.

In [3]:
# Are the V1 and V4 epochs of a population the same epochs in the same order?
rows = []
for a, b in zip(pops("V1"), pops("V4")):
    ka = a["p"].fillna(-1).groupby(["kind", "oi", "sep"]).size()
    kb = b["p"].fillna(-1).groupby(["kind", "oi", "sep"]).size()
    same_seq = (a["p"].fillna(-1)[["kind", "oi", "sep"]].values == b["p"].fillna(-1)[["kind", "oi", "sep"]].values).all(1)
    rows.append(dict(session=a["session"], orange=a["orange"], epochs=len(a["p"]),
                     same_counts_per_condition=ka.equals(kb), same_condition_at_same_index=same_seq.mean()))
al = pd.DataFrame(rows)
print(al.to_string())
print("Expected share of equal conditions at the same index if orders were unrelated: about",
      round(float(np.mean([(p["p"].fillna(-1).groupby(["kind", "oi", "sep"]).size() / len(p["p"])).pow(2).sum()
                           for p in pops("V1")])), 3))


def resid_series(p):
    """Population mean count per epoch minus the mean of its condition."""
    c = p["counts"].astype(float)
    key = p["p"].kind + p["p"].oi.astype(str) + p["p"].sep.fillna(-1).astype(str)
    r = c.copy()
    for k in key.unique():
        m = (key == k).values
        r[:, m] = c[:, m] - c[:, m].mean(1, keepdims=True)
    return r.mean(0)


def lagcorr(x, lag):
    return np.corrcoef(x[:-lag], x[lag:])[0, 1]


rows = []
for p in S:
    x = resid_series(p)
    rows.append(dict(area=p["area"], session=p["session"], orange=p["orange"],
                     lag1=lagcorr(x, 1), lag10=lagcorr(x, 10), lag50=lagcorr(x, 50),
                     pair_even=np.corrcoef(x[0:-1:2], x[1::2])[0, 1],
                     pair_odd=np.corrcoef(x[1:-1:2], x[2::2])[0, 1]))
ac = pd.DataFrame(rows)
print()
print("Autocorrelation of the population residual over the stored epoch order (median over populations):")
print(ac.groupby("area")[["lag1", "lag10", "lag50", "pair_even", "pair_odd"]].median().round(3).to_string())
print("Populations with lag-10 autocorrelation above 0.1: V1", int((ac.query("area=='V1'").lag10 > 0.1).sum()),
      "of 22, V4", int((ac.query("area=='V4'").lag10 > 0.1).sum()), "of 22")
    session  orange  epochs  same_counts_per_condition  same_condition_at_same_index
0         1       1    1057                       True                      0.030274
1         1       2    1045                       True                      0.043062
2         2       1    1125                       True                      0.031111
3         2       2    1125                       True                      0.040000
4         3       1    1232                       True                      0.043831
5         3       2    1240                       True                      0.048387
6         4       1    1098                       True                      0.042805
7         4       2    1111                       True                      0.036004
8         5       1     997                       True                      0.037111
9         5       2     994                       True                      0.029175
10        6       1    1207                       True                      0.044739
11        6       2    1208                       True                      0.043874
12        7       1    1273                       True                      0.043991
13        7       2    1263                       True                      0.046714
14        8       1     545                       True                      0.034862
15        8       2     546                       True                      0.042125
16        9       1    1154                       True                      0.032062
17        9       2    1142                       True                      0.037653
18       10       1     968                       True                      0.029959
19       10       2     967                       True                      0.041365
20       11       1    1064                       True                      0.029135
21       11       2    1070                       True                      0.037383
Expected share of equal conditions at the same index if orders were unrelated: about 0.04
Autocorrelation of the population residual over the stored epoch order (median over populations):
       lag1  lag10  lag50  pair_even  pair_odd
area                                          
V1    0.163  0.114  0.112      0.175     0.173
V4    0.005 -0.020 -0.002      0.000    -0.009
Populations with lag-10 autocorrelation above 0.1: V1 13 of 22, V4 0 of 22

Within each session and orientation range the V1 and V4 entries have the same number of epochs of every condition, but not in the same order: the share of epochs whose condition agrees at the same index is at the level expected for unrelated orders. The V1 epochs carry slow fluctuations of the population response (residual autocorrelation at a lag of 10 epochs), as recordings in time order do; the V4 epochs carry none. So the V1 epochs are consistent with the recording order and the V4 epochs are stored in some other order, and epochs cannot be matched between the areas. No claim tested here pairs V1 and V4 epochs. The two epochs of one trial cannot be told apart: in V1 the residuals of epochs 2k and 2k+1 are no more alike than those of 2k+1 and 2k+2. The description says nothing about either point.

In [4]:
# Clock check: the counts must follow the stimulus labels. Contrast target-alone with blank epochs,
# with the true labels and with the labels shifted by one and by five epochs.
rng = np.random.default_rng(1)
rows = []
for p in S:
    kind = p["p"].kind.values
    for shift in (0, 1, 5):
        k = np.roll(kind, shift)
        d = p["counts"][:, k == "alone"].mean(1) - p["counts"][:, k == "blank"].mean(1)
        rows.append(dict(area=p["area"], shift=shift, mean_diff=d.mean(), frac_pos=(d > 0).mean()))
ck = pd.DataFrame(rows).groupby(["area", "shift"]).agg(mean_alone_minus_blank=("mean_diff", "mean"),
                                                      frac_neurons_alone_above_blank=("frac_pos", "mean"))
print(ck.round(3).to_string())
# Orientation labels: single-neuron AUC between the extreme orientations, true against shifted labels
rows = []
for p in S:
    oi = p["p"].oi.values.copy()
    kind = p["p"].kind.values
    for shift in (0, 1):
        o = np.roll(oi, shift)
        a = p["counts"][:, (kind == "alone") & (o == 0)]
        b = p["counts"][:, (kind == "alone") & (o == 3)]
        au = np.array([cw.auc(a[i], b[i]) for i in range(a.shape[0])])
        rows.append(dict(area=p["area"], shift=shift, mean_abs_auc_dev=np.mean(np.abs(au - 0.5))))
print(pd.DataFrame(rows).groupby(["area", "shift"]).mean_abs_auc_dev.mean().round(3).to_string())
            mean_alone_minus_blank  frac_neurons_alone_above_blank
area shift                                                        
V1   0                       1.277                           0.757
     1                      -0.016                           0.466
     5                       0.013                           0.508
V4   0                       1.290                           0.751
     1                      -0.025                           0.508
     5                       0.038                           0.530
area  shift
V1    0        0.085
      1        0.051
V4    0        0.075
      1        0.059

Responses follow the labels: with the true labels target-alone counts exceed blank counts, and the extreme orientations are told apart more than with labels shifted by one epoch, in both areas. With the labels shifted the target and blank difference vanishes. The labels and counts share one order within each area. The next cell breaks this down by population.

In [5]:
# Blank and distractor-only epochs against target epochs, per population: mean over neurons of
# (mean count - blank mean) / blank SD, and the orientation tuning of target-alone counts (mean
# over neurons of the variance of the four orientation means over the mean within-orientation
# variance of a mean; about 1 without tuning), with true labels and labels shifted by one epoch.
rows = []
for p in S:
    c, P = p["counts"], p["p"]
    bl = c[:, cw.stim_mask(p, "blank")]
    sd = bl.std(1, ddof=1)
    sd[sd == 0] = 1
    r = dict(area=p["area"], animal=p["animal"], session=p["session"], orange=p["orange"], blank_mean=bl.mean())
    for kind, s, lab in (("alone", None, "z_alone"), ("dist", None, "z_dist_only"), ("crowd", 1.32, "z_crowd_1.3")):
        r[lab] = np.mean((c[:, cw.stim_mask(p, kind, s)].mean(1) - bl.mean(1)) / sd)
    for shift in (0, 1):
        kind = np.roll(P.kind.values, shift)
        oi = np.roll(P.oi.values, shift)
        ms = [(kind == "alone") & (oi == o) for o in range(4)]
        means = np.stack([c[:, m].mean(1) for m in ms], 1)
        within = np.mean([c[:, m].var(1) / m.sum() for m in ms], 0)
        r[f"tuning_F_shift{shift}"] = np.nanmean(means.var(1, ddof=1) / within)
    rows.append(r)
BL = pd.DataFrame(rows)
print(BL.round(2).to_string())
flat = BL.groupby("session").z_alone.max() < 0.5
print("Sessions whose target epochs do not exceed the blank epochs (z < 0.5 in every population):",
      list(flat[flat].index))
   area animal  session  orange  blank_mean  z_alone  z_dist_only  z_crowd_1.3  tuning_F_shift0  tuning_F_shift1
0    V1     AL        1       1        5.15     0.05         0.01         0.08             1.53             0.92
1    V1     AL        1       2        4.98     0.02        -0.03         0.07             1.36             1.15
2    V1     AL        2       1        3.91     0.09         0.05         0.12             1.79             1.22
3    V1     AL        2       2        4.42     0.04         0.03         0.15             1.53             0.95
4    V1     AL        3       1        2.09     3.71         0.78         4.18             1.72             1.02
5    V1     AL        3       2        2.13     2.94         0.66         3.62             1.69             1.06
6    V1     AL        4       1        1.44     3.15         0.54         3.61             1.19             0.69
7    V1     AL        4       2        1.44     3.30         0.73         3.86             1.09             0.92
8    V1     AL        5       1        1.49     2.69         0.33         2.80             1.59             1.23
9    V1     AL        5       2        1.52     2.19         0.29         2.14             1.39             1.32
10   V1     AL        6       1        0.74     2.69         0.71         3.19             1.89             0.52
11   V1     AL        6       2        0.68     2.74         0.63         3.05             1.67             0.72
12   V1     AL        7       1        1.15     2.38         0.45         2.70             1.51             1.24
13   V1     AL        7       2        1.48     1.89         0.44         2.45             1.75             1.14
14   V1     CA        8       1        9.07     0.07         0.03         0.16             1.33             0.79
15   V1     CA        8       2        9.03    -0.07        -0.16        -0.05             2.64             1.32
16   V1     CA        9       1        7.72     0.00        -0.24        -0.04             3.36             1.35
17   V1     CA        9       2        6.99    -0.15        -0.29        -0.10             1.44             1.39
18   V1     CA       10       1        8.54    -0.18        -0.10         0.31             9.09             0.50
19   V1     CA       10       2        6.11     0.12        -0.11        -0.25            12.85             1.17
20   V1     CA       11       1        8.51     0.09        -0.01         0.02             1.11             1.02
21   V1     CA       11       2       10.11     0.06        -0.02        -0.04             1.52             0.69
22   V4     AL        1       1        4.41     0.10         0.25         0.37             2.79             1.01
23   V4     AL        1       2        5.09    -0.10        -0.11        -0.01             2.88             1.41
24   V4     AL        2       1        4.54    -0.01        -0.07         0.08             1.31             0.75
25   V4     AL        2       2        4.75    -0.01         0.01         0.16             1.57             0.96
26   V4     AL        3       1        2.05     1.88         1.89         2.09             2.60             1.20
27   V4     AL        3       2        2.16     1.65         1.68         1.83             2.76             0.89
28   V4     AL        4       1        1.41     1.98         1.90         2.22             3.05             1.08
29   V4     AL        4       2        1.41     1.99         1.98         2.15             2.80             1.13
30   V4     AL        5       1        1.32     1.97         1.80         2.18             2.08             0.90
31   V4     AL        5       2        1.27     2.14         1.87         2.23             1.77             0.86
32   V4     AL        6       1        1.16     2.89         2.30         2.80             1.77             1.14
33   V4     AL        6       2        1.30     2.76         2.25         2.53             3.34             0.90
34   V4     AL        7       1        0.89     2.61         2.13         2.63             1.28             0.73
35   V4     AL        7       2        1.00     2.34         1.87         2.22             2.30             1.09
36   V4     CA        8       1        8.19     0.16         0.37         0.59             0.90             1.23
37   V4     CA        8       2        8.27     0.07         0.22         0.43             1.15             0.94
38   V4     CA        9       1        7.35    -0.03         0.01         0.30             2.57             1.20
39   V4     CA        9       2        6.48     0.10         0.10         0.38             2.31             0.94
40   V4     CA       10       1        7.79    -0.07         0.06         0.23             3.95             1.15
41   V4     CA       10       2        6.46     0.12         0.35         0.55             3.25             1.34
42   V4     CA       11       1        6.78     0.02         0.29         0.45             1.46             1.01
43   V4     CA       11       2        6.68     0.03         0.32         0.46             1.42             1.23
Sessions whose target epochs do not exceed the blank epochs (z < 0.5 in every population): [1, 2, 8, 9, 10, 11]
In [6]:
# Per population: the contrast values the parameters hold, and the mean count of the blank,
# distractor-only and target-alone epochs, with the fraction of units whose target-alone (and
# distractor-only) mean exceeds their blank mean.
rows = []
for p in S:
    P, c = p["p"], p["counts"]
    m = {k: c[:, cw.stim_mask(p, k)].mean(1) for k in ("blank", "dist", "alone")}
    rows.append(dict(area=p["area"], session=p["session"], orange=p["orange"],
                     target_contrasts=" ".join(f"{x:g}" for x in np.sort(P.target_contrast.unique())),
                     distractor_contrasts=" ".join(f"{x:g}" for x in np.sort(P.distractor_contrast.unique())),
                     n_blank=int((P.kind == "blank").sum()), n_dist=int((P.kind == "dist").sum()),
                     mean_blank=m["blank"].mean(), mean_dist=m["dist"].mean(), mean_alone=m["alone"].mean(),
                     frac_alone_gt_blank=np.mean(m["alone"] > m["blank"]),
                     frac_dist_gt_blank=np.mean(m["dist"] > m["blank"])))
CT = pd.DataFrame(rows)
print(CT.round(3).to_string())
flat_s = [1, 2, 8, 9, 10, 11]
for area in AREAS:
    d = CT[CT.area == area]
    for lab, sel in (("sessions 1, 2, 8-11", d.session.isin(flat_s)), ("sessions 3-7", ~d.session.isin(flat_s))):
        x = d[sel]
        print(f"{area} {lab}: fraction of units with target-alone mean above blank {x.frac_alone_gt_blank.min():.2f} "
              f"to {x.frac_alone_gt_blank.max():.2f}; distractor-only above blank {x.frac_dist_gt_blank.min():.2f} to "
              f"{x.frac_dist_gt_blank.max():.2f}")
   area  session  orange target_contrasts distractor_contrasts  n_blank  n_dist  mean_blank  mean_dist  mean_alone  frac_alone_gt_blank  frac_dist_gt_blank
0    V1        1       1            0 0.5                0 0.5       43     170       5.147      5.222       5.261                0.633               0.367
1    V1        1       2            0 0.5                0 0.5       43     162       4.983      4.937       4.987                0.515               0.333
2    V1        2       1            0 0.5                0 0.5       45     178       3.910      3.994       4.075                0.774               0.452
3    V1        2       2            0 0.5                0 0.5       46     182       4.422      4.475       4.488                0.645               0.484
4    V1        3       1            0 0.5                0 0.5       50     196       2.093      3.243       6.397                1.000               0.947
5    V1        3       2            0 0.5                0 0.5       50     198       2.134      3.184       5.814                1.000               0.842
6    V1        4       1            0 0.5                0 0.5       43     176       1.435      1.942       4.291                1.000               0.952
7    V1        4       2            0 0.5                0 0.5       44     179       1.438      2.121       4.520                1.000               1.000
8    V1        5       1            0 0.5                0 0.5       38     163       1.490      1.896       4.498                1.000               0.909
9    V1        5       2            0 0.5                0 0.5       41     161       1.523      1.907       4.135                1.000               1.000
10   V1        6       1            0 0.5                0 0.5       49     195       0.737      1.299       2.821                1.000               1.000
11   V1        6       2            0 0.5                0 0.5       48     193       0.680      1.213       2.928                1.000               1.000
12   V1        7       1            0 0.5                0 0.5       48     205       1.153      1.598       3.503                1.000               0.917
13   V1        7       2            0 0.5                0 0.5       50     200       1.477      1.924       3.585                1.000               0.833
14   V1        8       1            0 0.5                0 0.5       21      84       9.073      9.044       9.178                0.579               0.368
15   V1        8       2            0 0.5                0 0.5       21      84       9.031      8.602       8.845                0.500               0.450
16   V1        9       1            0 0.5                0 0.5       45     186       7.723      7.138       7.852                0.333               0.190
17   V1        9       2            0 0.5                0 0.5       45     183       6.994      6.275       6.624                0.080               0.000
18   V1       10       1            0 0.5                0 0.5       38     156       8.541      8.312       7.767                0.429               0.357
19   V1       10       2            0 0.5                0 0.5       38     152       6.113      5.921       6.363                0.857               0.286
20   V1       11       1            0 0.5                0 0.5       42     170       8.509      8.330       8.705                0.643               0.429
21   V1       11       2            0 0.5                0 0.5       42     172      10.113      9.891      10.170                0.667               0.500
22   V4        1       1            0 0.5                0 0.5       43     170       4.410      4.878       4.630                0.690               0.621
23   V4        1       2            0 0.5                0 0.5       43     162       5.088      4.776       4.861                0.226               0.323
24   V4        2       1            0 0.5                0 0.5       45     178       4.536      4.290       4.508                0.467               0.267
25   V4        2       2            0 0.5                0 0.5       46     182       4.753      4.635       4.704                0.500               0.467
26   V4        3       1            0 0.5                0 0.5       50     196       2.047      5.121       5.005                1.000               1.000
27   V4        3       2            0 0.5                0 0.5       50     198       2.163      5.104       5.013                1.000               1.000
28   V4        4       1            0 0.5                0 0.5       43     176       1.412      3.871       3.998                1.000               1.000
29   V4        4       2            0 0.5                0 0.5       44     179       1.411      3.877       3.973                1.000               1.000
30   V4        5       1            0 0.5                0 0.5       38     163       1.316      3.372       3.663                1.000               1.000
31   V4        5       2            0 0.5                0 0.5       41     161       1.274      3.219       3.520                1.000               1.000
32   V4        6       1            0 0.5                0 0.5       49     195       1.164      3.959       4.599                1.000               1.000
33   V4        6       2            0 0.5                0 0.5       48     193       1.296      4.222       4.756                1.000               1.000
34   V4        7       1            0 0.5                0 0.5       48     205       0.885      3.004       3.485                1.000               1.000
35   V4        7       2            0 0.5                0 0.5       50     200       1.004      2.954       3.514                1.000               1.000
36   V4        8       1            0 0.5                0 0.5       21      84       8.193      9.562       8.666                0.750               0.827
37   V4        8       2            0 0.5                0 0.5       21      84       8.274      9.122       8.460                0.593               0.667
38   V4        9       1            0 0.5                0 0.5       45     186       7.353      7.365       7.237                0.423               0.519
39   V4        9       2            0 0.5                0 0.5       45     183       6.479      6.683       6.701                0.696               0.571
40   V4       10       1            0 0.5                0 0.5       38     156       7.794      7.867       7.586                0.356               0.511
41   V4       10       2            0 0.5                0 0.5       38     152       6.459      7.283       6.729                0.740               0.740
42   V4       11       1            0 0.5                0 0.5       42     170       6.782      7.292       6.810                0.522               0.739
43   V4       11       2            0 0.5                0 0.5       42     172       6.682      7.234       6.730                0.562               0.667
V1 sessions 1, 2, 8-11: fraction of units with target-alone mean above blank 0.08 to 0.86; distractor-only above blank 0.00 to 0.50
V1 sessions 3-7: fraction of units with target-alone mean above blank 1.00 to 1.00; distractor-only above blank 0.83 to 1.00
V4 sessions 1, 2, 8-11: fraction of units with target-alone mean above blank 0.23 to 0.75; distractor-only above blank 0.27 to 0.83
V4 sessions 3-7: fraction of units with target-alone mean above blank 1.00 to 1.00; distractor-only above blank 1.00 to 1.00

In sessions 1, 2 and 8 to 11 (12 of the 22 populations in each area, both animals) the epochs labelled blank (target and distractor contrast 0) and those labelled distractor-only give the same counts as the target epochs (z near 0), while in sessions 3 to 7 the targets drive the neurons well above the blank epochs. The labels are aligned with the counts in all sessions: target-alone counts depend on the target orientation with the true labels (tuning F above 1) and not with labels shifted by one epoch. The contrast parameters hold the same two values (0 and 0.5) for targets and distractors in every session, so nothing in the labels marks the six sessions as different; only the counts do. In sessions 3 to 7 every unit's target-alone mean exceeds its blank mean; in the other six sessions 8% to 86% of V1 units and 23% to 75% of V4 units do, around the half expected when the two kinds of epoch do not differ. So in six sessions the epochs labelled blank cannot have been blank, or their counts are not those of the epochs the labels describe; the files cannot tell which. Spontaneous activity cannot be measured there. This is recorded as a finding; it bears on the selection rule (data-populations) and on the driven fractions of figs6-common-neuron-pool.

data-populations¶

Eleven sessions gave 22 neuronal populations in each area, of on average 19 +/- 1.9 V1 neurons and 31 +/- 3.4 V4 neurons, 396 V1 and 691 V4 neurons in the single-neuron analyses.

The selection rule ("responses >= 1 s.d. above spontaneous rate", STAR Methods) is applied to the deposited units under the two readings of the criterion, with blank epochs as the spontaneous condition (the only spontaneous data held) and the SD over blank epochs.

In [7]:
rows = []
for area in AREAS:
    ps = pops(area)
    sizes = np.array([p["counts"].shape[0] for p in ps])
    sel_a = sel_b = 0
    sizes_a, sizes_b = [], []
    for p in ps:
        bl = p["counts"][:, cw.stim_mask(p, "blank")]
        thr = bl.mean(1) + bl.std(1, ddof=1)
        a = p["counts"][:, cw.stim_mask(p, "alone")].mean(1) >= thr
        b = cw.tuning(p, "alone").max(1) >= thr
        sizes_a.append(a.sum())
        sizes_b.append(b.sum())
    for label, sz in (("deposited units", sizes), ("selection (a), mean over targets", np.array(sizes_a)),
                      ("selection (b), best target", np.array(sizes_b))):
        rows.append(dict(area=area, units=label, sessions=len({p["session"] for p in ps}), populations=len(ps),
                         mean_size=sz.mean(), sem_size=sz.std(ddof=1) / np.sqrt(len(sz)), total=sz.sum()))
dp = pd.DataFrame(rows)
print(dp.round(2).to_string())
print()
print("Deposited units per animal (Figure S7: V1 264 and 132, V4 288 and 403):")
print(info.query("experiment=='separation'").groupby(["area", "animal"]).neurons.sum().to_string())
print()
print("Expected: 11 sessions, 22 populations, V1 19 +/- 1.9, V4 31 +/- 3.4, totals 396 +/- 40 and 691 +/- 69")
for _, r in dp.iterrows():
    exp_size, tol_size, exp_tot, tol_tot = (19, 1.9, 396, 40) if r.area == "V1" else (31, 3.4, 691, 69)
    print(f"{r.area} {r.units:34s} size within: {abs(r.mean_size - exp_size) <= tol_size}; "
          f"total within: {abs(r.total - exp_tot) <= tol_tot}")
  area                             units  sessions  populations  mean_size  sem_size  total
0   V1                   deposited units        11           22      18.00      1.70    396
1   V1  selection (a), mean over targets        11           22       5.23      1.42    115
2   V1        selection (b), best target        11           22       6.05      1.57    133
3   V4                   deposited units        11           22      31.41      3.35    691
4   V4  selection (a), mean over targets        11           22       6.68      1.65    147
5   V4        selection (b), best target        11           22       7.91      1.66    174

Deposited units per animal (Figure S7: V1 264 and 132, V4 288 and 403):
area  animal
V1    AL        264
      CA        132
V4    AL        288
      CA        403

Expected: 11 sessions, 22 populations, V1 19 +/- 1.9, V4 31 +/- 3.4, totals 396 +/- 40 and 691 +/- 69
V1 deposited units                    size within: True; total within: True
V1 selection (a), mean over targets   size within: False; total within: False
V1 selection (b), best target         size within: False; total within: False
V4 deposited units                    size within: True; total within: True
V4 selection (a), mean over targets   size within: False; total within: False
V4 selection (b), best target         size within: False; total within: False

Result: partially reproduced. The data set holds 11 sessions and 22 populations per area, and its units number exactly 396 in V1 and 691 in V4 (264 and 132, 288 and 403 per animal, as in Figure S7), with mean population sizes of 18.0 +/- 1.7 and 31.4 +/- 3.4, within tolerance. But the deposited units are the selected ones, and the Methods' rule, applied to them under either reading of the criterion, keeps only 115 or 133 of the V1 units and 147 or 174 of the V4 units, far from the reported counts. One reason is in the data check: in sessions 1, 2 and 8 to 11 the epochs labelled blank respond as the target epochs do, so no unit there passes. The counts hold for the data as deposited; the stated selection does not regenerate them.

Single-neuron discriminability (Figure 2A to 2C)¶

fig2a-v1-single-neuron-near: V1 single-neuron discriminability of target orientation is lower with the nearest distractors than for targets alone, with a regression slope of 0.60 (95% CI 0.50 to 0.69).

fig2b-v4-single-neuron-near: In V4 the loss of single-neuron discriminability with the nearest distractors is stronger, with a regression slope of 0.20 (95% CI 0.14 to 0.26).

fig2c-farthest-spacing-slopes: At the farthest spacing ... slopes of 0.74 (0.66 to 0.82) in V1 and 0.44 (0.37 to 0.50) in V4.

fig2c-v4-worse-all-spacings: Distractors impair single-neuron discriminability more in V4 than in V1 at every target-distractor spacing.

All deposited units are used (n = 396 and 691, as in Figure 2). AUC of the two extreme target orientations, the one closer to 0 degrees taken as the preferred (Results, paragraph on Figure 2A); OLS slope of crowded on target-alone AUC; 95% CI from 1000 bootstrap samples over neurons. "Closer to 0" is read as the axial orientation; in the paper's frame of orientations relative to the reference (-9 to +9 degrees) the two extremes are equally close to 0, so the reading with the lower orientation always taken as preferred is shown as a variant (slope_lower_orientation_first).

In [8]:
rng = np.random.default_rng(2)
AUC = {}
for area in AREAS:
    for order in ("paper", "lower_first"):
        AUC[(area, order, None)] = np.concatenate([cw.neuron_aucs(p, "alone", order=order) for p in pops(area)])
        for s in SP:
            AUC[(area, order, s)] = np.concatenate([cw.neuron_aucs(p, "crowd", s, order=order) for p in pops(area)])
animal = {area: np.concatenate([[p["animal"]] * p["counts"].shape[0] for p in pops(area)]) for area in AREAS}
rows = []
for area in AREAS:
    for s in SP:
        x, y = AUC[(area, "paper", None)], AUC[(area, "paper", s)]
        sl, lo, hi = cw.slope_ci(x, y, rng)
        so, slo, shi = cw.slope_ci(x, y, rng, fit=cw.origin_slope)
        sv = cw.ols_slope(AUC[(area, "lower_first", None)], AUC[(area, "lower_first", s)])
        r = dict(area=area, spacing=SPL[s], n=len(x), slope=sl, ci_low=lo, ci_high=hi,
                 slope_through_half=so, ci_low_through_half=slo, ci_high_through_half=shi,
                 slope_lower_orientation_first=sv)
        for an in ("AL", "CA"):
            m = animal[area] == an
            r[f"slope_{an}"] = cw.ols_slope(x[m], y[m])
        rows.append(r)
f2 = pd.DataFrame(rows)
print(f2.round(3).to_string())
print()
print("AUC ranges: alone V1", np.round([AUC[('V1', 'paper', None)].min(), AUC[('V1', 'paper', None)].max()], 3),
      "V4", np.round([AUC[('V4', 'paper', None)].min(), AUC[('V4', 'paper', None)].max()], 3))
exp = {("V1", 1.32): (0.60, 0.10), ("V4", 1.32): (0.20, 0.06), ("V1", 2.56): (0.74, 0.08), ("V4", 2.56): (0.44, 0.07)}
for (area, s), (v, tol) in exp.items():
    r = f2[(f2.area == area) & (f2.spacing == SPL[s])].iloc[0]
    print(f"{area} {SPL[s]} deg: slope {r.slope:.3f} [{r.ci_low:.3f}, {r.ci_high:.3f}] against {v} +/- {tol}: "
          f"within {abs(r.slope - v) <= tol}; CI upper bound below 1: {r.ci_high < 1}")
print()
for s in SP:
    a = f2[(f2.area == "V1") & (f2.spacing == SPL[s])].iloc[0]
    b = f2[(f2.area == "V4") & (f2.spacing == SPL[s])].iloc[0]
    print(f"{SPL[s]} deg: (a) V4 slope below V1: {b.slope < a.slope}; (b) CIs do not overlap: {b.ci_high < a.ci_low}")

fig, axs = plt.subplots(1, 3, figsize=(12, 3.6))
for ax, area in zip(axs, AREAS):
    ax.scatter(AUC[(area, "paper", None)], AUC[(area, "paper", 1.32)], s=6, alpha=0.5)
    ax.plot([0, 1], [0, 1], "k:")
    ax.set(xlim=(0, 1), ylim=(0, 1), xlabel="AUC target alone", ylabel="AUC nearest distractors", title=area)
for area, c in zip(AREAS, ("tab:blue", "tab:red")):
    d = f2[f2.area == area]
    axs[2].errorbar(np.arange(4), d.slope, yerr=[d.slope - d.ci_low, d.ci_high - d.slope], color=c, label=area, marker="o")
axs[2].set(xticks=range(4), xticklabels=[SPL[s] for s in SP], xlabel="spacing (deg)", ylabel="regression slope", ylim=(0, 1))
axs[2].legend()
plt.tight_layout()
plt.show()
print("All AUC values lie in [0, 1], inside the axes.")
  area spacing    n  slope  ci_low  ci_high  slope_through_half  ci_low_through_half  ci_high_through_half  slope_lower_orientation_first  slope_AL  slope_CA
0   V1     1.3  396  0.580   0.486    0.669               0.607                0.502                 0.700                          0.602     0.495     0.644
1   V1     1.6  396  0.689   0.601    0.765               0.703                0.622                 0.778                          0.700     0.582     0.783
2   V1     2.1  396  0.641   0.556    0.721               0.658                0.572                 0.729                          0.660     0.490     0.758
3   V1     2.6  396  0.728   0.647    0.798               0.746                0.666                 0.818                          0.742     0.556     0.874
4   V4     1.3  691  0.206   0.145    0.269               0.203                0.145                 0.266                          0.200     0.319     0.122
5   V4     1.6  691  0.297   0.228    0.357               0.299                0.233                 0.365                          0.299     0.473     0.167
6   V4     2.1  691  0.313   0.244    0.383               0.308                0.243                 0.375                          0.308     0.402     0.245
7   V4     2.6  691  0.437   0.368    0.501               0.441                0.372                 0.504                          0.440     0.514     0.379

AUC ranges: alone V1 [0.063 0.988] V4 [0.046 0.993]
V1 1.3 deg: slope 0.580 [0.486, 0.669] against 0.6 +/- 0.1: within True; CI upper bound below 1: True
V4 1.3 deg: slope 0.206 [0.145, 0.269] against 0.2 +/- 0.06: within True; CI upper bound below 1: True
V1 2.6 deg: slope 0.728 [0.647, 0.798] against 0.74 +/- 0.08: within True; CI upper bound below 1: True
V4 2.6 deg: slope 0.437 [0.368, 0.501] against 0.44 +/- 0.07: within True; CI upper bound below 1: True

1.3 deg: (a) V4 slope below V1: True; (b) CIs do not overlap: True
1.6 deg: (a) V4 slope below V1: True; (b) CIs do not overlap: True
2.1 deg: (a) V4 slope below V1: True; (b) CIs do not overlap: True
2.6 deg: (a) V4 slope below V1: True; (b) CIs do not overlap: True
No description has been provided for this image
All AUC values lie in [0, 1], inside the axes.

Result: fig2a-v1-single-neuron-near reproduced. The V1 slope at 1.3 degrees is 0.580 (95% CI 0.486 to 0.669), within 0.60 +/- 0.10, with the CI below 1; 0.607 through (0.5, 0.5). With the lower orientation always preferred the slopes are 0.602 and 0.200 at 1.3 degrees and 0.742 and 0.440 at 2.6 (V1 and V4), within 0.022 of the main reading, so no outcome below depends on it.

Result: fig2b-v4-single-neuron-near reproduced. The V4 slope at 1.3 degrees is 0.206 (0.145 to 0.269), within 0.20 +/- 0.06.

Result: fig2c-farthest-spacing-slopes reproduced. At 2.6 degrees the slopes are 0.728 (0.647 to 0.798) in V1 and 0.437 (0.368 to 0.501) in V4, within 0.74 +/- 0.08 and 0.44 +/- 0.07.

Result: fig2c-v4-worse-all-spacings reproduced. At every spacing the V4 slope is below the V1 slope and the two 95% CIs do not overlap (reading b). Per animal the V4 slope is below the V1 slope at every spacing in both animals (AL 0.319 to 0.514 against 0.490 to 0.582; CA 0.122 to 0.379 against 0.644 to 0.874).

fig3ab-correlations-reduced¶

Distractors reduce noise correlations, from 0.07 +/- 0.003 to 0.05 +/- 0.002 in V1 and from 0.11 +/- 0.001 to 0.06 +/- 0.001 in V4 with the nearest distractors (paired t test, p < 0.001).

Pairs within each population; per stimulus, trials with both counts within 3 SD of their means; averaged over the four target orientations (STAR Methods). Reading (a), every stored epoch as a presentation, is the only one that can be run: the files do not say which epoch of a trial is the first, and the residuals do not reveal the pairing (data check), so reading (b) cannot be formed.

In [9]:
RSC = {}
for area in AREAS:
    RSC[(area, None)] = np.concatenate([cw.pair_rsc(p, "alone") for p in pops(area)])
    for s in SP:
        RSC[(area, s)] = np.concatenate([cw.pair_rsc(p, "crowd", s) for p in pops(area)])
rows = []
for area in AREAS:
    a0 = RSC[(area, None)]
    for s in [None] + list(SP):
        x = RSC[(area, s)]
        ok = np.isfinite(a0) & np.isfinite(x)
        t = stats.ttest_rel(a0[ok], x[ok]) if s is not None else None
        rows.append(dict(area=area, condition="target alone" if s is None else SPL[s], pairs=len(x),
                         pairs_finite=int(np.isfinite(x).sum()), mean=np.nanmean(x),
                         sem=np.nanstd(x, ddof=1) / np.sqrt(np.isfinite(x).sum()),
                         paired_t=None if t is None else t.statistic, p=None if t is None else t.pvalue,
                         n_paired=int(ok.sum())))
f3 = pd.DataFrame(rows)
print(f3.to_string(float_format=lambda v: f"{v:.4g}"))
print()
for area, (e0, e1) in (("V1", (0.07, 0.05)), ("V4", (0.11, 0.06))):
    r0 = f3[(f3.area == area) & (f3.condition == "target alone")].iloc[0]
    r1 = f3[(f3.area == area) & (f3.condition == "1.3")].iloc[0]
    print(f"{area}: alone {r0['mean']:.4f} (expected {e0} +/- 0.005, within {abs(r0['mean'] - e0) <= 0.005}); "
          f"nearest {r1['mean']:.4f} (expected {e1} +/- 0.005, within {abs(r1['mean'] - e1) <= 0.005}); "
          f"decrease p = {r1.p:.2g}; pairs {r0.pairs} (expected {4028 if area == 'V1' else 13020} +/- 10%)")
for area in AREAS:
    print(area, "rSC per animal, alone and nearest:",
          {an: (round(float(np.nanmean(np.concatenate([cw.pair_rsc(p, 'alone') for p in pops(area) if p['animal'] == an]))), 4),
                round(float(np.nanmean(np.concatenate([cw.pair_rsc(p, 'crowd', 1.32) for p in pops(area) if p['animal'] == an]))), 4))
           for an in ("AL", "CA")})
  area     condition  pairs  pairs_finite    mean       sem  paired_t         p  n_paired
0   V1  target alone   4036          4036 0.06722  0.002496       NaN       NaN      4036
1   V1           1.3   4036          4036 0.04789  0.002306     9.559 2.009e-21      4036
2   V1           1.6   4036          4036 0.05759  0.002394      5.23 1.784e-07      4036
3   V1           2.1   4036          4036  0.0566   0.00247      5.88 4.446e-09      4036
4   V1           2.6   4036          4036 0.06402  0.002516     1.793   0.07308      4036
5   V4  target alone  13101         13101  0.1122  0.001309       NaN       NaN     13101
6   V4           1.3  13101         13101 0.05553  0.000958     44.43         0     13101
7   V4           1.6  13101         13100 0.06033 0.0009772     40.47         0     13100
8   V4           2.1  13101         13051 0.05719  0.000974     42.97         0     13051
9   V4           2.6  13101         13101  0.0519 0.0009905     45.95         0     13101

V1: alone 0.0672 (expected 0.07 +/- 0.005, within True); nearest 0.0479 (expected 0.05 +/- 0.005, within True); decrease p = 2e-21; pairs 4036 (expected 4028 +/- 10%)
V4: alone 0.1122 (expected 0.11 +/- 0.005, within True); nearest 0.0555 (expected 0.06 +/- 0.005, within True); decrease p = 0; pairs 13101 (expected 13020 +/- 10%)
V1 rSC per animal, alone and nearest: {'AL': (0.0337, 0.0304), 'CA': (0.1524, 0.0924)}
V4 rSC per animal, alone and nearest: {'AL': (0.0658, 0.0495), 'CA': (0.1266, 0.0574)}

Result: reproduced. Mean rSC falls from 0.0672 +/- 0.0025 to 0.0479 +/- 0.0023 in V1 and from 0.1122 +/- 0.0013 to 0.0555 +/- 0.0010 in V4 with the nearest distractors, all four within 0.005 of the paper's values; paired t tests give p = 2e-21 (V1) and p below 1e-300 (V4, printed 0). There are 4036 V1 and 13101 V4 pairs against 4028 and 13020. Only reading (a), every epoch as a presentation, could be run. The decrease is also present in each animal.

Fano factors (Figure 3D and 3E)¶

fig3d-v1-fano-closest: In V1, distractors at the closest spacing slightly reduce variability, the Fano factor falling from 1.05 +/- 0.02 for targets alone to 0.98 +/- 0.01 (paired t test, p < 0.001).

fig3e-v4-fano-all-spacings: In V4, distractors at all spacings significantly reduce variability, the Fano factor falling from 1.00 +/- 0.01 for targets alone to 0.93 +/- 0.01 with the closest distractors (paired t test, p < 0.001 for each spacing).

Per neuron, the geometric mean over the four stimulus conditions of variance over mean; across neurons the geometric mean, with the SEM of the logs transformed back (exp(mean +/- SEM) given as a half-width). Conditions with zero mean or zero variance are left out (a standard choice); the paired t test is run on the Fano factors and on their logs.

In [10]:
FF = {}
rows = []
for area in AREAS:
    FF[(area, None)] = np.concatenate([cw.fano(p, "alone") for p in pops(area)])
    for s in SP:
        FF[(area, s)] = np.concatenate([cw.fano(p, "crowd", s) for p in pops(area)])
    a0 = FF[(area, None)]
    for s in [None] + list(SP):
        x = FF[(area, s)]
        lx = np.log(x[np.isfinite(x)])
        gm, sem = np.exp(lx.mean()), lx.std(ddof=1) / np.sqrt(len(lx))
        r = dict(area=area, condition="target alone" if s is None else SPL[s], n=int(np.isfinite(x).sum()),
                 geo_mean=gm, sem_halfwidth=gm * (np.exp(sem) - np.exp(-sem)) / 2)
        if s is not None:
            ok = np.isfinite(a0) & np.isfinite(x)
            t1 = stats.ttest_rel(a0[ok], x[ok])
            t2 = stats.ttest_rel(np.log(a0[ok]), np.log(x[ok]))
            r.update(t_ff=t1.statistic, p_ff=t1.pvalue, t_log=t2.statistic, p_log=t2.pvalue)
        rows.append(r)
ff = pd.DataFrame(rows)
print(ff.to_string(float_format=lambda v: f"{v:.4g}"))
print("Neurons left out (no usable condition): ", {k: int((~np.isfinite(v)).sum()) for k, v in FF.items() if k[1] in (None, 1.32)})
print("Fano factor range over neurons, V1 alone", np.round([np.nanmin(FF[('V1', None)]), np.nanmax(FF[('V1', None)])], 3),
      "V4 alone", np.round([np.nanmin(FF[('V4', None)]), np.nanmax(FF[('V4', None)])], 3))
print()
for area, e0, e1, tol0, tol1 in (("V1", 1.05, 0.98, 0.02, 0.01), ("V4", 1.00, 0.93, 0.01, 0.01)):
    r0 = ff[(ff.area == area) & (ff.condition == "target alone")].iloc[0]
    r1 = ff[(ff.area == area) & (ff.condition == "1.3")].iloc[0]
    print(f"{area}: alone {r0.geo_mean:.3f} (expected {e0} +/- {tol0}: {abs(r0.geo_mean - e0) <= tol0}); "
          f"closest {r1.geo_mean:.3f} (expected {e1} +/- {tol1}: {abs(r1.geo_mean - e1) <= tol1})")
for area in AREAS:
    for an in ("AL", "CA"):
        m = animal[area] == an
        print(area, an, "geometric mean alone %.3f, closest %.3f" % (np.exp(np.nanmean(np.log(FF[(area, None)][m]))),
                                                                   np.exp(np.nanmean(np.log(FF[(area, 1.32)][m])))))
  area     condition    n  geo_mean  sem_halfwidth    t_ff      p_ff   t_log     p_log
0   V1  target alone  396     1.051        0.01403     NaN       NaN     NaN       NaN
1   V1           1.3  396    0.9847         0.0113   5.636 3.322e-08   5.364  1.39e-07
2   V1           1.6  396     1.004        0.01127   5.256 2.416e-07   4.542 7.428e-06
3   V1           2.1  396     1.054        0.01312  0.1254    0.9003 -0.3412    0.7331
4   V1           2.6  396      1.06        0.01367 -0.6481    0.5173  -1.003    0.3166
5   V4  target alone  691    0.9974       0.008824     NaN       NaN     NaN       NaN
6   V4           1.3  691    0.9285       0.006779   9.044 1.508e-18   8.789 1.191e-17
7   V4           1.6  691    0.9483       0.006927   6.716 3.904e-11    6.31 5.001e-10
8   V4           2.1  691    0.9502       0.007321   6.141 1.387e-09   5.826 8.697e-09
9   V4           2.6  691    0.9453       0.007163   6.626 6.963e-11   6.318 4.763e-10
Neurons left out (no usable condition):  {('V1', None): 0, ('V1', 1.32): 0, ('V4', None): 0, ('V4', 1.32): 0}
Fano factor range over neurons, V1 alone [0.29  2.469] V4 alone [0.409 2.377]

V1: alone 1.051 (expected 1.05 +/- 0.02: True); closest 0.985 (expected 0.98 +/- 0.01: True)
V4: alone 0.997 (expected 1.0 +/- 0.01: True); closest 0.928 (expected 0.93 +/- 0.01: True)
V1 AL geometric mean alone 1.040, closest 0.981
V1 CA geometric mean alone 1.074, closest 0.993
V4 AL geometric mean alone 1.008, closest 0.973
V4 CA geometric mean alone 0.990, closest 0.898

Result: fig3d-v1-fano-closest reproduced. The V1 geometric mean Fano factor is 1.051 for targets alone and 0.985 at 1.3 degrees, within 1.05 +/- 0.02 and 0.98 +/- 0.01; paired t test p = 3.3e-08 on the Fano factors and 1.4e-07 on their logs.

Result: fig3e-v4-fano-all-spacings reproduced. In V4 the values are 0.997 alone and 0.928 at 1.3 degrees, within 1.00 +/- 0.01 and 0.93 +/- 0.01, and the decrease has p < 0.001 at each of the four spacings under both tests (largest p 1.4e-09 on the Fano factors, 8.7e-09 on logs).

Modulation indices (Figure 4)¶

fig4a-v1-modulation-indices: In V1, distractors at the closest spacing suppress and facilitate responses in roughly equal proportion, with significant suppression in 23% and facilitation in 27% of neurons; for farther distractors modulation is weaker, with 2.5% significant facilitation and 13% suppression.

fig4b-v4-modulation-indices: For the closest distractors most V4 neurons are facilitated (mean index 1.11 +/- 0.38, t test, p < 0.001; significant facilitation in 51% and suppression in 14% of cases), and the average index is larger than in V1 (one-sided t test, p < 0.01); at larger spacing facilitation and suppression are roughly equal (0.97 +/- 0.48; 24% and 32% significant).

Index per neuron and spacing: geometric mean over the four target orientations of the crowded over the target-alone mean count. Null: target-alone and crowded responses combined, resampled with replacement in the experimental numbers, 1000 times (STAR Methods); combined within each orientation or over all orientations. Tail rules: (a) two-sided, 2.5% per tail; (b) one-sided, 5% per direction. Neurons with a zero target-alone or crowded mean at some orientation have no index and are dropped.

In [11]:
rng = np.random.default_rng(4)
MI, NULL = {}, {}
for area in AREAS:
    for s in SP:
        MI[(area, s)] = np.concatenate([cw.modulation(p, s) for p in pops(area)])
        for pool in ("orientation", "all"):
            NULL[(area, s, pool)] = np.concatenate([cw.modulation_null(p, s, rng, pool=pool) for p in pops(area)])


def sig_counts(area, s, pool, rule):
    mi, nl = MI[(area, s)], NULL[(area, s, pool)]
    ok = np.isfinite(mi)
    # rank among the null draws that are defined (a draw is undefined when a resampled mean is 0)
    rank = np.sum(nl < mi[:, None], 1) / np.maximum(np.sum(np.isfinite(nl), 1), 1)
    tail = 0.025 if rule == "two-sided" else 0.05
    fac = ok & (rank > 1 - tail)
    sup = ok & (rank < tail)
    return ok, fac, sup


rows = []
for area in AREAS:
    for s in SP:
        for pool in ("orientation", "all"):
            for rule in ("two-sided", "one-sided"):
                ok, fac, sup = sig_counts(area, s, pool, rule)
                mi = MI[(area, s)][ok]
                rows.append(dict(area=area, spacing=SPL[s], pool=pool, rule=rule, n=int(ok.sum()),
                                 dropped=int((~ok).sum()), frac_above_1=np.mean(mi > 1), frac_below_1=np.mean(mi < 1),
                                 sig_fac_pct_all=100 * fac.sum() / ok.sum(), sig_sup_pct_all=100 * sup.sum() / ok.sum(),
                                 sig_fac_pct_of_facilitated=100 * fac.sum() / (mi > 1).sum(),
                                 sig_sup_pct_of_suppressed=100 * sup.sum() / (mi < 1).sum()))
        # farther spacings pooled (reading b)
for area in AREAS:
    for pool in ("orientation", "all"):
        for rule in ("two-sided", "one-sided"):
            oks, facs, sups, mis = [], [], [], []
            for s in SP[1:]:
                ok, fac, sup = sig_counts(area, s, pool, rule)
                oks.append(ok); facs.append(fac); sups.append(sup); mis.append(MI[(area, s)])
            ok, fac, sup, mi = map(np.concatenate, (oks, facs, sups, mis))
            mi = mi[ok]
            rows.append(dict(area=area, spacing="1.6-2.6 pooled", pool=pool, rule=rule, n=int(ok.sum()),
                             dropped=int((~ok).sum()), frac_above_1=np.mean(mi > 1), frac_below_1=np.mean(mi < 1),
                             sig_fac_pct_all=100 * fac.sum() / ok.sum(), sig_sup_pct_all=100 * sup.sum() / ok.sum(),
                             sig_fac_pct_of_facilitated=100 * fac.sum() / (mi > 1).sum(),
                             sig_sup_pct_of_suppressed=100 * sup.sum() / (mi < 1).sum()))
mod = pd.DataFrame(rows)
print(mod.round(1).to_string())
print("Undefined null draws (a resampled mean of 0), percent of all draws of the neurons with a defined index:")
for area in AREAS:
    for s in SP:
        ok = np.isfinite(MI[(area, s)])
        print(f"   {area} {SPL[s]} deg: " + ", ".join(
            f"pool {pool} {100 * np.mean(~np.isfinite(NULL[(area, s, pool)][ok])):.2f}%" for pool in ("orientation", "all")))
   area         spacing         pool       rule     n  dropped  frac_above_1  frac_below_1  sig_fac_pct_all  sig_sup_pct_all  sig_fac_pct_of_facilitated  sig_sup_pct_of_suppressed
0    V1             1.3  orientation  two-sided   396        0           0.4           0.6             26.5             24.5                        61.0                       43.3
1    V1             1.3  orientation  one-sided   396        0           0.4           0.6             28.3             28.8                        65.1                       50.9
2    V1             1.3          all  two-sided   396        0           0.4           0.6             26.0             24.7                        59.9                       43.8
3    V1             1.3          all  one-sided   396        0           0.4           0.6             28.3             28.3                        65.1                       50.0
4    V1             1.6  orientation  two-sided   396        0           0.3           0.7              9.8             22.5                        29.8                       33.6
5    V1             1.6  orientation  one-sided   396        0           0.3           0.7             11.4             28.0                        34.4                       41.9
6    V1             1.6          all  two-sided   396        0           0.3           0.7              9.6             21.5                        29.0                       32.1
7    V1             1.6          all  one-sided   396        0           0.3           0.7             11.6             28.0                        35.1                       41.9
8    V1             2.1  orientation  two-sided   396        0           0.3           0.7              0.8             15.2                         2.6                       21.4
9    V1             2.1  orientation  one-sided   396        0           0.3           0.7              1.3             24.0                         4.3                       33.9
10   V1             2.1          all  two-sided   396        0           0.3           0.7              0.8             14.4                         2.6                       20.4
11   V1             2.1          all  one-sided   396        0           0.3           0.7              1.5             24.5                         5.2                       34.6
12   V1             2.6  orientation  two-sided   396        0           0.3           0.7              2.0             14.4                         7.6                       19.6
13   V1             2.6  orientation  one-sided   396        0           0.3           0.7              2.5             19.7                         9.5                       26.8
14   V1             2.6          all  two-sided   396        0           0.3           0.7              1.8             12.9                         6.7                       17.5
15   V1             2.6          all  one-sided   396        0           0.3           0.7              2.3             20.2                         8.6                       27.5
16   V4             1.3  orientation  two-sided   691        0           0.7           0.3             50.7             15.1                        72.6                       49.8
17   V4             1.3  orientation  one-sided   691        0           0.7           0.3             53.1             17.1                        76.1                       56.5
18   V4             1.3          all  two-sided   691        0           0.7           0.3             50.7             14.3                        72.6                       47.4
19   V4             1.3          all  one-sided   691        0           0.7           0.3             53.1             17.1                        76.1                       56.5
20   V4             1.6  orientation  two-sided   691        0           0.6           0.4             38.1             25.0                        68.0                       56.9
21   V4             1.6  orientation  one-sided   691        0           0.6           0.4             40.8             27.1                        72.9                       61.5
22   V4             1.6          all  two-sided   691        0           0.6           0.4             37.9             24.9                        67.7                       56.6
23   V4             1.6          all  one-sided   691        0           0.6           0.4             40.7             27.1                        72.6                       61.5
24   V4             2.1  orientation  two-sided   689        2           0.5           0.5             30.6             29.6                        64.1                       56.7
25   V4             2.1  orientation  one-sided   689        2           0.5           0.5             33.2             32.5                        69.6                       62.2
26   V4             2.1          all  two-sided   689        2           0.5           0.5             30.3             29.3                        63.5                       56.1
27   V4             2.1          all  one-sided   689        2           0.5           0.5             33.5             33.1                        70.2                       63.3
28   V4             2.6  orientation  two-sided   689        2           0.4           0.6             23.9             33.8                        54.1                       60.7
29   V4             2.6  orientation  one-sided   689        2           0.4           0.6             26.7             37.7                        60.3                       67.7
30   V4             2.6          all  two-sided   689        2           0.4           0.6             23.5             33.8                        53.1                       60.7
31   V4             2.6          all  one-sided   689        2           0.4           0.6             26.4             37.7                        59.7                       67.7
32   V1  1.6-2.6 pooled  orientation  two-sided  1188        0           0.3           0.7              4.2             17.3                        14.2                       24.6
33   V1  1.6-2.6 pooled  orientation  one-sided  1188        0           0.3           0.7              5.1             23.9                        17.0                       34.0
34   V1  1.6-2.6 pooled          all  two-sided  1188        0           0.3           0.7              4.0             16.2                        13.6                       23.1
35   V1  1.6-2.6 pooled          all  one-sided  1188        0           0.3           0.7              5.1             24.2                        17.3                       34.4
36   V4  1.6-2.6 pooled  orientation  two-sided  2069        4           0.5           0.5             30.9             29.5                        62.6                       58.2
37   V4  1.6-2.6 pooled  orientation  one-sided  2069        4           0.5           0.5             33.6             32.4                        68.1                       64.0
38   V4  1.6-2.6 pooled          all  two-sided  2069        4           0.5           0.5             30.6             29.3                        62.0                       57.9
39   V4  1.6-2.6 pooled          all  one-sided  2069        4           0.5           0.5             33.5             32.6                        68.0                       64.4
Undefined null draws (a resampled mean of 0), percent of all draws of the neurons with a defined index:
   V1 1.3 deg: pool orientation 0.00%, pool all 0.00%
   V1 1.6 deg: pool orientation 0.00%, pool all 0.00%
   V1 2.1 deg: pool orientation 0.00%, pool all 0.00%
   V1 2.6 deg: pool orientation 0.00%, pool all 0.00%
   V4 1.3 deg: pool orientation 0.12%, pool all 0.02%
   V4 1.6 deg: pool orientation 0.15%, pool all 0.04%
   V4 2.1 deg: pool orientation 0.00%, pool all 0.00%
   V4 2.6 deg: pool orientation 0.00%, pool all 0.00%
In [12]:
print("V1 expected: closest 23 +/- 2.3 % suppression and 27 +/- 2.7 % facilitation; farther 2.5 +/- 0.25 % "
      "facilitation and 13 +/- 1.3 % suppression (percent of all neurons)")
for pool in ("orientation", "all"):
    for rule in ("two-sided", "one-sided"):
        near = mod.query("area=='V1' and spacing=='1.3' and pool==@pool and rule==@rule").iloc[0]
        ok_near = abs(near.sig_sup_pct_all - 23) <= 2.3 and abs(near.sig_fac_pct_all - 27) <= 2.7
        for far_label in ("2.6", "1.6-2.6 pooled"):
            far = mod.query("area=='V1' and spacing==@far_label and pool==@pool and rule==@rule").iloc[0]
            ok_far = abs(far.sig_fac_pct_all - 2.5) <= 0.25 and abs(far.sig_sup_pct_all - 13) <= 1.3
            print(f"pool {pool:11s} {rule:9s} far={far_label:15s} near sup {near.sig_sup_pct_all:5.1f} fac "
                  f"{near.sig_fac_pct_all:5.1f} (within {ok_near}); far fac {far.sig_fac_pct_all:5.1f} sup "
                  f"{far.sig_sup_pct_all:5.1f} (within {ok_far})")
mi1 = MI[("V1", 1.32)]
print("V1 closest spacing: index above 1 in %.1f%%, below 1 in %.1f%% of neurons; median %.3f"
      % (100 * np.nanmean(mi1 > 1), 100 * np.nanmean(mi1 < 1), np.nanmedian(mi1)))
V1 expected: closest 23 +/- 2.3 % suppression and 27 +/- 2.7 % facilitation; farther 2.5 +/- 0.25 % facilitation and 13 +/- 1.3 % suppression (percent of all neurons)
pool orientation two-sided far=2.6             near sup  24.5 fac  26.5 (within True); far fac   2.0 sup  14.4 (within False)
pool orientation two-sided far=1.6-2.6 pooled  near sup  24.5 fac  26.5 (within True); far fac   4.2 sup  17.3 (within False)
pool orientation one-sided far=2.6             near sup  28.8 fac  28.3 (within False); far fac   2.5 sup  19.7 (within False)
pool orientation one-sided far=1.6-2.6 pooled  near sup  28.8 fac  28.3 (within False); far fac   5.1 sup  23.9 (within False)
pool all         two-sided far=2.6             near sup  24.7 fac  26.0 (within True); far fac   1.8 sup  12.9 (within False)
pool all         two-sided far=1.6-2.6 pooled  near sup  24.7 fac  26.0 (within True); far fac   4.0 sup  16.2 (within False)
pool all         one-sided far=2.6             near sup  28.3 fac  28.3 (within False); far fac   2.3 sup  20.2 (within False)
pool all         one-sided far=1.6-2.6 pooled  near sup  28.3 fac  28.3 (within False); far fac   5.1 sup  24.2 (within False)
V1 closest spacing: index above 1 in 43.4%, below 1 in 56.6% of neurons; median 0.980

Result: fig4a-v1-modulation-indices partially reproduced. At 1.3 degrees, with the two-sided rule, 24.5% of V1 neurons are significantly suppressed and 26.5% facilitated (pooling within orientation; 24.7% and 26.0% pooling over all), within 23 +/- 2.3% and 27 +/- 2.7%; 56.6% have an index below 1 and 43.4% above. At farther spacings no reading puts both values within tolerance: at 2.6 degrees, two-sided, facilitation is 2.0% or 1.8% (expected 2.5 +/- 0.25) with suppression 14.4% or 12.9% (13 +/- 1.3); one-sided, facilitation is 2.5% or 2.3% but suppression 19.7% or 20.2%; pooled over the three farther spacings facilitation is 4.0 to 5.1%. The modulation is weaker at farther spacings, as the claim says, and the far percentages are near the paper's. At 2.6 degrees, two-sided and pooled within orientation, 2.0% is 8 of 396 neurons and 14.4% is 57; the tolerances (2.25 to 2.75% and 11.7 to 14.3%) correspond to 9 or 10 and 47 to 56 neurons, so each far value misses by one neuron. The facilitation tolerance of 0.25 points is about one neuron of 396, finer than the counts can resolve; this is asked of a reader in questions/henry-2022.yaml, and the claim is judged as the claims file has it.

In [13]:
mi4, mi1 = MI[("V4", 1.32)], MI[("V1", 1.32)]
v4, v1 = mi4[np.isfinite(mi4)], mi1[np.isfinite(mi1)]
mi4f = np.concatenate([MI[("V4", s)] for s in SP[1:]])
mi4f = mi4f[np.isfinite(mi4f)]
mi4_26 = MI[("V4", 2.56)][np.isfinite(MI[("V4", 2.56)])]
print(f"V4 closest: mean index {v4.mean():.3f}, SD {v4.std(ddof=1):.3f}, SEM {v4.std(ddof=1) / np.sqrt(len(v4)):.3f}, "
      f"n = {len(v4)}; above 1 in {100 * np.mean(v4 > 1):.1f}%")
print("   t test against 1 on the index: p = %.2g; on log index: p = %.2g"
      % (stats.ttest_1samp(v4, 1).pvalue, stats.ttest_1samp(np.log(v4), 0).pvalue))
print("   V4 > V1, one-sided two-sample t test on the index: p = %.2g (Welch %.2g); on log index: p = %.2g (Welch %.2g)"
      % (ttest_1s_greater(v4, v1).pvalue, ttest_1s_greater(v4, v1, False).pvalue,
         ttest_1s_greater(np.log(v4), np.log(v1)).pvalue, ttest_1s_greater(np.log(v4), np.log(v1), False).pvalue))
print(f"V1 closest: mean index {v1.mean():.3f}, SD {v1.std(ddof=1):.3f}")
print(f"V4 farthest (2.6): mean {mi4_26.mean():.3f}, SD {mi4_26.std(ddof=1):.3f}; three larger spacings pooled: "
      f"mean {mi4f.mean():.3f}, SD {mi4f.std(ddof=1):.3f}")
print("Expected: V4 closest 1.11 +/- 0.111, facilitation 51 +/- 5.1 %, suppression 14 +/- 1.4 %; "
      "larger spacing 0.97 +/- 0.097, facilitation 24 +/- 2.4 %, suppression 32 +/- 3.2 %")
for pool in ("orientation", "all"):
    for rule in ("two-sided", "one-sided"):
        near = mod.query("area=='V4' and spacing=='1.3' and pool==@pool and rule==@rule").iloc[0]
        for far_label, mfar in (("2.6", mi4_26), ("1.6-2.6 pooled", mi4f)):
            far = mod.query("area=='V4' and spacing==@far_label and pool==@pool and rule==@rule").iloc[0]
            for denom in ("all", "of"):
                if denom == "all":
                    nf, ns, ff_, fs = near.sig_fac_pct_all, near.sig_sup_pct_all, far.sig_fac_pct_all, far.sig_sup_pct_all
                else:
                    nf, ns = near.sig_fac_pct_of_facilitated, near.sig_sup_pct_of_suppressed
                    ff_, fs = far.sig_fac_pct_of_facilitated, far.sig_sup_pct_of_suppressed
                vals_ok = [abs(v4.mean() - 1.11) <= 0.111, abs(nf - 51) <= 5.1, abs(ns - 14) <= 1.4,
                           abs(mfar.mean() - 0.97) <= 0.097, abs(ff_ - 24) <= 2.4, abs(fs - 32) <= 3.2]
                print(f"pool {pool:11s} {rule:9s} far={far_label:15s} denominator={denom:3s}: near fac {nf:5.1f} sup {ns:5.1f}; "
                      f"far fac {ff_:5.1f} sup {fs:5.1f}; values within: {vals_ok}")
V4 closest: mean index 1.134, SD 0.379, SEM 0.014, n = 691; above 1 in 69.8%
   t test against 1 on the index: p = 1.9e-19; on log index: p = 4.5e-17
   V4 > V1, one-sided two-sample t test on the index: p = 0.074 (Welch 0.084); on log index: p = 0.009 (Welch 0.0089)
V1 closest: mean index 1.097, SD 0.446
V4 farthest (2.6): mean 1.009, SD 0.473; three larger spacings pooled: mean 1.038, SD 0.467
Expected: V4 closest 1.11 +/- 0.111, facilitation 51 +/- 5.1 %, suppression 14 +/- 1.4 %; larger spacing 0.97 +/- 0.097, facilitation 24 +/- 2.4 %, suppression 32 +/- 3.2 %
pool orientation two-sided far=2.6             denominator=all: near fac  50.7 sup  15.1; far fac  23.9 sup  33.8; values within: [np.True_, np.True_, np.True_, np.True_, np.True_, np.True_]
pool orientation two-sided far=2.6             denominator=of : near fac  72.6 sup  49.8; far fac  54.1 sup  60.7; values within: [np.True_, np.False_, np.False_, np.True_, np.False_, np.False_]
pool orientation two-sided far=1.6-2.6 pooled  denominator=all: near fac  50.7 sup  15.1; far fac  30.9 sup  29.5; values within: [np.True_, np.True_, np.True_, np.True_, np.False_, np.True_]
pool orientation two-sided far=1.6-2.6 pooled  denominator=of : near fac  72.6 sup  49.8; far fac  62.6 sup  58.2; values within: [np.True_, np.False_, np.False_, np.True_, np.False_, np.False_]
pool orientation one-sided far=2.6             denominator=all: near fac  53.1 sup  17.1; far fac  26.7 sup  37.7; values within: [np.True_, np.True_, np.False_, np.True_, np.False_, np.False_]
pool orientation one-sided far=2.6             denominator=of : near fac  76.1 sup  56.5; far fac  60.3 sup  67.7; values within: [np.True_, np.False_, np.False_, np.True_, np.False_, np.False_]
pool orientation one-sided far=1.6-2.6 pooled  denominator=all: near fac  53.1 sup  17.1; far fac  33.6 sup  32.4; values within: [np.True_, np.True_, np.False_, np.True_, np.False_, np.True_]
pool orientation one-sided far=1.6-2.6 pooled  denominator=of : near fac  76.1 sup  56.5; far fac  68.1 sup  64.0; values within: [np.True_, np.False_, np.False_, np.True_, np.False_, np.False_]
pool all         two-sided far=2.6             denominator=all: near fac  50.7 sup  14.3; far fac  23.5 sup  33.8; values within: [np.True_, np.True_, np.True_, np.True_, np.True_, np.True_]
pool all         two-sided far=2.6             denominator=of : near fac  72.6 sup  47.4; far fac  53.1 sup  60.7; values within: [np.True_, np.False_, np.False_, np.True_, np.False_, np.False_]
pool all         two-sided far=1.6-2.6 pooled  denominator=all: near fac  50.7 sup  14.3; far fac  30.6 sup  29.3; values within: [np.True_, np.True_, np.True_, np.True_, np.False_, np.True_]
pool all         two-sided far=1.6-2.6 pooled  denominator=of : near fac  72.6 sup  47.4; far fac  62.0 sup  57.9; values within: [np.True_, np.False_, np.False_, np.True_, np.False_, np.False_]
pool all         one-sided far=2.6             denominator=all: near fac  53.1 sup  17.1; far fac  26.4 sup  37.7; values within: [np.True_, np.True_, np.False_, np.True_, np.False_, np.False_]
pool all         one-sided far=2.6             denominator=of : near fac  76.1 sup  56.5; far fac  59.7 sup  67.7; values within: [np.True_, np.False_, np.False_, np.True_, np.False_, np.False_]
pool all         one-sided far=1.6-2.6 pooled  denominator=all: near fac  53.1 sup  17.1; far fac  33.5 sup  32.6; values within: [np.True_, np.True_, np.False_, np.True_, np.False_, np.True_]
pool all         one-sided far=1.6-2.6 pooled  denominator=of : near fac  76.1 sup  56.5; far fac  68.0 sup  64.4; values within: [np.True_, np.False_, np.False_, np.True_, np.False_, np.False_]

Result: fig4b-v4-modulation-indices reproduced, under the two-sided rule with percentages of all neurons, the farthest spacing as "larger spacing", and the t tests on log indices. The V4 mean index at 1.3 degrees is 1.134 (SD 0.379, printed in the paper as +/- 0.38), with 69.8% of neurons above 1 and p = 1.9e-19 against 1; 50.7% are significantly facilitated and 15.1% (or 14.3%) suppressed. At 2.6 degrees the mean is 1.009 (SD 0.473), with 23.9% (23.5%) facilitated and 33.8% suppressed. All six values are within tolerance under both poolings. V4 against V1 at 1.3 degrees, one-sided: p = 0.009 on log indices, below 0.01, but p = 0.074 on the indices themselves (V1 mean 1.097), so this part rests on the log reading. With percentages of the facilitated and suppressed neurons as denominators, the values are far out (72.6% and 49.8%).

Modulation strength (Figure 4C)¶

fig4c-modulation-strength-significant: The strength of modulation, the mean absolute log modulation index, is significant in both areas at all spacings (permutation test, p < 0.01).

fig4c-v4-stronger-than-v1: Modulation strength is stronger in V4 than in V1 at all separations (one-sided t test, p = 0.01 for the closest distractors, p < 0.001 for the others).

fig4c-v4-maintained-v1-weaker-far: Modulation strength in V4 is largely maintained across spacings (one-sided t test nearest against farthest, p = 0.44), whereas in V1 the farthest separation yields weaker modulation than the nearest (one-sided t test, p < 0.001).

Strength per neuron is |log2 index|. The null is the per-neuron resampled indices above (both poolings), averaged over neurons in each of the 1000 resamples.

In [14]:
STR = {k: np.abs(np.log2(v)) for k, v in MI.items()}
rows = []
for area in AREAS:
    for s in SP:
        x = STR[(area, s)]
        obs = np.nanmean(x)
        r = dict(area=area, spacing=SPL[s], n=int(np.isfinite(x).sum()), strength=obs,
                 sem=np.nanstd(x, ddof=1) / np.sqrt(np.isfinite(x).sum()))
        for pool in ("orientation", "all"):
            nl = np.nanmean(np.abs(np.log2(NULL[(area, s, pool)][np.isfinite(x)])), 0)
            r[f"null_mean_{pool}"] = nl.mean()
            r[f"null_99pct_{pool}"] = np.percentile(nl, 99)
            r[f"p_{pool}"] = (1 + np.sum(nl >= obs)) / (1 + len(nl))
        rows.append(r)
ms = pd.DataFrame(rows)
print(ms.to_string(float_format=lambda v: f"{v:.4g}"))
print("Observed above the 99th null percentile at all eight: pooling within orientation",
      bool((ms.strength > ms.null_99pct_orientation).all()), "; over all orientations",
      bool((ms.strength > ms.null_99pct_all).all()))
  area spacing    n  strength      sem  null_mean_orientation  null_99pct_orientation  p_orientation  null_mean_all  null_99pct_all    p_all
0   V1     1.3  396    0.2426  0.01528                0.06414                 0.07167       0.000999        0.06437         0.07087 0.000999
1   V1     1.6  396    0.1369 0.008604                0.06423                 0.07138       0.000999        0.06473         0.07192 0.000999
2   V1     2.1  396    0.0912 0.003679                0.06527                  0.0737       0.000999        0.06564         0.07286 0.000999
3   V1     2.6  396   0.08656 0.003558                0.06516                 0.07257       0.000999        0.06568         0.07306 0.000999
4   V4     1.3  691    0.2854  0.01108                0.06426                 0.07106       0.000999        0.06497          0.0729 0.000999
5   V4     1.6  691    0.2784   0.0115                 0.0655                 0.07289       0.000999        0.06618         0.07337 0.000999
6   V4     2.1  689    0.2833  0.01336                0.06615                 0.07334       0.000999        0.06652         0.07281 0.000999
7   V4     2.6  689    0.2813  0.01389                0.06645                 0.07272       0.000999         0.0666         0.07332 0.000999
Observed above the 99th null percentile at all eight: pooling within orientation True ; over all orientations True

Result: fig4c-modulation-strength-significant reproduced. In all eight area and spacing pairs the observed strength (0.087 to 0.285) exceeds the 99th percentile of its null (0.071 to 0.074), under both poolings; p = 0.001, the smallest attainable with 1000 resamples.

In [15]:
for s in SP:
    a, b = STR[("V4", s)], STR[("V1", s)]
    a, b = a[np.isfinite(a)], b[np.isfinite(b)]
    print(f"{SPL[s]} deg: V4 {a.mean():.4f} vs V1 {b.mean():.4f}; one-sided Student p = {ttest_1s_greater(a, b).pvalue:.2g}, "
          f"Welch p = {ttest_1s_greater(a, b, False).pvalue:.2g}")
1.3 deg: V4 0.2854 vs V1 0.2426; one-sided Student p = 0.011, Welch p = 0.012
1.6 deg: V4 0.2784 vs V1 0.1369; one-sided Student p = 1.9e-17, Welch p = 2.8e-22
2.1 deg: V4 0.2833 vs V1 0.0912; one-sided Student p = 4.7e-26, Welch p = 1.4e-39
2.6 deg: V4 0.2813 vs V1 0.0866; one-sided Student p = 5.8e-25, Welch p = 4e-38

Result: fig4c-v4-stronger-than-v1 reproduced. V4 strength exceeds V1 at every spacing: one-sided p = 0.011 at 1.3 degrees (paper 0.01; Welch 0.012) and p from 1.9e-17 to 4.7e-26 at the other three (Welch 2.8e-22 to 1.4e-39).

In [16]:
for area in AREAS:
    n_, f_ = STR[(area, 1.32)], STR[(area, 2.56)]
    ok = np.isfinite(n_) & np.isfinite(f_)
    tp = stats.ttest_rel(n_[ok], f_[ok], alternative="greater")
    ti = stats.ttest_ind(n_[np.isfinite(n_)], f_[np.isfinite(f_)], alternative="greater")
    print(f"{area}: nearest {np.nanmean(n_):.4f}, farthest {np.nanmean(f_):.4f}, difference {np.nanmean(n_) - np.nanmean(f_):.4f}; "
          f"one-sided paired p = {tp.pvalue:.3g} (n = {ok.sum()}), one-sided two-sample p = {ti.pvalue:.3g}")
V1: nearest 0.2426, farthest 0.0866, difference 0.1560; one-sided paired p = 9.26e-23 (n = 396), one-sided two-sample p = 2.53e-22
V4: nearest 0.2854, farthest 0.2813, difference 0.0041; one-sided paired p = 0.403 (n = 689), one-sided two-sample p = 0.409

Result: fig4c-v4-maintained-v1-weaker-far reproduced. In V4, nearest 0.2854 against farthest 0.2813 (difference 0.0041): one-sided p = 0.403 paired and 0.409 two-sample, against the paper's 0.44, so neither test finds a decrease. In V1, 0.2426 against 0.0866: p = 9.3e-23 paired and 2.5e-22 two-sample, below 0.001.

Tuning model (Figure 5, Figure S5, fit quality)¶

fig5bc-tuning-model-terms: With both terms allowed, V1 tuning amid distractors has a multiplicative term below 1 (0.59 +/- 0.03) and a positive additive term (0.39 +/- 0.16); in V4 the multiplicative term is 0.36 +/- 0.01 and the additive term 0.90 +/- 0.02; the multiplicative term is smaller and the additive term larger in V4 than in V1 (t test).

Neurons whose target-alone tuning from even and from odd presentations of each orientation (in stored order) correlates above 0.5. In V4 the stored order is not the recording order (data check), so there the split is in effect a random half split. Per neuron and spacing, rTD = max(mrT + amean(rT), 0), m and a by maximum Poisson likelihood, on single-trial counts (reading 1a) and on mean counts per orientation (1b).

In [17]:
REL = {area: np.concatenate([cw.even_odd_reliability(p) for p in pops(area)]) for area in AREAS}
for area in AREAS:
    print(f"{area}: reliability > 0.5 in {np.sum(REL[area] > 0.5)} of {len(REL[area])} neurons "
          f"(undefined in {np.sum(~np.isfinite(REL[area]))}); per animal "
          f"{ {an: int(np.sum((REL[area] > 0.5) & (animal[area] == an))) for an in ('AL', 'CA')} }")
# The V4 stored order is not the recording order (data check). Two order-free variants: the count
# passing under single random half splits (what an even/odd split of a random order gives), and
# REL_R, the reliability averaged over 20 random half splits, whose selection is fitted below too.
rng_sp = np.random.default_rng(13)
for area in AREAS:
    cnt = [sum(int(np.sum(cw.random_split_reliability(p, rng_sp, 1) > 0.5)) for p in pops(area)) for _ in range(20)]
    print(f"{area}: neurons above 0.5 under 20 single random half splits: mean {np.mean(cnt):.1f}, range {min(cnt)} to {max(cnt)}")
rng = np.random.default_rng(6)
REL_R = {area: np.concatenate([cw.random_split_reliability(p, rng) for p in pops(area)]) for area in AREAS}
for area in AREAS:
    print(f"{area}: REL_R (mean over 20 random splits) > 0.5 in {np.sum(REL_R[area] > 0.5)} neurons; per animal "
          f"{ {an: int(np.sum((REL_R[area] > 0.5) & (animal[area] == an))) for an in ('AL', 'CA')} }; "
          f"both selections {np.sum((REL[area] > 0.5) & (REL_R[area] > 0.5))}")


def fit_population(p, rel, single_trial):
    rows = []
    rT_all = cw.tuning(p, "alone")
    for i in np.flatnonzero(rel > 0.5):
        rT = rT_all[i]
        for s in SP:
            rc = [r[i] for r in cw.responses(p, "crowd", s)]
            m, a, ll = cw.fit_affine(rT, rc, single_trial)
            pred = np.maximum(m * rT + a * rT.mean(), cw.EPS)
            ll_null = cw._poisson_ll(np.full(len(rT), np.mean(np.concatenate(rc))), rc, True)
            ll_orac = cw._poisson_ll(np.array([c.mean() for c in rc]), rc, True)
            ll_mod = cw._poisson_ll(pred, rc, True)
            cm, llm = cw.fit_single(rT, rc, "mult", single_trial)
            ca, lla = cw.fit_single(rT, rc, "add", single_trial)
            rows.append(dict(area=p["area"], animal=p["animal"], session=p["session"], orange=p["orange"],
                             neuron=i, spacing=s, m=m, a=a, ll_null=ll_null, ll_oracle=ll_orac, ll_model=ll_mod,
                             c_mult=cm, c_add=ca, ll_mult=llm, ll_add=lla,
                             n_trials=[len(c) for c in rc]))
    return rows


t0 = time.time()
FIT = {}
for st in (True, False):
    res = Parallel(n_jobs=4)(delayed(fit_population)(p, cw.even_odd_reliability(p), st) for p in S)
    FIT[st] = pd.DataFrame([r for rr in res for r in rr])
offsets = {area: np.cumsum([0] + [p["counts"].shape[0] for p in pops(area)]) for area in AREAS}
rel_r_pop = [REL_R[p["area"]][offsets[p["area"]][k]:offsets[p["area"]][k + 1]]
             for area in AREAS for k, p in enumerate(pops(area))]
pop_order = [p for area in AREAS for p in pops(area)]
FIT_R = pd.DataFrame([r for rr in Parallel(n_jobs=4)(delayed(fit_population)(p, rl, True)
                                                     for p, rl in zip(pop_order, rel_r_pop)) for r in rr])
print(f"fits done in {time.time() - t0:.0f} s; cases per area:", FIT[True].groupby("area").size().to_dict(),
      "; random-split selection (REL_R):", FIT_R.groupby("area").size().to_dict())

rows = []
for st in (True, False):
    f = FIT[st]
    for unit in ("cases", "neurons"):
        g = f if unit == "cases" else f.groupby(["area", "session", "orange", "neuron"], as_index=False)[["m", "a"]].mean()
        r = dict(likelihood="single trial" if st else "means", unit=unit)
        for area in AREAS:
            x = g[g.area == area]
            r[f"{area}_n"] = len(x)
            r[f"{area}_m"] = x.m.mean(); r[f"{area}_m_sem"] = x.m.std(ddof=1) / np.sqrt(len(x))
            r[f"{area}_a"] = x.a.mean(); r[f"{area}_a_sem"] = x.a.std(ddof=1) / np.sqrt(len(x))
            r[f"{area}_m_below1_p"] = stats.ttest_1samp(x.m, 1, alternative="less").pvalue
        a1, a4 = g[g.area == "V1"], g[g.area == "V4"]
        r["m_V4_lt_V1_p_two_sided"] = stats.ttest_ind(a4.m, a1.m).pvalue
        r["m_V4_minus_V1"] = a4.m.mean() - a1.m.mean()
        r["a_V4_gt_V1_p_two_sided"] = stats.ttest_ind(a4.a, a1.a).pvalue
        r["a_V4_minus_V1"] = a4.a.mean() - a1.a.mean()
        rows.append(r)
f5 = pd.DataFrame(rows)
print(f5.T.to_string(float_format=lambda v: f"{v:.4g}"))
print()
print("Expected: V1 m 0.59 +/- 0.03, a 0.39 +/- 0.16; V4 m 0.36 +/- 0.01, a 0.90 +/- 0.02; 146 and 198 neurons")
for _, r in f5.iterrows():
    ok = [abs(r.V1_m - 0.59) <= 0.03, abs(r.V1_a - 0.39) <= 0.16, abs(r.V4_m - 0.36) <= 0.01, abs(r.V4_a - 0.90) <= 0.02]
    print(f"{r.likelihood:12s} {r.unit:8s} values within: {ok}")
f = FIT[True]
print("Range of fitted m: V1", np.round([f[f.area == 'V1'].m.min(), f[f.area == 'V1'].m.max()], 2),
      "V4", np.round([f[f.area == 'V4'].m.min(), f[f.area == 'V4'].m.max()], 2),
      "; of a: V1", np.round([f[f.area == 'V1'].a.min(), f[f.area == 'V1'].a.max()], 2),
      "V4", np.round([f[f.area == 'V4'].a.min(), f[f.area == 'V4'].a.max()], 2))
print("Median m and a (single trial, cases):", f.groupby("area")[["m", "a"]].median().round(3).to_dict())
print("Per animal (single trial, cases):")
print(f.groupby(["area", "animal"]).agg(neurons=("neuron", lambda x: len(x) // 4), m=("m", "mean"), a=("a", "mean")).round(3).to_string())
fig, axs = plt.subplots(1, 2, figsize=(8, 3.6))
for ax, area in zip(axs, AREAS):
    x = f[f.area == area]
    ax.scatter(x.m, x.a, c=x.spacing, cmap="viridis_r", s=6)
    ax.set(xlim=(-2, 2), ylim=(-2, 2), xlabel="multiplicative term", ylabel="additive term", title=area)
plt.tight_layout()
plt.show()
for area in AREAS:
    x = f[f.area == area]
    print(area, "cases outside the axes (|m| or |a| > 2):", int(((x.m.abs() > 2) | (x.a.abs() > 2)).sum()), "of", len(x))
V1: reliability > 0.5 in 146 of 396 neurons (undefined in 0); per animal {'AL': 89, 'CA': 57}
V4: reliability > 0.5 in 244 of 691 neurons (undefined in 0); per animal {'AL': 114, 'CA': 130}
V1: neurons above 0.5 under 20 single random half splits: mean 143.8, range 126 to 163
V4: neurons above 0.5 under 20 single random half splits: mean 238.3, range 219 to 256
V1: REL_R (mean over 20 random splits) > 0.5 in 109 neurons; per animal {'AL': 61, 'CA': 48}; both selections 85
V4: REL_R (mean over 20 random splits) > 0.5 in 160 neurons; per animal {'AL': 73, 'CA': 87}; both selections 114
fits done in 96 s; cases per area: {'V1': 584, 'V4': 976} ; random-split selection (REL_R): {'V1': 436, 'V4': 640}
                                   0             1         2          3
likelihood              single trial  single trial     means      means
unit                           cases       neurons     cases    neurons
V1_n                             584           146       584        146
V1_m                          0.4048        0.4048    0.4053     0.4053
V1_m_sem                     0.02321       0.03526    0.0232    0.03526
V1_a                          0.5955        0.5955    0.5951     0.5951
V1_a_sem                     0.02583       0.03912   0.02582    0.03911
V1_m_below1_p              5.657e-98     2.418e-36  6.29e-98  2.602e-36
V4_n                             976           244       976        244
V4_m                          0.1542        0.1542    0.1547     0.1547
V4_m_sem                      0.0171       0.02081    0.0171    0.02078
V4_a                          0.9071        0.9071    0.9067     0.9067
V4_a_sem                     0.02263       0.03513   0.02264    0.03514
V4_m_below1_p             3.028e-268    1.167e-110 3.92e-268 1.003e-110
m_V4_lt_V1_p_two_sided     3.622e-18     1.918e-10 3.563e-18  1.875e-10
m_V4_minus_V1                -0.2506       -0.2506   -0.2506    -0.2506
a_V4_gt_V1_p_two_sided     3.731e-18     2.257e-08 3.758e-18  2.268e-08
a_V4_minus_V1                 0.3116        0.3116    0.3116     0.3116

Expected: V1 m 0.59 +/- 0.03, a 0.39 +/- 0.16; V4 m 0.36 +/- 0.01, a 0.90 +/- 0.02; 146 and 198 neurons
single trial cases    values within: [False, False, False, True]
single trial neurons  values within: [False, False, False, True]
means        cases    values within: [False, False, False, True]
means        neurons  values within: [False, False, False, True]
Range of fitted m: V1 [-1.39  2.86] V4 [-2.14  2.61] ; of a: V1 [-1.85  5.14] V4 [-1.57  7.68]
Median m and a (single trial, cases): {'m': {'V1': 0.403, 'V4': 0.173}, 'a': {'V1': 0.583, 'V4': 0.865}}
Per animal (single trial, cases):
             neurons      m      a
area animal                       
V1   AL           89  0.333  0.679
     CA           57  0.517  0.465
V4   AL          114  0.227  0.797
     CA          130  0.091  1.003
No description has been provided for this image
V1 cases outside the axes (|m| or |a| > 2): 11 of 584
V4 cases outside the axes (|m| or |a| > 2): 46 of 976

Result: partially reproduced. The even/odd criterion keeps 146 V1 neurons, exactly the paper's count (89 and 57 per animal, as in Figure S7), and 244 V4 neurons against 198 +/- 20 (114 and 130 against 93 and 105). The V4 epochs are not stored in recording order (data check), but the order does not explain the excess: single random half splits keep 238.3 V4 neurons on average (219 to 256 over 20 splits) and 143.8 V1 neurons (126 to 163), so both stored-order counts lie in the range of random splits. The directions hold: m is below 1 in both areas (p < 1e-35), V4 has the smaller m (difference -0.251, p = 3.6e-18) and the larger a (+0.312, p = 3.7e-18). The values do not: over cases V1 m = 0.405 +/- 0.023 and a = 0.596 +/- 0.026 (expected 0.59 and 0.39), V4 m = 0.154 +/- 0.017 (expected 0.36) and a = 0.907 +/- 0.023, the only one within tolerance. Fits on means and averages over neurons change these by less than 0.001. On the selection by reliability averaged over 20 random splits (109 V1 and 160 V4 neurons, below) the picture is the same: m 0.403 and 0.178, a 0.588 and 0.894, only the V4 additive term within tolerance, and the V4 differences at p = 4.1e-16 and 1.9e-14.

fit-quality¶

In the neurons fitted with the tuning model, the fit quality (a normalized likelihood between a null model at 0 and an oracle at 1) is 0.63 in V1 and 0.73 in V4.

In [18]:
for st in (True, False):
    f = FIT[st].copy()
    f["q"] = (f.ll_model - f.ll_null) / (f.ll_oracle - f.ll_null)
    ok = (f.ll_oracle - f.ll_null) > 1e-9
    for area in AREAS:
        x = f[ok & (f.area == area)]
        pooled = (x.ll_model - x.ll_null).sum() / (x.ll_oracle - x.ll_null).sum()
        print(f"fits on {'single trials' if st else 'means'}: {area} mean per case {x.q.mean():.3f}, median per case "
              f"{x.q.median():.3f}, pooled {pooled:.3f} (n = {len(x)}, degenerate cases dropped {int((~ok & (f.area == area)).sum())}; "
              f"range {x.q.min():.2f} to {x.q.max():.2f})")
print("Expected: V1 0.63 +/- 0.063, V4 0.73 +/- 0.073")
fits on single trials: V1 mean per case 0.455, median per case 0.460, pooled 0.623 (n = 584, degenerate cases dropped 0; range 0.00 to 1.00)
fits on single trials: V4 mean per case 0.410, median per case 0.328, pooled 0.589 (n = 976, degenerate cases dropped 0; range 0.00 to 1.00)
fits on means: V1 mean per case 0.454, median per case 0.460, pooled 0.623 (n = 584, degenerate cases dropped 0; range -0.00 to 1.00)
fits on means: V4 mean per case 0.410, median per case 0.328, pooled 0.589 (n = 976, degenerate cases dropped 0; range -0.00 to 1.00)
Expected: V1 0.63 +/- 0.063, V4 0.73 +/- 0.073

Result: not reproduced. The V1 fit quality is 0.623 when pooled over cases, within 0.63 +/- 0.063, but 0.455 as a mean and 0.460 as a median per case; V4 gives 0.589 pooled, 0.410 mean and 0.328 median, all outside 0.73 +/- 0.073. No reading puts both values within tolerance. On the random-split selection (below) V1 gives 0.489 mean, 0.494 median and 0.663 pooled, and V4 0.440, 0.410 and 0.651, again with V4 outside tolerance under every reading.

fig5-terms-covary¶

In both V1 and V4 the additive and multiplicative terms covary strongly, consistent with a flattening of tuning with maintained responsivity.

In [19]:
for st in (True, False):
    f = FIT[st]
    for area in AREAS:
        x = f[f.area == area]
        r, p = stats.pearsonr(x.m, x.a)
        rs, ps = stats.spearmanr(x.m, x.a)
        print(f"fits on {'single trials' if st else 'means'}: {area} Pearson r = {r:.3f} (p = {p:.2g}), "
              f"Spearman rho = {rs:.3f} (p = {ps:.2g}), n = {len(x)} cases")
fits on single trials: V1 Pearson r = -0.892 (p = 2.4e-203), Spearman rho = -0.955 (p = 2.1e-310), n = 584 cases
fits on single trials: V4 Pearson r = -0.682 (p = 2.5e-134), Spearman rho = -0.839 (p = 1.6e-259), n = 976 cases
fits on means: V1 Pearson r = -0.892 (p = 3.1e-203), Spearman rho = -0.955 (p = 2.1e-310), n = 584 cases
fits on means: V4 Pearson r = -0.682 (p = 1.8e-134), Spearman rho = -0.839 (p = 1e-259), n = 976 cases

Result: reproduced. m and a are strongly and negatively correlated: Pearson r = -0.892 in V1 (584 cases) and -0.682 in V4 (976 cases), p below 1e-130 (Spearman -0.955 and -0.839). Over 20 single random half splits, each keeping the neurons whose reliability on that split is above 0.5 (below), r is -0.966 to -0.854 in V1 and -0.893 to -0.639 in V4 (medians -0.886 and -0.683), so the criterion holds on all 20 and the stored-order split is typical of single splits. Only the selection by reliability averaged over 20 random splits, which keeps fewer neurons (160 in V4), gives V4 r = -0.459 (p = 1.1e-34), below the criterion's 0.5 (V1 -0.913). The outcome rests on a single split, as the paper's rule describes, and is marked as resting on that assumption.

fig5-negative-multiplicative¶

Some fits give a negative multiplicative term, offset by a large additive term; such cases are rare in V1 and more frequent in V4.

In [20]:
for st in (True, False):
    f = FIT[st]
    tab = []
    for area in AREAS:
        x = f[f.area == area]
        neg = x.m < 0
        tab.append([neg.sum(), (~neg).sum()])
        print(f"fits on {'single trials' if st else 'means'}: {area} m < 0 in {neg.sum()} of {len(x)} cases "
              f"({100 * neg.mean():.1f}%); mean a with m < 0 {x.a[neg].mean():.3f}, otherwise {x.a[~neg].mean():.3f}")
    print("   Fisher exact test, two-sided: p = %.2g" % stats.fisher_exact(tab)[1])
fits on single trials: V1 m < 0 in 136 of 584 cases (23.3%); mean a with m < 0 1.291, otherwise 0.384
fits on single trials: V4 m < 0 in 343 of 976 cases (35.1%); mean a with m < 0 1.411, otherwise 0.634
   Fisher exact test, two-sided: p = 7.7e-07
fits on means: V1 m < 0 in 137 of 584 cases (23.5%); mean a with m < 0 1.290, otherwise 0.382
fits on means: V4 m < 0 in 344 of 976 cases (35.2%); mean a with m < 0 1.413, otherwise 0.631
   Fisher exact test, two-sided: p = 1e-06

Result: partially reproduced. Negative multiplicative terms are more frequent in V4 (35.1% of cases) than in V1 (23.3%; Fisher p = 7.7e-07), and they come with large additive terms (mean a 1.29 and 1.41 against 0.38 and 0.63). But 23.3% of V1 cases is not rare by the criterion's reading (below 10%). On the random-split selection (below) the fractions are 20.2% and 33.6% (Fisher p = 1.3e-06), the same partial outcome.

fig5de-simulated-discriminability¶

Simulating crowded responses with the fitted multiplicative and additive terms yields some loss of discriminability in V1 and more in V4, similar to but slightly stronger than the measured loss, and depending weakly on spacing.

For each fitted neuron and spacing, Poisson counts at the two extreme orientations with the measured target-alone means and with the model's prediction (single-trial fits); AUC with the preferred extreme as in Figure 2; OLS slope with 1000 bootstrap samples. Trials per stimulus: (a) as recorded, (b) 1000. Measured slopes: (a) Figure 2C over all neurons, (b) the fitted neurons only.

In [21]:
rng = np.random.default_rng(5)
popkey = {(p["area"], p["session"], p["orange"]): p for p in S}


def simulate_aucs(f, mode, rng, rule="affine"):
    """Simulated (alone, crowded) AUCs per case. rule 'affine' uses m and a; 'single' the
    additive fit when the case's index is above 1 and the multiplicative one otherwise."""
    out = []
    for _, r in f.iterrows():
        p = popkey[(r.area, r.session, r.orange)]
        first, second = cw.extreme_order(p)
        rT = cw.tuning(p, "alone")[r.neuron]
        if rule == "affine":
            pred = np.maximum(r.m * rT + r.a * rT.mean(), 0)
        elif r.mi > 1:
            pred = np.maximum(rT + r.c_add * rT.mean(), 0)
        else:
            pred = np.maximum(r.c_mult * rT, 0)
        ra, rc = cw.responses(p, "alone"), cw.responses(p, "crowd", r.spacing)
        if mode == "recorded":
            na1, na2, nc1, nc2 = ra[first].shape[1], ra[second].shape[1], rc[first].shape[1], rc[second].shape[1]
        else:
            na1 = na2 = nc1 = nc2 = 1000
        a = cw.auc(rng.poisson(rT[first], na1), rng.poisson(rT[second], na2))
        c = cw.auc(rng.poisson(pred[first], nc1), rng.poisson(pred[second], nc2))
        out.append((a, c))
    return np.array(out)


fitted = FIT[True].copy()
fitted["mi"] = [cw.modulation(popkey[(r.area, r.session, r.orange)], r.spacing)[r.neuron] for _, r in fitted.iterrows()]
meas_fitted = {}
for area in AREAS:
    for s in SP:
        x = fitted[(fitted.area == area) & (fitted.spacing == s)]
        a = np.array([cw.neuron_aucs(popkey[(r.area, r.session, r.orange)], "alone")[r.neuron] for _, r in x.iterrows()])
        c = np.array([cw.neuron_aucs(popkey[(r.area, r.session, r.orange)], "crowd", s)[r.neuron] for _, r in x.iterrows()])
        meas_fitted[(area, s)] = cw.ols_slope(a, c)
SIM = {}
rows = []
for rule in ("affine", "single"):
    for mode in ("recorded", "1000"):
        for area in AREAS:
            for s in SP:
                x = fitted[(fitted.area == area) & (fitted.spacing == s)]
                ac = simulate_aucs(x, mode, rng, rule)
                sl, lo, hi = cw.slope_ci(ac[:, 0], ac[:, 1], rng)
                m2 = f2[(f2.area == area) & (f2.spacing == SPL[s])].iloc[0].slope
                rows.append(dict(model=rule, trials=mode, area=area, spacing=SPL[s], n=len(x), sim_slope=sl, ci_low=lo,
                                 ci_high=hi, measured_all=m2, measured_fitted=meas_fitted[(area, s)]))
sim = pd.DataFrame(rows)
print(sim.round(3).to_string())
print()
for mode in ("recorded", "1000"):
    d = sim[(sim.model == "affine") & (sim.trials == mode)]
    v1, v4 = d[d.area == "V1"].sim_slope.values, d[d.area == "V4"].sim_slope.values
    print(f"affine, trials {mode}: V4 simulated slope below V1 at every spacing: {bool(np.all(v4 < v1))}")
    for meas in ("measured_all", "measured_fitted"):
        for area in AREAS:
            dd = d[d.area == area]
            print(f"   {meas:16s} {area}: simulated at or below measured at {int((dd.sim_slope <= dd[meas]).sum())} of 4 spacings")
     model    trials area spacing    n  sim_slope  ci_low  ci_high  measured_all  measured_fitted
0   affine  recorded   V1     1.3  146      0.404   0.290    0.514         0.580            0.590
1   affine  recorded   V1     1.6  146      0.533   0.393    0.661         0.689            0.758
2   affine  recorded   V1     2.1  146      0.567   0.475    0.653         0.641            0.708
3   affine  recorded   V1     2.6  146      0.523   0.395    0.642         0.728            0.750
4   affine  recorded   V4     1.3  244      0.243   0.167    0.323         0.206            0.264
5   affine  recorded   V4     1.6  244      0.294   0.200    0.382         0.297            0.347
6   affine  recorded   V4     2.1  244      0.305   0.217    0.396         0.313            0.351
7   affine  recorded   V4     2.6  244      0.336   0.237    0.437         0.437            0.480
8   affine      1000   V1     1.3  146      0.448   0.331    0.553         0.580            0.590
9   affine      1000   V1     1.6  146      0.630   0.522    0.715         0.689            0.758
10  affine      1000   V1     2.1  146      0.624   0.537    0.699         0.641            0.708
11  affine      1000   V1     2.6  146      0.660   0.566    0.747         0.728            0.750
12  affine      1000   V4     1.3  244      0.251   0.176    0.319         0.206            0.264
13  affine      1000   V4     1.6  244      0.356   0.279    0.431         0.297            0.347
14  affine      1000   V4     2.1  244      0.329   0.243    0.407         0.313            0.351
15  affine      1000   V4     2.6  244      0.429   0.338    0.508         0.437            0.480
16  single  recorded   V1     1.3  146      0.911   0.840    0.979         0.580            0.590
17  single  recorded   V1     1.6  146      0.826   0.749    0.900         0.689            0.758
18  single  recorded   V1     2.1  146      0.863   0.777    0.948         0.641            0.708
19  single  recorded   V1     2.6  146      0.895   0.807    1.001         0.728            0.750
20  single  recorded   V4     1.3  244      0.776   0.723    0.823         0.206            0.264
21  single  recorded   V4     1.6  244      0.822   0.765    0.878         0.297            0.347
22  single  recorded   V4     2.1  244      0.782   0.708    0.843         0.313            0.351
23  single  recorded   V4     2.6  244      0.800   0.730    0.857         0.437            0.480
24  single      1000   V1     1.3  146      0.918   0.893    0.943         0.580            0.590
25  single      1000   V1     1.6  146      0.956   0.937    0.972         0.689            0.758
26  single      1000   V1     2.1  146      0.956   0.937    0.973         0.641            0.708
27  single      1000   V1     2.6  146      0.960   0.944    0.974         0.728            0.750
28  single      1000   V4     1.3  244      0.908   0.892    0.924         0.206            0.264
29  single      1000   V4     1.6  244      0.918   0.899    0.935         0.297            0.347
30  single      1000   V4     2.1  244      0.907   0.878    0.928         0.313            0.351
31  single      1000   V4     2.6  244      0.910   0.884    0.931         0.437            0.480

affine, trials recorded: V4 simulated slope below V1 at every spacing: True
   measured_all     V1: simulated at or below measured at 4 of 4 spacings
   measured_all     V4: simulated at or below measured at 3 of 4 spacings
   measured_fitted  V1: simulated at or below measured at 4 of 4 spacings
   measured_fitted  V4: simulated at or below measured at 4 of 4 spacings
affine, trials 1000: V4 simulated slope below V1 at every spacing: True
   measured_all     V1: simulated at or below measured at 4 of 4 spacings
   measured_all     V4: simulated at or below measured at 1 of 4 spacings
   measured_fitted  V1: simulated at or below measured at 4 of 4 spacings
   measured_fitted  V4: simulated at or below measured at 3 of 4 spacings

Result: reproduced. Under reading (a) of both open details (recorded trial counts, Figure 2C slopes over all neurons) the simulated V4 slope is below the V1 slope at every spacing (0.243 to 0.336 against 0.404 to 0.567), and the simulated slope is at or below the measured one at 4 of 4 spacings in V1 and 3 of 4 in V4 (V4 at 1.3 degrees: 0.243 against 0.206). The criterion is also met with recorded trial counts against the fitted neurons' own slopes (4 of 4 in each area) and with 1000 trials against the fitted neurons' slopes (V4 3 of 4); with 1000 trials against all neurons V4 is at or below the measured slope at only 1 of 4 spacings. Reading (a, a) is near its limit: over 20 single random splits (below) it holds on 11, and on the stored-order split with another simulation draw V4 is at or below at 2 of 4. Against the fitted neurons' own slopes with recorded trial counts the criterion holds on all 20 single random splits and on the selection by reliability averaged over 20 random splits (V4 4 of 4; below), where reading (a, a) gives V4 at or below at 1 of 4 spacings (2 of 4 with another draw). The outcome was marked as resting on the even/odd selection because reading (a, a) fails on the averaged selection; under the reading against the fitted neurons' slopes it holds on every selection tested.

figs5-additive-vs-multiplicative¶

Fitting either a multiplicative or an additive change of target tuning alone, neurons facilitated by distractors are better described by the additive model and suppressed neurons by the multiplicative model, in V1 and V4; each single form reduces discriminability, but less than in the measured responses.

Single-form fits on the same cases (the tuning model's neuron selection); log-likelihood ratio, multiplicative over additive, against the case's modulation index. Panels C and D: the simulation above with the additive fit for facilitated cases and the multiplicative fit for suppressed ones (rows model == single). The all-driven-neurons variant of the selection is shown below.

In [22]:
for st in (True, False):
    f = FIT[st].copy()
    f["mi"] = fitted["mi"].values
    f["llr"] = f.ll_mult - f.ll_add
    for area in AREAS:
        x = f[f.area == area]
        fac, sup = x[x.mi > 1], x[x.mi < 1]
        print(f"fits on {'single trials' if st else 'means'}: {area} facilitated cases favouring additive (LLR < 0): "
              f"{(fac.llr < 0).sum()} of {len(fac)} ({100 * (fac.llr < 0).mean():.1f}%); suppressed favouring "
              f"multiplicative (LLR > 0): {(sup.llr > 0).sum()} of {len(sup)} ({100 * (sup.llr > 0).mean():.1f}%)")


def single_form_all(p):
    rows = []
    rT_all = cw.tuning(p, "alone")
    for i in range(p["counts"].shape[0]):
        mi = {s: cw.modulation(p, s)[i] for s in SP}
        for s in SP:
            rc = [r[i] for r in cw.responses(p, "crowd", s)]
            _, llm = cw.fit_single(rT_all[i], rc, "mult")
            _, lla = cw.fit_single(rT_all[i], rc, "add")
            rows.append(dict(area=p["area"], mi=mi[s], llr=llm - lla))
    return rows


allf = pd.DataFrame([r for rr in Parallel(n_jobs=4)(delayed(single_form_all)(p) for p in S) for r in rr])
for area in AREAS:
    x = allf[(allf.area == area) & np.isfinite(allf.mi)]
    fac, sup = x[x.mi > 1], x[x.mi < 1]
    print(f"all neurons: {area} facilitated favouring additive {100 * (fac.llr < 0).mean():.1f}% of {len(fac)}; "
          f"suppressed favouring multiplicative {100 * (sup.llr > 0).mean():.1f}% of {len(sup)}")
print()
for mode in ("recorded", "1000"):
    d = sim[(sim.model == "single") & (sim.trials == mode)]
    for area in AREAS:
        dd = d[d.area == area]
        print(f"single-form simulation, trials {mode}, {area}: slopes {np.round(dd.sim_slope.values, 3)}; all below 1: "
              f"{bool((dd.sim_slope < 1).all())} (point slopes), {bool((dd.ci_high < 1).all())} (upper CI); above measured (all neurons) at {int((dd.sim_slope > dd.measured_all).sum())} of 4, "
              f"above measured (fitted neurons) at {int((dd.sim_slope > dd.measured_fitted).sum())} of 4")
fits on single trials: V1 facilitated cases favouring additive (LLR < 0): 167 of 186 (89.8%); suppressed favouring multiplicative (LLR > 0): 333 of 398 (83.7%)
fits on single trials: V4 facilitated cases favouring additive (LLR < 0): 526 of 542 (97.0%); suppressed favouring multiplicative (LLR > 0): 396 of 430 (92.1%)
fits on means: V1 facilitated cases favouring additive (LLR < 0): 168 of 186 (90.3%); suppressed favouring multiplicative (LLR > 0): 334 of 398 (83.9%)
fits on means: V4 facilitated cases favouring additive (LLR < 0): 527 of 542 (97.2%); suppressed favouring multiplicative (LLR > 0): 395 of 430 (91.9%)
all neurons: V1 facilitated favouring additive 86.1% of 524; suppressed favouring multiplicative 81.0% of 1060
all neurons: V4 facilitated favouring additive 92.2% of 1503; suppressed favouring multiplicative 88.5% of 1257

single-form simulation, trials recorded, V1: slopes [0.911 0.826 0.863 0.895]; all below 1: True (point slopes), False (upper CI); above measured (all neurons) at 4 of 4, above measured (fitted neurons) at 4 of 4
single-form simulation, trials recorded, V4: slopes [0.776 0.822 0.782 0.8  ]; all below 1: True (point slopes), True (upper CI); above measured (all neurons) at 4 of 4, above measured (fitted neurons) at 4 of 4
single-form simulation, trials 1000, V1: slopes [0.918 0.956 0.956 0.96 ]; all below 1: True (point slopes), True (upper CI); above measured (all neurons) at 4 of 4, above measured (fitted neurons) at 4 of 4
single-form simulation, trials 1000, V4: slopes [0.908 0.918 0.907 0.91 ]; all below 1: True (point slopes), True (upper CI); above measured (all neurons) at 4 of 4, above measured (fitted neurons) at 4 of 4

Result: reproduced. Among the tuning model's cases, 89.8% of facilitated V1 cases and 97.0% of facilitated V4 cases favour the additive model, and 83.7% and 92.1% of suppressed cases favour the multiplicative one; over all neurons 86.1%, 92.2%, 81.0% and 88.5%. The single-form simulation (additive for facilitation, multiplicative for suppression) gives slopes below 1 at every spacing (point slopes 0.776 to 0.911 with recorded trial counts; judged by the upper CI instead, V1 at 2.6 degrees reaches 1.001), above the measured Figure 2 slopes at 4 of 4 spacings in each area. On the random-split selection (below) the shares are 93.1%, 98.0%, 84.9% and 93.2% and the single-form slopes 0.807 to 0.887, above the measured ones at 4 of 4 spacings in each area.

Tuning-model claims on the random-split selection¶

The fig5bc, fit-quality, fig5-terms-covary, fig5-negative-multiplicative, fig5de and figs5 tests repeated on the neurons selected by REL_R (reliability averaged over 20 random half splits, single-trial likelihood, means over cases), since the V4 stored order is not the recording order.

In [23]:
rng = np.random.default_rng(14)
fr = FIT_R.copy()
fr["q"] = (fr.ll_model - fr.ll_null) / (fr.ll_oracle - fr.ll_null)
fr["mi"] = [cw.modulation(popkey[(r.area, r.session, r.orange)], r.spacing)[r.neuron] for _, r in fr.iterrows()]
fr["llr"] = fr.ll_mult - fr.ll_add
okq = (fr.ll_oracle - fr.ll_null) > 1e-9
for area in AREAS:
    x = fr[fr.area == area]
    xq = fr[okq & (fr.area == area)]
    fac, sup = x[x.mi > 1], x[x.mi < 1]
    print(f"{area}: {len(x) // 4} neurons; m {x.m.mean():.3f} +/- {x.m.std(ddof=1) / np.sqrt(len(x)):.3f}, "
          f"a {x.a.mean():.3f} +/- {x.a.std(ddof=1) / np.sqrt(len(x)):.3f}; m < 1 p = {stats.ttest_1samp(x.m, 1, alternative='less').pvalue:.2g}")
    print(f"   fit quality mean {xq.q.mean():.3f}, median {xq.q.median():.3f}, pooled "
          f"{(xq.ll_model - xq.ll_null).sum() / (xq.ll_oracle - xq.ll_null).sum():.3f}")
    print(f"   m, a Pearson r = {stats.pearsonr(x.m, x.a)[0]:.3f} (p = {stats.pearsonr(x.m, x.a)[1]:.2g}); "
          f"m < 0 in {100 * (x.m < 0).mean():.1f}% of {len(x)} cases")
    print(f"   facilitated favouring additive {100 * (fac.llr < 0).mean():.1f}% of {len(fac)}; suppressed favouring "
          f"multiplicative {100 * (sup.llr > 0).mean():.1f}% of {len(sup)}")
a1, a4 = fr[fr.area == "V1"], fr[fr.area == "V4"]
print(f"V4 - V1: m {a4.m.mean() - a1.m.mean():+.3f} (p = {stats.ttest_ind(a4.m, a1.m).pvalue:.2g}), "
      f"a {a4.a.mean() - a1.a.mean():+.3f} (p = {stats.ttest_ind(a4.a, a1.a).pvalue:.2g})")
print("Expected: V1 m 0.59 +/- 0.03, a 0.39 +/- 0.16; V4 m 0.36 +/- 0.01, a 0.90 +/- 0.02; 146 and 198 neurons; "
      "fit quality 0.63 +/- 0.063 and 0.73 +/- 0.073")
print("   within:", {"V1 m": abs(a1.m.mean() - 0.59) <= 0.03, "V1 a": abs(a1.a.mean() - 0.39) <= 0.16,
                     "V4 m": abs(a4.m.mean() - 0.36) <= 0.01, "V4 a": abs(a4.a.mean() - 0.90) <= 0.02})
tab = [[int((x.m < 0).sum()), int((x.m >= 0).sum())] for x in (a1, a4)]
print(f"Fisher exact test, m < 0 in V4 against V1: p = {stats.fisher_exact(tab)[1]:.2g}")
rows = []
for rule in ("affine", "single"):
    for area in AREAS:
        for s in SP:
            x = fr[(fr.area == area) & (fr.spacing == s)]
            ac = simulate_aucs(x, "recorded", rng, rule)
            sl, lo, hi = cw.slope_ci(ac[:, 0], ac[:, 1], rng)
            m2 = f2[(f2.area == area) & (f2.spacing == SPL[s])].iloc[0].slope
            rows.append(dict(model=rule, area=area, spacing=SPL[s], n=len(x), sim_slope=sl, ci_low=lo, ci_high=hi,
                             measured_all=m2))
simr = pd.DataFrame(rows)
print(simr.round(3).to_string())
d = simr[simr.model == "affine"]
print("affine, recorded trials: V4 simulated slope below V1 at every spacing:",
      bool(np.all(d[d.area == "V4"].sim_slope.values < d[d.area == "V1"].sim_slope.values)),
      "; at or below measured (all neurons):", {a: int((d[d.area == a].sim_slope <= d[d.area == a].measured_all).sum()) for a in AREAS})
d = simr[simr.model == "single"]
print("single form, recorded trials: point slopes below 1:", {a: bool((d[d.area == a].sim_slope < 1).all()) for a in AREAS},
      "; above measured:", {a: int((d[d.area == a].sim_slope > d[d.area == a].measured_all).sum()) for a in AREAS})
# The other readings of fig5de on this selection: 1000 trials per stimulus, and the measured slopes
# of the selected neurons themselves.
rng = np.random.default_rng(18)
for mode in ("recorded", "1000"):
    sim_sl, meas_f, meas_a = {}, {}, {}
    for area in AREAS:
        for s in SP:
            x = fr[(fr.area == area) & (fr.spacing == s)]
            ac = simulate_aucs(x, mode, rng)
            sim_sl[(area, s)] = cw.ols_slope(ac[:, 0], ac[:, 1])
            pp = [popkey[(r.area, r.session, r.orange)] for r in x.itertuples()]
            meas_f[(area, s)] = cw.ols_slope([cw.neuron_aucs(p, "alone")[r.neuron] for p, r in zip(pp, x.itertuples())],
                                             [cw.neuron_aucs(p, "crowd", s)[r.neuron] for p, r in zip(pp, x.itertuples())])
            meas_a[(area, s)] = f2[(f2.area == area) & (f2.spacing == SPL[s])].iloc[0].slope
    below = all(sim_sl[("V4", s)] < sim_sl[("V1", s)] for s in SP)
    for meas, ref in (("all neurons", meas_a), ("selected neurons", meas_f)):
        n = {a: int(sum(sim_sl[(a, s)] <= ref[(a, s)] for s in SP)) for a in AREAS}
        print(f"affine, trials {mode}, measured slopes of {meas}: V4 below V1 at every spacing {below}; simulated at or "
              f"below measured at {n} of 4 spacings; criterion met: {below and min(n.values()) >= 3}")
V1: 109 neurons; m 0.403 +/- 0.023, a 0.588 +/- 0.026; m < 1 p = 3.8e-93
   fit quality mean 0.489, median 0.494, pooled 0.663
   m, a Pearson r = -0.913 (p = 3.4e-171); m < 0 in 20.2% of 436 cases
   facilitated favouring additive 93.1% of 131; suppressed favouring multiplicative 84.9% of 305
V4: 160 neurons; m 0.178 +/- 0.016, a 0.894 +/- 0.027; m < 1 p = 7.4e-224
   fit quality mean 0.440, median 0.410, pooled 0.651
   m, a Pearson r = -0.459 (p = 1.1e-34); m < 0 in 33.6% of 640 cases
   facilitated favouring additive 98.0% of 357; suppressed favouring multiplicative 93.2% of 279
V4 - V1: m -0.225 (p = 4.1e-16), a +0.307 (p = 1.9e-14)
Expected: V1 m 0.59 +/- 0.03, a 0.39 +/- 0.16; V4 m 0.36 +/- 0.01, a 0.90 +/- 0.02; 146 and 198 neurons; fit quality 0.63 +/- 0.063 and 0.73 +/- 0.073
   within: {'V1 m': np.False_, 'V1 a': np.False_, 'V4 m': np.False_, 'V4 a': np.True_}
Fisher exact test, m < 0 in V4 against V1: p = 1.3e-06
     model area spacing    n  sim_slope  ci_low  ci_high  measured_all
0   affine   V1     1.3  109      0.417   0.293    0.540         0.580
1   affine   V1     1.6  109      0.604   0.474    0.703         0.689
2   affine   V1     2.1  109      0.512   0.396    0.619         0.641
3   affine   V1     2.6  109      0.470   0.349    0.594         0.728
4   affine   V4     1.3  160      0.246   0.165    0.328         0.206
5   affine   V4     1.6  160      0.310   0.217    0.406         0.297
6   affine   V4     2.1  160      0.328   0.238    0.413         0.313
7   affine   V4     2.6  160      0.392   0.288    0.490         0.437
8   single   V1     1.3  109      0.807   0.710    0.901         0.580
9   single   V1     1.6  109      0.814   0.728    0.886         0.689
10  single   V1     2.1  109      0.861   0.766    0.960         0.641
11  single   V1     2.6  109      0.833   0.748    0.911         0.728
12  single   V4     1.3  160      0.887   0.829    0.945         0.206
13  single   V4     1.6  160      0.843   0.790    0.893         0.297
14  single   V4     2.1  160      0.808   0.743    0.873         0.313
15  single   V4     2.6  160      0.825   0.768    0.879         0.437
affine, recorded trials: V4 simulated slope below V1 at every spacing: True ; at or below measured (all neurons): {'V1': 4, 'V4': 1}
single form, recorded trials: point slopes below 1: {'V1': True, 'V4': True} ; above measured: {'V1': 4, 'V4': 4}
affine, trials recorded, measured slopes of all neurons: V4 below V1 at every spacing True; simulated at or below measured at {'V1': 4, 'V4': 2} of 4 spacings; criterion met: False
affine, trials recorded, measured slopes of selected neurons: V4 below V1 at every spacing True; simulated at or below measured at {'V1': 4, 'V4': 4} of 4 spacings; criterion met: True
affine, trials 1000, measured slopes of all neurons: V4 below V1 at every spacing True; simulated at or below measured at {'V1': 4, 'V4': 0} of 4 spacings; criterion met: False
affine, trials 1000, measured slopes of selected neurons: V4 below V1 at every spacing True; simulated at or below measured at {'V1': 4, 'V4': 3} of 4 spacings; criterion met: True
In [24]:
# fig5-terms-covary and fig5de over 20 single random half splits. The even/odd split in stored order
# is one half split; this shows whether its V4 r and fig5de comparison are typical of single random
# splits. Every neuron is fitted once (single-trial likelihood), and each split selects the neurons
# whose reliability on that split is above 0.5.
def fit_all(p):
    rT_all = cw.tuning(p, "alone")
    rows = []
    for s in SP:
        rc_all = cw.responses(p, "crowd", s)
        for i in range(p["counts"].shape[0]):
            m, a, _ = cw.fit_affine(rT_all[i], [r[i] for r in rc_all], True)
            rows.append(dict(area=p["area"], session=p["session"], orange=p["orange"], neuron=i, spacing=s, m=m, a=a))
    return rows


t0 = time.time()
ALLFIT = pd.DataFrame([r for rr in Parallel(n_jobs=4)(delayed(fit_all)(p) for p in S) for r in rr])
ALLFIT = ALLFIT.sort_values(["area", "session", "orange", "neuron", "spacing"], kind="stable").reset_index(drop=True)
chk = FIT[True].merge(ALLFIT, on=["area", "session", "orange", "neuron", "spacing"], suffixes=("", "_all"))
print(f"all {len(ALLFIT)} neuron and spacing cases fitted in {time.time() - t0:.0f} s; largest difference from the "
      f"even/odd fits: m {np.abs(chk.m - chk.m_all).max():.2g}, a {np.abs(chk.a - chk.a_all).max():.2g} ({len(chk)} cases)")
key_order = ALLFIT.drop_duplicates(["area", "session", "orange"])[["area", "session", "orange"]].itertuples(index=False)
pops_sorted = [popkey[tuple(k)] for k in key_order]
AUC_A = {id(p): cw.neuron_aucs(p, "alone") for p in S}
AUC_C = {(id(p), s): cw.neuron_aucs(p, "crowd", s) for p in S for s in SP}


def split_tests(selected, rng):
    """Pearson r of m and a per area, and the fig5de comparison under the four readings."""
    x = ALLFIT[selected]
    out = {}
    for area in AREAS:
        xa = x[x.area == area]
        out[f"{area}_neurons"] = len(xa) // 4
        out[f"{area}_r"] = stats.pearsonr(xa.m, xa.a)[0]
    sl = {}
    for mode in ("recorded", "1000"):
        for area in AREAS:
            for s in SP:
                xs = x[(x.area == area) & (x.spacing == s)]
                ac = simulate_aucs(xs, mode, rng)
                sl[(mode, area, s)] = cw.ols_slope(ac[:, 0], ac[:, 1])
    meas_f = {}
    for area in AREAS:
        for s in SP:
            xs = x[(x.area == area) & (x.spacing == s)]
            pp = [popkey[(r.area, r.session, r.orange)] for r in xs.itertuples()]
            meas_f[(area, s)] = cw.ols_slope([AUC_A[id(p)][r.neuron] for p, r in zip(pp, xs.itertuples())],
                                             [AUC_C[(id(p), s)][r.neuron] for p, r in zip(pp, xs.itertuples())])
    for mode in ("recorded", "1000"):
        below = all(sl[(mode, "V4", s)] < sl[(mode, "V1", s)] for s in SP)
        out[f"{mode}_V4_below_V1"] = below
        for meas in ("all", "fitted"):
            for area in AREAS:
                ref = {s: (f2[(f2.area == area) & (f2.spacing == SPL[s])].iloc[0].slope if meas == "all"
                           else meas_f[(area, s)]) for s in SP}
                out[f"{mode}_{meas}_{area}"] = sum(sl[(mode, area, s)] <= ref[s] for s in SP)
            out[f"{mode}_{meas}_pass"] = below and out[f"{mode}_{meas}_V1"] >= 3 and out[f"{mode}_{meas}_V4"] >= 3
    return out


t0 = time.time()
rng_split, rng_sim = np.random.default_rng(16), np.random.default_rng(17)
rows = []
for k in range(21):
    if k == 0:   # the even/odd split in stored order, the main selection
        rel = [cw.even_odd_reliability(p) for p in pops_sorted]
    else:
        rel = [cw.random_split_reliability(p, rng_split, 1) for p in pops_sorted]
    selected = np.concatenate([np.repeat(r > 0.5, len(SP)) for r in rel])
    rows.append(dict(split="even/odd" if k == 0 else f"random {k}", **split_tests(selected, rng_sim)))
SPLITS = pd.DataFrame(rows)
print(f"21 selections in {time.time() - t0:.0f} s")
print(SPLITS.round(3).to_string())
rs = SPLITS.iloc[1:]
for area in AREAS:
    print(f"{area} r over 20 random splits: median {rs[f'{area}_r'].median():.3f}, range {rs[f'{area}_r'].min():.3f} to "
          f"{rs[f'{area}_r'].max():.3f}; |r| >= 0.5 in {int((rs[f'{area}_r'] <= -0.5).sum())} of 20; even/odd "
          f"{SPLITS[f'{area}_r'].iloc[0]:.3f}")
print("fig5-terms-covary criterion (r <= -0.5 in both areas) met in", int(((rs.V1_r <= -0.5) & (rs.V4_r <= -0.5)).sum()), "of 20")
for c in ("recorded_all", "recorded_fitted", "1000_all", "1000_fitted"):
    print(f"fig5de, reading {c}: V4 at or below measured at", rs[f"{c}_V4"].value_counts().sort_index().to_dict(),
          f"(spacings: splits); criterion met in {int(rs[f'{c}_pass'].sum())} of 20")
print("fig5de criterion met under at least one reading in", int(rs[[f"{c}_pass" for c in ("recorded_all", "recorded_fitted", "1000_all", "1000_fitted")]].any(axis=1).sum()), "of 20")
all 4348 neuron and spacing cases fitted in 110 s; largest difference from the even/odd fits: m 0, a 0 (1560 cases)
21 selections in 296 s
        split  V1_neurons   V1_r  V4_neurons   V4_r  recorded_V4_below_V1  recorded_all_V1  recorded_all_V4  recorded_all_pass  recorded_fitted_V1  recorded_fitted_V4  recorded_fitted_pass  1000_V4_below_V1  1000_all_V1  1000_all_V4  1000_all_pass  1000_fitted_V1  1000_fitted_V4  1000_fitted_pass
0    even/odd         146 -0.892         244 -0.682                  True                4                2              False                   4                   4                  True              True            4            1          False               4               3              True
1    random 1         147 -0.886         250 -0.691                  True                4                3               True                   4                   4                  True              True            4            0          False               4               3              True
2    random 2         139 -0.966         253 -0.684                  True                4                3               True                   4                   4                  True              True            4            1          False               4               3              True
3    random 3         138 -0.875         235 -0.707                  True                4                2              False                   4                   4                  True              True            4            0          False               4               4              True
4    random 4         142 -0.869         257 -0.893                  True                4                4               True                   4                   4                  True              True            4            2          False               4               4              True
5    random 5         139 -0.872         243 -0.671                  True                4                3               True                   4                   4                  True              True            4            0          False               4               3              True
6    random 6         150 -0.938         240 -0.639                  True                4                3               True                   4                   4                  True              True            4            1          False               4               3              True
7    random 7         145 -0.944         233 -0.664                  True                4                3               True                   4                   4                  True              True            4            1          False               4               4              True
8    random 8         147 -0.959         244 -0.680                  True                4                2              False                   4                   4                  True              True            4            1          False               4               4              True
9    random 9         145 -0.890         243 -0.693                  True                4                3               True                   4                   3                  True              True            4            0          False               4               3              True
10  random 10         162 -0.856         216 -0.671                  True                4                2              False                   4                   4                  True              True            4            0          False               4               3              True
11  random 11         137 -0.881         232 -0.874                  True                4                2              False                   4                   3                  True              True            4            1          False               4               3              True
12  random 12         149 -0.888         271 -0.690                  True                4                3               True                   4                   4                  True              True            4            1          False               4               2             False
13  random 13         142 -0.854         227 -0.698                  True                4                2              False                   4                   4                  True              True            4            0          False               4               3              True
14  random 14         141 -0.943         240 -0.659                  True                4                3               True                   4                   4                  True              True            4            0          False               4               4              True
15  random 15         149 -0.881         232 -0.673                  True                4                2              False                   4                   4                  True              True            4            0          False               4               3              True
16  random 16         149 -0.869         245 -0.737                  True                4                3               True                   4                   4                  True              True            4            1          False               4               4              True
17  random 17         144 -0.886         225 -0.667                  True                4                2              False                   4                   3                  True              True            4            0          False               4               3              True
18  random 18         139 -0.886         255 -0.661                  True                4                2              False                   4                   3                  True              True            4            0          False               4               4              True
19  random 19         144 -0.903         236 -0.822                  True                4                3               True                   4                   4                  True              True            4            1          False               4               3              True
20  random 20         158 -0.891         244 -0.681                  True                4                2              False                   4                   4                  True              True            4            1          False               4               4              True
V1 r over 20 random splits: median -0.886, range -0.966 to -0.854; |r| >= 0.5 in 20 of 20; even/odd -0.892
V4 r over 20 random splits: median -0.683, range -0.893 to -0.639; |r| >= 0.5 in 20 of 20; even/odd -0.682
fig5-terms-covary criterion (r <= -0.5 in both areas) met in 20 of 20
fig5de, reading recorded_all: V4 at or below measured at {2: 9, 3: 10, 4: 1} (spacings: splits); criterion met in 11 of 20
fig5de, reading recorded_fitted: V4 at or below measured at {3: 4, 4: 16} (spacings: splits); criterion met in 20 of 20
fig5de, reading 1000_all: V4 at or below measured at {0: 10, 1: 9, 2: 1} (spacings: splits); criterion met in 0 of 20
fig5de, reading 1000_fitted: V4 at or below measured at {2: 1, 3: 11, 4: 8} (spacings: splits); criterion met in 19 of 20
fig5de criterion met under at least one reading in 20 of 20

The first row is the even/odd split in stored order, the main selection; its fits are the same as the main fits (largest difference 0). Single random half splits keep 137 to 162 V1 and 216 to 271 V4 neurons. Over the 20 of them V4 r is -0.893 to -0.639 and V1 r -0.966 to -0.854, so fig5-terms-covary holds on every one; the stored-order V4 r (-0.682) is at their median (-0.683). For fig5de, with recorded trial counts, the V4 simulated slope is at or below the measured slope of the selected neurons at 3 or 4 of 4 spacings on every split (criterion met on 20 of 20), and at or below the Figure 2C slope over all neurons at 2 of 4 on 9 splits, 3 of 4 on 10 and 4 of 4 on 1 (met on 11 of 20). With 1000 trials the criterion is met on 19 of 20 against the selected neurons and on none against all neurons. The simulation is redrawn here, so the stored-order row can differ from the fig5de cell (V4 2 of 4 against all neurons here, 3 of 4 there).

Tuning correlations (Figure 6C to 6E)¶

fig6c-tuning-correlation-near: Tuning for targets alone correlates well with tuning for targets with nearby distractors in V1 (0.38 +/- 0.03 for cells above a reliability criterion of 0.5), and significantly less in V4 (0.22 +/- 0.03; one-sided t test, p < 0.001).

fig6d-tuning-correlation-spacing: Target tuning with near and with far distractors correlates less in V4 than V1 (0.17 +/- 0.02 against 0.36 +/- 0.02 at criterion 0.5; one-sided t test, p < 0.001).

fig6e-tuning-correlation-configuration: In 4 further sessions, target tuning with two distractor configurations whose orientations differ by 20 degrees differs substantially in V4 (correlation 0.24 +/- 0.06) and is nearly unaffected in V1 (0.65 +/- 0.06; p < 0.001, one-sided t test).

Reliability as for the tuning model (even and odd presentations in stored order); Pearson correlation of mean count per target orientation between two conditions; mean +/- SEM over neurons; V1 greater than V4 by a one-sided two-sample t test (Student, Welch shown too).

In [25]:
def tuning_pooled(p, seps):
    """Mean count per orientation over the epochs of several spacings."""
    return np.stack([np.concatenate([cw.responses(p, "crowd", s)[o] for s in seps], 1).mean(1)
                     for o in range(len(p["oris"]))], 1)


TC = {}
for area in AREAS:
    ta = np.concatenate([cw.tuning(p, "alone") for p in pops(area)])
    near_a = np.concatenate([cw.tuning(p, "crowd", 1.32) for p in pops(area)])
    near_b = np.concatenate([tuning_pooled(p, SP[:2]) for p in pops(area)])
    far_a = np.concatenate([cw.tuning(p, "crowd", 2.56) for p in pops(area)])
    far_b = np.concatenate([tuning_pooled(p, SP[2:]) for p in pops(area)])
    TC[(area, "6C (a) alone vs 1.3")] = cw.rowcorr(ta, near_a)
    TC[(area, "6C (b) alone vs 1.3+1.6")] = cw.rowcorr(ta, near_b)
    TC[(area, "6D (a) 1.3 vs 2.6")] = cw.rowcorr(near_a, far_a)
    TC[(area, "6D (b) 1.3+1.6 vs 2.1+2.6")] = cw.rowcorr(near_b, far_b)


def compare(key, crit, rel):
    out = {}
    for area in AREAS:
        x = TC[(area, key)][(rel[area] > crit)]
        out[area] = x[np.isfinite(x)]
    t = ttest_1s_greater(out["V1"], out["V4"])
    tw = ttest_1s_greater(out["V1"], out["V4"], False)
    return out, t.pvalue, tw.pvalue


rows = []
for key in ["6C (a) alone vs 1.3", "6C (b) alone vs 1.3+1.6", "6D (a) 1.3 vs 2.6", "6D (b) 1.3+1.6 vs 2.1+2.6"]:
    for crit in (0.5, 0.7, 0.9):
        out, p_, pw = compare(key, crit, REL)
        rows.append(dict(comparison=key, criterion=crit, V1_n=len(out["V1"]), V1_mean=out["V1"].mean(),
                         V1_sem=out["V1"].std(ddof=1) / np.sqrt(len(out["V1"])), V4_n=len(out["V4"]),
                         V4_mean=out["V4"].mean(), V4_sem=out["V4"].std(ddof=1) / np.sqrt(len(out["V4"])),
                         p_V1_gt_V4=p_, p_welch=pw))
f6 = pd.DataFrame(rows)
print(f6.to_string(float_format=lambda v: f"{v:.4g}"))
print("Correlations undefined (flat tuning) at criterion 0.5:",
      {k: int((~np.isfinite(v[REL[k[0]] > 0.5])).sum()) for k, v in TC.items()})
print("Expected 6C: V1 0.38 +/- 0.03, V4 0.22 +/- 0.03; 6D: V1 0.36 +/- 0.02, V4 0.17 +/- 0.02; p < 0.001")
for _, r in f6[f6.criterion == 0.5].iterrows():
    e1, e4, tol = (0.38, 0.22, 0.03) if r.comparison.startswith("6C") else (0.36, 0.17, 0.02)
    print(f"{r.comparison:28s} V1 {r.V1_mean:.3f} within {abs(r.V1_mean - e1) <= tol}; V4 {r.V4_mean:.3f} within "
          f"{abs(r.V4_mean - e4) <= tol}; p {r.p_V1_gt_V4:.2g}")
for an in ("AL", "CA"):
    for key in ["6C (a) alone vs 1.3", "6D (a) 1.3 vs 2.6"]:
        v = {area: np.nanmean(TC[(area, key)][(REL[area] > 0.5) & (animal[area] == an)]) for area in AREAS}
        print(f"{an} {key}: V1 {v['V1']:.3f}, V4 {v['V4']:.3f}")
                   comparison  criterion  V1_n  V1_mean  V1_sem  V4_n  V4_mean  V4_sem  p_V1_gt_V4   p_welch
0         6C (a) alone vs 1.3        0.5   146   0.3891  0.0424   244   0.1612 0.03903   8.874e-05 4.665e-05
1         6C (a) alone vs 1.3        0.7    89   0.4365 0.05045   163   0.1396 0.04883   5.904e-05 1.714e-05
2         6C (a) alone vs 1.3        0.9    31   0.5524 0.08649    74   0.2668 0.06826    0.009313  0.005822
3     6C (b) alone vs 1.3+1.6        0.5   146   0.4605 0.04318   244   0.2382 0.03863   0.0001231 7.406e-05
4     6C (b) alone vs 1.3+1.6        0.7    89   0.5023  0.0542   163   0.2431 0.04579   0.0002636 0.0001652
5     6C (b) alone vs 1.3+1.6        0.9    31   0.6014  0.0876    74   0.3887 0.06264     0.03042   0.02637
6           6D (a) 1.3 vs 2.6        0.5   146    0.432 0.04515   244   0.1351 0.03956   1.172e-06 6.029e-07
7           6D (a) 1.3 vs 2.6        0.7    89    0.427 0.05963   163   0.1332 0.04926   0.0001448 9.657e-05
8           6D (a) 1.3 vs 2.6        0.9    31   0.5376  0.1016    74   0.2604 0.07246     0.01758   0.01498
9   6D (b) 1.3+1.6 vs 2.1+2.6        0.5   146   0.5152 0.04176   244    0.214 0.03741   1.811e-07 7.265e-08
10  6D (b) 1.3+1.6 vs 2.1+2.6        0.7    89   0.5614 0.05385   163   0.2148 0.04524   1.752e-06 8.673e-07
11  6D (b) 1.3+1.6 vs 2.1+2.6        0.9    31   0.6142 0.09138    74   0.3811 0.06549     0.02472   0.02114
Correlations undefined (flat tuning) at criterion 0.5: {('V1', '6C (a) alone vs 1.3'): 0, ('V1', '6C (b) alone vs 1.3+1.6'): 0, ('V1', '6D (a) 1.3 vs 2.6'): 0, ('V1', '6D (b) 1.3+1.6 vs 2.1+2.6'): 0, ('V4', '6C (a) alone vs 1.3'): 0, ('V4', '6C (b) alone vs 1.3+1.6'): 0, ('V4', '6D (a) 1.3 vs 2.6'): 0, ('V4', '6D (b) 1.3+1.6 vs 2.1+2.6'): 0}
Expected 6C: V1 0.38 +/- 0.03, V4 0.22 +/- 0.03; 6D: V1 0.36 +/- 0.02, V4 0.17 +/- 0.02; p < 0.001
6C (a) alone vs 1.3          V1 0.389 within True; V4 0.161 within False; p 8.9e-05
6C (b) alone vs 1.3+1.6      V1 0.460 within False; V4 0.238 within True; p 0.00012
6D (a) 1.3 vs 2.6            V1 0.432 within False; V4 0.135 within False; p 1.2e-06
6D (b) 1.3+1.6 vs 2.1+2.6    V1 0.515 within False; V4 0.214 within False; p 1.8e-07
AL 6C (a) alone vs 1.3: V1 0.398, V4 0.163
AL 6D (a) 1.3 vs 2.6: V1 0.402, V4 0.149
CA 6C (a) alone vs 1.3: V1 0.375, V4 0.160
CA 6D (a) 1.3 vs 2.6: V1 0.479, V4 0.123

A random half split gives a reliability that does not depend on the stored order. As the V4 order is not the recording order, the comparison is repeated with reliability from 20 random half splits of each orientation's presentations (mean correlation over splits), as a variant (REL_R, computed in the fig5bc section).

In [26]:
# REL_R, the reliability averaged over 20 random half splits, is computed in the fig5bc section.
print("Neurons above 0.5 with random splits: V1", int((REL_R["V1"] > 0.5).sum()), "V4", int((REL_R["V4"] > 0.5).sum()))
for key in ["6C (a) alone vs 1.3", "6D (a) 1.3 vs 2.6"]:
    out, p_, pw = compare(key, 0.5, REL_R)
    print(f"{key}: V1 {out['V1'].mean():.3f} +/- {out['V1'].std(ddof=1) / np.sqrt(len(out['V1'])):.3f} (n {len(out['V1'])}), "
          f"V4 {out['V4'].mean():.3f} +/- {out['V4'].std(ddof=1) / np.sqrt(len(out['V4'])):.3f} (n {len(out['V4'])}), p = {p_:.2g}")
Neurons above 0.5 with random splits: V1 109 V4 160
6C (a) alone vs 1.3: V1 0.413 +/- 0.047 (n 109), V4 0.159 +/- 0.050 (n 160), p = 0.00023
6D (a) 1.3 vs 2.6: V1 0.374 +/- 0.057 (n 109), V4 0.132 +/- 0.045 (n 160), p = 0.00047

Result: fig6c-tuning-correlation-near partially reproduced. At criterion 0.5, reading (a), V1 gives 0.389 +/- 0.042, within 0.38 +/- 0.03, and V4 0.161 +/- 0.039, below 0.22 +/- 0.03; reading (b) gives 0.460 (out) and 0.238 (within). V4 is lower than V1 at p = 8.9e-05 (a) and 1.2e-04 (b), and at criteria 0.7 and 0.9 too (p = 5.9e-05 and 0.009). No reading puts both values within tolerance; the V4 value is lower than the paper's, a larger effect.

Result: fig6d-tuning-correlation-spacing partially reproduced. Near against far tuning correlates less in V4 than V1 (reading a: 0.135 against 0.432, p = 1.2e-06; reading b: 0.214 against 0.515, p = 1.8e-07), but no value is within tolerance of 0.17 +/- 0.02 and 0.36 +/- 0.02. The random-split variant of the reliability gives the same picture (V1 0.374 against V4 0.132).

In [27]:
TE, RELE = {}, {}
for area in AREAS:
    ps = pops(area, O)
    RELE[area] = np.concatenate([cw.even_odd_reliability(p) for p in ps])
    c0 = np.concatenate([cw.tuning(p, "crowd", config=0) for p in ps])
    c1 = np.concatenate([cw.tuning(p, "crowd", config=1) for p in ps])
    TE[area] = cw.rowcorr(c0, c1)
    print(f"{area}: {len(RELE[area])} neurons in the orientation experiment; target-alone presentations per orientation "
          f"{min(r.shape[1] for p in ps for r in cw.responses(p, 'alone'))} to {max(r.shape[1] for p in ps for r in cw.responses(p, 'alone'))}, "
          f"crowded per orientation and configuration {min(r.shape[1] for p in ps for c in (0, 1) for r in cw.responses(p, 'crowd', config=c))} "
          f"to {max(r.shape[1] for p in ps for c in (0, 1) for r in cw.responses(p, 'crowd', config=c))}")
for crit in (0.5, 0.7, 0.9):
    out = {area: TE[area][(RELE[area] > crit) & np.isfinite(TE[area])] for area in AREAS}
    print(f"criterion {crit}: V1 {out['V1'].mean():.3f} +/- {out['V1'].std(ddof=1) / np.sqrt(len(out['V1'])):.3f} (n {len(out['V1'])}), "
          f"V4 {out['V4'].mean():.3f} +/- {out['V4'].std(ddof=1) / np.sqrt(len(out['V4'])):.3f} (n {len(out['V4'])}); "
          f"one-sided p = {ttest_1s_greater(out['V1'], out['V4']).pvalue:.2g} (Welch {ttest_1s_greater(out['V1'], out['V4'], False).pvalue:.2g})")
print("Expected: V4 0.24 +/- 0.06, V1 0.65 +/- 0.06, p < 0.001")
oA = [p for p in O if p["area"] == "V4"]
print("Autocorrelation of the population residual, orientation experiment (median lag 10): V1",
      round(float(np.median([lagcorr(resid_series(p), 10) for p in O if p['area'] == 'V1'])), 3),
      "V4", round(float(np.median([lagcorr(resid_series(p), 10) for p in oA])), 3))
V1: 155 neurons in the orientation experiment; target-alone presentations per orientation 45 to 52, crowded per orientation and configuration 44 to 54
V4: 336 neurons in the orientation experiment; target-alone presentations per orientation 45 to 52, crowded per orientation and configuration 44 to 54
criterion 0.5: V1 0.644 +/- 0.061 (n 50), V4 0.214 +/- 0.047 (n 90); one-sided p = 6.7e-08 (Welch 9.7e-08)
criterion 0.7: V1 0.697 +/- 0.074 (n 30), V4 0.217 +/- 0.074 (n 49); one-sided p = 2.1e-05 (Welch 9.1e-06)
criterion 0.9: V1 0.941 +/- 0.019 (n 8), V4 0.476 +/- 0.112 (n 18); one-sided p = 0.0057 (Welch 0.00033)
Expected: V4 0.24 +/- 0.06, V1 0.65 +/- 0.06, p < 0.001
Autocorrelation of the population residual, orientation experiment (median lag 10): V1 0.092 V4 -0.015

Result: reproduced. In the orientation experiment, at criterion 0.5, the tuning with the two distractor configurations correlates 0.644 +/- 0.061 in V1 (50 neurons) and 0.214 +/- 0.047 in V4 (90 neurons), within 0.65 +/- 0.06 and 0.24 +/- 0.06; V1 exceeds V4 at p = 6.7e-08. The same holds at criteria 0.7 and 0.9 (p = 2.1e-05 and 0.006).

figs6-common-neuron-pool¶

The distinct V4 decoding axes for different displays do not arise from relying on distinct subsets of neurons; most target-responsive neurons remain driven with distractors, and the most informative neuron for targets alone remains informative with distractors.

Driven: mean count above the blank mean plus 1 SD of the blank counts (Figure S6 legend), to targets alone and, for those, to targets with distractors at each spacing. Informativeness: |d'| between the two extreme targets, normalized by the population's summed |d'| in that condition.

In [28]:
rows = []
for p in S:
    bl = p["counts"][:, cw.stim_mask(p, "blank")]
    thr = bl.mean(1) + bl.std(1, ddof=1)
    drv = p["counts"][:, cw.stim_mask(p, "alone")].mean(1) > thr
    r = dict(area=p["area"], session=p["session"], orange=p["orange"], n=len(thr), driven=drv.mean())
    for s in SP:
        dc = p["counts"][:, cw.stim_mask(p, "crowd", s)].mean(1) > thr
        r[f"still_{SPL[s]}"] = dc[drv].mean() if drv.any() else np.nan
    first, second = cw.extreme_order(p)
    dps = {}
    for cond, s in (("alone", None), ("near", 1.32), ("far", 2.56)):
        rr = cw.responses(p, "alone" if s is None else "crowd", s)
        d = np.abs(np.array([cw.dprime(rr[first][i], rr[second][i]) for i in range(len(thr))]))
        d[~np.isfinite(d)] = 0
        dps[cond] = d / d.sum()
    top = int(np.argmax(dps["alone"]))
    r.update(top_alone=dps["alone"][top], top_near=dps["near"][top], top_far=dps["far"][top])
    rows.append(r)
s6 = pd.DataFrame(rows)
print(s6.groupby("area")[["driven"] + [f"still_{SPL[s]}" for s in SP]].agg(["mean", "sem"]).round(3).T.to_string())
print("Populations with no target-driven neuron:", s6.groupby("area")["still_1.3"].apply(lambda x: int(x.isna().sum())).to_dict())
print("Fraction driven by targets over the populations with a target-driven neuron:",
      s6[s6.driven > 0].groupby("area").driven.agg(["count", "mean", "min", "max"]).round(3).to_dict("index"))
for area in AREAS:
    d = s6[s6.area == area]
    for cond in ("near", "far"):
        r_, p_ = stats.pearsonr(d.top_alone, d[f"top_{cond}"])
        print(f"{area} top neuron, alone {d.top_alone.mean():.3f} vs {cond} {d[f'top_{cond}'].mean():.3f}: Pearson r = {r_:.3f}, "
              f"p = {p_:.2g}, n = {len(d)} populations")
area               V1     V4
driven    mean  0.372  0.396
          sem   0.090  0.095
still_1.3 mean  0.944  0.953
          sem   0.017  0.020
still_1.6 mean  0.958  0.929
          sem   0.018  0.015
still_2.1 mean  0.960  0.895
          sem   0.022  0.029
still_2.6 mean  0.948  0.866
          sem   0.023  0.026
Populations with no target-driven neuron: {'V1': 12, 'V4': 12}
Fraction driven by targets over the populations with a target-driven neuron: {'V1': {'count': 10, 'mean': 0.817, 'min': 0.583, 'max': 1.0}, 'V4': {'count': 10, 'mean': 0.871, 'min': 0.714, 'max': 0.955}}
V1 top neuron, alone 0.200 vs near 0.169: Pearson r = 0.855, p = 4e-07, n = 22 populations
V1 top neuron, alone 0.200 vs far 0.178: Pearson r = 0.921, p = 1.2e-09, n = 22 populations
V4 top neuron, alone 0.192 vs near 0.110: Pearson r = 0.672, p = 0.00062, n = 22 populations
V4 top neuron, alone 0.192 vs far 0.151: Pearson r = 0.803, p = 6.8e-06, n = 22 populations

Result: reproduced. The driven fractions cover only the 10 of 22 populations per area (sessions 3 to 7) in which at least one unit's target-alone mean exceeds its blank mean by 1 SD. In the other 12 no unit passes this threshold, although 8% to 86% of V1 units and 23% to 75% of V4 units there have a target-alone mean above their blank mean (data check). In those 10, the mean fraction of target-driven units still driven with distractors is 0.944 to 0.960 in V1 and 0.866 to 0.953 in V4, at least 0.8 at every spacing. The top-unit test covers all 22 populations: the most informative unit for targets alone keeps its share of the population's d' with distractors, across V4 populations r = 0.672 (p = 0.0006) with near and 0.803 (p = 6.8e-06) with far distractors (V1: 0.855 and 0.921). The fraction driven by targets alone is 0.817 (V1) and 0.871 (V4) over the 10 populations, above the range of Figure S6A (0.3 to 0.5); its means over all 22 populations (0.372 and 0.396) fall in that range only because the 12 populations with no driven unit count as 0. The criterion does not test this fraction.

Population decoding¶

One L1 logistic decoder per population, pair of target orientations (six pairs) and condition (targets alone, or with distractors at each spacing), fitted and tested by cross-validation as the STAR Methods describe. Runs: main (10 outer and 10 inner folds), folds5 (5 and 5, the variant), shuffled_all (each neuron's counts shuffled across trials of the same stimulus before decoding, reading (a) of fig3c) and shuffled_train (training trials shuffled, test trials intact, reading (b)). Each population's run has its own seeded generator. Timed on two populations first: about 1 s per decoder for main.

In [29]:
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), "folds5": (5, 5), "shuffled_all": (10, 10), "shuffled_train": (10, 10)}


def decode_population(pi, mode):
    p = S[pi]
    outer, inner = MODES[mode]
    rng = np.random.default_rng([7, pi, list(MODES).index(mode)])
    rows = []
    for a, b in PAIRS:
        for kind, s in CONDS:
            X, y = cw.pair_trials(p, kind, s, a, b)
            diag = []
            if mode == "shuffled_all":
                perf = cw.decode(cw.shuffle_within(X, y, rng), y, rng, outer, inner, diag)
            elif mode == "shuffled_train":
                perf = cw.decode_shuffled_train(X, y, rng, outer, inner)
            else:
                perf = cw.decode(X, y, rng, outer, inner, diag)
            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, Cs=[c for c, _, _ in diag], nonzero=[k for _, k, _ in diag],
                             perf_nonzero=float(np.mean([v for _, _, v in diag])) if diag else np.nan))
    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
folds5: 1320 decoders in 172 s
shuffled_all: 1320 decoders in 700 s
shuffled_train: 1320 decoders in 700 s
decoding total 2322 s; peak memory 0.42 GB
                           count   mean    min    max
mode           area cond                             
folds5         V1   1.32     132  0.575  0.393  0.949
                    1.64     132  0.576  0.362  0.923
                    2.04     132  0.573  0.377  0.923
                    2.56     132  0.580  0.401  0.962
                    alone    132  0.580  0.376  0.961
               V4   1.32     132  0.528  0.395  0.737
                    1.64     132  0.550  0.366  0.835
                    2.04     132  0.548  0.356  0.827
                    2.56     132  0.566  0.375  0.831
                    alone    132  0.631  0.422  0.973
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
shuffled_all   V1   1.32     132  0.570  0.385  0.948
                    1.64     132  0.586  0.425  0.936
                    2.04     132  0.582  0.414  0.900
                    2.56     132  0.576  0.375  0.948
                    alone    132  0.579  0.417  0.950
               V4   1.32     132  0.522  0.350  0.725
                    1.64     132  0.543  0.353  0.803
                    2.04     132  0.543  0.350  0.789
                    2.56     132  0.572  0.375  0.834
                    alone    132  0.626  0.375  0.988
shuffled_train V1   1.32     132  0.570  0.325  0.948
                    1.64     132  0.578  0.342  0.898
                    2.04     132  0.572  0.379  0.895
                    2.56     132  0.578  0.414  0.950
                    alone    132  0.572  0.370  0.938
               V4   1.32     132  0.533  0.398  0.725
                    1.64     132  0.544  0.390  0.758
                    2.04     132  0.549  0.395  0.842
                    2.56     132  0.566  0.370  0.851
                    alone    132  0.629  0.425  0.948
In [30]:
# Decoder diagnostics (main run): the penalty chosen in each outer fold, and how often the chosen
# penalty leaves no nonzero coefficient (the decoder then predicts one class for every test trial).
dm = DEC[DEC["mode"] == "main"]
rows = []
for (area, cond), d in dm.groupby(["area", "cond"]):
    cs = np.concatenate(d.Cs.values)
    nz = np.concatenate(d.nonzero.values)
    r = dict(area=area, cond=cond, folds=len(cs), frac_all_zero=np.mean(nz == 0), median_nonzero=np.median(nz))
    for c in cw.CS:
        r[f"C={c:.2g}"] = np.mean(np.isclose(cs, c))
    rows.append(r)
print(pd.DataFrame(rows).round(3).to_string())
print("Fraction of folds at the smallest C (largest penalty) and at the largest C, all decoders:",
      round(float(np.mean(np.isclose(np.concatenate(dm.Cs.values), cw.CS[0]))), 3),
      round(float(np.mean(np.isclose(np.concatenate(dm.Cs.values), cw.CS[-1]))), 3))
# Variant: in each outer fold whose chosen decoder has no nonzero coefficient, the decoder at the
# smallest larger C that has one (cw.fit_nonzero), on the same folds; its performances form the run
# "main_nonzero", used below for the threshold elevations.
NZ = dm.assign(mode="main_nonzero", perf=dm.perf_nonzero)
print("Mean performance, main run and the variant without all-zero decoders, and the fraction of decoders whose "
      "performance changes:")
print(pd.DataFrame({"main": dm.groupby(["area", "cond"]).perf.mean(), "nonzero": NZ.groupby(["area", "cond"]).perf.mean(),
                    "changed": (NZ.perf != dm.perf).groupby([dm.area, dm.cond]).mean()}).round(3).to_string())
DEC = pd.concat([DEC, NZ], ignore_index=True)
  area   cond  folds  frac_all_zero  median_nonzero  C=0.01  C=0.022  C=0.046  C=0.1  C=0.22  C=0.46    C=1  C=2.2  C=4.6   C=10   C=22   C=46  C=1e+02
0   V1   1.32   1320          0.114             6.0   0.114      0.0    0.008  0.154   0.239   0.158  0.119  0.069  0.055  0.038  0.021  0.018    0.008
1   V1   1.64   1320          0.122             6.0   0.120      0.0    0.009  0.133   0.268   0.180  0.112  0.058  0.045  0.036  0.017  0.014    0.005
2   V1   2.04   1320          0.145             6.0   0.145      0.0    0.011  0.136   0.243   0.156  0.109  0.084  0.048  0.033  0.020  0.006    0.009
3   V1   2.56   1320          0.099             6.0   0.099      0.0    0.021  0.123   0.250   0.162  0.115  0.078  0.067  0.040  0.020  0.015    0.009
4   V1  alone   1320          0.099             6.0   0.098      0.0    0.011  0.150   0.259   0.156  0.102  0.075  0.060  0.042  0.027  0.013    0.008
5   V4   1.32   1320          0.184             7.0   0.184      0.0    0.000  0.133   0.270   0.137  0.080  0.064  0.049  0.033  0.022  0.017    0.011
6   V4   1.64   1320          0.166             8.0   0.166      0.0    0.010  0.171   0.184   0.135  0.098  0.080  0.061  0.039  0.024  0.014    0.017
7   V4   2.04   1320          0.141             6.0   0.139      0.0    0.004  0.216   0.249   0.120  0.096  0.057  0.041  0.032  0.022  0.017    0.008
8   V4   2.56   1320          0.126             7.0   0.125      0.0    0.021  0.229   0.208   0.128  0.091  0.077  0.044  0.038  0.012  0.016    0.011
9   V4  alone   1320          0.048             9.0   0.048      0.0    0.012  0.201   0.265   0.192  0.107  0.052  0.048  0.027  0.015  0.020    0.014
Fraction of folds at the smallest C (largest penalty) and at the largest C, all decoders: 0.124 0.01
Mean performance, main run and the variant without all-zero decoders, and the fraction of decoders whose performance changes:
             main  nonzero  changed
area cond                          
V1   1.32   0.576    0.576    0.311
     1.64   0.582    0.580    0.348
     2.04   0.575    0.576    0.356
     2.56   0.576    0.583    0.295
     alone  0.584    0.591    0.326
V4   1.32   0.521    0.524    0.477
     1.64   0.550    0.549    0.386
     2.04   0.553    0.559    0.371
     2.56   0.570    0.571    0.356
     alone  0.638    0.638    0.144

In 9.9% to 14.5% of the main run's outer folds in V1, and 4.8% (targets alone) to 18.4% (1.3 degrees) in V4, the chosen penalty is the largest of the grid (C = 0.01) and leaves no nonzero coefficient, so the decoder predicts one class for every held-out trial of the fold. The paper's rule (the largest penalty that reaches the maximal cross-validated performance) selects such a decoder whenever no smaller penalty does better on the inner folds; how often it does depends on the grid's lower bound, a choice made here. In the variant, each such decoder is replaced by the one at the smallest larger C that has a nonzero coefficient, on the same folds. Mean performances change by at most 0.007 (V1 targets alone 0.584 to 0.591, V1 at 2.6 degrees 0.576 to 0.583), so the all-zero decoders do not pull the performances to chance on average.

fig2de-population-decoding-example¶

In one animal at the nearest spacing, V4 population decoding performance with distractors tends to be lower than for targets alone when performance is above chance (p < 0.001), while in V1 the loss is not significant (p > 0.05).

The animal with 84 cases (6 pairs x 14 populations) is AL; CA has 48. Both are shown.

In [31]:
for mode in ("main", "folds5"):
    for an in ("AL", "CA"):
        for area in AREAS:
            j = paired_points(mode, area, 1.32, an)
            for restrict in (True, False):
                x = j[j.perf_alone > 0.5] if restrict else j
                d = x.perf_alone - x.perf_crowd
                tt = stats.ttest_rel(x.perf_alone, x.perf_crowd)
                w = stats.wilcoxon(x.perf_alone, x.perf_crowd) if (d != 0).any() else None
                print(f"{mode:6s} {an} {area} {'alone > 0.5' if restrict else 'all cases  '}: n = {len(x):3d} of {len(j)}, "
                      f"alone {x.perf_alone.mean():.3f}, crowded {x.perf_crowd.mean():.3f}, difference {d.mean():+.3f}; "
                      f"paired t p = {tt.pvalue:.2g}, Wilcoxon p = {w.pvalue if w else np.nan:.2g}")
fig, axs = plt.subplots(1, 2, figsize=(8, 3.8))
for ax, area in zip(axs, AREAS):
    j = paired_points("main", area, 1.32, "AL")
    ax.scatter(j.perf_alone, j.perf_crowd, s=10)
    ax.plot([0.3, 1], [0.3, 1], "k:")
    ax.set(xlim=(0.3, 1), ylim=(0.3, 1), xlabel="performance, target alone", ylabel="performance, nearest distractors", title=f"{area}, AL")
plt.tight_layout()
plt.show()
for area in AREAS:
    j = paired_points("main", area, 1.32, "AL")
    print(area, "points outside the axes (below 0.3):", int(((j.perf_alone < 0.3) | (j.perf_crowd < 0.3)).sum()), "of", len(j))
main   AL V1 alone > 0.5: n =  62 of 84, alone 0.592, crowded 0.560, difference +0.032; paired t p = 0.018, Wilcoxon p = 0.025
main   AL V1 all cases  : n =  84 of 84, alone 0.560, crowded 0.552, difference +0.008; paired t p = 0.46, Wilcoxon p = 0.6
main   AL V4 alone > 0.5: n =  74 of 84, alone 0.645, crowded 0.536, difference +0.109; paired t p = 1.5e-15, Wilcoxon p = 2.8e-11
main   AL V4 all cases  : n =  84 of 84, alone 0.624, crowded 0.530, difference +0.094; paired t p = 1.6e-13, Wilcoxon p = 7.2e-11
main   CA V1 alone > 0.5: n =  34 of 48, alone 0.697, crowded 0.654, difference +0.044; paired t p = 0.024, Wilcoxon p = 0.032
main   CA V1 all cases  : n =  48 of 48, alone 0.625, crowded 0.619, difference +0.006; paired t p = 0.73, Wilcoxon p = 0.8
main   CA V4 alone > 0.5: n =  42 of 48, alone 0.691, crowded 0.514, difference +0.177; paired t p = 7.8e-11, Wilcoxon p = 7.9e-10
main   CA V4 all cases  : n =  48 of 48, alone 0.664, crowded 0.507, difference +0.157; paired t p = 3.5e-10, Wilcoxon p = 6.5e-10
folds5 AL V1 alone > 0.5: n =  60 of 84, alone 0.589, crowded 0.557, difference +0.033; paired t p = 0.011, Wilcoxon p = 0.014
folds5 AL V1 all cases  : n =  84 of 84, alone 0.555, crowded 0.548, difference +0.007; paired t p = 0.5, Wilcoxon p = 0.69
folds5 AL V4 alone > 0.5: n =  70 of 84, alone 0.647, crowded 0.545, difference +0.102; paired t p = 3.5e-14, Wilcoxon p = 1.5e-10
folds5 AL V4 all cases  : n =  84 of 84, alone 0.618, crowded 0.537, difference +0.080; paired t p = 6.5e-11, Wilcoxon p = 4.2e-09
folds5 CA V1 alone > 0.5: n =  36 of 48, alone 0.680, crowded 0.646, difference +0.034; paired t p = 0.051, Wilcoxon p = 0.021
folds5 CA V1 all cases  : n =  48 of 48, alone 0.625, crowded 0.623, difference +0.001; paired t p = 0.93, Wilcoxon p = 0.64
folds5 CA V4 alone > 0.5: n =  42 of 48, alone 0.683, crowded 0.511, difference +0.172; paired t p = 1.9e-10, Wilcoxon p = 1.7e-10
folds5 CA V4 all cases  : n =  48 of 48, alone 0.655, crowded 0.512, difference +0.144; paired t p = 2e-08, Wilcoxon p = 3.2e-08
No description has been provided for this image
V1 points outside the axes (below 0.3): 0 of 84
V4 points outside the axes (below 0.3): 0 of 84

Result: reproduced, with V1 taken over all cases. In AL at 1.3 degrees (84 cases), V4 performance with distractors is lower where target-alone performance exceeds 0.5 (74 cases, 0.645 against 0.536, paired t p = 1.5e-15, Wilcoxon p = 2.8e-11). In V1 the difference over all 84 cases is not significant (0.560 against 0.552, p = 0.46 and 0.60), but restricted as V4 is it is (62 cases, p = 0.018 and 0.025), so the V1 part rests on the unrestricted reading. The 5-fold variant and the other animal give the same pattern.

Threshold elevation (Figure 2F)¶

fig2f-v1-threshold-elevation: In V1, distractors elevate the estimated discrimination threshold of the populations by 1.31 +/- 0.10 at the closest spacing and 1.15 +/- 0.08 at the farthest, significant at all but the farthest spacing (permutation test, p < 0.05).

fig2f-v4-threshold-elevation: In V4 the estimated threshold elevations are greater than in V1, 2.52 +/- 0.23 for the closest distractors and 1.89 +/- 0.19 for the farthest, significant at all spacings (permutation test, p < 0.001).

Per animal, area and spacing, k by maximum likelihood over the (target alone, crowded) points of all pairs and populations; points with target-alone performance at or below 0.5 or at 1 dropped. Binomial trial count: (a) the held-out trials of one fold, (b) all trials of the pair; since the held-out count is a tenth of the total for every point, the two scale the likelihood by a constant and give the same k, so they differ only in the bootstrap and permutation draws. The Figure 2F value is the mean of the two animals' estimates; its SEM is the SD of that mean over 1000 bootstrap samples of each animal's points; the permutation test swaps the two labels at random within each point, 1000 times, refits both animals and averages; the table gives the median and the 5th and 95th percentiles of that null. The k grid runs from 0.2 to 20; k_wide repeats the estimate on a grid up to 1000 to show where the bound censors it.

In [32]:
def elevation(mode, area, s, ntrials, rng, n_boot=1000, n_perm=1000):
    ests, boots, perms, used, wide = [], [], [], [], []
    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))
        wide.append(cw.fit_k(pa, pc, n, cw.K_GRID_WIDE))
        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), k_AL_wide=wide[0], k_CA_wide=wide[1], k_wide=np.mean(wide))
    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))
        out["null_median"], out["null_5"], out["null_95"] = np.percentile(null, [50, 5, 95])
    return out


t0 = time.time()
rng = np.random.default_rng(8)
TE_ROWS = [elevation(mode, area, s, nt, rng) for mode in ("main", "folds5") for nt in ("fold", "all")
           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}"))
print(f"Estimates at the upper bound of K_GRID ({cw.K_GRID[-1]:g}):", int((TH[["k_AL", "k_CA"]] >= cw.K_GRID[-1]).sum().sum()),
      f"of {2 * len(TH)}; k_wide is the estimate on K_GRID_WIDE (up to {cw.K_GRID_WIDE[-1]:g})")
threshold fits in 237 s
      mode area spacing ntrials  k_AL  k_CA     k  points_used  k_AL_wide  k_CA_wide  k_wide    sem   p_perm  null_median  null_5  null_95
0     main   V1     1.3    fold 1.888 1.483 1.685  62/84 34/48      1.889       1.48   1.685 0.3511   0.4206        1.634   1.339    1.946
1     main   V1     1.6    fold 1.595 1.405   1.5  62/84 34/48      1.599      1.407   1.503 0.1586   0.1848        1.412    1.25    1.575
2     main   V1     2.1    fold 1.529 1.607 1.568  62/84 34/48      1.533      1.605   1.569 0.1566  0.04795        1.381   1.196    1.565
3     main   V1     2.6    fold 2.062 1.277 1.669  62/84 34/48      2.057      1.273   1.665 0.3137  0.06194         1.49   1.316    1.679
4     main   V4     1.3    fold 3.738 10.87 7.302  74/84 42/48      3.734      10.87   7.301  2.465 0.000999        3.511   2.448    4.665
5     main   V4     1.6    fold 2.176 18.52 10.35  74/84 42/48      2.171      18.47   10.32  2.454 0.000999        4.156   2.537    6.678
6     main   V4     2.1    fold 2.218 7.234 4.726  74/84 42/48      2.214      7.238   4.726  1.959 0.000999        2.665    1.91    3.468
7     main   V4     2.6    fold 1.831 3.383 2.607  74/84 42/48      1.831      3.376   2.604 0.2893 0.000999        1.751   1.384    2.103
8     main   V1     1.3     all 1.888 1.483 1.685  62/84 34/48      1.889       1.48   1.685 0.3309   0.3666        1.624   1.316    1.918
9     main   V1     1.6     all 1.595 1.405   1.5  62/84 34/48      1.599      1.407   1.503  0.153   0.1818        1.408   1.242     1.57
10    main   V1     2.1     all 1.529 1.607 1.568  62/84 34/48      1.533      1.605   1.569 0.1577  0.04695         1.37   1.186    1.565
11    main   V1     2.6     all 2.062 1.277 1.669  62/84 34/48      2.057      1.273   1.665 0.4282  0.05894        1.498   1.305    1.679
12    main   V4     1.3     all 3.738 10.87 7.302  74/84 42/48      3.734      10.87   7.301  2.478 0.000999        3.487   2.436    4.608
13    main   V4     1.6     all 2.176 18.52 10.35  74/84 42/48      2.171      18.47   10.32  2.463 0.000999        4.159   2.442    6.547
14    main   V4     2.1     all 2.218 7.234 4.726  74/84 42/48      2.214      7.238   4.726  1.885 0.000999        2.656   1.914    3.454
15    main   V4     2.6     all 1.831 3.383 2.607  74/84 42/48      1.831      3.376   2.604 0.2849 0.000999        1.768   1.426    2.094
16  folds5   V1     1.3    fold 2.054 1.421 1.738  60/84 36/48      2.057      1.424    1.74 0.3124   0.2897        1.648    1.36    1.904
17  folds5   V1     1.6    fold 1.715 1.316 1.516  60/84 36/48      1.715      1.313   1.514 0.1472   0.1578        1.412   1.249    1.583
18  folds5   V1     2.1    fold 1.783 1.438  1.61  60/84 36/48      1.782      1.435   1.609 0.2316   0.0989        1.457   1.273    1.655
19  folds5   V1     2.6    fold 1.888 1.146 1.517  60/84 36/48      1.889      1.146   1.518 0.2652   0.1279        1.403   1.235    1.571
20  folds5   V4     1.3    fold 3.244 17.09 10.17  70/84 42/48      3.248       17.1   10.17  2.161 0.000999        4.801   2.884    6.841
21  folds5   V4     1.6    fold     2    20    11  70/84 42/48      1.994      41.01    21.5  1.969 0.000999        5.845    3.03    10.67
22  folds5   V4     2.1    fold 2.218 7.488 4.853  70/84 42/48      2.214      7.495   4.854  1.888 0.000999        2.776   1.999    3.588
23  folds5   V4     2.6    fold 1.696 4.376 3.036  70/84 42/48      1.695      4.376   3.035 0.6437 0.000999        1.941   1.473    2.388
24  folds5   V1     1.3     all 2.054 1.421 1.738  60/84 36/48      2.057      1.424    1.74 0.2953   0.2448        1.629   1.351    1.904
25  folds5   V1     1.6     all 1.715 1.316 1.516  60/84 36/48      1.715      1.313   1.514 0.1457   0.1499        1.409   1.249    1.584
26  folds5   V1     2.1     all 1.783 1.438  1.61  60/84 36/48      1.782      1.435   1.609 0.2273   0.1129        1.471   1.291    1.661
27  folds5   V1     2.6     all 1.888 1.146 1.517  60/84 36/48      1.889      1.146   1.518 0.2262   0.1329        1.408   1.234    1.566
28  folds5   V4     1.3     all 3.244 17.09 10.17  70/84 42/48      3.248       17.1   10.17  2.161 0.000999        4.769       3    6.927
29  folds5   V4     1.6     all     2    20    11  70/84 42/48      1.994      41.01    21.5  2.016 0.000999        5.737   2.925    10.69
30  folds5   V4     2.1     all 2.218 7.488 4.853  70/84 42/48      2.214      7.495   4.854  1.884 0.000999        2.806    2.04    3.526
31  folds5   V4     2.6     all 1.696 4.376 3.036  70/84 42/48      1.695      4.376   3.035 0.8225 0.000999        1.957   1.509    2.386
Estimates at the upper bound of K_GRID (20): 2 of 64; k_wide is the estimate on K_GRID_WIDE (up to 1000)
In [33]:
# Calibration of the threshold-elevation estimate: with no crowding (true k = 1), crowded and
# target-alone performances drawn as binomial fractions around each case's recorded target-alone
# performance, with the recorded trial count of the pair; k estimated as above, mean of the two
# animals, 200 simulations per area and spacing.
rng = np.random.default_rng(15)
rows = []
for area in AREAS:
    for s in SP:
        ks = []
        for _ in range(200):
            e = []
            for an in ("AL", "CA"):
                j = paired_points("main", area, s, an)
                n = j.n_crowd.values
                pt = np.clip(j.perf_alone.values, 0.5, 1)
                e.append(cw.fit_k(rng.binomial(n, pt) / n, rng.binomial(n, pt) / n, n))
            ks.append(np.mean(e))
        ks = np.array(ks)
        rows.append(dict(area=area, spacing=SPL[s], k_null_mean=ks.mean(), k_null_median=np.median(ks),
                         k_null_5=np.percentile(ks, 5), k_null_95=np.percentile(ks, 95)))
print(pd.DataFrame(rows).round(3).to_string())
  area spacing  k_null_mean  k_null_median  k_null_5  k_null_95
0   V1     1.3        1.173          1.169     1.082      1.286
1   V1     1.6        1.169          1.169     1.075      1.265
2   V1     2.1        1.181          1.177     1.077      1.293
3   V1     2.6        1.170          1.173     1.068      1.264
4   V4     1.3        1.088          1.089     1.024      1.150
5   V4     1.6        1.093          1.091     1.034      1.158
6   V4     2.1        1.090          1.088     1.027      1.154
7   V4     2.6        1.089          1.088     1.020      1.162

With no crowding the estimate is biased upward: its mean is 1.17 to 1.18 in V1 (5th to 95th percentile 1.07 to 1.29) and 1.09 in V4 (1.02 to 1.16), because points near chance enter the fit by noise. The permutation nulls are shifted further: their medians are 1.37 to 1.63 in V1 and 1.75 to 4.16 in V4 (main run), well above the no-crowding calibration, so the permutation null is not calibrated by it. Judged against the calibration, every V1 estimate (1.50 to 1.69) would count as elevated; judged against the permutation null, only 2.1 degrees does. The V1 significance pattern therefore depends on the null and says little either way; the V1 outcome rests on the values.

In [34]:
# Variant: threshold elevations from the main run's decoders with every all-zero decoder replaced by
# the nearest one with a nonzero coefficient (run "main_nonzero", decoder diagnostics above), held-out
# trial count. Shows how much of each estimate the all-zero decoders account for.
t0 = time.time()
rng = np.random.default_rng(19)
TH_NZ = pd.DataFrame([elevation("main_nonzero", area, s, "fold", rng) for area in AREAS for s in SP])
main_k = TH[(TH["mode"] == "main") & (TH.ntrials == "fold")].set_index(["area", "spacing"])
TH_NZ = TH_NZ.join(main_k[["k", "k_AL", "k_CA", "p_perm"]].add_suffix("_main"), on=["area", "spacing"])
print(f"in {time.time() - t0:.0f} s")
print(TH_NZ[["area", "spacing", "k_AL", "k_CA", "k", "sem", "p_perm", "null_median", "k_AL_main", "k_CA_main", "k_main",
             "p_perm_main", "k_wide"]].to_string(float_format=lambda v: f"{v:.4g}"))
in 62 s
  area spacing  k_AL  k_CA     k    sem   p_perm  null_median  k_AL_main  k_CA_main  k_main  p_perm_main  k_wide
0   V1     1.3  1.91 1.466 1.688 0.3917   0.2907        1.593      1.888      1.483   1.685       0.4206   1.687
1   V1     1.6 1.483   1.4 1.441 0.1325   0.1718        1.341      1.595      1.405     1.5       0.1848   1.444
2   V1     2.1 1.438 1.601 1.519 0.1306  0.04695         1.33      1.529      1.607   1.568      0.04795   1.517
3   V1     2.6 1.888 1.262 1.575 0.2385  0.06693         1.43      2.062      1.277   1.669      0.06194   1.576
4   V4     1.3 3.358 10.46 6.907  2.428 0.000999        3.323      3.738      10.87   7.302     0.000999    6.91
5   V4     1.6 2.127    20 11.06  2.362 0.000999        4.541      2.176      18.52   10.35     0.000999   14.83
6   V4     2.1 2.176 5.857 4.017  1.121 0.000999         2.36      2.218      7.234   4.726     0.000999   4.022
7   V4     2.6 1.783 3.319 2.551 0.2647 0.000999        1.717      1.831      3.383   2.607     0.000999   2.553

Without all-zero decoders the threshold elevations hardly change: V1 1.688 at 1.3 degrees and 1.575 at 2.6 (main 1.685 and 1.669), V4 6.91 and 2.55 (main 7.30 and 2.61). The large CA estimates remain (10.46 at 1.3 degrees; at 1.6 degrees 20, the bound of the grid, against 18.52 in the main run). The significance pattern is the same: in V1 only 2.1 degrees has p < 0.05 (0.047; 1.3 degrees 0.29 against 0.42 in the main run), and in V4 p = 0.001 at all four spacings. So the all-zero decoders do not account for the differences from the paper's values.

In [35]:
for (mode, nt), d in TH[TH.area == "V1"].groupby(["mode", "ntrials"], sort=False):
    k = d.set_index("spacing")
    vals = abs(k.loc["1.3", "k"] - 1.31) <= 0.10 and abs(k.loc["2.6", "k"] - 1.15) <= 0.08
    sig = [bool(k.loc[x, "p_perm"] < 0.05) for x in ("1.3", "1.6", "2.1", "2.6")]
    print(f"{mode:6s} n={nt:4s}: V1 closest {k.loc['1.3', 'k']:.3f} +/- {k.loc['1.3', 'sem']:.3f}, farthest "
          f"{k.loc['2.6', 'k']:.3f} +/- {k.loc['2.6', 'sem']:.3f}; values within: {vals}; p < 0.05 at 1.3, 1.6, 2.1, 2.6: {sig}")
main   n=fold: V1 closest 1.685 +/- 0.351, farthest 1.669 +/- 0.314; values within: False; p < 0.05 at 1.3, 1.6, 2.1, 2.6: [False, False, True, False]
main   n=all : V1 closest 1.685 +/- 0.331, farthest 1.669 +/- 0.428; values within: False; p < 0.05 at 1.3, 1.6, 2.1, 2.6: [False, False, True, False]
folds5 n=fold: V1 closest 1.738 +/- 0.312, farthest 1.517 +/- 0.265; values within: False; p < 0.05 at 1.3, 1.6, 2.1, 2.6: [False, False, False, False]
folds5 n=all : V1 closest 1.738 +/- 0.295, farthest 1.517 +/- 0.226; values within: False; p < 0.05 at 1.3, 1.6, 2.1, 2.6: [False, False, False, False]

Result: not reproduced. The V1 threshold elevation is 1.685 +/- 0.351 at 1.3 degrees and 1.669 +/- 0.314 at 2.6, outside 1.31 +/- 0.10 and 1.15 +/- 0.08. The permutation test finds only 2.1 degrees significant (p = 0.048 and 0.047 for the two trial counts), not 1.3 or 1.6 (p = 0.18 to 0.42) and not 2.6 (p = 0.059 and 0.062); with 5 folds no spacing is significant. The two trial counts are one reading for the estimate (same k). The V1 estimates are above the no-crowding calibration (95th percentile 1.26 to 1.29) and near the medians of their permutation nulls (1.63 at 1.3 degrees, 1.49 at 2.6). The null is shifted much further than the calibration, so the significance pattern says little in either direction; the outcome rests on the values, which fail. Without all-zero decoders the values are 1.688 and 1.575, also outside.

In [36]:
for (mode, nt), d in TH.groupby(["mode", "ntrials"], sort=False):
    k4 = d[d.area == "V4"].set_index("spacing")
    k1 = d[d.area == "V1"].set_index("spacing")
    vals = abs(k4.loc["1.3", "k"] - 2.52) <= 0.23 and abs(k4.loc["2.6", "k"] - 1.89) <= 0.19
    sig = bool((k4.p_perm < 0.001).all())
    above = bool((k4.k > k1.k).all())
    print(f"{mode:6s} n={nt:4s}: V4 closest {k4.loc['1.3', 'k']:.3f} +/- {k4.loc['1.3', 'sem']:.3f}, farthest "
          f"{k4.loc['2.6', 'k']:.3f} +/- {k4.loc['2.6', 'sem']:.3f}; values within: {vals}; p < 0.001 at all four: {sig} "
          f"(smallest attainable p with 1000 permutations is {1 / 1001:.4f}); V4 above V1 at every spacing: {above}")
main   n=fold: V4 closest 7.302 +/- 2.465, farthest 2.607 +/- 0.289; values within: False; p < 0.001 at all four: True (smallest attainable p with 1000 permutations is 0.0010); V4 above V1 at every spacing: True
main   n=all : V4 closest 7.302 +/- 2.478, farthest 2.607 +/- 0.285; values within: False; p < 0.001 at all four: True (smallest attainable p with 1000 permutations is 0.0010); V4 above V1 at every spacing: True
folds5 n=fold: V4 closest 10.166 +/- 2.161, farthest 3.036 +/- 0.644; values within: False; p < 0.001 at all four: True (smallest attainable p with 1000 permutations is 0.0010); V4 above V1 at every spacing: True
folds5 n=all : V4 closest 10.166 +/- 2.161, farthest 3.036 +/- 0.823; values within: False; p < 0.001 at all four: True (smallest attainable p with 1000 permutations is 0.0010); V4 above V1 at every spacing: True

Result: partially reproduced. V4 elevations exceed V1 at every spacing and the permutation test gives p = 0.001 (the smallest attainable) at all four spacings, but the values are far from the paper's: 7.30 +/- 2.47 at 1.3 degrees and 2.61 +/- 0.29 at 2.6, against 2.52 +/- 0.23 and 1.89 +/- 0.19. The CA estimates are large (10.87 and 18.52 at 1.3 and 1.6 degrees); on the grid up to 1000 they are 10.87 and 18.47, so the bound of 20 does not censor the main run (in the 5-fold run CA at 1.6 degrees reaches it, 41.0 on the wider grid). The AL estimates are 3.74 and 1.83 at the closest and farthest spacings. The V4 estimates are far above their permutation null medians (3.51 at 1.3 degrees, 1.75 at 2.6). Without all-zero decoders V4 gives 6.91 and 2.55, and CA 10.46 at 1.3 degrees, so these decoders do not explain the large CA estimates.

fig3c-shuffled-threshold-elevation¶

When decoders are fit to trial-shuffled responses, distractors still lead to threshold elevations similar to those in the original data, so the change in correlations plays a minimal role in the information loss.

In [37]:
rng = np.random.default_rng(9)
rows = []
for mode in ("shuffled_all", "shuffled_train"):
    for nt in ("fold", "all"):
        for area in AREAS:
            for s in SP:
                r = elevation(mode, area, s, nt, rng, n_boot=0, n_perm=0)
                o = TH[(TH["mode"] == "main") & (TH.ntrials == nt) & (TH.area == area) & (TH.spacing == SPL[s])].iloc[0]
                r.update(k_original=o.k, sem_original=o["sem"], within_2sem=abs(r["k"] - o.k) <= 2 * o["sem"])
                rows.append(r)
SH = pd.DataFrame(rows)
print(SH[["mode", "ntrials", "area", "spacing", "k", "k_original", "sem_original", "within_2sem"]].to_string(float_format=lambda v: f"{v:.3f}"))
for (mode, nt), d in SH.groupby(["mode", "ntrials"], sort=False):
    k4, k1 = d[d.area == "V4"].k.values, d[d.area == "V1"].k.values
    print(f"{mode:15s} n={nt:4s}: within twice the SEM at {int(d.within_2sem.sum())} of 8; V4 above V1 at every spacing: {bool((k4 > k1).all())}")
              mode ntrials area spacing      k  k_original  sem_original  within_2sem
0     shuffled_all    fold   V1     1.3  1.768       1.685         0.351         True
1     shuffled_all    fold   V1     1.6  1.488       1.500         0.159         True
2     shuffled_all    fold   V1     2.1  1.543       1.568         0.157         True
3     shuffled_all    fold   V1     2.6  1.687       1.669         0.314         True
4     shuffled_all    fold   V4     1.3  8.402       7.302         2.465         True
5     shuffled_all    fold   V4     1.6 11.122      10.349         2.454         True
6     shuffled_all    fold   V4     2.1  4.988       4.726         1.959         True
7     shuffled_all    fold   V4     2.6  3.032       2.607         0.289         True
8     shuffled_all     all   V1     1.3  1.768       1.685         0.331         True
9     shuffled_all     all   V1     1.6  1.488       1.500         0.153         True
10    shuffled_all     all   V1     2.1  1.543       1.568         0.158         True
11    shuffled_all     all   V1     2.6  1.687       1.669         0.428         True
12    shuffled_all     all   V4     1.3  8.402       7.302         2.478         True
13    shuffled_all     all   V4     1.6 11.122      10.349         2.463         True
14    shuffled_all     all   V4     2.1  4.988       4.726         1.885         True
15    shuffled_all     all   V4     2.6  3.032       2.607         0.285         True
16  shuffled_train    fold   V1     1.3  1.513       1.685         0.351         True
17  shuffled_train    fold   V1     1.6  1.303       1.500         0.159         True
18  shuffled_train    fold   V1     2.1  1.570       1.568         0.157         True
19  shuffled_train    fold   V1     2.6  1.395       1.669         0.314         True
20  shuffled_train    fold   V4     1.3  9.644       7.302         2.465         True
21  shuffled_train    fold   V4     1.6 11.092      10.349         2.454         True
22  shuffled_train    fold   V4     2.1  4.439       4.726         1.959         True
23  shuffled_train    fold   V4     2.6  2.775       2.607         0.289         True
24  shuffled_train     all   V1     1.3  1.513       1.685         0.331         True
25  shuffled_train     all   V1     1.6  1.303       1.500         0.153         True
26  shuffled_train     all   V1     2.1  1.570       1.568         0.158         True
27  shuffled_train     all   V1     2.6  1.395       1.669         0.428         True
28  shuffled_train     all   V4     1.3  9.644       7.302         2.478         True
29  shuffled_train     all   V4     1.6 11.092      10.349         2.463         True
30  shuffled_train     all   V4     2.1  4.439       4.726         1.885         True
31  shuffled_train     all   V4     2.6  2.775       2.607         0.285         True
shuffled_all    n=fold: within twice the SEM at 8 of 8; V4 above V1 at every spacing: True
shuffled_all    n=all : within twice the SEM at 8 of 8; V4 above V1 at every spacing: True
shuffled_train  n=fold: within twice the SEM at 8 of 8; V4 above V1 at every spacing: True
shuffled_train  n=all : within twice the SEM at 8 of 8; V4 above V1 at every spacing: True

Result: reproduced. With shuffled responses the threshold elevations lie within twice the bootstrap SEM of the original estimates at 8 of 8 area and spacing pairs, and V4 exceeds V1 at every spacing, under both readings (shuffling all trials or only the training trials) and both trial counts. The comparison is with this attempt's own original estimates, which differ from the paper's (fig2f claims). The test is lenient where the SEMs are large (V4 2.0 to 2.5 at 1.3 to 2.1 degrees).

fig7cd-fixed-decoder-generalization¶

Projected onto the decoding axis of the opposite condition, discriminability is largely preserved in V1 (d' 0.95 +/- 0.13 same, 0.88 +/- 0.12 cross, p = 0.20) but drops significantly in V4 (1.02 +/- 0.13 against 0.67 +/- 0.05, p = 0.002, paired t test).

Per population, two L1 logistic decoders (penalty as above) on the two most different target orientations, one on targets alone and one with distractors at 1.3 degrees. Ten folds over all trials of both conditions and all four orientations; in each, both decoders are fitted on the training trials of the extremes and the held-out trials of all orientations, in both conditions, are projected onto both axes. d' = (mu2 - mu1) / sqrt(0.5 (s1^2 + s2^2)) per pair of orientations (signed so that the trained direction is positive). Readings: unit of the test (a) population, averaged over pairs and both conditions, or (b) population x pair x condition; pairs (all, or the 18 degree pair alone).

In [38]:
def fixed_axes(pi):
    p = S[pi]
    rng = np.random.default_rng([10, pi])
    m = cw.stim_mask(p, "alone") | cw.stim_mask(p, "crowd", 1.32)
    idx = np.flatnonzero(m)
    X = p["counts"][:, idx].T.astype(float)
    cond = (p["p"].kind.values[idx] == "crowd").astype(int)
    oi = p["p"].oi.values[idx]
    folds = cw._folds(cond * 10 + oi, 10, rng)
    proj = np.full((len(idx), 2, 2), np.nan)   # last axis: the decoder as chosen, and cw.fit_nonzero
    n_zero = 0
    for j in range(10):
        tr, te = folds != j, folds == j
        for axis in (0, 1):
            sel = tr & (cond == axis) & np.isin(oi, (0, 3))
            Xa, ya = X[sel], (oi[sel] == 3).astype(int)
            C = cw.choose_C(Xa, ya, 10, rng)
            Xtr, Xte = cw._zscore(Xa, X[te])
            coef, b = cw._fit(Xtr, ya, C)
            proj[te, axis, 0] = Xte @ coef + b
            if not np.any(coef != 0):
                n_zero += 1
                coef, b = cw.fit_nonzero(Xtr, ya, C)
            proj[te, axis, 1] = Xte @ coef + b
    rows = []
    for a, b_ in PAIRS:
        for c in (0, 1):
            for axis in (0, 1):
                x1 = proj[(cond == c) & (oi == a), axis]
                x2 = proj[(cond == c) & (oi == b_), axis]
                rows.append(dict(area=p["area"], animal=p["animal"], session=p["session"], orange=p["orange"], a=a, b=b_,
                                 sep_deg=6 * (b_ - a), data="alone" if c == 0 else "crowded",
                                 axis="alone" if axis == 0 else "crowded", same=c == axis, dprime=cw.dprime(x2[:, 0], x1[:, 0]),
                                 dprime_nonzero=cw.dprime(x2[:, 1], x1[:, 1]), zero_fits=n_zero))
    return rows


t0 = time.time()
F7 = pd.DataFrame([r for rr in Parallel(n_jobs=4)(delayed(fixed_axes)(pi) for pi in range(len(S))) for r in rr])
print(f"fixed-axis decoding in {time.time() - t0:.0f} s; d' undefined in {int(F7.dprime.isna().sum())} of {len(F7)}")
print(F7.groupby(["area", "same", "sep_deg"]).dprime.mean().unstack().round(3).to_string())
fixed-axis decoding in 51 s; d' undefined in 0 of 1056
sep_deg        6      12     18
area same                      
V1   False  0.234  0.447  0.682
     True   0.216  0.417  0.645
V4   False  0.158  0.326  0.467
     True   0.243  0.514  0.710
In [39]:
exp7 = {"V1": (0.95, 0.13, 0.88, 0.12), "V4": (1.02, 0.13, 0.67, 0.05)}
for pairs_label, pair_sel in (("all pairs", F7.sep_deg > 0), ("18 deg pair", F7.sep_deg == 18)):
    for unit in ("population", "population x pair x condition"):
        for area in AREAS:
            d = F7[pair_sel & (F7.area == area)]
            if unit == "population":
                g = d.groupby(["session", "orange", "same"]).dprime.mean().unstack()
            else:
                g = d.pivot_table(index=["session", "orange", "a", "b", "data"], columns="same", values="dprime")
            s_, c_ = g[True], g[False]
            t = stats.ttest_rel(s_, c_, nan_policy="omit")
            e = exp7[area]
            ok = [abs(s_.mean() - e[0]) <= e[1], abs(c_.mean() - e[2]) <= e[3]]
            print(f"{pairs_label:11s} {unit:30s} {area}: same {s_.mean():.3f} +/- {s_.sem():.3f}, cross {c_.mean():.3f} +/- "
                  f"{c_.sem():.3f} (n = {len(g)}), paired t p = {t.pvalue:.3g}; values within {ok}")
print("d' per population, 18 degree pair, before averaging (same and cross axis, each the mean of the two conditions):")
g18 = F7[F7.sep_deg == 18].groupby(["area", "session", "orange", "same"]).dprime.mean().unstack()
g18.columns = ["cross", "same"]
print(g18[["same", "cross"]].round(3).to_string())
for an in ("AL", "CA"):
    for area in AREAS:
        d = F7[(F7.area == area) & (F7.animal == an)]
        print(an, area, "same %.3f, cross %.3f" % (d[d.same].dprime.mean(), d[~d.same].dprime.mean()))
# Variant: fixed decoders with no nonzero coefficient replaced by the nearest one that has one
# (cw.fit_nonzero), per population, all pairs and the 18 degree pair.
zf = F7.groupby(["area", "session", "orange"]).zero_fits.first()
print("Variant without all-zero fixed decoders; all-zero fits (of 20 per population):",
      {a: int(zf[a].sum()) for a in AREAS}, "of", {a: 20 * len(zf[a]) for a in AREAS})
for pairs_label, pair_sel in (("all pairs", F7.sep_deg > 0), ("18 deg pair", F7.sep_deg == 18)):
    for area in AREAS:
        g = F7[pair_sel & (F7.area == area)].groupby(["session", "orange", "same"]).dprime_nonzero.mean().unstack()
        t = stats.ttest_rel(g[True], g[False], nan_policy="omit")
        print(f"{pairs_label:11s} {area}: same {g[True].mean():.3f} +/- {g[True].sem():.3f}, cross {g[False].mean():.3f} "
              f"+/- {g[False].sem():.3f}, paired t p = {t.pvalue:.3g}")
all pairs   population                     V1: same 0.354 +/- 0.044, cross 0.380 +/- 0.039 (n = 22), paired t p = 0.359; values within [np.False_, np.False_]
all pairs   population                     V4: same 0.411 +/- 0.044, cross 0.265 +/- 0.043 (n = 22), paired t p = 0.000445; values within [np.False_, np.False_]
all pairs   population x pair x condition  V1: same 0.354 +/- 0.024, cross 0.380 +/- 0.022 (n = 264), paired t p = 0.278; values within [np.False_, np.False_]
all pairs   population x pair x condition  V4: same 0.411 +/- 0.028, cross 0.265 +/- 0.019 (n = 264), paired t p = 2.76e-08; values within [np.False_, np.False_]
18 deg pair population                     V1: same 0.645 +/- 0.085, cross 0.682 +/- 0.068 (n = 22), paired t p = 0.503; values within [np.False_, np.False_]
18 deg pair population                     V4: same 0.710 +/- 0.083, cross 0.467 +/- 0.079 (n = 22), paired t p = 0.00181; values within [np.False_, np.False_]
18 deg pair population x pair x condition  V1: same 0.645 +/- 0.081, cross 0.682 +/- 0.057 (n = 44), paired t p = 0.657; values within [np.False_, np.False_]
18 deg pair population x pair x condition  V4: same 0.710 +/- 0.094, cross 0.467 +/- 0.062 (n = 44), paired t p = 0.00683; values within [np.False_, np.False_]
d' per population, 18 degree pair, before averaging (same and cross axis, each the mean of the two conditions):
                      same  cross
area session orange              
V1   1       1       0.309  0.471
             2       0.540  0.603
     2       1       0.281  0.688
             2       1.049  1.054
     3       1       0.795  0.506
             2       0.623  0.660
     4       1       0.451  0.145
             2       0.477  0.372
     5       1       0.502  0.615
             2       0.245  0.281
     6       1       0.022  0.244
             2       0.321  0.449
     7       1       0.686  0.829
             2       0.776  0.386
     8       1       0.212  0.709
             2       1.218  0.794
     9       1       0.944  0.988
             2       1.088  1.067
     10      1       1.041  1.074
             2       1.664  1.420
     11      1       0.319  0.740
             2       0.624  0.904
V4   1       1       1.360  0.677
             2       1.248  0.475
     2       1       0.076 -0.098
             2       0.360  0.361
     3       1       1.111  0.993
             2       0.808  0.844
     4       1       0.297  0.382
             2       1.219  1.313
     5       1       0.424  0.290
             2       0.499  0.615
     6       1       0.716  0.534
             2       1.067  0.950
     7       1       0.094 -0.094
             2       1.011  0.883
     8       1       0.479  0.181
             2       0.888  0.520
     9       1       0.910  0.071
             2       0.531  0.118
     10      1       0.540  0.458
             2       1.163  0.346
     11      1       0.577 -0.029
             2       0.241  0.475
AL V1 same 0.289, cross 0.294
AL V4 same 0.423, cross 0.327
CA V1 same 0.469, cross 0.529
CA V4 same 0.390, cross 0.157
Variant without all-zero fixed decoders; all-zero fits (of 20 per population): {'V1': 8, 'V4': 7} of {'V1': 440, 'V4': 440}
all pairs   V1: same 0.359 +/- 0.044, cross 0.380 +/- 0.039, paired t p = 0.43
all pairs   V4: same 0.411 +/- 0.044, cross 0.263 +/- 0.043, paired t p = 0.000375
18 deg pair V1: same 0.653 +/- 0.083, cross 0.682 +/- 0.068, paired t p = 0.583
18 deg pair V4: same 0.711 +/- 0.083, cross 0.463 +/- 0.080, paired t p = 0.00147

Result: partially reproduced. The tests hold: in V1 the cross projection does not lower d' (per population, all pairs: same 0.354 +/- 0.044, cross 0.380 +/- 0.039, p = 0.36), and in V4 it does (0.411 +/- 0.044 against 0.265 +/- 0.043, p = 0.0004; 18 degree pair 0.710 against 0.467, p = 0.002). The d' values are well below the paper's (0.95, 0.88, 1.02 and 0.67), under every reading. Per population, before averaging, the 18 degree pair gives same-axis d' of 0.02 to 1.66 in V1 and 0.08 to 1.36 in V4; 17 of 22 V1 populations are below 0.95 and 16 of 22 V4 populations below 1.02. Only 8 of 440 V1 and 7 of 440 V4 fixed decoders have no nonzero coefficient; replacing them changes the per-population means by at most 0.005 over all pairs (V1 same 0.359, V4 cross 0.263) and 0.008 for the 18 degree pair, and the tests give the same result (p = 0.43 and 0.0004).

Summary¶

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.

Claim Outcome
data-populations partially reproduced (counts match the deposit; the stated selection does not regenerate them)
fig1b-v4-rf-larger blocked: data missing
fig2a-v1-single-neuron-near reproduced
fig2b-v4-single-neuron-near reproduced
fig2c-farthest-spacing-slopes reproduced
fig2c-v4-worse-all-spacings reproduced
fig2de-population-decoding-example reproduced (V1 part on all cases)
fig2f-v1-threshold-elevation not reproduced
fig2f-v4-threshold-elevation partially reproduced
figs3-pseudo-populations see pseudo_populations.ipynb
fig3ab-correlations-reduced reproduced
fig3c-shuffled-threshold-elevation reproduced
fig3d-v1-fano-closest reproduced
fig3e-v4-fano-all-spacings reproduced
fig4a-v1-modulation-indices partially reproduced
fig4b-v4-modulation-indices reproduced (log-index tests)
fig4c-modulation-strength-significant reproduced
fig4c-v4-stronger-than-v1 reproduced
fig4c-v4-maintained-v1-weaker-far reproduced
figs4-rf-alignment blocked: data missing
figs5-additive-vs-multiplicative reproduced
fig5bc-tuning-model-terms partially reproduced
fit-quality not reproduced
fig5-terms-covary reproduced (rests on the even/odd selection)
fig5-negative-multiplicative partially reproduced
fig5de-simulated-discriminability reproduced (rests on the even/odd selection under reading (a, a))
fig6c-tuning-correlation-near partially reproduced
fig6d-tuning-correlation-spacing partially reproduced
fig6e-tuning-correlation-configuration reproduced
fig6-well-isolated blocked: data missing
fig7cd-fixed-decoder-generalization partially reproduced
figs6-common-neuron-pool reproduced

How the analysis differs from the paper's. The paper's code is not public, so every method is the Methods' as the claims file reads them, with open details run under each reading. The decoders' penalty grid, z-scoring and fold assignment, the threshold-elevation grid, and the handling of zero means are standard choices stated in crowding.py. All deposited units are used, as the stated selection cannot be applied (data-populations). Noise correlations use every stimulus epoch, as the first epoch of a trial cannot be identified. Even and odd presentations follow the stored order, which for V4 is not the recording order; single random half splits keep about as many neurons as the stored-order split in both areas, and the tuning-model claims are repeated on a selection by reliability averaged over 20 random splits, under which fig5-terms-covary and fig5-terms-covary would not hold in V4, nor fig5de-simulated-discriminability under reading (a, a). Over 20 single random splits both hold in every split (fig5de against the selected neurons' own slopes), so the stored-order split is typical of the single split the paper describes. Under the stated penalty rule and the grid used here (lower bound C = 0.01) the chosen decoder has no nonzero coefficient in 5% to 18% of outer folds; replacing these decoders changes the threshold elevations little (V4 6.91 against 7.30 at 1.3 degrees) and the fixed-decoder d' by at most 0.008. With no crowding the threshold-elevation estimate is biased upward (1.17 in V1, 1.09 in V4), a property of the fit as the paper describes it; the permutation nulls are shifted further (V1 medians 1.37 to 1.63), so the V1 significance pattern depends on the null used.

What was found about the data set. (1) In sessions 1, 2 and 8 to 11 the epochs labelled blank and distractor-only respond as the target epochs do, so the spontaneous rate cannot be measured and the Methods' selection cannot be checked there. (2) V1 and V4 entries of the same population hold the same epochs but in different orders; the V1 order is consistent with the recording order and the V4 order is not, so epochs cannot be matched across areas and even/odd splits of V4 cannot follow time. 244 V4 units pass the reliability criterion against the paper's 198, while V1 gives the paper's 146 exactly; single random splits give similar counts (238 and 144 on average), so the order does not explain the difference. (3) The two epochs of a trial are not marked. (4) The files hold blank and distractor-only epochs and the spacing of the orientation experiment is not stored; the description mentions neither. (5) The receptive-field mapping, the per-session coarse mapping and the waveforms are not deposited.