Skip to content

A lightweight, interactive web-based tool designed to build an intuitive understanding of EEG forward modeling. This simulation visualizes how a neural source (modeled as a current dipole) generates electrical potentials across the scalp, bridging the gap between underlying brain activity and the waveforms seen on an EEG monitor.

License

Notifications You must be signed in to change notification settings

AdityaAsopa/EEG-Forward-Model

Β 
Β 

Repository files navigation

EEG Dipole Demo v2.0: Forward Modeling Simulator

EEG Dipole Demo Screenshot

A comprehensive, interactive web-based tool for understanding EEG forward modeling. This advanced simulation visualizes how neural sources (modeled as current dipoles or distributed active regions) generate electrical potentials across the scalp, bridging the gap between underlying brain activity and the waveforms measured by EEG.

Live Demo | Zero Dependencies | Offline Capable

This project is a significantly enhanced fork of the original EEG-Dipole-Demo by dbrang, extended with comprehensive scientific documentation, advanced features, and educational materials.


Table of Contents

  1. Overview
  2. Key Features
  3. Quick Start
  4. Understanding EEG Forward Modeling
  5. User Interface Guide
  6. Source Types
  7. Reference Configurations
  8. Signal Quality Simulation
  9. Time Series & Animation
  10. 3D Brain Visualization
  11. Pan & Zoom Controls
  12. Keyboard Shortcuts
  13. Data Export
  14. Technical Details
  15. Educational Use Cases
  16. Contributing
  17. License

Overview

Understanding EEG requires grasping two fundamental problems:

  • Forward Problem: Given a known neural source, calculate the resulting scalp potentials
  • Inverse Problem: Given measured scalp potentials, estimate the underlying source(s)

This tool provides a real-time interactive visualization of the Forward Problem, enabling students, researchers, and engineers to develop intuition about:

  • How dipole position, orientation, and strength affect scalp topography
  • The difference between radial and tangential sources
  • Volume conduction effects through brain, skull, and scalp
  • Reference electrode configurations and their impact on signals
  • Common mode rejection and DRL circuit behavior

Key Features

Multi-View Visualization

  • 3D Brain View: Interactive WebGL rendering with orbit controls, showing sources in anatomical context
  • Coronal Slice: Cross-sectional view with MRI background, ideal for understanding depth effects
  • Scalp Topomap: Classic 2D interpolated heatmap using the 10-20 electrode system

Advanced Source Modeling

  • Single Dipoles: Point-source current dipoles with adjustable position, amplitude, and orientation
  • Active Regions (Blobs): Distributed Gaussian clusters simulating cortical patches
  • Multiple Sources: Add, duplicate, and manage multiple simultaneous sources

Comprehensive Reference Systems

  • Average Reference: Software-based common average reference
  • Single Electrode Reference: Traditional linked-ears or mastoid reference
  • CMS/DRL (Design 1): Hardware common-mode sense with driven right leg
  • Virtual CMS/DRL (Design 2): Reference electrode with computed CMS and DRL injection

Signal Quality Simulation

  • Gaussian Noise: Adjustable baseline noise level
  • Electrode Impedance: Per-electrode impedance modeling with random or custom values
  • Mains Hum: 50/60 Hz powerline interference simulation
  • Body Transfer Function: Phase lag and attenuation modeling for DRL stability analysis

Time Series Animation

  • CSV Upload: Import time series data to animate source activity
  • Channel Mapping: Map CSV channels to individual sources
  • Playback Controls: Play, pause, seek, loop, and speed adjustment

Modern UI

  • Dark/Light Mode: Toggle between themes with persistent preference
  • Pan & Zoom: Navigate 2D views with scroll wheel and shift-drag
  • Responsive Design: Works on desktop and tablet screens

Quick Start

No build process, no installation, no server required.

  1. Download or clone the repository
  2. Open index.html in any modern browser (Chrome, Firefox, Safari, Edge)
  3. Interact with the controls to explore EEG forward modeling
