OSCR

A reproducible EEG hyperscanning dataset for triadic social decision-making during an iterated 3-player Prisoner's Dilemma.

Code ↔ Paper

6 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

4 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 6 matches
  1. [1] § Experimental Design, Materials and Methods › Technical validation › Inter brain synchrony ↔ pd_eeg_analysis/ibs_analysis.py, lines 1 to 57 · score 0.94 · Inter brain synchrony, 14–25 Hz, 30–45 Hz, 8–12 Hz, 0–2000 ms, 4–7 Hz · block oscr:b:4W8Z3ZT78EMQ7-C · Report a mismatch
  2. [2] § Experimental Design, Materials and Methods › Technical validation › Preprocessing ↔ pd_eeg_analysis/preprocess.py, lines 1 to 52 · score 0.91 · 1–100 Hz, ICLabel, eye blink, preprocessing pipeline, Task EEG, notch · block oscr:b:16PWK170ERDKB-B · Report a mismatch
  3. [3] § Experimental Design, Materials and Methods › Technical validation › Inter brain synchrony ↔ pd_eeg_analysis/ibs_analysis.py, lines 1 to 57 · score 0.83 · window matched, S1 S2, S1 S3, S2 S3, overlapping, onset · block oscr:b:4W8Z3ZT78EMQ7-C · Report a mismatch
  4. [4] § Experimental Design, Materials and Methods › Technical validation › Preprocessing ↔ pd_eeg_analysis/ibs_analysis.py, lines 200 to 233 · score 0.61 · 1–45 Hz, resting IBS, cross, overlapping, filtering, window · block oscr:b:RND67FWJJY79Z-6 · Report a mismatch
  5. [5] § Experimental Design, Materials and Methods › Behavioral validation: computation of behavioral indices ↔ pd_eeg_analysis/ibs_analysis.py, lines 89 to 91 · score 0.59 · S1 S2, S1 S3, S2 S3 · block oscr:b:VYJTDE76S2QHS-4 · Report a mismatch
  6. [6] § Experimental Design, Materials and Methods › Technical validation › Behavioral validation: computation of behavioral indices ↔ pd_eeg_analysis/ibs_analysis.py, lines 89 to 91 · score 0.59 · S1 S2, S1 S3, S2 S3 · block oscr:b:VYJTDE76S2QHS-4 · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 531 lines · 24 KB · no license · 5 matches

  1. """
  2. ibs_analysis.py
  3. ===============
  4. Inter-Brain Synchrony (IBS) analysis for three-person hyperscanning EEG.
  5. Requires cleaned_eeg.pkl produced by preprocess.py.
  6. Analysis
  7. --------
  8. - Metrics : PLV, Coherence (ccorr) via HyPyP
  9. - Windows : 0–1000 ms, 0–2000 ms post-stimulus onset
  10. - Tasks : decision, feedback
  11. - Pairs : all 3 dyads within each trio (S1-S2, S1-S3, S2-S3)
  12. - Condition: Cooperative (both chose cooperate) vs. Other
  13. - Resting : non-overlapping windows matched to task window length (baseline)
  14. - Stats : cluster-permutation test (HyPyP, 2000 permutations, two-tailed)
  15. Frequency bands
  16. ---------------
  17. delta 1–3 Hz
  18. theta 4–7 Hz
  19. alpha 8–12 Hz
  20. beta 14–25 Hz
  21. gamma 30–45 Hz
  22. Output
  23. ------
  24. results/
  25. ibs_data.pkl IBS arrays per task / window / metric / condition
  26. cluster_stats.pkl Cluster-permutation results (min_p, n_sig, F_obs)
  27. stats_ibs_by_band.csv Per-band summary (mean ± SEM, Cohen's d, cluster p)
  28. fig_ibs_plv.png Bar figure — PLV
  29. fig_ibs_coh.png Bar figure — Coherence
  30. Usage
  31. -----
  32. python ibs_analysis.py
  33. python ibs_analysis.py --cache results/cleaned_eeg.pkl --output_dir results
  34. """
  35. import os
  36. import argparse
  37. import pickle
  38. import warnings
  39. import numpy as np
  40. import scipy.signal as sig
  41. import scipy.sparse as sparse
  42. import matplotlib
  43. matplotlib.use('Agg')
  44. import matplotlib.pyplot as plt
  45. import mne
  46. import hypyp.analyses as hana
  47. import hypyp.stats as hstats
  48. warnings.filterwarnings('ignore', category=RuntimeWarning)
  49. warnings.filterwarnings('ignore', category=UserWarning)
  50. # ── Default paths ──────────────────────────────────────────────────────────────
  51. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  52. _CACHE = os.path.abspath(os.path.join(BASE_DIR, '..', 'results', 'cleaned_eeg.pkl'))
  53. _OUTPUT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'results'))
  54. # ── Recording parameters ───────────────────────────────────────────────────────
  55. SRATE = 300
  56. GROUP_IDS = list(range(1, 12))
  57. N_SUBJ = 3
  58. N_CH = 19
  59. N_TRIALS = 40
  60. CH_NAMES = ['P3','C3','F3','Fz','F4','C4','P4','Cz','Pz',
  61. 'Fp1','Fp2','T3','T5','O1','O2','F7','F8','T6','T4']
  62. MONTAGE = mne.channels.make_standard_montage('standard_1020')
  63. # ── Frequency bands ────────────────────────────────────────────────────────────
  64. BANDS = {
  65. 'delta': ( 1, 3),
  66. 'theta': ( 4, 7),
  67. 'alpha': ( 8, 12),
  68. 'beta' : (14, 25),
  69. 'gamma': (30, 45),
  70. }
  71. BAND_NAMES = list(BANDS.keys())
  72. FREQS_MEAN = [2.0, 5.5, 10.0, 19.5, 37.5] # representative frequency per band
  73. N_BANDS = len(BANDS)
  74. N_FEAT = N_BANDS * N_CH # 95
  75. # ── Subject pairs within each trio ────────────────────────────────────────────
  76. PAIRS = [(0, 1), (0, 2), (1, 2)]
  77. PAIR_LABELS = ['S1-S2', 'S1-S3', 'S2-S3']
  78. # ── Analysis windows (ms relative to stimulus onset at 0 ms) ──────────────────
  79. WIN_ONSET_SMP = int(1000 * SRATE / 1000) # pre-stimulus = 1000 ms = 300 samples
  80. WINDOWS = [(0, 1000), (0, 2000)]
  81. WIN_LABELS = ['0-1000 ms', '0-2000 ms']
  82. # ── Resting state ──────────────────────────────────────────────────────────────
  83. REST_N_RUNS = 3
  84. # ── Statistics ─────────────────────────────────────────────────────────────────
  85. N_PERMS = 2000
  86. # ── Figure colors ──────────────────────────────────────────────────────────────
  87. COND_COLORS = {'coop': '#2166AC', 'other': '#D6604D'}
  88. # ══════════════════════════════════════════════════════════════════════════════
  89. # Utilities
  90. # ══════════════════════════════════════════════════════════════════════════════
  91. def ms_to_smp(ms):
  92. return int(ms * SRATE / 1000)
  93. def _sig_label(p):
  94. if p < 0.001: return '***'
  95. if p < 0.01: return '**'
  96. if p < 0.05: return '*'
  97. return 'n.s.'
  98. def _per_band_means(arr):
  99. """arr: (n, 95) → dict band → (mean, sem)"""
  100. out = {}
  101. for bi, band in enumerate(BAND_NAMES):
  102. chunk = arr[:, bi * N_CH:(bi + 1) * N_CH].mean(axis=1)
  103. out[band] = (chunk.mean(), chunk.std(ddof=1) / np.sqrt(len(chunk)))
  104. return out
  105. # ══════════════════════════════════════════════════════════════════════════════
  106. # HyPyP adjacency matrix (memoised per window length)
  107. # ══════════════════════════════════════════════════════════════════════════════
  108. _adj_cache = {}
  109. def get_adjacency(win_len_smp):
  110. if win_len_smp in _adj_cache:
  111. return _adj_cache[win_len_smp]
  112. info = mne.create_info(CH_NAMES, sfreq=SRATE, ch_types='eeg')
  113. info.set_montage(MONTAGE, on_missing='ignore')
  114. ep = mne.EpochsArray(np.zeros((5, N_CH, win_len_smp)), info, verbose=False)
  115. ch_con = hstats.con_matrix(ep, freqs_mean=FREQS_MEAN, draw=False)
  116. meta = hstats.metaconn_matrix_2brains(
  117. [(i, i) for i in range(N_CH)], ch_con.ch_con,
  118. freqs_mean=FREQS_MEAN, plot=False)
  119. adj = sparse.csr_matrix(meta.metaconn_freq)
  120. _adj_cache[win_len_smp] = adj
  121. return adj
  122. # ══════════════════════════════════════════════════════════════════════════════
  123. # IBS computation
  124. # ══════════════════════════════════════════════════════════════════════════════
  125. def _band_analytic(eeg_win, flo, fhi):
  126. """Bandpass + Hilbert for task epochs.
  127. Parameters
  128. ----------
  129. eeg_win : ndarray (n_ch, n_times, n_trials)
  130. Returns
  131. -------
  132. ndarray (n_trials, n_ch, 1, n_times) complex
  133. """
  134. sos = sig.butter(4, [flo, fhi], btype='bandpass', fs=SRATE, output='sos')
  135. filt = sig.sosfiltfilt(sos, eeg_win, axis=1)
  136. anal = sig.hilbert(filt, axis=1)
  137. return anal.transpose(2, 0, 1)[:, :, np.newaxis, :]
  138. def compute_task_ibs(eeg_a, eeg_b, win_start_smp, win_end_smp):
  139. """PLV and Coherence (ccorr) between two subjects across all task trials.
  140. Parameters
  141. ----------
  142. eeg_a, eeg_b : ndarray (n_ch, n_times, n_trials)
  143. win_start_smp : int start sample index within epoch
  144. win_end_smp : int end sample index within epoch
  145. Returns
  146. -------
  147. plv_mat, coh_mat : ndarray (n_trials, N_FEAT=95)
  148. """
  149. seg_a = eeg_a[:, win_start_smp:win_end_smp, :]
  150. seg_b = eeg_b[:, win_start_smp:win_end_smp, :]
  151. plv_bands, coh_bands = [], []
  152. for (flo, fhi) in BANDS.values():
  153. cs = np.stack([_band_analytic(seg_a, flo, fhi),
  154. _band_analytic(seg_b, flo, fhi)], axis=0)
  155. plv_f = hana.compute_sync(cs, mode='plv', epochs_average=False)
  156. coh_f = hana.compute_sync(cs, mode='ccorr', epochs_average=False)
  157. plv_ibs = plv_f[0, :, 0:N_CH, N_CH:2*N_CH]
  158. coh_ibs = coh_f[0, :, 0:N_CH, N_CH:2*N_CH]
  159. plv_bands.append(np.array([np.diag(plv_ibs[t]) for t in range(N_TRIALS)]))
  160. coh_bands.append(np.array([np.diag(np.real(coh_ibs[t])) for t in range(N_TRIALS)]))
  161. return (np.concatenate(plv_bands, axis=1),
  162. np.concatenate(coh_bands, axis=1))
  163. def compute_resting_ibs(rest_a, rest_b, win_len_smp):
  164. """PLV and Coherence for resting-state non-overlapping windows.
  165. Parameters
  166. ----------
  167. rest_a, rest_b : ndarray (n_ch, n_times) µV, 1–45 Hz filtered
  168. win_len_smp : int window length in samples
  169. Returns
  170. -------
  171. plv_mat, coh_mat : ndarray (n_windows, N_FEAT=95)
  172. """
  173. n_windows = rest_a.shape[1] // win_len_smp
  174. plv_bands, coh_bands = [], []
  175. for (flo, fhi) in BANDS.values():
  176. sos = sig.butter(4, [flo, fhi], btype='bandpass', fs=SRATE, output='sos')
  177. anal_a = sig.hilbert(sig.sosfiltfilt(sos, rest_a, axis=1), axis=1)
  178. anal_b = sig.hilbert(sig.sosfiltfilt(sos, rest_b, axis=1), axis=1)
  179. plv_wins, coh_wins = [], []
  180. for w in range(n_windows):
  181. sl = slice(w * win_len_smp, (w + 1) * win_len_smp)
  182. sa, sb = anal_a[:, sl], anal_b[:, sl]
  183. phi = np.angle(sa) - np.angle(sb)
  184. plv = np.abs(np.mean(np.exp(1j * phi), axis=1))
  185. cross = sa * np.conj(sb)
  186. coh = (np.abs(np.mean(cross, axis=1)) /
  187. (np.sqrt(np.mean(np.abs(sa)**2, axis=1) *
  188. np.mean(np.abs(sb)**2, axis=1)) + 1e-12))
  189. plv_wins.append(plv)
  190. coh_wins.append(coh)
  191. plv_bands.append(np.array(plv_wins))
  192. coh_bands.append(np.array(coh_wins))
  193. return (np.concatenate(plv_bands, axis=1),
  194. np.concatenate(coh_bands, axis=1))
  195. # ══════════════════════════════════════════════════════════════════════════════
  196. # Aggregate IBS across all groups
  197. # ══════════════════════════════════════════════════════════════════════════════
  198. def aggregate_ibs(cache):
  199. """Compute IBS for all tasks / windows / pairs and resting state.
  200. Returns
  201. -------
  202. results : dict
  203. results[task][(start_ms, end_ms)][metric]['coop'] → ndarray (n, 95)
  204. results[task][(start_ms, end_ms)][metric]['other'] → ndarray (n, 95)
  205. results['resting'][dur_ms][metric]['all'] → ndarray (n, 95)
  206. """
  207. tasks = {'decision': 'decision', 'feedback': 'feedback'}
  208. results = {}
  209. for task in tasks:
  210. results[task] = {}
  211. for win in WINDOWS:
  212. results[task][win] = {m: {'coop': [], 'other': []}
  213. for m in ('plv', 'coh')}
  214. rest_durations = sorted(set(end - start for start, end in WINDOWS))
  215. results['resting'] = {d: {m: {'all': []} for m in ('plv', 'coh')}
  216. for d in rest_durations}
  217. for g in GROUP_IDS:
  218. score = cache[g]['score'] # (40, 3) 1 = coop
  219. for task in tasks:
  220. cleaned = cache[g][task] # (57, n_times, 40)
  221. for (start_ms, end_ms) in WINDOWS:
  222. w_start = WIN_ONSET_SMP + ms_to_smp(start_ms)
  223. w_end = WIN_ONSET_SMP + ms_to_smp(end_ms)
  224. for sa, sb in PAIRS:
  225. mask = (score[:, sa] == 1) & (score[:, sb] == 1)
  226. ea = cleaned[sa * N_CH:(sa + 1) * N_CH]
  227. eb = cleaned[sb * N_CH:(sb + 1) * N_CH]
  228. plv_mat, coh_mat = compute_task_ibs(ea, eb, w_start, w_end)
  229. key = (start_ms, end_ms)
  230. results[task][key]['plv']['coop'].append(plv_mat[mask])
  231. results[task][key]['plv']['other'].append(plv_mat[~mask])
  232. results[task][key]['coh']['coop'].append(coh_mat[mask])
  233. results[task][key]['coh']['other'].append(coh_mat[~mask])
  234. for run_idx in range(REST_N_RUNS):
  235. rest = cache[g]['resting'][run_idx] # (57, 18000)
  236. for sa, sb in PAIRS:
  237. ra = rest[sa * N_CH:(sa + 1) * N_CH]
  238. rb = rest[sb * N_CH:(sb + 1) * N_CH]
  239. for dur_ms in rest_durations:
  240. plv_r, coh_r = compute_resting_ibs(ra, rb, ms_to_smp(dur_ms))
  241. results['resting'][dur_ms]['plv']['all'].append(plv_r)
  242. results['resting'][dur_ms]['coh']['all'].append(coh_r)
  243. print(f' G{g:02d} done.', flush=True)
  244. # Concatenate
  245. for task in tasks:
  246. for win in WINDOWS:
  247. for metric in ('plv', 'coh'):
  248. for cond in ('coop', 'other'):
  249. results[task][win][metric][cond] = np.concatenate(
  250. results[task][win][metric][cond], axis=0)
  251. for dur_ms in rest_durations:
  252. for metric in ('plv', 'coh'):
  253. results['resting'][dur_ms][metric]['all'] = np.concatenate(
  254. results['resting'][dur_ms][metric]['all'], axis=0)
  255. return results
  256. # ══════════════════════════════════════════════════════════════════════════════
  257. # Cluster-permutation test
  258. # ══════════════════════════════════════════════════════════════════════════════
  259. def run_cluster_test(coop, other, win_len_smp):
  260. adj = get_adjacency(win_len_smp)
  261. result = hstats.statscondCluster(
  262. data=[coop, other],
  263. freqs_mean=FREQS_MEAN,
  264. ch_con_freq=adj,
  265. tail=0,
  266. n_permutations=N_PERMS,
  267. alpha=0.05,
  268. )
  269. pvs = result.cluster_p_values
  270. min_p = min(pvs) if len(pvs) else 1.0
  271. n_sig = sum(p < 0.05 for p in pvs)
  272. return min_p, n_sig, result
  273. # ══════════════════════════════════════════════════════════════════════════════
  274. # Figures
  275. # ══════════════════════════════════════════════════════════════════════════════
  276. def plot_ibs_bars(results, cluster_stats, output_dir):
  277. metric_labels = {'plv': 'PLV', 'coh': 'Coherence (ccorr)'}
  278. tasks = [t for t in results if t != 'resting']
  279. for metric in ('plv', 'coh'):
  280. fig, axes = plt.subplots(len(tasks), len(WINDOWS),
  281. figsize=(5 * len(WINDOWS), 4.5 * len(tasks)),
  282. sharey='row')
  283. fig.suptitle(
  284. f'Inter-Brain Synchrony — {metric_labels[metric]}\n'
  285. f'Cooperative vs. Other (mean ± SEM, cluster permutation n={N_PERMS})',
  286. fontsize=12, fontweight='bold')
  287. x = np.arange(N_BANDS)
  288. w = 0.35
  289. band_caps = [b.capitalize() for b in BAND_NAMES]
  290. for ri, task in enumerate(tasks):
  291. for ci, (win, win_lbl) in enumerate(zip(WINDOWS, WIN_LABELS)):
  292. ax = axes[ri, ci]
  293. coop_bm = _per_band_means(results[task][win][metric]['coop'])
  294. other_bm = _per_band_means(results[task][win][metric]['other'])
  295. for bi, band in enumerate(BAND_NAMES):
  296. c_m, c_s = coop_bm[band]
  297. o_m, o_s = other_bm[band]
  298. ax.bar(x[bi] - w/2, c_m, w, color=COND_COLORS['coop'],
  299. yerr=c_s, capsize=3, error_kw=dict(elinewidth=1),
  300. label='Cooperative' if bi == 0 else '')
  301. ax.bar(x[bi] + w/2, o_m, w, color=COND_COLORS['other'],
  302. yerr=o_s, capsize=3, error_kw=dict(elinewidth=1),
  303. label='Other' if bi == 0 else '')
  304. min_p, n_sig = cluster_stats[task][metric][win]['min_p'], \
  305. cluster_stats[task][metric][win]['n_sig']
  306. slbl = _sig_label(min_p)
  307. if min_p < 0.001:
  308. p_str = f'cluster p < 0.001 {slbl}'
  309. elif min_p < 0.01:
  310. p_str = f'cluster p < 0.01 {slbl}'
  311. elif min_p < 0.05:
  312. p_str = f'cluster p = {min_p:.3f} {slbl}'
  313. else:
  314. p_str = f'cluster p = {min_p:.3f} n.s.'
  315. color_sig = 'red' if min_p < 0.05 else 'dimgray'
  316. ax.text(0.98, 0.97, p_str, transform=ax.transAxes,
  317. ha='right', va='top', fontsize=9, color=color_sig,
  318. bbox=dict(boxstyle='round,pad=0.3',
  319. facecolor='white', edgecolor=color_sig, alpha=0.85))
  320. ax.set_xticks(x)
  321. ax.set_xticklabels(band_caps, fontsize=10)
  322. ax.set_title(f'{task.capitalize()} [{win_lbl}]', fontsize=11)
  323. ax.set_ylabel(metric_labels[metric], fontsize=10)
  324. ax.spines['top'].set_visible(False)
  325. ax.spines['right'].set_visible(False)
  326. if ri == 0 and ci == 0:
  327. ax.legend(fontsize=8, loc='upper left')
  328. plt.tight_layout()
  329. path = os.path.join(output_dir, f'fig_ibs_{metric}.png')
  330. plt.savefig(path, dpi=200, bbox_inches='tight')
  331. plt.close()
  332. print(f' Saved: {os.path.basename(path)}')
  333. def plot_fstat(cluster_stats, output_dir):
  334. for task in ('decision', 'feedback'):
  335. for metric in ('plv', 'coh'):
  336. sig_wins = [(win, cluster_stats[task][metric][win])
  337. for win in WINDOWS
  338. if cluster_stats[task][metric][win]['n_sig'] > 0]
  339. if not sig_wins:
  340. continue
  341. n = len(sig_wins)
  342. fig, axes = plt.subplots(1, n, figsize=(6 * n, 4.5))
  343. if n == 1:
  344. axes = [axes]
  345. fig.suptitle(f'Cluster F-statistic — {task.capitalize()} {metric.upper()}',
  346. fontsize=12, fontweight='bold')
  347. for ax, (win, info) in zip(axes, sig_wins):
  348. F = info['F_obs'].reshape(N_BANDS, N_CH)
  349. lim = np.abs(F).max()
  350. im = ax.imshow(F, aspect='auto', cmap='RdBu_r',
  351. vmin=-lim, vmax=lim)
  352. ax.set_xticks(range(N_CH))
  353. ax.set_xticklabels(CH_NAMES, rotation=90, fontsize=7)
  354. ax.set_yticks(range(N_BANDS))
  355. ax.set_yticklabels([b.capitalize() for b in BAND_NAMES], fontsize=9)
  356. min_p = info['min_p']
  357. p_str = '< 0.001' if min_p < 0.001 else f'= {min_p:.3f}'
  358. ax.set_title(f'[{win[0]}-{win[1]} ms] p {p_str}', fontsize=10)
  359. plt.colorbar(im, ax=ax, fraction=0.046, label='F-statistic')
  360. plt.tight_layout()
  361. path = os.path.join(output_dir, f'fig_fstat_{task}_{metric}.png')
  362. plt.savefig(path, dpi=200, bbox_inches='tight')
  363. plt.close()
  364. print(f' Saved: {os.path.basename(path)}')
  365. # ══════════════════════════════════════════════════════════════════════════════
  366. # CSV export
  367. # ══════════════════════════════════════════════════════════════════════════════
  368. def export_csv(results, cluster_stats, output_dir):
  369. import csv
  370. rows = []
  371. for task in ('decision', 'feedback'):
  372. for win in WINDOWS:
  373. win_lbl = f'{win[0]}-{win[1]}ms'
  374. for metric in ('plv', 'coh'):
  375. info = cluster_stats[task][metric][win]
  376. coop_bm = _per_band_means(results[task][win][metric]['coop'])
  377. other_bm = _per_band_means(results[task][win][metric]['other'])
  378. for bi, band in enumerate(BAND_NAMES):
  379. c_m, c_s = coop_bm[band]
  380. o_m, o_s = other_bm[band]
  381. diff = c_m - o_m
  382. nc = results[task][win][metric]['coop'].shape[0]
  383. no = results[task][win][metric]['other'].shape[0]
  384. ca = results[task][win][metric]['coop'][:, bi*N_CH:(bi+1)*N_CH].mean(axis=1)
  385. oa = results[task][win][metric]['other'][:, bi*N_CH:(bi+1)*N_CH].mean(axis=1)
  386. pool = np.sqrt(((nc-1)*ca.std(ddof=1)**2 + (no-1)*oa.std(ddof=1)**2) / (nc+no-2))
  387. rows.append({
  388. 'task': task, 'window': win_lbl, 'metric': metric, 'band': band,
  389. 'coop_mean': f'{c_m:.6f}', 'coop_sem': f'{c_s:.6f}',
  390. 'other_mean': f'{o_m:.6f}', 'other_sem': f'{o_s:.6f}',
  391. 'diff': f'{diff:.6f}',
  392. 'cohens_d': f'{diff / (pool + 1e-12):.4f}',
  393. 'cluster_p': f'{info["min_p"]:.4f}',
  394. 'n_sig_clusters': info['n_sig'],
  395. 'sig': _sig_label(info['min_p']),
  396. })
  397. path = os.path.join(output_dir, 'stats_ibs_by_band.csv')
  398. with open(path, 'w', newline='') as f:
  399. w = csv.DictWriter(f, fieldnames=rows[0].keys())
  400. w.writeheader(); w.writerows(rows)
  401. print(f' Saved: {os.path.basename(path)}')
  402. # ══════════════════════════════════════════════════════════════════════════════
  403. # CLI
  404. # ══════════════════════════════════════════════════════════════════════════════
  405. def parse_args():
  406. p = argparse.ArgumentParser(description='Hyperscanning IBS analysis')
  407. p.add_argument('--cache', default=_CACHE,
  408. help='Path to cleaned_eeg.pkl from preprocess.py')
  409. p.add_argument('--output_dir', default=_OUTPUT_DIR,
  410. help='Directory to write figures and CSVs')
  411. return p.parse_args()
  412. def main():
  413. args = parse_args()
  414. os.makedirs(args.output_dir, exist_ok=True)
  415. print('=== IBS Analysis ===')
  416. print(f' cache : {args.cache}')
  417. print(f' output_dir : {args.output_dir}')
  418. print('\n[1/4] Loading preprocessed cache...')
  419. with open(args.cache, 'rb') as f:
  420. cache = pickle.load(f)
  421. print('\n[2/4] Computing IBS (PLV + Coherence)...')
  422. results = aggregate_ibs(cache)
  423. with open(os.path.join(args.output_dir, 'ibs_data.pkl'), 'wb') as f:
  424. pickle.dump(results, f)
  425. print('\n[3/4] Cluster-permutation tests...')
  426. cluster_stats = {}
  427. for task in ('decision', 'feedback'):
  428. cluster_stats[task] = {'plv': {}, 'coh': {}}
  429. for (start_ms, end_ms) in WINDOWS:
  430. win = (start_ms, end_ms)
  431. win_smp = ms_to_smp(end_ms - start_ms)
  432. for metric in ('plv', 'coh'):
  433. coop = results[task][win][metric]['coop']
  434. other = results[task][win][metric]['other']
  435. print(f' {task} [{start_ms}-{end_ms}ms] {metric.upper()}'
  436. f' coop n={coop.shape[0]}, other n={other.shape[0]}',
  437. flush=True)
  438. min_p, n_sig, result = run_cluster_test(coop, other, win_smp)
  439. print(f' min_p = {min_p:.4f} n_sig = {n_sig} {_sig_label(min_p)}')
  440. cluster_stats[task][metric][win] = {
  441. 'min_p': min_p, 'n_sig': n_sig,
  442. 'F_obs': result.F_obs_plot,
  443. }
  444. with open(os.path.join(args.output_dir, 'cluster_stats.pkl'), 'wb') as f:
  445. pickle.dump(cluster_stats, f)
  446. print('\n[4/4] Figures and CSV...')
  447. plot_ibs_bars(results, cluster_stats, args.output_dir)
  448. plot_fstat(cluster_stats, args.output_dir)
  449. export_csv(results, cluster_stats, args.output_dir)
  450. print('\nDone.')
  451. if __name__ == '__main__':
  452. main()

