This chapter specifies, in reproducible detail, how the recorded signals — scalp EEG and continuous heart rate — are transformed into the two dependent constructs the study is built to measure: attention (the allocation of processing resources) and automaticity (the same task performed with less controlled effort). Each analysis condition is recorded pre and post nine-square training across four tasks — Baseline, Flanker, Go/NoGo, and 9-square movement — and every method below maps onto a specific, pre-registrable prediction. All code is a working MNE-Python skeleton against published, standard pipelines; nothing is invented.
00Mapping data to theoretical structure
แผนที่ข้อมูล → โครงสร้างเชิงทฤษฎี — ส่วนที่สำคัญที่สุด อ่านก่อน. The dependent variable is not one quantity but two dissociable ones. Attention and automatic response are distinct mechanisms, measured by different signals in different conditions, and they can move in opposite directions after training. Fixing this mapping first is what keeps every later statistical test interpretable.
| Construct | Measured in | Primary indices | Predicted direction (post 9-square) |
|---|---|---|---|
| Attention (allocation / effort) | Baseline · Flanker · Go/NoGo | P3/P300 amplitude (Pz/Cz), frontal-midline theta (Fz), parietal alpha desynchronisation | P3↑ or theta↑ as resources are allocated more effectively (framework-dependent) |
| Automaticity (automatic processing) | pre→post of conflict trials (incongruent, NoGo) | N2↓ · conflict-theta↓ · P3 latency↓ together with RT↓ + RT-variability↓ + accuracy stable/better | smaller frontal control signal, yet performance is as fast and accurate — “more automatic” |
Operational definition — the heart of the thesisหัวใจของ thesis: automaticity is declared only when several conditions hold simultaneously, never from a single index. After training, on the same conflict task, N2 and/or frontal-midline theta decrease and P3 latency shortens, while RT gets faster, RT variability falls, and accuracy / d′ do not drop. That joint pattern — “อัตโนมัติขึ้น” — is what separates genuine automatisation from merely getting better (accuracy↑ with effort unchanged).
The supporting theory is explicit: automaticity is a reduction in controlled processing, which lowers the conflict-monitoring signal generated near anterior cingulate cortex (N2 / frontal-midline theta) and lowers resource cost (P3). This follows Shiffrin & Schneider (controlled vs. automatic processing), Botvinick's conflict-monitoring account, and Cavanagh & Frank's demonstration that frontal-midline theta is a mechanism of cognitive control.
| Pre-training | Post-training | |
|---|---|---|
| Baseline eyes-open rest |
spectral θ/α1/fHRV rest |
spectral θ/α1/fHRV rest |
| Flanker cong / incong |
N2P3FM-θHRV |
N2P3FM-θHRV |
| Go/NoGo go / nogo |
N2P3ERNHRV |
N2P3ERNHRV |
| 9-square movement |
θ/α power*mean HR *ASR-cleaned · exploratory |
θ/α power*mean HR *intensity covariate |
01Preprocessing — one standard pipeline for every condition
“Makoto-style” pipeline. Order matters, and the same recipe is applied identically to all conditions so that any pre→post difference cannot be an artefact of differential cleaning. The canonical sequence is:
filter → record bad channels → ICA (high-pass 1 Hz) → ICLabel reject → interpolate → re-reference → epoch → reject / ASR
import mne
from mne.preprocessing import ICA
import numpy as np
# 1.1 โหลด (ปรับ reader ตามเครื่อง: BrainVision .vhdr / EDF / EEGLAB .set)
raw = mne.io.read_raw_brainvision("subj01_pre_flanker.vhdr", preload=True)
raw.set_montage("standard_1020", on_missing="warn")
# 1.2 Filter — ไฟบ้านไทย 50 Hz (notch), band 0.1–40 Hz สำหรับ ERP
raw.notch_filter(50.0)
raw_erp = raw.copy().filter(0.1, 40.0, fir_design="firwin")
# 1.3 ICA ต้อง high-pass 1 Hz (ICA เกลียด drift) แล้ว "ยก" solution ไปใช้กับสัญญาณ 0.1 Hz
raw_ica = raw.copy().filter(1.0, 40.0)
ica = ICA(n_components=0.99, method="picard", max_iter="auto", random_state=97)
ica.fit(raw_ica)
# 1.4 จัด component อัตโนมัติด้วย ICLabel (แทนการเดา) — ตัด eye/muscle/heart/line
from mne_icalabel import label_components
labels = label_components(raw_ica, ica, method="iclabel")
bad_ic = [i for i, (lab, p) in enumerate(zip(labels["labels"], labels["y_pred_proba"]))
if lab in ("eye blink", "muscle artifact", "heart beat", "line noise", "channel noise") and p > 0.8]
ica.exclude = bad_ic
ica.apply(raw_erp) # ใช้กับสัญญาณ ERP (0.1 Hz)
# 1.5 bad channels → interpolate → average reference (report ทั้ง 2 อย่างในเล่ม)
# raw_erp.info["bads"] = [...] # จากการตรวจ/มาตรฐาน (เช่น PREP pipeline)
raw_erp.interpolate_bads(reset_bads=True)
raw_erp.set_eeg_reference("average", projection=False) # หรือ linked-mastoid TP9/TP10
mne-icalabel classifies components automatically (p > 0.8) rather than by eye.Report in the Methods chapter — for reproducibilityรายงานให้ reproducible: the number of bad channels per participant, the number of ICs removed and the ICLabel criterion, the reference used, and the number of surviving epochs — following ARTEM-IS / ERP reporting standards.
1.6EEG during 9-square movement — the hardest problem
จุดยากที่สุด — ต้องมีแผนชัด. Vigorous stepping injects heavy motion, EMG, and electrode-cable artifact. Reading EEG “while moving” at face value is not credible; the plan is an explicit three-layer defence:
# (A) ASR — ลบ transient burst artifact โดยไม่ทิ้งทั้ง epoch (ก่อนหรือแทน reject แข็ง) import asrpy asr = asrpy.ASR(sfreq=raw_erp.info["sfreq"], cutoff=20) # cutoff 15–30 (ยิ่งต่ำยิ่ง aggressive) asr.fit(raw_erp.copy().filter(1., 40.)) # fit บนช่วง "สะอาด" (baseline) raw_move = asr.transform(raw_move_raw)
- (A) ASR (
asrpy/clean_rawdatain EEGLAB) — reconstructs burst segments, keeping more data than rejection. - (B) Restrict to low frequencies and frontal-midline channels — theta/alpha at Fz/FCz tolerate EMG far better than beta/gamma at the rim — and interpret power only, not ERPs, during movement.
- (C) Report the proportion of epochs / time discarded transparently and treat movement-EEG as secondary / exploratory.
- The confirmatory results come from the clean pairs: Baseline (rest) and seated Flanker / Go-NoGo, compared pre↔post. Movement is corroborative.
02Spectral power & the aperiodic–periodic split
For Baseline and 9-square, band power indexes attention and arousal. Welch PSD is computed on overlapping fixed-length epochs; power is expressed in decibels because that is more robust to outliers than raw µV². Absolute band power is complemented by relative band power (each band normalised by total) to remove global scale differences between sessions.
epochs = mne.make_fixed_length_epochs(raw, duration=2.0, overlap=1.0, preload=True)
spec = epochs.compute_psd(method="welch", fmin=1, fmax=45, n_fft=int(2*epochs.info["sfreq"]))
psds, freqs = spec.get_data(return_freqs=True) # (n_epochs, n_ch, n_freqs)
psds_db = 10*np.log10(psds) # dB — ทน outlier กว่า raw µV²
bands = {"delta":(1,4),"theta":(4,8),"alpha":(8,13),"beta":(13,30),"gamma":(30,45)}
def bp(lo,hi):
idx=(freqs>=lo)&(freqs<hi); return psds[...,idx].mean(-1)
abs_bp={b:bp(lo,hi) for b,(lo,hi) in bands.items()}
total=sum(abs_bp.values()); rel_bp={b:abs_bp[b]/total for b in bands} # relative = ตัดสเกลรวม
ch=epochs.ch_names; Fz=ch.index("Fz"); Pz=ch.index("Pz")
fm_theta = abs_bp["theta"][:,Fz].mean() # frontal-midline theta = control/effort
parietal_alpha = abs_bp["alpha"][:,Pz].mean() # alpha↓ = engagement มากขึ้น
2.1Separating aperiodic 1/f from true oscillations
สำคัญกับ theta/beta ratio. A change in “theta power” or the theta/beta ratio can be driven entirely by the 1/f aperiodic slope rather than a genuine oscillation. Parameterising the spectrum with specparam (FOOOF) splits the two — an aperiodic component (offset + exponent, the 1/f steepness) and periodic peaks (centre frequency, power, bandwidth) — so an “attention change” can be correctly attributed to an oscillation versus broadband arousal.
from specparam import SpectralModel
sm = SpectralModel(peak_width_limits=[1,8], max_n_peaks=6)
sm.fit(freqs, psds[:, Fz, :].mean(0), [1,45])
# แยก: aperiodic (offset, exponent = ความชัน 1/f) ↔ periodic peaks (theta/alpha center, power, bandwidth)
theta_peak = sm.get_params("peak_params") # เอา oscillation จริง ไม่ปนกับ 1/f
03ERP — Flanker & Go/NoGo
The event-related potentials are the study's most powerful axis for both attention and automaticity. Epochs are cut −200 to +800 ms around stimulus onset, baseline-corrected on the pre-stimulus interval, and — critically — only correct-response trials are averaged for the standard N2/P3, so component amplitudes are not contaminated by error processing.
events, event_id = mne.events_from_annotations(raw_erp)
epochs = mne.Epochs(raw_erp, events, event_id, tmin=-0.2, tmax=0.8,
baseline=(-0.2, 0.0), reject=dict(eeg=120e-6), preload=True)
# เฉลี่ยเฉพาะ trial ที่ตอบถูก (correct-only) สำหรับ N2/P3 ปกติ
erp_cong = epochs["flanker/congruent/correct"].average()
erp_incong = epochs["flanker/incongruent/correct"].average()
erp_go = epochs["go/correct"].average()
erp_nogo = epochs["nogo/correct"].average()
task/condition/accuracy) let each cell be averaged with one selector. A 120 µV peak-to-peak reject rule removes residual gross artifacts after ICA.Components to extract (Cai et al. 2025 scoping review: P3 dominates the field with 43 studies, N2 with 17):
| Component | Window | Site | Meaning | Answers |
|---|---|---|---|---|
| N2 | 200–350 ms | FCz/Fz | conflict monitoring / inhibition | Flanker-incong, NoGo → automaticity: N2↓ post |
| P3/P300 | 300–600 ms | Pz (P3b)/Cz | resource allocation | attention: amplitude; NoGo-P3 = inhibition success |
| ERN/Ne · Pe | 0–150 ms post-error | FCz/Cz | error detection / awareness | error monitoring, adaptive control |
def mean_amp(evoked, ch, tmin, tmax): # mean amplitude = ทน noise > peak
return evoked.copy().pick([ch]).crop(tmin,tmax).data.mean()
def peak(evoked, ch, tmin, tmax, mode):
_,lat,amp = evoked.copy().pick([ch]).get_peak(tmin=tmin,tmax=tmax,mode=mode,return_amplitude=True)
return amp, lat
p3_incong = mean_amp(erp_incong,"Pz",0.30,0.60); n2_incong = mean_amp(erp_incong,"FCz",0.20,0.35)
p3_nogo = mean_amp(erp_nogo, "Pz",0.30,0.60); n2_nogo = mean_amp(erp_nogo, "FCz",0.20,0.35)
_,p3_lat = peak(erp_incong,"Pz",0.30,0.60,"pos") # latency = ความเร็วประมวลผล (automaticity)
3.1Difference waves — isolating the conflict/inhibition signal
Subtracting the easy from the hard condition cancels the shared sensory response and leaves the pure conflict/inhibition signal, which is the most direct pre↔post contrast.
flanker_diff = mne.combine_evoked([erp_incong, erp_cong], weights=[1,-1]) # incong − cong nogo_diff = mne.combine_evoked([erp_nogo, erp_go], weights=[1,-1]) # NoGo − Go n2_conflict = mean_amp(flanker_diff,"FCz",0.20,0.35) # N2-conflict effect p3_nogo_eff = mean_amp(nogo_diff, "Cz", 0.30,0.60) # NoGo-P3 inhibition effect
04Time-frequency — conflict theta & ITC
Complementing the ERP, Morlet time-frequency decomposition recovers the frontal-midline theta burst that the averaged waveform partly hides, plus inter-trial coherence. Power is baseline-corrected as a log-ratio; the analysis window is the canonical FCz theta band, 4–8 Hz, 200–500 ms.
freqs = np.arange(3,31,1); n_cycles = freqs/2.
tfr = epochs["flanker/incongruent/correct"].compute_tfr(
method="morlet", freqs=freqs, n_cycles=n_cycles, return_itc=True, average=True)
power, itc = tfr
power.apply_baseline((-0.2,0.0), mode="logratio") # baseline-correct (dB-like)
# frontal-midline theta (4–8 Hz, 200–500 ms) ที่ FCz = conflict theta
fmt = power.copy().pick(["FCz"]).crop(0.2,0.5,fmin=4,fmax=8).data.mean()
fmt_itc = itc.copy().pick(["FCz"]).crop(0.2,0.5,fmin=4,fmax=8).data.mean() # phase-locking
Automaticity read-out: conflict-theta decreasing after training (less control engaged) is consistent with, and corroborates, the N2 decrease.
05Heart rate & HRV — an autonomic index of effort
Heart-rate variability indexes attentional effort / cognitive load through the neurovisceral integration model (Thayer & Lane): higher vagal / HF-HRV tracks better self-regulation. HRV is computed per condition × pre/post from the ECG (or PPG) R-peaks with NeuroKit2.
import neurokit2 as nk signals, info = nk.ecg_process(ecg_raw, sampling_rate=1000) # หรือ nk.ppg_process ถ้าเป็น PPG # ต่อ "เงื่อนไข" — segment ตาม event ของแต่ละ task แล้วคำนวณ HRV แยก hrv = nk.hrv(info["ECG_R_Peaks"], sampling_rate=1000, show=False) # ดัชนีหลัก: HRV_RMSSD, HRV_SDNN (overall/vagal) · HRV_HF, HRV_LF, HRV_LFHF (autonomic balance) · mean HR
- Compute HRV separately for every condition × pre/post: Baseline · Flanker · Go/NoGo · 9-square.
- 9-square: use mean HR as exercise intensity (%HRmax = HR/(220−age)) as a covariate / manipulation check.
- Confound to control: respiration rate influences HF-HRV — if recorded, report or covary it.
- Contrasts: Baseline↔task (HRV falls under effort) and pre↔post — if automaticity increases, the same task costs less effort, so HRV falls less: converging autonomic evidence.
06Statistics — linking EEG ↔ heart ↔ behaviour
The core design is 2 (Time: pre/post) × Condition. Because the data are trial-level, a linear mixed model is preferred to a subject-mean rmANOVA — it uses every trial and models per-subject random slopes of time.
import pingouin as pg # หรือ statsmodels / lme4 ใน R
# rmANOVA (subject-level means)
aov = pg.rm_anova(dv="P3_amp", within=["time","condition"], subject="subj", data=df, detailed=True)
# LMM (trial-level, แนะนำ)
import statsmodels.formula.api as smf
m = smf.mixedlm("P3_amp ~ time*condition", df, groups=df["subj"],
re_formula="~time").fit() # random slope ของ time ต่อ subject
time*condition fixed, random slope of time per subject) is the recommended trial-level analysis.Controlling multiple comparisons across EEG — the gold standard is cluster-based permutation, which needs no a-priori choice of window or channel. The cluster statistic sums the per-sample t within a supra-threshold cluster and compares it to a null built by permutation:
from mne.stats import permutation_cluster_1samp_test # X = post − pre ต่อ subject, shape (n_subj, n_times[, n_ch]) → หา cluster ที่ต่างจาก 0 T_obs, clusters, p, _ = permutation_cluster_1samp_test(X, n_permutations=5000, tail=0, seed=42)
Behaviour & brain–behaviour coupling
Behaviour: RT (correct), accuracy, RT variability (SD/CV), d′ (Go/NoGo sensitivity), the Flanker effect (incong−cong RT), and post-error slowing.
Linking EEG↔behaviour: correlate Δ(N2/P3/theta) with Δ(RT / RT-CV / d′) to test whether a change in the wave explains the change in behaviour (mediation is available). Effect size & certainty: report partial η² / Cohen's dz with 95% CIs; consider Bayesian tests (JASP / pingouin.ttest(...bayesian)) to support the null (e.g. accuracy genuinely unchanged = accuracy really was held constant); and estimate power / sample size in advance.
6.1The operational “became automatic” decision framework
ต้องเข้าครบ ไม่ใช่ตัวเดียว. Automaticity is declared only if the pattern is joint. This is the pre-registrable rule the whole methodology exists to test:
- RT faster (Δ<0) and RT variability (CV) lower.
- N2 and/or conflict-theta decrease in the hard condition (difference wave).
- P3 latency shortens (and/or amplitude shifts per framework).
- Accuracy / d′ hold or improve — not fast-because-careless; the speed–accuracy trade-off must not be spent.
- (supporting) HRV falls less on the same task = reduced autonomic effort.
Decision ruleCriteria 1–4 met (plus 5) ⇒ automaticity, not merely a performance improvement. Any single index moving alone is insufficient and is reported as such.
§Method references
งานจริง — resolve DOI ยืนยันก่อนลงเล่ม. Every DOI below is resolved and quartile-joined by the harvester before final submission; classic entries are flagged for a resolve-check.
Confirmed (3-vote)
- Griggs, M.A., Parr, B., Vandegrift, N.S., & Jelsone-Swain, L. (2023). The effect of acute exercise on attentional control and theta power in young adults. Experimental Brain Research, 241(10), 2509–2520. DOI 10.1007/s00221-023-06660-3 · PMID 37670008 — template: exercise + Flanker + EEG theta.
Sourced (DOI/PMID; re-check)
- Cai et al. (2025). A scoping review of effects of acute exercise on executive function: evidence from ERPs. Frontiers in Psychology. DOI 10.3389/fpsyg.2025.1599861 — P3 43 studies · N2 17.
- Hosang et al. (2022). Effects of exercise on EEG neural oscillations: systematic review. Int. Review of Sport & Exercise Psychology. DOI 10.1080/1750984X.2022.2103841.
- Liu et al. (2025). Physical activity, P300 & prefrontal theta during Flanker. Front. Hum. Neurosci. DOI 10.3389/fnhum.2025.1591458.
- Coordinative Ability Training → adolescents' cognition (2021). Front. Psychol. PMID 33584480 · DOI 10.3389/fpsyg.2021.620440.
Standard method / theory (classic — verify DOI before use)
- Polich (2007). Updating P300: an integrative theory of P3a/P3b. Clin. Neurophysiol. — P300.
- Folstein & Van Petten (2008). Influence of cognitive control on the N2. Psychophysiology — N2.
- Cavanagh & Frank (2014). Frontal theta as a mechanism for cognitive control. Trends Cogn. Sci. — FM-theta.
- Botvinick et al. (2001). Conflict monitoring and cognitive control. Psychol. Review — conflict / N2 framework.
- Thayer & Lane (2000/2009). Neurovisceral integration — HRV ↔ attention / self-regulation.
- Gramfort et al. (2013). MEG/EEG analysis with MNE-Python. Front. Neurosci. — MNE.
- Mullen et al. (2015). Real-time neuroimaging & ASR. IEEE TBME — ASR (movement artifact).
- Donoghue et al. (2020). Parameterizing neural power spectra (FOOOF/specparam). Nat. Neurosci. — aperiodic vs. oscillation.
- Pion-Tonachini et al. (2019). ICLabel — automatic IC classification. NeuroImage.
!Integrity note
หมายเหตุความซื่อสัตย์ — honesty note
- In-motion EEG (9-square) is the hardest signal — the confirmatory results are the pre/post contrasts of resting + seated tasks; movement-EEG is secondary/exploratory with limitations stated plainly.
- Some classic DOIs/quartiles are cited from standard knowledge — the harvester (
harvest.py) resolves every DOI and joins the real quartile before submission.- The code is a skeleton — trigger names, channel labels, file format and sampling rate must match the actual recording rig, and reject thresholds / ICA settings must be tuned to signal quality.
- Pre-register + BIDS: where possible, pre-register the hypotheses and the operational definition of automaticity, and organise the data as EEG-BIDS for reproducibility.
● Methods grounded in published work and standard pipelines (MNE-Python · EEGLAB · NeuroKit2) — no fabricated numbers or DOIs. Companion to the reference library. thesis.globmaps.com · expanded 2026-07-23.