A reproducible EEG hyperscanning dataset for triadic social decision-making during an iterated 3-player Prisoner's Dilemma.
The 6 matches
- [1] § Experimental Design, Materials and Methods › Technical validation › Inter brain synchrony ↔ pd_eeg_analysis/ibs_analysis.py, lines 1–57 · score 0.94 · Inter brain synchrony, 14–25 Hz, 30–45 Hz, 8–12 Hz, 0–2000 ms, 4–7 Hz
- [2] § Experimental Design, Materials and Methods › Technical validation › Preprocessing ↔ pd_eeg_analysis/preprocess.py, lines 1–52 · score 0.91 · 1–100 Hz, ICLabel, eye blink, preprocessing pipeline, Task EEG, notch
- [3] § Experimental Design, Materials and Methods › Technical validation › Inter brain synchrony ↔ pd_eeg_analysis/ibs_analysis.py, lines 1–57 · score 0.83 · window matched, S1 S2, S1 S3, S2 S3, overlapping, onset
- [4] § Experimental Design, Materials and Methods › Technical validation › Preprocessing ↔ pd_eeg_analysis/ibs_analysis.py, lines 200–233 · score 0.61 · 1–45 Hz, resting IBS, cross, overlapping, filtering, window
- [5] § Experimental Design, Materials and Methods › Behavioral validation: computation of behavioral indices ↔ pd_eeg_analysis/ibs_analysis.py, lines 89–91 · score 0.59 · S1 S2, S1 S3, S2 S3
- [6] § Experimental Design, Materials and Methods › Technical validation › Behavioral validation: computation of behavioral indices ↔ pd_eeg_analysis/ibs_analysis.py, lines 89–91 · score 0.59 · S1 S2, S1 S3, S2 S3
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: 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
- """
- ibs_analysis.py
- ===============
- Inter-Brain Synchrony (IBS) analysis for three-person hyperscanning EEG.
- Requires cleaned_eeg.pkl produced by preprocess.py.
- Analysis
- --------
- - Metrics : PLV, Coherence (ccorr) via HyPyP
- - Windows : 0–1000 ms, 0–2000 ms post-stimulus onset
- - Tasks : decision, feedback
- - Pairs : all 3 dyads within each trio (S1-S2, S1-S3, S2-S3)
- - Condition: Cooperative (both chose cooperate) vs. Other
- - Resting : non-overlapping windows matched to task window length (baseline)
- - Stats : cluster-permutation test (HyPyP, 2000 permutations, two-tailed)
- Frequency bands
- ---------------
- delta 1–3 Hz
- theta 4–7 Hz
- alpha 8–12 Hz
- beta 14–25 Hz
- gamma 30–45 Hz
- Output
- ------
- results/
- ibs_data.pkl IBS arrays per task / window / metric / condition
- cluster_stats.pkl Cluster-permutation results (min_p, n_sig, F_obs)
- stats_ibs_by_band.csv Per-band summary (mean ± SEM, Cohen's d, cluster p)
- fig_ibs_plv.png Bar figure — PLV
- fig_ibs_coh.png Bar figure — Coherence
- Usage
- -----
- python ibs_analysis.py
- python ibs_analysis.py --cache results/cleaned_eeg.pkl --output_dir results
- """
- import os
- import argparse
- import pickle
- import warnings
- import numpy as np
- import scipy.signal as sig
- import scipy.sparse as sparse
- import matplotlib
- matplotlib.use('Agg')
- import matplotlib.pyplot as plt
- import mne
- import hypyp.analyses as hana
- import hypyp.stats as hstats
- warnings.filterwarnings('ignore', category=RuntimeWarning)
- warnings.filterwarnings('ignore', category=UserWarning)
- # ── Default paths ──────────────────────────────────────────────────────────────
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
- _CACHE = os.path.abspath(os.path.join(BASE_DIR, '..', 'results', 'cleaned_eeg.pkl'))
- _OUTPUT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'results'))
- # ── Recording parameters ───────────────────────────────────────────────────────
- SRATE = 300
- GROUP_IDS = list(range(1, 12))
- N_SUBJ = 3
- N_CH = 19
- N_TRIALS = 40
- CH_NAMES = ['P3','C3','F3','Fz','F4','C4','P4','Cz','Pz',
- 'Fp1','Fp2','T3','T5','O1','O2','F7','F8','T6','T4']
- MONTAGE = mne.channels.make_standard_montage('standard_1020')
- # ── Frequency bands ────────────────────────────────────────────────────────────
- BANDS = {
- 'delta': ( 1, 3),
- 'theta': ( 4, 7),
- 'alpha': ( 8, 12),
- 'beta' : (14, 25),
- 'gamma': (30, 45),
- }
- BAND_NAMES = list(BANDS.keys())
- FREQS_MEAN = [2.0, 5.5, 10.0, 19.5, 37.5] # representative frequency per band
- N_BANDS = len(BANDS)
- N_FEAT = N_BANDS * N_CH # 95
- # ── Subject pairs within each trio ────────────────────────────────────────────
- PAIRS = [(0, 1), (0, 2), (1, 2)]
- PAIR_LABELS = ['S1-S2', 'S1-S3', 'S2-S3']
- # ── Analysis windows (ms relative to stimulus onset at 0 ms) ──────────────────
- WIN_ONSET_SMP = int(1000 * SRATE / 1000) # pre-stimulus = 1000 ms = 300 samples
- WINDOWS = [(0, 1000), (0, 2000)]
- WIN_LABELS = ['0-1000 ms', '0-2000 ms']
- # ── Resting state ──────────────────────────────────────────────────────────────
- REST_N_RUNS = 3
- # ── Statistics ─────────────────────────────────────────────────────────────────
- N_PERMS = 2000
- # ── Figure colors ──────────────────────────────────────────────────────────────
- COND_COLORS = {'coop': '#2166AC', 'other': '#D6604D'}
- # ══════════════════════════════════════════════════════════════════════════════
- # Utilities
- # ══════════════════════════════════════════════════════════════════════════════
- def ms_to_smp(ms):
- return int(ms * SRATE / 1000)
- def _sig_label(p):
- if p < 0.001: return '***'
- if p < 0.01: return '**'
- if p < 0.05: return '*'
- return 'n.s.'
- def _per_band_means(arr):
- """arr: (n, 95) → dict band → (mean, sem)"""
- out = {}
- for bi, band in enumerate(BAND_NAMES):
- chunk = arr[:, bi * N_CH:(bi + 1) * N_CH].mean(axis=1)
- out[band] = (chunk.mean(), chunk.std(ddof=1) / np.sqrt(len(chunk)))
- return out
- # ══════════════════════════════════════════════════════════════════════════════
- # HyPyP adjacency matrix (memoised per window length)
- # ══════════════════════════════════════════════════════════════════════════════
- _adj_cache = {}
- def get_adjacency(win_len_smp):
- if win_len_smp in _adj_cache:
- return _adj_cache[win_len_smp]
- info = mne.create_info(CH_NAMES, sfreq=SRATE, ch_types='eeg')
- info.set_montage(MONTAGE, on_missing='ignore')
- ep = mne.EpochsArray(np.zeros((5, N_CH, win_len_smp)), info, verbose=False)
- ch_con = hstats.con_matrix(ep, freqs_mean=FREQS_MEAN, draw=False)
- meta = hstats.metaconn_matrix_2brains(
- [(i, i) for i in range(N_CH)], ch_con.ch_con,
- freqs_mean=FREQS_MEAN, plot=False)
- adj = sparse.csr_matrix(meta.metaconn_freq)
- _adj_cache[win_len_smp] = adj
- return adj
- # ══════════════════════════════════════════════════════════════════════════════
- # IBS computation
- # ══════════════════════════════════════════════════════════════════════════════
- def _band_analytic(eeg_win, flo, fhi):
- """Bandpass + Hilbert for task epochs.
- Parameters
- ----------
- eeg_win : ndarray (n_ch, n_times, n_trials)
- Returns
- -------
- ndarray (n_trials, n_ch, 1, n_times) complex
- """
- sos = sig.butter(4, [flo, fhi], btype='bandpass', fs=SRATE, output='sos')
- filt = sig.sosfiltfilt(sos, eeg_win, axis=1)
- anal = sig.hilbert(filt, axis=1)
- return anal.transpose(2, 0, 1)[:, :, np.newaxis, :]
- def compute_task_ibs(eeg_a, eeg_b, win_start_smp, win_end_smp):
- """PLV and Coherence (ccorr) between two subjects across all task trials.
- Parameters
- ----------
- eeg_a, eeg_b : ndarray (n_ch, n_times, n_trials)
- win_start_smp : int start sample index within epoch
- win_end_smp : int end sample index within epoch
- Returns
- -------
- plv_mat, coh_mat : ndarray (n_trials, N_FEAT=95)
- """
- seg_a = eeg_a[:, win_start_smp:win_end_smp, :]
- seg_b = eeg_b[:, win_start_smp:win_end_smp, :]
- plv_bands, coh_bands = [], []
- for (flo, fhi) in BANDS.values():
- cs = np.stack([_band_analytic(seg_a, flo, fhi),
- _band_analytic(seg_b, flo, fhi)], axis=0)
- plv_f = hana.compute_sync(cs, mode='plv', epochs_average=False)
- coh_f = hana.compute_sync(cs, mode='ccorr', epochs_average=False)
- plv_ibs = plv_f[0, :, 0:N_CH, N_CH:2*N_CH]
- coh_ibs = coh_f[0, :, 0:N_CH, N_CH:2*N_CH]
- plv_bands.append(np.array([np.diag(plv_ibs[t]) for t in range(N_TRIALS)]))
- coh_bands.append(np.array([np.diag(np.real(coh_ibs[t])) for t in range(N_TRIALS)]))
- return (np.concatenate(plv_bands, axis=1),
- np.concatenate(coh_bands, axis=1))
- def compute_resting_ibs(rest_a, rest_b, win_len_smp):
- """PLV and Coherence for resting-state non-overlapping windows.
- Parameters
- ----------
- rest_a, rest_b : ndarray (n_ch, n_times) µV, 1–45 Hz filtered
- win_len_smp : int window length in samples
- Returns
- -------
- plv_mat, coh_mat : ndarray (n_windows, N_FEAT=95)
- """
- n_windows = rest_a.shape[1] // win_len_smp
- plv_bands, coh_bands = [], []
- for (flo, fhi) in BANDS.values():
- sos = sig.butter(4, [flo, fhi], btype='bandpass', fs=SRATE, output='sos')
- anal_a = sig.hilbert(sig.sosfiltfilt(sos, rest_a, axis=1), axis=1)
- anal_b = sig.hilbert(sig.sosfiltfilt(sos, rest_b, axis=1), axis=1)
- plv_wins, coh_wins = [], []
- for w in range(n_windows):
- sl = slice(w * win_len_smp, (w + 1) * win_len_smp)
- sa, sb = anal_a[:, sl], anal_b[:, sl]
- phi = np.angle(sa) - np.angle(sb)
- plv = np.abs(np.mean(np.exp(1j * phi), axis=1))
- cross = sa * np.conj(sb)
- coh = (np.abs(np.mean(cross, axis=1)) /
- (np.sqrt(np.mean(np.abs(sa)**2, axis=1) *
- np.mean(np.abs(sb)**2, axis=1)) + 1e-12))
- plv_wins.append(plv)
- coh_wins.append(coh)
- plv_bands.append(np.array(plv_wins))
- coh_bands.append(np.array(coh_wins))
- return (np.concatenate(plv_bands, axis=1),
- np.concatenate(coh_bands, axis=1))
- # ══════════════════════════════════════════════════════════════════════════════
- # Aggregate IBS across all groups
- # ══════════════════════════════════════════════════════════════════════════════
- def aggregate_ibs(cache):
- """Compute IBS for all tasks / windows / pairs and resting state.
- Returns
- -------
- results : dict
- results[task][(start_ms, end_ms)][metric]['coop'] → ndarray (n, 95)
- results[task][(start_ms, end_ms)][metric]['other'] → ndarray (n, 95)
- results['resting'][dur_ms][metric]['all'] → ndarray (n, 95)
- """
- tasks = {'decision': 'decision', 'feedback': 'feedback'}
- results = {}
- for task in tasks:
- results[task] = {}
- for win in WINDOWS:
- results[task][win] = {m: {'coop': [], 'other': []}
- for m in ('plv', 'coh')}
- rest_durations = sorted(set(end - start for start, end in WINDOWS))
- results['resting'] = {d: {m: {'all': []} for m in ('plv', 'coh')}
- for d in rest_durations}
- for g in GROUP_IDS:
- score = cache[g]['score'] # (40, 3) 1 = coop
- for task in tasks:
- cleaned = cache[g][task] # (57, n_times, 40)
- for (start_ms, end_ms) in WINDOWS:
- w_start = WIN_ONSET_SMP + ms_to_smp(start_ms)
- w_end = WIN_ONSET_SMP + ms_to_smp(end_ms)
- for sa, sb in PAIRS:
- mask = (score[:, sa] == 1) & (score[:, sb] == 1)
- ea = cleaned[sa * N_CH:(sa + 1) * N_CH]
- eb = cleaned[sb * N_CH:(sb + 1) * N_CH]
- plv_mat, coh_mat = compute_task_ibs(ea, eb, w_start, w_end)
- key = (start_ms, end_ms)
- results[task][key]['plv']['coop'].append(plv_mat[mask])
- results[task][key]['plv']['other'].append(plv_mat[~mask])
- results[task][key]['coh']['coop'].append(coh_mat[mask])
- results[task][key]['coh']['other'].append(coh_mat[~mask])
- for run_idx in range(REST_N_RUNS):
- rest = cache[g]['resting'][run_idx] # (57, 18000)
- for sa, sb in PAIRS:
- ra = rest[sa * N_CH:(sa + 1) * N_CH]
- rb = rest[sb * N_CH:(sb + 1) * N_CH]
- for dur_ms in rest_durations:
- plv_r, coh_r = compute_resting_ibs(ra, rb, ms_to_smp(dur_ms))
- results['resting'][dur_ms]['plv']['all'].append(plv_r)
- results['resting'][dur_ms]['coh']['all'].append(coh_r)
- print(f' G{g:02d} done.', flush=True)
- # Concatenate
- for task in tasks:
- for win in WINDOWS:
- for metric in ('plv', 'coh'):
- for cond in ('coop', 'other'):
- results[task][win][metric][cond] = np.concatenate(
- results[task][win][metric][cond], axis=0)
- for dur_ms in rest_durations:
- for metric in ('plv', 'coh'):
- results['resting'][dur_ms][metric]['all'] = np.concatenate(
- results['resting'][dur_ms][metric]['all'], axis=0)
- return results
- # ══════════════════════════════════════════════════════════════════════════════
- # Cluster-permutation test
- # ══════════════════════════════════════════════════════════════════════════════
- def run_cluster_test(coop, other, win_len_smp):
- adj = get_adjacency(win_len_smp)
- result = hstats.statscondCluster(
- data=[coop, other],
- freqs_mean=FREQS_MEAN,
- ch_con_freq=adj,
- tail=0,
- n_permutations=N_PERMS,
- alpha=0.05,
- )
- pvs = result.cluster_p_values
- min_p = min(pvs) if len(pvs) else 1.0
- n_sig = sum(p < 0.05 for p in pvs)
- return min_p, n_sig, result
- # ══════════════════════════════════════════════════════════════════════════════
- # Figures
- # ══════════════════════════════════════════════════════════════════════════════
- def plot_ibs_bars(results, cluster_stats, output_dir):
- metric_labels = {'plv': 'PLV', 'coh': 'Coherence (ccorr)'}
- tasks = [t for t in results if t != 'resting']
- for metric in ('plv', 'coh'):
- fig, axes = plt.subplots(len(tasks), len(WINDOWS),
- figsize=(5 * len(WINDOWS), 4.5 * len(tasks)),
- sharey='row')
- fig.suptitle(
- f'Inter-Brain Synchrony — {metric_labels[metric]}\n'
- f'Cooperative vs. Other (mean ± SEM, cluster permutation n={N_PERMS})',
- fontsize=12, fontweight='bold')
- x = np.arange(N_BANDS)
- w = 0.35
- band_caps = [b.capitalize() for b in BAND_NAMES]
- for ri, task in enumerate(tasks):
- for ci, (win, win_lbl) in enumerate(zip(WINDOWS, WIN_LABELS)):
- ax = axes[ri, ci]
- coop_bm = _per_band_means(results[task][win][metric]['coop'])
- other_bm = _per_band_means(results[task][win][metric]['other'])
- for bi, band in enumerate(BAND_NAMES):
- c_m, c_s = coop_bm[band]
- o_m, o_s = other_bm[band]
- ax.bar(x[bi] - w/2, c_m, w, color=COND_COLORS['coop'],
- yerr=c_s, capsize=3, error_kw=dict(elinewidth=1),
- label='Cooperative' if bi == 0 else '')
- ax.bar(x[bi] + w/2, o_m, w, color=COND_COLORS['other'],
- yerr=o_s, capsize=3, error_kw=dict(elinewidth=1),
- label='Other' if bi == 0 else '')
- min_p, n_sig = cluster_stats[task][metric][win]['min_p'], \
- cluster_stats[task][metric][win]['n_sig']
- slbl = _sig_label(min_p)
- if min_p < 0.001:
- p_str = f'cluster p < 0.001 {slbl}'
- elif min_p < 0.01:
- p_str = f'cluster p < 0.01 {slbl}'
- elif min_p < 0.05:
- p_str = f'cluster p = {min_p:.3f} {slbl}'
- else:
- p_str = f'cluster p = {min_p:.3f} n.s.'
- color_sig = 'red' if min_p < 0.05 else 'dimgray'
- ax.text(0.98, 0.97, p_str, transform=ax.transAxes,
- ha='right', va='top', fontsize=9, color=color_sig,
- bbox=dict(boxstyle='round,pad=0.3',
- facecolor='white', edgecolor=color_sig, alpha=0.85))
- ax.set_xticks(x)
- ax.set_xticklabels(band_caps, fontsize=10)
- ax.set_title(f'{task.capitalize()} [{win_lbl}]', fontsize=11)
- ax.set_ylabel(metric_labels[metric], fontsize=10)
- ax.spines['top'].set_visible(False)
- ax.spines['right'].set_visible(False)
- if ri == 0 and ci == 0:
- ax.legend(fontsize=8, loc='upper left')
- plt.tight_layout()
- path = os.path.join(output_dir, f'fig_ibs_{metric}.png')
- plt.savefig(path, dpi=200, bbox_inches='tight')
- plt.close()
- print(f' Saved: {os.path.basename(path)}')
- def plot_fstat(cluster_stats, output_dir):
- for task in ('decision', 'feedback'):
- for metric in ('plv', 'coh'):
- sig_wins = [(win, cluster_stats[task][metric][win])
- for win in WINDOWS
- if cluster_stats[task][metric][win]['n_sig'] > 0]
- if not sig_wins:
- continue
- n = len(sig_wins)
- fig, axes = plt.subplots(1, n, figsize=(6 * n, 4.5))
- if n == 1:
- axes = [axes]
- fig.suptitle(f'Cluster F-statistic — {task.capitalize()} {metric.upper()}',
- fontsize=12, fontweight='bold')
- for ax, (win, info) in zip(axes, sig_wins):
- F = info['F_obs'].reshape(N_BANDS, N_CH)
- lim = np.abs(F).max()
- im = ax.imshow(F, aspect='auto', cmap='RdBu_r',
- vmin=-lim, vmax=lim)
- ax.set_xticks(range(N_CH))
- ax.set_xticklabels(CH_NAMES, rotation=90, fontsize=7)
- ax.set_yticks(range(N_BANDS))
- ax.set_yticklabels([b.capitalize() for b in BAND_NAMES], fontsize=9)
- min_p = info['min_p']
- p_str = '< 0.001' if min_p < 0.001 else f'= {min_p:.3f}'
- ax.set_title(f'[{win[0]}-{win[1]} ms] p {p_str}', fontsize=10)
- plt.colorbar(im, ax=ax, fraction=0.046, label='F-statistic')
- plt.tight_layout()
- path = os.path.join(output_dir, f'fig_fstat_{task}_{metric}.png')
- plt.savefig(path, dpi=200, bbox_inches='tight')
- plt.close()
- print(f' Saved: {os.path.basename(path)}')
- # ══════════════════════════════════════════════════════════════════════════════
- # CSV export
- # ══════════════════════════════════════════════════════════════════════════════
- def export_csv(results, cluster_stats, output_dir):
- import csv
- rows = []
- for task in ('decision', 'feedback'):
- for win in WINDOWS:
- win_lbl = f'{win[0]}-{win[1]}ms'
- for metric in ('plv', 'coh'):
- info = cluster_stats[task][metric][win]
- coop_bm = _per_band_means(results[task][win][metric]['coop'])
- other_bm = _per_band_means(results[task][win][metric]['other'])
- for bi, band in enumerate(BAND_NAMES):
- c_m, c_s = coop_bm[band]
- o_m, o_s = other_bm[band]
- diff = c_m - o_m
- nc = results[task][win][metric]['coop'].shape[0]
- no = results[task][win][metric]['other'].shape[0]
- ca = results[task][win][metric]['coop'][:, bi*N_CH:(bi+1)*N_CH].mean(axis=1)
- oa = results[task][win][metric]['other'][:, bi*N_CH:(bi+1)*N_CH].mean(axis=1)
- pool = np.sqrt(((nc-1)*ca.std(ddof=1)**2 + (no-1)*oa.std(ddof=1)**2) / (nc+no-2))
- rows.append({
- 'task': task, 'window': win_lbl, 'metric': metric, 'band': band,
- 'coop_mean': f'{c_m:.6f}', 'coop_sem': f'{c_s:.6f}',
- 'other_mean': f'{o_m:.6f}', 'other_sem': f'{o_s:.6f}',
- 'diff': f'{diff:.6f}',
- 'cohens_d': f'{diff / (pool + 1e-12):.4f}',
- 'cluster_p': f'{info["min_p"]:.4f}',
- 'n_sig_clusters': info['n_sig'],
- 'sig': _sig_label(info['min_p']),
- })
- path = os.path.join(output_dir, 'stats_ibs_by_band.csv')
- with open(path, 'w', newline='') as f:
- w = csv.DictWriter(f, fieldnames=rows[0].keys())
- w.writeheader(); w.writerows(rows)
- print(f' Saved: {os.path.basename(path)}')
- # ══════════════════════════════════════════════════════════════════════════════
- # CLI
- # ══════════════════════════════════════════════════════════════════════════════
- def parse_args():
- p = argparse.ArgumentParser(description='Hyperscanning IBS analysis')
- p.add_argument('--cache', default=_CACHE,
- help='Path to cleaned_eeg.pkl from preprocess.py')
- p.add_argument('--output_dir', default=_OUTPUT_DIR,
- help='Directory to write figures and CSVs')
- return p.parse_args()
- def main():
- args = parse_args()
- os.makedirs(args.output_dir, exist_ok=True)
- print('=== IBS Analysis ===')
- print(f' cache : {args.cache}')
- print(f' output_dir : {args.output_dir}')
- print('\n[1/4] Loading preprocessed cache...')
- with open(args.cache, 'rb') as f:
- cache = pickle.load(f)
- print('\n[2/4] Computing IBS (PLV + Coherence)...')
- results = aggregate_ibs(cache)
- with open(os.path.join(args.output_dir, 'ibs_data.pkl'), 'wb') as f:
- pickle.dump(results, f)
- print('\n[3/4] Cluster-permutation tests...')
- cluster_stats = {}
- for task in ('decision', 'feedback'):
- cluster_stats[task] = {'plv': {}, 'coh': {}}
- for (start_ms, end_ms) in WINDOWS:
- win = (start_ms, end_ms)
- win_smp = ms_to_smp(end_ms - start_ms)
- for metric in ('plv', 'coh'):
- coop = results[task][win][metric]['coop']
- other = results[task][win][metric]['other']
- print(f' {task} [{start_ms}-{end_ms}ms] {metric.upper()}'
- f' coop n={coop.shape[0]}, other n={other.shape[0]}',
- flush=True)
- min_p, n_sig, result = run_cluster_test(coop, other, win_smp)
- print(f' min_p = {min_p:.4f} n_sig = {n_sig} {_sig_label(min_p)}')
- cluster_stats[task][metric][win] = {
- 'min_p': min_p, 'n_sig': n_sig,
- 'F_obs': result.F_obs_plot,
- }
- with open(os.path.join(args.output_dir, 'cluster_stats.pkl'), 'wb') as f:
- pickle.dump(cluster_stats, f)
- print('\n[4/4] Figures and CSV...')
- plot_ibs_bars(results, cluster_stats, args.output_dir)
- plot_fstat(cluster_stats, args.output_dir)
- export_csv(results, cluster_stats, args.output_dir)
- print('\nDone.')
- if __name__ == '__main__':
- main()
ibs_analysis.py at commit 0862853, no license · at the source
Overview
- Department of AI Convergence, Gwangju Institute of Science and Technology, Gwangju, 61005, South Korea
- Center of Excellence in Product Design and Advanced Manufacturing, North Carolina A&T State University, Greensboro, NC, 27411, USA
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=
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
0862853f1095404db1f4df04f7c5ac17d8da3865, 15 July 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
7 files
- pd_eeg_analysis/
erp_analysis.py , Python, 422 lines - pd_eeg_analysis/
ibs_analysis.py , Python, 531 lines, 5 matches - pd_eeg_analysis/
preprocess.py , Python, 240 lines, 1 match - pd_eeg_analysis/
preprocess_bids.py , Python, 160 lines - pd_eeg_analysis/
preprocessing_core.py , Python, 106 lines - pd_eeg_analysis/
run_all.py , Python, 72 lines - README.md, Text, 66 lines
Code availability
The analysis code is available at: https://
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/
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=
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
- doi:10.18112/
openneuro.ds007822.v1.0. , at OpenNeuro; found in “Data availability”0 - doi:10.18112/
openneuro.ds007822.v1.0. , at OpenNeuro; found in the resources table0direct
Data Availability Statement
The dataset is publicly available on OpenNeuro (DOI: https://
FigshareEEG and Hyperscanning, triadic Prisoner's dilemma game (Original data) (https://
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://
BibTeX
@article{kim2026reproduc
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/
url = {https://
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/
VL - 68
SP - 113064
SN - 2352-3409
PB - Elsevier
DO - 10.1016/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1016/
"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":
"volume": "68",
"page": "113064",
"DOI": "10.1016/
"PMID": "42541318",
"PMCID": "PMC13427532",
"ISSN": "2352-3409",
"publisher": "Elsevier",
"URL": "https://
"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.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
- [2] doi:10.1097/j.pain.0000000000004044 [code]
- No effect of rhythmic visual stimulation on experimental pain perception.Journal: PainIn common: ICLabel, MNE-Python, pandas, 3 other tools, EEG, 2 references
- [3] doi:10.3758/s13428-026-02997-z [code]
- PyLossless: A non-destructive EEG processing pipeline.Journal: Behavior research methodsIn common: ICLabel, MNE-Python, pandas, 2 other tools, methods / tools, EEG, 2 references
- [4] doi:10.1038/s41597-025-05174-7 [code]
- A large-scale MEG and EEG dataset for object recognition in naturalistic scenesJournal: n/aIn common: ICLabel, MNE-Python, pandas, 3 other tools, methods / tools, EEG, 1 reference
- [5] doi:10.1002/hbm.70528 [code]
- Explainable AI Insights Into EEG Classification and Its Alignment to Neural Correlates.Journal: Human brain mappingIn common: ICLabel, MNE-Python, pandas, 3 other tools, EEG, 1 reference
- [6] doi:10.3390/s26134019 [code]
- NeuroStat: An Open-Source EEG Connectivity Platform for Randomised Controlled Trials.Journal: Sensors (Basel, Switzerland)In common: ICLabel, MNE-Python, pandas, 3 other tools, EEG, 1 reference
- [7] doi:10.1038/s41597-026-07807-x [code]
- A Multimodal fNIRS-EEG Dataset for Unilateral Limb Motor Imagery.Journal: Scientific dataIn common: ICLabel, MNE-Python, SciPy, 2 other tools, methods / tools, EEG, 1 reference
- [8] doi:10.1038/s41597-026-07146-x [code]
- Intention-Action Conflict EEG-Hand Kinematics Dataset for Unimanual Control under Congruent and Incongruent Conditions.Journal: Scientific dataIn common: ICLabel, MNE-Python, pandas, 3 other tools, methods / tools, EEG
- [9] doi:10.1186/s12967-026-08108-y [code]
- An explainable multimodal machine learning model for diagnosing disorders of consciousness: evidence from a large multicenter Chinese cohort.Journal: Journal of translational medicineIn common: ICLabel, MNE-Python, pandas, 2 other tools, EEG, 1 reference
- [10] doi:10.1002/hbm.70628 [code]
- EEG Biomarkers for Affective Disorders Diagnosis: An Evaluation and Validation Study.Journal: Human brain mappingIn common: ICLabel, MNE-Python, pandas, 3 other tools, EEG
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.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 6 scripts, and 6 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:6134a6aa4360486d…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
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: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