ibs_analysis.py at commit 0862853, no license · at the source

Overview

Authors: H Kim1, SC Jun1, CS Nam2
ORCID iDs: SC Jun, CS Nam
  1. Department of AI Convergence, Gwangju Institute of Science and Technology, Gwangju, 61005, South Korea
  2. Center of Excellence in Product Design and Advanced Manufacturing, North Carolina A&T State University, Greensboro, NC, 27411, USA
Journal: Data in brief, volume 68, article 113064
Dates: received 22 May 2026; accepted 3 July 2026; published online 10 July 2026
Type: Data paper · Language: English
License: CC BY
Identifiers: DOI 10.1016/j.dib.2026.113064 · PMID 42541318 · PMCID PMC13427532 · OpenAlex W7167941105
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: EEG (modality), human (organism), methods / tools (subfield)
Methods: Spectral & time-frequency, Preprocessing, Statistics, Smoothing, state filtering, decompositions, Connectivity, Evoked potentials, Graphs, Physiology & signal measures
Keywords: EEG hyperscanning, Triadic interaction, Prisoner’s Dilemma, Inter-brain synchrony, Phase-locking value, Event-related potentials
Topic: Reinforcement Learning in Robotics (Artificial Intelligence, Computer Science), according to OpenAlex
Funding: Ministry of Science and ICT, South Korea (2019-0-01842); Ministry of Education (RS-2025-25425143, RS-2024-00361688); Institute for Information and Communications Technology Promotion; National Research Foundation of Korea (NRF-2023S1A5A2A01076552); National Science Foundation (IIS-2554482)
Citations: not cited yet (Europe PMC); 14 references in the paper

