Reproducing Holdgraf et al. (2016) from CRCNS ac-4¶

Paper: Holdgraf, de Heer, Pasley, Rieger, Crone, Lin, Knight & Theunissen (2016), "Rapid tuning shifts in human auditory cortex enhance speech intelligibility", Nat Commun 7:13654, doi:10.1038/ncomms13654.

Dataset: CRCNS ac-4 (doi:10.6080/K08S4N4J), "Electrocorticography recordings from patients during a passive listening task of degraded and intact English speech", read in place from ac-4/live/data.zip in the public S3 bucket crcnsarchive.

Version: CRCNS data sets are not versioned, so the version is recorded as unversioned. The bucket holds one copy of the data set (ac-4/live/, no old/ folder), the data descriptor's version 0.6 of 28 May 2019, which is the only published version and the one the paper's data availability statement points to. The MD5 of data.zip in the data set's checksums.md5 is printed below, so a later change is detectable.

Claims: claims/crcns-ac-4/10.1038-ncomms13654.yaml, written from the version of record with its Supplementary Information. The claims file decides what is tested; method details it lacks are taken from the paper and cited where they are used (in this notebook or in ac4.py).

Claim Tested here
behav-no-context-baseline, behav-context-enhancement, supp1a-linguistic-context, supp1a-speaker-no-difference, supp1b-filter-type, supp5a-behaviour-over-trials Blocked: the behavioural control data are not in the data set
speech-r-count Tested
fig3b-hfb-increase-after Tested
supp3a-pink-noise-no-hfb-change Tested
supp5b-hfb-stable-over-session Tested
fig4a-coherence-after-higher, fig4b-coherence-sentence-specific Tested
strf-r-count, included-electrode-count Tested
fig8-mtf-matches-filter Tested
fig9-rms-increase, fig9-middle-generalizes-after Tested
fig10-partial-correlation, fig10b-similarity-correlates, fig10c-stg-location Tested
supp3b-pink-noise-no-pcorr-change Run, but no electrode of the pink noise subjects is included, so it is blocked
supp6a-connectivity-increase, supp6a-after-closer-to-middle, supp6b-no-pac-change Tested
supp7-envelope-coherence Tested
supp4-hfb-power-increase Tested

The whole notebook streams about 1.6 GB and takes about 25 minutes, about half of it loading.

Revised after the first verification round: supp5b runs under the three z-scores with a bootstrap that resamples whole sounds or subjects; the coherence of fig4, supp6a and supp7 uses MNE's default multitaper half-bandwidth (NW = 4, seven tapers; claims, open detail 10), with the earlier choices as variants; supp6a uses all included electrodes as seeds, as the criterion says; the spectrogram and the HFB are checked for alignment; fig8 adds a region rule from the filter cutoffs; PAC leaves an electrode out of its own phase mean; supp4 adds power without a baseline.

In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "4")
import time
import resource
import urllib.request
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mne
from scipy import stats
import ac4

mne.set_log_level("ERROR")
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)
print(ac4.DATASET, "doi:" + ac4.DOI)
print(urllib.request.urlopen(ac4.BASE + "/checksums.md5").read().decode())
crcns:ac-4/unversioned doi:10.6080/K08S4N4J
a3f4fc4396018c4336289aeae07f3a24  data.zip
e5fada4a35959c02599388fa667f9629  docs/crcns_ac-4_data_description.docx
5967170cec24533198d9a116e0ac34bf  docs/crcns_ac-4_data_description.pdf
03c6756f455486e0cc0169a76f48df3e  filelist.txt

In [2]:
# LOAD: stream each subject, reduce it to HFB at 50 Hz, the auditory spectrograms and speech
# envelopes of every sound, and the re-referenced signal around each sound (see ac4.load_subject)
t0 = time.time()
z = ac4.open_zip()
D = {}
for s in ac4.SUBJECTS:
    D[s] = ac4.load_subject(z, s)
    print(s, f"{time.time() - t0:.0f} s", f"peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.1f} GB")
S01 138 s peak memory 2.3 GB
S02 246 s peak memory 2.3 GB
S03 332 s peak memory 2.3 GB
S04 410 s peak memory 2.3 GB
S07 544 s peak memory 2.6 GB
S08 657 s peak memory 2.6 GB
S13 783 s peak memory 2.8 GB

Data check¶

In [3]:
def region(desc):
    if desc.startswith("temporal") or desc == "sub_temporal":
        return "temporal"
    if desc.endswith("-inferior"):
        return "perisylvian"          # inferior frontal, premotor, motor, parietal
    if desc.startswith("frontal") or desc.startswith("premotor"):
        return "frontal"
    return "other"

rows = []
for s, d in D.items():
    ch, tr, js = d["channels"], d["trials"], d["json"]
    rows.append(dict(subject=s, channels=len(ch), good=int((ch.status == "good").sum()),
                     fs=js["SamplingFrequency"], duration_json=js["RecordingDuration"],
                     duration_samples=d["stats"]["n_samples"] / ac4.FS,
                     audio_sr=d["audio_sr"], audio_s=d["audio_len"] / d["audio_sr"],
                     triplets=tr.loc[tr.trial_num >= 0, "trial_num"].nunique(),
                     noise_triplets=tr.loc[tr.noise, "trial_num"].nunique(),
                     lone_unfiltered=int((tr.trial_num < 0).sum()),
                     sound_s=f"{tr.duration.min():.2f}-{tr.duration.max():.2f}",
                     bad_spans=int((d["events"].trial_type == "bad").sum()),
                     sounds_overlapping_bad=int(tr.overlaps_bad.sum()),
                     raw_abs_median=d["stats"]["raw_abs_median"],
                     car_residual=d["stats"]["car_residual"]))
summary = pd.DataFrame(rows)
print(summary.to_string())
print("total channels", summary.channels.sum(), "good", summary.good.sum(), "(paper: 468 kept of 524)")
print("units in channels.tsv:", {s: d["channels"].units.unique().tolist() for s, d in D.items()})
print("reference in channels.tsv:", {s: d["channels"].reference.unique().tolist() for s, d in D.items()})

E = pd.concat([d["good"] for d in D.values()], ignore_index=True)
E["region"] = E.description.map(region)
E["stg"] = E.description.eq("temporal-superior")
print(pd.crosstab(E.subject, E.region, margins=True))
print(E.description.value_counts().to_string())

cond = pd.concat([d["trials"].assign(subject=s) for s, d in D.items()])
print(pd.crosstab([cond.subject, cond.noise], [cond.trial_phase, cond.filt_type]))
# every triplet has one sound of each phase, the same filter BEFORE and AFTER, and similar durations
for s, d in D.items():
    t = d["trials"][d["trials"].trial_num >= 0]
    g = t.groupby("trial_num")
    ok_phase = (g.trial_phase.apply(lambda x: sorted(x) == ["aft", "bef", "mid"])).sum()
    filt_same = g.apply(lambda x: x.loc[x.trial_phase == "bef", "filt_type"].tolist() == x.loc[x.trial_phase == "aft", "filt_type"].tolist()).sum()
    order = g.apply(lambda x: list(x.sort_values("onset").trial_phase) == ["bef", "mid", "aft"]).sum()
    print(s, "triplets", g.ngroups, "complete", ok_phase, "same filter BEFORE/AFTER", filt_same, "in order BEFORE-MIDDLE-AFTER", order)

# HFB range
for s, d in D.items():
    h = d["hfb"]
    print(s, "HFB shape", h.shape, "at", ac4.FS_OUT, "Hz;", f"range {h.min():.3g} to {h.max():.3g} (stored units)")
  subject  channels  good      fs  duration_json  duration_samples  audio_sr      audio_s  triplets  noise_triplets  lone_unfiltered    sound_s  bad_spans  sounds_overlapping_bad  raw_abs_median  car_residual
0     S01        64    61  1000.0       1204.041          1204.042     16000  1204.042000        56               0                6  1.52-3.39          9                       7    3.151261e+02  1.910911e-08
1     S02        64    59  1000.0        815.000           815.001     16000   815.001062        47               0                6  1.79-4.08          0                       0    2.103745e+08  1.894045e-08
2     S03        64    52  1000.0        780.166           780.167     16000   780.622125        39               0                6  1.53-3.21         12                      10    6.244610e+08  1.234181e-08
3     S04        48    40  1000.0        660.211           660.212     16000   660.249312        32               0                6  1.92-4.05          6                       4    2.057520e+08  1.601341e-08
4     S07        60    60  1000.0        988.913           988.914     16000  1015.170687        57              28                0  1.45-3.21          1                       1    2.722568e+08  1.580337e-08
5     S08        52    52  1000.0        942.243           942.244     16000   943.364375        57              28                0  1.60-3.52          0                       0    3.703386e+08  1.196917e-08
6     S13        64    53  1000.0        982.011           982.012     20000   983.183100        57              28                0  1.52-3.24          0                       0    1.747290e+08  1.891248e-08
total channels 416 good 377 (paper: 468 kept of 524)
units in channels.tsv: {'S01': ['milliV'], 'S02': ['milliV'], 'S03': ['milliV'], 'S04': ['milliV'], 'S07': ['milliV'], 'S08': ['milliV'], 'S13': ['milliV']}
reference in channels.tsv: {'S01': ['CAR'], 'S02': ['CAR'], 'S03': ['CAR'], 'S04': ['CAR'], 'S07': ['CAR'], 'S08': ['CAR'], 'S13': ['CAR']}
region   frontal  other  perisylvian  temporal  All
subject                                            
S01           13     22            8        18   61
S02            8     10            9        32   59
S03            6      9           13        24   52
S04            0      3            9        28   40
S07           20      0            6        34   60
S08            5      6            6        35   52
S13           12     12            8        21   53
All           64     62           59       192  377
description
temporal-superior     78
temporal-medial       50
temporal-inferior     36
parietal-medial       28
parietal-inferior     24
temporal-posterior    20
frontal-medial        16
premotor-medial       16
frontal-inferior      16
frontal-anterior      15
motor-medial          14
parietal-superior     13
premotor-inferior     10
frontal-superior       9
motor-inferior         9
premotor-superior      8
sub_temporal           8
motor-superior         7
trial_phase    aft       bef       mid
filt_type     freq temp freq temp norm
subject noise                         
S01     False   28   28   28   28   62
S02     False   23   23   24   23   53
S03     False   20   18   20   19   44
S04     False   16   16   16   16   38
S07     False   11   18   11   18   29
        True    12   16   12   16   28
S08     False   12   17   12   17   29
        True    15   13   15   13   28
S13     False   17   12   17   12   29
        True    17   11   17   11   28
S01 triplets 56 complete 56 same filter BEFORE/AFTER 56 in order BEFORE-MIDDLE-AFTER 56
S02 triplets 47 complete 46 same filter BEFORE/AFTER 46 in order BEFORE-MIDDLE-AFTER 46
S03 triplets 39 complete 38 same filter BEFORE/AFTER 38 in order BEFORE-MIDDLE-AFTER 38
S04 triplets 32 complete 32 same filter BEFORE/AFTER 32 in order BEFORE-MIDDLE-AFTER 32
S07 triplets 57 complete 57 same filter BEFORE/AFTER 57 in order BEFORE-MIDDLE-AFTER 57
S08 triplets 57 complete 57 same filter BEFORE/AFTER 57 in order BEFORE-MIDDLE-AFTER 57
S13 triplets 57 complete 57 same filter BEFORE/AFTER 57 in order BEFORE-MIDDLE-AFTER 57
S01 HFB shape (61, 60203) at 50.0 Hz; range 1.46 to 2.1e+03 (stored units)
S02 HFB shape (59, 40751) at 50.0 Hz; range 4.15e+05 to 5.99e+07 (stored units)
S03 HFB shape (52, 39009) at 50.0 Hz; range 2.52e+06 to 7.88e+09 (stored units)
S04 HFB shape (40, 33011) at 50.0 Hz; range 7.31e+05 to 8.42e+07 (stored units)
S07 HFB shape (60, 49446) at 50.0 Hz; range 1.02e+06 to 2.09e+08 (stored units)
S08 HFB shape (52, 47113) at 50.0 Hz; range 7.66e+05 to 1.93e+08 (stored units)
S13 HFB shape (53, 49101) at 50.0 Hz; range 4.81e+05 to 4.27e+07 (stored units)

The checks above, stated:

  • Sampling rate 1000 Hz in every ieeg.json, and sample counts give the stated recording durations (columns duration_json and duration_samples).
  • The stored values are not in the stated millivolts: the median absolute value is about 300 in S01 and 1.7e8 to 6.2e8 in the other subjects. The analysis uses only z-scored or normalized measures, so the scale does not enter any result; it is recorded as a finding.
  • The good channels are already re-referenced to their common average (the mean over good channels is about 1e-8 of the signal), as channels.tsv says (CAR).
  • The paper reports 7 subjects with grids of 48, 64, 68, 68, 62, 110 and 104 channels and 468 electrodes kept; the data set has 7 subjects with 416 channels, 377 marked good.
  • Three subjects (S07, S08, S13) have pink noise triplets, about half of their triplets, as the paper says.

Clock checks follow: the audio track against the event onsets, and the HFB against the onsets, with the onsets shifted as the contrast.

In [4]:
fig, ax = plt.subplots(1, 2, figsize=(10, 3))
for s, d in D.items():
    t, a = d["audio_onset_profile"]
    pre, post = a[(t < -0.05)].mean(), a[(t > 0.05) & (t < 0.5)].mean()
    ax[0].plot(t, a / post, lw=0.8, label=s)
    print(s, f"mean |audio| before onsets {pre:.2e}, 0.05-0.5 s after {post:.2e}, ratio {post / pre:.1f}")
ax[0].set(xlabel="time from sound onset (s)", ylabel="mean |audio| (relative)", title="audio at event onsets")
ax[0].legend(fontsize=6)

# HFB clock check: on temporal electrodes, mean HFB 0.1-0.5 s after onset minus -0.4-0 s,
# at the true onsets and at onsets shifted by -2 to +2 s
shifts = np.arange(-2.0, 2.01, 0.1)
for s, d in D.items():
    temp = (d["good"].description.map(region) == "temporal").to_numpy()
    h = d["hfb"][temp]
    on = d["trials"].onset.to_numpy()
    con = []
    for sh in shifts:
        i = np.round((on + sh) * ac4.FS_OUT).astype(int)
        post = np.mean([h[:, j + 5:j + 25].mean() for j in i])
        pre = np.mean([h[:, j - 20:j].mean() for j in i])
        con.append((post - pre) / h.std())
    con = np.array(con)
    ax[1].plot(shifts, con, lw=0.8)
    print(s, f"HFB contrast at true onsets {con[np.argmin(np.abs(shifts))]:.3f}; largest at shift {shifts[np.argmax(con)]:+.1f} s; range {con.min():.3f} to {con.max():.3f}")
ax[1].set(xlabel="onset shift (s)", ylabel="HFB post minus pre (s.d.)", title="HFB at shifted onsets")
plt.tight_layout()
S01 mean |audio| before onsets 3.43e-04, 0.05-0.5 s after 3.30e-02, ratio 96.4
S02 mean |audio| before onsets 3.04e-04, 0.05-0.5 s after 1.28e-02, ratio 42.1
S03 mean |audio| before onsets 2.94e-04, 0.05-0.5 s after 3.23e-02, ratio 110.0
S04 mean |audio| before onsets 7.10e-04, 0.05-0.5 s after 1.15e-02, ratio 16.1
S07 mean |audio| before onsets 1.38e+02, 0.05-0.5 s after 1.52e+03, ratio 11.1
S08 mean |audio| before onsets 3.57e+00, 0.05-0.5 s after 7.53e+02, ratio 210.7
S13 mean |audio| before onsets 2.03e+02, 0.05-0.5 s after 5.50e+02, ratio 2.7
S01 HFB contrast at true onsets 0.214; largest at shift +0.1 s; range -0.078 to 0.234
S02 HFB contrast at true onsets 0.120; largest at shift +0.2 s; range -0.038 to 0.163
S03 HFB contrast at true onsets 0.029; largest at shift +0.1 s; range -0.016 to 0.032
S04 HFB contrast at true onsets 0.160; largest at shift +0.1 s; range -0.049 to 0.200
S07 HFB contrast at true onsets 0.112; largest at shift +0.0 s; range -0.043 to 0.112
S08 HFB contrast at true onsets 0.094; largest at shift +0.1 s; range -0.041 to 0.112
S13 HFB contrast at true onsets 0.072; largest at shift +0.0 s; range -0.032 to 0.072
No description has been provided for this image

Electrode selection (Speech-R)¶

Methods, Evoked HFB and speech-responsive electrodes: each trial baselined at -800 to -100 ms, the mean post-stimulus activity per trial, a bootstrap 99% interval of the mean over trials, and Speech-R when its 0.5th percentile is above 0 in response to unfiltered speech. The claims file names three open details (1 trials, 2 window, 3 z-score); every combination is run.

Triplets with pink noise are left out of every speech analysis (Figure 3 heading "MIDDLE (context) unfiltered speech only"). The six unfiltered sentences outside any triplet in S01 to S04 (trial number -1) are left out too: they are not MIDDLE sounds of the task.

speech-r-count: 92 of the 468 electrodes (19.6%) responded to speech above baseline (Speech-R), generally centred on perisylvian regions.

In [5]:
rng = np.random.default_rng(101)
EP = {}
for s, d in D.items():
    EP[s] = ac4.hfb_epochs(d)
POST = {}
readings = []
for zmode in ["trial", "pooled", "nonevent"]:
    for win in ["sound", "2.5"]:
        for tsel in ["mid", "all"]:
            lbs = []
            for s, d in D.items():
                ep, times = EP[s]
                tr = d["trials"]
                zep = ac4.zscore_epochs(d, ep, times, zmode)
                pm = ac4.post_mean(zep, times, tr.duration.to_numpy(), win)
                POST[(s, zmode, win)] = pm
                sel = (tr.trial_num >= 0) & ~tr.noise
                if tsel == "mid":
                    sel &= tr.trial_phase == "mid"
                lbs.append(ac4.bootstrap_lower(pm[sel.to_numpy()], rng))
            lb = np.concatenate(lbs)
            E[f"lb_{zmode}_{win}_{tsel}"] = lb
            n = int((lb > 0).sum())
            readings.append(dict(zscore=zmode, window=win, trials=tsel, speech_r=n,
                                 pct_of_good=100 * n / len(E), within_92_tol=abs(n - 92) <= 9.2,
                                 **{s: int((lb[E.subject.eq(s).to_numpy()] > 0).sum()) for s in D}))
R_speech = pd.DataFrame(readings)
print(R_speech.to_string())
print(f"electrodes: {len(E)} good of {summary.channels.sum()} in the data set; paper 468 (tolerance 421.2-514.8)")
print("readings within 92 +/- 9.2:", int(R_speech.within_92_tol.sum()), "of", len(R_speech))

MAIN = ("nonevent", "2.5", "mid")
E["speech_r"] = E[f"lb_{MAIN[0]}_{MAIN[1]}_{MAIN[2]}"] > 0
print("adopted reading", MAIN, "Speech-R", int(E.speech_r.sum()))
print(pd.crosstab(E.region, E.speech_r))
      zscore window trials  speech_r  pct_of_good  within_92_tol  S01  S02  S03  S04  S07  S08  S13
0      trial  sound    mid       145    38.461538          False   33   29   11   20   19   22   11
1      trial  sound    all       185    49.071618          False   47   35   19   23   19   29   13
2      trial    2.5    mid       141    37.400531          False   30   29   12   19   18   22   11
3      trial    2.5    all       182    48.275862          False   46   35   20   20   19   29   13
4     pooled  sound    mid       138    36.604775          False   29   28   15   23   18   11   14
5     pooled  sound    all       150    39.787798          False   40   27   15   21   18   18   11
6     pooled    2.5    mid       131    34.748011          False   28   26   14   22   18   11   12
7     pooled    2.5    all       145    38.461538          False   39   27   15   20   16   17   11
8   nonevent  sound    mid       104    27.586207          False   19   22    8   16   15   10   14
9   nonevent  sound    all        96    25.464191           True   19   20    8   12   12   15   10
10  nonevent    2.5    mid       101    26.790451           True   19   22    8   16   14   10   12
11  nonevent    2.5    all        99    26.259947           True   19   21    8   12   11   16   12
electrodes: 377 good of 416 in the data set; paper 468 (tolerance 421.2-514.8)
readings within 92 +/- 9.2: 3 of 12
adopted reading ('nonevent', '2.5', 'mid') Speech-R 101
speech_r     False  True 
region                   
frontal         52     12
other           57      5
perisylvian     41     18
temporal       126     66

