Reproducing Robotka et al. (2023) from CRCNS aa-5¶

Paper. Robotka, Thomas, Yu, Wood, Elie, Gahr & Theunissen (2023), "Sparse ensemble neural code for a complete vocal repertoire", Cell Reports 42, 112034, doi:10.1016/j.celrep.2023.112034.

Dataset. CRCNS aa-5, "Simultaneous extracellular recordings of avian auditory neurons in freely behaving zebra finches...", doi:10.6080/K0TT4P5Q, read from the public bucket crcnsarchive/aa-5/live/. CRCNS data sets are not versioned: the version is recorded as unversioned, the one published version there is, and the MD5 sums of every file read (from the data set's checksums.md5) are printed below so that a later change can be detected. The paper cites this DOI and no version; the bucket holds a single copy (live/, data descriptor v0.6 of 29 Nov 2022), so that is what is pinned.

Claims. claims/robotka-2023.yaml, written from the version of record with its STAR Methods and supplement, and the paper's code (github.com/ftheunissen/Ensemble-Code-Cell-Reports-2022 at commit f2d2376). Method details the claims file lacks are taken from the paper and that code, cited in the helper aa5.py and below.

claim status here
stimulus-set-link tested
paper-good-units-link (link claim added by the author) tested
auditory-units tested
inhibited-units tested
fig3c-peak-call-types tested
fig4a-unit-z-vs-zt tested
good-units-100 tested
fig4b-ensemble-20 tested
fig4b-top-ensembles tested
fig4b-confusions tested
figs4-per-bird-and-sex tested; blocked when the selection gives a bird fewer than 15 good units
figs6-primary-vs-secondary blocked: no brain area per unit in the dataset
fig5e-volume tested
fig5f-si-unrelated tested
fig5g-entropy-selectivity tested
fig5h-neural-noise tested
fig5-multiple-regression tested
pcs-variance tested
table1-snr tested
figs5-region-anova blocked: no brain area per unit in the dataset
fig6a-acoustic-clusters, acoustic-labels-decoding, fig6c-number-of-clusters, fig6c-ari-call-over-acoustic, figs10-ensemble-size blocked: the vocalization database and acoustic labels are not public (the call-type half of fig6c-number-of-clusters is computed)
anesth-auditory-units, anesth-decoding-better, anesth-regressions, anesth-primary-secondary-rate blocked: CRCNS aa-4 not analysed in this run
figs9-per-region-regressions blocked: no brain area per unit (and aa-4 not analysed)

Reading the data streams about 164 GB of tar.gz from the bucket (four sites at a time); this takes 15 to 30 minutes and is most of the run time.

In [1]:
import time, resource, warnings
from itertools import combinations
from math import comb

import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt

import aa5

warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 30)
T_START = time.time()

Data check¶

The bucket's listing and the MD5 sums of the files read, then every site is streamed once and each unit reduced to spike times, the stored KDE, labels and the stimulus waveforms (aa5.read_all).

In [2]:
listing = aa5.list_files()
md5 = aa5.checksums()
tars = sorted([(k, s) for k, s in listing if k.endswith(".tar.gz")], key=lambda x: -x[1])
print(len(listing), "objects;", len(tars), "site files,", round(sum(s for _, s in tars) / 1e9, 1), "GB")
for k, s in listing:
    if not k.endswith("/"):
        print(f"{s:>12d}  {md5.get(k.replace(aa5.PREFIX, ''), '-'):32s}  {k}")
62 objects; 50 site files, 163.8 GB
        3947  -                                 aa-5/live/checksums.md5
       19910  328e7bbbb48dc30dab9d225a00434499  aa-5/live/data/PlotPSTHCategoriesGUI.ipynb
  2834343757  54c3ca708933385a994d0a5f18265710  aa-5/live/data/ZF4F/ZF4F_2t_190611_160843.tar.gz
  6289758495  d5ca291e5a93934ea20d176900e2e707  aa-5/live/data/ZF4F/ZF4F_2t_190612_101201.tar.gz
  4343768853  72fe1873a831f77f162ef9ad50efdff5  aa-5/live/data/ZF4F/ZF4F_2t_190612_134337.tar.gz
  5583252055  dae2631f8eea26a87178d6ebafd615a3  aa-5/live/data/ZF4F/ZF4F_2t_190613_101015.tar.gz
  1265287545  4a650f0949c4265039400c42d1c84382  aa-5/live/data/ZF4F/ZF4F_2t_190613_142654.tar.gz
  6976698853  48e2265137cc49d3b05c43a04776bee8  aa-5/live/data/ZF4F/ZF4F_3t_190613_150928.tar.gz
       17784  d16d9957d9dd4cae97796030672ebcf7  aa-5/live/data/ZF4F/ZF4F_4t_190614_094759.tar.gz
  3545990920  e98f66e1693fdb9e1749c3faf9d5cc1e  aa-5/live/data/ZF4F/ZF4F_5t_190615_114154.tar.gz
  1186039399  162de973e45f1f53afea7bd6fa0bd68c  aa-5/live/data/ZF4F/ZF4F_5t_190616_102456.tar.gz
    44537328  eb919a20df81e351ed77713d4abb9649  aa-5/live/data/ZF4F/ZF4F_6_5_190618_110932.tar.gz
  3720594094  35936bb6b7b8c009d20be8def75278f4  aa-5/live/data/ZF4F/ZF4F_6t_190616_142033.tar.gz
  1038330954  918e7ddca554522c9da4a5fe93f6a284  aa-5/live/data/ZF4F/ZF4F_7t_190619_095313.tar.gz
   401205399  7cea8b4c85f21519a8f276aceecdede3  aa-5/live/data/ZF4F/ZF4F_8_5t_190621_100019.tar.gz
  1095157918  a8183b8200244e7d78ecd866173dd8df  aa-5/live/data/ZF4F/ZF4F_8t_190620_101233.tar.gz
  4333966397  7897d1ccd0ff25bfb9ed8d55e9dfa083  aa-5/live/data/ZF5M/ZF5M_10_5t_190703_133641.tar.gz
  5404360582  1055f7937ccd31bc00b853bfb1919ccf  aa-5/live/data/ZF5M/ZF5M_10t_190702_095313.tar.gz
  3894983502  5a4ffdaaadae1bb6f8a211142a3f500e  aa-5/live/data/ZF5M/ZF5M_11_5t_190705_102710.tar.gz
  6046038540  e5370c8ef59439c45f65feb68b057a2f  aa-5/live/data/ZF5M/ZF5M_11t_190704_100420.tar.gz
  5129143152  5abab3a45ef3418ae68c4f02ef4ff347  aa-5/live/data/ZF5M/ZF5M_11t_190704_121850.tar.gz
  2762856931  dc05cc48872a69169a53731e7e5df11e  aa-5/live/data/ZF5M/ZF5M_12t_190707_102304.tar.gz
  1043340439  205987e6f04fb0d440dde6ba58e7fddd  aa-5/live/data/ZF5M/ZF5M_6_5t_190625_135634.tar.gz
  1560644227  d566fff0ac9a53e9f66ce22b8c3a3d98  aa-5/live/data/ZF5M/ZF5M_6t_190625_102256.tar.gz
  3177488339  93f9d6b2edf57cee99f95ba022dbdaff  aa-5/live/data/ZF5M/ZF5M_7t_190625_154417.tar.gz
   679657201  c0e6905a34464ce88e8579b53857cbef  aa-5/live/data/ZF5M/ZF5M_7t_190626_101721.tar.gz
  3254100649  549153153dcfbc217109f1718e073dff  aa-5/live/data/ZF5M/ZF5M_8_5t_190629_095922.tar.gz
  6784216809  3b493d0c48934d4254ab5a6018f526b2  aa-5/live/data/ZF5M/ZF5M_8t_190627_132428.tar.gz
  1906422425  23e9e5920bfb8790ba95381a0529bf93  aa-5/live/data/ZF5M/ZF5M_8t_190628_100257.tar.gz
  2196821200  c121842bb675d0fdabb4d693af429764  aa-5/live/data/ZF5M/ZF5M_8t_190628_124320.tar.gz
  2388985498  0ac2e616efce26d66b0fe762b42b0ac4  aa-5/live/data/ZF5M/ZF5M_9_5t_190701_125653.tar.gz
  2450297699  c36f2c3ec169495cff4a4af89ee0618a  aa-5/live/data/ZF5M/ZF5M_9t_190630_100846.tar.gz
   509520809  32137243945c08cd1a2831897688a0dc  aa-5/live/data/ZF5M/ZF5M_9t_190701_102100.tar.gz
  1517344326  8bfd9306e85d2fa5b6be0341eaf29c1a  aa-5/live/data/ZF6M/ZF6M_10_5t_190808_102150.tar.gz
  1691012416  9d05ba3e70b8cbd4637c7abc46499d6f  aa-5/live/data/ZF6M/ZF6M_2t_190715_172820.tar.gz
  3785365627  d8bb642ba6be421eee75b35ba60431aa  aa-5/live/data/ZF6M/ZF6M_2t_190716_085010.tar.gz
  4728993310  f35724f4261b07ca1d530ad39ca07134  aa-5/live/data/ZF6M/ZF6M_6_5t_190719_094702.tar.gz
  6288992330  d195f50d7ce0cd0bb027762db13f7ed6  aa-5/live/data/ZF6M/ZF6M_7_5t_190723_100723.tar.gz
  4397202722  c2e7761a5cb074808abee7cd61cac64d  aa-5/live/data/ZF6M/ZF6M_7_5t_190723_141539.tar.gz
  5904987989  c1d3b433418a0c059b2ec3becf073d2f  aa-5/live/data/ZF6M/ZF6M_8t_190725_105432.tar.gz
  1686476050  8d959ee509f4494f2f61b53153305a98  aa-5/live/data/ZF6M/ZF6M_9_5t_190805_102553.tar.gz
  2240722109  7f4b4312079abf868ca3c93c28b1f2de  aa-5/live/data/ZF6M/ZF6M_9_5t_190805_130046.tar.gz
  1963384862  05153acf58c659fca13d3f810742b013  aa-5/live/data/ZF7F/ZF7F_3t_190716_130715.tar.gz
  1522836076  60787c0b59c3b9545c29e0432108ad12  aa-5/live/data/ZF7F/ZF7F_4_5t_190718_091732.tar.gz
  1170276452  c4a1554842c52676586672dacf20e897  aa-5/live/data/ZF7F/ZF7F_4t_190717_094723.tar.gz
  6052265435  214b898540ce7c7c07ef02f595f0dc82  aa-5/live/data/ZF7F/ZF7F_5_5t_190722_121506.tar.gz
  4848100887  64e516af1129156daeb33282787dd27a  aa-5/live/data/ZF7F/ZF7F_5t_190720_152938.tar.gz
   143087879  06bb81c7ad90a467753ceebf35af3024  aa-5/live/data/ZF7F/ZF7F_5t_190720_182644.tar.gz
  5912130814  d8030248195b879d4f3204dd86ed2fb8  aa-5/live/data/ZF7F/ZF7F_6t_190724_104215.tar.gz
  6076169670  4de72659235b32f71a423daf2d86d39e  aa-5/live/data/ZF7F/ZF7F_7_5t_190807_105305.tar.gz
  6668616338  bbf27a8ccb02a3317832943b949aa614  aa-5/live/data/ZF7F/ZF7F_7t_190806_115742.tar.gz
  5329502454  92e4c6b8ee688525e20728b6cbb016e8  aa-5/live/data/ZF7F/ZF7F_8_5t_190809_133540.tar.gz
       18162  07ed0cea0a97481f25a0d7b4ea10b0a5  aa-5/live/docs/crcns_aa-5_data_description.docx
       85000  8ac46973b1d32e281eb74535e950af31  aa-5/live/docs/crcns_aa-5_data_description.pdf
        3530  0d9ca1a60cfdc4341446a7ea01c9b0d0  aa-5/live/filelist.txt