# Clone the repository
git clone https://github.com/AdityaAsopa/EEG-Forward-Model.git

# Open in browser
open index.html

Understanding EEG Forward Modeling

The Physics

EEG forward modeling calculates scalp potentials from known neural sources using the quasi-static approximation of Maxwell's equations. For a current dipole in a homogeneous conductive medium:

V(r) = (1/4πσ) Γ— (p Β· R) / |R|Β³

Where:

  • V(r) = potential at point r
  • Οƒ = conductivity of the medium
  • p = dipole moment vector
  • R = vector from dipole to measurement point

Volume Conduction

The head is modeled as concentric shells (brain, skull, scalp) with different conductivities:

  • Brain: ~0.33 S/m (highly conductive)
  • Skull: ~0.0042 S/m (poorly conductive - 80x less than brain)
  • Scalp: ~0.33 S/m (similar to brain)

The skull acts as a spatial low-pass filter, smearing and attenuating the neural signals.

Dipole Orientation Matters

  • Radial dipoles (pointing toward the scalp) produce focal, symmetric patterns
  • Tangential dipoles (parallel to the scalp) produce dipolar patterns with positive and negative poles
  • Most cortical activity is tangential (perpendicular to the cortical surface)

User Interface Guide

Left Panel: Controls

Section Description
Source Mode Toggle between single dipole and blob (active region) modes
Sources Add, duplicate, delete, and manage sources with position inputs
Preset Locations Jump to anatomically-relevant positions (motor cortex, visual, etc.)
Dipole/Blob Controls Adjust amplitude, angle, radius, orientation
Y Position Move source anterior-posterior (into/out of the coronal plane)
Time Series Upload and control animated source activity
View Options Toggle labels, values, MRI overlay, auto-scaling
Signal Quality Add noise, impedance variations, mains hum
Reference & DRL Configure reference scheme and DRL parameters
Electrode Montage Enable/disable individual electrodes
Export Download electrode values as CSV

Right Panel: Visualizations

View Description
3D Brain View Interactive WebGL rendering with orbit, pan, zoom
Coronal Slice Cross-sectional anatomical view with electrodes
Scalp Topomap 2D interpolated potential map

Source Types

Single Dipole

A point-source current dipole representing a small, coherent patch of cortical activity.

Parameters:

  • Position (x, y, z): Location in normalized coordinates (-1 to 1)
  • Amplitude: Dipole moment magnitude (arbitrary units)
  • Angle: Orientation in the coronal plane (0Β° = right, 90Β° = up, 180Β° = left)

Active Region (Blob)

A Gaussian-distributed cluster of coherent dipoles, better representing extended cortical activation.

Parameters:

  • Position (x, y, z): Center location
  • Radius: Spatial extent (sigma of Gaussian)
  • Strength: Overall activity magnitude
  • Theta (ΞΈ): Polar angle from vertical (0Β° = up, 90Β° = horizontal)
  • Phi (Ο†): Azimuthal rotation angle

Source States

Sources automatically turn INACTIVE (shown in red) when positioned outside the brain volume. Only sources inside the brain ellipsoid contribute to scalp potentials.


Reference Configurations

None (Raw Potentials)

No reference applied. Shows absolute potentials (rarely used in practice).

Average Reference

Subtracts the mean of all electrode values. Common for research applications.

V'α΅’ = Vα΅’ - (1/N)βˆ‘Vβ±Ό

Single Electrode Reference

Subtracts the value at a chosen reference electrode (e.g., Cz, linked mastoids).

V'α΅’ = Vα΅’ - Vα΅£β‚‘f

Design 1: CMS + DRL

Hardware-based common mode rejection with dedicated electrodes:

  1. CMS (Common Mode Sense): A dedicated electrode measures common mode noise
  2. DRL (Driven Right Leg): An integrator amplifies and inverts the CMS signal
  3. The inverted signal is injected back into the body via the DRL electrode
  4. All recording electrodes are referenced to CMS

