MNE-Python: KIT Attention Task of Worden et al. (2000), sensor-space analysis
Lead author: Hadi Zaatiti hadi.zaatiti@nyu.edu
Sensor-space analysis of the first participant (sub-0955, session of 2026-11-16) of the attention_task_worden experiment, the lab’s replication of
Worden MS, Foxe JJ, Wang N, Simpson GV (2000). Anticipatory biasing of visuospatial attention indexed by retinotopically specific alpha-band electroencephalography increases over occipital cortex. J Neurosci 20(6):RC63.
The task. A central arrow (the cue, 33 ms) points left or right. About one second later a stimulus (a rotated T, or two dots in apparent motion) appears briefly in one of two squares, left or right of fixation, in the upper or the lower visual field. The participant presses a button only when the stimulus at the cued square is the target of the block, and ignores the other square. One run is 8 blocks of 16 trials (128 trials); the cue side changes from trial to trial.
The prediction of the paper. In the second between the cue and the stimulus, alpha-band (8-14 Hz) amplitude over the occipital cortex becomes higher over the hemisphere ipsilateral to the cued side (the hemisphere that processes the location to ignore) than over the contralateral one. With the lateralisation index LI = (R - L) / (R + L) of the alpha amplitude over the right (R) and left (L) posterior sensors, LI should be higher after a cue to the right than after a cue to the left.
What this notebook does.
Behaviour: did the participant use the cue?
Checks of the recording: trigger timing, sensors that stopped working during the session.
Two positive controls that the recording and the lateralisation measure work: the field evoked by the stimulus, and the alpha lateralisation that follows a lateralised stimulus.
The analysis of the paper: alpha amplitude over time after the cue, lateralisation index, sensor maps, split by visual field, task, run and frequency band, and a time-frequency map.
How much the result depends on the analysis choices, and how many trials a conclusive test needs.
Every statistic is over the trials of one participant. The results are discussed section by section and summarised at the end.
The results at a glance.
Question |
Answer |
Evidence |
|---|---|---|
Did the participant use the cue? |
Yes |
responds to the target identity in 68% of the trials at the cued square and 7% at the uncued one, p = 7 x 10^-19 |
Is the recording sound? |
Yes, with two reservations |
left and right stimuli evoke mirror-image posterior fields (cluster p = 0.0005 and 0.002); but 13 sensors went flat during the session, and the cue-to-stimulus interval is one video frame short in 45% of the trials |
Does the lateralisation index detect a known alpha lateralisation? |
No |
after a lateralised stimulus the index does not differ between left and right stimuli (d = +0.04, p = 0.64) |
Is alpha lateralised after the cue as in the paper? |
In the direction of the paper, not reliably |
d = +0.11, p = 0.17 in the planned window; one stretch of the time course, 700-800 ms after the cue, passes the cluster test (p = 0.04) |
The earlier notebook on the first version of the task (attention cued once per block) is MNE-Python: KIT Attention Task Analysis.
Data and pipeline. Dataset MEG/Data/attention-task-worden (five recordings, run-04 to run-08; run-01 to run-03 were start-up tests without a recording). The notebook reads the original .con recordings and the events.tsv files the stimulus computer wrote for each run, so it does not depend on any stage of the KIT general pipeline. No CALM noise reduction and no ICA are applied here.
Setup
Set the MEG_DATA environment variable to the Box MEG/Data folder (the folder that contains attention-task-worden). Figures and results.json are written to attention-task-worden/derivatives/mne_attention_worden_sensor.
[1]:
import os, json, warnings
from pathlib import Path
import numpy as np
import pandas as pd
import scipy.stats as ss
import matplotlib.pyplot as plt
import mne
mne.set_log_level("ERROR")
warnings.filterwarnings("ignore")
MEG_DATA = Path(os.environ.get("MEG_DATA", Path.home() / "Box" / "MEG" / "Data"))
ROOT = MEG_DATA / "attention-task-worden"
SUB, SES, TASK = "0955", "01", "attentionworden"
SESDIR = ROOT / f"sub-{SUB}" / f"ses-{SES}"
OUT = Path(os.environ.get("ATTENTION_WORDEN_OUT", ROOT / "derivatives" / "mne_attention_worden_sensor"))
OUT.mkdir(parents=True, exist_ok=True)
RUNS = [4, 5, 6, 7, 8]
# KIT trigger line -> event (MNE names the lines MISC 001 ... MISC 004)
CODES = {224: "cue_left", 225: "cue_right", 226: "stimulus_left", 227: "stimulus_right"}
BANDS = {"theta": (4, 7), "alpha": (8, 14), "beta": (15, 25)}
SF = 250.0 # sampling rate after resampling (Hz); recorded at 1000 Hz
TMIN, TMAX = -0.5, 1.3 # cue-locked epoch (s); the stimulus comes 1.03 s after the cue
WIN = (0.775, 1.025) # analysis window: the 250 ms before the earliest stimulus
BASE = (-0.4, -0.1) # pre-cue reference of the percent-change curves
FLAT_T = 15e-15 # T: a sensor whose 1-40 Hz standard deviation is below this is flat
WINDOW_S = 30 # s: length of the windows in which sensor quality is assessed
RNG = np.random.default_rng(0)
BLUE, RED, GREY = "#2a78d6", "#d64a3a", "0.45"
RES = dict(subject=SUB, session=SES, runs=RUNS, window_s=WIN)
def robust_z(x):
med = np.median(x)
return (x - med) / (1.4826 * np.median(np.abs(x - med)))
def savefig(name):
plt.savefig(OUT / f"{name}.png", dpi=130, bbox_inches="tight")
plt.show()
plt.close()
def stem(run):
return f"sub-{SUB}_ses-{SES}_task-{TASK}_run-{run:02d}"
def portable(path):
"""A path shown relative to MEG_DATA, so that the outputs do not contain a machine-specific location."""
try:
return "$MEG_DATA/" + Path(path).relative_to(MEG_DATA).as_posix()
except ValueError:
return Path(path).name
print("dataset:", portable(ROOT), "| found:", ROOT.is_dir())
dataset: $MEG_DATA/attention-task-worden | found: True
1. Behaviour: did the participant use the cue?
The alpha effect of the paper is a signature of deploying attention to the cued side. If the participant had ignored the cue, there would be nothing to find, so behaviour comes first.
The beh.tsv file of each run has one row per trial. A stimulus with the identity of the block’s target can appear at the cued square (a button press is a hit, no press a miss) or at the uncued square (it must be ignored: a press there is a false alarm). A participant who uses the cue responds to the target identity often at the cued square and almost never at the uncued one; a participant who ignores the cue responds equally at both.
Accuracy is computed as in the paper: (hits - false alarms) / number of targets.
[2]:
beh = pd.concat([pd.read_csv(SESDIR / "beh" / f"{stem(r)}_beh.tsv", sep="\t", na_values=["n/a"]).assign(run=r)
for r in RUNS], ignore_index=True)
beh["target_identity_shown"] = beh.stimulus_identity == beh.target_identity
cued_t = beh[(beh.location_cued == 1) & beh.target_identity_shown] # targets: respond
uncued_t = beh[(beh.location_cued == 0) & beh.target_identity_shown] # same identity, uncued square: ignore
other = beh[~beh.target_identity_shown] # any other stimulus: ignore
rows = []
for r in RUNS + ["all"]:
sel = (lambda d: d if r == "all" else d[d.run == r])
c, u, o = sel(cued_t), sel(uncued_t), sel(other)
b = sel(beh)
hits, fa = int(c.responded.sum()), int(u.responded.sum() + o.responded.sum())
rows.append({"run": r, "trials": len(b), "targets (cued square)": len(c), "hits": hits, "misses": len(c) - hits,
"hit rate": round(hits / len(c), 2),
"target identity at uncued square": len(u), "responses there": int(u.responded.sum()),
"responses to other stimuli": int(o.responded.sum()),
"accuracy (hits - FA) / targets": round((hits - fa) / len(c), 2),
"median hit RT (ms)": int(round(1000 * c.response_time.median()))})
beh_table = pd.DataFrame(rows).set_index("run")
print(beh_table.T.to_string())
# Is the response rate to the target identity different at the cued and the uncued square?
table = [[int(cued_t.responded.sum()), int((1 - cued_t.responded).sum())],
[int(uncued_t.responded.sum()), int((1 - uncued_t.responded).sum())]]
odds, p_fisher = ss.fisher_exact(table)
RES["behaviour"] = dict(hit_rate=float(cued_t.responded.mean()), n_targets=int(len(cued_t)),
response_rate_uncued_target_identity=float(uncued_t.responded.mean()), n_uncued=int(len(uncued_t)),
fisher_p=float(p_fisher), odds_ratio=float(odds),
median_hit_rt_s=float(cued_t.response_time.median()),
by_run=beh_table.reset_index().astype(str).to_dict("records"))
print(f"\nResponse rate to the target identity: cued square {cued_t.responded.mean():.0%} ({table[0][0]}/{len(cued_t)}), "
f"uncued square {uncued_t.responded.mean():.0%} ({table[1][0]}/{len(uncued_t)}); Fisher exact p = {p_fisher:.1e}")
fig, axes = plt.subplots(1, 2, figsize=(11, 3.6))
x = np.arange(len(RUNS))
axes[0].bar(x - 0.2, [cued_t[cued_t.run == r].responded.mean() for r in RUNS], 0.4, color=BLUE, label="target identity at the cued square (hit)")
axes[0].bar(x + 0.2, [uncued_t[uncued_t.run == r].responded.mean() for r in RUNS], 0.4, color=RED, label="target identity at the uncued square (false alarm)")
axes[0].set_xticks(x); axes[0].set_xticklabels([f"run-{r:02d}" for r in RUNS]); axes[0].set(ylabel="proportion of button presses", ylim=(0, 1.25)); axes[0].set_yticks([0, 0.25, 0.5, 0.75, 1])
axes[0].legend(fontsize=8, loc="upper left"); axes[0].set_title("The cue decides whether the participant responds")
hit_rt = cued_t[cued_t.responded == 1]
axes[1].hist(1000 * hit_rt.response_time, bins=20, color=GREY)
axes[1].set(xlabel="response time of the hits (ms)", ylabel="trials", title=f"Hits: median {1000 * hit_rt.response_time.median():.0f} ms")
savefig("fig01_behaviour")
run 4 5 6 7 8 all
trials 128.00 128.00 128.00 128.0 128.00 640.00
targets (cued square) 25.00 30.00 24.00 30.0 29.00 138.00
hits 17.00 26.00 14.00 15.0 22.00 94.00
misses 8.00 4.00 10.00 15.0 7.00 44.00
hit rate 0.68 0.87 0.58 0.5 0.76 0.68
target identity at uncued square 13.00 16.00 15.00 15.0 13.00 72.00
responses there 4.00 1.00 0.00 0.0 0.00 5.00
responses to other stimuli 5.00 0.00 0.00 0.0 1.00 6.00
accuracy (hits - FA) / targets 0.32 0.83 0.58 0.5 0.72 0.60
median hit RT (ms) 651.00 544.00 589.00 533.0 554.00 578.00
Response rate to the target identity: cued square 68% (94/138), uncued square 7% (5/72); Fisher exact p = 6.7e-19
Reading. The participant used the cue. A stimulus with the target identity is answered in 68% of the trials when it appears at the cued square (94 of 138) and in 7% when it appears at the uncued square (5 of 72; Fisher exact p = 7 x 10^-19). Four of those five false alarms are in run-04, the first run, which is also why its accuracy is the lowest (0.32): the participant was still learning to ignore the uncued square. From run-06 on there is not a single response at the uncued square.
The task is not easy: a third of the targets are missed (hit rate between 0.50 and 0.87 per run), and the hits take 578 ms (median). Attention was therefore engaged and directed by the cue, which is the precondition for everything that follows.
2. Loading the recordings
For each run:
Triggers. The four trigger lines used here (cue left / right, stimulus left / right) are read at the original 1000 Hz. A pulse is the sample where the line rises above 1 V. The pulses of each line are paired, in order, with the rows of that line in the run’s
events.tsv, which is how each event gets its block, trial, task, visual field and outcome. The number of pulses must equal the number of rows (the notebook stops otherwise).Resampling. The 208 KIT sensors (MNE types them
mag; they are axial gradiometers) are resampled to 250 Hz, which removes everything above 125 Hz.Filtering. A 1-40 Hz band-pass copy is used for the evoked fields, trial rejection and the time-frequency map. For theta, alpha and beta, the resampled data are band-passed and replaced by the amplitude of their Hilbert transform: the envelope of the oscillation. This is the “temporal spectral evolution” (TSE) of the paper (band-pass, rectify, average); the Hilbert envelope is its smooth equivalent. No notch filter is needed: every band-pass used stops below 50 Hz.
Epochs. Cue-locked from -0.5 to 1.3 s (the stimulus comes at 1.03 s), and stimulus-locked for the positive controls. No baseline is subtracted from the envelopes.
Sensor quality. The 1-40 Hz standard deviation of every sensor in consecutive 30 s windows is kept for section 4.
[3]:
def load_run(run):
raw = mne.io.read_raw_kit(SESDIR / "meg" / f"{stem(run)}_meg.con", preload=False)
duration = raw.n_times / raw.info["sfreq"]
trig = raw.copy().pick([f"MISC {k:03d}" for k in range(1, 5)]).load_data().get_data()
tsv = pd.read_csv(SESDIR / "meg" / f"{stem(run)}_events.tsv", sep="\t", na_values=["n/a"])
tsv = tsv[tsv.hardware_emitted == 1]
keep_cols = ["block", "trial", "task", "visual_field", "target_identity", "cue_side", "stimulus_side",
"stimulus_identity", "location_cued", "is_target"]
parts = []
for i, code in enumerate(CODES):
onsets = np.flatnonzero((trig[i, 1:] > 1.0) & (trig[i, :-1] <= 1.0)) + 1
rows = tsv[tsv.value == code].reset_index(drop=True)
if len(onsets) != len(rows):
raise RuntimeError(f"run {run}, line {code}: {len(onsets)} pulses but {len(rows)} rows in events.tsv")
rows = rows[keep_cols].copy()
rows["sample_1k"], rows["code"], rows["run"] = onsets, code, run
parts.append(rows)
ev = pd.concat(parts).sort_values("sample_1k").reset_index(drop=True)
stim = ev[ev.code.isin([226, 227])].set_index(["block", "trial"])
outcome = tsv[tsv.value.isin([226, 227])].set_index(["block", "trial"])["outcome"]
ev["outcome"] = [outcome.get((b, t), np.nan) for b, t in zip(ev.block, ev.trial)]
# cue-to-stimulus interval of each trial, at the original 1 ms resolution
ev["soa_ms"] = [float(stim.loc[(b, t), "sample_1k"] - s) if c in (224, 225) else np.nan
for b, t, s, c in zip(ev.block, ev.trial, ev.sample_1k, ev.code)]
raw.pick("mag").load_data()
arr = np.c_[ev["sample_1k"].to_numpy(), np.zeros(len(ev), int), ev["code"].to_numpy()]
raw, arr = raw.resample(SF, events=arr)
ev["sample"] = arr[:, 0]
def epochs(r, codes, tmin, tmax, baseline=None):
sel = ev[ev.code.isin(codes)].reset_index(drop=True)
a = np.c_[sel["sample"].to_numpy(), np.zeros(len(sel), int), sel["code"].to_numpy()]
ep = mne.Epochs(r, a, tmin=tmin, tmax=tmax, baseline=baseline, preload=True)
if len(ep) != len(sel):
raise RuntimeError(f"run {run}: {len(sel) - len(ep)} epochs fall outside the recording")
return ep.get_data().astype(np.float32), ep.times, sel
out = dict(run=run, info=raw.info, duration=duration)
bb = raw.copy().filter(1, 40)
x = bb.get_data()
n = int(WINDOW_S * SF)
k = x.shape[1] // n
out["sdw"] = x[:, :k * n].reshape(len(x), k, n).std(2) # sensors x 30 s windows
del x
out["cue"], out["times"], out["meta"] = epochs(bb, [224, 225], TMIN, TMAX)
out["stim"], out["stimes"], out["smeta"] = epochs(bb, [226, 227], -0.2, 0.6, (-0.2, 0))
del bb
out["env"] = {}
for band, (lo, hi) in BANDS.items():
env = raw.copy().filter(lo, hi).apply_hilbert(envelope=True)
out["env"][band] = epochs(env, [224, 225], TMIN, TMAX)[0]
del env
# alpha band-passed signal (not its envelope) around the stimulus, for the control of section 7
out["bp_stim"], out["etimes"], _ = epochs(raw.copy().filter(*BANDS["alpha"]), [226, 227], -0.6, 1.3)
print(f"run-{run:02d}: {duration:.0f} s, {len(out['meta'])} cue epochs "
f"({(out['meta'].code == 224).sum()} left, {(out['meta'].code == 225).sum()} right), "
f"{len(out['smeta'])} stimulus epochs")
return out
R = [load_run(r) for r in RUNS]
info_all, times, stimes, etimes = R[0]["info"], R[0]["times"], R[0]["stimes"], R[0]["etimes"]
pos_all = np.array([c["loc"][:3] for c in info_all["chs"]]) # sensor positions in the helmet frame (m)
run-04: 685 s, 128 cue epochs (64 left, 64 right), 128 stimulus epochs
run-05: 515 s, 128 cue epochs (64 left, 64 right), 128 stimulus epochs
run-06: 525 s, 128 cue epochs (64 left, 64 right), 128 stimulus epochs
run-07: 510 s, 128 cue epochs (64 left, 64 right), 128 stimulus epochs
run-08: 490 s, 128 cue epochs (64 left, 64 right), 128 stimulus epochs
3. Check of the trigger timing: the cue-to-stimulus interval
The experiment plans the stimulus 124 video frames after the cue (4 frames of cue + 120 frames of delay at 120 Hz = 1033.6 ms). The triggers are read by the DataPixx from a pixel of the video frame itself, so the interval between the cue pulse and the stimulus pulse in the recording is the interval that was actually shown.
[4]:
soa = pd.concat([r["meta"][["run", "soa_ms"]] for r in R], ignore_index=True)
frame_ms = 1000 / 119.974
soa["frames"] = np.round(soa.soa_ms / frame_ms).astype(int)
counts = soa.groupby("run").frames.value_counts().unstack(fill_value=0)
print("Cue-to-stimulus interval in video frames (rows: run, columns: frames):")
print(counts.to_string())
print(f"\nAll trials: {soa.soa_ms.min():.0f} to {soa.soa_ms.max():.0f} ms; "
f"{(soa.frames == 123).mean():.0%} at 123 frames (about 1025 ms), {(soa.frames == 124).mean():.0%} at 124 frames (about 1034 ms)")
RES["cue_to_stimulus"] = dict(min_ms=float(soa.soa_ms.min()), max_ms=float(soa.soa_ms.max()),
fraction_123_frames=float((soa.frames == 123).mean()),
fraction_124_frames=float((soa.frames == 124).mean()),
by_run={f"run-{int(k):02d}": {str(c): int(v[c]) for c in counts.columns} for k, v in counts.iterrows()})
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.hist(soa.soa_ms, bins=np.arange(1020.5, 1040.5, 1), color=GREY)
ax.axvline(124 * frame_ms, c=RED, ls="--", label="planned: 124 frames")
ax.axvline(123 * frame_ms, c=BLUE, ls="--", label="123 frames")
ax.set(xlabel="cue pulse to stimulus pulse (ms)", ylabel="trials", title="Cue-to-stimulus interval in the recordings (640 trials)")
ax.legend(fontsize=8)
savefig("fig02_cue_to_stimulus_interval")
Cue-to-stimulus interval in video frames (rows: run, columns: frames):
frames 123 124
run
4 61 67
5 63 65
6 62 66
7 52 76
8 51 77
All trials: 1025 to 1034 ms; 45% at 123 frames (about 1025 ms), 55% at 124 frames (about 1034 ms)
Reading. The interval takes two values, one video frame (8.3 ms) apart: the planned 124 frames, or 123 frames. Nothing else occurs, and no trial is off by more than one frame. The stimulus computer logged a constant 1030 ms, which is not a whole number of frames: its flip time stamps were off by a fraction of a frame (Psychtoolbox reported a beam-position time stamp error at start-up), and the experiment schedules each flip from the previous time stamp, so a flip lands on either side of a frame boundary.
For this analysis the consequence is small. The epochs are locked to the cue pulse, and the analysis window ends at 1025 ms, the earliest moment a stimulus appeared. The experiment should nevertheless count frames instead of scheduling by time before more participants are recorded, because the same one-frame uncertainty applies to the 33 ms cue and the 83 ms stimulus.
4. Check of the sensors: channels that stopped working during the session
A KIT sensor that loses its lock reads an almost flat line. The 1-40 Hz standard deviation of the working sensors in this session is 50 fT or more; a sensor is called flat in a 30 s window when it is below 15 fT. A sensor is noisy in a window when it is more than five times the median of all sensors in that window.
[5]:
sdw = np.concatenate([r["sdw"] for r in R], axis=1) # sensors x windows of the session
run_of_window = np.concatenate([[r["run"]] * r["sdw"].shape[1] for r in R])
flat = sdw < FLAT_T
noisy = sdw > 5 * np.median(sdw, axis=0)
flat_idx = np.flatnonzero(flat.any(1))
persist_noisy_idx = np.flatnonzero(noisy.mean(1) > 0.2)
bad_idx = sorted(set(flat_idx) | set(persist_noisy_idx))
BADS = [info_all.ch_names[i] for i in bad_idx]
first_flat = {}
for i in flat_idx:
w = np.flatnonzero(flat[i])[0]
run = int(run_of_window[w])
first_flat[info_all.ch_names[i]] = f"run-{run:02d}, {WINDOW_S * int(w - np.flatnonzero(run_of_window == run)[0])} s"
print("Flat sensors and the moment each one first went flat:")
for name, when in sorted(first_flat.items(), key=lambda kv: kv[1]):
i = info_all.ch_names.index(name)
print(f" {name}: {when:14s} position x = {100 * pos_all[i, 0]:+5.1f} cm, y = {100 * pos_all[i, 1]:+5.1f} cm, flat in {flat[i].mean():.0%} of the session")
print("Flat sensors per run (at the end of the run):", {f"run-{r['run']:02d}": int((r["sdw"][:, -1] < FLAT_T).sum()) for r in R})
print("Persistently noisy sensors:", [info_all.ch_names[i] for i in persist_noisy_idx])
bursts = np.flatnonzero(noisy.sum(0) > 5)
print("Windows with a burst of noise on more than 5 sensors:",
[(f"run-{int(run_of_window[w]):02d}", int(noisy[:, w].sum())) for w in bursts])
print("Flat sensors before and one minute after each burst:")
burst_rows = []
for w in bursts:
before, after = int(flat[:, max(w - 1, 0)].sum()), int(flat[:, min(w + 2, flat.shape[1] - 1)].sum())
burst_rows.append(dict(run=int(run_of_window[w]), n_noisy=int(noisy[:, w].sum()), flat_before=before, flat_after=after))
print(f" run-{int(run_of_window[w]):02d}: {int(noisy[:, w].sum())} noisy sensors in the burst; {before} flat sensors before, {after} after")
RES["sensors"] = dict(removed=BADS, first_flat=first_flat, bursts=burst_rows,
flat_at_end_of_run={f"run-{r['run']:02d}": int((r["sdw"][:, -1] < FLAT_T).sum()) for r in R},
noise_bursts=[dict(run=int(run_of_window[w]), n_sensors=int(noisy[:, w].sum())) for w in bursts])
fig, axes = plt.subplots(1, 3, figsize=(16, 4), gridspec_kw=dict(width_ratios=[1.9, 1.3, 1]))
im = axes[0].imshow(np.log10(sdw[flat_idx] * 1e15), aspect="auto", cmap="viridis", vmin=0.3, vmax=2.3, interpolation="nearest")
axes[0].set_yticks(range(len(flat_idx))); axes[0].set_yticklabels([info_all.ch_names[i] for i in flat_idx], fontsize=7)
edges = np.flatnonzero(np.diff(run_of_window)) + 0.5
for e in edges: axes[0].axvline(e, c="w", lw=1)
centres = [np.flatnonzero(run_of_window == r).mean() for r in RUNS]
axes[0].set_xticks(centres); axes[0].set_xticklabels([f"run-{r:02d}" for r in RUNS])
axes[0].set_title("Sensors that went flat: 1-40 Hz standard deviation per 30 s window")
cb = fig.colorbar(im, ax=axes[0]); cb.set_ticks([0.3, 1, 1.7, 2.3]); cb.set_ticklabels(["2", "10", "50", "200"]); cb.set_label("fT")
axes[1].plot(flat.sum(0), c="k", label="flat sensors")
axes[1].plot(noisy.sum(0), c=RED, label="noisy sensors (> 5 x median)")
for e in edges: axes[1].axvline(e, c="0.8", lw=1)
axes[1].set_xticks(centres); axes[1].set_xticklabels([f"run-{r:02d}" for r in RUNS])
axes[1].set(ylabel="number of sensors", title="Flat and noisy sensors over the session"); axes[1].legend(fontsize=8)
axes[2].scatter(pos_all[:, 0], pos_all[:, 1], s=10, c="0.8")
axes[2].scatter(pos_all[bad_idx, 0], pos_all[bad_idx, 1], s=40, c="k", marker="x")
for i in bad_idx: axes[2].annotate(info_all.ch_names[i][4:], pos_all[i, :2], fontsize=7, xytext=(3, 3), textcoords="offset points")
axes[2].set_aspect("equal"); axes[2].set(title="Removed sensors, top view (front up)", xlabel="x (m), right +", ylabel="y (m), front +")
savefig("fig03_sensor_quality")
Flat sensors and the moment each one first went flat:
MEG 041: run-05, 330 s position x = -2.2 cm, y = +12.3 cm, flat in 62% of the session
MEG 147: run-06, 210 s position x = +7.4 cm, y = -9.9 cm, flat in 44% of the session
MEG 032: run-06, 240 s position x = +2.8 cm, y = +10.1 cm, flat in 44% of the session
MEG 111: run-06, 240 s position x = -4.5 cm, y = +11.5 cm, flat in 47% of the session
MEG 136: run-06, 240 s position x = -9.3 cm, y = -8.0 cm, flat in 46% of the session
MEG 181: run-06, 300 s position x = -7.8 cm, y = -9.6 cm, flat in 37% of the session
MEG 137: run-07, 120 s position x = +10.3 cm, y = -6.0 cm, flat in 33% of the session
MEG 001: run-07, 150 s position x = +6.0 cm, y = -0.7 cm, flat in 7% of the session
MEG 139: run-07, 150 s position x = +9.0 cm, y = -8.2 cm, flat in 30% of the session
MEG 142: run-07, 150 s position x = +8.9 cm, y = -8.0 cm, flat in 31% of the session
MEG 004: run-07, 420 s position x = +1.6 cm, y = -5.8 cm, flat in 1% of the session
MEG 160: run-07, 480 s position x = +10.2 cm, y = -6.2 cm, flat in 18% of the session
MEG 093: run-08, 450 s position x = -1.8 cm, y = +11.7 cm, flat in 1% of the session
Flat sensors per run (at the end of the run): {'run-04': 0, 'run-05': 1, 'run-06': 6, 'run-07': 10, 'run-08': 11}
Persistently noisy sensors: []
Windows with a burst of noise on more than 5 sensors: [('run-05', 40), ('run-06', 45), ('run-07', 39), ('run-08', 28)]
Flat sensors before and one minute after each burst:
run-05: 40 noisy sensors in the burst; 0 flat sensors before, 1 after
run-06: 45 noisy sensors in the burst; 1 flat sensors before, 5 after
run-07: 39 noisy sensors in the burst; 6 flat sensors before, 10 after
run-08: 28 noisy sensors in the burst; 10 flat sensors before, 11 after
Reading. No sensor is flat in run-04. The first one stops in the middle of run-05, and the number grows to 6 at the end of run-06, 10 at the end of run-07 and 11 at the end of run-08; 13 different sensors are flat at some point. Seven of them lie in the posterior regions used below (two on the left, five on the right), which is where the effect of the paper is expected.
Each run from run-05 on also contains one 30 s window in which 28 to 45 sensors are noisy at once. These bursts and the flat sensors are the same story: the number of flat sensors steps up right after each burst (0 to 1, 1 to 5, 6 to 10, 10 to 11). Something disturbed the system once per run, and each time a few more sensors did not recover.
Every sensor that is flat at any moment is removed from all runs, so that the left and right sensor groups are the same in every trial. The bursts are left to the trial rejection below. This progressive loss of sensors is worth reporting to whoever maintains the system.
5. Trial rejection and regions of interest
Trials. An epoch is rejected when its largest peak-to-peak amplitude (1-40 Hz, over the remaining sensors) is far above the distribution of its own run: robust z-score of the log amplitude above 3.5. This removes the noise bursts, large movements and blinks without a fixed threshold. There is no EOG channel and no eye tracking in this session.
Regions of interest. Without source localisation the analysis is done in the helmet frame (x to the right, y to the front). The left and right posterior regions are the sensors at the back of the helmet (y < -6 cm), at least 2 cm from the midline. They are defined from the sensor positions only, before looking at any contrast. Note that the KIT sensors are axial gradiometers: the field of a source is largest on either side of it, not above it, so a left / right split of the sensors separates the hemispheres less cleanly than EEG electrodes or planar gradiometers would.
[6]:
good = np.setdiff1d(np.arange(len(info_all.ch_names)), bad_idx)
info = mne.pick_info(info_all, good)
pos = pos_all[good]
keep, skeep = [], []
for r in R:
for key, store in (("cue", keep), ("stim", skeep)):
ptp = np.ptp(r[key][:, good], axis=2).max(axis=1)
store.append(robust_z(np.log(ptp)) < 3.5)
kept_by_run = {f"run-{r['run']:02d}": f"{int(k.sum())} of {len(k)}" for r, k in zip(R, keep)}
keep, skeep = np.concatenate(keep), np.concatenate(skeep)
meta = pd.concat([r["meta"] for r in R], ignore_index=True)[keep].reset_index(drop=True)
smeta = pd.concat([r["smeta"] for r in R], ignore_index=True)[skeep].reset_index(drop=True)
ENV = {b: np.concatenate([r["env"][b] for r in R])[keep][:, good] for b in BANDS} # trials x sensors x times
CUE = np.concatenate([r["cue"] for r in R])[keep][:, good] # 1-40 Hz, cue-locked
STIM = np.concatenate([r["stim"] for r in R])[skeep][:, good] # 1-40 Hz, stimulus-locked
BP_STIM = np.concatenate([r["bp_stim"] for r in R])[skeep][:, good] # alpha band-passed, stimulus-locked
n_all = int(len(keep))
del R
is_left = (meta.code == 224).to_numpy() # cue left
s_left = (smeta.code == 226).to_numpy() # stimulus left
ROI_L = np.flatnonzero((pos[:, 1] < -0.06) & (pos[:, 0] < -0.02))
ROI_R = np.flatnonzero((pos[:, 1] < -0.06) & (pos[:, 0] > 0.02))
win = (times >= WIN[0]) & (times <= WIN[1])
base = (times >= BASE[0]) & (times <= BASE[1])
print("cue epochs kept per run:", kept_by_run)
print(f"cue epochs kept: {len(meta)} of {n_all} ({is_left.sum()} cue left, {(~is_left).sum()} cue right); "
f"stimulus epochs kept: {len(smeta)} ({s_left.sum()} left, {(~s_left).sum()} right)")
print(f"{len(good)} sensors kept; left posterior region {len(ROI_L)} sensors, right posterior region {len(ROI_R)}")
lost = pos_all[bad_idx]
print("removed sensors that would have been in the left region:", int(((lost[:, 1] < -0.06) & (lost[:, 0] < -0.02)).sum()),
"| in the right region:", int(((lost[:, 1] < -0.06) & (lost[:, 0] > 0.02)).sum()))
RES["trials"] = dict(recorded=n_all, kept=int(len(meta)), cue_left=int(is_left.sum()), cue_right=int((~is_left).sum()), kept_by_run=kept_by_run)
RES["roi"] = dict(left=[info.ch_names[i] for i in ROI_L], right=[info.ch_names[i] for i in ROI_R])
# sensor adjacency for the cluster tests
adjacency, adj_names = mne.channels.find_ch_adjacency(info_all, "mag")
ia = [adj_names.index(c) for c in info.ch_names]
adjacency = adjacency[ia][:, ia]
welch_t = lambda a, b: ss.ttest_ind(a, b, equal_var=False).statistic
fig, ax = plt.subplots(figsize=(5.2, 5.2))
ax.scatter(pos[:, 0], pos[:, 1], s=14, c="0.78")
ax.scatter(*pos[ROI_L, :2].T, s=24, c=BLUE, label=f"left posterior region (n={len(ROI_L)})")
ax.scatter(*pos[ROI_R, :2].T, s=24, c=RED, label=f"right posterior region (n={len(ROI_R)})")
ax.scatter(*pos_all[bad_idx, :2].T, s=36, c="k", marker="x", label=f"removed (n={len(bad_idx)})")
ax.set(title="KIT sensors, top view (front up)", xlabel="x (m), right +", ylabel="y (m), front +")
ax.set_aspect("equal"); ax.legend(fontsize=8, loc="upper center")
savefig("fig04_sensors_and_regions")
cue epochs kept per run: {'run-04': '125 of 128', 'run-05': '123 of 128', 'run-06': '122 of 128', 'run-07': '120 of 128', 'run-08': '118 of 128'}
cue epochs kept: 608 of 640 (307 cue left, 301 cue right); stimulus epochs kept: 617 (308 left, 309 right)
194 sensors kept; left posterior region 23 sensors, right posterior region 20
removed sensors that would have been in the left region: 2 | in the right region: 5
6. Positive control 1: the field evoked by the stimulus
Before looking for a small effect, a large and well-known one: a stimulus in the left visual field is processed first by the right occipital cortex, and the reverse. The evoked field (average of the 1-40 Hz epochs, baseline -200 to 0 ms) should therefore show mirror-image patterns over the back of the head for left and right stimuli.
The statistical test compares, across trials, the mean field between 130 and 200 ms after a left and after a right stimulus at every sensor, with a cluster permutation test over neighbouring sensors (2000 permutations).
[7]:
evk = {"left": STIM[s_left].mean(0), "right": STIM[~s_left].mean(0)}
gfp = {k: np.sqrt((v ** 2).mean(0)) for k, v in evk.items()}
search = (stimes >= 0.06) & (stimes <= 0.3)
t_peak = float(stimes[search][(gfp["left"] + gfp["right"])[search].argmax()])
w_evk = (stimes >= 0.13) & (stimes <= 0.20)
X = [STIM[s_left][:, :, w_evk].mean(2).astype(float), STIM[~s_left][:, :, w_evk].mean(2).astype(float)]
T_evk, cl, pv, _ = mne.stats.permutation_cluster_test(X, stat_fun=welch_t, threshold=ss.t.ppf(0.975, len(smeta) - 2), tail=0,
adjacency=adjacency, n_permutations=2000, seed=0, out_type="mask")
sig_evk = np.zeros(len(T_evk), bool)
RES["stimulus_evoked"] = dict(n_left=int(s_left.sum()), n_right=int((~s_left).sum()), peak_s=t_peak,
peak_rms_fT=float(max(gfp["left"][search].max(), gfp["right"][search].max()) * 1e15),
prestimulus_rms_fT=float(gfp["left"][stimes < 0].mean() * 1e15), clusters=[])
for c, p in sorted(zip(cl, pv), key=lambda cp: cp[1]):
if p < 0.05:
sig_evk |= c
RES["stimulus_evoked"]["clusters"].append(dict(p=float(p), n_sensors=int(c.sum()), mean_t=float(T_evk[c].mean()),
mean_x_cm=float(100 * pos[c, 0].mean()), mean_y_cm=float(100 * pos[c, 1].mean())))
print(f"evoked field peaks {1000 * t_peak:.0f} ms after the stimulus: {RES['stimulus_evoked']['peak_rms_fT']:.0f} fT "
f"(RMS over sensors) against {RES['stimulus_evoked']['prestimulus_rms_fT']:.0f} fT before the stimulus")
print("left versus right stimulus, 130-200 ms, clusters with p < 0.05:")
for c in RES["stimulus_evoked"]["clusters"]:
print(f" p = {c['p']:.4f}, {c['n_sensors']} sensors, mean t = {c['mean_t']:+.1f}, centred at x = {c['mean_x_cm']:+.1f} cm, y = {c['mean_y_cm']:+.1f} cm")
fig = plt.figure(figsize=(16, 4))
ax = fig.add_subplot(1, 4, 1)
for k, c in (("left", BLUE), ("right", RED)):
ax.plot(stimes, gfp[k] * 1e15, c=c, label=f"stimulus {k} (n={(s_left if k == 'left' else ~s_left).sum()})")
ax.axvline(0, c="k", lw=0.6); ax.axvspan(0.13, 0.20, color="0.9", zorder=0)
ax.set(title="Evoked field, RMS over sensors", xlabel="Time from stimulus (s)", ylabel="fT"); ax.legend(fontsize=8); ax.grid(alpha=0.3)
maps = [evk[k][:, w_evk].mean(1) * 1e15 for k in ("left", "right")]
vl = np.abs(maps).max()
for j, (m, k) in enumerate(zip(maps, ("left", "right"))):
ax = fig.add_subplot(1, 4, 2 + j)
im, _ = mne.viz.plot_topomap(m, info, axes=ax, show=False, vlim=(-vl, vl), cmap="RdBu_r")
ax.set_title(f"Stimulus {k}\n130-200 ms (fT)", fontsize=10)
fig.colorbar(im, ax=fig.axes[1:3], shrink=0.7)
ax = fig.add_subplot(1, 4, 4)
v = np.abs(T_evk).max()
im, _ = mne.viz.plot_topomap(T_evk, info, axes=ax, show=False, vlim=(-v, v), cmap="RdBu_r", mask=sig_evk,
mask_params=dict(marker="o", markerfacecolor="k", markeredgecolor="k", markersize=3))
ax.set_title("left minus right stimulus, t over trials\n(dots: cluster p < 0.05)"); fig.colorbar(im, ax=ax, shrink=0.7)
savefig("fig05_stimulus_evoked")
evoked field peaks 172 ms after the stimulus: 36 fT (RMS over sensors) against 5 fT before the stimulus
left versus right stimulus, 130-200 ms, clusters with p < 0.05:
p = 0.0005, 58 sensors, mean t = -5.3, centred at x = -1.0 cm, y = -7.8 cm
p = 0.0020, 22 sensors, mean t = +4.3, centred at x = +9.5 cm, y = -1.2 cm
Reading. The control comes out clearly. The evoked field rises from 5 fT before the stimulus to 36 fT (RMS over sensors) at about 170 ms. The maps for left and right stimuli are mirror images of each other over the back of the helmet, and the difference between them forms two clusters of sensors with p = 0.0005 (58 sensors, posterior) and p = 0.002 (22 sensors, right side). The triggers, their pairing with events.tsv and the recording itself are therefore sound, and the left / right
organisation of the visual response is visible at the sensor level.
7. Positive control 2: alpha lateralisation after a lateralised stimulus
The same lateralisation index that is used below for the cue, applied to a situation where the answer is known: a stimulus in one visual field reduces alpha over the contralateral occipital cortex for several hundred milliseconds. After a left stimulus the right hemisphere loses alpha, so LI = (R - L) / (R + L) should be lower than after a right stimulus.
If the sensor regions and the index can show this, they are able to show a lateralisation of alpha in this participant; if they cannot, a null result after the cue would mean little.
One complication: the evoked field of section 6 itself contains energy between 8 and 14 Hz, and it is largest over the contralateral hemisphere, so it adds alpha-band amplitude exactly where the suppression removes it. The index is therefore computed twice: on the total alpha amplitude (as in the rest of the notebook), and on the induced alpha, obtained by subtracting the average response to left (or right) stimuli from every left (or right) trial before taking the envelope. The window is 200 to 600 ms after the stimulus.
[8]:
def li_of(a):
"""(R - L) / (R + L) of the two posterior regions; a = trials x sensors [x times]."""
left, right = a[:, ROI_L].mean(1), a[:, ROI_R].mean(1)
return (right - left) / (right + left)
def compare(x_a, x_b, n_perm=10000):
"""Mean of x_b minus mean of x_a over trials, with Welch t, permutation p and Cohen's d."""
diff = x_b.mean() - x_a.mean()
sp = np.sqrt((x_a.var(ddof=1) + x_b.var(ddof=1)) / 2)
t, p = ss.ttest_ind(x_b, x_a, equal_var=False)
allx, n = np.r_[x_a, x_b], len(x_a)
perm = np.empty(n_perm)
for k in range(n_perm):
z = RNG.permutation(allx)
perm[k] = z[n:].mean() - z[:n].mean()
d = diff / sp
se_d = np.sqrt((len(x_a) + len(x_b)) / (len(x_a) * len(x_b)) + d ** 2 / (2 * (len(x_a) + len(x_b))))
return dict(mean_a=float(x_a.mean()), mean_b=float(x_b.mean()), diff=float(diff), cohen_d=float(d),
d_ci95=[float(d - 1.96 * se_d), float(d + 1.96 * se_d)], t=float(t), p=float(p),
p_perm=float((np.sum(np.abs(perm) >= abs(diff)) + 1) / (n_perm + 1)), n=[int(len(x_a)), int(len(x_b))])
def time_clusters(a, b, t_axis, t_from, t_to):
"""Cluster permutation test along time of two sets of trials x times (b minus a)."""
sel = (t_axis >= t_from) & (t_axis <= t_to)
T, cl, pv, _ = mne.stats.permutation_cluster_test([b[:, sel], a[:, sel]], stat_fun=welch_t,
threshold=ss.t.ppf(0.975, len(a) + len(b) - 2), tail=0,
n_permutations=2000, seed=0, out_type="mask")
return sorted([dict(p=float(p), t_start=float(t_axis[sel][c][0]), t_end=float(t_axis[sel][c][-1]), mean_t=float(T[c].mean()))
for c, p in zip(cl, pv)], key=lambda d: d["p"])
from scipy.signal import hilbert
roi = np.r_[ROI_L, ROI_R]
n_l = len(ROI_L)
def li_roi(a):
"""Lateralisation index of an array restricted to the sensors of the two regions (left region first)."""
left, right = a[:, :n_l].mean(1), a[:, n_l:].mean(1)
return (right - left) / (right + left)
bp = BP_STIM[:, roi].astype(float) # trials x region sensors x times
induced_in = bp.copy()
for m in (s_left, ~s_left):
induced_in[m] -= bp[m].mean(0, keepdims=True) # remove the phase-locked (evoked) part
crop = (etimes >= -0.3) & (etimes <= 1.0) # drop the edges of the Hilbert transform
ct = etimes[crop]
ALPHA_S = {"total": np.abs(hilbert(bp, axis=-1))[:, :, crop], "induced": np.abs(hilbert(induced_in, axis=-1))[:, :, crop]}
del bp, induced_in
w_post = (ct >= 0.2) & (ct <= 0.6)
RES["control_stimulus_alpha"] = {}
for kind, a in ALPHA_S.items():
li_post = li_roi(a[:, :, w_post].mean(2))
c = compare(li_post[s_left], li_post[~s_left]) # right minus left stimulus: predicted > 0
c["time_clusters"] = time_clusters(li_roi(a)[s_left], li_roi(a)[~s_left], ct, 0.0, 1.0)
RES["control_stimulus_alpha"][kind] = c
print(f"{kind} alpha, LI 200-600 ms after the stimulus: left stimulus {c['mean_a']:+.4f}, right stimulus {c['mean_b']:+.4f}, "
f"difference {c['diff']:+.4f} (predicted > 0), d = {c['cohen_d']:+.2f} [{c['d_ci95'][0]:+.2f}, {c['d_ci95'][1]:+.2f}], "
f"t = {c['t']:.2f}, p = {c['p']:.2g}, permutation p = {c['p_perm']:.2g}")
print(" clusters along time:", [f"{k['t_start']:.2f}-{k['t_end']:.2f} s, mean t = {k['mean_t']:+.1f}, p = {k['p']:.3f}" for k in c["time_clusters"][:3]])
fig, axes = plt.subplots(1, 4, figsize=(20, 3.8))
ebase = (ct >= -0.3) & (ct <= -0.05)
a = ALPHA_S["induced"]
for ax, sl, nm in zip(axes[:2], (slice(0, n_l), slice(n_l, None)), ("Left", "Right")):
for m, col, lab in ((s_left, BLUE, "stimulus left"), (~s_left, RED, "stimulus right")):
x = a[m][:, sl].mean((0, 1))
ax.plot(ct, 100 * (x / x[ebase].mean() - 1), c=col, label=lab)
ax.set(xlabel="Time from stimulus (s)", ylabel="% change from before the stimulus")
ax.set_title(f"{nm} posterior sensors:\ninduced alpha amplitude", fontsize=10)
for ax, kind in zip(axes[2:], ("induced", "total")):
lis = li_roi(ALPHA_S[kind])
for m, col, lab in ((s_left, BLUE, "stimulus left"), (~s_left, RED, "stimulus right")):
mu, se = lis[m].mean(0), lis[m].std(0, ddof=1) / np.sqrt(m.sum())
ax.plot(ct, mu, c=col, label=lab); ax.fill_between(ct, mu - se, mu + se, color=col, alpha=0.22, lw=0)
for k in RES["control_stimulus_alpha"][kind]["time_clusters"]:
if k["p"] < 0.05: ax.axvspan(k["t_start"], k["t_end"], color="gold", alpha=0.4, zorder=0)
ax.set(xlabel="Time from stimulus (s)")
ax.set_title(f"Lateralisation index, {kind} alpha (mean +- s.e.m.)\nprediction: right stimulus above left stimulus", fontsize=10)
for ax in axes: ax.axvline(0, c="k", lw=0.6); ax.legend(fontsize=8); ax.grid(alpha=0.3)
del ALPHA_S
savefig("fig06_control_alpha_after_stimulus")
total alpha, LI 200-600 ms after the stimulus: left stimulus +0.0285, right stimulus +0.0307, difference +0.0022 (predicted > 0), d = +0.03 [-0.13, +0.18], t = 0.33, p = 0.74, permutation p = 0.74
clusters along time: ['0.23-0.24 s, mean t = +2.0, p = 0.603']
induced alpha, LI 200-600 ms after the stimulus: left stimulus +0.0280, right stimulus +0.0310, difference +0.0031 (predicted > 0), d = +0.04 [-0.12, +0.20], t = 0.46, p = 0.64, permutation p = 0.65
clusters along time: ['0.21-0.25 s, mean t = +2.2, p = 0.345']
Reading. This control does not come out. After the stimulus the alpha amplitude drops by about 4 to 9% in both regions, whichever side the stimulus was on, and the lateralisation index does not separate left from right stimuli: d = +0.03 (p = 0.74) for the total alpha and d = +0.04 (p = 0.64) for the induced alpha, with no cluster along time.
So, in this recording, the region-based index has not been shown to detect a lateralised change of alpha even in the textbook situation. Likely reasons: the stimuli are small (1.2 degrees) and brief (83 ms), so the suppression they cause is weak and largely bilateral; axial gradiometers mix the two hemispheres more than EEG electrodes or planar gradiometers; and five sensors of the right region were lost during the session.
The consequence for section 9 is important: a weak or absent effect of the cue on this index cannot be read as evidence against the effect of the paper, because the measure has not proven its sensitivity here.
8. Exploratory: does the cue change the field evoked by the stimulus?
Not an analysis of the paper, but the classical consequence of spatial attention: the same stimulus evokes a different response when its location is attended. The evoked fields of stimuli at the cued and at the uncued square are compared, separately for left and right stimuli. Only stimuli that do not have the target identity and received no button press are used, so that neither condition contains a motor response.
Test: spatio-temporal cluster permutation test over sensors and time (0 to 400 ms, 1000 permutations). With about a hundred trials per condition this test has little power; it is reported whatever the outcome.
[9]:
nontarget = ((smeta.stimulus_identity != smeta.target_identity) & (smeta.outcome != "false_alarm")).to_numpy()
cued = (smeta.location_cued == 1).to_numpy()
t_sel = np.flatnonzero((stimes >= 0.0) & (stimes <= 0.4))[::2] # 125 Hz
RES["attention_on_evoked"] = {}
fig, axes = plt.subplots(1, 4, figsize=(17, 3.8), gridspec_kw=dict(width_ratios=[1.5, 1, 1.5, 1]))
for j, (side, m_side) in enumerate((("left", s_left), ("right", ~s_left))):
a, b = m_side & nontarget & cued, m_side & nontarget & ~cued
X = [np.transpose(STIM[a][:, :, t_sel], (0, 2, 1)).astype(float), np.transpose(STIM[b][:, :, t_sel], (0, 2, 1)).astype(float)]
T, cl, pv, _ = mne.stats.spatio_temporal_cluster_test(X, stat_fun=welch_t, threshold=ss.t.ppf(0.975, a.sum() + b.sum() - 2), tail=0,
adjacency=adjacency, n_permutations=1000, seed=0, out_type="mask")
found = sorted([dict(p=float(p), t_start=float(stimes[t_sel][c.any(1)][0]), t_end=float(stimes[t_sel][c.any(1)][-1]),
n_sensors=int(c.any(0).sum()), mean_t=float(T[c].mean())) for c, p in zip(cl, pv)], key=lambda d: d["p"])
RES["attention_on_evoked"][f"stimulus_{side}"] = dict(n_cued=int(a.sum()), n_uncued=int(b.sum()), clusters=found[:5])
print(f"stimulus {side}: {a.sum()} cued, {b.sum()} uncued non-target trials; smallest cluster p values: "
+ (", ".join(f"p = {k['p']:.3f} ({k['t_start']:.2f}-{k['t_end']:.2f} s, {k['n_sensors']} sensors)" for k in found[:3]) or "no cluster"))
ea, eb = STIM[a].mean(0), STIM[b].mean(0)
ax = axes[2 * j]
ax.plot(stimes, np.sqrt((ea ** 2).mean(0)) * 1e15, c=BLUE, label=f"cued (n={a.sum()})")
ax.plot(stimes, np.sqrt((eb ** 2).mean(0)) * 1e15, c=RED, label=f"uncued (n={b.sum()})")
for k in found:
if k["p"] < 0.05: ax.axvspan(k["t_start"], k["t_end"], color="gold", alpha=0.35, zorder=0)
ax.axvline(0, c="k", lw=0.6); ax.legend(fontsize=8); ax.grid(alpha=0.3)
ax.set(title=f"Stimulus {side}: evoked field, RMS over sensors", xlabel="Time from stimulus (s)", ylabel="fT")
wd = (stimes >= 0.13) & (stimes <= 0.20)
dmap = (ea - eb)[:, wd].mean(1) * 1e15
v = np.abs(dmap).max()
im, _ = mne.viz.plot_topomap(dmap, info, axes=axes[2 * j + 1], show=False, vlim=(-v, v), cmap="RdBu_r")
axes[2 * j + 1].set_title("cued minus uncued,\n130-200 ms (fT)"); fig.colorbar(im, ax=axes[2 * j + 1], shrink=0.7)
savefig("fig07_attention_on_evoked_field")
stimulus left: 104 cued, 100 uncued non-target trials; smallest cluster p values: p = 0.317 (0.30-0.34 s, 29 sensors), p = 0.349 (0.22-0.27 s, 14 sensors), p = 0.349 (0.22-0.29 s, 27 sensors)
stimulus right: 101 cued, 105 uncued non-target trials; smallest cluster p values: p = 0.489 (0.30-0.34 s, 18 sensors), p = 0.495 (0.37-0.40 s, 21 sensors), p = 0.794 (0.27-0.30 s, 13 sensors)
Reading. No difference between cued and uncued stimuli passes the test (smallest cluster p = 0.32 for left stimuli and 0.49 for right stimuli). With about a hundred trials per condition this is inconclusive rather than negative.
9. The analysis of the paper: alpha after the cue
9.1 Alpha amplitude over time in each hemisphere
Alpha amplitude (the 8-14 Hz envelope) averaged over the trials and over the sensors of each posterior region, for the two cue directions, as a percent change from the 300 ms before the cue. The grey band is the analysis window (the 250 ms before the stimulus); the dashed line is the stimulus.
What the paper predicts: in the left region the cue left curve lies above the cue right curve before the stimulus, and the reverse in the right region.
The third panel is the lateralisation index of every trial, averaged (with its standard error) per cue direction: the prediction is cue right above cue left. A cluster permutation test along time (0 to 1.025 s, 2000 permutations) marks in yellow the stretches where the two conditions differ.
[10]:
A = ENV["alpha"][:, :, win].mean(2).astype(float) # trials x sensors: mean alpha amplitude in the window
LI = li_of(A) # one value per trial
LIt = li_of(ENV["alpha"].astype(float)) # trials x times
main = compare(LI[is_left], LI[~is_left]) # cue right minus cue left: predicted > 0
main["time_clusters"] = time_clusters(LIt[is_left], LIt[~is_left], times, 0.0, 1.025)
RES["alpha_cue"] = main
for nm, roi in (("left", ROI_L), ("right", ROI_R)):
a = A[:, roi].mean(1)
t, p = ss.ttest_ind(np.log(a[is_left]), np.log(a[~is_left]), equal_var=False)
RES["alpha_cue"][f"{nm}_region_cue_left_minus_right_pct"] = float(100 * (a[is_left].mean() - a[~is_left].mean()) / a.mean())
RES["alpha_cue"][f"{nm}_region_t_p"] = [float(t), float(p)]
print(f"LI in the window: cue left {main['mean_a']:+.4f}, cue right {main['mean_b']:+.4f}, difference {main['diff']:+.4f} (predicted > 0)")
print(f" Cohen's d = {main['cohen_d']:+.3f}, 95% interval [{main['d_ci95'][0]:+.2f}, {main['d_ci95'][1]:+.2f}], "
f"Welch t = {main['t']:.2f}, p = {main['p']:.3f}, permutation p = {main['p_perm']:.3f}")
print(f" left region: cue left minus cue right = {main['left_region_cue_left_minus_right_pct']:+.2f} % (predicted > 0), p = {main['left_region_t_p'][1]:.2f}")
print(f" right region: cue left minus cue right = {main['right_region_cue_left_minus_right_pct']:+.2f} % (predicted < 0), p = {main['right_region_t_p'][1]:.2f}")
print("clusters along time (cue right minus cue left):",
[f"{k['t_start']:.2f}-{k['t_end']:.2f} s, mean t = {k['mean_t']:+.1f}, p = {k['p']:.3f}" for k in main["time_clusters"][:4]])
fig, axes = plt.subplots(1, 3, figsize=(16, 4))
e = ENV["alpha"].astype(float)
for ax, roi, nm in zip(axes[:2], (ROI_L, ROI_R), ("Left", "Right")):
for m, col, lab in ((is_left, BLUE, "cue left"), (~is_left, RED, "cue right")):
x = e[m][:, roi].mean((0, 1))
ax.plot(times, 100 * (x / x[base].mean() - 1), c=col, label=lab)
ax.set(title=f"{nm} posterior sensors: alpha amplitude", xlabel="Time from cue (s)", ylabel="% change from before the cue")
for m, col, lab in ((is_left, BLUE, "cue left"), (~is_left, RED, "cue right")):
mu, se = LIt[m].mean(0), LIt[m].std(0, ddof=1) / np.sqrt(m.sum())
axes[2].plot(times, mu, c=col, label=lab); axes[2].fill_between(times, mu - se, mu + se, color=col, alpha=0.22, lw=0)
for k in main["time_clusters"]:
if k["p"] < 0.05: axes[2].axvspan(k["t_start"], k["t_end"], color="gold", alpha=0.45, zorder=0)
axes[2].set(title="Lateralisation index (R - L) / (R + L), mean +- s.e.m.\nprediction: cue right above cue left (yellow: cluster p < 0.05)", xlabel="Time from cue (s)")
for ax in axes:
ax.axvline(0, c="k", lw=0.6); ax.axvline(1.03, c="k", lw=0.6, ls="--"); ax.axvspan(*WIN, color="0.9", zorder=0)
ax.legend(fontsize=8); ax.grid(alpha=0.3)
fig.suptitle(f"sub-{SUB}: alpha (8-14 Hz) after the cue, {is_left.sum()} cue-left and {(~is_left).sum()} cue-right trials", y=1.02)
savefig("fig08_alpha_after_cue")
LI in the window: cue left +0.0337, cue right +0.0450, difference +0.0114 (predicted > 0)
Cohen's d = +0.111, 95% interval [-0.05, +0.27], Welch t = 1.37, p = 0.171, permutation p = 0.171
left region: cue left minus cue right = +1.94 % (predicted > 0), p = 0.21
right region: cue left minus cue right = -0.50 % (predicted < 0), p = 0.90
clusters along time (cue right minus cue left): ['0.70-0.80 s, mean t = +2.5, p = 0.040', '0.44-0.48 s, mean t = +2.1, p = 0.361', '0.17-0.18 s, mean t = -2.0, p = 0.599']
Reading. In the planned window the lateralisation index is +0.034 after a cue to the left and +0.045 after a cue to the right. The difference, +0.011, has the sign predicted by the paper but is small and not significant: d = +0.11 (95% interval -0.05 to +0.27), p = 0.17.
Taken region by region, the pattern is also the paper’s but weak: over the left region alpha is 1.9% higher after a cue to the left (p = 0.21); over the right region it is 0.5% lower (p = 0.90).
The time course of the index gives the one significant result of the cue analysis: the two cue directions separate from about 550 ms after the cue, and the stretch from 700 to 800 ms passes the cluster test (p = 0.04, cue right above cue left). That is just before the planned window, in the second half of the cue-to-stimulus interval, where the paper reports its effect. It is a single cluster at p = 0.04 in one participant, so it is an encouraging observation and not a replication.
Note also that alpha in both regions rises by a few percent towards the end of the interval for both cue directions: a general preparation for the stimulus, on which the lateralisation rides.
9.2 Where on the helmet?
For every sensor, the modulation index (cue left - cue right) / (cue left + cue right) of the mean alpha amplitude in the window (top row), and the t-value of the same contrast over trials (bottom row). For the t-maps every trial is first divided by its mean over sensors (on a log scale), which removes changes of alpha that affect the whole head. Cluster permutation test over neighbouring sensors, 2000 permutations.
What the paper predicts: more alpha (red) over the left posterior sensors and less (blue) over the right ones. The paper also found that the focus of the effect moves with the visual field of the squares (upper or lower), which is why the two fields are shown separately.
[11]:
def topo_test(mask):
a, left = A[mask], is_left[mask]
mi = (a[left].mean(0) - a[~left].mean(0)) / (a[left].mean(0) + a[~left].mean(0))
x = np.log(a) - np.log(a).mean(1, keepdims=True)
T, clusters, pv, _ = mne.stats.permutation_cluster_test([x[left], x[~left]], stat_fun=welch_t,
threshold=ss.t.ppf(0.975, mask.sum() - 2), tail=0,
adjacency=adjacency, n_permutations=2000, seed=0, out_type="mask")
sig = np.zeros(len(T), bool)
found = []
for c, p in zip(clusters, pv):
found.append(dict(p=float(p), n_sensors=int(c.sum()), mean_t=float(T[c].mean()),
mean_x_cm=float(100 * pos[c, 0].mean()), mean_y_cm=float(100 * pos[c, 1].mean())))
if p < 0.05: sig |= c
return mi, T, sig, sorted(found, key=lambda d: d["p"])[:4]
TOPO = {"all trials": topo_test(np.ones(len(meta), bool)),
"upper field": topo_test((meta.visual_field == "upper").to_numpy()),
"lower field": topo_test((meta.visual_field == "lower").to_numpy())}
RES["alpha_cue"]["topography_clusters"] = {k: v[3] for k, v in TOPO.items()}
for k, v in TOPO.items():
print(f"{k}: smallest cluster p = " + (f"{v[3][0]['p']:.3f} ({v[3][0]['n_sensors']} sensors)" if v[3] else "no cluster above threshold")
+ f"; mean modulation left region {100 * v[0][ROI_L].mean():+.2f} %, right region {100 * v[0][ROI_R].mean():+.2f} %")
RES["alpha_cue"].setdefault("modulation_pct", {})[k] = dict(left_region=float(100 * v[0][ROI_L].mean()), right_region=float(100 * v[0][ROI_R].mean()))
fig, axes = plt.subplots(2, 3, figsize=(12, 7.6))
for j, (k, (mi, T, sig, found)) in enumerate(TOPO.items()):
v = np.abs(mi).max()
im, _ = mne.viz.plot_topomap(100 * mi, info, axes=axes[0, j], show=False, vlim=(-100 * v, 100 * v), cmap="RdBu_r")
axes[0, j].set_title(f"{k}\n(cue L - cue R) / (cue L + cue R), %", fontsize=10); fig.colorbar(im, ax=axes[0, j], shrink=0.65)
v = max(np.abs(T).max(), 3)
im, _ = mne.viz.plot_topomap(T, info, axes=axes[1, j], show=False, vlim=(-v, v), cmap="RdBu_r", mask=sig,
mask_params=dict(marker="o", markerfacecolor="k", markeredgecolor="k", markersize=4))
best = f"smallest cluster p = {found[0]['p']:.2f}" if found else "no cluster above threshold"
axes[1, j].set_title(f"t over trials; {best}", fontsize=10); fig.colorbar(im, ax=axes[1, j], shrink=0.65)
fig.suptitle(f"sub-{SUB}: alpha amplitude {int(1000 * WIN[0])}-{int(1000 * WIN[1])} ms after the cue, cue left minus cue right", y=0.98)
savefig("fig09_alpha_topography")
all trials: smallest cluster p = 0.278 (2 sensors); mean modulation left region +0.83 %, right region -0.38 %
upper field: smallest cluster p = 0.578 (1 sensors); mean modulation left region +1.60 %, right region -0.05 %
lower field: smallest cluster p = 0.312 (2 sensors); mean modulation left region +0.02 %, right region -0.72 %
Reading. No cluster of sensors passes the test (smallest p = 0.28 for all trials). The average modulation has the predicted signs (left region +0.8%, right region -0.4%), and the upper-field map shows the expected picture most clearly (left posterior sensors red, right posterior sensors blue; left region +1.6%), while the lower-field map does not. The paper’s finding that the focus moves with the visual field can therefore neither be confirmed nor contradicted with these data.
9.3 Is the effect consistent, and is it specific to alpha?
The same comparison (LI after a cue to the right minus LI after a cue to the left, as Cohen’s d with its 95% interval) within each visual field, each task and each run, and for the theta and beta bands. A real effect of attention on alpha should have the same sign in the subsets and should not appear in the neighbouring bands; an artefact of eye movements or of slow drifts would not be confined to 8-14 Hz.
[12]:
subsets = {}
for name, col in (("field", "visual_field"), ("task", "task"), ("run", "run")):
for level in sorted(meta[col].unique()):
m = (meta[col] == level).to_numpy()
subsets[f"{name}: {level}"] = compare(LI[m & is_left], LI[m & ~is_left], n_perm=5000)
by_band = {b: compare(*(lambda x: (x[is_left], x[~is_left]))(li_of(ENV[b][:, :, win].mean(2).astype(float)))) for b in BANDS}
RES["alpha_cue"]["subsets"], RES["by_band"] = subsets, by_band
summary = pd.DataFrame([dict(subset=k, n_left=v["n"][0], n_right=v["n"][1], LI_cue_left=round(v["mean_a"], 4), LI_cue_right=round(v["mean_b"], 4),
d=round(v["cohen_d"], 3), p=round(v["p"], 3)) for k, v in [("all trials", main)] + list(subsets.items())]).set_index("subset")
print(summary.to_string())
print("\nby band:", {b: f"d = {v['cohen_d']:+.3f}, p = {v['p']:.2f}" for b, v in by_band.items()})
n_same = sum(v["cohen_d"] > 0 for k, v in subsets.items() if k.startswith("run"))
print(f"runs with the sign of the paper: {n_same} of {len(RUNS)}")
fig, axes = plt.subplots(1, 2, figsize=(13, 4.2), gridspec_kw=dict(width_ratios=[2.4, 1]))
names, vals = ["all trials"] + list(subsets), [main] + list(subsets.values())
d = np.array([v["cohen_d"] for v in vals])
lo = d - np.array([v["d_ci95"][0] for v in vals]); hi = np.array([v["d_ci95"][1] for v in vals]) - d
axes[0].bar(range(len(d)), d, yerr=[lo, hi], color=["0.25"] + ["#7aa6d8"] * (len(d) - 1), capsize=3)
axes[0].set_xticks(range(len(d))); axes[0].set_xticklabels([n.replace(": ", "\n") for n in names], fontsize=8)
axes[0].axhline(0, c="k", lw=0.6)
axes[0].set(title="Alpha lateralisation, cue right minus cue left (Cohen's d, 95% interval)\npositive = direction of the paper", ylabel="d")
bd = [by_band[b]["cohen_d"] for b in BANDS]
be = [[by_band[b]["cohen_d"] - by_band[b]["d_ci95"][0] for b in BANDS], [by_band[b]["d_ci95"][1] - by_band[b]["cohen_d"] for b in BANDS]]
axes[1].bar([f"{b}\n{lo_}-{hi_} Hz" for b, (lo_, hi_) in BANDS.items()], bd, yerr=be, color=["0.65", "0.25", "0.65"], capsize=3)
axes[1].axhline(0, c="k", lw=0.6); axes[1].set(title="Same comparison by frequency band", ylabel="d")
savefig("fig10_effect_sizes")
n_left n_right LI_cue_left LI_cue_right d p
subset
all trials 307 301 0.0337 0.0450 0.111 0.171
field: lower 154 154 0.0418 0.0490 0.069 0.548
field: upper 153 147 0.0254 0.0409 0.155 0.181
task: motion 156 156 0.0335 0.0460 0.122 0.284
task: orientation 151 145 0.0338 0.0440 0.099 0.393
run: 4 62 63 0.0216 0.0387 0.186 0.302
run: 5 61 62 0.0422 0.0600 0.166 0.358
run: 6 64 58 0.0357 0.0450 0.086 0.633
run: 7 61 59 0.0320 0.0491 0.163 0.372
run: 8 59 59 0.0370 0.0321 -0.048 0.794
by band: {'theta': 'd = -0.072, p = 0.37', 'alpha': 'd = +0.111, p = 0.17', 'beta': 'd = -0.011, p = 0.90'}
runs with the sign of the paper: 4 of 5
Reading. The effect has the sign of the paper in both visual fields, in both tasks and in four of the five runs (all but run-08, the run with the most sensors lost), and it is absent in the neighbouring bands (theta d = -0.07, beta d = -0.01). That consistency and the specificity to alpha are what one expects from a real effect. But every interval includes zero: none of these comparisons is significant on its own.
9.4 Time-frequency view
The envelope analysis fixes the band in advance. Here the power of every trial is computed with Morlet wavelets from 4 to 30 Hz (number of cycles = frequency / 2) on the sensors of the two regions, the lateralisation index of the power is formed per trial at every time and frequency, and the two cue directions are compared (t over trials). Red means cue right above cue left, the direction of the paper. A cluster permutation test over the time-frequency plane (0 to 1.025 s, 500 permutations) outlines the clusters with p < 0.05, if any.
[13]:
freqs = np.arange(4.0, 31.0, 1.0)
roi = np.r_[ROI_L, ROI_R]
ep = mne.EpochsArray(CUE[:, roi].astype(float), mne.pick_info(info, roi), tmin=TMIN)
P = ep.compute_tfr("morlet", freqs=freqs, n_cycles=freqs / 2, decim=5, average=False).data.astype(np.float32) # trials x sensors x freqs x times
tf_times = times[::5]
PL, PR = P[:, :len(ROI_L)].mean(1), P[:, len(ROI_L):].mean(1)
LIf = ((PR - PL) / (PR + PL)).astype(float) # trials x freqs x times
del P, PL, PR
T_tf = ss.ttest_ind(LIf[~is_left], LIf[is_left], equal_var=False).statistic
tsel = (tf_times >= 0.0) & (tf_times <= 1.025)
Tc, cl, pv, _ = mne.stats.permutation_cluster_test([LIf[~is_left][:, :, tsel], LIf[is_left][:, :, tsel]], stat_fun=welch_t,
threshold=ss.t.ppf(0.975, len(meta) - 2), tail=0, n_permutations=500, seed=0, out_type="mask")
tf_found = sorted([dict(p=float(p), f_min=float(freqs[c.any(1)][0]), f_max=float(freqs[c.any(1)][-1]),
t_start=float(tf_times[tsel][c.any(0)][0]), t_end=float(tf_times[tsel][c.any(0)][-1]), mean_t=float(Tc[c].mean()))
for c, p in zip(cl, pv)], key=lambda d: d["p"])
RES["alpha_cue"]["time_frequency_clusters"] = tf_found[:5]
print("time-frequency clusters, smallest p first:")
for k in tf_found[:5]:
print(f" p = {k['p']:.3f}: {k['f_min']:.0f}-{k['f_max']:.0f} Hz, {k['t_start']:.2f}-{k['t_end']:.2f} s, mean t = {k['mean_t']:+.1f}")
fig, ax = plt.subplots(figsize=(9, 4))
show = (tf_times >= -0.3) & (tf_times <= 1.2)
im = ax.pcolormesh(tf_times[show], freqs, T_tf[:, show], cmap="RdBu_r", vmin=-3.5, vmax=3.5, shading="nearest")
sig = np.zeros(T_tf.shape, bool)
for c, p in zip(cl, pv):
if p < 0.05: sig[:, np.flatnonzero(tsel)] |= c
if sig.any(): ax.contour(tf_times[show], freqs, sig[:, show].astype(float), levels=[0.5], colors="k", linewidths=1.5)
ax.axvline(0, c="k", lw=0.6); ax.axvline(1.03, c="k", lw=0.6, ls="--")
ax.axhline(8, c="0.4", lw=0.6, ls=":"); ax.axhline(14, c="0.4", lw=0.6, ls=":")
ax.set(xlabel="Time from cue (s)", ylabel="Frequency (Hz)", title="Lateralisation index of power, cue right minus cue left (t over trials)")
fig.colorbar(im, ax=ax, label="t")
savefig("fig11_time_frequency_lateralisation")
del LIf
time-frequency clusters, smallest p first:
p = 0.138: 11-15 Hz, 0.68-0.84 s, mean t = +2.6
p = 0.464: 27-29 Hz, 0.30-0.48 s, mean t = +2.2
p = 0.636: 5-8 Hz, 0.56-0.66 s, mean t = +2.3
p = 0.858: 28-29 Hz, 0.12-0.18 s, mean t = +2.1
p = 0.862: 9-11 Hz, 0.44-0.48 s, mean t = +2.1
Reading. The map has one focus that stands out: 11 to 15 Hz, 0.68 to 0.84 s after the cue, in the direction of the paper (t up to about 3.5). It lies in the upper part of the alpha band, at the same latency as the cluster of section 9.1. Corrected over the whole time-frequency plane it does not pass the test (cluster p = 0.14): the plane contains many more comparisons than the single time course of the 8-14 Hz index.
10. How much does the result depend on the analysis choices?
The window and the regions were fixed before looking at the contrast, but a result that only appears for one choice would not be worth much. The table repeats the main comparison for three analysis windows and three definitions of “posterior” (how far back the regions start). The last window, 700-800 ms, is the stretch that the time course of section 9.1 singled out: it is chosen after seeing the data, so its p-value is optimistic and is shown only for comparison.
[14]:
rows = []
for y_max in (-0.04, -0.06, -0.08):
rl = np.flatnonzero((pos[:, 1] < y_max) & (pos[:, 0] < -0.02)); rr = np.flatnonzero((pos[:, 1] < y_max) & (pos[:, 0] > 0.02))
for w in ((0.5, 1.025), WIN, (0.7, 0.8)):
ws = (times >= w[0]) & (times <= w[1])
a = ENV["alpha"][:, :, ws].mean(2).astype(float)
li = (a[:, rr].mean(1) - a[:, rl].mean(1)) / (a[:, rr].mean(1) + a[:, rl].mean(1))
t, p = ss.ttest_ind(li[~is_left], li[is_left], equal_var=False)
dd = (li[~is_left].mean() - li[is_left].mean()) / np.sqrt((li[is_left].var(ddof=1) + li[~is_left].var(ddof=1)) / 2)
rows.append({"regions start at": f"y < {100 * y_max:.0f} cm ({len(rl)} + {len(rr)} sensors)",
"window (ms)": f"{int(1000 * w[0])}-{int(1000 * w[1])}" + (" (post hoc)" if w == (0.7, 0.8) else " (main)" if w == WIN else ""),
"d": round(float(dd), 3), "t": round(float(t), 2), "p": round(float(p), 3)})
robust = pd.DataFrame(rows)
RES["robustness"] = robust.to_dict("records")
print(robust.to_string(index=False))
print(f"\nsign of the paper in {int((robust.d > 0).sum())} of {len(robust)} combinations")
regions start at window (ms) d t p
y < -4 cm (31 + 26 sensors) 500-1025 0.147 1.81 0.071
y < -4 cm (31 + 26 sensors) 775-1025 (main) 0.119 1.47 0.142
y < -4 cm (31 + 26 sensors) 700-800 (post hoc) 0.233 2.87 0.004
y < -6 cm (23 + 20 sensors) 500-1025 0.149 1.84 0.067
y < -6 cm (23 + 20 sensors) 775-1025 (main) 0.111 1.37 0.171
y < -6 cm (23 + 20 sensors) 700-800 (post hoc) 0.236 2.91 0.004
y < -8 cm (17 + 16 sensors) 500-1025 0.134 1.65 0.100
y < -8 cm (17 + 16 sensors) 775-1025 (main) 0.098 1.20 0.229
y < -8 cm (17 + 16 sensors) 700-800 (post hoc) 0.222 2.74 0.006
sign of the paper in 9 of 9 combinations
Reading. The sign is the paper’s in all nine combinations, and the size of the effect barely depends on where the regions start. A longer window (500-1025 ms) gives d = 0.13 to 0.15 with p = 0.07 to 0.10; the planned window gives d = 0.10 to 0.12 with p = 0.14 to 0.23. The 700-800 ms window gives d = 0.22 to 0.24 (p = 0.004 to 0.006), but that window was chosen after looking at the data, so these p-values overstate the evidence; the honest figure for that stretch is the cluster-corrected p = 0.04 of section 9.1.
11. How many trials would a conclusive test need?
Taking the measured effect size at face value, the number of trials per cue direction needed to detect it with 80% power at a two-sided 5% level (two-sample comparison) is n = 2 (1.96 + 0.84)^2 / d^2. The interval of d is wide, so the same is computed for its upper end.
[15]:
def n_needed(d):
return int(np.ceil(2 * (1.96 + 0.84) ** 2 / d ** 2)) if d > 0 else None
d_hat, d_hi = main["cohen_d"], main["d_ci95"][1]
RES["power"] = dict(d=d_hat, trials_per_cue_direction=n_needed(d_hat), runs_of_128_trials=None if n_needed(d_hat) is None else int(np.ceil(2 * n_needed(d_hat) / 128)),
trials_per_cue_direction_if_d_at_upper_bound=n_needed(d_hi))
print(f"measured d = {d_hat:+.3f}: {RES['power']['trials_per_cue_direction']} trials per cue direction, "
f"about {RES['power']['runs_of_128_trials']} runs of 128 trials (this session: 5 runs, {len(meta)} trials kept)")
print(f"if the true effect were at the upper end of the interval (d = {d_hi:+.2f}): {RES['power']['trials_per_cue_direction_if_d_at_upper_bound']} trials per cue direction")
json.dump(RES, open(OUT / "results.json", "w"), indent=1, default=str)
print("results written to", portable(OUT / "results.json"))
measured d = +0.111: 1271 trials per cue direction, about 20 runs of 128 trials (this session: 5 runs, 608 trials kept)
if the true effect were at the upper end of the interval (d = +0.27): 215 trials per cue direction
results written to $MEG_DATA/attention-task-worden/derivatives/mne_attention_worden_sensor/results.json
Reading. If the true effect has the measured size (d = 0.11), a single participant needs about 1270 trials per cue direction, some 20 runs, for a conclusive test; this session has 300. If the true effect were at the upper end of the interval (d = 0.27), about 215 trials per cue direction would be enough, which this session already has; the truth probably lies in between. A group of participants is the realistic way forward: the paper’s result is a group result.
Results for sub-0955 (session of 2026-11-16)
Significant results
The participant used the cue. Responses to the target identity: 68% at the cued square, 7% at the uncued square (Fisher exact p = 7 x 10^-19); no response at the uncued square from the third run on.
The stimulus evokes the expected lateralised field. Mirror-image posterior maps for left and right stimuli around 170 ms; left versus right stimulus: sensor clusters with p = 0.0005 and p = 0.002.
Alpha lateralisation after the cue, 700-800 ms. The lateralisation index is higher after a cue to the right than after a cue to the left in this stretch (cluster test along time, p = 0.04), the direction and the part of the interval reported by Worden et al. (2000).
Results in the direction of the paper that are not significant
Planned window (250 ms before the stimulus): d = +0.11, 95% interval -0.05 to +0.27, p = 0.17.
Same sign in both visual fields, both tasks, four of five runs and all nine combinations of window and region; nothing in theta or beta.
Time-frequency focus at 11-15 Hz, 0.68-0.84 s (cluster p = 0.14).
No significant cluster of sensors; the expected left / right picture is visible for the upper visual field only.
Results that limit the conclusions
The lateralisation index failed its positive control. It does not separate left from right stimuli after the stimulus (d = +0.04, p = 0.64), although a lateralised stimulus is known to suppress contralateral alpha. The index, as built here from axial gradiometers, is not a proven detector of alpha lateralisation in this recording, so the weak cue effect cannot be held against the paper.
Thirteen sensors went flat during the session, seven of them in the posterior regions (two left, five right), each loss following a burst of noise (one per run from
run-05on). They were removed from all runs.The cue-to-stimulus interval was 123 instead of 124 video frames in 45% of the trials (1025 instead of 1034 ms): the stimulus computer’s flip time stamps were off by a fraction of a frame. Small for this analysis, but the same uncertainty applies to the 33 ms cue.
No eye tracking and no EOG: small gaze shifts towards the cued side cannot be excluded. The confinement of the effect to 8-14 Hz speaks against an eye-movement artefact, but does not rule it out.
No CALM noise reduction and no ICA were applied.
Conclusion. With one participant the replication is neither achieved nor refuted. The behaviour shows that attention followed the cue, the recording shows the expected sensory responses, and the alpha lateralisation after the cue points in the direction of the paper with one stretch (700-800 ms) that is significant; but the main planned comparison is not, and the measure itself did not pass its positive control.
What would make the test conclusive
More data: a group of participants, or about four times as many trials in this one.
A measure that separates the hemispheres better than a left / right split of axial gradiometers: source-space alpha in the left and right occipital cortex (the
.mrkmarkers, the head shape and the T1 of this participant are in the dataset, so stages 10 to 15 of the KIT general pipeline can provide it), and a rerun of the positive control of section 7 there.Eye tracking, to reject trials with gaze shifts.
A stable sensor array: find out what causes the bursts after which sensors stay flat.
Frame-counted timing in the experiment, so that every interval is exact.
CALM and ICA before the analysis (stages 0, 5 and 6 of the pipeline); the script can then be pointed at the cleaned recordings.