Abstract

This data article describes an open EEG hyperscanning dataset acquired during an iterated 3-player Prisoner’s Dilemma (PD) task, designed to support reproducible research on triadic social decision-making. EEG was recorded simultaneously from three participants per group (11 groups; 33 subjects) using synchronized acquisition, with decision-locked and feedback-locked epochs provided for 40 task trials per subject and three 60-s resting-state runs per group. The released BIDS format contain 19-channel EEG arrays sampled at 300 Hz, with explicit epoch definitions for decision (−1000 to 4000 ms) and feedback (−1000 to 2000 ms) periods, as well as trial-wise behavioral choice labels (1=cooperate, 2=defect) enabling reconstruction of dyad- and triad-level outcomes. Questionnaire metadata (personal information and pre/mid/post state measures) Yare also provided as supplementary spreadsheets. To facilitate reuse and benchmarking, we release Python code that reproduces the preprocessing pipeline (average reference, FIR filtering, ICA + ICLabel for task EEG), ERP summaries, and inter-brain synchrony measures (PLV and coherence) with window-matched resting baselines and cluster-permutation statistics. The dataset is intended for method development and benchmarking in ERP analysis, inter-brain synchrony estimation, and modeling of dynamic group interaction states in triadic games.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 6 matches between paragraphs and lines of code.

