Web Simulation 

 

 

 

 

EEG Brain State Visualizer 

This note provides an interactive, visual simulation of EEG (Electroencephalogram) signal processing. It demonstrates brain state analysis including the "Alpha Blockade" phenomenon (alpha waves suppressed when eyes are open) and Event-Related Desynchronization (ERD) for motor tasks.

The simulation loads EEG data (default: eeg_data_diverse_ideal.json) and provides tools to visualize brain signals in both time and frequency domains. You can select different experimental states and channels, apply preprocessing filters, and observe ERD scores for motor imagery tasks.

Math behind the Simulation

1. Short-Time Fourier Transform (STFT)

The spectrogram is computed using STFT to analyze how the frequency content of the EEG signal changes over time:

  • Window Function: The signal is divided into overlapping windows. Each window can be multiplied by a Hanning window function (optional) to reduce spectral leakage:
    w[n] = 0.5 × (1 - cos(2πn / (N - 1)))
    where N is the window size (configurable: 64, 128, 256, or 512 samples).
  • Window Parameters: Window size and overlap are configurable via dropdown menus. Default window size is automatically calculated based on sample rate (targeting ~1 second of data, rounded to nearest power of 2). Default overlap is 50% of window size. The hop size = window size - overlap.
  • Zero Padding: After windowing, each segment is zero-padded to a fixed FFT size of 512 samples. This decouples spectral resolution from window size, providing smoother spectrograms. Frequency resolution = sample rate / 512.
  • FFT Computation: For each windowed and zero-padded segment, the Fast Fourier Transform (FFT) is computed to convert from time domain to frequency domain.
  • Magnitude Spectrum: The magnitude at each frequency bin is calculated as |X[k]| = √(Re(X[k])² + Im(X[k])²), where X[k] is the complex FFT output.

2. Fast Fourier Transform (FFT)

The simulation implements a radix-2 FFT algorithm to compute the frequency spectrum:

  • Radix-2 Algorithm: The FFT uses an iterative radix-2 implementation. For small arrays (N ≤ 32), it falls back to Discrete Fourier Transform (DFT) for robustness.
  • Frequency Resolution: With zero padding to 512 samples, the frequency resolution is Δf = fs / 512. For fs = 250 Hz, Δf ≈ 0.49 Hz. For fs = 160 Hz, Δf ≈ 0.31 Hz.
  • Nyquist Frequency: The maximum frequency that can be represented is fNyquist = fs / 2. The spectrogram displays frequencies up to 40 Hz to focus on brain activity bands and avoid power-line noise.

3. Power Spectral Density (PSD)

The PSD chart calculates the average power across different frequency bands:

  • Power Calculation: For each windowed and zero-padded segment, the power at frequency k is P[k] = |X[k]|² = Re(X[k])² + Im(X[k])².
  • Average PSD: The power values are averaged across all windows: PSD[k] = (1/M) Σi=0M-1 Pi[k], where M is the number of windows.
  • Relative Power: The power in each brain band is normalized to relative power percentages: Relative Power = (Band Power / Total Power) × 100%, where Total Power is the sum of power from 1-40 Hz. This normalization cancels out broadband shifts and artifacts.

4. Signal Preprocessing

The simulation supports several preprocessing options to clean the signal:

  • DC Offset Removal: Calculates the mean of the signal and subtracts it from every sample. This removes baseline drift and DC bias: signal'[n] = signal[n] - mean(signal).
  • Hanning Window: When enabled, each window is multiplied by a Hanning window function before FFT to reduce spectral leakage and side lobes.
  • Spatial Filter (Common Average Reference - CAR): For multi-channel data, calculates the average signal across all channels at each time point, then subtracts it from each channel. This removes common noise and artifacts: Cleani[n] = Signali[n] - (1/N) Σj=1N Signalj[n]. CAR is applied before DC offset removal.

5. Event-Related Desynchronization (ERD) Score

The ERD score quantifies the suppression of brain rhythms during motor tasks:

  • Relative Power Calculation: For each event marker, calculates relative power (percentage of total power) in the Beta band (16-24 Hz) for motor tasks. Baseline period: 4.5s to 2.5s before the event. Active period: 0s to 1.5s after the event.
  • ERD Formula: ERD = ((Active Power - Baseline Power) / Baseline Power) × 100%. Negative values indicate desynchronization (suppression), positive values indicate synchronization (enhancement).
  • Averaging: ERD scores are averaged across all events in the data to provide a robust measurement.

