Useful tools
Useful tools
| Option | Description |
|---|---|
| title | utils.py |
| authors | Florence Brun, Guillaume Dumas |
| date | 2020-03-18 |
concatenate_epochs(epoch_S1, epoch_S2)
Concatenate multiple epochs objects into single epochs objects for each participant.
This function combines multiple epoch instances (e.g., from different experimental blocks or sessions) into a single epochs object for each participant.
Parameters
epoch_S1 : list List of Epochs objects for participant 1
list
List of Epochs objects for participant 2
Returns
tuple : (mne.Epochs, mne.Epochs) A tuple containing two concatenated Epochs objects, one for each participant
Notes
This function is useful when you have recorded multiple experimental blocks or conditions and want to combine them for analysis.
The epochs to be concatenated must be compatible in terms of sampling rate, channel names, and other attributes.
Examples
Concatenate epochs from two experimental blocks
epochs_S1_all, epochs_S2_all = concatenate_epochs( ... [epochs_S1_block1, epochs_S1_block2], ... [epochs_S2_block1, epochs_S2_block2] ... ) print(f"Total epochs: {len(epochs_S1_all)}")
create_epochs(raw_S1, raw_S2, duration)
Create epochs from continuous raw EEG data for two participants.
This function segments continuous EEG data into fixed-length epochs for both participants, interpolates bad channels, and prepares the data for further analysis.
Parameters
raw_S1 : mne.io.Raw Raw EEG data for participant 1
mne.io.Raw
Raw EEG data for participant 2
float
Duration of each epoch in seconds
Returns
tuple : (List[mne.Epochs], List[mne.Epochs]) A tuple containing two lists of Epochs objects, one for each participant
Notes
The function performs the following steps: 1. Creates fixed-length events at regular intervals 2. Segments the continuous data into epochs based on these events 3. Interpolates bad channels if present 4. Removes bad channel labels after interpolation
The returned epochs have no baseline correction applied (baseline=None), and no automatic rejection criteria (reject=None).
Examples
Create 2-second epochs from raw data
epochs_S1, epochs_S2 = create_epochs(raw_S1, raw_S2, duration=2.0) print(f"Created {len(epochs_S1[0])} epochs for participant 1") print(f"Created {len(epochs_S2[0])} epochs for participant 2")
generate_random_epoch(epoch, mu=0, sigma=2.0)
Generate epochs with random data following a normal distribution.
This function creates a new Epochs object with the same structure as the input epochs, but with random data values drawn from a normal distribution.
Parameters
epoch : mne.Epochs Template Epochs object to copy structure from
float, optional
Mean of the normal distribution (default=0)
float, optional
Standard deviation of the normal distribution (default=2.0)
Returns
random_epochs : mne.Epochs New Epochs object with random data values
Notes
This function is useful for: - Creating null data for testing analysis pipelines - Generating surrogate data for statistical tests - Simulating baseline noise with known properties
The random data has the same dimensions as the input epoch data: (n_epochs, n_channels, n_times)
Examples
Generate random epochs with the same structure as real data
random_epochs = generate_random_epoch(real_epochs, mu=0, sigma=1.0)
Compare real and random data
real_mean = np.mean(real_epochs.get_data()) random_mean = np.mean(random_epochs.get_data()) print(f"Real data mean: {real_mean}, Random data mean: {random_mean}")
generate_random_label(length)
Generate a random label of a specific length
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
int
|
length of the string |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
a unique label |
generate_virtual_epoch(epoch, W, frequency_mean=10, frequency_std=0.2, noise_phase_level=0.005, noise_amplitude_level=0.1)
Generate epochs with simulated data using Kuramoto oscillators.
This function creates a new Epochs object with simulated EEG data based on a network of coupled Kuramoto oscillators, which can be used to model brain oscillations and synchronization.
Parameters
epoch : mne.Epochs Template Epochs object to copy structure from
np.ndarray
Coupling matrix between oscillators, with shape (n_channels, n_channels)
float, optional
Mean frequency of oscillators in Hz (default=10)
float, optional
Standard deviation of oscillator frequencies in Hz (default=0.2)
float, optional
Amount of noise added to the phase (default=0.005)
float, optional
Amount of noise added to the amplitude (default=0.1)
Returns
simulated_epochs : mne.Epochs New Epochs object with simulated data values
Notes
The Kuramoto model is a mathematical model used to describe synchronization
in a network of coupled oscillators. Each oscillator has its own natural
frequency drawn from a normal distribution with mean frequency_mean and
standard deviation frequency_std.
The coupling between oscillators is defined by the matrix W, where W[i,j] represents the strength of the connection from oscillator j to oscillator i.
The simulation uses the scipy.integrate.solve_ivp function to solve the differential equations of the Kuramoto model.
This function is useful for: - Testing connectivity measures with known ground truth - Simulating synchronization phenomena - Generating data with controlled properties for method validation
Examples
Create a simple coupling matrix (3 oscillators)
W = np.array([ ... [0, 0.2, 0], ... [0.2, 0, 0.2], ... [0, 0.2, 0] ... ])
Generate simulated epochs in the alpha band
sim_epochs = generate_virtual_epoch( ... real_epochs, W, frequency_mean=10, frequency_std=0.1 ... )
Analyze the simulated data
from mne.time_frequency import psd_welch psds, freqs = psd_welch(sim_epochs, fmin=8, fmax=12) print(f"Peak frequency: {freqs[np.argmax(np.mean(psds, axis=0))]}")
merge(epoch_S1, epoch_S2)
Merge epochs from two participants into a single hyperscanning dataset.
This function combines the EEG data from two participants into a single Epochs object, where channels from each participant are labeled with suffixes "_S1" and "_S2" respectively.
Parameters
epoch_S1 : mne.Epochs Epochs object for participant 1
mne.Epochs
Epochs object for participant 2
Returns
ep_hyper : mne.Epochs Merged Epochs object containing data from both participants
Notes
Prior to merging, any bad channels are interpolated and their labels are removed from the 'bads' list.
The function assumes that the time alignment between participants has already been performed at the raw data creation stage.
After merging, average referencing cannot be applied to the data, and standard topographic plotting is not possible. Use specialized hyperscanning visualization tools instead.
The function preserves channel types (EEG/EOG) from the original data.
Examples
Merge epochs from two participants
epochs_merged = merge(epochs_S1, epochs_S2) print(f"Original channels: {len(epochs_S1.ch_names)}") print(f"Merged channels: {len(epochs_merged.ch_names)}")
normalizing(baseline, task, type)
Normalize data (PSD or CSD values) relative to a baseline condition.
This function computes Z-scores or log-ratios between task and baseline conditions, which is useful for comparing spectral power or connectivity changes relative to a reference state.
Parameters
baseline : np.ndarray Baseline condition data with shape (n_epochs, n_channels, n_frequencies)
np.ndarray
Task condition data with shape (n_epochs, n_channels, n_frequencies)
str
Normalization method to use: - 'Zscore': (task - baseline_mean) / baseline_std - 'Logratio': log10(task / baseline_mean)
Returns
Normed_task : np.ndarray Normalized data with shape (n_channels, n_frequencies)
Notes
For 'Logratio' normalization, only positive values can be used as input. If your data contains negative values, consider taking the absolute value before normalization.
Both normalization methods average across epochs before computing the normalization, resulting in a single normalized value per channel and frequency.
Examples
Normalize alpha power using Z-scores
alpha_power_baseline = baseline_psd[:, :, 8:13] # Alpha band alpha_power_task = task_psd[:, :, 8:13] # Alpha band normalized_alpha = normalizing( ... alpha_power_baseline, alpha_power_task, type='Zscore' ... ) print(f"Shape of normalized data: {normalized_alpha.shape}")
split(raw_merge)
Split merged raw data back into separate datasets for each participant.
This function reverses the merging process, extracting individual participants' data from a merged hyperscanning dataset based on channel name suffixes.
Parameters
raw_merge : mne.io.Raw Merged Raw data for both participants, with channels having suffixes "_S1" and "_S2" (or "_1" and "_2")
Returns
tuple : (mne.io.Raw, mne.io.Raw) A tuple containing two Raw objects, one for each participant, with standard 10-20 montage applied
Notes
The function performs the following steps: 1. Separates channels based on their suffix 2. Creates new Raw objects for each participant 3. Applies the standard 10-20 montage to both datasets 4. Sets the EEG reference to the average of all channels
Channel types (EEG/EOG) are preserved from the original data. Bad channel labels are transferred to the appropriate participant.
Examples
Split previously merged raw data
raw_S1, raw_S2 = split(raw_merged) print(f"Channels for participant 1: {len(raw_S1.ch_names)}") print(f"Channels for participant 2: {len(raw_S2.ch_names)}")