In [3]:
t0 = time.time()
units, waves, other = aa5.read_all([k for k, _ in tars], workers=4, log=lambda s: None)
print(f"streamed {len(tars)} sites in {(time.time() - t0) / 60:.1f} min; {len(units)} unit pickles; "
      f"peak memory of this process {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
streamed 50 sites in 16.9 min; 872 unit pickles; peak memory of this process 3.22 GB
In [4]:
# What a unit pickle holds: the unit dictionary's keys and every column of both tables
print("unitInfo keys:", sorted({k for u in units for k in u["info_keys"]}))
print("dfAbsTime columns:", sorted({c for u in units for c in u["abs_columns"]}))
print("dfRelTime columns:", sorted({c for u in units for c in u["rel_columns"]}))
print("other tar members:", len(other), "all AppleDouble '._' files:", all(o[0].split('/')[-1].startswith('._') for o in other))

ut = aa5.unit_table(units)
print()
print("pickles per bird:", ut.groupby("bird").size().to_dict(), " sites per bird:", ut.groupby("bird").site.nunique().to_dict())
empty = ut[ut.n_trials_all == 0]
print("empty pickles (no stimulus rows):", len(empty), "in sites", empty.site.value_counts().to_dict())
print("pickles with vocalization (call-type) trials:", (ut.n_calls > 0).sum(), "; song-only:", ((ut.n_calls == 0) & (ut.n_trials_all > 0)).sum())
print("call types per unit (units with any):", ut[ut.n_calls > 0].n_calls.value_counts().sort_index().to_dict())
print(f"SpikeSNR range {ut.snr.min():.2f} to {ut.snr.max():.2f}; units with SNR >= 5: {(ut.snr >= 5).sum()}")

# consistency of the per-trial fields
bad_tr = sum(len(r["spikeTimes"]) != r["nTrials"] for u in units for r in u["rows"])
bad_mic = sum(r["micShape"][0] != r["nTrials"] for u in units for r in u["rows"] if len(r["micShape"]) == 2)
allsp = np.concatenate([s for u in units for r in u["rows"] for s in r["spikeTimes"] if len(s)])
print("rows where len(spikeTimes) != nTrials:", bad_tr, "; where micWav rows != nTrials:", bad_mic)
print(f"spike times relative to onset: {allsp.min():.3f} to {allsp.max():.3f} s (descriptor: -0.5 to 4.5 s); {len(allsp)} spikes")
kde_grid = pd.Series([(r["nKDE"], round(r["tKDE0"], 3), round(r["dtKDE"], 4)) for u in units for r in u["rows"]]).value_counts()
print("KDE time grids (n samples, start s, step s):", kde_grid.to_dict())
stim_grid = pd.Series([(round(r["tStim0"], 3), round(1 / r["dtStim"]), r["stimLen"]) for u in units for r in u["rows"]]).value_counts()
print("stimulus grids (start s, Hz, samples):", stim_grid.head(3).to_dict(), "...", len(stim_grid), "kinds")
nhash = {s: len({r["stimHash"] for u in units for r in u["rows"] if r["file"] == s}) for s in waves}
print("vocalization stimuli:", len(waves), "; with a waveform that differs between units:", sum(v > 1 for v in nhash.values()))
kbw = pd.Series([u["KDE_BW"] for u in units])
print(f"KDE_BW (descriptor: bandwidth in s of the coarse rate used for RateThreshold): {kbw.min()} to {kbw.max()},",
      "pickles per value:", kbw.value_counts().sort_index().to_dict())
rth = pd.Series([u["RateThreshold"] for u in units])
print(f"RateThreshold (descriptor: spikes/s): {rth.min()} to {rth.max()}, {rth.nunique()} distinct values")

# recordings deposited twice: identical spike trains in two pickles
nonempty = ut[ut.n_trials_all > 0]
dup = nonempty[nonempty.spike_hash.duplicated(keep=False)]
print("non-empty pickles with a spike train identical to another pickle:", len(dup))
print("sites per bird and depth:", ut.groupby("bird").site.apply(lambda s: sorted(set(x.split('_')[1] for x in s))).to_dict())
unitInfo keys: ['Bird', 'Electrode', 'KDE_BW', 'RateThreshold', 'Site', 'Sort', 'SpikeSNR', 'SpikeShape', 'SpikeStd', 'StimName', 'nStim', 'nTrials']
dfAbsTime columns: ['On', 'call_type', 'duration', 'file', 'file_path', 'relation_short', 'spikes', 'start_time', 'stop_time']
dfRelTime columns: ['call_type', 'file', 'micWav', 'nTrials', 'relation_short', 'spikeKDE', 'spikeTimes', 'stimWav', 'tKDE', 'tMic', 'tStim', 'trialInd']
other tar members: 872 all AppleDouble '._' files: True
pickles per bird: {'ZF4F': 255, 'ZF5M': 308, 'ZF6M': 161, 'ZF7F': 148}  sites per bird: {'ZF4F': 14, 'ZF5M': 17, 'ZF6M': 9, 'ZF7F': 10}
empty pickles (no stimulus rows): 34 in sites {'ZF4F_4t_190614_094759': 20, 'ZF4F_8t_190620_101233': 9, 'ZF7F_5t_190720_182644': 2, 'ZF5M_7t_190625_154417': 1, 'ZF4F_8_5t_190621_100019': 1, 'ZF4F_7t_190619_095313': 1}
pickles with vocalization (call-type) trials: 726 ; song-only: 112
call types per unit (units with any): {1: 1, 2: 1, 3: 7, 4: 4, 5: 1, 6: 1, 8: 2, 9: 3, 10: 706}
SpikeSNR range 2.37 to 18.03; units with SNR >= 5: 491
rows where len(spikeTimes) != nTrials: 0 ; where micWav rows != nTrials: 0
spike times relative to onset: -0.500 to 4.500 s (descriptor: -0.5 to 4.5 s); 10318714 spikes
KDE time grids (n samples, start s, step s): {(5001, -0.5, 0.001): 96556}
stimulus grids (start s, Hz, samples): {(-0.5, 25000, 125000): 71793, (-0.5, 32000, 160000): 24758, (-0.5, 44100, 220499): 4} ... 4 kinds
vocalization stimuli: 110 ; with a waveform that differs between units: 0
KDE_BW (descriptor: bandwidth in s of the coarse rate used for RateThreshold): 0.2 to 10.0, pickles per value: {0.2: 1, 3.0: 1, 5.0: 148, 5.2: 15, 5.4: 11, 6.0: 1, 6.3: 1, 6.8: 1, 7.2: 1, 7.4: 1, 7.5: 1, 7.6: 1, 7.7: 2, 7.9: 7, 8.0: 1, 8.1: 5, 8.4: 10, 8.6: 5, 8.8: 2, 8.9: 1, 9.9: 10, 10.0: 646}
RateThreshold (descriptor: spikes/s): 0.05 to 10.0, 50 distinct values
non-empty pickles with a spike train identical to another pickle: 0
sites per bird and depth: {'ZF4F': ['2t', '3t', '4t', '5t', '6', '6t', '7t', '8', '8t'], 'ZF5M': ['10', '10t', '11', '11t', '12t', '6', '6t', '7t', '8', '8t', '9', '9t'], 'ZF6M': ['10', '2t', '6', '7', '8t', '9'], 'ZF7F': ['3t', '4', '4t', '5', '5t', '6t', '7', '7t', '8']}
In [5]:
# Stimulus set: call types and exemplar counts over all units
voc = pd.DataFrame([(s, w[0]["call_type"]) for s, w in waves.items()], columns=["stim", "call"])
print(voc.call.value_counts().to_dict(), "total", len(voc))
{'Te': 15, 'Ne': 15, 'DC': 14, 'LT': 13, 'Wh': 13, 'Be': 12, 'Ag': 9, 'So': 9, 'Th': 5, 'Di': 5} total 110

Are the paper's units in the dataset?¶

decodingCallTypesNaiveBayesPart2.ipynb, in the paper's code at the pinned commit, prints the names of its 100 good units (site and pickle name, with their single-unit PCC). Read here only to check which of them the dataset holds; nothing else is taken from it.

In [6]:
import re, requests
CODE_URL = ("https://raw.githubusercontent.com/ftheunissen/Ensemble-Code-Cell-Reports-2022/"
            "f2d237639217425e7fc81d694708f19428a3b026/decodingCallTypesNaiveBayesPart2.ipynb")
nbp = requests.get(CODE_URL, timeout=60).json()
txt = "".join("".join(o.get("text", [])) for c in nbp["cells"] if c["cell_type"] == "code" for o in c.get("outputs", []))
paper_good = dict(re.findall(r"(ZF[\w.]+?_goodPlayback-e\d+-c\d+\.pkl) ([\d.]+)", txt))
uids = set(ut.uid)
in_ds = [n for n in paper_good if n in uids]
renamed = [n for n in paper_good if n not in uids and n.replace(".old", "") in uids]
missing = [n for n in paper_good if n not in uids]
print(f"paper's good units listed: {len(paper_good)}; in the dataset under the same name: {len(in_ds)}; missing: {len(missing)}")
print("missing, by site:", pd.Series([n.split("_goodPlayback")[0] for n in missing]).value_counts().to_dict())
print("of these, a pickle of the same name exists in the site without '.old':", len(renamed))
print("dataset site ZF4F_2t_190613_101015 holds", int((ut.site == "ZF4F_2t_190613_101015").sum()), "pickles")
paper's good units listed: 100; in the dataset under the same name: 91; missing: 9
missing, by site: {'ZF4F_2t_190613_101015.old': 9}
of these, a pickle of the same name exists in the site without '.old': 0
dataset site ZF4F_2t_190613_101015 holds 18 pickles

The per-trial database and the clock of spikes and stimuli¶

Auditory units (SNR >= 5, auditory test p <= 0.01, with vocalization trials; C1 and GenerateDataBase.ipynb), their trial Z (C2), the PCA of trial-averaged KDE responses and the per-trial T1 to T5 (C4). Spike times are stored relative to stimulus onset. The check that they share the stimulus clock: the population rate around onset, and decoding call type from spike counts in a window before onset (where no information should be) against the same window after onset.

In [7]:
t0 = time.time()
db = aa5.build_database(units, waves)
aud = db["aud"]
print(f"database built in {time.time() - t0:.0f} s: {len(aud)} auditory units, {db['n_kde_rows']} KDE rows in the PCA")
print("auditory units per bird:", aud.groupby("bird").size().to_dict())
print("of the paper's good units held by the dataset,", sum(n in set(aud.uid) for n in in_ds), "of", len(in_ds), "are auditory here")
print("  and", sum((db["feat"][n][1] > 0).sum() == len(db["stims"]) for n in in_ds if n in db["feat"]), "of them have all 110 stimuli")
byuid = {u["Site"] + "_" + u["pkl"]: u for u in units}

# population PSTH of auditory units, vocalization trials
bins = np.arange(-0.5, 1.0001, 0.01)
h = np.zeros(len(bins) - 1); ntr = 0
for x in aud.uid:
    for r in aa5.voc_rows(byuid[x]):
        for s in r["spikeTimes"]:
            h += np.histogram(s, bins)[0]; ntr += 1
rate = h / ntr / 0.01
pre, post = rate[bins[:-1] < 0].mean(), rate[(bins[:-1] >= 0.02) & (bins[:-1] < 0.1)].mean()
first = bins[:-1][np.argmax(rate > pre + 5 * rate[bins[:-1] < 0].std())]
print(f"mean rate before onset {pre:.2f} spikes/s, 20 to 100 ms after onset {post:.2f} spikes/s; first 10 ms bin above baseline + 5 SD starts at {first * 1000:.0f} ms")
fig, ax = plt.subplots(figsize=(6, 2.5))
ax.plot(bins[:-1] * 1000, rate); ax.axvline(0, color="k", lw=0.5)
ax.set_xlabel("time from stimulus onset (ms)"); ax.set_ylabel("spikes/s"); ax.set_title(f"{len(aud)} auditory units, range {rate.min():.1f} to {rate.max():.1f}")
plt.show()
database built in 9 s: 287 auditory units, 11706 KDE rows in the PCA
auditory units per bird: {'ZF4F': 103, 'ZF5M': 84, 'ZF6M': 42, 'ZF7F': 58}
of the paper's good units held by the dataset, 91 of 91 are auditory here
  and 91 of them have all 110 stimuli
mean rate before onset 6.77 spikes/s, 20 to 100 ms after onset 15.28 spikes/s; first 10 ms bin above baseline + 5 SD starts at 0 ms
No description has been provided for this image

Result: partially reproduced (paper-good-units-link). 91 of the 100 good units the paper's code lists are in the dataset under the same site and pickle name, and all 91 are auditory with all 110 stimuli here. The other 9 come from a site folder named ZF4F_2t_190613_101015.old; the dataset's site ZF4F_2t_190613_101015 holds 18 pickles, none with those names (they are listed, with their electrodes, in the good-units-100 section). The 91 held by the dataset are 34 of ZF4F, 19 of ZF5M, 16 of ZF6M and 22 of ZF7F.

In [8]:
# Clock check by decoding: single-unit count features from [-0.5, 0) against [0, 0.5) s
rng = np.random.default_rng(101)
full_all = [x for x in aud.uid if (db["feat"][x][1] > 0).sum() == len(db["stims"])]
def count_feats(x, lo, hi):
    tr = db["trials"][x]
    u = byuid[x]
    cnt = np.array([np.sum((s >= lo) & (s < hi)) for r in aa5.voc_rows(u) for s in r["spikeTimes"]], float)
    F, C = aa5.unit_features(tr.assign(z=cnt), np.zeros((len(tr), 5)), db["stims"])
    return F, C
out = {}
for name, (lo, hi) in {"before onset [-0.5, 0)": (-0.5, 0.0), "after onset [0, 0.5)": (0.0, 0.5)}.items():
    p = []
    for x in full_all:
        F, C = count_feats(x, lo, hi)
        conf, nt = aa5.decode(F[None], C[None], db["y"], 10, rng, code="Z", cv="trial", nperm=10)
        p.append(aa5.pcc_code(conf, nt))
    out[name] = np.array(p)
    print(f"{name}: mean single-unit PCC {np.mean(p):.2f}% over {len(p)} units (chance 10%), t vs 10 = {stats.ttest_1samp(p, 10).statistic:.2f}")
before onset [-0.5, 0): mean single-unit PCC 9.89% over 187 units (chance 10%), t vs 10 = -2.83
after onset [0, 0.5): mean single-unit PCC 10.85% over 187 units (chance 10%), t vs 10 = 10.60
In [9]:
# The stored spikeKDE against a Gaussian KDE of the spike times (STAR Methods, PC analysis: "Gaussian
# kernels of 30 ms"), on 3 stimuli of each of 60 random auditory units (aa5.kde_check)
rng = np.random.default_rng(102)
recs = []
for x in rng.choice(list(aud.uid), 60, replace=False):
    for r in [r for r in aa5.voc_rows(byuid[x]) if r["nTrials"] >= aa5.MIN_TRIALS_KDE][:3]:
        if sum(len(s) for s in r["spikeTimes"]) >= 10:
            kq = aa5.kde_check(r)
            recs.append(dict(nTrials=r["nTrials"], scale=kq.pop("scale"), **{f"r_{round(k * 1000)}ms": v for k, v in kq.items()}))
kc = pd.DataFrame(recs)
rcols = [c for c in kc if c.startswith("r_")]
print(f"{len(kc)} stimulus rows; median correlation with the stored KDE by kernel SD:", kc[rcols].median().round(4).to_dict())
print("kernel SD of highest correlation, rows per SD:", kc[rcols].idxmax(axis=1).value_counts().to_dict())
print(f"30 ms: correlation above 0.99 in {(kc.r_30ms > 0.99).sum()} of {len(kc)} rows, range {kc.r_30ms.min():.3f} to {kc.r_30ms.max():.3f}")
print("stored KDE over the trial-averaged 30 ms KDE (scale), median by number of trials:", kc.groupby("nTrials").scale.median().round(3).to_dict())
# kde_matrix sets a row to zero when the stimulus has no spikes; the earlier test (sum of spike times == 0) would also have zeroed rows with spikes
n_old = sum(1 for x in aud.uid for r in aa5.voc_rows(byuid[x]) if r["nTrials"] >= aa5.MIN_TRIALS_KDE
            and sum(len(s) for s in r["spikeTimes"]) and not np.sum(np.concatenate(r["spikeTimes"])))
n_zero = sum(1 for x in aud.uid for r in aa5.voc_rows(byuid[x]) if r["nTrials"] >= aa5.MIN_TRIALS_KDE and not sum(len(s) for s in r["spikeTimes"]))
print(f"KDE rows of stimuli with no spikes (set to zero): {n_zero}; rows with spikes whose spike times sum to 0: {n_old}")
114 stimulus rows; median correlation with the stored KDE by kernel SD: {'r_10ms': 0.8309, 'r_20ms': 0.9726, 'r_30ms': 1.0, 'r_50ms': 0.9489}
kernel SD of highest correlation, rows per SD: {'r_30ms': 107, 'r_20ms': 4, 'r_10ms': 2}
30 ms: correlation above 0.99 in 107 of 114 rows, range 0.840 to 1.000
stored KDE over the trial-averaged 30 ms KDE (scale), median by number of trials: {5: 1.003, 6: 1.204, 7: 1.403, 8: 1.605, 9: 1.808, 10: 2.014, 15: 3.008}
KDE rows of stimuli with no spikes (set to zero): 1; rows with spikes whose spike times sum to 0: 0
/tmp/ipykernel_2337/989979373.py:13: FutureWarning: The behavior of DataFrame.idxmax with all-NA values, or any-NA and skipna=False, is deprecated. In a future version this will raise ValueError
  print("kernel SD of highest correlation, rows per SD:", kc[rcols].idxmax(axis=1).value_counts().to_dict())

stimulus-set-link¶

The dataset holds the awake playback experiment the paper describes, four birds (ZF4F, ZF5M, ZF6M, ZF7F) and 110 distinct stimuli labelled with the 10 call types in the paper's numbers.

In [10]:
paper_counts = dict(Be=12, LT=13, Th=5, Di=5, Ag=9, Wh=13, Ne=15, Te=15, DC=14, So=9)
got = voc.call.value_counts().to_dict()
tab = pd.DataFrame({"paper": paper_counts, "dataset": {k: got.get(k, 0) for k in paper_counts}})
tab["diff"] = tab.dataset - tab.paper
print(tab.T)
birds = sorted(ut.bird.unique())
print("birds:", birds, len(birds), "; distinct vocalization stimuli:", len(voc))
print("labels in the files not in the paper's list:", sorted(set(got) - set(paper_counts)))
         Be  LT  Th  Di  Ag  Wh  Ne  Te  DC  So
paper    12  13   5   5   9  13  15  15  14   9
dataset  12  13   5   5   9  13  15  15  14   9
diff      0   0   0   0   0   0   0   0   0   0
birds: ['ZF4F', 'ZF5M', 'ZF6M', 'ZF7F'] 4 ; distinct vocalization stimuli: 110
labels in the files not in the paper's list: []

Result: reproduced. The files hold 4 birds and 110 distinct vocalization stimuli whose call-type counts equal the paper's for all 10 types (every difference is 0). The stimulus waveform of each stimulus is the same in every unit that heard it.

auditory-units¶

Of 730 spike-sorted units in the awake dataset, 292 (40.1%) were auditory.

Auditory test as C1, on the spike-count difference over all trials of the pickle (song and vocalizations; GenerateReport.ipynb calc_zscore_all), Methods reading (one-sample t-test, n - 1 df) and the code's (n df). Denominators: (a) units with SNR above 5, (b) all units the dataset holds, counted three ways: every pickle, every non-empty pickle, every pickle with vocalization trials (the code's summary keeps only these: if ncalls == 0: continue).