Configurable Parameters:

  • CMS electrode position (10-20 location)
  • DRL electrode position (typically forehead or mastoid)
  • DRL gain, time constant, injection efficiency
  • Body transfer function (attenuation, phase lag)
  • Upload custom frequency-dependent LUT

Design 2: Reference + Virtual CMS + DRL

Alternative design where:

  1. A Reference electrode provides the actual signal reference
  2. Virtual CMS is computed by averaging all electrode values
  3. DRL injects the inverted virtual CMS signal

Phase Margin & Stability

The DRL feedback loop can become unstable if phase margin is too low. The UI displays:

  • Phase Margin: Degrees of margin before instability (>45Β° is safe)
  • Stability Indicator: Green = stable, Red = warning

Signal Quality Simulation

Gaussian Noise

Add random baseline noise to simulate thermal and biological noise sources.

Electrode Impedance

Model the effects of poor electrode contact:

  • Higher impedance = signal attenuation
  • Impedance mismatch = increased common mode pickup
  • Randomize impedances to simulate realistic conditions

Mains Hum (50/60 Hz)

Simulate powerline interference:

  • Select 50 Hz (Europe/Asia) or 60 Hz (Americas)
  • Adjust amplitude to see DRL rejection in action

Time Series & Animation

Uploading Data

Upload CSV files with time series data:

time,channel1,channel2,channel3
0.000,0.5,0.3,-0.2
0.004,0.6,0.4,-0.1
0.008,0.7,0.5,0.0
...

Requirements:

  • First column must be time (seconds)
  • Subsequent columns are channel values
  • Header row with channel names is recommended

Channel Mapping

Map each CSV channel to one or more sources:

  • Click the dropdown next to each channel
  • Select which source(s) should be modulated by that channel
  • Sources without mapping remain static

Playback Controls

Control Function
β–Ά Play Start animation
⏹ Stop Stop and reset to beginning
πŸ” Loop Toggle looping
Timeline Seek to any time point
Speed 0.25x to 4x playback speed

3D Brain Visualization

The 3D view uses Three.js to render:

  • Semi-transparent brain mesh (GLB model)
  • Source positions as spheres/arrows
  • Color coding for inside/outside brain

Controls

Action Method
Rotate Click and drag
Zoom Scroll wheel
Pan Right-click drag
Reset Click "Reset" button
Preset Views Front, Top, Side buttons

Display Options

  • Show Brain: Toggle brain mesh visibility
  • Opacity: Adjust brain transparency

Pan & Zoom Controls

Both 2D views (Coronal and Topomap) support pan and zoom:

Action Method
Zoom In Scroll up or click +
Zoom Out Scroll down or click -
Pan Hold Shift + drag
Reset Click ⟲ button

Zoom range: 50% to 300%


Keyboard Shortcuts

Key Action
Delete / Backspace Remove selected source
A Rotate counter-clockwise
D Rotate clockwise
W Increase amplitude/strength
S Decrease amplitude/strength

Data Export

Export Current Frame

Download a CSV with electrode names and current potential values.

Export Time Series

Download the full animation as CSV with all time points and all electrodes.

Output Format:

time,Fp1,Fp2,F7,F3,Fz,F4,F8,...
0.000,0.123,-0.456,0.789,...
0.004,0.234,-0.567,0.890,...

Technical Details

Architecture