heegyukim4043/PD_EEG_hyperscan_processing

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 0862853f1095404db1f4df04f7c5ac17d8da3865, 15 July 2026
Languages: Python (6)
Size: 8 files, 6 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, environment (pd_eeg_analysis/requirements.txt)
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (5 files), MNE-Python (4 files), SciPy (3 files), ICLabel (2 files), Matplotlib (2 files), pandas (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
7 files

Code availability

The analysis code is available at: https://github.com/heegyukim4043/PD_EEG_hyperscan_processing.

The repository provides a fully reproducible workflow to generate the main technical validation outputs from the released BIDS, including (i) preprocessing to create a cleaned cache (cleaned_eeg.pkl), (ii) inter-brain synchrony (IBS) analyses using PLV and circular correlation coefficient (ccorr) with cluster-based permutation testing, and (iii) ERP analyses for decision- and feedback-locked epochs. All scripts are organized to enable direct execution with minimal configuration, supporting full reproducibility of the reported results. The repository is structured to allow users to reproduce, verify, and extend all analyses from raw data to final outputs.

Preprocessing (bids.py): loads BIDS (.set) and produces results/cleaned_eeg.pkl after average referencing, band-pass filtering, and ICA-based artifact rejection for task EEG (Infomax ICA + ICLabel; eye blink/muscle, probability > 0.80). Resting EEG is processed with filtering and average reference (no ICA). This step generates a standardized intermediate dataset that serves as the input for all subsequent analyses and ensures consistency across the pipeline.

IBS analysis (ibs_analysis.py): computes dyad-wise IBS for all within-triad pairs (S1–S2, S1–S3, S2–S3) in the decision and feedback epochs using 0–1000 ms and 0–2000 ms windows, with a window-matched resting baseline and cluster-permutation tests (n=2000, two-tailed). Outputs include figures and per-band summary CSV tables. This analysis design enables statistically robust and comparable estimation of inter-brain synchrony across conditions.

Reproduced under the paper's license (CC BY), from the paper cited above.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 6 scripts, each with its path and the digest of its content;
  • 6 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

Datasets cited

Data Availability Statement

The dataset is publicly available on OpenNeuro (DOI: https://doi.org/10.18112/openneuro.ds007822.v1.0.0). The repository contains BIDS format, questionnaire spreadsheets, behavioral annotations, and metadata required for reuse.

FigshareEEG and Hyperscanning, triadic Prisoner's dilemma game (Original data) (https://doi.org/10.6084/m9.figshare.32197038)

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 2, 28 September 2026

  • Authors: added SC Jun (0000-0001-5357-4436); CS Nam (0000-0001-9005-0703); removed SC Jun; CS Nam

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, pages, dates, 3 authors, 6 keywords, 5 funders, 14 references.

Cite

This paper

Kim, H., Jun, S., & Nam, C. (2026). A reproducible EEG hyperscanning dataset for triadic social decision-making during an iterated 3-player Prisoner's Dilemma. Data in brief, 68, 113064. https://doi.org/10.1016/j.dib.2026.113064

BibTeX

@article{kim2026reproducible,
author = {Kim, H and Jun, SC and Nam, CS},
title = {{A reproducible EEG hyperscanning dataset for triadic social decision-making during an iterated 3-player Prisoner's Dilemma}},
journal = {Data in brief},
year = {2026},
month = jul,
volume = {68},
pages = {113064},
publisher = {Elsevier},
issn = {2352-3409},
doi = {10.1016/j.dib.2026.113064},
url = {https://doi.org/10.1016/j.dib.2026.113064},
pmid = {42541318},
pmcid = {PMC13427532}
}

RIS

TY - JOUR
AU - Kim, H
AU - Jun, SC
AU - Nam, CS
TI - A reproducible EEG hyperscanning dataset for triadic social decision-making during an iterated 3-player Prisoner's Dilemma
T2 - Data in brief
J2 - Data Brief
PY - 2026
DA - 2026/07/10
VL - 68
SP - 113064
SN - 2352-3409
PB - Elsevier
DO - 10.1016/j.dib.2026.113064
UR - https://doi.org/10.1016/j.dib.2026.113064
LA - en
ER -

CSL-JSON

{
"id": "10.1016/j.dib.2026.113064",
"type": "article-journal",
"title": "A reproducible EEG hyperscanning dataset for triadic social decision-making during an iterated 3-player Prisoner's Dilemma",
"container-title": "Data in brief",
"author": [
{
"family": "Kim",
"given": "H"
},
{
"family": "Jun",
"given": "SC"
},
{
"family": "Nam",
"given": "CS"
}
],
"container-title-short": "Data Brief",
"volume": "68",
"page": "113064",
"DOI": "10.1016/j.dib.2026.113064",
"PMID": "42541318",
"PMCID": "PMC13427532",
"ISSN": "2352-3409",
"publisher": "Elsevier",
"URL": "https://doi.org/10.1016/j.dib.2026.113064",
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
10
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41597-025-06032-2 [code]
A 40-Class SSVEP Speller Dataset: Beta Range Stimulation for Low-Fatigue BCI Applications.
Journal: Scientific data
In common: MNE-Python, SciPy, Matplotlib, 1 other tool, methods / tools, EEG, author SC Jun
[2] doi:10.1038/s41597-022-01509-w [code]
EEG Dataset for RSVP and P300 Speller Brain-Computer Interfaces.
Journal: Scientific data
In common: MNE-Python, SciPy, Matplotlib, 1 other tool, methods / tools, EEG, author SC Jun
[3] doi:10.1371/journal.pone.0327791 [code]
PyNoetic: A modular python framework for no-code development of EEG brain-computer interfaces.
Journal: PloS one
In common: ICLabel, MNE-Python, pandas, 3 other tools, methods / tools, EEG, 2 references
[4] doi:10.1093/cercor/bhag113 [code]
Long-term reliability and stability of parameterized resting state EEG: evidence from a five-year follow-up.
Journal: Cerebral cortex (New York, N.Y. : 1991)
In common: ICLabel, MNE-Python, pandas, 3 other tools, methods / tools, EEG, 2 references
[5] doi:10.1038/s41597-022-01538-5 [code]
A resource for assessing dynamic binary choices in the adult brain using EEG and mouse-tracking.
Journal: Scientific data
In common: ICLabel, MNE-Python, pandas, 3 other tools, methods / tools, EEG, 2 references
[6] doi:10.1097/j.pain.0000000000004044 [code]
No effect of rhythmic visual stimulation on experimental pain perception.
Journal: Pain
In common: ICLabel, MNE-Python, pandas, 3 other tools, EEG, 2 references
[7] doi:10.1002/mds.70031 [code]
Cortical and Corticomuscular Beta-Gamma Phase-Amplitude Coupling During Different Locomotion States and the Effects of Levodopa in Parkinson's Disease.
Journal: Movement disorders : official journal of the Movement Disorder Society
In common: ICLabel, MNE-Python, pandas, 3 other tools, EEG, 2 references
[8] doi:10.1016/j.ebiom.2024.105259 [code]
Machine learning of brain-specific biomarkers from EEG.
Journal: EBioMedicine
In common: ICLabel, MNE-Python, pandas, 3 other tools, EEG, 2 references
[9] doi:10.1523/eneuro.0160-22.2022 [code]
Improved Manual Annotation of EEG Signals through Convolutional Neural Network Guidance.
Journal: eNeuro
In common: ICLabel, MNE-Python, pandas, 3 other tools, EEG, 2 references
[10] doi:10.3758/s13428-026-02997-z [code]
PyLossless: A non-destructive EEG processing pipeline.
Journal: Behavior research methods
In common: ICLabel, MNE-Python, pandas, 2 other tools, methods / tools, EEG, 2 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1016/j.dib.2026.113064.svg)](https://openscicode.org/badge/doi/10.1016/j.dib.2026.113064)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1016/j.dib.2026.113064.svg
   :target: https://openscicode.org/badge/doi/10.1016/j.dib.2026.113064
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1016/j.dib.2026.113064"><img src="https://openscicode.org/badge/doi/10.1016/j.dib.2026.113064.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.