6. Brain Frequency Bands

EEG signals are categorized into standard frequency bands that correlate with different brain states:

  • Delta (0.5-4 Hz): Deep sleep, unconscious states. Typically dominant during deep sleep.
  • Theta (4-8 Hz): Drowsiness, meditation, memory processing. Common during light sleep and daydreaming.
  • Alpha (8-13 Hz): Relaxed wakefulness, eyes closed. The "Alpha Blockade" phenomenon shows alpha waves are suppressed when eyes are open and enhanced when eyes are closed.
  • Beta (13-30 Hz): Active thinking, focused attention, alertness. Present during active cognitive tasks and focused mental activity.

 

Usage Example

Follow these steps to explore the EEG Brain State Visualizer and observe brain state analysis:

  1. Load Data: The simulation automatically loads the default EEG data file (EEG/eeg_data_diverse_ideal.json) on startup. You can also load custom JSON files using the "Load Data File" button. The data supports both "simple" format (flat structure) and "diverse" format (nested structure with multiple channels and events).
  2. Select State and Channel: Use the "State" dropdown to select an experimental condition (e.g., "motor_real", "motor_imag", "rest_open", "rest_closed"). Use the "Channel" dropdown to select an electrode (e.g., "C3", "C4", "Cz", "Fz", "Pz"). All charts update immediately when selections change.
  3. Configure Preprocessing: Toggle the preprocessing options:
    • DC Offset Removal: Removes baseline drift (enabled by default).
    • Hanning Window: Reduces spectral leakage (enabled by default).
    • Spatial Filter (CAR): Removes common noise across channels (requires multiple channels).
  4. Adjust STFT Parameters: Use the "Window Size" and "Overlap" dropdowns to adjust time-frequency resolution. The resolution information (frequency resolution, time per window, hop size) is displayed below the controls.
  5. Time Domain Chart (Top):
    • Observe the preprocessed EEG signal voltage over the entire duration.
    • The signal amplitude is displayed in microvolts (µV).
    • Red vertical lines indicate event markers (e.g., movement cues).
    • Note the signal characteristics and event timing.
  6. Spectrogram Chart (Middle):
    • This heatmap shows how frequency content changes over time (frequency vs. time).
    • The color intensity represents power at each frequency-time point (brighter = more power).
    • The frequency range is limited to 0-40 Hz to focus on brain activity bands.
    • Red vertical lines show event markers spanning the frequency range.
    • The colorbar is displayed horizontally at the bottom of the plot.
  7. Power Spectral Density Chart (Bottom):
    • This bar chart shows the relative power (%) in each brain frequency band (Delta, Theta, Alpha, Beta).
    • The Alpha band bar (8-13 Hz) is colored red to highlight its importance.
    • The bars show relative power percentages, normalized so the sum of all bands equals 100%.
  8. ERD Score: The Event-Related Desynchronization score is displayed between the control panel and the time chart. It shows the percentage change in Beta band (16-24 Hz) power during motor tasks compared to baseline. Negative values indicate desynchronization (expected for motor tasks), positive values may indicate artifacts or synchronization.

Tips:

  •   For motor tasks, look for negative ERD scores (desynchronization) in the Beta band (16-24 Hz). The ERD score uses relative power to cancel out broadband shifts and artifacts.
  •   The Alpha Blockade is most clearly visible in the Spectrogram: look for the bright horizontal line around 10 Hz in rest states with eyes closed.
  •   Compare the Alpha bar height in the PSD chart between different states—it should be significantly higher when eyes are closed.
  •   Adjust window size and overlap to balance time and frequency resolution. Larger windows provide better frequency resolution but poorer time resolution.
  •   Enable Spatial Filter (CAR) when working with multi-channel data to remove common noise and artifacts.
  •   The Time Domain chart shows the preprocessed signal with event markers. The frequency analysis (Spectrogram and PSD) reveals the underlying brain rhythms.

 

Visualizations