EEG-Forward-Model/
β”œβ”€β”€ index.html          # Main HTML structure
β”œβ”€β”€ css/
β”‚   └── styles.css      # Styling (dark/light themes)
β”œβ”€β”€ js/
β”‚   β”œβ”€β”€ main.js         # Application entry point
β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”œβ”€β”€ physics.js      # Forward model calculations
β”‚   β”‚   β”œβ”€β”€ math.js         # Math utilities, color mapping
β”‚   β”‚   β”œβ”€β”€ electrodes.js   # 10-20 electrode positions
β”‚   β”‚   β”œβ”€β”€ reference.js    # Reference schemes, DRL
β”‚   β”‚   └── presets.js      # Anatomical preset locations
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ state.js        # Application state management
β”‚   β”‚   β”œβ”€β”€ dipole.js       # Dipole model
β”‚   β”‚   β”œβ”€β”€ blob.js         # Blob model
β”‚   β”‚   └── timeseries.js   # Time series handling
β”‚   β”œβ”€β”€ views/
β”‚   β”‚   β”œβ”€β”€ coronal.js      # Coronal slice rendering
β”‚   β”‚   β”œβ”€β”€ topomap.js      # Topographic map rendering
β”‚   β”‚   └── brain3d.js      # 3D WebGL view
β”‚   β”œβ”€β”€ ui/
β”‚   β”‚   β”œβ”€β”€ controls.js     # UI control bindings
β”‚   β”‚   β”œβ”€β”€ timeline.js     # Playback controls
β”‚   β”‚   └── file-upload.js  # CSV upload handling
β”‚   └── export/
β”‚       └── csv.js          # CSV export utilities
└── assets/
    β”œβ”€β”€ coronal-slice.png   # MRI background
    └── brain_human.glb     # 3D brain model

Physics Implementation

Dipole Potential:

V = (p Β· R) / |R|Β³

Blob (Gaussian Cluster):

  • 27-point 3D grid sampling
  • Gaussian-weighted contributions
  • Normalized to preserve total dipole moment

Brain Boundary:

  • 3D ellipsoid: center (0, 0, -0.05), radii (0.75, 0.80, 0.70)
  • Sources outside are inactive (no contribution)

Dependencies

  • Three.js v0.160.0: 3D rendering (loaded from CDN)
  • GLTFLoader: Brain model loading
  • OrbitControls: 3D camera interaction

All other functionality is vanilla JavaScript with no build tools required.

Browser Support

  • Chrome 90+
  • Firefox 88+
  • Safari 14+
  • Edge 90+

Educational Use Cases

Neuroscience Courses

  1. Forward vs. Inverse Problem: Demonstrate why source localization is ill-posed
  2. Dipole Orientation: Show radial vs. tangential source patterns
  3. Volume Conduction: Visualize how skull attenuates and spreads signals
  4. Reference Effects: Compare different montages and their artifacts

EEG Technician Training

  1. Electrode Placement: See how position affects recorded signals
  2. Impedance Effects: Understand importance of good electrode contact
  3. Artifact Recognition: Recognize patterns from different noise sources

Biomedical Engineering

  1. DRL Circuit Design: Explore loop gain, phase margin, stability
  2. CMRR Optimization: Tune parameters for optimal noise rejection
  3. Transfer Functions: Upload and test custom DRL characteristics

Research Applications

  1. Source Modeling: Prototype source configurations before experiments
  2. Montage Design: Evaluate electrode placement strategies
  3. Data Quality: Understand noise sources and mitigation

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Notes

  • No build tools required - edit files directly
  • Test in multiple browsers before submitting
  • Follow existing code style and documentation patterns

License

Distributed under the MIT License. See LICENSE for more information.


Acknowledgments

  • Three.js for 3D rendering capabilities
  • The neuroscience and EEG research community for inspiration
  • All contributors and users providing feedback

Developed for educational purposes in Neuroscience, Signal Processing, and Biomedical Engineering.

Questions? Issues? Open a GitHub issue or reach out to the maintainers.

About

A lightweight, interactive web-based tool designed to build an intuitive understanding of EEG forward modeling. This simulation visualizes how a neural source (modeled as a current dipole) generates electrical potentials across the scalp, bridging the gap between underlying brain activity and the waveforms seen on an EEG monitor.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • HTML 92.9%
  • JavaScript 6.6%
  • CSS 0.5%