Connect#

The brainaccess.connect.processor module provides a suite of tools for processing and analyzing EEG data. These functions cover a range of common tasks, from initial data cleaning and quality assessment to advanced frequency analysis.

This guide provides an overview of the available functionalities, grouped by category, with brief code examples.

Note

All processing functions expect the input data (x) to be a NumPy array with the shape (channels, time_points).

Data Cleaning and Preprocessing#

These functions are used to prepare raw EEG data for analysis by removing noise and standardizing the signal.

Example: Detrending and Standardizing Data

import numpy as np
from brainaccess.connect import processor

# Create a sample data array (2 channels, 1000 time points)
sample_data = np.random.randn(2, 1000) + np.linspace(0, 5, 1000)

# Remove the linear trend from the data
detrended_data = processor.detrend(sample_data)

# Standardize the data (zero mean, unit variance)
standardized_data = processor.standardize(detrended_data)

print("Original data shape:", sample_data.shape)
print("Processed data shape:", standardized_data.shape)

Key functions in this category include: * detrend(x): Removes the linear trend from each channel. * demean(x): Subtracts the mean from each channel. * standardize(x): Standardizes data to have a mean of 0 and a variance of 1. * ewma_standardize(x, alpha, epsilon): Applies exponential weighted moving average standardization, useful for online processing.

Signal Quality and Statistics#

Use these functions to assess the quality of the EEG signal or to compute basic descriptive statistics.

Example: Checking Signal Quality

# For demonstration, we'll use random data
# In a real scenario, use a 2-3 second snippet of unprocessed EEG data
raw_data = np.random.randn(8, 500) # 8 channels, 2s of data at 250Hz

quality = processor.get_signal_quality(raw_data)

for i, q in enumerate(quality):
    print(f"Channel {i} quality: {q}")

Key functions include: * get_signal_quality(x): Estimates signal quality based on amplitude and noise. Returns 0 (bad), 1 (good amplitude), or 2 (good amplitude and low noise). * mean(x), median(x), std(x): Calculate the mean, median, and standard deviation for each channel. * get_minmax(x): Returns a dictionary with the minimum and maximum values for each channel.

Filtering#

The module provides a set of standard filters to isolate specific frequency bands or remove unwanted noise, such as power-line interference.

Warning

Data should be detrended before applying filters to avoid edge artifacts.

Example: Applying Bandpass and Notch Filters

sampling_freq = 250  # Hz

# Apply a bandpass filter to keep frequencies between 1 Hz and 40 Hz
bandpassed_data = processor.filter_bandpass(
    standardized_data,
    sampling_freq=sampling_freq,
    freq_low=1.0,
    freq_high=40.0
)

# Apply a notch filter to remove 50 Hz power-line noise
notched_data = processor.filter_notch(
    bandpassed_data,
    sampling_freq=sampling_freq,
    center_freq=50.0,
    width_freq=2.0
)

Key functions include: * filter_bandpass(x, sampling_freq, freq_low, freq_high) * filter_notch(x, sampling_freq, center_freq, width_freq) * filter_highpass(x, sampling_freq, freq) * filter_lowpass(x, sampling_freq, freq)

Frequency Analysis#

After preprocessing, you can analyze the frequency components of the signal.

Example: Calculating Power in Frequency Bands

# Calculate the power in standard EEG frequency bands (Delta, Theta, Alpha, Beta, Gamma)
bands = processor.get_bands(notched_data, sfreq=sampling_freq)

print("Alpha band power for each channel:")
print(bands['alpha'])

Key functions include: * fft(x, sampling_freq): Computes the Fast Fourier Transform, returning frequencies, magnitudes, and phases. * get_bands(x, sfreq, ...): Calculates the average power in the standard delta, theta, alpha, beta, and gamma frequency bands. * get_pow_freq_bands(x, sfreq, ...): A more general function to calculate power in custom frequency bands.

Epoching#

This function allows you to segment continuous data into smaller, fixed-length windows called epochs, which is a common step for many BCI and ERP analyses.

Example: Cutting Data into Overlapping Epochs

# Cut the data into 2-second epochs with 50% overlap
epochs = processor.cut_into_epochs(
    notched_data,
    sfreq=sampling_freq,
    epoch_length=2.0,
    overlap=0.5
)

print(f"Created {epochs.shape[0]} epochs.")
print("Shape of epochs array (epochs, channels, time_points):", epochs.shape)

Full Usage Example#

The following example demonstrates a complete processing pipeline, from loading data to applying several of the functions described above.

import numpy as np

from brainaccess.connect import processor


sampling_rate = 250
t = np.arange(0, 5, step=1.0 / (sampling_rate))
wave = 10 * np.sin(np.pi * 2 * 5 * t)
wave += 100 * np.sin(np.pi * 2 * 23 * t)
wave = wave.reshape(5, sampling_rate) + 2
wave2 = 10 * np.sin(np.pi * 2 * 5 * t).reshape(5, sampling_rate) + 2
data = np.stack([wave, wave2], axis=2)
data = np.moveaxis(data, 2, 0)


# Calculate mean of the data

mean = processor.mean(data[0, :, :])

# Get signal quality
quality = processor.get_signal_quality(data[0, :, :])

# Filter data

data_filtered = processor.filter_bandpass(data, sampling_rate, 48, 52)

# Calculate fft

data_fft = processor.fft(data, sampling_rate)["mag"]

Module Reference#

For comprehensive documentation of all available functions and their parameters, please refer to the brainaccess.connect.processor module reference.