The simulation provides three synchronized visualizations that update together when you change state, channel, or preprocessing options:
  • 1. Time Domain Signal (Top Chart): Displays the preprocessed EEG signal voltage over the entire duration. The signal amplitude is shown in microvolts (µV). Red vertical lines indicate event markers (e.g., movement cues). This chart provides a direct view of the electrical activity recorded from the brain. The signal shows continuous oscillations that are characteristic of EEG recordings.
  • 2. Spectrogram (Middle Chart): A heatmap visualization showing how the frequency content of the EEG signal changes over time. The x-axis represents time (seconds), and the y-axis represents frequency (0-40 Hz). The color intensity (from dark blue to bright yellow/red in the 'Jet' colormap) represents the power at each frequency-time point. Red vertical lines show event markers spanning the frequency range. The colorbar is displayed horizontally at the bottom. The spectrogram is computed using Short-Time Fourier Transform (STFT) with configurable window size and overlap, using zero padding to 512 samples for consistent frequency resolution.
  • 3. Power Spectral Density (Bottom Chart): A bar chart showing the relative power (%) in four standard brain frequency bands: Delta (0.5-4 Hz, blue), Theta (4-8 Hz, purple), Alpha (8-13 Hz, red), and Beta (13-30 Hz, orange). The Alpha band is colored red to highlight its significance. The power is calculated by averaging the magnitude-squared FFT across all time windows (with zero padding to 512 samples) and normalized to show relative percentages (the sum of all bands equals 100%). This chart quantifies the distribution of brain rhythms across frequency bands.
  • 4. ERD Score Display: Located between the control panel and the time chart, this displays the Event-Related Desynchronization score. It shows the percentage change in Beta band (16-24 Hz) relative power during motor tasks compared to baseline. Negative values (green) indicate desynchronization (suppression), positive values (orange) indicate synchronization or artifacts. The score is averaged across all events in the data.

Controls

  • State Dropdown: Select an experimental condition from the dropdown menu. Options are automatically populated based on the loaded data file (e.g., "motor_real", "motor_imag", "rest_open", "rest_closed"). All charts update immediately when the selection changes.
  • Channel Dropdown: Select an electrode/channel from the dropdown menu. Options are automatically populated based on available channels in the data (e.g., "C3", "C4", "Cz", "Fz", "Pz", "Oz"). All charts update immediately when the selection changes.
  • Load Data File Button: Click to load a custom JSON file. The file can be in "simple" format (flat structure) or "diverse" format (nested structure with multiple channels and events). The default file is eeg_data_diverse_ideal.json.
  • DC Offset Removal Checkbox: When enabled (default), removes the mean value from the signal to eliminate baseline drift and DC bias.
  • Hanning Window Checkbox: When enabled (default), applies a Hanning window to each segment before FFT to reduce spectral leakage.
  • Spatial Filter (CAR) Checkbox: When enabled, applies Common Average Reference filtering to remove common noise across channels. Requires multiple channels in the data.
  • Window Size Dropdown: Select the STFT window size in samples (64, 128, 256, or 512). The default is automatically calculated based on the sample rate. Larger windows provide better frequency resolution but poorer time resolution.
  • Overlap Dropdown: Select the overlap between windows in samples. Options are dynamically generated based on the selected window size. Default is 50% of window size.
  • State Info Display: Shows the currently selected state, channel, and sampling rate of the EEG data.
  • Resolution Info Display: Shows the frequency resolution (Hz/bin), time per window (seconds), and hop size (samples and seconds) based on the current window size and overlap settings.

Data Format

The EEG data should be provided as a JSON object. The simulation supports two formats:

Simple Format (Flat Structure):

{
  "eyes_open": [12.5, 13.2, 14.1, 15.3, 14.8, ...],
  "eyes_closed": [18.3, 19.1, 20.5, 21.2, 20.8, ...],
  "fs": 160
}
                                        

Diverse Format (Nested Structure with Multiple Channels and Events):

{
  "fs": 250,
  "activities": {
    "motor_real": {
      "description": "Real: Left vs Right Fist",
      "signals": {
        "C3": [12.5, 13.2, 14.1, ...],
        "C4": [11.8, 12.5, 13.1, ...],
        "Cz": [10.2, 10.9, 11.5, ...]
      },
      "events": [
        {"time": 4.0, "label": "Left Fist"},
        {"time": 12.0, "label": "Right Fist"}
      ]
    }
  }
}
                                        

Each array contains floating-point numbers representing voltage measurements in microvolts (µV). The "fs" field specifies the sampling rate in Hz. The default data file is located at EEG/eeg_data_diverse_ideal.json and contains filtered, artifact-free data with multiple channels and event markers for motor imagery tasks.