The reading carried into the later claims is the z-score by non-event times (the code's zscore_by_non_events), the 0 to 2.5 s window, and MIDDLE trials (the Methods): of the readings within the paper's count, it is the first in the order the claims file lists them. Only the non-event z-score gives counts near the paper's; see the record's assumptions. Sounds that overlap a span marked bad in the events table are kept, as the paper does not mention such spans (column sounds_overlapping_bad above).

Result: speech-r-count. Three of the twelve readings give a count within 92 +/- 9.2, all with the z-score by non-event times: 96 (onset to sound end, all speech trials), 101 (0 to 2.5 s, MIDDLE trials) and 99 (0 to 2.5 s, all trials). The z-score by each trial's own baseline or by the pooled baseline gives 131 to 185. The data set holds 377 good electrodes (416 in all), against the paper's 468, so 101 is 26.8% of the electrodes against the paper's 19.6%. Speech-R electrodes lie mostly on temporal (66) and perisylvian (18) sites. The count is reproduced under the non-event z-score; the electrode total differs.

HFB increase AFTER against BEFORE¶

fig3b-hfb-increase-after: Across Speech-R electrodes, HFB activity is higher in the AFTER condition than in the BEFORE condition (cluster-based permutation test, P = 0.003, n = 92).

Per electrode, the trial-averaged AFTER minus BEFORE time course of z-scored HFB (Methods, Evoked HFB: "the difference in time-varying HFB activity in each trial was calculated and then averaged across trials"), from -0.5 to 3 s (the Figure 3b axis), and MNE's one-sample cluster permutation test across electrodes (claims, open detail 11: default threshold, 10,000 permutations).

In [6]:
def diff_timecourse(zmode, sel_fn, t0=-0.5, t1=3.0):
    """(electrodes, time) of mean AFTER minus mean BEFORE z-HFB, for the electrodes of E in order."""
    out = []
    for s, d in D.items():
        ep, times = EP[s]
        zep = ac4.zscore_epochs(d, ep, times, zmode)
        tr = d["trials"]
        keep = (times >= t0) & (times <= t1)
        b = sel_fn(tr) & (tr.trial_phase == "bef")
        a = sel_fn(tr) & (tr.trial_phase == "aft")
        out.append(zep[a.to_numpy()][..., keep].mean(0) - zep[b.to_numpy()][..., keep].mean(0))
    return np.concatenate(out), times[keep]

def as_mask(cl, shape):
    m = np.zeros(shape, bool)
    m[cl] = True
    return m

def clusters_of(X, seed, n_perm=10000):
    """MNE's one-sample cluster permutation test (default threshold, two-tailed); masks."""
    T, clusters, pv, _ = mne.stats.permutation_cluster_1samp_test(X, n_permutations=n_perm, tail=0, seed=seed, out_type="mask")
    return T, [as_mask(c, X.shape[1:]) for c in clusters], pv

def cluster_report(X, label, seed, times=None, n_perm=10000):
    T, clusters, pv = clusters_of(X, seed, n_perm)
    rows = []
    for c, p in zip(clusters, pv):
        idx = np.where(c)[0] if c.ndim == 1 else None
        rows.append(dict(set=label, n=X.shape[0], p=p, sign="+" if T[c].mean() > 0 else "-",
                         start=None if idx is None or times is None else times[idx[0]],
                         end=None if idx is None or times is None else times[idx[-1]],
                         size=int(c.sum())))
    return pd.DataFrame(rows) if rows else pd.DataFrame([dict(set=label, n=X.shape[0], p=np.nan, sign="none", start=None, end=None, size=0)])

speech = lambda tr: (tr.trial_num >= 0) & ~tr.noise
out = []
for zmode in ["nonevent", "trial"]:
    DIF, tt = diff_timecourse(zmode, speech)
    for label, m in [("(a) all Speech-R", E.speech_r), ("(b) Speech-R temporal+perisylvian", E.speech_r & E.region.isin(["temporal", "perisylvian"]))]:
        r = cluster_report(DIF[m.to_numpy()], label, 3, tt)
        r["zscore"] = zmode
        out.append(r)
        if zmode == "nonevent" and label.startswith("(a)"):
            DIF_main = DIF[m.to_numpy()]
R3b = pd.concat(out, ignore_index=True)
print(R3b.to_string())
mean_d = DIF_main.mean(0)
print(f"mean AFTER-BEFORE over electrodes (a): range {mean_d.min():.3f} to {mean_d.max():.3f} z; 0-1 s mean {mean_d[(tt>=0)&(tt<1)].mean():.3f}, 1-3 s mean {mean_d[tt>=1].mean():.3f}")
for s in D:
    m = (E.subject.eq(s) & E.speech_r).to_numpy()
    sub = DIF_main[(E.subject[E.speech_r] == s).to_numpy()]
    print(s, "Speech-R", int(m.sum()), "mean AFTER-BEFORE 0-3 s", f"{sub[:, tt >= 0].mean():.3f}" if len(sub) else "n/a")
fig, ax = plt.subplots(figsize=(6, 3))
se = DIF_main.std(0) / np.sqrt(len(DIF_main))
ax.plot(tt, mean_d, color="purple")
ax.fill_between(tt, mean_d - se, mean_d + se, color="purple", alpha=0.3)
ax.axhline(0, color="k", lw=0.5)
ax.set(xlabel="time (s)", ylabel="AFTER - BEFORE HFB (z)", title=f"Speech-R electrodes, n = {len(DIF_main)}")
/home/runner/work/encore/encore/executed/holdgraf-2016/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
                                  set    n       p sign  start   end  size    zscore
0                    (a) all Speech-R  101  0.0001    +   0.36  1.28    47  nonevent
1                    (a) all Speech-R  101  0.1358    +   1.32  1.42     6  nonevent
2                    (a) all Speech-R  101  0.2565    +   1.58  1.66     5  nonevent
3                    (a) all Speech-R  101  0.0072    +   1.72  2.02    16  nonevent
4                    (a) all Speech-R  101  0.3753    -  -0.06  0.00     4  nonevent
5                    (a) all Speech-R  101  0.4307    -   2.58  2.64     4  nonevent
6                    (a) all Speech-R  101  0.1186    -   2.74  2.84     6  nonevent
7                    (a) all Speech-R  101  0.1384    -   2.90  3.00     6  nonevent
8   (b) Speech-R temporal+perisylvian   84  0.0001    +   0.40  1.42    52  nonevent
9   (b) Speech-R temporal+perisylvian   84  0.4113    +   1.58  1.64     4  nonevent
10  (b) Speech-R temporal+perisylvian   84  0.0097    +   1.74  2.02    15  nonevent
11  (b) Speech-R temporal+perisylvian   84  0.7705    -  -0.18 -0.16     2  nonevent
12  (b) Speech-R temporal+perisylvian   84  0.4999    -  -0.06 -0.02     3  nonevent
13  (b) Speech-R temporal+perisylvian   84  0.6685    -   2.58  2.62     3  nonevent
14  (b) Speech-R temporal+perisylvian   84  0.1952    -   2.76  2.84     5  nonevent
15  (b) Speech-R temporal+perisylvian   84  0.2697    -   2.92  3.00     5  nonevent
16                   (a) all Speech-R  101  0.5816    +   0.06  0.10     3     trial
17                   (a) all Speech-R  101  0.0002    +   0.30  1.28    50     trial
18                   (a) all Speech-R  101  0.1585    +   1.32  1.42     6     trial
19                   (a) all Speech-R  101  0.0035    +   1.56  2.04    25     trial
20                   (a) all Speech-R  101  0.4036    -   2.58  2.64     4     trial
21                   (a) all Speech-R  101  0.0906    -   2.72  2.86     8     trial
22                   (a) all Speech-R  101  0.1674    -   2.90  3.00     6     trial
23  (b) Speech-R temporal+perisylvian   84  0.3941    +   0.06  0.12     4     trial
24  (b) Speech-R temporal+perisylvian   84  0.8665    +   0.26  0.26     1     trial
25  (b) Speech-R temporal+perisylvian   84  0.0002    +   0.34  1.42    55     trial
26  (b) Speech-R temporal+perisylvian   84  0.0044    +   1.58  2.04    24     trial
27  (b) Speech-R temporal+perisylvian   84  0.7498    -   2.58  2.60     2     trial
28  (b) Speech-R temporal+perisylvian   84  0.1676    -   2.74  2.84     6     trial
29  (b) Speech-R temporal+perisylvian   84  0.4044    -   2.92  2.98     4     trial
mean AFTER-BEFORE over electrodes (a): range -0.088 to 0.212 z; 0-1 s mean 0.084, 1-3 s mean 0.025
S01 Speech-R 19 mean AFTER-BEFORE 0-3 s 0.039
S02 Speech-R 22 mean AFTER-BEFORE 0-3 s -0.015
S03 Speech-R 8 mean AFTER-BEFORE 0-3 s 0.107
S04 Speech-R 16 mean AFTER-BEFORE 0-3 s 0.109
S07 Speech-R 14 mean AFTER-BEFORE 0-3 s 0.032
S08 Speech-R 10 mean AFTER-BEFORE 0-3 s 0.118
S13 Speech-R 12 mean AFTER-BEFORE 0-3 s -0.012
Out[6]:
[Text(0.5, 0, 'time (s)'),
 Text(0, 0.5, 'AFTER - BEFORE HFB (z)'),
 Text(0.5, 1.0, 'Speech-R electrodes, n = 101')]
No description has been provided for this image

Result: fig3b-hfb-increase-after. Over the 101 Speech-R electrodes, AFTER is higher than BEFORE in a cluster from 0.36 to 1.28 s (P = 0.0001) and in a second from 1.72 to 2.02 s (P = 0.0072); the 84 Speech-R electrodes on temporal or perisylvian cortex give a cluster from 0.40 to 1.42 s (P = 0.0001), and the per-trial baseline z-score gives the same (P = 0.0002). The mean difference is 0.084 z over 0 to 1 s. Two of seven subjects (S02, S13) have a slightly negative mean difference. Reproduced.

Pink noise triplets: no HFB change¶

supp3a-pink-noise-no-hfb-change: In the three subjects with pink noise trials, evoked HFB does not differ between AFTER and BEFORE when the MIDDLE sound was pink noise.

The same test on the pink noise triplets of S07, S08 and S13. The electrode set (a), the electrodes included in the eSTRF analyses, is computed below with the eSTRF selection; it is reported in that section. Set (b), the Speech-R electrodes of the three subjects, is here.

In [7]:
noise_tr = lambda tr: (tr.trial_num >= 0) & tr.noise
noise_subjects = ["S07", "S08", "S13"]
def noise_diff(zmode="nonevent"):
    out = []
    for s in noise_subjects:
        d = D[s]
        ep, times = EP[s]
        zep = ac4.zscore_epochs(d, ep, times, zmode)
        tr = d["trials"]
        keep = (times >= -0.5) & (times <= 3.0)
        b = (noise_tr(tr) & (tr.trial_phase == "bef")).to_numpy()
        a = (noise_tr(tr) & (tr.trial_phase == "aft")).to_numpy()
        out.append(zep[a][..., keep].mean(0) - zep[b][..., keep].mean(0))
    return np.concatenate(out), times[keep]
DIFN, ttn = noise_diff()
EN = E[E.subject.isin(noise_subjects)].reset_index(drop=True)
r = cluster_report(DIFN[EN.speech_r.to_numpy()], "(b) Speech-R of S07, S08, S13", 5, ttn)
print(r.to_string())
print("speech triplets of the same subjects and electrodes, for comparison:")
DIFS = diff_timecourse("nonevent", speech)[0][E.subject.isin(noise_subjects).to_numpy()]
print(cluster_report(DIFS[EN.speech_r.to_numpy()], "(b) speech triplets", 5, ttn).to_string())
mn, ms = DIFN[EN.speech_r.to_numpy()][:, ttn >= 0], DIFS[EN.speech_r.to_numpy()][:, ttn >= 0]
print(f"AFTER-BEFORE mean over (b), 0-3 s: pink noise {mn.mean():.6f} z, speech {ms.mean():.6f} z; s.e. over electrodes {mn.mean(1).std(ddof=1) / np.sqrt(len(mn)):.4f} and {ms.mean(1).std(ddof=1) / np.sqrt(len(ms)):.4f}")
print(f"largest absolute difference between the pink noise and speech time courses: {np.abs(mn - ms).max():.3f} z; correlation over electrodes of their 0-3 s means {np.corrcoef(mn.mean(1), ms.mean(1))[0, 1]:.3f}")
                              set   n       p sign  start   end  size
0   (b) Speech-R of S07, S08, S13  36  0.1126    +   0.34  0.44     6
1   (b) Speech-R of S07, S08, S13  36  0.3279    +   0.56  0.62     4
2   (b) Speech-R of S07, S08, S13  36  0.8719    +   1.12  1.14     2
3   (b) Speech-R of S07, S08, S13  36  0.1065    +   1.32  1.42     6
4   (b) Speech-R of S07, S08, S13  36  0.3901    +   1.48  1.54     4
5   (b) Speech-R of S07, S08, S13  36  0.9288    +   2.10  2.10     1
6   (b) Speech-R of S07, S08, S13  36  0.5859    +   2.32  2.36     3
7   (b) Speech-R of S07, S08, S13  36  0.0895    +   2.50  2.60     6
8   (b) Speech-R of S07, S08, S13  36  0.9359    +   2.80  2.80     1
9   (b) Speech-R of S07, S08, S13  36  0.7204    -  -0.50 -0.48     2
10  (b) Speech-R of S07, S08, S13  36  0.5139    -   1.66  1.70     3
speech triplets of the same subjects and electrodes, for comparison:
                   set   n       p sign  start   end  size
0  (b) speech triplets  36  0.0013    +   0.50  0.74    13
1  (b) speech triplets  36  0.0639    +   0.88  1.02     8
2  (b) speech triplets  36  0.8165    +   1.34  1.36     2
3  (b) speech triplets  36  0.0110    +   1.78  1.96    10
4  (b) speech triplets  36  0.9362    +   2.46  2.46     1
5  (b) speech triplets  36  0.0029    -  -0.22  0.02    13
6  (b) speech triplets  36  0.2002    -   1.46  1.54     5
7  (b) speech triplets  36  0.3608    -   2.76  2.82     4
8  (b) speech triplets  36  0.2613    -   2.92  3.00     5
AFTER-BEFORE mean over (b), 0-3 s: pink noise 0.040913 z, speech 0.041035 z; s.e. over electrodes 0.0186 and 0.0169
largest absolute difference between the pink noise and speech time courses: 1.541 z; correlation over electrodes of their 0-3 s means 0.607

HFB over the session¶

supp5b-hfb-stable-over-session: Mean HFB activity of Speech-R electrodes shows no significant relation to trial number over a session.

The paper's test is a bootstrap of the regression slope on trial number (ecogtools bootstrap_coefficients, 1000 resamples, as the claims file gives it). The value is the mean post-stimulus HFB of each speech sound (all three phases, 0 to 2.5 s), and trial number the triplet number. Two units, as the criterion names: (a) every Speech-R electrode's value per sound, pooled; (b) the mean over Speech-R electrodes per sound and subject. The z-score is open (claims, open detail 3), and the z-score by non-event times is fixed over the session, so a slow drift appears as a slope, while a per-trial baseline removes it; all three readings are run. Values of one sound are not independent across electrodes, so unit (a) is also bootstrapped by resampling whole sounds, and unit (b) by resampling whole subjects.

In [8]:
rng = np.random.default_rng(505)
def boot_slope(x, y, rng, n=1000, groups=None):
    """Slope of y on x and its 95% bootstrap interval; with groups, whole groups are resampled."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    slopes = np.empty(n)
    if groups is not None:
        ug, inv = np.unique(groups, return_inverse=True)
        members = [np.where(inv == k)[0] for k in range(len(ug))]
    for i in range(n):
        if groups is None:
            j = rng.integers(0, len(x), len(x))
        else:
            j = np.concatenate([members[k] for k in rng.integers(0, len(ug), len(ug))])
        slopes[i] = np.polyfit(x[j], y[j], 1)[0]
    return np.polyfit(x, y, 1)[0], np.percentile(slopes, [2.5, 97.5])
rows, sub_rows = [], []
for zmode in ["nonevent", "trial", "pooled"]:
    xa, ya, ga, xb, yb, gb = [], [], [], [], [], []
    for s, d in D.items():
        tr = d["trials"]
        sel = speech(tr).to_numpy()
        pm = POST[(s, zmode, MAIN[1])][sel][:, E.loc[E.subject.eq(s), "speech_r"].to_numpy()]
        tn = tr.trial_num.to_numpy()[sel]
        if pm.shape[1] == 0:
            continue
        xa.append(np.repeat(tn, pm.shape[1])); ya.append(pm.ravel())
        ga.append(np.repeat([f"{s}-{k}" for k in range(len(tn))], pm.shape[1]))   # one group per sound
        xb.append(tn); yb.append(pm.mean(1)); gb.append(np.full(len(tn), s))
        sl, ci = boot_slope(tn, pm.mean(1), rng)
        sub_rows.append(dict(zscore=zmode, subject=s, sounds=len(tn), speech_r=pm.shape[1], slope=sl, lo=ci[0], hi=ci[1]))
    xa, ya, ga, xb, yb, gb = map(np.concatenate, (xa, ya, ga, xb, yb, gb))
    for lab, x, y, g in [("(a) electrode x sound, pairs resampled", xa, ya, None),
                         ("(a) electrode x sound, sounds resampled", xa, ya, ga),
                         ("(b) mean over electrodes per sound", xb, yb, None),
                         ("(b) mean per sound, subjects resampled", xb, yb, gb)]:
        sl, ci = boot_slope(x, y, rng, groups=g)
        rows.append(dict(zscore=zmode, unit=lab, slope=sl, lo=ci[0], hi=ci[1], includes_0=ci[0] <= 0 <= ci[1],
                         change_over_57_triplets=57 * sl))
R5b = pd.DataFrame(rows)
print(R5b.to_string())
print("per subject (mean over electrodes per sound):")
S5b = pd.DataFrame(sub_rows)
S5b["includes_0"] = (S5b.lo <= 0) & (S5b.hi >= 0)
print(S5b.to_string())
print(S5b.groupby("zscore").apply(lambda t: f"{int((t.hi < 0).sum())} below 0, {int((t.lo > 0).sum())} above 0, {int(t.includes_0.sum())} include 0").to_string())
      zscore                                     unit     slope        lo        hi  includes_0  change_over_57_triplets
0   nonevent   (a) electrode x sound, pairs resampled -0.002201 -0.002793 -0.001681       False                -0.125483
1   nonevent  (a) electrode x sound, sounds resampled -0.002201 -0.003157 -0.001181       False                -0.125483
2   nonevent       (b) mean over electrodes per sound -0.001855 -0.002904 -0.000835       False                -0.105744
3   nonevent   (b) mean per sound, subjects resampled -0.001855 -0.003912  0.000011        True                -0.105744
4      trial   (a) electrode x sound, pairs resampled -0.002090 -0.003728 -0.000482       False                -0.119146
5      trial  (a) electrode x sound, sounds resampled -0.002090 -0.005628  0.001039        True                -0.119146
6      trial       (b) mean over electrodes per sound -0.003170 -0.006313  0.000078        True                -0.180687
7      trial   (b) mean per sound, subjects resampled -0.003170 -0.010485  0.001448        True                -0.180687
8     pooled   (a) electrode x sound, pairs resampled -0.002441 -0.003384 -0.001461       False                -0.139164
9     pooled  (a) electrode x sound, sounds resampled -0.002441 -0.004372 -0.000519       False                -0.139164
10    pooled       (b) mean over electrodes per sound -0.003017 -0.004866 -0.001193       False                -0.171956
11    pooled   (b) mean per sound, subjects resampled -0.003017 -0.007158 -0.000435       False                -0.171956
per subject (mean over electrodes per sound):
      zscore subject  sounds  speech_r     slope        lo        hi  includes_0
0   nonevent     S01     168        19 -0.002516 -0.003890 -0.001000       False
1   nonevent     S02     140        22 -0.002527 -0.004664 -0.000470       False
2   nonevent     S03     115         8 -0.002150 -0.004041 -0.000240       False
3   nonevent     S04      96        16 -0.001982 -0.008615  0.004914        True
4   nonevent     S07      87        14 -0.002821 -0.005044 -0.000451       False
5   nonevent     S08      87        10 -0.004236 -0.006667 -0.001513       False
6   nonevent     S13      87        12 -0.004176 -0.006302 -0.001951       False
7      trial     S01     168        19 -0.002210 -0.007757  0.003207        True
8      trial     S02     140        22 -0.002061 -0.006370  0.002254        True
9      trial     S03     115         8 -0.007013 -0.016924  0.002182        True
10     trial     S04      96        16 -0.007290 -0.022380  0.006766        True
11     trial     S07      87        14 -0.005653 -0.011252 -0.000998       False
12     trial     S08      87        10 -0.004215 -0.011264  0.003625        True
13     trial     S13      87        12 -0.002933 -0.007799  0.001330        True
14    pooled     S01     168        19 -0.004554 -0.007005 -0.001861       False
15    pooled     S02     140        22 -0.002658 -0.004908 -0.000567       False
16    pooled     S03     115         8 -0.005189 -0.009811 -0.000294       False
17    pooled     S04      96        16 -0.002917 -0.011554  0.005450        True
18    pooled     S07      87        14 -0.003091 -0.005396 -0.000556       False
19    pooled     S08      87        10 -0.004577 -0.007354 -0.001797       False
20    pooled     S13      87        12 -0.003954 -0.006101 -0.001884       False
zscore
nonevent    6 below 0, 0 above 0, 1 include 0
pooled      6 below 0, 0 above 0, 1 include 0
trial       1 below 0, 0 above 0, 6 include 0

Result: supp5b-hfb-stable-over-session. The slope of HFB on trial number is negative under every z-score and unit, about -0.1 to -0.18 z over 57 triplets. With the adopted z-score by non-event times, the 95% interval excludes 0 for unit (a) whether pairs or whole sounds are resampled (-0.0032 to -0.0012 with sounds) and for unit (b) (-0.0029 to -0.0008); resampling whole subjects in unit (b) gives -0.0039 to 0.00001, which just includes 0. The pooled baseline z-score excludes 0 under all four bootstraps. The per-trial baseline z-score includes 0 under three of four (unit (a) with sounds resampled, -0.0056 to 0.0010; unit (b), -0.0063 to 0.0001) and excludes it under the fourth (unit (a) with pairs resampled, -0.0037 to -0.0005), and only one of seven subjects has an interval below 0 with it, against six of seven with the other two z-scores. The claim of absence is not reproduced under the adopted z-score, the one carried into every HFB claim; under the per-trial baseline the absence holds with the grouped bootstraps (sounds or subjects resampled) and not with pairs resampled, so the outcome rests on the z-score.

Between-condition coherence¶

fig4a-coherence-after-higher / fig4b-coherence-sentence-specific

Methods, Between-condition coherence: per sentence, the coherence of the HFB time course between BEFORE and MIDDLE and between AFTER and MIDDLE, in 400 ms windows stepped by 200 ms from -500 to 2500 ms, jackknife-corrected, converted to bits/s, averaged over trials; then the sign-flip test of AFTER/MIDDLE minus BEFORE/MIDDLE across electrodes for the ranges of Figure 4 (-1 to 0, 0 to 1, 1 to 2.5 s). The multitaper bandwidth is open (claims, open detail 10), whose standard choice is MNE's multitaper default: a normalized half-bandwidth of 4 (_compute_mt_params with bandwidth=None), which for a 20-sample window gives seven tapers with concentration above 0.9. That is the main reading; NW = 2 (three tapers, the first revision's choice) is a variant. The coherence is integrated over all frequencies from 2.5 to 25 Hz: 2.5 Hz (1 / 400 ms) is the lowest frequency the window resolves, read here as the claims file's "lowest resolved frequency". The tapers smooth the spectrum over plus or minus W = NW / 0.4 s (10 Hz at NW = 4, 5 Hz at NW = 2), so a variant integrates from W. A window belongs to a range when it lies wholly inside it, so the -1 to 0 s range has one window (-0.5 to -0.1 s); assigning windows by their centre, which lets the window from -0.3 to 0.1 s into the pre-stimulus range, is shown as a variant. Electrode sets: (a) Speech-R on temporal or perisylvian cortex, (b) all temporal or perisylvian electrodes. Panel b subtracts from each trial the electrode's mean time course, (a) over all trials of all three conditions, (b) per condition.

In [9]:
def complete_triplets(tr):
    """Speech triplets with one BEFORE, one MIDDLE and one AFTER sound."""
    t = tr[speech(tr)]
    g = t.groupby("trial_num").trial_phase.apply(lambda x: sorted(x) == ["aft", "bef", "mid"])
    return sorted(g.index[g])

WIN_STARTS = np.round(np.arange(-0.5, 2.1001, 0.2), 1)
WIN_CENTRES = WIN_STARTS + 0.2
def coherence_bits(subtract=None, nw=4.0, fmin=None):
    """(electrodes of E, 2 pairs, windows) mean over triplets of integrated coherence in bits/s."""
    out = []
    for s, d in D.items():
        ep, times = EP[s]
        zep = ac4.zscore_epochs(d, ep, times, MAIN[0])
        tr = d["trials"]
        tsel = speech(tr)
        trip = complete_triplets(tr)
        ix = {ph: [tr.index[(tr.trial_num == n) & (tr.trial_phase == ph)][0] for n in trip] for ph in ["bef", "mid", "aft"]}
        X = {ph: zep[ix[ph]] for ph in ix}
        if subtract == "all":
            m = zep[tsel.to_numpy()].mean(0)
            X = {ph: X[ph] - m for ph in X}
        elif subtract == "condition":
            X = {ph: X[ph] - X[ph].mean(0) for ph in X}
        res = np.empty((zep.shape[1], 2, len(WIN_STARTS)))
        for w, ws in enumerate(WIN_STARTS):
            sel = (times >= ws - 1e-9) & (times < ws + 0.4 - 1e-9)
            for k, ph in enumerate(["bef", "aft"]):
                f, c = ac4.mt_coherence(X[ph][..., sel], X["mid"][..., sel], ac4.FS_OUT, nw=nw)
                res[:, k, w] = ac4.coh_to_bits(c, f, fmin=fmin).mean(0)
        out.append(res)
    return np.concatenate(out), f

def window_tests(C, mask, rng, label, assign="inside"):
    """Sign-flip tests per range of Figure 4. A window belongs to a range when it lies wholly
    inside it ("inside", the main reading) or when its centre does ("centre")."""
    rows = []
    for name, lo, hi in [("-1 to 0 s", -1, 0), ("0 to 1 s", 0, 1), ("1 to 2.5 s", 1, 2.5)]:
        if assign == "inside":
            w = (WIN_STARTS >= lo - 1e-9) & (WIN_STARTS + 0.4 <= hi + 1e-9)
        else:
            w = (WIN_CENTRES >= lo) & (WIN_CENTRES < (hi if hi < 2.5 else 2.6))
        diff = (C[mask][:, 1, w] - C[mask][:, 0, w]).mean(1)
        obs, p = ac4.signflip_test(diff, rng)
        rows.append(dict(set=label, window=name, assign=assign, n=int(mask.sum()), windows=int(w.sum()),
                         bef_mid=C[mask][:, 0, w].mean(), aft_mid=C[mask][:, 1, w].mean(),
                         diff=obs, se=diff.std(ddof=1) / np.sqrt(len(diff)), p=p))
    return rows

rng = np.random.default_rng(404)
peri = E.region.isin(["temporal", "perisylvian"]).to_numpy()
sets4 = {"(a) Speech-R temporal+perisylvian": peri & E.speech_r.to_numpy(), "(b) all temporal+perisylvian": peri}
COH4 = {nw: coherence_bits(None, nw) for nw in [4.0, 2.0]}
C4a, fr = COH4[4.0]
print("coherence frequencies (Hz):", fr)
rows = []
for nw, (C, _) in COH4.items():
    for assign in ["inside", "centre"]:
        for k, m in sets4.items():
            for r in window_tests(C, m, rng, k, assign):
                r["NW"] = nw
                rows.append(r)
for nw in [4.0, 2.0]:
    C, _ = coherence_bits(None, nw, fmin=nw / 0.4)
    for k, m in sets4.items():
        for r in window_tests(C, m, rng, k):
            r["NW"] = f"{nw:g}, from {nw / 0.4:g} Hz"
            rows.append(r)
R4a = pd.DataFrame(rows)
print("windows per range (inside):", [int(((WIN_STARTS >= lo - 1e-9) & (WIN_STARTS + 0.4 <= hi + 1e-9)).sum()) for lo, hi in [(-1, 0), (0, 1), (1, 2.5)]])
print(R4a.to_string())
print("NW = 4, per subject, set (a), 0-2.5 s AFTER/MIDDLE minus BEFORE/MIDDLE (bits/s):")
for s in D:
    m = sets4["(a) Speech-R temporal+perisylvian"] & E.subject.eq(s).to_numpy()
    w = WIN_CENTRES >= 0
    print(" ", s, int(m.sum()), f"{(C4a[m][:, 1, w] - C4a[m][:, 0, w]).mean():.3f}" if m.any() else "n/a")
m = sets4["(a) Speech-R temporal+perisylvian"]
fig, ax = plt.subplots(figsize=(6, 3))
for k, lab in enumerate(["BEFORE/MIDDLE", "AFTER/MIDDLE"]):
    ax.plot(WIN_CENTRES, C4a[m][:, k].mean(0), label=lab)
ax.set(xlabel="window centre (s)", ylabel="coherence (bits/s)")
ax.legend()
print(f"plotted range {C4a[m].mean(0).min():.3f} to {C4a[m].mean(0).max():.3f} bits/s")
coherence frequencies (Hz): [ 0.   2.5  5.   7.5 10.  12.5 15.  17.5 20.  22.5 25. ]
windows per range (inside): [1, 3, 6]
                                  set      window  assign    n  windows    bef_mid    aft_mid      diff        se         p             NW
0   (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  14.549696  14.859542  0.309846  0.209722  0.142886            4.0
1   (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  16.366095  17.163752  0.797657  0.198935  0.000300            4.0
2   (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  14.742170  15.235760  0.493590  0.138851  0.000400            4.0
3        (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  14.545115  14.746053  0.200939  0.125835  0.111289            4.0
4        (b) all temporal+perisylvian    0 to 1 s  inside  251        3  15.312292  15.387504  0.075213  0.098390  0.443756            4.0
5        (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  14.669028  14.893811  0.224783  0.063534  0.000300            4.0
6   (a) Speech-R temporal+perisylvian   -1 to 0 s  centre   84        2  14.883749  14.920439  0.036690  0.162430  0.824018            4.0
7   (a) Speech-R temporal+perisylvian    0 to 1 s  centre   84        5  16.333642  16.982196  0.648554  0.172232  0.000200            4.0
8   (a) Speech-R temporal+perisylvian  1 to 2.5 s  centre   84        7  14.746254  15.225781  0.479527  0.138124  0.000300            4.0
9        (b) all temporal+perisylvian   -1 to 0 s  centre  251        2  14.880531  14.854822 -0.025708  0.094327  0.788421            4.0
10       (b) all temporal+perisylvian    0 to 1 s  centre  251        5  15.295196  15.348202  0.053006  0.085320  0.542946            4.0
11       (b) all temporal+perisylvian  1 to 2.5 s  centre  251        7  14.675815  14.888440  0.212625  0.062969  0.000500            4.0
12  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  14.001857  14.549825  0.547968  0.216357  0.012899            2.0
13  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  14.789821  15.287232  0.497410  0.152272  0.001200            2.0
14  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  13.880494  14.152968  0.272474  0.107676  0.013399            2.0
15       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  13.989890  14.313331  0.323441  0.133853  0.014799            2.0
16       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  14.556094  14.579439  0.023345  0.087173  0.788121            2.0
17       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  14.115003  14.269176  0.154173  0.060035  0.010899            2.0
18  (a) Speech-R temporal+perisylvian   -1 to 0 s  centre   84        2  14.425669  14.700491  0.274822  0.181822  0.137286            2.0
19  (a) Speech-R temporal+perisylvian    0 to 1 s  centre   84        5  15.224524  15.623717  0.399192  0.127009  0.002300            2.0
20  (a) Speech-R temporal+perisylvian  1 to 2.5 s  centre   84        7  13.820454  14.109433  0.288979  0.099031  0.004100            2.0
21       (b) all temporal+perisylvian   -1 to 0 s  centre  251        2  14.472130  14.515362  0.043232  0.102152  0.672433            2.0
22       (b) all temporal+perisylvian    0 to 1 s  centre  251        5  14.690244  14.657413 -0.032831  0.072333  0.660134            2.0
23       (b) all temporal+perisylvian  1 to 2.5 s  centre  251        7  14.117202  14.239559  0.122357  0.056044  0.029897            2.0
24  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  11.270309  11.491552  0.221243  0.172188  0.208979  4, from 10 Hz
25  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  11.502075  11.784770  0.282695  0.114989  0.012799  4, from 10 Hz
26  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  10.983693  11.211396  0.227703  0.072932  0.001900  4, from 10 Hz
27       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  11.259023  11.323129  0.064106  0.097499  0.515748  4, from 10 Hz
28       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  11.534896  11.525484 -0.009412  0.065633  0.884412  4, from 10 Hz
29       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  11.211377  11.347130  0.135753  0.041505  0.001300  4, from 10 Hz
30  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  13.091081  13.626010  0.534929  0.215770  0.014099   2, from 5 Hz
31  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  13.494256  13.813158  0.318902  0.142609  0.027597   2, from 5 Hz
32  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  12.860621  13.064731  0.204110  0.097519  0.038196   2, from 5 Hz
33       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  13.097786  13.379219  0.281433  0.128861  0.031797   2, from 5 Hz
34       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  13.534821  13.519627 -0.015194  0.082756  0.854015   2, from 5 Hz
35       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  13.177140  13.308559  0.131419  0.057196  0.019998   2, from 5 Hz
NW = 4, per subject, set (a), 0-2.5 s AFTER/MIDDLE minus BEFORE/MIDDLE (bits/s):
  S01 11 1.491
  S02 16 -0.127
  S03 8 -0.052
  S04 16 1.128
  S07 13 0.389
  S08 10 0.625
  S13 10 0.288
plotted range 14.500 to 18.049 bits/s
No description has been provided for this image

Result: fig4a-coherence-after-higher. With NW = 4, over the 84 Speech-R electrodes on temporal or perisylvian cortex, AFTER/MIDDLE coherence is higher than BEFORE/MIDDLE in both post-stimulus ranges (0 to 1 s: +0.80 bits/s, P = 0.0003; 1 to 2.5 s: +0.49 bits/s, P = 0.0004) and not before the sound (+0.31, P = 0.14). Assigning windows by centre gives the same (P = 0.0002, 0.0003; before the sound 0.82). Over all 251 temporal or perisylvian electrodes only the late range differs (P = 0.0003; 0 to 1 s P = 0.44). With NW = 2 set (a) also passes both ranges (P = 0.0012 and 0.013), but the pre-stimulus window differs too (P = 0.013), unlike the paper's 0.924. Five of seven subjects have a positive mean difference (S02 and S03 slightly negative). Integrated from W = 10 Hz, the lowest frequency the tapers resolve apart from 0 Hz, set (a) still passes both ranges (P = 0.013 and 0.0019) and not the pre-stimulus window (P = 0.21); NW = 2 integrated from 5 Hz keeps the NW = 2 pattern (P = 0.028 and 0.038; before the sound 0.014). Reproduced on the Speech-R set, under the claims file's standard bandwidth.

In [10]:
rng = np.random.default_rng(405)
rows = []
for nw in [4.0, 2.0]:
    for sub in ["all", "condition"]:
        C4b, _ = coherence_bits(sub, nw)
        for r in sum([window_tests(C4b, m, rng, k) for k, m in sets4.items()], []):
            r["subtracted"] = "(a) mean over all trials" if sub == "all" else "(b) mean per condition"
            r["NW"] = nw
            rows.append(r)
for nw in [4.0, 2.0]:
    for sub in ["all", "condition"]:
        C4b, _ = coherence_bits(sub, nw, fmin=nw / 0.4)
        for r in sum([window_tests(C4b, m, rng, k) for k, m in sets4.items()], []):
            r["subtracted"] = "(a) mean over all trials" if sub == "all" else "(b) mean per condition"
            r["NW"] = f"{nw:g}, from {nw / 0.4:g} Hz"
            rows.append(r)
R4b = pd.DataFrame(rows)
print(R4b.to_string())
                                  set      window  assign    n  windows    bef_mid    aft_mid      diff        se         p                subtracted             NW
0   (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  14.488589  14.675746  0.187158  0.196043  0.339366  (a) mean over all trials            4.0
1   (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  14.541312  14.749859  0.208548  0.148675  0.165383  (a) mean over all trials            4.0
2   (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  14.286884  14.573153  0.286269  0.102618  0.006799  (a) mean over all trials            4.0
3        (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  14.567793  14.672844  0.105051  0.120703  0.382362  (a) mean over all trials            4.0
4        (b) all temporal+perisylvian    0 to 1 s  inside  251        3  14.644011  14.583311 -0.060700  0.082236  0.459654  (a) mean over all trials            4.0
5        (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  14.517653  14.650878  0.133224  0.054374  0.015198  (a) mean over all trials            4.0
6   (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  14.504466  14.593704  0.089238  0.197955  0.653235    (b) mean per condition            4.0
7   (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  14.258274  14.597196  0.338922  0.137344  0.014299    (b) mean per condition            4.0
8   (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  14.201102  14.619675  0.418573  0.104622  0.000100    (b) mean per condition            4.0
9        (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  14.627240  14.521968 -0.105272  0.127003  0.403560    (b) mean per condition            4.0
10       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  14.510790  14.492636 -0.018154  0.081623  0.820618    (b) mean per condition            4.0
11       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  14.404329  14.656953  0.252624  0.063753  0.000200    (b) mean per condition            4.0
12  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  14.188092  14.558183  0.370091  0.219380  0.098690  (a) mean over all trials            2.0
13  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  14.080218  14.435975  0.355757  0.122515  0.004100  (a) mean over all trials            2.0
14  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  13.951906  14.115625  0.163720  0.101547  0.111189  (a) mean over all trials            2.0
15       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  14.163709  14.414073  0.250364  0.138213  0.066393  (a) mean over all trials            2.0
16       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  14.331424  14.308937 -0.022488  0.079327  0.775622  (a) mean over all trials            2.0
17       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  14.196530  14.290465  0.093935  0.060132  0.124888  (a) mean over all trials            2.0
18  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  14.294080  14.544067  0.249987  0.222358  0.263474    (b) mean per condition            2.0
19  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  13.972955  14.324800  0.351846  0.134438  0.010899    (b) mean per condition            2.0
20  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  14.045027  14.301526  0.256499  0.101346  0.011999    (b) mean per condition            2.0
21       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  14.316557  14.323709  0.007152  0.131922  0.953405    (b) mean per condition            2.0
22       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  14.284405  14.322512  0.038107  0.077293  0.626237    (b) mean per condition            2.0
23       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  14.214361  14.371705  0.157344  0.062287  0.013699    (b) mean per condition            2.0
24  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  11.401533  11.550808  0.149275  0.163029  0.361464  (a) mean over all trials  4, from 10 Hz
25  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  11.241217  11.470925  0.229708  0.096423  0.019698  (a) mean over all trials  4, from 10 Hz
26  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  11.125374  11.297304  0.171930  0.071718  0.018598  (a) mean over all trials  4, from 10 Hz
27       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  11.384433  11.402590  0.018156  0.093472  0.845115  (a) mean over all trials  4, from 10 Hz
28       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  11.461985  11.461172 -0.000814  0.059572  0.989401  (a) mean over all trials  4, from 10 Hz
29       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  11.317558  11.415225  0.097667  0.041825  0.018798  (a) mean over all trials  4, from 10 Hz
30  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  11.400924  11.479230  0.078306  0.159977  0.624138    (b) mean per condition  4, from 10 Hz
31  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  11.249903  11.514596  0.264694  0.098246  0.008699    (b) mean per condition  4, from 10 Hz
32  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  11.197459  11.387043  0.189584  0.071220  0.009899    (b) mean per condition  4, from 10 Hz
33       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  11.429776  11.337231 -0.092546  0.096144  0.337266    (b) mean per condition  4, from 10 Hz
34       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  11.443097  11.480037  0.036940  0.059207  0.528247    (b) mean per condition  4, from 10 Hz
35       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  11.321406  11.471499  0.150093  0.046998  0.001600    (b) mean per condition  4, from 10 Hz
36  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  13.342410  13.681286  0.338876  0.216161  0.128887  (a) mean over all trials   2, from 5 Hz
37  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  13.189936  13.531682  0.341746  0.118193  0.005299  (a) mean over all trials   2, from 5 Hz
38  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  13.090483  13.222979  0.132496  0.098157  0.178282  (a) mean over all trials   2, from 5 Hz
39       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  13.306264  13.508561  0.202296  0.134509  0.133187  (a) mean over all trials   2, from 5 Hz
40       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  13.463337  13.455374 -0.007963  0.076931  0.911809  (a) mean over all trials   2, from 5 Hz
41       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  13.325605  13.412694  0.087089  0.059290  0.135386  (a) mean over all trials   2, from 5 Hz
42  (a) Speech-R temporal+perisylvian   -1 to 0 s  inside   84        1  13.433961  13.672339  0.238378  0.218556  0.283672    (b) mean per condition   2, from 5 Hz
43  (a) Speech-R temporal+perisylvian    0 to 1 s  inside   84        3  13.150798  13.487910  0.337112  0.129926  0.011299    (b) mean per condition   2, from 5 Hz
44  (a) Speech-R temporal+perisylvian  1 to 2.5 s  inside   84        6  13.213864  13.407862  0.193998  0.095612  0.042996    (b) mean per condition   2, from 5 Hz
45       (b) all temporal+perisylvian   -1 to 0 s  inside  251        1  13.444244  13.435315 -0.008929  0.128273  0.945105    (b) mean per condition   2, from 5 Hz
46       (b) all temporal+perisylvian    0 to 1 s  inside  251        3  13.436490  13.505278  0.068788  0.075583  0.363364    (b) mean per condition   2, from 5 Hz
47       (b) all temporal+perisylvian  1 to 2.5 s  inside  251        6  13.373560  13.504328  0.130768  0.059814  0.030197    (b) mean per condition   2, from 5 Hz

Result: fig4b-coherence-sentence-specific. With NW = 4, after subtracting the mean time course, the 1 to 2.5 s range still shows higher AFTER/MIDDLE coherence on the Speech-R set, with the mean over all trials subtracted (+0.29 bits/s, P = 0.0068) and with the mean per condition (+0.42, P = 0.0001). The 0 to 1 s range is not significant with the mean over all trials subtracted (P = 0.17, as in the paper, 0.241) and is with the mean per condition (P = 0.014). On all temporal or perisylvian electrodes the late range gives P = 0.015 and 0.0002. With NW = 2 the late range on the Speech-R set gives P = 0.11 (mean over all trials) and 0.012 (per condition). Integrated from W = 10 Hz at NW = 4, the late range still passes on the Speech-R set (P = 0.019 with the mean over all trials, 0.0099 per condition), and 0 to 1 s is then significant under both subtractions (P = 0.020 and 0.0087); NW = 2 from 5 Hz gives P = 0.18 and 0.043 for the late range. Reproduced on the Speech-R set under the standard bandwidth; with three tapers it holds under one of the two subtractions.

eSTRF fits¶

Methods, eSTRF model formulation: ridge regression of HFB on the auditory spectrogram at lags 0 to 400 ms, inputs and outputs z-scored (with the training trials' statistics here), one trial left out per split, R2 on the held-out trial; the ridge parameter is the mode of the per-split best values over active (Speech-R) electrodes and all conditions, and every model is re-fit with it; coefficients averaged over splits, and their mean over s.d. across splits where the paper says so. The ridge grid is a standard choice (log-spaced, 1 to 1e8), checked below to have its mode inside the grid. Samples per trial (claims, open detail 7): (a) onset to offset, the main reading; (b) onset to 400 ms after offset, run for the selection counts.

In [11]:
ALPHAS = np.logspace(0, 8, 17)
def cond_idx(tr, phase, noise=False, filt=None):
    sel = (tr.trial_num >= 0) & (tr.noise == noise) & (tr.trial_phase == phase)
    if filt is not None:
        sel &= tr.filt_type == filt
    return np.where(sel.to_numpy())[0]

t0 = time.time()
best, best_el = [], []
for s, d in D.items():
    sr = E.loc[E.subject.eq(s), "speech_r"].to_numpy()
    for ph in ["bef", "mid", "aft"]:
        Xs, ys = ac4.trial_design(d, cond_idx(d["trials"], ph))
        _, r2 = ac4.ridge_loto(Xs, ys, ALPHAS)
        best.append(ALPHAS[r2.argmax(1)][:, sr].ravel())
        best_el.append(ALPHAS[r2.mean(0).argmax(0)][sr])
best = np.concatenate(best)
vals, counts = np.unique(best, return_counts=True)
print(pd.Series(counts, index=[f"{v:.0e}" for v in vals]).to_string())
print(f"mode of all split values {vals[np.argmax(counts)]:.0e}, the top of the grid: in these splits no alpha predicts the held-out trial better than the null model")
inner = best[best < ALPHAS[-1]]
vals_i, counts_i = np.unique(inner, return_counts=True)
ALPHA = vals_i[np.argmax(counts_i)]
v_el, c_el = np.unique(np.concatenate(best_el), return_counts=True)
print(f"adopted: mode over split values below the top of the grid {ALPHA:.0e} ({len(inner)} of {len(best)} values)")
print(f"variant: mode of each electrode's best alpha (mean R2 over splits) {v_el[np.argmax(c_el)]:.0e}")
print(f"{time.time() - t0:.0f} s")

FITS = {}
def fit(s, key, idx, window="sound"):
    d = D[s]
    Xs, ys = ac4.trial_design(d, idx, window)
    coefs, r2 = ac4.ridge_loto(Xs, ys, [ALPHA])
    coefs, r2 = coefs[:, 0], r2[:, 0]
    FITS[(s, key)] = dict(mean=coefs.mean(0), z=coefs.mean(0) / coefs.std(0), r2=r2, n_trials=len(idx))
t0 = time.time()
for s, d in D.items():
    tr = d["trials"]
    for ph in ["bef", "mid", "aft"]:
        fit(s, ph, cond_idx(tr, ph))
    fit(s, "mid_plus", cond_idx(tr, "mid"), "plus")
    for ph in ["bef", "aft"]:
        for fl in ["temp", "freq"]:
            fit(s, f"{ph}_{fl}", cond_idx(tr, ph, filt=fl))
    if tr.noise.any():
        for ph in ["bef", "mid", "aft"]:
            fit(s, f"noise_{ph}", cond_idx(tr, ph, noise=True))
print(f"fits done in {time.time() - t0:.0f} s")
print(pd.DataFrame([dict(subject=s, fit=k, trials=v["n_trials"], median_r2=np.median(v["r2"])) for (s, k), v in FITS.items()]).pivot(index="subject", columns="fit", values="trials").to_string())
1e+00     230
3e+00      30
1e+01      73
3e+01     150
1e+02     311
3e+02     419
1e+03     705
3e+03     989
1e+04    1218
3e+04    1316
1e+05    1402
3e+05    1072
1e+06     706
3e+06     304
1e+07     130
3e+07      54
1e+08    2751
mode of all split values 1e+08, the top of the grid: in these splits no alpha predicts the held-out trial better than the null model
adopted: mode over split values below the top of the grid 1e+05 (9109 of 11860 values)
variant: mode of each electrode's best alpha (mean R2 over splits) 1e+05
41 s
fits done in 90 s
fit       aft  aft_freq  aft_temp   bef  bef_freq  bef_temp   mid  mid_plus  noise_aft  noise_bef  noise_mid
subject                                                                                                     
S01      56.0      28.0      28.0  56.0      28.0      28.0  56.0      56.0        NaN        NaN        NaN
S02      46.0      23.0      23.0  47.0      24.0      23.0  47.0      47.0        NaN        NaN        NaN
S03      38.0      20.0      18.0  39.0      20.0      19.0  38.0      38.0        NaN        NaN        NaN
S04      32.0      16.0      16.0  32.0      16.0      16.0  32.0      32.0        NaN        NaN        NaN
S07      29.0      11.0      18.0  29.0      11.0      18.0  29.0      29.0       28.0       28.0       28.0
S08      29.0      12.0      17.0  29.0      12.0      17.0  29.0      29.0       28.0       28.0       28.0
S13      29.0      17.0      12.0  29.0      17.0      12.0  29.0      29.0       28.0       28.0       28.0

STRF-R electrodes¶

strf-r-count: 53 of 468 electrodes (11.3%) were well modelled by the eSTRF (STRF-R), generally on perisylvian temporal lobe.

Methods, STRF-responsive electrode selection: the lower bound of the R2 over cross-validation splits of the MIDDLE model above 0. Readings (claims, open detail 8): (a) 0.5th percentile of a bootstrap of the mean R2 over splits, (b) 1st percentile of the per-split R2, (c) 0.5th percentile of the per-split R2; with the samples of open detail 7, (a) and (b).

In [12]:
rng = np.random.default_rng(606)
rows = []
for key, wlab in [("mid", "(a) onset-offset"), ("mid_plus", "(b) to offset+400 ms")]:
    lb = {"a": [], "b": [], "c": []}
    for s in D:
        r2 = FITS[(s, key)]["r2"]
        lb["a"].append(ac4.bootstrap_lower(r2, rng))
        lb["b"].append(np.percentile(r2, 1, axis=0))
        lb["c"].append(np.percentile(r2, 0.5, axis=0))
    for k in lb:
        v = np.concatenate(lb[k])
        E[f"strf_{key}_{k}"] = v > 0
        rows.append(dict(samples=wlab, bound=k, strf_r=int((v > 0).sum()), within_53_tol=abs((v > 0).sum() - 53) <= 5.3,
                         **{s: int((v[E.subject.eq(s).to_numpy()] > 0).sum()) for s in D}))
R_strf = pd.DataFrame(rows)
print(R_strf.to_string())
E["mid_r2"] = np.concatenate([FITS[(s, "mid")]["r2"].mean(0) for s in D])
E["strf_r"] = E["strf_mid_a"]
print("adopted: samples (a), bound (a); STRF-R", int(E.strf_r.sum()))
print(pd.crosstab(E.region, E.strf_r))
print(f"mean held-out R2 of MIDDLE models over STRF-R electrodes: {E.loc[E.strf_r, 'mid_r2'].mean():.3f} (range {E.loc[E.strf_r, 'mid_r2'].min():.3f} to {E.loc[E.strf_r, 'mid_r2'].max():.3f})")
                samples bound  strf_r  within_53_tol  S01  S02  S03  S04  S07  S08  S13
0      (a) onset-offset     a       9          False    4    1    0    4    0    0    0
1      (a) onset-offset     b       0          False    0    0    0    0    0    0    0
2      (a) onset-offset     c       0          False    0    0    0    0    0    0    0
3  (b) to offset+400 ms     a      13          False    5    1    0    5    0    2    0
4  (b) to offset+400 ms     b       1          False    0    0    0    1    0    0    0
5  (b) to offset+400 ms     c       1          False    0    0    0    1    0    0    0
adopted: samples (a), bound (a); STRF-R 9
strf_r       False  True 
region                   
frontal         64      0
other           62      0
perisylvian     56      3
temporal       186      6
mean held-out R2 of MIDDLE models over STRF-R electrodes: 0.131 (range 0.044 to 0.226)

Alignment of the spectrogram and the HFB¶

The verifier asked whether the low STRF-R count comes from a misalignment of the stimulus and the neural signal. The MIDDLE eSTRF is refit (best ridge value per electrode, Speech-R electrodes) with the spectrogram read up to 0.5 s earlier (negative shift) or later than the HFB, against the same HFB samples; the segment is padded with its edge values where the shift runs past it. A misaligned audio track would move the best R2 away from 0. Below are also the time at which the mean spectrogram and the mean evoked HFB (Speech-R, MIDDLE) reach half their rise, the ratio of the spectrogram before onset to after it (audio that is not silent before the sound), and the distribution of the MIDDLE model's held-out R2 (adopted ridge value) per subject. The cell after looks for clock drift over the session: it splits each subject's MIDDLE trials by onset into two halves and searches the shift in each over -1 to +1 s.

In [13]:
# Alignment of spectrogram and HFB: held-out R2 of the MIDDLE eSTRF (best ridge value per
# electrode) when the spectrogram is read up to 0.5 s earlier or later against the same HFB.
t0 = time.time()
SHIFTS = np.arange(-25, 26, 5)
rows = []
for s, d in D.items():
    sr = E.loc[E.subject.eq(s), "speech_r"].to_numpy()
    idx = cond_idx(d["trials"], "mid")
    for sh in SHIFTS:
        Xs, ys = ac4.trial_design(d, idx, xshift=int(sh))
        _, r2 = ac4.ridge_loto(Xs, [y[:, sr] for y in ys], ALPHAS)
        m = r2.mean(0).max(0)
        rows.append(dict(subject=s, shift_s=sh / ac4.FS_OUT, median_r2=np.median(m), max_r2=m.max(), n_r2_pos=int((m > 0).sum())))
SH = pd.DataFrame(rows)
print("spectrogram read later by shift_s (s); Speech-R electrodes, best ridge value per electrode")
for col in ["max_r2", "median_r2", "n_r2_pos"]:
    print(col); print(SH.pivot(index="shift_s", columns="subject", values=col).round(3).to_string())
print("shift with the highest median R2 per subject:", SH.loc[SH.groupby("subject").median_r2.idxmax(), ["subject", "shift_s"]].set_index("subject").shift_s.to_dict())
print(f"{time.time() - t0:.0f} s")
# onset of the spectrogram and of the evoked HFB (Speech-R mean, MIDDLE trials), time of half rise
rows = []
for s, d in D.items():
    idx = cond_idx(d["trials"], "mid")
    sp = np.stack([d["spec"][i][:, :75].mean(0) for i in idx]).mean(0)
    ts = np.arange(75) / ac4.FS_OUT - 0.5
    ep, times = EP[s]
    sr = E.loc[E.subject.eq(s), "speech_r"].to_numpy()
    h = ac4.zscore_epochs(d, ep, times, MAIN[0])[idx][:, sr].mean((0, 1))
    half = lambda t, v, b: t[np.argmax(v > v[b].mean() + 0.5 * (v.max() - v[b].mean()))]
    rows.append(dict(subject=s, spec_half_rise_s=half(ts, sp, (ts > -0.45) & (ts < -0.1)),
                     hfb_half_rise_s=half(times, h, (times > -0.5) & (times < -0.1)),
                     spec_pre_over_post=sp[(ts > -0.45) & (ts < 0)].mean() / sp[(ts >= 0) & (ts < 0.5)].mean(),
                     hfb_peak_z=h[(times >= 0) & (times < 1)].max()))
print(pd.DataFrame(rows).round(3).to_string())
# distribution of the MIDDLE model's held-out R2 (adopted ridge value, mean over splits) per subject
q = E.groupby("subject").mid_r2.describe(percentiles=[0.5, 0.9])[["count", "min", "50%", "90%", "max"]]
q["speech_r_median"] = E[E.speech_r].groupby("subject").mid_r2.median()
q["n_r2_pos"] = E.groupby("subject").mid_r2.apply(lambda v: int((v > 0).sum()))
print(q.round(3).to_string())
spectrogram read later by shift_s (s); Speech-R electrodes, best ridge value per electrode
max_r2
subject    S01    S02    S03    S04    S07    S08    S13
shift_s                                                 
-0.5    -0.001  0.052 -0.043  0.008 -0.043  0.060 -0.015
-0.4    -0.007  0.061 -0.043  0.007 -0.044  0.072 -0.036
-0.3     0.031  0.065 -0.033  0.029 -0.044  0.070 -0.051
-0.2     0.084  0.058 -0.029  0.089 -0.043  0.064 -0.052
-0.1     0.158  0.057 -0.019  0.206 -0.048  0.065 -0.037
 0.0     0.124  0.066 -0.023  0.242 -0.045  0.056 -0.024
 0.1     0.117  0.064 -0.033  0.255 -0.048  0.060 -0.019
 0.2     0.074  0.037 -0.066  0.254 -0.048  0.033 -0.018
 0.3     0.012 -0.002 -0.092  0.236 -0.048  0.005 -0.015
 0.4    -0.022 -0.003 -0.090  0.156 -0.049 -0.006 -0.028
 0.5    -0.025  0.001 -0.087  0.056 -0.049 -0.023 -0.026
median_r2
subject    S01    S02    S03    S04    S07    S08    S13
shift_s                                                 
-0.5    -0.084 -0.076 -0.167 -0.058 -0.095 -0.049 -0.125
-0.4    -0.070 -0.076 -0.165 -0.058 -0.099 -0.047 -0.130
-0.3    -0.058 -0.073 -0.154 -0.056 -0.101 -0.050 -0.128
-0.2    -0.035 -0.073 -0.148 -0.043 -0.101 -0.052 -0.124
-0.1    -0.022 -0.072 -0.149 -0.010 -0.106 -0.038 -0.124
 0.0    -0.034 -0.071 -0.149  0.005 -0.115 -0.052 -0.130
 0.1    -0.047 -0.072 -0.153  0.001 -0.118 -0.053 -0.132
 0.2    -0.062 -0.073 -0.169 -0.011 -0.118 -0.057 -0.132
 0.3    -0.075 -0.073 -0.173 -0.015 -0.117 -0.062 -0.134
 0.4    -0.093 -0.078 -0.173 -0.036 -0.118 -0.070 -0.134
 0.5    -0.095 -0.077 -0.173 -0.054 -0.117 -0.072 -0.134
n_r2_pos
subject  S01  S02  S03  S04  S07  S08  S13
shift_s                                   
-0.5       0    1    0    2    0    2    0
-0.4       0    1    0    1    0    2    0
-0.3       2    1    0    1    0    2    0
-0.2       7    2    0    2    0    3    0
-0.1       7    2    0    8    0    3    0
 0.0       6    2    0    8    0    3    0
 0.1       6    2    0    9    0    3    0
 0.2       6    1    0    7    0    2    0
 0.3       1    0    0    7    0    1    0
 0.4       0    0    0    3    0    0    0
 0.5       0    1    0    2    0    0    0
shift with the highest median R2 per subject: {'S01': -0.1, 'S02': 0.0, 'S03': -0.2, 'S04': 0.0, 'S07': -0.5, 'S08': -0.1, 'S13': -0.1}
140 s
  subject  spec_half_rise_s  hfb_half_rise_s  spec_pre_over_post  hfb_peak_z
0     S01              0.02             0.18               0.131       0.993
1     S02              0.16             0.22               0.430       0.652
2     S03              0.02             0.42               0.137       0.215
3     S04              0.06             0.16               0.504       1.142
4     S07              0.02             0.16               0.480       1.162
5     S08              0.16             0.10               0.015       1.353
6     S13              0.02             0.18               0.658       0.749
         count    min    50%    90%    max  speech_r_median  n_r2_pos
subject                                                              
S01       61.0 -0.829 -0.116 -0.013  0.124           -0.036         6
S02       59.0 -0.222 -0.099 -0.046  0.066           -0.074         2
S03       52.0 -1.881 -0.192 -0.113 -0.026           -0.151         0
S04       40.0 -1.065 -0.095  0.089  0.226            0.005         8
S07       60.0 -0.815 -0.140 -0.062 -0.032           -0.117         0
S08       52.0 -0.590 -0.139 -0.056  0.052           -0.052         3
S13       53.0 -1.066 -0.145 -0.085 -0.024           -0.131         0
In [14]:
# Drift check (verifier, round 2): a fixed offset per subject is tested above; a clock that
# drifts over the session would move the best shift between early and late trials. The MIDDLE
# trials of each subject are split by onset into a first and a second half, and the shift is
# searched over -1 to +1 s in each half (the grid above reaches -0.5 s, where S07's best lies).
t0 = time.time()
SHIFTS_D = np.arange(-50, 51, 5)
rows = []
for s, d in D.items():
    sr = E.loc[E.subject.eq(s), "speech_r"].to_numpy()
    idx = cond_idx(d["trials"], "mid")
    idx = idx[np.argsort(d["trials"].onset.to_numpy()[idx])]
    halves = {"first": idx[:len(idx) // 2], "second": idx[len(idx) // 2:], "all": idx}
    for half, hidx in halves.items():
        for sh in SHIFTS_D:
            if half == "all" and abs(sh) <= 25:
                continue                                  # computed in the grid above
            Xs, ys = ac4.trial_design(d, hidx, xshift=int(sh))
            _, r2 = ac4.ridge_loto(Xs, [y[:, sr] for y in ys], ALPHAS)
            m = r2.mean(0).max(0)
            rows.append(dict(subject=s, half=half, n_trials=len(hidx), shift_s=sh / ac4.FS_OUT,
                             median_r2=np.median(m), n_r2_pos=int((m > 0).sum())))
SD = pd.concat([pd.DataFrame(rows), SH.assign(half="all", n_trials=np.nan)[["subject", "half", "n_trials", "shift_s", "median_r2", "n_r2_pos"]]])
SDr = SD.sort_values(["subject", "half", "shift_s"]).reset_index(drop=True)
best_sh = SDr.loc[SDr.groupby(["subject", "half"]).median_r2.idxmax()]
print("shift (s) with the highest median R2, and that R2, per subject and half of the MIDDLE trials (grid -1 to +1 s):")
print(best_sh.pivot(index="subject", columns="half", values="shift_s").to_string())
print(best_sh.pivot(index="subject", columns="half", values="median_r2").round(3).to_string())
print("largest number of Speech-R electrodes with held-out R2 > 0 at any shift:")
print(SDr.groupby(["subject", "half"]).n_r2_pos.max().unstack().to_string())
print(f"{time.time() - t0:.0f} s")
shift (s) with the highest median R2, and that R2, per subject and half of the MIDDLE trials (grid -1 to +1 s):
half     all  first  second
subject                    
S01     -0.1   -0.1    -0.1
S02      0.0    0.0     0.0
S03     -0.2   -0.7     0.0
S04      0.0    0.0     0.0
S07     -0.6   -0.7     0.0
S08     -0.1    0.0    -0.4
S13     -0.1    0.0     0.0
half       all  first  second
subject                      
S01     -0.022 -0.003  -0.043
S02     -0.071 -0.080  -0.055
S03     -0.148 -0.188  -0.122
S04      0.005  0.024  -0.023
S07     -0.090 -0.073  -0.100
S08     -0.038 -0.056  -0.020
S13     -0.124 -0.166  -0.060
largest number of Speech-R electrodes with held-out R2 > 0 at any shift:
half     all  first  second
subject                    
S01        7      8       6
S02        2      3       3
S03        0      0       1
S04        9      9       7
S07        0      0       0
S08        3      2       4
S13        0      1       0
388 s

Result: strf-r-count. The MIDDLE eSTRFs predict held-out trials in few electrodes: 9 electrodes are STRF-R under the bootstrap bound (13 with samples to 400 ms after offset), and 0 or 1 under the per-split percentiles, against the paper's 53. Their mean held-out R2 ranges from 0.044 to 0.226, and they come from S01 (4), S02 (1) and S04 (4). Not reproduced.

The alignment check does not point to a misaligned stimulus. In S01 and S04, where the models work, the best R2 lies within 0.1 s of no shift (S01 best median at -0.1 s, S04 at 0 s; the largest R2 at -0.1 to +0.2 s), and the evoked HFB reaches half its rise 0.1 to 0.16 s after the spectrogram. In S03, S07 and S13 no shift from -0.5 to +0.5 s gives any Speech-R electrode a positive held-out R2, and in S02 and S08 at most 3 electrodes at any shift, so no single offset would raise the count. Two subject features bear on the failure: the audio of S02, S04, S07 and S13 is not silent before the sounds (spectrogram before onset 0.43 to 0.66 of that after), and S03's evoked HFB is weak (peak 0.22 z, against 0.65 to 1.35 z elsewhere). In S08 the HFB reaches half its rise 0.06 s before the spectrogram does, which could mean its audio track is a little late, but no shift raises its R2 count above 3. The median held-out R2 of Speech-R electrodes is below 0 in six of seven subjects. The paper's Figure 6b plots mean model scores that are all near or above 0 (most non-included electrodes near 0.07), while most scores here are negative, which suggests a different score; this is asked of the paper's authors.

The drift check finds no drift that would explain the count. In S01, S02, S04 and S13 the best shift is the same in both halves of the MIDDLE trials (-0.1, 0, 0 and 0 s). It differs between halves in S03 (-0.7 and 0 s), S07 (-0.7 and 0 s) and S08 (0 and -0.4 s), but in these subjects no shift in either half gives more than 4 Speech-R electrodes a positive held-out R2 (S07 none), and the median R2 at the best shift is below 0 in every half, so there the best shift is the maximum of a curve without a working model. On the grid widened to -1 s, S07's best median R2 over all trials lies at -0.6 s, still with no electrode above 0.

In [15]:
rows = []
for zr in R_speech.itertuples():
    sr = E[f"lb_{zr.zscore}_{zr.window}_{zr.trials}"] > 0
    for key in ["mid_a", "mid_b", "mid_c", "mid_plus_a", "mid_plus_b", "mid_plus_c"]:
        st = E[f"strf_{key}"]
        rows.append(dict(speech_r=f"{zr.zscore}/{zr.window}/{zr.trials}", strf=key,
                         temporal_perisylvian=int((sr & st & E.region.isin(["temporal", "perisylvian"])).sum()),
                         temporal_only=int((sr & st & E.region.eq("temporal")).sum())))
R_inc = pd.DataFrame(rows)
R_inc["within_41_tol"] = (R_inc.temporal_perisylvian - 41).abs() <= 4.1
print(R_inc.to_string())
print("readings within 41 +/- 4.1:", int(R_inc.within_41_tol.sum()), "of", len(R_inc))
E["included"] = E.speech_r & E.strf_r & E.region.isin(["temporal", "perisylvian"])
print("adopted reading: included", int(E.included.sum()))
print(E[E.included].groupby(["subject", "region"]).size().unstack(fill_value=0))

# Figure 6b (bottom) per subject: peri-Sylvian electrodes, all and active (included), read from
# the bar graph by eye; the paper's S1 to S7 have no mapping to this data set's subject names.
FIG6B_ACTIVE = [5, 10, 5, 6, 1, 4, 10]
FIG6B_ALL = [26, 37, 36, 37, 29, 41, 37]
ours = E.groupby("subject").agg(temporal_perisylvian=("region", lambda r: int(r.isin(["temporal", "perisylvian"]).sum())),
                                included=("included", "sum"))
print(ours.T.to_string())
print("Figure 6b, S1 to S7: all", FIG6B_ALL, "(sum", sum(FIG6B_ALL), "); active", FIG6B_ACTIVE, "(sum", sum(FIG6B_ACTIVE), ")")
print("sorted included counts, here:", sorted(ours.included, reverse=True), "; paper:", sorted(FIG6B_ACTIVE, reverse=True))
              speech_r        strf  temporal_perisylvian  temporal_only  within_41_tol
0      trial/sound/mid       mid_a                     9              6          False
1      trial/sound/mid       mid_b                     0              0          False
2      trial/sound/mid       mid_c                     0              0          False
3      trial/sound/mid  mid_plus_a                    13             10          False
4      trial/sound/mid  mid_plus_b                     1              1          False
5      trial/sound/mid  mid_plus_c                     1              1          False
6      trial/sound/all       mid_a                     9              6          False
7      trial/sound/all       mid_b                     0              0          False
8      trial/sound/all       mid_c                     0              0          False
9      trial/sound/all  mid_plus_a                    13             10          False
10     trial/sound/all  mid_plus_b                     1              1          False
11     trial/sound/all  mid_plus_c                     1              1          False
12       trial/2.5/mid       mid_a                     9              6          False
13       trial/2.5/mid       mid_b                     0              0          False
14       trial/2.5/mid       mid_c                     0              0          False
15       trial/2.5/mid  mid_plus_a                    13             10          False
16       trial/2.5/mid  mid_plus_b                     1              1          False
17       trial/2.5/mid  mid_plus_c                     1              1          False
18       trial/2.5/all       mid_a                     9              6          False
19       trial/2.5/all       mid_b                     0              0          False
20       trial/2.5/all       mid_c                     0              0          False
21       trial/2.5/all  mid_plus_a                    13             10          False
22       trial/2.5/all  mid_plus_b                     1              1          False
23       trial/2.5/all  mid_plus_c                     1              1          False
24    pooled/sound/mid       mid_a                     9              6          False
25    pooled/sound/mid       mid_b                     0              0          False
26    pooled/sound/mid       mid_c                     0              0          False
27    pooled/sound/mid  mid_plus_a                    13             10          False
28    pooled/sound/mid  mid_plus_b                     1              1          False
29    pooled/sound/mid  mid_plus_c                     1              1          False
30    pooled/sound/all       mid_a                     9              6          False
31    pooled/sound/all       mid_b                     0              0          False
32    pooled/sound/all       mid_c                     0              0          False
33    pooled/sound/all  mid_plus_a                    13             10          False
34    pooled/sound/all  mid_plus_b                     1              1          False
35    pooled/sound/all  mid_plus_c                     1              1          False
36      pooled/2.5/mid       mid_a                     9              6          False
37      pooled/2.5/mid       mid_b                     0              0          False
38      pooled/2.5/mid       mid_c                     0              0          False
39      pooled/2.5/mid  mid_plus_a                    13             10          False
40      pooled/2.5/mid  mid_plus_b                     1              1          False
41      pooled/2.5/mid  mid_plus_c                     1              1          False
42      pooled/2.5/all       mid_a                     9              6          False
43      pooled/2.5/all       mid_b                     0              0          False
44      pooled/2.5/all       mid_c                     0              0          False
45      pooled/2.5/all  mid_plus_a                    13             10          False
46      pooled/2.5/all  mid_plus_b                     1              1          False
47      pooled/2.5/all  mid_plus_c                     1              1          False
48  nonevent/sound/mid       mid_a                     9              6          False
49  nonevent/sound/mid       mid_b                     0              0          False
50  nonevent/sound/mid       mid_c                     0              0          False
51  nonevent/sound/mid  mid_plus_a                    13             10          False
52  nonevent/sound/mid  mid_plus_b                     1              1          False
53  nonevent/sound/mid  mid_plus_c                     1              1          False
54  nonevent/sound/all       mid_a                     9              6          False
55  nonevent/sound/all       mid_b                     0              0          False
56  nonevent/sound/all       mid_c                     0              0          False
57  nonevent/sound/all  mid_plus_a                    13             10          False
58  nonevent/sound/all  mid_plus_b                     1              1          False
59  nonevent/sound/all  mid_plus_c                     1              1          False
60    nonevent/2.5/mid       mid_a                     9              6          False
61    nonevent/2.5/mid       mid_b                     0              0          False
62    nonevent/2.5/mid       mid_c                     0              0          False
63    nonevent/2.5/mid  mid_plus_a                    13             10          False
64    nonevent/2.5/mid  mid_plus_b                     1              1          False
65    nonevent/2.5/mid  mid_plus_c                     1              1          False
66    nonevent/2.5/all       mid_a                     9              6          False
67    nonevent/2.5/all       mid_b                     0              0          False
68    nonevent/2.5/all       mid_c                     0              0          False
69    nonevent/2.5/all  mid_plus_a                    13             10          False
70    nonevent/2.5/all  mid_plus_b                     1              1          False
71    nonevent/2.5/all  mid_plus_c                     1              1          False
readings within 41 +/- 4.1: 0 of 72
adopted reading: included 9
region   perisylvian  temporal
subject                       
S01                1         3
S02                0         1
S04                2         2
subject               S01  S02  S03  S04  S07  S08  S13
temporal_perisylvian   26   41   37   37   40   41   29
included                4    1    0    4    0    0    0
Figure 6b, S1 to S7: all [26, 37, 36, 37, 29, 41, 37] (sum 243 ); active [5, 10, 5, 6, 1, 4, 10] (sum 41 )
sorted included counts, here: [4, 4, 1, 0, 0, 0, 0] ; paper: [10, 10, 6, 5, 5, 4, 1]

Result: included-electrode-count. The STRF-R electrodes are all Speech-R and on temporal or perisylvian cortex, so the included count follows the STRF-R count: 9 under the adopted readings and at most 13 under any, against 41. They come from three subjects (S01, S02, S04); none from the pink noise subjects. Per subject, the temporal and perisylvian electrodes here (26, 41, 37, 37, 40, 41, 29) are close in number to the peri-Sylvian electrodes of Figure 6b (26, 37, 36, 37, 29, 41, 37 as read from the bars, 251 here against 243), so the location labels agree with the paper's; the included counts (4, 4, 1, 0, 0, 0, 0 sorted) fall far below the paper's (10, 10, 6, 5, 5, 4, 1). Not reproduced.

Pink noise HFB on the included electrodes (supp3a, set (a))¶

In [16]:
m_inc_n = E.loc[E.subject.isin(noise_subjects), "included"].to_numpy()
print("included electrodes in S07, S08, S13:", int(m_inc_n.sum()))
if m_inc_n.sum() >= 2:
    print(cluster_report(DIFN[m_inc_n], "(a) included electrodes of S07, S08, S13", 5, ttn).to_string())
    print(f"pink noise AFTER-BEFORE mean over (a), 0-3 s: {DIFN[m_inc_n][:, ttn >= 0].mean():.3f} z (n = {m_inc_n.sum()})")
else:
    print("set (a) is empty or a single electrode: no test; the claim is judged on set (b)")
included electrodes in S07, S08, S13: 0
set (a) is empty or a single electrode: no test; the claim is judged on set (b)

Result: supp3a-pink-noise-no-hfb-change. On the pink noise triplets, no cluster of AFTER minus BEFORE reaches P < 0.05 over the 36 Speech-R electrodes of S07, S08 and S13 (smallest P = 0.0895), so the claim of absence is reproduced on set (b). Set (a) is empty: none of these subjects' electrodes is included in the eSTRF analyses here. The mean AFTER minus BEFORE difference over 0 to 3 s is nearly the same in pink noise and speech triplets (0.040913 and 0.041035 z, s.e. 0.019 and 0.017), from different time courses (largest difference 1.54 z, correlation of the electrode means 0.61), so the equality is a coincidence of the averages and not a shared array. The speech triplets of the same electrodes do give a significant cluster at 0.50 to 0.74 s (P = 0.0013), with about as many triplets per subject (29 against 28) and the same mean and s.e. over 0 to 3 s, so the difference between the two lies in the time course of the effect, not in the amount of data or the mean.

MTF of eSTRFs against filter type¶

fig8-mtf-matches-filter: the MTFs of the eSTRFs match the filter type of the stimuli they were fit on, in BEFORE, AFTER and in the AFTER minus BEFORE shift.

eSTRFs fit apart on temporal-filtered and spectral-filtered triplets (Figure 8 legend), the MTF as the amplitude of the 2-D FFT of the mean eSTRF (32 bands x 21 lags), the temporal minus spectral MTF difference per included electrode, and MNE's cluster permutation test over the modulation plane (the half plane of non-negative spectral modulation; the amplitude spectrum of a real eSTRF is symmetric). The criterion's region test: a positive cluster (temporal-filter MTF higher) must lie at low temporal and high spectral modulation, a negative one at high temporal and low spectral modulation; "low" and "high" are taken here as below and above the median of the plane's absolute modulations, measured at the cluster's centre (mean over its bins). A second rule takes the regions from the filter cutoffs (Methods, Filtered speech sound creation: 3 Hz, 0.5 cycles/kHz): a cluster is in region when more than half its bins lie at temporal modulation at most 3 Hz and spectral modulation above the cutoff (temporal filter), or the reverse (spectral filter). The spectral axis here is in cycles per band, so 0.5 cycles/kHz is converted at the mean band spacing (0.11 cycles per band); bands are ERB-spaced, so this is an approximation.

In [17]:
inc = E.included.to_numpy()
def strf_of(s, key, ch):
    return FITS[(s, key)]["mean"][:, ch]
tm = np.fft.fftshift(np.fft.fftfreq(ac4.MAX_LAG + 1, 1 / ac4.FS_OUT))      # Hz
sm = np.fft.fftshift(np.fft.fftfreq(ac4.N_BANDS, 1.0))                     # cycles per band
half = sm >= 0
def mtf_diffs(kind):
    out = []
    for s in D:
        chs = np.where(E.loc[E.subject.eq(s), "included"].to_numpy())[0]
        for c in chs:
            if kind in ("bef", "aft"):
                mt = ac4.mtf(strf_of(s, f"{kind}_temp", c)); ms = ac4.mtf(strf_of(s, f"{kind}_freq", c))
            elif kind == "shift_a":    # MTF of the AFTER minus BEFORE eSTRF
                mt = ac4.mtf(strf_of(s, "aft_temp", c) - strf_of(s, "bef_temp", c))
                ms = ac4.mtf(strf_of(s, "aft_freq", c) - strf_of(s, "bef_freq", c))
            else:                      # difference of MTFs
                mt = ac4.mtf(strf_of(s, "aft_temp", c)) - ac4.mtf(strf_of(s, "bef_temp", c))
                ms = ac4.mtf(strf_of(s, "aft_freq", c)) - ac4.mtf(strf_of(s, "bef_freq", c))
            out.append((mt - ms)[half])
    return np.array(out)
TMg, SMg = np.meshgrid(np.abs(tm), sm[half])
med_t, med_s = np.median(TMg), np.median(SMg)
# Second rule, from the filter cutoffs (Methods, Filtered speech sound creation): temporal
# modulations below 3 Hz, spectral modulations below 0.5 cycles/kHz. The spectral axis here is in
# cycles per band; at the mean band spacing (6.82 kHz over 31 steps) 0.5 cycles/kHz is
# 0.11 cycles per band. Low = at or below the cutoff, high = above it.
CUT_T, CUT_S = 3.0, 0.5 * (ac4.F_HI - ac4.F_LO) / 1000 / (ac4.N_BANDS - 1)
kept_t = (TMg <= CUT_T) & (SMg > CUT_S)       # kept by the temporal filter, removed by the spectral
kept_s = (TMg > CUT_T) & (SMg <= CUT_S)       # kept by the spectral filter, removed by the temporal
rows = []
for kind in ["bef", "aft", "shift_a", "shift_b"]:
    X = mtf_diffs(kind)
    T, clusters, pv = clusters_of(X, 8)
    for c, p in zip(clusters, pv):
        sign = "+" if T[c].mean() > 0 else "-"
        ct, cs = TMg[c].mean(), SMg[c].mean()
        match = (sign == "+" and ct < med_t and cs > med_s) or (sign == "-" and ct > med_t and cs < med_s)
        region = kept_t if sign == "+" else kept_s
        rows.append(dict(kind=kind, n=len(X), p=p, sign=sign, bins=int(c.sum()), centre_temporal_Hz=ct,
                         centre_spectral_cyc_per_band=cs, in_region_median_rule=match,
                         frac_bins_in_region_cutoff_rule=(c & region).sum() / c.sum(),
                         in_region_cutoff_rule=(c & region).sum() / c.sum() > 0.5))
    if not len(clusters):
        rows.append(dict(kind=kind, n=len(X), p=np.nan, sign="none"))
R8 = pd.DataFrame(rows)
print(f"median rule: |temporal modulation| {med_t:.2f} Hz, spectral modulation {med_s:.3f} cycles/band")
print(f"cutoff rule: temporal {CUT_T} Hz, spectral {CUT_S:.3f} cycles/band; bins kept by the temporal filter only {int(kept_t.sum())}, by the spectral filter only {int(kept_s.sum())}, of {kept_t.size}")
print(R8.sort_values(["kind", "p"]).to_string())
sig = R8[R8.p < 0.05]
print("significant clusters in region, per kind (median rule / cutoff rule):")
print(sig.groupby("kind")[["in_region_median_rule", "in_region_cutoff_rule"]].sum().reindex(["bef", "aft", "shift_a", "shift_b"]).fillna(0).astype(int).to_string())
median rule: |temporal modulation| 11.90 Hz, spectral modulation 0.234 cycles/band
cutoff rule: temporal 3.0 Hz, spectral 0.110 cycles/band; bins kept by the temporal filter only 36, by the spectral filter only 72, of 336
       kind  n         p sign  bins  centre_temporal_Hz  centre_spectral_cyc_per_band  in_region_median_rule  frac_bins_in_region_cutoff_rule  in_region_cutoff_rule
11      aft  9  0.015625    +    21           16.099773                      0.215774                  False                         0.000000                  False
15      aft  9  0.015625    +    24           17.658730                      0.355469                  False                         0.000000                  False
13      aft  9  0.019531    +    22           18.398268                      0.357955                  False                         0.000000                  False
10      aft  9  0.027344    +    20           16.785714                      0.217188                  False                         0.000000                  False
9       aft  9  0.031250    +    15            1.587302                      0.193750                  False                         0.866667                   True
14      aft  9  0.042969    +    14            2.040816                      0.399554                   True                         0.857143                   True
18      aft  9  0.253906    +     6           17.857143                      0.468750                  False                         0.000000                  False
19      aft  9  0.359375    +     5           19.047619                      0.468750                  False                         0.000000                  False
8       aft  9  0.597656    +     2            0.000000                      0.015625                  False                         0.000000                  False
16      aft  9  0.691406    +     2            8.333333                      0.343750                   True                         0.000000                  False
12      aft  9  0.839844    +     1            7.142857                      0.250000                   True                         0.000000                  False
17      aft  9  0.949219    +     1            9.523810                      0.437500                   True                         0.000000                  False
20      aft  9  0.957031    -     1            4.761905                      0.031250                  False                         1.000000                   True
4       bef  9  0.003906    +    48           16.369048                      0.321615                  False                         0.000000                  False
3       bef  9  0.007812    +    29            2.052545                      0.301724                   True                         0.862069                   True
5       bef  9  0.023438    +    20           18.095238                      0.223438                  False                         0.000000                  False
6       bef  9  0.027344    +    19           18.922306                      0.383224                  False                         0.000000                  False
1       bef  9  0.414062    +     3            1.587302                      0.062500                  False                         0.000000                  False
0       bef  9  0.730469    +     1            0.000000                      0.000000                  False                         0.000000                  False
2       bef  9  0.957031    +     1            0.000000                      0.125000                  False                         1.000000                   True
7       bef  9  0.988281    +     1            2.380952                      0.468750                   True                         1.000000                   True
22  shift_a  9  0.003906    +   121           15.328611                      0.298037                  False                         0.115702                  False
31  shift_a  9  0.527344    -     2            5.952381                      0.031250                  False                         1.000000                   True
30  shift_a  9  0.738281    -     1            4.761905                      0.031250                  False                         1.000000                   True
26  shift_a  9  0.757812    +     1            7.142857                      0.312500                   True                         0.000000                  False
25  shift_a  9  0.765625    +     1            2.380952                      0.156250                  False                         1.000000                   True
23  shift_a  9  0.781250    +     1           11.904762                      0.125000                  False                         0.000000                  False
32  shift_a  9  0.832031    -     1            7.142857                      0.312500                  False                         0.000000                  False
28  shift_a  9  0.839844    +     1            2.380952                      0.406250                   True                         1.000000                   True
33  shift_a  9  0.894531    -     1            7.142857                      0.437500                  False                         0.000000                  False
24  shift_a  9  0.949219    +     1           16.666667                      0.125000                  False                         0.000000                  False
29  shift_a  9  0.949219    +     1            0.000000                      0.437500                   True                         1.000000                   True
21  shift_a  9  1.000000    +     1           21.428571                      0.125000                  False                         0.000000                  False
27  shift_a  9  1.000000    +     1            4.761905                      0.406250                   True                         0.000000                  False
38  shift_b  9  0.691406    -     2            1.190476                      0.062500                  False                         0.000000                  False
35  shift_b  9  0.906250    +     1            0.000000                      0.250000                   True                         1.000000                   True
39  shift_b  9  0.949219    -     1            9.523810                      0.156250                  False                         0.000000                  False
34  shift_b  9  0.953125    +     1            0.000000                      0.093750                  False                         0.000000                  False
40  shift_b  9  0.960938    -     1            0.000000                      0.187500                  False                         0.000000                  False
36  shift_b  9  0.964844    +     1           14.285714                      0.312500                  False                         0.000000                  False
37  shift_b  9  0.992188    -     1            4.761905                      0.031250                  False                         1.000000                   True
significant clusters in region, per kind (median rule / cutoff rule):
         in_region_median_rule  in_region_cutoff_rule
kind                                                 
bef                          1                      1
aft                          1                      2
shift_a                      0                      0
shift_b                      0                      0

Result: fig8-mtf-matches-filter. With 9 electrodes, the temporal minus spectral MTF difference has one significant positive cluster in the region the temporal filter keeps in BEFORE (centre 2.1 Hz, P = 0.0078) and two in AFTER under the cutoff rule (1.6 Hz, P = 0.031; 2.0 Hz, P = 0.043), one of which also passes the median rule. Most significant clusters lie outside both regions, at 16 to 19 Hz (BEFORE P = 0.0039 to 0.027, AFTER P = 0.016 to 0.027). For the AFTER minus BEFORE shift, the only significant cluster (P = 0.0039, the smallest P possible with 9 electrodes) lies at 15.3 Hz, outside the regions, with the MTF of the difference, and no cluster reaches P < 0.05 with the difference of MTFs. The criterion asks for an in-region cluster in each of BEFORE, AFTER and the shift; the shift, which carries the claim's conclusion about the tuning change, has none under either rule. Not reproduced.

In [18]:
rng = np.random.default_rng(909)
rows = []
for strf_kind in ["mean", "z"]:
    for rms_kind in ["concat", "per_sound"]:
        diffs, befs = [], []
        for s, d in D.items():
            chs = np.where(E.loc[E.subject.eq(s), "included"].to_numpy())[0]
            if not len(chs):
                continue
            Xs, _ = ac4.trial_design(d, cond_idx(d["trials"], "mid"))
            Xa = np.concatenate(Xs)
            mu, sd = Xa.mean(0), Xa.std(0)
            for c in chs:
                v = {}
                for ph in ["bef", "aft"]:
                    w = FITS[(s, ph)][strf_kind][:, c]
                    w = (w - w.mean()) / w.std()
                    if rms_kind == "concat":
                        v[ph] = np.sqrt(np.mean((((Xa - mu) / sd) @ w) ** 2))
                    else:
                        v[ph] = np.mean([np.sqrt(np.mean((((X - mu) / sd) @ w) ** 2)) for X in Xs])
                diffs.append(v["aft"] - v["bef"]); befs.append(v["bef"])
        diffs, befs = np.array(diffs), np.array(befs)
        obs, p = ac4.signflip_test(diffs, rng)
        rows.append(dict(strf=strf_kind, rms=rms_kind, n=len(diffs), rms_before=befs.mean(), relative_increase=(diffs / befs).mean(), mean_increase=obs,
                         se=diffs.std(ddof=1) / np.sqrt(len(diffs)), sd=diffs.std(ddof=1), p=p,
                         within_tol=abs(obs - 0.12) <= 0.03, frac_positive=(diffs > 0).mean()))
R9a = pd.DataFrame(rows)
print(R9a.to_string())
   strf        rms  n  rms_before  relative_increase  mean_increase        se         sd         p  within_tol  frac_positive
0  mean     concat  9  105.106001           0.126502      12.031450  4.521247  13.563740  0.034197       False       0.888889
1  mean  per_sound  9  104.021738           0.126386      11.849495  4.446475  13.339424  0.030697       False       0.888889
2     z     concat  9  108.732262           0.124510      11.486647  5.492624  16.477872  0.076692       False       0.777778
3     z  per_sound  9  107.698951           0.124831      11.349996  5.368103  16.104310  0.072793       False       0.777778

Result: fig9-rms-increase. Over the 9 included electrodes, the AFTER eSTRF gives a larger RMS output to unfiltered speech than the BEFORE eSTRF under every reading (mean increase 11.4 to 12.0, 8 of 9 electrodes positive with mean coefficients), with P = 0.034 and 0.031 for mean coefficients and 0.077 and 0.073 for z-scored coefficients. The RMS is about 105 here, against about 4 on the paper's axis, so the increase cannot be compared with 0.12 on the paper's scale; the increase as a fraction of the BEFORE RMS is 0.12 to 0.13, printed for comparison only, as the criterion judges the absolute increase. The direction holds; the stated value does not: partially reproduced. Whether the claims file's absolute tolerance can apply to a quantity whose unit the paper does not give is asked of a reader.

MIDDLE eSTRFs predict AFTER better than BEFORE¶

fig9-middle-generalizes-after: eSTRFs fit on unfiltered speech predict HFB activity better in AFTER than in BEFORE (mean R2 improvement 0.05 plus/minus 0.01, P = 0.0001, n = 41).

Methods, MIDDLE condition coefficients generalization: the MIDDLE eSTRF (mean coefficients) convolved with the BEFORE and AFTER spectrograms, and R2 against the HFB. Spectrograms and HFB of each condition are z-scored by that condition's own statistics (Methods: inputs and outputs z-scored). R2 (a) per trial then averaged, (b) over all trials concatenated.

In [19]:
rng = np.random.default_rng(910)
rows = []
for r2_kind in ["per_trial", "concat"]:
    diffs, vals = [], []
    for s, d in D.items():
        chs = np.where(E.loc[E.subject.eq(s), "included"].to_numpy())[0]
        if not len(chs):
            continue
        W = FITS[(s, "mid")]["mean"][:, chs]
        r = {}
        for ph in ["bef", "aft"]:
            Xs, ys = ac4.trial_design(d, cond_idx(d["trials"], ph))
            Xa, ya = np.concatenate(Xs), np.concatenate(ys)[:, chs]
            mu, sd, my, sy = Xa.mean(0), Xa.std(0), ya.mean(0), ya.std(0)
            if r2_kind == "concat":
                pred = ((Xa - mu) / sd) @ W
                yz = (ya - my) / sy
                r[ph] = 1 - ((yz - pred) ** 2).sum(0) / ((yz - yz.mean(0)) ** 2).sum(0)
            else:
                rr = []
                for X, y in zip(Xs, ys):
                    pred = ((X - mu) / sd) @ W
                    yz = (y[:, chs] - my) / sy
                    rr.append(1 - ((yz - pred) ** 2).sum(0) / ((yz - yz.mean(0)) ** 2).sum(0))
                r[ph] = np.mean(rr, 0)
        diffs.append(r["aft"] - r["bef"]); vals.append(np.column_stack([r["bef"], r["aft"]]))
    diffs = np.concatenate(diffs); vals = np.concatenate(vals)
    obs, p = ac4.signflip_test(diffs, rng)
    rows.append(dict(r2=r2_kind, n=len(diffs), r2_before=vals[:, 0].mean(), r2_after=vals[:, 1].mean(),
                     mean_improvement=obs, se=diffs.std(ddof=1) / np.sqrt(len(diffs)), sd=diffs.std(ddof=1),
                     p=p, within_tol=abs(obs - 0.05) <= 0.01, frac_positive=(diffs > 0).mean()))
R9b = pd.DataFrame(rows)
print(R9b.to_string())
          r2  n  r2_before  r2_after  mean_improvement        se        sd         p  within_tol  frac_positive
0  per_trial  9  -0.189907 -0.101341          0.088566  0.047544  0.142632  0.019998       False       0.888889
1     concat  9   0.013403  0.063958          0.050555  0.023955  0.071866  0.020698        True       0.777778

Result: fig9-middle-generalizes-after. Over the 9 included electrodes, the MIDDLE eSTRF predicts AFTER better than BEFORE: with R2 over concatenated trials the improvement is 0.051 (P = 0.021), within 0.05 +/- 0.01; with R2 per trial it is 0.089 (P = 0.020). Reproduced under reading (b), on 9 electrodes against the paper's 41.

Partial correlation of eSTRFs¶

fig10-partial-correlation: Partial correlations of eSTRFs between AFTER and MIDDLE (controlling for BEFORE) exceed those between BEFORE and MIDDLE (controlling for AFTER), a mean improvement of 0.18 (P = 0.001, n = 41).

Methods, eSTRF linear overlap partial correlation analysis: each eSTRF as the z-score of each coefficient across CV splits; sim(aft, mid) = pcorr(after, middle | before), sim(bef, mid) = pcorr(before, middle | after); sign-flip test of the difference. Regression without (a) and with (b) an intercept.

In [20]:
rng = np.random.default_rng(1010)
def pcorr_table(keys=("bef", "mid", "aft"), mask_col="included", subjects=None):
    rows = []
    for s in (subjects or list(D)):
        chs = np.where(E.loc[E.subject.eq(s), mask_col].to_numpy())[0]
        for c in chs:
            b, m, a = (FITS[(s, k)]["z"][:, c] for k in keys)
            row = dict(subject=s, ch=c)
            for icpt in [False, True]:
                tag = "b" if icpt else "a"
                row[f"aft_mid_{tag}"] = ac4.partial_corr(a, m, b, icpt)
                row[f"bef_mid_{tag}"] = ac4.partial_corr(b, m, a, icpt)
                row[f"diff_{tag}"] = row[f"aft_mid_{tag}"] - row[f"bef_mid_{tag}"]
            rows.append(row)
    return pd.DataFrame(rows)
PC = pcorr_table()
rows = []
for tag in ["a", "b"]:
    obs, p = ac4.signflip_test(PC[f"diff_{tag}"], rng)
    rows.append(dict(intercept=tag, n=len(PC), bef_mid=PC[f"bef_mid_{tag}"].mean(), aft_mid=PC[f"aft_mid_{tag}"].mean(),
                     mean_diff=obs, median_diff=PC[f"diff_{tag}"].median(), se=PC[f"diff_{tag}"].std(ddof=1) / np.sqrt(len(PC)),
                     p=p, within_tol=abs(obs - 0.18) <= 0.018, frac_positive=(PC[f"diff_{tag}"] > 0).mean()))
R10 = pd.DataFrame(rows)
print(R10.to_string())
print(PC.groupby("subject")[["diff_a"]].agg(["count", "mean"]))
print("temporal-lobe electrodes only (Figure 10c legend):")
PCt = PC.merge(E.reset_index()[["subject", "region"]].assign(ch=E.groupby("subject").cumcount().to_numpy()), on=["subject", "ch"])
obs, p = ac4.signflip_test(PCt.loc[PCt.region.eq("temporal"), "diff_a"], rng)
print(f"  n = {PCt.region.eq('temporal').sum()}, mean difference {obs:.3f}, P = {p:.4f}")
  intercept  n   bef_mid   aft_mid  mean_diff  median_diff        se         p  within_tol  frac_positive
0         a  9 -0.017803  0.290318   0.308121     0.161958  0.110289  0.011199       False       0.888889
1         b  9 -0.007896  0.297374   0.305270     0.159343  0.107245  0.004200       False       1.000000
        diff_a          
         count      mean
subject                 
S01          4  0.241223
S02          1  0.260731
S04          4  0.386867
temporal-lobe electrodes only (Figure 10c legend):
  n = 6, mean difference 0.426, P = 0.0324

Result: fig10-partial-correlation. Over the 9 included electrodes, AFTER/MIDDLE partial correlation exceeds BEFORE/MIDDLE by a mean 0.308 (P = 0.011) without an intercept and 0.305 (P = 0.0042) with one; 8 of 9 electrodes are positive. The mean is outside 0.18 +/- 0.018 (the median is 0.16). The effect is present and larger: partially reproduced.

fig10b-similarity-correlates: the increase in eSTRF similarity correlates with the electrode's evoked HFB amplitude or model score (Pearson r = 0.42, P = 0.007).

In [21]:
Einc = E[E.included].copy()
Einc["ch"] = E.groupby("subject").cumcount()[E.included].to_numpy()
Einc["evoked"] = [POST[(s, MAIN[0], MAIN[1])][speech(D[s]["trials"]).to_numpy() & (D[s]["trials"].trial_phase == "mid").to_numpy()][:, c].mean()
                  for s, c in zip(Einc.subject, Einc.ch)]
M = PC.merge(Einc[["subject", "ch", "evoked", "mid_r2", "description"]], on=["subject", "ch"])
for x in ["evoked", "mid_r2"]:
    for tag in ["a", "b"]:
        r, p = stats.pearsonr(M[x], M[f"diff_{tag}"])
        print(f"({'a' if x == 'evoked' else 'b'}) {x} vs partial correlation difference (intercept {tag}): r = {r:.3f}, P = {p:.4f}, n = {len(M)}, within 0.42 +/- 0.042: {abs(r - 0.42) <= 0.042}")
print(f"evoked range {M.evoked.min():.2f} to {M.evoked.max():.2f} z; mid_r2 range {M.mid_r2.min():.3f} to {M.mid_r2.max():.3f}")
(a) evoked vs partial correlation difference (intercept a): r = 0.625, P = 0.0719, n = 9, within 0.42 +/- 0.042: False
(a) evoked vs partial correlation difference (intercept b): r = 0.633, P = 0.0671, n = 9, within 0.42 +/- 0.042: False
(b) mid_r2 vs partial correlation difference (intercept a): r = 0.549, P = 0.1262, n = 9, within 0.42 +/- 0.042: False
(b) mid_r2 vs partial correlation difference (intercept b): r = 0.524, P = 0.1474, n = 9, within 0.42 +/- 0.042: False
evoked range 0.62 to 2.08 z; mid_r2 range 0.044 to 0.226

Result: fig10b-similarity-correlates. Across the 9 included electrodes, the partial correlation difference correlates with the mean evoked HFB at r = 0.63 (P = 0.072) and with the MIDDLE model score at r = 0.55 (P = 0.126). Neither r is within 0.42 +/- 0.042 and neither P is below 0.05. Not reproduced.

fig10c-stg-location: Most of the increase in partial correlation lies around the superior temporal gyrus.

STG electrodes are those labelled temporal-superior in channels.tsv.

In [22]:
M["stg"] = M.description.eq("temporal-superior")
pos = M[M.diff_a > 0]
print("included electrodes by label:", M.description.value_counts().to_dict())
print(f"(a) share of the summed positive differences on STG: {pos.loc[pos.stg, 'diff_a'].sum() / pos.diff_a.sum():.3f} ({pos.loc[pos.stg, 'diff_a'].sum():.2f} of {pos.diff_a.sum():.2f})")
print(f"(b) share of electrodes with a positive difference on STG: {pos.stg.mean():.3f} ({int(pos.stg.sum())} of {len(pos)})")
print(f"reference: share of included electrodes on STG {M.stg.mean():.3f} ({int(M.stg.sum())} of {len(M)})")
included electrodes by label: {'temporal-superior': 4, 'parietal-inferior': 2, 'frontal-inferior': 1, 'temporal-inferior': 1, 'temporal-posterior': 1}
(a) share of the summed positive differences on STG: 0.517 (1.44 of 2.78)
(b) share of electrodes with a positive difference on STG: 0.500 (4 of 8)
reference: share of included electrodes on STG 0.444 (4 of 9)

Result: fig10c-stg-location. Of the summed positive partial correlation differences, 51.7% lie on the 4 electrodes labelled temporal-superior (reading a), and 4 of 8 electrodes with a positive difference are STG (50%, reading b, not more than half). Reading (a) holds, by a small margin on 9 electrodes: reproduced.

supp3b-pink-noise-no-pcorr-change: In pink noise trials the partial correlations of BEFORE/MIDDLE and AFTER/MIDDLE eSTRFs do not differ (permutation test, n = 12).

eSTRFs fit on the pink noise triplets (the MIDDLE eSTRF on the pink noise), with the same ridge parameter, for the included electrodes of S07, S08 and S13.

In [23]:
rng = np.random.default_rng(303)
PCn = pcorr_table(keys=("noise_bef", "noise_mid", "noise_aft"), subjects=noise_subjects)
print("included electrodes in S07, S08, S13:", len(PCn), "(paper: 12)")
for tag in (["a", "b"] if len(PCn) >= 2 else []):
    obs, p = ac4.signflip_test(PCn[f"diff_{tag}"], rng)
    print(f"intercept {tag}: n = {len(PCn)}, mean AFTER/MIDDLE {PCn[f'aft_mid_{tag}'].mean():.3f}, BEFORE/MIDDLE {PCn[f'bef_mid_{tag}'].mean():.3f}, difference {obs:.3f}, P = {p:.4f}")
if len(PCn):
    print(PCn.groupby("subject").size().to_string())
    print(f"MIDDLE pink noise model R2, median over these electrodes: {np.median([FITS[(s, 'noise_mid')]['r2'].mean(0)[c] for s, c in zip(PCn.subject, PCn.ch)]):.3f}")
included electrodes in S07, S08, S13: 0 (paper: 12)

Result: supp3b-pink-noise-no-pcorr-change. No electrode of S07, S08 or S13 is included in the eSTRF analyses here, so there is nothing to test; the claim is blocked.

Connectivity¶

supp6a-connectivity-increase: HFB amplitude coherence between eSTRF seed electrodes and frontal and temporal target electrodes rises slightly in AFTER against BEFORE (temporal-frontal p = 0.025, temporal-temporal p = 0.043, n = 39).

The criterion takes the seeds to be the included electrodes (9 here). The Supplementary Methods (Inter- and Intra-regional Coherence Analysis) restrict them to included electrodes "located on the temporal lobe, hereafter called Temporal seeds" (6 here); that reading is run as a variant and the difference is asked of a reader. Targets are all other temporal electrodes, or the frontal/premotor electrodes: every frontal-* and premotor-* label, including the inferior ones that the region column counts as perisylvian (90 electrodes; the frontal region alone has 64). Per trial the multitaper coherence of the HFB amplitude ("similar to that described above": the 400 ms windows of Figure 4, here the post-stimulus windows 0 to 2.5 s; NW = 4 as for Figure 4, NW = 2 as a variant), averaged over targets, then over trials, integrated over frequency in bits/s, AFTER minus BEFORE per seed, and MNE's permutation t-test across seeds. With n seeds the smallest P an exact sign-flip test can give is 2 / 2^n (0.0039 for 9, 0.031 for 6).

In [24]:
def seed_coherence(target_region, seed_set="included", nw=4.0, fmin=None):
    """Per seed the mean over post-stimulus windows of the coherence (bits/s) with the targets,
    averaged over targets then trials, for BEFORE, MIDDLE and AFTER."""
    rows = []
    for s, d in D.items():
        g = E[E.subject.eq(s)].reset_index(drop=True)
        seed_mask = g.included if seed_set == "included" else g.included & g.region.eq("temporal")
        seeds = np.where(seed_mask.to_numpy())[0]
        if target_region == "frontal":
            targ_all = np.where(g.description.str.startswith(("frontal", "premotor")).to_numpy())[0]
        else:
            targ_all = np.where(g.region.eq("temporal").to_numpy())[0]
        ep, times = EP[s]
        zep = ac4.zscore_epochs(d, ep, times, MAIN[0])
        tr = d["trials"]
        for c in seeds:
            targ = targ_all[targ_all != c]
            if not len(targ):
                continue
            row = dict(subject=s, seed=c, seed_region=g.region[c], n_targets=len(targ))
            for ph in ["bef", "mid", "aft"]:
                X = zep[cond_idx(tr, ph)]
                bits = []
                for ws in WIN_STARTS[WIN_STARTS >= 0]:
                    sel = (times >= ws - 1e-9) & (times < ws + 0.4 - 1e-9)
                    f, coh = ac4.mt_coherence(X[:, [c]][..., sel], X[:, targ][..., sel], ac4.FS_OUT, nw=nw)
                    bits.append(ac4.coh_to_bits(coh.mean(1), f, fmin=fmin).mean())   # mean over targets, then trials
                row[ph] = np.mean(bits)
            rows.append(row)
    return pd.DataFrame(rows)
COH6_ALL, rows = {}, []
for seed_set, fmin in [("included", None), ("temporal included", None), ("included", "W")]:
    for nw in [4.0, 2.0]:
        for reg in ["frontal", "temporal"]:
            t = seed_coherence(reg, seed_set, nw, None if fmin is None else nw / 0.4)
            label = seed_set if fmin is None else f"{seed_set}, from {nw / 0.4:g} Hz"
            COH6_ALL[(label, nw, reg)] = t
            diff = (t.aft - t.bef).to_numpy()
            T, p, _ = mne.stats.permutation_t_test(diff[:, None], n_permutations=10000, seed=6, tail=0)
            rows.append(dict(seeds=label, NW=nw, targets=reg, n_seeds=len(t), subjects=t.subject.nunique(),
                             bef=t.bef.mean(), mid=t.mid.mean(), aft=t.aft.mean(), aft_minus_bef=diff.mean(),
                             positive=int((diff > 0).sum()), t=T[0], p=p[0], min_possible_p=2 / 2 ** len(t)))
R6a = pd.DataFrame(rows)
print(R6a.to_string())
COH6 = {reg: COH6_ALL[("included", 4.0, reg)] for reg in ["frontal", "temporal"]}
print("main reading: seeds = all included electrodes (the criterion), NW = 4")
print(COH6["frontal"][["subject", "seed", "seed_region", "n_targets"]].to_string())
                   seeds   NW   targets  n_seeds  subjects        bef        mid        aft  aft_minus_bef  positive         t         p  min_possible_p
0               included  4.0   frontal        9         3  11.644401  12.462718  11.917961       0.273561         9  3.958311  0.003906        0.003906
1               included  4.0  temporal        9         3  11.800162  12.974733  12.047878       0.247716         7  2.640111  0.039062        0.003906
2               included  2.0   frontal        9         3   9.418076   9.460298   9.545520       0.127444         8  2.771503  0.027344        0.003906
3               included  2.0  temporal        9         3   9.290389   9.465076   9.387975       0.097586         7  2.196499  0.070312        0.003906
4      temporal included  4.0   frontal        6         3  11.616935  12.481210  11.932728       0.315793         6  3.483464  0.031250        0.031250
5      temporal included  4.0  temporal        6         3  11.778191  12.916997  12.019739       0.241548         5  2.168454  0.093750        0.031250
6      temporal included  2.0   frontal        6         3   9.335638   9.463843   9.508592       0.172954         6  3.236647  0.031250        0.031250
7      temporal included  2.0  temporal        6         3   9.256336   9.470021   9.366571       0.110235         5  2.049239  0.093750        0.031250
8   included, from 10 Hz  4.0   frontal        9         3   8.636958   8.440580   8.688498       0.051539         5  0.827622  0.464844        0.003906
9   included, from 10 Hz  4.0  temporal        9         3   8.538181   8.420585   8.562980       0.024799         5  0.462529  0.718750        0.003906
10   included, from 5 Hz  2.0   frontal        9         3   8.679048   8.468365   8.753830       0.074783         7  1.322208  0.230469        0.003906
11   included, from 5 Hz  2.0  temporal        9         3   8.491007   8.329024   8.530270       0.039263         5  0.856718  0.406250        0.003906
main reading: seeds = all included electrodes (the criterion), NW = 4
  subject  seed  seed_region  n_targets
0     S01    38  perisylvian         14
1     S01    46     temporal         15
2     S01    47     temporal         15
3     S01    49     temporal         15
4     S02    35     temporal         12
5     S04     9  perisylvian          4
6     S04    10  perisylvian          4
7     S04    15     temporal          4
8     S04    17     temporal          4

Result: supp6a-connectivity-increase. Integrated from 2.5 Hz with the 9 included electrodes as seeds and NW = 4, HFB coherence rises from BEFORE to AFTER with frontal/premotor targets (+0.27 bits/s, 9 of 9 seeds positive, t = 3.96, P = 0.0039) and with temporal targets (+0.25, 7 of 9, t = 2.64, P = 0.039). This result depends on the seeds and the bandwidth as well: with NW = 2 the temporal targets give P = 0.070, and with the 6 temporal seeds of the Supplementary Methods P = 0.094 (NW = 4) and 0.094 (NW = 2), while the frontal targets pass in every variant (P = 0.0039 to 0.031). The seeds come from three subjects.

Integrated from W (10 Hz at NW = 4, 5 Hz at NW = 2), the lowest frequency the tapers resolve apart from 0 Hz, neither target region shows an increase (frontal P = 0.46, temporal P = 0.72 at NW = 4; 0.23 and 0.41 at NW = 2). Of the frontal increase of 0.27 bits/s at NW = 4, 0.05 remains from 10 Hz up, so the effect lies in the bins at 2.5 to 7.5 Hz, whose tapers reach 0 Hz and so carry the slow time course of each window. The claims file's standard choice integrates from the lowest resolved frequency, read here as W, so the claim is not reproduced. The third verification round agreed with this change of outcome (it was reproduced, from 2.5 Hz, in rounds 1 and 2). The outcome rests on reading the lowest resolved frequency as W, which follows from the multitaper bandwidth, and the paper gives neither.

In [25]:
rows = []
for (seed_set, nw, reg), t in COH6_ALL.items():
    da, db = (t.aft - t.mid).abs().mean(), (t.bef - t.mid).abs().mean()
    rows.append(dict(seeds=seed_set, NW=nw, targets=reg, n_seeds=len(t), mean_abs_aft_mid=da, mean_abs_bef_mid=db,
                     after_closer=da < db, seeds_after_closer=int(((t.aft - t.mid).abs() < (t.bef - t.mid).abs()).sum()),
                     bef=t.bef.mean(), mid=t.mid.mean(), aft=t.aft.mean()))
print(pd.DataFrame(rows).to_string())
                   seeds   NW   targets  n_seeds  mean_abs_aft_mid  mean_abs_bef_mid  after_closer  seeds_after_closer        bef        mid        aft
0               included  4.0   frontal        9          0.544756          0.818317          True                   9  11.644401  12.462718  11.917961
1               included  4.0  temporal        9          0.926856          1.174571          True                   7  11.800162  12.974733  12.047878
2               included  2.0   frontal        9          0.114500          0.171806          True                   6   9.418076   9.460298   9.545520
3               included  2.0  temporal        9          0.204391          0.182093         False                   4   9.290389   9.465076   9.387975
4      temporal included  4.0   frontal        6          0.548481          0.864274          True                   6  11.616935  12.481210  11.932728
5      temporal included  4.0  temporal        6          0.897259          1.138806          True                   5  11.778191  12.916997  12.019739
6      temporal included  2.0   frontal        6          0.088666          0.156358          True                   4   9.335638   9.463843   9.508592
7      temporal included  2.0  temporal        6          0.207241          0.213685          True                   3   9.256336   9.470021   9.366571
8   included, from 10 Hz  4.0   frontal        9          0.247917          0.240974         False                   6   8.636958   8.440580   8.688498
9   included, from 10 Hz  4.0  temporal        9          0.207453          0.142765         False                   2   8.538181   8.420585   8.562980
10   included, from 5 Hz  2.0   frontal        9          0.285465          0.232444         False                   2   8.679048   8.468365   8.753830
11   included, from 5 Hz  2.0  temporal        9          0.223196          0.184670         False                   3   8.491007   8.329024   8.530270

Result: supp6a-after-closer-to-middle. Integrated from 2.5 Hz with the 9 included seeds and NW = 4, for both target regions the AFTER coherence is closer to MIDDLE than BEFORE is: mean |AFTER - MIDDLE| 0.54 against |BEFORE - MIDDLE| 0.82 bits/s for frontal targets (9 of 9 seeds closer), and 0.93 against 1.17 for temporal targets (7 of 9). The 6 temporal seeds give the same at NW = 4 and NW = 2. With 9 seeds at NW = 2 the temporal targets do not (0.204 against 0.182). Integrated from W, the lowest resolved frequency as for supp6a-connectivity-increase, AFTER is not closer to MIDDLE in either region (frontal 0.248 against 0.241, temporal 0.207 against 0.143 at NW = 4; 0.285 against 0.232 and 0.223 against 0.185 at NW = 2), and MIDDLE has the lowest coherence of the three conditions. Not reproduced. The third verification round agreed with this change of outcome (it was reproduced, from 2.5 Hz, in rounds 1 and 2).

supp6b-no-pac-change: Phase-amplitude coupling between 3 to 8 Hz phase in frontal/premotor electrodes and HFB amplitude in the eSTRF electrodes does not change from BEFORE to AFTER.

Supplementary Methods, Theta Connectivity Phase-Amplitude Coupling Analysis: phase from 3 to 10 Hz in 0.5 Hz steps (band-pass of +/- 1 Hz around each, a standard choice) on the frontal/premotor electrodes, HFB amplitude from 10 log-spaced bands 70 to 140 Hz on the included electrodes, the post-stimulus samples (onset to sound end) concatenated over trials per condition, PAC as in Ozkurt and Schnitzler (2011), averaged over phases 3 to 8 Hz (variants 4 to 8 and 2 to 12 Hz, the legend's), then over phase electrodes other than the amplitude electrode itself (one included electrode is also a frontal/premotor phase electrode); AFTER minus BEFORE; permutation t-test against 0.

In [26]:
PH_F = np.arange(2.0, 12.01, 0.5)
def ozkurt(amp, ph):
    n = amp.shape[-1]
    return np.abs((amp * np.exp(1j * ph)).sum(-1)) / (np.sqrt(n) * np.sqrt((amp ** 2).sum(-1)))
rows = []
for s, d in D.items():
    g = E[E.subject.eq(s)].reset_index(drop=True)
    amp_ch = np.where(g.included.to_numpy())[0]
    ph_ch = np.where(g.description.str.startswith(("frontal", "premotor")).to_numpy())[0]
    if not len(amp_ch) or not len(ph_ch):
        continue
    tr = d["trials"]
    t_ep = np.arange(int(ac4.EPOCH[0] * ac4.FS), int(ac4.EPOCH[1] * ac4.FS)) / ac4.FS
    res = {}
    for ph in ["bef", "aft"]:
        idx = cond_idx(tr, ph)
        raw = d["raw_ep"][idx].astype(np.float64)
        amp = ac4.hfb_amplitude(raw[:, amp_ch], np.geomspace(70, 140, 10))
        phases = np.stack([ac4.band_phase(raw[:, ph_ch], f - 1, f + 1) for f in PH_F])  # (freq, trials, ch, t)
        masks = [(t_ep >= 0) & (t_ep < dur) for dur in tr.duration.to_numpy()[idx]]
        A = np.concatenate([amp[i][:, m] for i, m in enumerate(masks)], axis=-1)          # (amp_ch, samples)
        P = np.concatenate([phases[:, i][..., m] for i, m in enumerate(masks)], axis=-1)  # (freq, ph_ch, samples)
        res[ph] = ozkurt(A[None, None], P[:, :, None])                                    # (freq, ph_ch, amp_ch)
    for j, c in enumerate(amp_ch):
        others = ph_ch != c            # an included frontal electrode is not its own phase electrode
        row = dict(subject=s, ch=c, n_phase_ch=int(others.sum()), self_excluded=bool((~others).any()))
        for lab, lo, hi in [("3-8", 3, 8), ("4-8", 4, 8), ("2-12", 2, 12)]:
            fm = (PH_F >= lo) & (PH_F <= hi)
            row[f"bef_{lab}"] = res["bef"][fm][:, others, j].mean()
            row[f"aft_{lab}"] = res["aft"][fm][:, others, j].mean()
        rows.append(row)
PAC = pd.DataFrame(rows)
for lab in ["3-8", "4-8", "2-12"]:
    diff = (PAC[f"aft_{lab}"] - PAC[f"bef_{lab}"]).to_numpy()
    T, p, _ = mne.stats.permutation_t_test(diff[:, None], n_permutations=10000, seed=7, tail=0)
    print(f"phase {lab} Hz: n = {len(diff)} amplitude electrodes ({PAC.subject.nunique()} subjects), BEFORE {PAC[f'bef_{lab}'].mean():.4f}, AFTER {PAC[f'aft_{lab}'].mean():.4f}, AFTER-BEFORE {diff.mean():.5f}, t = {T[0]:.2f}, P = {p[0]:.4f}")
print("amplitude electrodes that are also phase electrodes (left out of their own mean):", int(PAC.self_excluded.sum()))
phase 3-8 Hz: n = 9 amplitude electrodes (3 subjects), BEFORE 0.0054, AFTER 0.0060, AFTER-BEFORE 0.00057, t = 1.60, P = 0.1445
phase 4-8 Hz: n = 9 amplitude electrodes (3 subjects), BEFORE 0.0046, AFTER 0.0052, AFTER-BEFORE 0.00065, t = 1.93, P = 0.0625
phase 2-12 Hz: n = 9 amplitude electrodes (3 subjects), BEFORE 0.0053, AFTER 0.0056, AFTER-BEFORE 0.00026, t = 0.86, P = 0.5156
amplitude electrodes that are also phase electrodes (left out of their own mean): 1

Result: supp6b-no-pac-change. PAC between 3 to 8 Hz frontal/premotor phase and HFB amplitude of the 9 included electrodes does not change from BEFORE to AFTER (difference 0.00057, t = 1.60, P = 0.14); the variants give P = 0.063 (4 to 8 Hz) and 0.52 (2 to 12 Hz). With 9 electrodes the test has little power, and the 4 to 8 Hz variant is near the bound. Reproduced.

Coherence with the speech envelope¶

supp7-envelope-coherence: In temporal electrodes, theta coherence with the speech envelope is higher for unfiltered speech than for BEFORE (p = 0.001, n = 72), but does not differ between BEFORE and AFTER; frontal electrodes show no effects.

Supplementary Methods and Supplementary Figure 7: the speech envelope from 64 log-spaced wavelets 500 to 2000 Hz, rectified and averaged; multitaper coherence of the re-referenced ECoG with the envelope over 0 to 3 s per trial (both resampled to 100 Hz; jackknife; NW = 4, seven tapers, MNE's default as for Figure 4, and NW = 3, five tapers, the first revision's choice, as a variant), converted to normal mutual information per frequency (-log2(1 - coh)), averaged over trials; the MIDDLE minus BEFORE and AFTER minus BEFORE differences per frequency, and MNE's cluster permutation test over frequency (1 to 30 Hz) across the Speech-R electrodes of the temporal lobe and of frontal/premotor cortex.

In [27]:
import scipy.signal as ss
def envelope_nmi(nw):
  NMI = []
  for s, d in D.items():
      tr = d["trials"]
      t_ep = np.arange(int(ac4.EPOCH[0] * ac4.FS), int(ac4.EPOCH[1] * ac4.FS)) / ac4.FS
      sel = (t_ep >= 0) & (t_ep < 3.0)
      out = {}
      for ph in ["bef", "mid", "aft"]:
          idx = cond_idx(tr, ph)
          x = ss.resample_poly(d["raw_ep"][idx][..., sel].astype(np.float64), 1, 10, axis=-1)       # (trials, ch, 300)
          env = np.stack([ss.resample_poly(d["env"][i][:3000], 1, 10) for i in idx])                # (trials, 300)
          f, coh = ac4.mt_coherence(x, np.broadcast_to(env[:, None], x.shape), 100.0, nw=nw)
          out[ph] = (-np.log2(1 - np.clip(coh, 0, 1 - 1e-9))).mean(0)                                # (ch, freqs)
      NMI.append(out)
  return {ph: np.concatenate([o[ph] for o in NMI]) for ph in ["bef", "mid", "aft"]}, f
NMI_NW = {nw: envelope_nmi(nw) for nw in [4.0, 3.0]}
NMI, f = NMI_NW[4.0]
fsel = (f >= 1) & (f <= 30)
print("frequencies tested:", f[fsel])
groups = {"temporal": (E.speech_r & E.region.eq("temporal")).to_numpy(),
          "frontal": (E.speech_r & E.description.str.startswith(("frontal", "premotor"))).to_numpy()}
rows = []
for nw, (NMI_, _) in NMI_NW.items():
  for gname, m in groups.items():
    for comp in ["mid", "aft"]:
        X = (NMI_[comp] - NMI_["bef"])[m][:, fsel]
        if len(X) < 3:
            rows.append(dict(NW=nw, electrodes=gname, comparison=f"{comp}-bef", n=len(X), p=np.nan, sign="too few"))
            continue
        T, clusters, pv = clusters_of(X, 77)
        if not len(clusters):
            rows.append(dict(NW=nw, electrodes=gname, comparison=f"{comp}-bef", n=len(X), p=np.nan, sign="no cluster"))
        for c, p in zip(clusters, pv):
            fc = f[fsel][c]
            rows.append(dict(NW=nw, electrodes=gname, comparison=f"{comp}-bef", n=len(X), p=p, sign="+" if T[c].mean() > 0 else "-",
                             f_lo=fc.min(), f_hi=fc.max(), overlaps_3_8=(fc.min() <= 8) and (fc.max() >= 3),
                             overlaps_2_12=(fc.min() <= 12) and (fc.max() >= 2)))
R7 = pd.DataFrame(rows)
print(R7.to_string())
for gname, m in groups.items():
    th = (f >= 3) & (f <= 8)
    print(f"{gname} Speech-R (n = {m.sum()}): mean NMI 3-8 Hz BEFORE {NMI['bef'][m][:, th].mean():.4f}, MIDDLE {NMI['mid'][m][:, th].mean():.4f}, AFTER {NMI['aft'][m][:, th].mean():.4f} bits")
frequencies tested: [ 1.          1.33333333  1.66666667  2.          2.33333333  2.66666667
  3.          3.33333333  3.66666667  4.          4.33333333  4.66666667
  5.          5.33333333  5.66666667  6.          6.33333333  6.66666667
  7.          7.33333333  7.66666667  8.          8.33333333  8.66666667
  9.          9.33333333  9.66666667 10.         10.33333333 10.66666667
 11.         11.33333333 11.66666667 12.         12.33333333 12.66666667
 13.         13.33333333 13.66666667 14.         14.33333333 14.66666667
 15.         15.33333333 15.66666667 16.         16.33333333 16.66666667
 17.         17.33333333 17.66666667 18.         18.33333333 18.66666667
 19.         19.33333333 19.66666667 20.         20.33333333 20.66666667
 21.         21.33333333 21.66666667 22.         22.33333333 22.66666667
 23.         23.33333333 23.66666667 24.         24.33333333 24.66666667
 25.         25.33333333 25.66666667 26.         26.33333333 26.66666667
 27.         27.33333333 27.66666667 28.         28.33333333 28.66666667
 29.         29.33333333 29.66666667 30.        ]
     NW electrodes comparison   n       p sign       f_lo       f_hi  overlaps_3_8  overlaps_2_12
0   4.0   temporal    mid-bef  66  0.0369    +   1.333333   2.333333         False           True
1   4.0   temporal    mid-bef  66  0.1803    +   4.333333   4.666667          True           True
2   4.0   temporal    mid-bef  66  0.8641    +   5.666667   5.666667          True           True
3   4.0   temporal    mid-bef  66  0.3211    +   6.333333   6.666667          True           True
4   4.0   temporal    mid-bef  66  0.0123    +   7.333333   8.666667          True           True
5   4.0   temporal    mid-bef  66  0.1619    +  11.333333  12.000000         False           True
6   4.0   temporal    mid-bef  66  0.6968    +  29.666667  29.666667         False          False
7   4.0   temporal    mid-bef  66  0.7201    -   9.666667   9.666667         False           True
8   4.0   temporal    mid-bef  66  0.5089    -  19.333333  19.666667         False          False
9   4.0   temporal    mid-bef  66  0.7514    -  21.666667  21.666667         False          False
10  4.0   temporal    mid-bef  66  0.7430    -  23.000000  23.000000         False          False
11  4.0   temporal    aft-bef  66  0.3224    +  28.666667  29.000000         False          False
12  4.0   temporal    aft-bef  66  0.7357    +  29.666667  29.666667         False          False
13  4.0   temporal    aft-bef  66  0.0951    -   9.000000  10.000000         False           True
14  4.0   temporal    aft-bef  66  0.3891    -  13.666667  14.000000         False          False
15  4.0   temporal    aft-bef  66  0.7114    -  16.000000  16.000000         False          False
16  4.0   temporal    aft-bef  66  0.8987    -  17.666667  17.666667         False          False
17  4.0    frontal    mid-bef  19  0.7091    +   7.333333   7.333333          True           True
18  4.0    frontal    mid-bef  19  0.0807    +   8.000000   9.000000          True           True
19  4.0    frontal    mid-bef  19  0.8565    +  12.666667  12.666667         False          False
20  4.0    frontal    mid-bef  19  0.8692    -   1.000000   1.000000         False          False
21  4.0    frontal    mid-bef  19  0.9505    -  14.333333  14.333333         False          False
22  4.0    frontal    mid-bef  19  0.9578    -  20.333333  20.333333         False          False
23  4.0    frontal    mid-bef  19  0.7500    -  27.333333  27.333333         False          False
24  4.0    frontal    aft-bef  19  0.6665    -   1.000000   1.000000         False          False
25  4.0    frontal    aft-bef  19  0.9179    -   6.000000   6.000000          True           True
26  4.0    frontal    aft-bef  19  0.8513    -   7.000000   7.000000          True           True
27  4.0    frontal    aft-bef  19  0.9581    -  10.333333  10.333333         False           True
28  4.0    frontal    aft-bef  19  0.9571    -  16.000000  16.000000         False          False
29  4.0    frontal    aft-bef  19  0.7040    -  19.000000  19.000000         False          False
30  4.0    frontal    aft-bef  19  0.2205    -  27.333333  27.666667         False          False
31  3.0   temporal    mid-bef  66  0.0934    +   1.666667   2.333333         False           True
32  3.0   temporal    mid-bef  66  0.9078    +   3.666667   3.666667          True           True
33  3.0   temporal    mid-bef  66  0.4704    +   4.333333   4.333333          True           True
34  3.0   temporal    mid-bef  66  0.8052    +   7.333333   7.333333          True           True
35  3.0   temporal    mid-bef  66  0.6018    +   8.666667   8.666667         False           True
36  3.0   temporal    mid-bef  66  0.9584    -  10.000000  10.000000         False           True
37  3.0   temporal    mid-bef  66  0.4162    -  19.666667  20.000000         False          False
38  3.0   temporal    mid-bef  66  0.9390    -  21.333333  21.333333         False          False
39  3.0   temporal    aft-bef  66  0.9121    +   3.666667   3.666667          True           True
40  3.0   temporal    aft-bef  66  0.7192    +   4.333333   4.333333          True           True
41  3.0   temporal    aft-bef  66  0.9283    +  28.333333  28.333333         False          False
42  3.0   temporal    aft-bef  66  0.1410    +  29.000000  29.666667         False          False
43  3.0   temporal    aft-bef  66  0.7515    -   5.000000   5.000000          True           True
44  3.0   temporal    aft-bef  66  0.3234    -   8.000000   8.333333          True           True
45  3.0   temporal    aft-bef  66  0.7012    -   9.000000   9.000000         False           True
46  3.0   temporal    aft-bef  66  0.9151    -  12.333333  12.333333         False          False
47  3.0   temporal    aft-bef  66  0.9588    -  13.666667  13.666667         False          False
48  3.0    frontal    mid-bef  19  0.0012    +   6.666667   8.333333          True           True
49  3.0    frontal    mid-bef  19  0.8729    +  20.666667  20.666667         False          False
50  3.0    frontal    mid-bef  19  0.6280    +  24.333333  24.333333         False          False
51  3.0    frontal    mid-bef  19  0.9229    -  14.000000  14.000000         False          False
52  3.0    frontal    mid-bef  19  0.9771    -  27.333333  27.333333         False          False
53  3.0    frontal    aft-bef  19  0.7221    +   7.666667   7.666667          True           True
54  3.0    frontal    aft-bef  19  0.8012    +  21.000000  21.000000         False          False
55  3.0    frontal    aft-bef  19  0.9702    -   1.666667   1.666667         False          False
56  3.0    frontal    aft-bef  19  0.3471    -   6.333333   6.666667          True           True
57  3.0    frontal    aft-bef  19  0.8591    -   9.000000   9.000000         False           True
58  3.0    frontal    aft-bef  19  0.8811    -  10.333333  10.333333         False           True
59  3.0    frontal    aft-bef  19  0.6216    -  12.000000  12.000000         False           True
60  3.0    frontal    aft-bef  19  0.0802    -  14.000000  14.666667         False          False
61  3.0    frontal    aft-bef  19  0.8837    -  18.666667  18.666667         False          False
62  3.0    frontal    aft-bef  19  0.3100    -  27.333333  27.666667         False          False
temporal Speech-R (n = 66): mean NMI 3-8 Hz BEFORE 0.1393, MIDDLE 0.1542, AFTER 0.1409 bits
frontal Speech-R (n = 19): mean NMI 3-8 Hz BEFORE 0.1426, MIDDLE 0.1540, AFTER 0.1360 bits

Result: supp7-envelope-coherence. With NW = 4, in the 66 temporal Speech-R electrodes, MIDDLE minus BEFORE envelope coherence has positive clusters at 7.3 to 8.7 Hz (P = 0.012) and 1.3 to 2.3 Hz (P = 0.037), overlapping the 3 to 8 Hz and 2 to 12 Hz theta ranges; no AFTER minus BEFORE cluster reaches P < 0.05 (smallest 0.095); in the 19 frontal/premotor Speech-R electrodes no cluster of either test reaches P < 0.05 (smallest 0.081). Mean NMI from 3 to 8 Hz in temporal electrodes is 0.139 BEFORE, 0.154 MIDDLE and 0.141 AFTER bits. Reproduced under NW = 4, with the theta cluster at the upper edge of 3 to 8 Hz. With NW = 3 it is not: no temporal MIDDLE minus BEFORE cluster reaches P < 0.05 (smallest 0.093, 1.7 to 2.3 Hz), and the frontal electrodes show MIDDLE above BEFORE at 6.7 to 8.3 Hz (P = 0.0012). The outcome rests on the bandwidth, which the paper does not give.

HFB power by wavelets¶

supp4-hfb-power-increase: Power in the HFB range rises in AFTER against BEFORE in frontal (p = 0.001, n = 75) and temporal (p = 0.002, n = 217) electrodes, and power below 25 Hz falls in frontal electrodes (p = 0.001).

Supplementary Figure 4 legend: 100 log-spaced Morlet wavelets of 5 cycles, post-stimulus power averaged over time, AFTER minus BEFORE, cluster permutation test over frequency across frontal and across temporal electrodes. The claims file's standard choice is 1 to 200 Hz with power in decibels against the -800 to -100 ms baseline; the kept epochs (-1 to 3.5 s) are too short for a 5-cycle wavelet below about 3 Hz, so the range here is 3 to 200 Hz. Below about 10 Hz the wavelets reach the start of the epoch from inside the baseline, so the post-stimulus power alone (dB, no baseline; 0 to 2.5 s ends 1 s before the epoch end) is also tested. Post-stimulus is 0 to 2.5 s (claims, open detail 2, reading b). Frontal electrodes are the frontal-* and premotor-* labels, temporal the temporal lobe labels; all good electrodes.

In [28]:
WF = np.geomspace(3, 200, 100)
POW, POWR = [], []
for s, d in D.items():
    tr = d["trials"]
    t_ep = np.arange(int(ac4.EPOCH[0] * ac4.FS), int(ac4.EPOCH[1] * ac4.FS)) / ac4.FS
    td = t_ep[::10]
    base = (td >= -0.8) & (td <= -0.1)
    post = (td >= 0) & (td <= 2.5)
    out, outr = {}, {}
    for ph in ["bef", "aft"]:
        x = d["raw_ep"][cond_idx(tr, ph)].astype(np.float64)
        acc, accr = [], []
        for fchunk in np.array_split(WF, 10):
            p = mne.time_frequency.tfr_array_morlet(x, ac4.FS, fchunk, n_cycles=5, output="power", decim=10)
            acc.append(10 * np.log10(p[..., post].mean(-1) / p[..., base].mean(-1)).mean(0))     # (ch, f)
            accr.append(10 * np.log10(p[..., post].mean(-1)).mean(0))     # no baseline: post-stimulus power only
        out[ph], outr[ph] = np.concatenate(acc, axis=1), np.concatenate(accr, axis=1)
    POW.append(out["aft"] - out["bef"]); POWR.append(outr["aft"] - outr["bef"])
POW, POWR = np.concatenate(POW), np.concatenate(POWR)
rows = []
for power, PW in [("dB against baseline", POW), ("post-stimulus dB, no baseline", POWR)]:
    for gname, m in [("frontal", E.description.str.startswith(("frontal", "premotor")).to_numpy()), ("temporal", E.region.eq("temporal").to_numpy())]:
        T, clusters, pv = clusters_of(PW[m], 44)
        for c, p in zip(clusters, pv):
            rows.append(dict(power=power, electrodes=gname, n=int(m.sum()), p=p, sign="+" if T[c].mean() > 0 else "-", f_lo=WF[c].min(), f_hi=WF[c].max(),
                             hfb_overlap=(WF[c].max() >= 70) and (WF[c].min() <= 150), below_25=WF[c].min() < 25))
        hf = (WF >= 70) & (WF <= 150)
        print(f"{power}, {gname}: n = {m.sum()}, mean AFTER-BEFORE 70-150 Hz {PW[m][:, hf].mean():.3f} dB, below 25 Hz {PW[m][:, WF < 25].mean():.3f} dB")
R4 = pd.DataFrame(rows)
print(R4.to_string())
dB against baseline, frontal: n = 90, mean AFTER-BEFORE 70-150 Hz 0.231 dB, below 25 Hz -0.331 dB
dB against baseline, temporal: n = 192, mean AFTER-BEFORE 70-150 Hz 0.155 dB, below 25 Hz 0.057 dB
post-stimulus dB, no baseline, frontal: n = 90, mean AFTER-BEFORE 70-150 Hz 0.095 dB, below 25 Hz -0.039 dB
post-stimulus dB, no baseline, temporal: n = 192, mean AFTER-BEFORE 70-150 Hz 0.122 dB, below 25 Hz -0.105 dB
                           power electrodes    n       p sign       f_lo        f_hi  hfb_overlap  below_25
0            dB against baseline    frontal   90  0.0001    +  26.104213  200.000000         True     False
1            dB against baseline    frontal   90  0.3602    -   3.000000    3.265637        False      True
2            dB against baseline    frontal   90  0.0001    -   4.212189   19.397572        False      True
3            dB against baseline   temporal  192  0.1672    +   7.628415   10.710774        False      True
4            dB against baseline   temporal  192  0.2474    +  17.079588   22.030143        False      True
5            dB against baseline   temporal  192  0.0005    +  51.461653  200.000000         True     False
6  post-stimulus dB, no baseline    frontal   90  0.0006    +  19.397572  200.000000         True      True
7  post-stimulus dB, no baseline    frontal   90  0.0344    -   3.869556    6.716830        False      True
8  post-stimulus dB, no baseline   temporal  192  0.0002    +  25.019999  200.000000         True     False
9  post-stimulus dB, no baseline   temporal  192  0.0063    -   3.000000    7.628415        False      True

Result: supp4-hfb-power-increase. AFTER minus BEFORE wavelet power has a positive cluster covering the HFB range in frontal/premotor electrodes (26 to 200 Hz, P = 0.0001, n = 90) and in temporal electrodes (51 to 200 Hz, P = 0.0005, n = 192), and a negative cluster below 25 Hz in frontal electrodes (4.2 to 19.4 Hz, P = 0.0001). Without a baseline the three effects remain: HFB increases in frontal (19 to 200 Hz, P = 0.0006) and temporal electrodes (25 to 200 Hz, P = 0.0002) and a frontal decrease at 3.9 to 6.7 Hz (P = 0.034). Reproduced, with electrode counts that differ from the paper's 75 and 217.

Summary¶

Claim Outcome
behav-no-context-baseline, behav-context-enhancement, supp1a-linguistic-context, supp1a-speaker-no-difference, supp1b-filter-type, supp5a-behaviour-over-trials Blocked: data missing
speech-r-count Reproduced (101 under the non-event z-score; 377 electrodes against 468)
fig3b-hfb-increase-after Reproduced
supp3a-pink-noise-no-hfb-change Reproduced
supp5b-hfb-stable-over-session Not reproduced (assumption: z-score by non-event times; holds with the per-trial baseline)
fig4a-coherence-after-higher Reproduced (assumption: multitaper bandwidth)
fig4b-coherence-sentence-specific Reproduced (assumption: multitaper bandwidth)
strf-r-count Not reproduced (9 against 53)
included-electrode-count Not reproduced (9 against 41)
fig8-mtf-matches-filter Not reproduced (no in-region cluster for the shift)
fig9-rms-increase Partially reproduced
fig9-middle-generalizes-after Reproduced
fig10-partial-correlation Partially reproduced
fig10b-similarity-correlates Not reproduced
fig10c-stg-location Reproduced
supp3b-pink-noise-no-pcorr-change Blocked: no included electrode in the pink noise subjects
supp6a-connectivity-increase Not reproduced (assumption: multitaper bandwidth; integrated from W = 10 Hz; reproduced from 2.5 Hz)
supp6a-after-closer-to-middle Not reproduced (assumption: multitaper bandwidth; integrated from W = 10 Hz; reproduced from 2.5 Hz)
supp6b-no-pac-change Reproduced
supp7-envelope-coherence Reproduced (assumption: multitaper bandwidth; not with NW = 3)
supp4-hfb-power-increase Reproduced

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 HFB band edges, the filter orders, the auditory spectrogram's compression and sharpening and the wavelet range are standard choices the paper does not fix; the multitaper bandwidth is MNE's default (NW = 4), the claims file's standard choice, on which supp6a-connectivity-increase, supp6a-after-closer-to-middle and supp7-envelope-coherence depend; the coherence of Supplementary Figure 6a is integrated from the tapers' half-bandwidth (10 Hz), the lowest resolved frequency, and both supp6a claims are reproduced when it is integrated from 2.5 Hz; Figure 4's claims are reproduced under either bound; the z-score that defines Speech-R is the code's z-score by non-event times, the only one of three readings that gives counts near the paper's; the ridge parameter is the mode of the per-split best values below the top of the grid, since the mode over all values falls at the top of any grid. The eSTRFs predict held-out trials in far fewer electrodes than the paper reports (9 against 53), so every eSTRF claim rests on 9 electrodes from three subjects, and the pink noise eSTRF claim cannot be tested. A check of the alignment of spectrogram and HFB finds no offset, and no drift over the session, that would raise the count.

What was found about the data set: it holds 7 subjects with 416 channels (377 marked good) against the paper's 524 recorded and 468 kept, with no mapping between its subject names and the paper's S1 to S7; the stored values are not in the stated millivolts and their scale differs by six orders of magnitude between S01 and the other subjects; the behavioural control data are not included; the stimulus audio is included although the data set's own notebook says it is not; events marked bad are not described.