Overview: The Biophysics of Electroencephalography
Electroencephalography (EEG) is a non-invasive neuroimaging technique that records the electrical activity generated by the brain. It is an indispensable tool in both clinical neurology and cognitive neuroscience, offering millisecond-level temporal resolution to capture highly transient cortical dynamics. The macroscopic signals acquired via scalp electrodes primarily reflect the spatial summation of synchronized postsynaptic potentials (PSPs) originating from pyramidal neurons located in the cerebral cortex. Because these neurons are oriented perpendicularly to the cortical surface, their synchronized activation establishes robust current dipoles. However, measuring these microvolt-level signals on the scalp is intrinsically difficult due to volume conduction. The signals must pass through multiple distinct biological layers—the cerebrospinal fluid (CSF), meninges, thick cranial bone, and scalp tissue—each possessing highly divergent electrical conductivities. This multi-layered filtering essentially acts as a low-pass spatial filter, smearing the spatial topography and significantly attenuating high-frequency components.
To map these complex spatial dynamics, standard configurations like the International 10-20 system are employed. The nomenclature specifies electrode placements using relative cranial landmarks (nasion, inion, pre-auricular points) to ensure high reproducibility across subjects of varying skull geometries. The temporal domain of the resulting signal is traditionally decomposed into well-established frequency bands, each correlating with specific neurophysiological or behavioral states: Delta (0.5 – 4 Hz) dominates during deep non-REM slow-wave sleep and is generated largely by thalamocortical oscillations; Theta (4 – 8 Hz) is prominent during drowsiness, deep meditation, and memory encoding within the hippocampus; Alpha (8 – 13 Hz) serves as the fundamental idling rhythm of the visual cortex, dominating posterior regions during relaxed wakefulness with closed eyes; Beta (13 – 30 Hz) manifests over motor and frontal regions during active concentration, conscious problem solving, and motor execution; and finally, Gamma (30 – 100+ Hz) represents high-level cognitive processing, sensory binding, and cross-modal synchronization.
How to Use: The Diagnostic Simulation Interface
The interactive laboratory provided in the workspace above serves as a real-time signal generation and spectral analysis terminal. By manipulating the Frequency Band Parameters within the collapsible right-side diagnostic panel, you can manually construct a synthetic EEG waveform in real-time. The top half of the visualizer canvas operates as an oscilloscope, continuously plotting the composite time-domain signal $y(t)$ generated by summing the weighted contributions of the Delta, Theta, Alpha, Beta, and Gamma frequency bands. The bottom half renders a high-contrast Power Spectral Density (PSD) bar chart, mapping the instantaneous amplitudes back to their respective frequency bins, simulating standard Fast Fourier Transform (FFT) analysis.
To initiate an automated, sequential demonstration of standard neurological states, engage the Start Demo button situated at the pinnacle of the control hierarchy. Once triggered, the internal state machine overrides manual input, automatically sweeping the parameters to simulate transitions from deep slow-wave sleep (high Delta), through relaxed wakefulness (high Alpha), into high-alert cognitive processing (high Beta and Gamma). The demo mode is strictly interruptible; manipulating any slider or explicitly interacting with the canvas will instantly snap the system back to the pre-recorded user baseline state, relinquishing absolute manual control. The Reset Baseline button acts as a failsafe, instantaneously flushing all runtime modifications and restoring the precise band power distributions derived natively from the MNE-Python `sample_audvis_raw.fif` baseline processing script.
Additionally, this module features a heavily optimized Web Audio API binaural synthesizer. Activating the Sound ON toggle injects a continuous fundamental carrier frequency (250 Hz) into the left channel, while simultaneously modulating the right channel utilizing the currently dominant EEG frequency band. This generates a phase-interfering binaural beat inside the user’s auditory cortex that perfectly mirrors the dynamic frequency tracking of the visual simulation.
Technical Details: Signal Processing & Spectral Extraction
Extracting usable, low-variance frequency components from raw, noisy EEG streams requires sophisticated digital signal processing. The fundamental baseline data driving this application was computed via Multitaper Spectral Analysis using the `mne.time_frequency.psd_array_multitaper` library module. Unlike standard periodograms which suffer from high spectral leakage and variance, the multitaper method applies a series of orthogonal data tapers known as Discrete Prolate Spheroidal Sequences (DPSS or Slepian functions). The power spectral density (PSD) estimate $S(f)$ is determined by averaging the individual tapered spectra:
$$ S(f) = \frac{1}{K} \sum_{k=1}^{K} \left| \sum_{t=1}^{N} x_t w_{t,k} e^{-2\pi i f t} \right|^2 $$
Here, $K$ represents the total number of orthogonal tapers utilized, $x_t$ represents the time-series EEG data, and $w_{t,k}$ represents the $k$-th Slepian data taper. Once the smooth, low-variance continuous spectrum is established, the absolute band power is extracted by applying a numerical integration across the specified frequency boundary $[f_{\text{min}}, f_{\text{max}}]$ using the trapezoidal rule:
$$ P_{\text{band}} = \int_{f_{\text{min}}}^{f_{\text{max}}} S(f) \, df \approx \sum_{j=0}^{M-1} \frac{S(f_{j+1}) + S(f_j)}{2} \Delta f $$
Following feature extraction, the original architectural script mapped these five scalar band values (Delta, Theta, Alpha, Beta, Gamma) into feature vectors for machine learning classification. The data was subjected to standard $Z$-score normalization $Z = \frac{X - \mu}{\sigma}$ to prevent variance bias before being passed into a Support Vector Machine (SVM). The SVM utilized 5-fold Stratified Cross-Validation combined with a `GridSearchCV` hyperparameter tuning matrix to dynamically identify the optimal penalty parameter $C$ and kernel type. For a strictly linear kernel, the algorithm seeks to optimize the separating hyperplane defined by:
$$ \min_{w, b} \frac{1}{2} ||w||^2 + C \sum_{i=1}^{n} \xi_i $$
subject to the margin constraints $y_i(w \cdot x_i + b) \geq 1 - \xi_i$. The resultant model perfectly isolated auditory/left vs auditory/right stimulus responses based solely on the structural variations observed in regional band power geometry.
Original Python Processing Pipeline Reference:
import numpy as np
import mne
from mne.time_frequency import psd_array_multitaper
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold, GridSearchCV
from sklearn.preprocessing import StandardScaler
import json
# Load standard MNE visual/auditory dataset
raw_file = mne.datasets.sample.data_path() / 'MEG' / 'sample' / 'sample_audvis_raw.fif'
raw = mne.io.read_raw_fif(raw_file, preload=True)
raw.filter(l_freq=0.1, h_freq=50)
# Epoch events and structure Multitaper PSD
events = mne.find_events(raw, stim_channel='STI 014')
event_ids = {'auditory/left': 1, 'auditory/right': 2}
epochs = mne.Epochs(raw, events, event_id=event_ids, tmin=-0.2, tmax=0.5, preload=True)
data_reshaped = epochs.get_data().reshape(len(epochs) * len(raw.ch_names), len(epochs.times))
psds, freqs = psd_array_multitaper(data_reshaped, sfreq=epochs.info['sfreq'], adaptive=False)
psds = psds.reshape(len(epochs), len(raw.ch_names), -1)
# Extract Frequency Band Features via Integration
feature_list = []
for psd in psds:
d = np.trapz(psd[:, (freqs >= 0.5) & (freqs <= 4)].mean(axis=0))
t = np.trapz(psd[:, (freqs >= 4) & (freqs <= 8)].mean(axis=0))
a = np.trapz(psd[:, (freqs >= 8) & (freqs <= 13)].mean(axis=0))
b = np.trapz(psd[:, (freqs >= 13) & (freqs <= 30)].mean(axis=0))
g = np.trapz(psd[:, (freqs >= 30) & (freqs <= 40)].mean(axis=0))
feature_list.append([d, t, a, b, g])
# Execute Support Vector Machine Optimization Grid
X = StandardScaler().fit_transform(feature_list)
labels = [e[2] for e in events if e[2] in [1, 2]][:len(epochs)]
clf = GridSearchCV(SVC(class_weight='balanced'), {'C': [0.1, 1, 10], 'kernel': ['linear', 'rbf']}, cv=5)
clf.fit(X, labels)
# Export Normalized Baseline Data for UI Rendering
average_band_powers = np.mean(feature_list, axis=0)
bands = ['delta', 'theta', 'alpha', 'beta', 'gamma']
data_to_export = [{'band': b, 'value': v} for b, v in zip(bands, average_band_powers)]
with open('eeg_band_powers.json', 'w') as f:
json.dump(data_to_export, f)