In [11]:
voc_u = ut[ut.n_calls > 0]
rows = []
for test in ["p_methods", "p_code"]:
    n_aud = int(((voc_u.snr >= 5) & (voc_u[test] <= 0.01)).sum())
    for name, den in [("(a) SNR above 5, with vocalization trials", int((voc_u.snr >= 5).sum())),
                      ("(a') SNR above 5, all pickles", int((ut.snr >= 5).sum())),
                      ("(b) all pickles", len(ut)),
                      ("(b) non-empty pickles", int((ut.n_trials_all > 0).sum())),
                      ("(b) pickles with vocalization trials", len(voc_u))]:
        rows.append(dict(test=test, denominator=name, total=den, auditory=n_aud, fraction=100 * n_aud / den))
res_aud = pd.DataFrame(rows)
print(res_aud.round(2).to_string(index=False))
print("auditory units among SNR >= 5 units with vocalization trials, by bird:",
      voc_u[(voc_u.snr >= 5) & (voc_u.p_methods <= 0.01)].groupby("bird").size().to_dict())
print("auditory test on all units regardless of SNR (vocalization pickles):", int((voc_u.p_methods <= 0.01).sum()))
     test                               denominator  total  auditory  fraction
p_methods (a) SNR above 5, with vocalization trials    414       287     69.32
p_methods             (a') SNR above 5, all pickles    491       287     58.45
p_methods                           (b) all pickles    872       287     32.91
p_methods                     (b) non-empty pickles    838       287     34.25
p_methods      (b) pickles with vocalization trials    726       287     39.53
   p_code (a) SNR above 5, with vocalization trials    414       287     69.32
   p_code             (a') SNR above 5, all pickles    491       287     58.45
   p_code                           (b) all pickles    872       287     32.91
   p_code                     (b) non-empty pickles    838       287     34.25
   p_code      (b) pickles with vocalization trials    726       287     39.53
auditory units among SNR >= 5 units with vocalization trials, by bird: {'ZF4F': 103, 'ZF5M': 84, 'ZF6M': 42, 'ZF7F': 58}
auditory test on all units regardless of SNR (vocalization pickles): 433

Result: reproduced. 287 units are auditory under both the Methods' and the code's t-test (paper 292, tolerance 29.2). With the denominator read as the units the dataset holds with vocalization trials, the total is 726 (paper 730) and the fraction 39.5% (paper 40.1%), both within tolerance; every pickle (872) or every non-empty pickle (838) is outside the 730 +- 73 tolerance, and the SNR reading (a) gives 414 units, a fraction of 69%.

inhibited-units¶

In the awake dataset 46 of the 292 auditory units (15.7%) were inhibited by sound.

In [12]:
a = aud
n_inh = int((a.meanD < 0).sum())
print(f"inhibited (mean d < 0): {n_inh} of {len(a)} = {100 * n_inh / len(a):.1f}%  (paper 46 of 292 = 15.7%)")
print("by bird:", a[a.meanD < 0].groupby("bird").size().to_dict())
inhibited (mean d < 0): 47 of 287 = 16.4%  (paper 46 of 292 = 15.7%)
by bird: {'ZF4F': 5, 'ZF5M': 29, 'ZF6M': 2, 'ZF7F': 11}

Result: reproduced. 47 of the 287 auditory units (16.4%) have a negative mean spike-count difference, within the tolerances of 46 +- 4.6 and 15.7 +- 1.57%.

table1-snr¶

The awake units have a mean spike SNR of 7.42 (SD 2.52; quartiles 5.51, 6.50, 9.03).

In [13]:
for name, s in [("(a) auditory units", aud.snr), ("(b) units with SNR above 5 and vocalization trials", voc_u.snr[voc_u.snr >= 5]),
                ("(b') all units with SNR above 5", ut.snr[ut.snr >= 5])]:
    q = s.quantile([0.25, 0.5, 0.75]).to_numpy()
    print(f"{name}: n = {len(s)}, mean {s.mean():.2f}, SD {s.std():.2f}, quartiles {q[0]:.2f}, {q[1]:.2f}, {q[2]:.2f}")
print("paper: mean 7.42 (tolerance 0.742), median 6.50 (tolerance 0.65)")
(a) auditory units: n = 287, mean 6.84, SD 1.99, quartiles 5.37, 6.07, 7.65
(b) units with SNR above 5 and vocalization trials: n = 414, mean 6.97, SD 2.09, quartiles 5.41, 6.20, 7.90
(b') all units with SNR above 5: n = 491, mean 6.99, SD 2.14, quartiles 5.41, 6.21, 7.93
paper: mean 7.42 (tolerance 0.742), median 6.50 (tolerance 0.65)

Result: reproduced. The auditory units have a mean SNR of 6.84 and a median of 6.07, both inside the tolerances (6.68 to 8.16 and 5.85 to 7.15); under reading (b) the mean is 6.97 and the median 6.20. In every reading both values sit below the paper's, and the upper quartile (7.6 to 7.9) is well below its 9.03.

pcs-variance¶

The first five principal components of the time-varying responses explain about 90% of their variance.

In [14]:
evr = db["pca"].explained_variance_ratio_
print("explained variance ratio, PCs 1 to 10:", np.round(evr, 4))
print(f"cumulative, first 5 PCs: {evr[:5].sum():.4f}  (paper about 0.90, tolerance 0.09; the code printed 0.922)")
print("KDE rows (unit x stimulus with >= 5 trials):", db["n_kde_rows"])
explained variance ratio, PCs 1 to 10: [0.7541 0.0609 0.052  0.0335 0.0238 0.015  0.0111 0.0098 0.0081 0.0066]
cumulative, first 5 PCs: 0.9244  (paper about 0.90, tolerance 0.09; the code printed 0.922)
KDE rows (unit x stimulus with >= 5 trials): 11706

Result: reproduced. The first five PCs explain 92.4% of the variance of the trial-averaged responses (the code printed 92.2%).

fig3c-peak-call-types¶

Across the 292 auditory units, distress calls had the highest average response strength followed by song; 51 units had their peak response to distress calls and 61 to song; the preference is biased toward the longer calls (Ag, Be, So, Di).

zCT under the two readings of C3: (a) mean trial Z per call type; (b) the code's mean(d)/sd(d).

In [15]:
za_list, zb_list = [], []
for x in aud.uid:
    za, zb = aa5.zct_unit(byuid[x], db["trials"][x])
    za_list.append(za); zb_list.append(zb)
ZA = pd.DataFrame(za_list, index=aud.uid)[aa5.CALL_TYPES]
ZB = pd.DataFrame(zb_list, index=aud.uid)[aa5.CALL_TYPES]
fig3 = {}
for name, Z in [("(a) mean trial Z", ZA), ("(b) code zCT", ZB)]:
    m = Z.mean().sort_values(ascending=False)
    peaks = Z.idxmax(axis=1).value_counts().reindex(aa5.CALL_TYPES, fill_value=0).sort_values(ascending=False)
    fig3[name] = (m, peaks)
    print(name)
    print("  mean zCT by call type, ranked:", m.round(3).to_dict())
    print("  peak units by call type:", peaks.to_dict(), " units with missing types:", int(Z.isna().any(axis=1).sum()))
    print("  top five by peak units:", list(peaks.index[:5]), "; Ag, Be, So, Di among them:", sum(c in peaks.index[:5] for c in ["Ag", "Be", "So", "Di"]))
    for b, g in Z.groupby(aud.set_index("uid").bird):
        print(f"   {b}: n={len(g)}, top mean {g.mean().idxmax()}, peaks Di {int((g.idxmax(axis=1) == 'Di').sum())}, So {int((g.idxmax(axis=1) == 'So').sum())}")
print("paper: Di first, So second; peaks Di 51 (tolerance 5.1), So 61 (6.1)")
(a) mean trial Z
  mean zCT by call type, ranked: {'So': 0.591, 'Ag': 0.573, 'Di': 0.527, 'Be': 0.441, 'DC': 0.403, 'Wh': 0.377, 'Th': 0.251, 'LT': 0.25, 'Ne': 0.232, 'Te': 0.161}
  peak units by call type: {'So': 71, 'Ag': 57, 'Di': 57, 'Be': 32, 'Th': 22, 'DC': 22, 'Wh': 13, 'LT': 6, 'Ne': 4, 'Te': 3}  units with missing types: 4
  top five by peak units: ['So', 'Ag', 'Di', 'Be', 'Th'] ; Ag, Be, So, Di among them: 4
   ZF4F: n=103, top mean Ag, peaks Di 24, So 24
   ZF5M: n=84, top mean So, peaks Di 13, So 22
   ZF6M: n=42, top mean Ag, peaks Di 8, So 12
   ZF7F: n=58, top mean Di, peaks Di 12, So 13
(b) code zCT
  mean zCT by call type, ranked: {'Di': 0.623, 'So': 0.564, 'Ag': 0.546, 'Be': 0.454, 'DC': 0.431, 'Wh': 0.403, 'Th': 0.335, 'LT': 0.303, 'Ne': 0.283, 'Te': 0.197}
  peak units by call type: {'So': 58, 'Ag': 54, 'Di': 53, 'Be': 36, 'Th': 31, 'DC': 28, 'Wh': 10, 'LT': 10, 'Ne': 4, 'Te': 3}  units with missing types: 4
  top five by peak units: ['So', 'Ag', 'Di', 'Be', 'Th'] ; Ag, Be, So, Di among them: 4
   ZF4F: n=103, top mean Di, peaks Di 26, So 18
   ZF5M: n=84, top mean So, peaks Di 10, So 18
   ZF6M: n=42, top mean Ag, peaks Di 9, So 6
   ZF7F: n=58, top mean Di, peaks Di 8, So 16
paper: Di first, So second; peaks Di 51 (tolerance 5.1), So 61 (6.1)

Result: reproduced, under the code's zCT (reading b), adopted as an assumption. With the code's zCT, which is what Figure 3C plots (SummaryStatistics.ipynb, cells 11 and 15, reads zcall from summarySel.pkl), Di has the highest mean (0.623) and So the second (0.564); 53 units peak on Di and 58 on So (paper 51 and 61, both within tolerance); the five call types with the most peak units are So, Ag, Di, Be and Th, which include Ag, Be, So and Di. Under the Methods' reading (a), So ranks first (0.591), Ag second and Di third, and the So peak count (71) is outside tolerance: the claim would not be reproduced under that reading.

fig4a-unit-z-vs-zt¶

For single units decoded independently, adding the temporal pattern (Z + T) to the response strength (Z) raises the mean PCC from 10.78% to 12.3% (a 14% increase), over 191 units with data for all 110 calls.

Units: auditory units with all 110 vocalization stimuli (code: nstimsUnit == 110). Readings of C5: (a) the Methods, one exemplar per call type held out, PCC as the mean diagonal of the row-normalized matrix; (b) the code, one random trial per stimulus held out, PCC as trace over test trials, with one repetition (the single-unit notebook) and with 100.

In [16]:
full = full_all
n_ge2 = sum((db["feat"][x][1] >= 2).all() for x in full)
print(f"auditory units with all 110 stimuli: {len(full)} (paper 191); of these with >= 2 trials of every stimulus: {n_ge2}")
single = {}
readings = {"(a) exemplar, PCC_a": ("exemplar", 1, "pcc_methods"), "(b) trial, 1 rep, PCC_b": ("trial", 1, "pcc_code"),
            "(b) trial, 100 reps, PCC_b": ("trial", 100, "pcc_code")}
seed = 4000
for name, (cv, nperm, m) in readings.items():
    for cd in ["Z", "ZT"]:
        seed += 1
        single[(name, cd)] = aa5.run_ensembles(db, [[x] for x in full], code=cd, cv=cv, nperm=nperm, seed=seed)
rows = []
for name, (cv, nperm, m) in readings.items():
    z, zt = single[(name, "Z")][m], single[(name, "ZT")][m]
    t = stats.ttest_rel(zt, z)
    rows.append(dict(reading=name, n=len(z), PCC_Z=z.mean(), PCC_ZT=zt.mean(), increase_pct=100 * (zt.mean() / z.mean() - 1),
                     t=t.statistic, df=len(z) - 1, p=t.pvalue))
fig4a = pd.DataFrame(rows)
print(fig4a.round(4).to_string(index=False))
print("paper: Z 10.78 (tol 1.078), Z+T 12.3 (tol 1.23), t(190) = 10.06, p < 1e-5")
bird_of = aud.set_index("uid").bird
for name, (cv, nperm, m) in readings.items():
    d = pd.DataFrame({"Z": single[(name, "Z")][m], "ZT": single[(name, "ZT")][m]}, index=full)
    print(name, "by bird:", d.groupby(bird_of.loc[full].values).mean().round(2).to_dict("index"))
auditory units with all 110 stimuli: 187 (paper 191); of these with >= 2 trials of every stimulus: 125
                   reading   n   PCC_Z  PCC_ZT  increase_pct       t  df   p
       (a) exemplar, PCC_a 187 10.6770 12.0508       12.8678  7.1738 186 0.0
   (b) trial, 1 rep, PCC_b 187 10.7528 12.1666       13.1485  8.9863 186 0.0
(b) trial, 100 reps, PCC_b 187 10.7578 12.2675       14.0343 12.3040 186 0.0
paper: Z 10.78 (tol 1.078), Z+T 12.3 (tol 1.23), t(190) = 10.06, p < 1e-5
(a) exemplar, PCC_a by bird: {'ZF4F': {'Z': 10.85, 'ZT': 13.0}, 'ZF5M': {'Z': 10.65, 'ZT': 12.31}, 'ZF6M': {'Z': 10.34, 'ZT': 11.21}, 'ZF7F': {'Z': 10.69, 'ZT': 11.22}}
(b) trial, 1 rep, PCC_b by bird: {'ZF4F': {'Z': 11.04, 'ZT': 13.14}, 'ZF5M': {'Z': 10.67, 'ZT': 11.66}, 'ZF6M': {'Z': 10.38, 'ZT': 11.67}, 'ZF7F': {'Z': 10.72, 'ZT': 11.85}}
(b) trial, 100 reps, PCC_b by bird: {'ZF4F': {'Z': 11.04, 'ZT': 13.28}, 'ZF5M': {'Z': 10.66, 'ZT': 11.9}, 'ZF6M': {'Z': 10.43, 'ZT': 11.53}, 'ZF7F': {'Z': 10.72, 'ZT': 11.91}}
In [17]:
# Variant: the Methods' unit rule, all 110 stimuli with at least 2 trials of each. Each unit is decoded alone,
# so these are the same decodings restricted to those units.
full2 = [j for j, x in enumerate(full) if (db["feat"][x][1] >= 2).all()]
rows = []
for name, (cv, nperm, m) in readings.items():
    z, zt = single[(name, "Z")][m][full2], single[(name, "ZT")][m][full2]
    t = stats.ttest_rel(zt, z)
    rows.append(dict(reading=name, n=len(z), PCC_Z=z.mean(), PCC_ZT=zt.mean(), increase_pct=100 * (zt.mean() / z.mean() - 1),
                     t=t.statistic, df=len(z) - 1, p=t.pvalue))
print("units with >= 2 trials of every stimulus (Methods):")
print(pd.DataFrame(rows).round(4).to_string(index=False))
units with >= 2 trials of every stimulus (Methods):
                   reading   n   PCC_Z  PCC_ZT  increase_pct       t  df   p
       (a) exemplar, PCC_a 125 10.7455 12.3009       14.4752  6.8422 124 0.0
   (b) trial, 1 rep, PCC_b 125 10.8002 12.3962       14.7769  8.1642 124 0.0
(b) trial, 100 reps, PCC_b 125 10.8155 12.4692       15.2898 10.3553 124 0.0

Result: reproduced. 187 units have all 110 stimuli (paper 191). Under every reading Z+T beats Z by a paired t-test with p far below 1e-5, and both means are within tolerance: Methods reading 10.7% and 12.0%, code reading 10.8% and 12.2 to 12.3%. With the Methods' unit rule (at least 2 trials of every stimulus, 125 units) the means are 10.7 to 10.8% and 12.3 to 12.5%, also within tolerance, with t(124) = 6.84 to 10.36; the 187 of the code's rule are closer to the paper's 191.

good-units-100¶

Exactly 100 units had a single-unit PCC Z+T above 12%, and they came from all four birds (ZF4F 43, ZF5M 19, ZF6M 16, ZF7F 22).

The count comes from one run, as the code; the range over 10 runs with other seeds is shown. The good-unit set of each reading feeds the ensemble analyses of the same reading.

In [18]:
bird_n = lambda us: pd.Series([bird_of.loc[x] for x in us]).value_counts().reindex(sorted(set(bird_of)), fill_value=0).to_dict()
good = {}
for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    cv, nperm, m = readings[name]
    p = single[(name, "ZT")][m]
    good[name] = [x for x, v in zip(full, p) if v > 12]
    reps, rep_birds = [], []
    for s in range(10):
        r = aa5.run_ensembles(db, [[x] for x in full], code="ZT", cv=cv, nperm=1, seed=5000 + s)
        g_s = [x for x, v in zip(full, r[m]) if v > 12]
        reps.append(len(g_s)); rep_birds.append(bird_n(g_s))
    print(f"{name}: {len(good[name])} good units; by bird {bird_n(good[name])}; "
          f"over 10 other seeds {min(reps)} to {max(reps)} (mean {np.mean(reps):.1f}; within 90 to 110: {sum(90 <= r <= 110 for r in reps)} of 10)")
    rb = pd.DataFrame(rep_birds, index=[f"seed {5000 + s}" for s in range(10)]); rb["total"] = reps
    print(rb.T.to_string())
    print(f"   of the {len(in_ds)} paper good units in the dataset, {sum(n in set(good[name]) for n in in_ds)} are good here; "
          f"by bird {bird_n([n for n in in_ds if n in set(good[name])])}")
p100 = single[("(b) trial, 100 reps, PCC_b", "ZT")]["pcc_code"]
g100 = [x for x, v in zip(full, p100) if v > 12]
print("(b) with 100 repetitions:", len(g100), "good units; by bird", bird_n(g100))
print("the paper's 100 listed good units by bird:", pd.Series([n.split("_")[0] for n in paper_good]).value_counts().sort_index().to_dict(),
      "; the 91 the dataset holds:", bird_n(in_ds))
print("paper: 100 (tol 10); ZF4F 43 (4.3), ZF5M 19 (1.9), ZF6M 16 (1.6), ZF7F 22 (2.2)")
(a) exemplar, PCC_a: 77 good units; by bird {'ZF4F': 30, 'ZF5M': 24, 'ZF6M': 9, 'ZF7F': 14}; over 10 other seeds 70 to 94 (mean 80.1; within 90 to 110: 1 of 10)
       seed 5000  seed 5001  seed 5002  seed 5003  seed 5004  seed 5005  seed 5006  seed 5007  seed 5008  seed 5009
ZF4F          31         32         34         26         37         36         36         28         35         36
ZF5M          17         19         23         22         24         14         17         19         17         18
ZF6M          11         10          7          8         16          8         11         11          9          9
ZF7F          20         23         20         14         17         19         16         16         18         17
total         79         84         84         70         94         77         80         74         79         80
   of the 91 paper good units in the dataset, 51 are good here; by bird {'ZF4F': 23, 'ZF5M': 11, 'ZF6M': 6, 'ZF7F': 11}
(b) trial, 1 rep, PCC_b: 89 good units; by bird {'ZF4F': 39, 'ZF5M': 20, 'ZF6M': 10, 'ZF7F': 20}; over 10 other seeds 87 to 101 (mean 93.0; within 90 to 110: 8 of 10)
       seed 5000  seed 5001  seed 5002  seed 5003  seed 5004  seed 5005  seed 5006  seed 5007  seed 5008  seed 5009
ZF4F          44         40         39         40         44         41         36         40         36         38
ZF5M          21         24         20         25         19         25         23         18         23         19
ZF6M          11         11         14          8         11         13         12         10         11         13
ZF7F          19         21         22         20         17         22         23         20         20         17
total         95         96         95         93         91        101         94         88         90         87
   of the 91 paper good units in the dataset, 70 are good here; by bird {'ZF4F': 29, 'ZF5M': 14, 'ZF6M': 9, 'ZF7F': 18}
(b) with 100 repetitions: 91 good units; by bird {'ZF4F': 42, 'ZF5M': 21, 'ZF6M': 10, 'ZF7F': 18}
the paper's 100 listed good units by bird: {'ZF4F': 43, 'ZF5M': 19, 'ZF6M': 16, 'ZF7F': 22} ; the 91 the dataset holds: {'ZF4F': 34, 'ZF5M': 19, 'ZF6M': 16, 'ZF7F': 22}
paper: 100 (tol 10); ZF4F 43 (4.3), ZF5M 19 (1.9), ZF6M 16 (1.6), ZF7F 22 (2.2)
In [19]:
# The 9 listed units of ZF4F_2t_190613_101015.old, with the single-unit PCC the code printed, and the 18 pickles the
# dataset holds for ZF4F_2t_190613_101015, with this attempt's single-unit PCC Z+T (code reading, one repetition).
# Matching them by spike train is not possible: the .old sorting is not deposited.
print("listed, missing:", {n.split("_goodPlayback-")[1]: float(paper_good[n]) for n in missing})
pb = dict(zip(full, single[("(b) trial, 1 rep, PCC_b", "ZT")]["pcc_code"]))
site18 = ut[ut.site == "ZF4F_2t_190613_101015"][["uid", "electrode", "snr", "p_code", "n_voc_stim"]].copy()
site18["auditory"] = site18.uid.isin(set(aud.uid)); site18["PCC_ZT_b"] = site18.uid.map(pb)
site18["uid"] = site18.uid.str.split("_goodPlayback-").str[1]
print(site18.round(3).to_string(index=False))
print("electrodes of the missing units:", sorted({n.split("-e")[1].split("-")[0] for n in missing}),
      "; of the dataset's pickles there:", sorted(set(site18.electrode)))
listed, missing: {'e11-c62.pkl': 17.741038436633367, 'e19-c60.pkl': 15.998596064371162, 'e16-c63.pkl': 15.215760876073531, 'e8-c42.pkl': 13.589663330602757, 'e16-c52.pkl': 13.58622182537735, 'e11-c65.pkl': 13.489246122948048, 'e8-c43.pkl': 13.420430889404797, 'e20-c136.pkl': 13.062118746235765, 'e20-c134.pkl': 12.960004493482968}
        uid electrode    snr  p_code  n_voc_stim  auditory  PCC_ZT_b
e20-c62.pkl        20  9.750   0.129         107     False       NaN
 e8-c11.pkl         8  4.709   0.000         110     False       NaN
 e10-c1.pkl        10  4.536   0.000         110     False       NaN
e11-c34.pkl        11  4.733   0.000         110     False       NaN
e16-c36.pkl        16  4.906   0.000         110     False       NaN
 e17-c8.pkl        17  4.731   0.000         110     False       NaN
  e8-c8.pkl         8  5.973   0.000         110      True    12.884
e11-c33.pkl        11 11.519   0.000         110      True    13.405
e16-c35.pkl        16  5.864   0.000         110      True     8.322
e20-c61.pkl        20  9.155   0.000         110      True    12.289
e20-c63.pkl        20  5.247   0.000         110      True    13.033
 e21-c0.pkl        21  4.272   0.113         110     False       NaN
e19-c49.pkl        19  3.310   0.000         110     False       NaN
 e18-c1.pkl        18  4.900   0.000         110     False       NaN
  e9-c1.pkl         9  4.914   0.000         110     False       NaN
e19-c46.pkl        19  7.541   0.000         110      True    13.455
e16-c33.pkl        16  8.209   0.001         110      True    12.821
 e22-c2.pkl        22  4.475   0.676         110     False       NaN
electrodes of the missing units: ['11', '16', '19', '20', '8'] ; of the dataset's pickles there: ['10', '11', '16', '17', '18', '19', '20', '21', '22', '8', '9']

Result: not reproduced. One run of the code's reading gives 89 units with single-unit PCC Z+T above 12%, one below the tolerance (90 to 110); the Methods' reading gives 77. Every bird contributes units. The count depends on the random held-out draw: over 10 other seeds the code's reading gives 87 to 101 (8 of 10 within tolerance) and 100 repetitions give 91; the Methods' reading gives 70 to 94 (1 of 10). Per bird (code reading) ZF4F 39, ZF5M 20 and ZF7F 20 are within their tolerances and ZF6M 10 is not (paper 16); over the 10 other seeds ZF6M has 8 to 14 good units, never within 16 +- 1.6. Of the paper's 100 listed good units, 91 are in the dataset (ZF4F 34, ZF5M 19, ZF6M 16, ZF7F 22) and 70 of them are good here (29, 14, 9 and 18), so the shortfall in ZF6M comes from listed units that fall below 12% here, while the 9 listed units absent from the dataset are all of ZF4F.

fig4b-ensemble-20¶

Ensemble decoding performance rises with ensemble size, reaching an average PCC Z+T of 42% for 20 units, above the 29.6% obtained from response strength alone (Z), a 43% increase.

Ensembles as C7: all single units and pairs, 10,000 random draws for sizes 3, 4, 5, 10, 15 and 20 (code), each decoded once (the Methods: "a single leave-one-out per call-type"; the code ran 100 repetitions, which changes the spread of single-ensemble values but not their mean). C8 t-test with df 2 neff - 2.

In [20]:
SIZES = [1, 2, 3, 4, 5, 10, 15, 20]
N_RAND = 10000
ens4b, res4b = {}, {}
seed = 6000
for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    cv, nperm, m = readings[name]
    g = good[name]
    rng = np.random.default_rng(6100 if name.startswith("(a)") else 6200)
    for k in SIZES:
        if k <= 2:
            e = [list(c) for c in combinations(g, k)]
        else:
            e = [list(rng.choice(g, k, replace=False)) for _ in range(N_RAND)]
        ens4b[(name, k)] = e
        for cd in ["Z", "ZT"]:
            seed += 1
            res4b[(name, k, cd)] = aa5.run_ensembles(db, e, code=cd, cv=cv, nperm=1, seed=seed)
    curve = pd.DataFrame({cd: [res4b[(name, k, cd)][m].mean() for k in SIZES] for cd in ["Z", "ZT"]}, index=SIZES)
    curve["n_ensembles"] = [len(ens4b[(name, k)]) for k in SIZES]
    print(name, f"({len(g)} good units)")
    print(curve.round(2).T)
    zt, z = res4b[(name, 20, "ZT")][m], res4b[(name, 20, "Z")][m]
    t, df, p = aa5.corrected_ttest(zt, z, len(g), 20)
    print(f"  size 20: Z+T {zt.mean():.2f}, Z {z.mean():.2f}, increase {100 * (zt.mean() / z.mean() - 1):.0f}%; corrected t({df}) = {t:.2f}, p = {p:.2g}")
    print("  Z+T rises at every step:", bool(np.all(np.diff(curve.ZT) > 0)))
print("paper: Z+T 42.3 (tol 4.23), Z 29.6 (tol 2.96), t(160) = 8.83, p < 1e-5")
print(f"elapsed so far {(time.time() - T_START) / 60:.1f} min")
(a) exemplar, PCC_a (77 good units)
                1        2         3         4         5         10        15       20
Z            11.01    11.98     12.91     13.84     14.65     18.51     21.55     24.1
ZT           12.93    15.24     17.16     18.76     20.05     25.45     29.25     32.0
n_ensembles  77.00  2926.00  10000.00  10000.00  10000.00  10000.00  10000.00  10000.0
  size 20: Z+T 32.00, Z 24.10, increase 33%; corrected t(114) = 5.79, p = 6.3e-08
  Z+T rises at every step: True
(b) trial, 1 rep, PCC_b (89 good units)
                1        2         3         4         5         10        15        20
Z            11.24    12.55     13.81     15.04     16.20     21.69     26.41     30.36
ZT           13.92    17.32     20.20     22.67     24.77     32.80     38.61     43.15
n_ensembles  89.00  3916.00  10000.00  10000.00  10000.00  10000.00  10000.00  10000.00
  size 20: Z+T 43.15, Z 30.36, increase 42%; corrected t(138) = 9.53, p = 7.5e-17
  Z+T rises at every step: True
paper: Z+T 42.3 (tol 4.23), Z 29.6 (tol 2.96), t(160) = 8.83, p < 1e-5
elapsed so far 20.1 min
In [21]:
# Variant: the code's 100 repetitions, on 500 of the 10,000 size-20 ensembles (reading b)
name = "(b) trial, 1 rep, PCC_b"
sub = ens4b[(name, 20)][:500]
v = {cd: aa5.run_ensembles(db, sub, code=cd, cv="trial", nperm=100, seed=6900 + i)["pcc_code"] for i, cd in enumerate(["Z", "ZT"])}
print(f"500 ensembles, 100 repetitions: Z+T {v['ZT'].mean():.2f}, Z {v['Z'].mean():.2f}; one repetition on the same ensembles: "
      f"Z+T {res4b[(name, 20, 'ZT')]['pcc_code'][:500].mean():.2f}, Z {res4b[(name, 20, 'Z')]['pcc_code'][:500].mean():.2f}")
print(f"SD over ensembles, Z+T: 100 reps {v['ZT'].std():.2f}, 1 rep {res4b[(name, 20, 'ZT')]['pcc_code'][:500].std():.2f}")
# Variant: ensembles drawn from the paper's own good units that the dataset holds (code reading)
rng = np.random.default_rng(6950)
e = [list(rng.choice(in_ds, 20, replace=False)) for _ in range(N_RAND)]
vp = {cd: aa5.run_ensembles(db, e, code=cd, cv="trial", nperm=1, seed=6960 + i)["pcc_code"] for i, cd in enumerate(["Z", "ZT"])}
t, df, p = aa5.corrected_ttest(vp["ZT"], vp["Z"], len(in_ds), 20)
print(f"{N_RAND} ensembles of 20 from the paper's {len(in_ds)} listed good units: Z+T {vp['ZT'].mean():.2f}, Z {vp['Z'].mean():.2f}; t({df}) = {t:.2f}, p = {p:.2g}")
500 ensembles, 100 repetitions: Z+T 43.09, Z 30.45; one repetition on the same ensembles: Z+T 43.46, Z 30.38
SD over ensembles, Z+T: 100 reps 4.77, 1 rep 7.66
10000 ensembles of 20 from the paper's 91 listed good units: Z+T 40.67, Z 29.44; t(142) = 7.06, p = 6.9e-11
In [22]:
# What the two cross-validations measure, on synthetic ensembles of 20 units with 10 trials of each of the 110
# stimuli: each unit responds with a mean specific to the exemplar (SD 1) and no call-type signal, trial noise SD 1.
rng = np.random.default_rng(6990)
S = len(db["stims"])
syn = {"trial": [], "exemplar": []}
for _ in range(200):
    mu = rng.normal(size=(20, S, 1, 6))
    F = mu + rng.normal(size=(20, S, 10, 6)); Cn = np.full((20, S), 10)
    for cv in syn:
        conf, nt = aa5.decode(F, Cn, db["y"], 10, rng, code="ZT", cv=cv, nperm=1)
        syn[cv].append(aa5.pcc_code(conf, nt))
print("synthetic exemplar-only signal, mean PCC over 200 ensembles: " +
      ", ".join(f"{cv} CV {np.mean(v):.1f}% (SD {np.std(v):.1f})" for cv, v in syn.items()) + "; chance 10%")
synthetic exemplar-only signal, mean PCC over 200 ensembles: trial CV 78.2% (SD 2.7), exemplar CV 9.8% (SD 3.7); chance 10%

Result: reproduced, under the code's cross-validation, adopted as an assumption. With one random trial per stimulus held out (decoders.naiveBayes), the mean PCC of ensembles of 20 is 43.2% with Z+T and 30.4% with Z (paper 42.3% and 29.6%), Z+T rises at every size from 1 to 20, and the corrected t-test gives t(138) = 9.53, p = 7.5e-17 (138 df from the 89 good units of this reading). Under the Methods' cross-validation (one exemplar per call type held out) the means are 32.0% and 24.1%, both outside tolerance, while the rise and the test hold (t(114) = 5.79): partially reproduced under that reading. 100 repetitions on 500 of the ensembles give 43.1% and 30.5%, and ensembles drawn from the paper's own 91 listed good units give 40.7% and 29.4%. The two schemes measure different things: on synthetic ensembles whose units carry only exemplar-specific responses and no call-type signal, the code's scheme gives 78.2% and the Methods' 9.8% (chance 10%), because the code's tests trials of exemplars it was trained on. The outcome rests on the assumption that the paper's values come from the code's scheme.

fig4b-top-ensembles¶

The top 10% of ensembles of 20 units reach an average PCC Z+T of about 50%, and the best ensembles approach the 65% achieved by acoustic classifiers.

The top 10% (Results) or 5% (Methods) of the size-20 ensembles by their first decoding, re-estimated with a second random held-out draw (Methods).

In [23]:
for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    cv, nperm, m = readings[name]
    first = res4b[(name, 20, "ZT")][m]
    for top in [10, 5]:
        idx = np.argsort(first)[::-1][: int(len(first) * top / 100)]
        sec = aa5.run_ensembles(db, [ens4b[(name, 20)][i] for i in idx], code="ZT", cv=cv, nperm=1, seed=7000 + top + (0 if name.startswith("(a)") else 50))[m]
        print(f"{name}, top {top}% ({len(idx)} ensembles): first draw mean {first[idx].mean():.2f}, re-estimated mean {sec.mean():.2f}, "
              f"best re-estimated {sec.max():.2f}, best first draw {first.max():.2f}")
print("paper: about 50 (tol 5); best close to 65 (read as >= 55)")
(a) exemplar, PCC_a, top 10% (1000 ensembles): first draw mean 45.42, re-estimated mean 33.96, best re-estimated 59.77, best first draw 63.05
(a) exemplar, PCC_a, top 5% (500 ensembles): first draw mean 47.89, re-estimated mean 34.45, best re-estimated 55.67, best first draw 63.05
(b) trial, 1 rep, PCC_b, top 10% (1000 ensembles): first draw mean 58.11, re-estimated mean 48.80, best re-estimated 86.42, best first draw 88.36
(b) trial, 1 rep, PCC_b, top 5% (500 ensembles): first draw mean 61.86, re-estimated mean 50.41, best re-estimated 95.02, best first draw 88.36
paper: about 50 (tol 5); best close to 65 (read as >= 55)

Result: reproduced, under the code's cross-validation (assumption). The top 10% of the size-20 ensembles, re-estimated with a second held-out draw, average 48.8% (paper about 50%, tolerance 5) and the top 5% 50.4%. The best re-estimated single draw (86.4%) overstates the best ensemble, as one draw is noisy (SD over 500 ensembles 7.7 points with one repetition against 4.8 with 100); the best of the 1,800 Figure 5 ensembles decoded with 100 repetitions is 68.4%, above the 55% the criterion reads as close to 65% (top 10% of them 52.8%). Under the Methods' cross-validation the re-estimated top-10% mean is 34.0%, outside tolerance, and the best 100-repetition ensemble 41.1%.

fig4b-confusions¶

Most ensemble misclassifications are systematic, Ne confused with Te, LT with Be, Th (Tu) with Te, and Di with Ag.

In [24]:
labels = db["labels"]
pairs = [("Ne", "Te"), ("LT", "Be"), ("Th", "Te"), ("Di", "Ag")]
for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    M = aa5.mean_confusion(res4b[(name, 20, "ZT")])
    print(name)
    print(pd.DataFrame(100 * M, index=labels, columns=labels).round(1))
    n_ok = 0
    for a_, b_ in pairs:
        i, j = labels.index(a_), labels.index(b_)
        off = [(M[i, k], labels[k]) for k in range(len(labels)) if k != i]
        order = [l for _, l in sorted(off, reverse=True)]
        rank = order.index(b_) + 1
        n_ok += rank <= 2
        print(f"  true {a_} predicted {b_}: {100 * M[i, j]:.1f}%, rank {rank} of 9 off-diagonal entries (largest: {order[0]} {100 * max(off)[0]:.1f}%)")
    print("  pairs among the two largest of their row:", n_ok, "of 4")
(a) exemplar, PCC_a
      Ag    Be    DC    Di    LT    Ne    So    Te    Th    Wh
Ag  40.1   9.8   5.9   4.7   3.0   6.2  10.2   1.0   0.8  18.4
Be   8.9  43.6   6.1   1.3  14.0   4.8   3.4   3.6   1.9  12.5
DC   5.2  10.0  35.9   4.2   8.6  10.5   4.6   9.0   3.5   8.6
Di  20.9   4.3  11.4  20.0   4.6   8.1  16.5   4.9   1.4   8.0
LT   3.7  15.4   8.1   0.9  21.6  13.7   1.7  19.1   4.1  11.7
Ne   4.3   3.9   6.6   2.2   8.0  36.3   3.4  19.3   6.3   9.7
So  11.2   6.4   7.2   5.6   1.6   6.3  52.6   1.0   0.4   7.7
Te   1.6   4.5   8.5   1.2  12.0  23.1   1.0  34.7   6.5   6.9
Th   2.2   6.6  10.5   1.4  10.8  29.8   2.0  18.2  11.3   7.2
Wh  12.9  10.4   7.9   1.3   8.7  16.6   4.1  11.8   2.2  24.0
  true Ne predicted Te: 19.3%, rank 1 of 9 off-diagonal entries (largest: Te 19.3%)
  true LT predicted Be: 15.4%, rank 2 of 9 off-diagonal entries (largest: Te 19.1%)
  true Th predicted Te: 18.2%, rank 2 of 9 off-diagonal entries (largest: Ne 29.8%)
  true Di predicted Ag: 20.9%, rank 1 of 9 off-diagonal entries (largest: Ag 20.9%)
  pairs among the two largest of their row: 4 of 4
(b) trial, 1 rep, PCC_b
      Ag    Be    DC    Di    LT    Ne    So    Te    Th    Wh
Ag  40.9   7.6   6.8   5.5   1.8   3.7   6.9   1.1   2.1  12.9
Be   7.4  58.9   4.6   1.8  10.2   3.0   1.5   2.1   1.0   9.5
DC   4.4   5.2  49.0   4.2   6.0   9.1   4.5   6.6   3.8   6.9
Di  10.9   2.7   6.6  22.7   2.5   6.8  12.4   5.7   2.2   5.3
LT   3.9  11.6   4.6   0.6  32.8  10.7   0.8  24.3   3.2   6.8
Ne   4.5   3.0   6.3   2.7   6.0  30.2   3.4  14.8   6.9   8.7
So   8.9   3.7   6.4   3.6   1.0   4.3  61.2   0.5   0.4   4.7
Te   0.6   2.2   5.0   1.9  12.6  18.2   0.4  43.2   6.3   4.9
Th   1.0   2.5  14.1   1.9   5.3  22.3   1.4  22.5  18.2   4.0
Wh   9.1   8.5   6.4   2.8   7.8  15.2   4.5  12.8   2.9  30.0
  true Ne predicted Te: 14.8%, rank 1 of 9 off-diagonal entries (largest: Te 14.8%)
  true LT predicted Be: 11.6%, rank 2 of 9 off-diagonal entries (largest: Te 24.3%)
  true Th predicted Te: 22.5%, rank 1 of 9 off-diagonal entries (largest: Te 22.5%)
  true Di predicted Ag: 10.9%, rank 2 of 9 off-diagonal entries (largest: So 12.4%)
  pairs among the two largest of their row: 4 of 4

Result: reproduced. In the mean row-normalized confusion matrix of the 10,000 ensembles of 20, each named pair is the largest or second largest off-diagonal entry of its row under both readings. Code reading: Ne as Te 14.8% (rank 1), LT as Be 11.6% (rank 2), Th as Te 22.5% (rank 1), Di as Ag 10.9% (rank 2). Methods' reading: ranks 1, 2, 2 and 1.

figs4-per-bird-and-sex¶

Decoding performance and its systematic errors are similar in every bird decoded alone, and PCC does not differ significantly between female and male birds (difference 8.3%).

Ensembles of 15 drawn within each bird from its good units: all combinations when there are at most 9,999, otherwise 10,000 random (decodingCallTypesNaiveBayesPart2-SameBird.ipynb, maxTest = 9999). The test is plotConfusionsBird.ipynb's.

In [25]:
NE = 15
def per_bird(name, units_, rng, seed0):
    cv, nperm, m = readings[name]
    g = pd.Series(units_); gb = bird_of.loc[g].values
    per = {}
    for i, b in enumerate(sorted(set(bird_of))):
        gu = list(g[gb == b])
        if len(gu) < NE:
            per[b] = dict(ns=len(gu), mean=np.nan, sd=np.nan); continue
        e = [list(c) for c in combinations(gu, NE)] if comb(len(gu), NE) <= 9999 else [list(rng.choice(gu, NE, replace=False)) for _ in range(10000)]
        r = aa5.run_ensembles(db, e, code="ZT", cv=cv, nperm=1, seed=seed0 + i)
        pc = r[m]
        sd = pc.std() * np.sqrt(len(gu) / (len(gu) - NE)) if len(gu) > NE else np.nan
        M = aa5.mean_confusion(r)
        nb = sum(sorted([(M[labels.index(a_), k], labels[k]) for k in range(10) if k != labels.index(a_)], reverse=True).index((M[labels.index(a_), labels.index(b_)], b_)) < 2 for a_, b_ in pairs)
        per[b] = dict(ns=len(gu), n_ens=len(e), mean=pc.mean(), sd=sd, pairs_top2=nb)
    P = pd.DataFrame(per).T
    print(P)
    if P["sd"].notna().all():
        n = P.ns - NE + 1
        def sexstats(b1, b2):
            mean = (n[b1] * P.loc[b1, "mean"] + n[b2] * P.loc[b2, "mean"]) / (n[b1] + n[b2])
            sd = np.sqrt((P.loc[b1, "sd"] ** 2 * (n[b1] - 1) + P.loc[b2, "sd"] ** 2 * (n[b2] - 1)) / (n[b1] + n[b2] - 2))
            return mean, sd
        mf, sf = sexstats("ZF4F", "ZF7F"); mm, sm = sexstats("ZF5M", "ZF6M")
        pooled = np.sqrt((sf ** 2 + sm ** 2) / 2)
        t = (mf - mm) / (pooled * np.sqrt(1 / 2 + 1 / 2))
        print(f"  female {mf:.2f}, male {mm:.2f}, difference {mf - mm:.2f}; t(2) = {t:.3f}, p = {2 * stats.t.sf(abs(t), 2):.3f}")
    else:
        print(f"  birds with fewer than {NE + 1} good units ({', '.join(f'{b} {int(v)}' for b, v in P.ns.items() if v <= NE)}): "
              f"ensembles of {NE} with the corrected SD (sqrt(ns/(ns - {NE}))) need at least {NE + 1}, so the test cannot be run")

for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    print(name, "good units of this attempt")
    per_bird(name, good[name], np.random.default_rng(8000 if name.startswith("(a)") else 8100), 8200 + (0 if name.startswith("(a)") else 10))
print("paper: difference 8.3 (tol 0.83), t(2) = 0.6757, p = 0.5689")
(a) exemplar, PCC_a good units of this attempt
        ns    n_ens       mean         sd  pairs_top2
ZF4F  30.0  10000.0  33.527827  10.345685         3.0
ZF5M  24.0  10000.0  26.420444  11.233582         3.0
ZF6M   9.0      NaN        NaN        NaN         NaN
ZF7F  14.0      NaN        NaN        NaN         NaN
  birds with fewer than 16 good units (ZF6M 9, ZF7F 14): ensembles of 15 with the corrected SD (sqrt(ns/(ns - 15))) need at least 16, so the test cannot be run
(b) trial, 1 rep, PCC_b good units of this attempt
        ns    n_ens       mean         sd  pairs_top2
ZF4F  39.0  10000.0  37.901838   8.953319         3.0
ZF5M  20.0  10000.0  37.407199  12.542282         3.0
ZF6M  10.0      NaN        NaN        NaN         NaN
ZF7F  20.0  10000.0  40.971053  10.720652         4.0
  birds with fewer than 16 good units (ZF6M 10): ensembles of 15 with the corrected SD (sqrt(ns/(ns - 15))) need at least 16, so the test cannot be run
paper: difference 8.3 (tol 0.83), t(2) = 0.6757, p = 0.5689
In [26]:
# Variant: the paper's own listed good units that the dataset holds (paper-good-units-link), within each bird
for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    print(name, f"the paper's {len(in_ds)} listed good units held by the dataset")
    per_bird(name, in_ds, np.random.default_rng(8300 if name.startswith("(a)") else 8400), 8500 + (0 if name.startswith("(a)") else 10))
(a) exemplar, PCC_a the paper's 91 listed good units held by the dataset
        ns    n_ens       mean         sd  pairs_top2
ZF4F  34.0  10000.0  33.789516   9.891244         4.0
ZF5M  19.0   3876.0  31.042670  16.221161         2.0
ZF6M  16.0     16.0  23.458607  19.878426         2.0
ZF7F  22.0  10000.0  31.374456  13.389679         4.0
  female 33.10, male 28.88, difference 4.22; t(2) = 0.295, p = 0.796
(b) trial, 1 rep, PCC_b the paper's 91 listed good units held by the dataset
        ns    n_ens       mean         sd  pairs_top2
ZF4F  34.0  10000.0  36.962164  12.646042         3.0
ZF5M  19.0   3876.0  35.918356  14.222377         4.0
ZF6M  16.0     16.0  22.186964  13.797258         3.0
ZF7F  22.0  10000.0  40.209232   9.556780         3.0
  female 37.89, male 32.00, difference 5.89; t(2) = 0.451, p = 0.696

Result: blocked (other: too few units under the claim's own rule). Ensembles of 15 with the corrected SD need at least 16 good units in each bird. ZF6M has 10 good units under the code's reading (9 under the Methods', where ZF7F also has 14), so the paper's test cannot be run on this attempt's good units. In the birds with more than 15, mean PCC Z+T at 15 units is 37.9% (ZF4F), 37.4% (ZF5M) and 41.0% (ZF7F) under the code's reading, and 3, 3 and 4 of the four Figure 4B error pairs are among the two largest entries of their rows. As a variant, on the paper's 91 listed good units the dataset holds (ZF4F 34, ZF5M 19, ZF6M 16, ZF7F 22), the test runs: female minus male 5.89 points, t(2) = 0.451, p = 0.696 (code reading), and 4.22, t(2) = 0.295, p = 0.796 (Methods' reading), so no sex difference, with a difference below the paper's 8.3. The link claim's criterion keeps every outcome off the listed names, so the outcome stays blocked.

Figure 5: MRFs, volume and the ensemble regressions¶

1,800 random ensembles of 20 good units, each decoded with 100 held-out repetitions (Methods), under the two cross-validation readings. MPS of the 110 stimuli (C9, both sound windows); MRFs of each good unit (six components); LDA axes (C10, both rules); volume, SI, ES and neural noise (C11).

In [27]:
# The lines of the paper's code (pinned commit) behind details the verifier could not see: ES normalization,
# MRF scaling (one SD pooled over the good units), the LDA axes (eigh), the PCC > 30 filter, the sex test, and the
# neural clustering's threshold grid. allz holds the z of every trial of the good units (the loop over unitNamesGood).
BASE = "https://raw.githubusercontent.com/ftheunissen/Ensemble-Code-Cell-Reports-2022/f2d237639217425e7fc81d694708f19428a3b026/"
want = {"decodingCallTypesNaiveBayesPart2.ipynb": ["pccDiag", "selH[istart"],
        "GenerateMLFilters.ipynb": ["for i,unit in enumerate(unitNamesGood)", "allz.append(", "stdz = ", "stdPC = ", "/(110*stdz)", "np.linalg.eigh", "indGood = (pcc > 30)", "np.linalg.det(np.cov(unitMTFLDA", "unitNoiseComb += std"],
        "plotConfusionsBird.ipynb": ["nE = numUnits[6]", "n0 = 2", "n1 = 2", "tval = ", "fac = np.sqrt"],
        "EPHYS4-Population_Clustering.ipynb": ["delta = (clustered.max()", "start_thresh = clustered.min()", "for cl in range(1,500)"]}
for f, keys in want.items():
    nbc = requests.get(BASE + f, timeout=120).json()
    lines = [ln for c in nbc["cells"] if c["cell_type"] == "code" for ln in "".join(c["source"]).splitlines()]
    print(f)
    for k in keys:
        hit = [ln.strip() for ln in lines if k in ln]
        print(f"   {k!r}: {hit[:2] if hit else 'not found'}")
decodingCallTypesNaiveBayesPart2.ipynb
   'pccDiag': ['pccDiag = np.diag(confMat)', 'pccDiag = pccDiag/np.sum(pccDiag)']
   'selH[istart': ['selH[istart + i] = 1 - np.sum(-pccDiag*np.log2(pccDiag))/(np.log2(ncalls))']
GenerateMLFilters.ipynb
   'for i,unit in enumerate(unitNamesGood)': ['for i,unit in enumerate(unitNamesGood):', 'for i,unit in enumerate(unitNamesGood):']
   'allz.append(': ["allz.append(dfDataBase['z'][ind])"]
   'stdz = ': ['stdz = np.std(allz)']
   'stdPC = ': ['stdPC = np.std(np.array(allPC), axis = 0)']
   '/(110*stdz)': ['x = np.dot(eigVect[:,0], mtf)/(110*stdz)', 'y = np.dot(eigVect[:,1], mtf)/(110*stdz)']
   'np.linalg.eigh': ['eigVal, eigVect = np.linalg.eigh(eigMatrix)']
   'indGood = (pcc > 30)': ['indGood = (pcc > 30)']
   'np.linalg.det(np.cov(unitMTFLDA': ['np.linalg.det(np.cov(unitMTFLDABest.transpose()))', '# volumeLDA[ilist] = np.linalg.det(np.cov(unitMTFLDA.transpose()))']
   'unitNoiseComb += std': ['#    unitNoiseComb += std/np.abs(mean)', 'unitNoiseComb += std**2']
plotConfusionsBird.ipynb
   'nE = numUnits[6]': ['nE = numUnits[6]']
   'n0 = 2': ['n0 = 2']
   'n1 = 2': ['n1 = 2']
   'tval = ': ['tval = diffMean/(pooledSD*np.sqrt(1/n0 + 1/n1))']
   'fac = np.sqrt': ['fac = np.sqrt(unitNumber[i][j]/(unitNumber[i][j]-nUnit))']
EPHYS4-Population_Clustering.ipynb
   'delta = (clustered.max()': ['delta = (clustered.max()-clustered.min())/500 #.1']
   'start_thresh = clustered.min()': ['start_thresh = clustered.min()#100 #.25']
   'for cl in range(1,500)': ['for cl in range(1,500):']
In [28]:
t0 = time.time()
mps = {}
for win in ["methods", "code"]:
    out = []
    for s in db["stims"]:
        w = waves[s][0]
        M_, wt, wf = aa5.stimulus_mps(w["wav"], w["tStim0"], w["dt"], win)
        out.append(M_)
    mps[win] = np.array(out)
fsl, tsl = aa5.mps_window(wt, wf)
print(f"MPS of {len(db['stims'])} stimuli x 2 windows in {time.time() - t0:.0f} s; shape {mps['methods'].shape[1:]}, "
      f"kept {fsl.stop - fsl.start} spectral x {tsl.stop - tsl.start} temporal modulations "
      f"({wf[fsl][0] * 1000:.2f} to {wf[fsl][-1] * 1000:.2f} cyc/kHz, {wt[tsl][0]:.1f} to {wt[tsl][-1]:.1f} Hz)")
MPS of 110 stimuli x 2 windows in 13 s; shape (193, 101), kept 41 spectral x 11 temporal modulations (0.00 to 3.98 cyc/kHz, -49.5 to 49.5 Hz)
In [29]:
N5, NPERM5 = 1800, 100
res5, ens5 = {}, {}
t0 = time.time()
for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    cv, nperm, m = readings[name]
    rng = np.random.default_rng(9000 if name.startswith("(a)") else 9100)
    ens5[name] = [list(rng.choice(good[name], 20, replace=False)) for _ in range(N5)]
    res5[name] = aa5.run_ensembles(db, ens5[name], code="ZT", cv=cv, nperm=NPERM5, seed=9200 + (0 if name.startswith("(a)") else 1))
    p = res5[name][m]
    print(f"{name}: {N5} ensembles x {NPERM5} repetitions, mean PCC {p.mean():.2f}, range {p.min():.1f} to {p.max():.1f}, "
          f"above 30%: {(p > 30).sum()} (paper 1746)")
print(f"decoded in {(time.time() - t0) / 60:.1f} min")
(a) exemplar, PCC_a: 1800 ensembles x 100 repetitions, mean PCC 32.00, range 22.6 to 41.1, above 30%: 1329 (paper 1746)
(b) trial, 1 rep, PCC_b: 1800 ensembles x 100 repetitions, mean PCC 43.05, range 23.4 to 68.4, above 30%: 1797 (paper 1746)
decoded in 7.4 min
In [30]:
# fig4b-top-ensembles, without the bias of a single draw: the 1,800 ensembles of 20 decoded with 100 repetitions
for name in res5:
    p = res5[name][readings[name][2]]
    top = np.sort(p)[::-1]
    print(f"{name}: best of {len(p)} ensembles {top[0]:.2f}; top 10% mean {top[: len(p) // 10].mean():.2f}, top 5% mean {top[: len(p) // 20].mean():.2f}")
(a) exemplar, PCC_a: best of 1800 ensembles 41.09; top 10% mean 37.33, top 5% mean 38.20
(b) trial, 1 rep, PCC_b: best of 1800 ensembles 68.41; top 10% mean 52.76, top 5% mean 55.21
In [31]:
def unit_regressors(name):
    # Per good unit: MRF projections (per window and LDA rule), SI (a, b), ES (a, b), neural noise (variance, SD)
    g = good[name]
    cv, nperm, m = readings[name]
    allz = np.concatenate([db["trials"][x]["z"].to_numpy() for x in g])
    allT = np.vstack([db["T"][x] for x in g])
    sdz, sdT = allz.std(), allT.std(axis=0)
    sres = single[(name, "ZT")]
    pos = {x: i for i, x in enumerate(full)}
    out = {}
    for x in g:
        tr = db["trials"][x].copy()
        T = db["T"][x]
        for k in range(5):
            tr[f"T{k + 1}"] = T[:, k]
        w = tr.groupby("stim")[["z", "T1", "T2", "T3", "T4", "T5"]].mean().reindex(db["stims"])
        za, zb = aa5.zct_unit(byuid[x], db["trials"][x])
        noise_var = np.mean([g_.z.var(ddof=0) for _, g_ in tr.groupby("call")])
        noise_sd = np.mean([g_.z.std(ddof=0) for _, g_ in tr.groupby("call")])
        conf, nt = sres["conf"][pos[x]], sres["ntest"][pos[x]]
        out[x] = dict(w=w.to_numpy(), SI_a=aa5.selectivity_index(za.values()), SI_b=aa5.selectivity_index(zb.values()),
                      ES_a=aa5.entropy_selectivity(conf, nt, True), ES_b=aa5.entropy_selectivity(conf, nt, False),
                      noise_var=noise_var, noise_sd=noise_sd)
    scale = np.concatenate([[sdz], sdT])
    proj = {}
    for win in ["methods", "code"]:
        X = mps[win][:, fsl, tsl]
        dev = (X - X.mean(axis=0)).reshape(len(X), -1)
        for rule in ["largest", "eigh"]:
            axes, _ = aa5.lda_axes(X, db["y"], rule)
            for x in g:
                mrf = dev.T @ np.nan_to_num(out[x]["w"])            # (features, 6): sum over stimuli
                proj[(win, rule, x)] = (axes.T @ mrf).T / (110 * scale[:, None])   # 6 x 3
    return out, proj

def ensemble_table(name, out, proj):
    rows = []
    for e in ens5[name]:
        r = {}
        for win in ["methods", "code"]:
            for rule in ["largest", "eigh"]:
                V = np.vstack([proj[(win, rule, x)] for x in e])
                r[f"logvol_{win}_{rule}"] = np.log(np.linalg.det(np.cov(V.T)))
        for k in ["SI_a", "SI_b", "ES_a", "ES_b", "noise_var", "noise_sd"]:
            r[k] = np.mean([out[x][k] for x in e])
        rows.append(r)
    return pd.DataFrame(rows)

t0 = time.time()
tab5 = {}
for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    out, proj = unit_regressors(name)
    tab5[name] = ensemble_table(name, out, proj)
    tab5[name]["pcc"] = res5[name][readings[name][2]]
print(f"regressors in {time.time() - t0:.0f} s")
print(tab5["(b) trial, 1 rep, PCC_b"].describe().T.round(3))

def regress(name, xcols, filt):
    d = tab5[name]
    if filt == "pcc > 30":
        d = d[d.pcc > 30]
    return aa5.corrected_regression(d[xcols].to_numpy(), d.pcc.to_numpy(), len(good[name]), 20)
regressors in 2 s
                         count    mean    std     min     25%     50%     75%     max
logvol_methods_largest  1800.0  16.493  0.725  14.088  15.962  16.480  17.028  18.248
logvol_methods_eigh     1800.0  28.631  0.988  25.491  27.874  28.563  29.431  31.200
logvol_code_largest     1800.0  15.268  0.821  12.639  14.629  15.181  15.937  17.267
logvol_code_eigh        1800.0  27.068  0.869  24.634  26.399  26.957  27.772  29.220
SI_a                    1800.0   0.433  0.055   0.264   0.396   0.434   0.470   0.634
SI_b                    1800.0   0.390  0.060   0.203   0.350   0.390   0.431   0.622
ES_a                    1800.0   0.059  0.009   0.034   0.053   0.059   0.065   0.095
ES_b                    1800.0  -0.120  0.018  -0.183  -0.132  -0.120  -0.108  -0.067
noise_var               1800.0   0.907  0.016   0.855   0.896   0.908   0.919   0.959
noise_sd                1800.0   0.929  0.011   0.888   0.921   0.929   0.937   0.959
pcc                     1800.0  43.052  5.013  23.387  39.829  42.662  45.869  68.415

fig5e-volume¶

Across random ensembles of 20 units, PCC increases with the volume the ensemble's MRF components span in the 3D LDA space of call types (R2adj = 0.1).

In [32]:
rows = []
for name in tab5:
    for filt in ["pcc > 30", "all"]:
        for win in ["methods", "code"]:
            for rule in ["largest", "eigh"]:
                r = regress(name, [f"logvol_{win}_{rule}"], filt)
                rows.append(dict(cv=name[:3], ensembles=filt, n=r["n"], window=win, lda=rule, slope=r["coef"][1], R2adj=r["r2adj"],
                                 F=r["F"], df=str(r["df"]), p=r["p"]))
fig5e = pd.DataFrame(rows)
print(fig5e.round(4).to_string(index=False))
print("paper: R2adj 0.1 (tol 0.01), F(1,79) = 8.975, p = 0.0036, 1746 ensembles")
 cv ensembles    n  window     lda  slope  R2adj       F      df      p
(a)  pcc > 30 1329 methods largest 1.1744 0.1776 12.5637 (1, 56) 0.0008
(a)  pcc > 30 1329 methods    eigh 0.7227 0.1145  7.5379 (1, 56) 0.0081
(a)  pcc > 30 1329    code largest 0.9885 0.1500 10.2688 (1, 56) 0.0022
(a)  pcc > 30 1329    code    eigh 0.8569 0.1221  8.1076 (1, 56) 0.0062
(a)       all 1800 methods largest 1.9327 0.2981 24.6477 (1, 56) 0.0000
(a)       all 1800 methods    eigh 1.2702 0.2076 15.2211 (1, 56) 0.0003
(a)       all 1800    code largest 1.6992 0.2620 20.6109 (1, 56) 0.0000
(a)       all 1800    code    eigh 1.5236 0.2252 16.8836 (1, 56) 0.0001
(b)  pcc > 30 1797 methods largest 2.3814 0.1203  9.6035 (1, 68) 0.0028
(b)  pcc > 30 1797 methods    eigh 1.4936 0.0879  6.7795 (1, 68) 0.0113
(b)  pcc > 30 1797    code largest 2.0642 0.1163  9.2426 (1, 68) 0.0034
(b)  pcc > 30 1797    code    eigh 1.7536 0.0938  7.2824 (1, 68) 0.0088
(b)       all 1800 methods largest 2.4292 0.1228  9.8354 (1, 68) 0.0025
(b)       all 1800 methods    eigh 1.5192 0.0891  6.8826 (1, 68) 0.0107
(b)       all 1800    code largest 2.0918 0.1170  9.3090 (1, 68) 0.0033
(b)       all 1800    code    eigh 1.7766 0.0944  7.3303 (1, 68) 0.0086
paper: R2adj 0.1 (tol 0.01), F(1,79) = 8.975, p = 0.0036, 1746 ensembles

Result: reproduced, under the code's cross-validation, sound window and LDA axes (assumption). PCC rises with log volume under every reading, with corrected p of 0.011 or less. With the code's choices throughout (one random trial held out, the -500 to 500 ms window and numpy eigh's first three axes), R2adj is 0.094 over the 1,797 ensembles with PCC above 30% (F(1,68) = 7.28, p = 0.0088), within 0.1 +- 0.01; the criterion names the window and axes as readings, and these are the choices that made the paper's printed F(1,79) = 8.975. With the Methods' window and the axes of largest eigenvalue R2adj is 0.120 (F(1,68) = 9.60, p = 0.0028), outside tolerance. Under the Methods' cross-validation R2adj is 0.11 to 0.30. Here 1,797 of the 1,800 ensembles exceed 30%, against the paper's 1,746.

fig5f-si-unrelated¶

The average Z-based selectivity index of the units in an ensemble is not related to the ensemble's decoding performance.

In [33]:
rows = []
for name in tab5:
    for filt in ["pcc > 30", "all"]:
        for si in ["SI_a", "SI_b"]:
            r = regress(name, [si], filt)
            rows.append(dict(cv=name[:3], ensembles=filt, n=r["n"], SI=si, slope=r["coef"][1], R2adj=r["r2adj"], F=r["F"], df=str(r["df"]), p=r["p"]))
print(pd.DataFrame(rows).round(4).to_string(index=False))
print("paper (code output): R2adj = -0.0006, p = 0.99")
 cv ensembles    n   SI    slope   R2adj      F      df      p
(a)  pcc > 30 1329 SI_a  -5.9004  0.0167 1.0253 (1, 56) 0.3156
(a)  pcc > 30 1329 SI_b  -5.6579  0.0178 1.0925 (1, 56) 0.3004
(a)       all 1800 SI_a -11.2714  0.0357 2.1781 (1, 56) 0.1456
(a)       all 1800 SI_b -11.1315  0.0402 2.4618 (1, 56) 0.1223
(b)  pcc > 30 1797 SI_a  -2.0181 -0.0001 0.0346 (1, 68) 0.8530
(b)  pcc > 30 1797 SI_b  -4.1739  0.0020 0.1787 (1, 68) 0.6738
(b)       all 1800 SI_a  -2.0593 -0.0001 0.0353 (1, 68) 0.8516
(b)       all 1800 SI_b  -4.2622  0.0020 0.1826 (1, 68) 0.6705
paper (code output): R2adj = -0.0006, p = 0.99

Result: reproduced. The ensemble-corrected F-test of PCC on the ensemble mean of the Methods' SI gives p = 0.85 (R2adj -0.0001) under the code's cross-validation and p = 0.32 under the Methods'; the code's SI gives p = 0.67 and 0.30. No reading finds a relation at p < 0.05.

fig5g-entropy-selectivity¶

The ensemble average Entropy Selectivity of its units is negatively correlated with ensemble decoding performance.

In [34]:
rows = []
for name in tab5:
    for filt in ["pcc > 30", "all"]:
        for es in ["ES_a", "ES_b"]:
            r = regress(name, [es], filt)
            rows.append(dict(cv=name[:3], ensembles=filt, n=r["n"], ES=es, slope=r["coef"][1], R2adj=r["r2adj"], F=r["F"], df=str(r["df"]), p=r["p"]))
print(pd.DataFrame(rows).round(4).to_string(index=False))
print("paper: negative, F(1,79) = 6.73, p = 0.011 (code R2adj 0.076)")
 cv ensembles    n   ES    slope  R2adj       F      df      p
(a)  pcc > 30 1329 ES_a -41.4996 0.0661  4.1479 (1, 56) 0.0464
(a)  pcc > 30 1329 ES_b -49.9940 0.1909 13.7150 (1, 56) 0.0005
(a)       all 1800 ES_a -73.6218 0.1204  7.9676 (1, 56) 0.0066
(a)       all 1800 ES_b -82.1209 0.3263 28.1121 (1, 56) 0.0000
(b)  pcc > 30 1797 ES_a  18.9022 0.0005  0.0749 (1, 68) 0.7852
(b)  pcc > 30 1797 ES_b -69.3899 0.0646  4.8696 (1, 68) 0.0307
(b)       all 1800 ES_a  15.7061 0.0002  0.0506 (1, 68) 0.8226
(b)       all 1800 ES_b -71.5674 0.0675  5.1023 (1, 68) 0.0271
paper: negative, F(1,79) = 6.73, p = 0.011 (code R2adj 0.076)

Result: reproduced. With the Methods' ES formula (reading b), the slope is negative and significant under both cross-validations (code: -69.4, F(1,68) = 4.87, p = 0.031; Methods: -50.0, p = 0.0005, over the ensembles above 30%). With the code's normalized ES (reading a) the slope is negative under the Methods' cross-validation (p = 0.046) but positive and not significant under the code's (p = 0.79). The Methods' ES takes negative values here (ensemble means -0.18 to -0.07), while the Figure 5G legend says ES ranges from 0 to 1, which only the code's normalized ES does (0.034 to 0.095); whether reading (b) belongs in the criterion is asked of a reader (questions/robotka-2023.yaml).

fig5h-neural-noise¶

As neural variability within call types (neural noise plus lack of invariance) increases, ensemble decoding performance decreases (R2adj = 0.1).

In [35]:
rows = []
for name in tab5:
    for filt in ["pcc > 30", "all"]:
        for nz in ["noise_var", "noise_sd"]:
            r = regress(name, [nz], filt)
            rows.append(dict(cv=name[:3], ensembles=filt, n=r["n"], noise=nz, slope=r["coef"][1], R2adj=r["r2adj"], F=r["F"], df=str(r["df"]), p=r["p"]))
print(pd.DataFrame(rows).round(4).to_string(index=False))
print("paper: negative, R2adj 0.1 (tol 0.01), F(1,79) = 8.75, p = 0.004")
 cv ensembles    n     noise     slope  R2adj       F      df      p
(a)  pcc > 30 1329 noise_var  -60.8308 0.1674 11.6947 (1, 56) 0.0012
(a)  pcc > 30 1329  noise_sd -115.8305 0.1475 10.0732 (1, 56) 0.0024
(a)       all 1800 noise_var  -95.7281 0.2694 21.4034 (1, 56) 0.0000
(a)       all 1800  noise_sd -189.1259 0.2489 19.2404 (1, 56) 0.0001
(b)  pcc > 30 1797 noise_var -138.8927 0.2096 18.5931 (1, 68) 0.0001
(b)  pcc > 30 1797  noise_sd -159.7427 0.1313 10.6132 (1, 68) 0.0018
(b)       all 1800 noise_var -139.3077 0.2064 18.2366 (1, 68) 0.0001
(b)       all 1800  noise_sd -160.2891 0.1293 10.4318 (1, 68) 0.0019
paper: negative, R2adj 0.1 (tol 0.01), F(1,79) = 8.75, p = 0.004

Result: partially reproduced. PCC falls with the ensemble mean neural noise under every reading (code cross-validation, variance: slope -139, F(1,68) = 18.6, p = 0.0001), but R2adj is 0.21 with the variance and 0.13 with the SD under the code's cross-validation, and 0.15 to 0.27 under the Methods', all outside 0.1 +- 0.01.

fig5-multiple-regression¶

A linear model of PCC on volume spanned, neural variability and the two selectivity measures together explains R2adj = 0.22 of the variance of ensemble decoding performance.

In [36]:
rows = []
for name in tab5:
    for filt in ["pcc > 30", "all"]:
        for win in ["methods", "code"]:
            for rule in ["largest", "eigh"]:
                r = regress(name, ["noise_var", f"logvol_{win}_{rule}", "ES_a", "SI_b"], filt)
                r2 = regress(name, ["noise_var", f"logvol_{win}_{rule}", "ES_a", "SI_a"], filt)
                rows.append(dict(cv=name[:3], ensembles=filt, n=r["n"], window=win, lda=rule, R2adj_SIb=r["r2adj"], F_SIb=r["F"],
                                 p_SIb=r["p"], R2adj_SIa=r2["r2adj"], p_SIa=r2["p"], df=str(r["df"])))
print(pd.DataFrame(rows).round(4).to_string(index=False))
print("paper: R2adj 0.22 (tol 0.022), F(4,76) = 5.832, p = 0.00038")
print(f"total run time {(time.time() - T_START) / 60:.1f} min; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB (this process)")
 cv ensembles    n  window     lda  R2adj_SIb   F_SIb  p_SIb  R2adj_SIa  p_SIa      df
(a)  pcc > 30 1329 methods largest     0.3411  7.5430 0.0001     0.3427 0.0001 (4, 53)
(a)  pcc > 30 1329 methods    eigh     0.2963  6.1430 0.0004     0.2968 0.0004 (4, 53)
(a)  pcc > 30 1329    code largest     0.3242  6.9939 0.0001     0.3253 0.0001 (4, 53)
(a)  pcc > 30 1329    code    eigh     0.3030  6.3422 0.0003     0.3022 0.0003 (4, 53)
(a)       all 1800 methods largest     0.4841 13.6320 0.0000     0.4866 0.0000 (4, 53)
(a)       all 1800 methods    eigh     0.4336 11.1280 0.0000     0.4352 0.0000 (4, 53)
(a)       all 1800    code largest     0.4669 12.7227 0.0000     0.4692 0.0000 (4, 53)
(a)       all 1800    code    eigh     0.4442 11.6121 0.0000     0.4439 0.0000 (4, 53)
(b)  pcc > 30 1797 methods largest     0.2515  5.9168 0.0004     0.2515 0.0004 (4, 65)
(b)  pcc > 30 1797 methods    eigh     0.2376  5.4907 0.0007     0.2372 0.0007 (4, 65)
(b)  pcc > 30 1797    code largest     0.2481  5.8113 0.0005     0.2478 0.0005 (4, 65)
(b)  pcc > 30 1797    code    eigh     0.2411  5.5947 0.0006     0.2402 0.0006 (4, 65)
(b)       all 1800 methods largest     0.2504  5.8821 0.0004     0.2505 0.0004 (4, 65)
(b)       all 1800 methods    eigh     0.2354  5.4243 0.0008     0.2350 0.0008 (4, 65)
(b)       all 1800    code largest     0.2458  5.7390 0.0005     0.2455 0.0005 (4, 65)
(b)       all 1800    code    eigh     0.2385  5.5168 0.0007     0.2376 0.0007 (4, 65)
paper: R2adj 0.22 (tol 0.022), F(4,76) = 5.832, p = 0.00038
total run time 31.6 min; peak memory 4.28 GB (this process)

Result: reproduced, under the code's cross-validation and LDA axes (assumption). With numpy eigh's axes, as the code, the four regressors give R2adj = 0.238 (Methods' window) and 0.241 (code's window) over the ensembles above 30%, F(4,65) = 5.49 and 5.59, p = 0.0007 and 0.0006, within 0.22 +- 0.022. With the axes of largest eigenvalue R2adj is 0.252 and 0.248, just outside tolerance. Under the Methods' cross-validation R2adj is 0.30 to 0.49.

fig6c-number-of-clusters (call-type half)¶

The optimal number of neural clusters varies from 1 to 30 across ensembles, but its mean and median are close to the number of call types whether call types (mean 10.83, median 9) or acoustic labels (mean 10.03, median 9) are the reference, with no significant difference between the two.

The claim is blocked: the acoustic labels are not public. Its call-type values need only this dataset, and the criterion judges them on their own, so they are computed here. Neural clustering as C12 (aa5.run_clustering) on the 1,800 Figure 5 ensembles of each reading of the good units (the criterion's variant; the legend's 10,000 were not run, for time), (a) UMAP then Ward (the code), (b) Ward on the averaged responses. The tree is cut at 499 thresholds between its smallest and largest linkage distance, as C12 states; as a variant, between the minimum and maximum of the whole linkage matrix, its index and count columns included, as the code computes them (clustered.min() and clustered.max(), printed in the code-lines cell above). Both cuts are made on the same trees.

In [37]:
import os
os.environ.setdefault("NUMBA_NUM_THREADS", "1")
t0 = time.time()
rows = []
for name in ["(a) exemplar, PCC_a", "(b) trial, 1 rep, PCC_b"]:
    for use_umap in [True, False]:
        ari_d, k_d, ari_m, k_m = aa5.run_clustering(db, ens5[name], use_umap=use_umap, seed=9500 + (0 if name.startswith("(a)") else 10) + use_umap)
        for grid, ari, k in [("distances (C12)", ari_d, k_d), ("matrix (code)", ari_m, k_m)]:
            for filt, sel in [("all", np.ones(len(k), bool)), ("pcc > 30", res5[name][readings[name][2]] > 30)]:
                rows.append(dict(units=name[:3], clustering="(a) UMAP + Ward" if use_umap else "(b) Ward", grid=grid, ensembles=filt, n=int(sel.sum()),
                                 mean_k=k[sel].mean(), median_k=np.median(k[sel]), min_k=k[sel].min(), max_k=k[sel].max(), mean_ARIcall=ari[sel].mean()))
print(pd.DataFrame(rows).round(3).to_string(index=False))
# grid: thresholds between the smallest and largest linkage distance (C12), or between the min and max of the whole
# linkage matrix, index and count columns included (the code, printed above), a variant
print("paper, call types: mean 10.83 (tol 1.083), median 9 (tol 0.9), range 1 to 30")
print(f"clustered in {(time.time() - t0) / 60:.1f} min")
units      clustering            grid ensembles    n  mean_k  median_k  min_k  max_k  mean_ARIcall
  (a) (a) UMAP + Ward distances (C12)       all 1800  10.160       9.0      2     35         0.140
  (a) (a) UMAP + Ward distances (C12)  pcc > 30 1329  10.403      10.0      2     35         0.143
  (a) (a) UMAP + Ward   matrix (code)       all 1800   9.691       9.0      2     33         0.138
  (a) (a) UMAP + Ward   matrix (code)  pcc > 30 1329   9.949       9.0      2     33         0.141
  (a)        (b) Ward distances (C12)       all 1800  11.591      11.0      2     42         0.159
  (a)        (b) Ward distances (C12)  pcc > 30 1329  11.494      11.0      2     42         0.162
  (a)        (b) Ward   matrix (code)       all 1800  11.583      11.0      2     42         0.159
  (a)        (b) Ward   matrix (code)  pcc > 30 1329  11.491      11.0      2     42         0.161
  (b) (a) UMAP + Ward distances (C12)       all 1800  10.445      10.0      3     32         0.137
  (b) (a) UMAP + Ward distances (C12)  pcc > 30 1797  10.447      10.0      3     32         0.137
  (b) (a) UMAP + Ward   matrix (code)       all 1800   9.910       9.0      2     30         0.135
  (b) (a) UMAP + Ward   matrix (code)  pcc > 30 1797   9.912       9.0      2     30         0.135
  (b)        (b) Ward distances (C12)       all 1800  11.902      11.0      3     44         0.157
  (b)        (b) Ward distances (C12)  pcc > 30 1797  11.898      11.0      3     44         0.157
  (b)        (b) Ward   matrix (code)       all 1800  11.899      11.0      3     45         0.157
  (b)        (b) Ward   matrix (code)  pcc > 30 1797  11.895      11.0      3     45         0.157
paper, call types: mean 10.83 (tol 1.083), median 9 (tol 0.9), range 1 to 30
clustered in 5.4 min

Result: blocked (data missing: the acoustic labels). The call-type half alone: with UMAP then Ward (the code) and the tree cut between its smallest and largest linkage distance (C12), the optimal number of clusters over the 1,800 ensembles of the code reading's good units has mean 10.4 and median 10 (range 2 to 33), and over those of the Methods reading's good units mean 10.3 and median 10 (range 2 to 30); the paper gives mean 10.83 and median 9 (range 1 to 30). The mean is within tolerance in both, the median in neither. With the code's threshold grid (minimum and maximum over the whole linkage matrix) on the same trees, the means are 9.9 and 9.8 and the medians 9, all within tolerance. Ward on the averaged responses gives means of 11.5 to 11.9 and medians of 11 under both grids. No ensemble's best cut has 1 cluster (minimum 2). The acoustic half and the paired test cannot be run.

Summary¶

claim outcome
stimulus-set-link reproduced
paper-good-units-link partially reproduced (91 of 100 units found)
auditory-units reproduced
inhibited-units reproduced
table1-snr reproduced
pcs-variance reproduced
fig3c-peak-call-types reproduced (assumption: the code's zCT)
fig4a-unit-z-vs-zt reproduced
good-units-100 not reproduced (89 against 100 +- 10; 87 to 101 over seeds)
fig4b-ensemble-20 reproduced (assumption: the code's cross-validation)
fig4b-top-ensembles reproduced (same assumption)
fig4b-confusions reproduced
figs4-per-bird-and-sex blocked: ZF6M has fewer than 16 good units (the paper's listed units, a variant, give p = 0.70)
fig5e-volume reproduced (assumption: the code's cross-validation, window and LDA axes)
fig5f-si-unrelated reproduced
fig5g-entropy-selectivity reproduced
fig5h-neural-noise partially reproduced
fig5-multiple-regression reproduced (assumption: the code's cross-validation and LDA axes)
figs6, figs5-region-anova, figs9 blocked: no brain area per unit
fig6a, acoustic-labels-decoding, fig6c (2), figs10 blocked: acoustic database not public (the call-type half of fig6c-number-of-clusters is computed: with the C12 threshold grid, mean 10.4 and median 10 on the code reading's good units, mean 10.3 and median 10 on the Methods reading's; with the code's grid, means 9.9 and 9.8, medians 9)
anesthetized claims (4) blocked: CRCNS aa-4 not analysed in this run

A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.

How the analysis differs from the paper's. The Methods and the paper's code differ on the decoder's cross-validation (one exemplar per call type held out, against one random trial per stimulus); both are run, and the ensemble claims are judged on the code's, whose results match the paper's printed values (an assumption). The code's scheme tests trials of exemplars it was trained on, so it rewards exemplar-specific responses as well as call-type ones (78% against 10% on synthetic units with exemplar signal alone). For Figure 5 the code's sound window and LDA axes are likewise adopted where they decide the outcome, as the paper's printed values come from them. The Figure 4B ensembles are decoded once each (the Methods' single leave-one-out; the code ran 100 repetitions). Both readings of zCT, SI, ES, neural noise, the MPS window, the LDA axes and the 30% ensemble filter are shown. The good-unit set is selected here (89 units) and differs from the paper's 100. The best ensemble of fig4b-top-ensembles is taken from the 1,800 Figure 5 ensembles decoded with 100 repetitions, not from the Figure 4B ensembles decoded once. The neural clustering of Figure 6C is run on the 1,800 Figure 5 ensembles, not the legend's 10,000, and its tree is cut on both the C12 threshold grid and the code's.

What was found about the dataset. The files match the paper's stimulus set exactly and hold 4 birds, 50 sites and 872 unit pickles, 34 of them empty and 112 with song stimuli only. Unit counts are close to the paper's (726 units with vocalization trials against 730; 287 auditory against 292; 187 with all 110 stimuli against 191). Nine of the paper's 100 listed good units come from a site sorting named ZF4F_2t_190613_101015.old that is not in the dataset, whose site of that name holds other clusters. No unit carries a brain area, so the claims by area cannot be tested. KDE_BW (0.2 to 10, 646 of the 872 pickles at 10) is, as the descriptor says, the bandwidth of the coarse rate used for the rate threshold, not that of spikeKDE. The stored spikeKDE is a 30 ms Gaussian KDE of the spike times, as the paper says, but scaled by the number of trials over 5 (ratio 1.00 at 5 trials, 2.01 at 10, 3.01 at 15), so it is not the per-trial rate the descriptor's "time-varying rate" suggests. Each tar holds an AppleDouble ._ file for every pickle.