clamnibs package

clamnibs.base module

class clamnibs.base.EpochsCLAM(raw, apply_hil=True)[source]

Bases: Epochs

Initialize an EpochsCLAM object.

Parameters:

rawRawCLAM object

The EEG data.

apply_hilbool

Whether to apply Hilbert transformation to the EEG data to obtain the analytic signal.

Notes:

This class extends Epochs and provides additional functionality specific to CLAM-NIBS experiments.

Attributes:

designstr

The experimental design type (‘trial_wise’ or ‘session_wise’).

l_freq_targetfloat

Lower edge of the target frequency range (in Hz).

h_freq_targetfloat

Higher edge of the target frequency range (in Hz).

marker_definitiondict

Dictionary containing marker definitions. Mapping from target phase markers (e.g. 1 - 6) to target phases [-pi, pi].

is_stimbool

Indicates whether the data was recorded in the presence of CLAM-NIBS or not.

participantstr

Participant identifier.

sessionstr

Session identifier.

forward_fullndarray or None

Forward model for all EEG channels (with zero for bads).

flipinteger

Sign flip for dipole (-1 or 1).

Raises:

None

class clamnibs.base.EpochsCLAMVariable(raw, end_codes, start_codes=None, tmin=0, tmax=0, apply_hil=True)[source]

Bases: object

Variable-length epochs for CLAM-NIBS experiments.

Unlike EpochsCLAM (which inherits from mne.Epochs and requires fixed-length epochs), this class supports epochs of different durations. Each epoch spans from a start marker to the next end marker.

Parameters:

rawRawCLAM object

The EEG data.

end_codeslist of int

Event codes that mark the end of a trial.

start_codeslist of int or None, optional

Event codes that mark the start of a trial. If None, defaults to the keys of raw.marker_definition.

tminfloat, optional

Time offset in seconds from start marker (default 0).

tmaxfloat, optional

Time offset in seconds from end marker (default 0).

apply_hilbool, optional

Whether to apply Hilbert transformation to the EEG data (default True).

Attributes:

datalist of ndarray

List of 2D arrays, each of shape (n_channels, n_timepoints_i).

eventsndarray, shape (n_epochs, 3)

Event array in MNE format (sample, 0, event_code) for start events.

durationslist of float

Duration of each epoch in seconds.

infomne.Info

Measurement info copied from the raw object.

ch_nameslist of str

Channel names.

design, l_freq_target, h_freq_target, marker_definition, is_stim, participant, session, forward_full, flip, n_chs :

Copied from the RawCLAM object.

property durations
get_channel_types()[source]
get_data(picks=None)[source]

Get epoch data, optionally selecting channels.

Parameters:

pickslist of int, list of str, str, or None

Channel indices, names, or type to select. If None, all channels.

Returns:

list of ndarray

List of 2D arrays, each of shape (n_selected_channels, n_timepoints_i).

class clamnibs.base.RawCLAM(path, l_freq_target=None, h_freq_target=None, tmin=None, tmax=None, n_chs=64, design='trial_wise', ecg_channels=[], misc_channels=['envelope', 'envelope_am'], marker_definition={1: 0.0, 2: 1.0471975511965976, 3: 2.0943951023931953, 4: 3.141592653589793, 5: 4.1887902047863905, 6: 5.235987755982989}, sfreq=None, ignore_calibration_files=False, default_bads=['Fp1', 'Fpz', 'Fp2', 'F9', 'FT9', 'TP9', 'F10', 'FT10', 'TP10'])[source]

Bases: RawBrainVision

Initialize a RawCLAM object.

Parameters:

pathstr

The path to the BrainVision header file (.vhdr).

l_freq_targetfloat

Lower edge of the target frequency range.

h_freq_targetfloat

Higher edge of the target frequency range.

tminfloat or None, optional

For ‘trial_wise’ designs, this is the start time of the trial relative to the target phase marker. Required paramter when trigger markers are provided (e.g. marker_definition != {}).

tmaxfloat or None, optional

For ‘trial_wise’ designs, this is the end time of the trial relative to the target phase marker. Required paramter when trigger markers are provided (e.g. marker_definition != {}).

n_chsint, optional

Number of EEG channels in the data (including bads).

designstr, optional

The experimental design type. ‘trial_wise’ means that multiple phase lags were tested in the session. ‘session_wise’ means that a single phase lag was tested in the session (e.g. patient treatment).

misc_channelslist, optional

List of miscellaneous channel names (not EEG or ECG).

marker_definitiondict, optional

Dictionary containing marker definitions. Mapping from target phase markers (e.g. 1 - 6) to target phases [-pi, pi]. Target phases can also take the string values ‘open-loop’ (open-loop stimulation), ‘no-stim’ (no stimulation), ‘optimal’ (optimal target phase), or ‘suboptimal’ (suboptimal target phase).

sfreqfloat or None, optional

New sampling frequency, or None if the data should not be resampled.

ignore_calibration_files: bool, optional

If True, the user will be prompted to select bad channels and target spatial component regardless of the presence of calibration (.mat) files in the data folder

default_badslist of str, optional

The user may specify the list of channels that are marked bad by default in viz.set_bads

Notes:

This class extends RawBrainVision and provides additional functionality specific to CLAM-NIBS experiments.

Raises:

Exception:
  • If data with CLAM-NIBS is loaded but no forward model is present in the data folder.

  • If data with CLAM-NIBS is loaded but no dipole sign flip is present in the data folder.

plot_forward(sensors=False)[source]

clamnibs.beamformer module

clamnibs.beamformer.get_target(obj)[source]

Compute the target signal from EEG data using LCMV beamforming.

This function computes the target signal from EEG data using Linearly Constrained Minimum Variance (LCMV) beamforming [1]. It extracts the target signal by spatially filtering the EEG data based on the forward model.

Parameters:

objRawCLAM or EpochsCLAM object

The RawCLAM or EpochsCLAM object containing EEG data.

Returns:

targetndarray

The target signal extracted from the EEG data using LCMV beamforming.

Raises:

Exception:

If the input object is not an instance of RawCLAM or EpochsCLAM.

References:

[1] Van Veen, Barry D., and Kevin M. Buckley. “Beamforming: A versatile approach to spatial filtering.”

IEEE assp magazine 5.2 (1988): 4-24.

clamnibs.beamformer.set_forward(raw, l_freq_noise, h_freq_noise, n_comp=4)[source]

Compute and set the forward model for target source reconstruction.

This method computes and sets the forward model necessary for LCMV beamforming. A data-driven approach called Spatio-Spectral Decomposition (SSD) [1] is used to find components in the signal that maximize power in the target frequency range while minimizing power in the noise frequency range.

A component must be selected by the user by clicking on the respective power spectrum before closing the plot.

Parameters:

rawRawCLAM object

The RawCLAM object containing EEG data.

l_freq_noisefloat

Lower edge of the noise frequency range.

h_freq_noisefloat

Higher edge of the noise frequency range.

n_compint, optional

Number of SSD components to plot. Default is 4.

Returns:

None

Raises:

Exception:

If the input object is not an instance of RawCLAM. If the data does not contain frequencies of at least 1 - 40 Hz. If no target for stimulation (forward model) is selected by the user.

References:

[1] Nikulin, Vadim V., Guido Nolte, and Gabriel Curio. “A novel method for reliable and fast extraction of neuronal

EEG/MEG oscillations on the basis of spatio-spectral decomposition.” NeuroImage 55.4 (2011): 1528-1535.

clamnibs.misc module

clamnibs.misc.compute_single_trial_behavior(raw, measure='binary_accuracy', correct_codes=[10], incorrect_codes=[11, 12])[source]

Compute single-trial task performance and assign it to CLAM-NIBS target phase. Applicable to any task with trial-by-trial responses.

Parameters:

rawRawCLAM

The RawCLAM object containing the raw data to analyze.

measurestr, optional

The method used to compute task performance. Either ‘binary’ (default) or ‘cwm’.

Returns:

pandas.DataFrame

A DataFrame containing the computed performance values and CLAM-NIBS target phase for each trial.

Raises:

Exception

If the input raw data is not of type RawCLAM. If the modulation of task performance is attempted on data without CLAM-tACS stimulation.

Notes:

  • This function only works if the data contains a target phase marker at the beginning of each trial.

clamnibs.misc.compute_single_trial_rr(raw, end_codes=None)[source]

Compute single-trial RR-intervals and assign them to CLAM-NIBS target phase.

Parameters:

rawRawCLAM

The RawCLAM object containing the raw data to analyze.

end_codeslist of int or None, optional

If provided, use variable-length epochs defined by start markers (from marker_definition) to end markers (end_codes). If None, use fixed-length epochs (default).

Returns:

pandas.DataFrame

A DataFrame containing the computed RR intervals and CLAM-NIBS target phases.

Raises:

Exception

If the input raw data is not of type RawCLAM. If the method is attempted on data without CLAM-tACS stimulation.

clamnibs.misc.compute_single_trial_scr(raw, end_codes=None)[source]

Compute single-trial area under the curve (AUC) of the skin conductance response (SCR) [1], and assign it to CLAM-NIBS target phase.

Parameters:

rawRawCLAM

The RawCLAM object containing the raw data to analyze.

end_codeslist of int or None, optional

If provided, use variable-length epochs defined by start markers (from marker_definition) to end markers (end_codes). If None, use fixed-length epochs (default).

Returns:

pandas.DataFrame

A DataFrame containing the computed SCR AUC and CLAM-NIBS target phases.

Raises:

Exception

If the input raw data is not of type RawCLAM. If the method is attempted on data without CLAM-tACS stimulation.

[1] Bach, Dominik R., Karl J. Friston, and Raymond J. Dolan. “Analytic measures for quantification of arousal

from spontaneous skin conductance fluctuations.” International journal of psychophysiology 76.1 (2010): 52-55.

clamnibs.misc.concat_dfs(dfs)[source]
clamnibs.misc.df_to_array(df_data)[source]

Convert a DataFrame containing one data point (trial or participant) per row to an ndarray.

Parameters:

df_datapandas.DataFrame

The DataFrame object containing the data to convert.

Returns:

numpy.ndarray

An ndarray of shape (n_phases, n_datapoints, …).

clamnibs.misc.save_calibration_data(obj, folder_path, phase_delay=None)[source]

clamnibs.sensor module

clamnibs.sensor.clean_sensor_data(obj_no_stim, obj_stim)[source]

Use Stimulation Artifact Source Separation (SASS) [1] to remove electric stimulation artifacts from EEG sensor data recorded during CLAM-NIBS. Bad sensors are excluded from the procedure, and interpolated after application of SASS.

Parameters:

obj_no_stimRawCLAM or EpochsCLAM

The RawCLAM or EpochsCLAM object containing the sensor data without CLAM-NIBS stimulation.

obj_stimRawCLAM or EpochsCLAM

The RawCLAM or EpochsCLAM object containing the sensor data with CLAM-NIBS stimulation.

Raises:

Exception

If the input data types are not RawCLAM or EpochsCLAM objects. If the data with and without CLAM-NIBS have different bandpass filter or target frequency range settings.

References:

[1] Haslacher, David, et al. “Stimulation artifact source separation (SASS) for assessing electric brain oscillations during transcranial alternating current stimulation (tACS).” Neuroimage 228 (2021): 117571.

clamnibs.sensor.compute_single_trial_connectivity(raw, measure='phase_lag_index', end_codes=None)[source]

Compute single-trial amplitude of target oscillation and assign it to CLAM-NIBS target phase.

Parameters:

rawRawCLAM

The RawCLAM object containing the raw data to analyze.

measurestr, optional

The connectivity measure to compute. Currently, only ‘phase_lag_index’ is supported (default).

end_codeslist of int or None, optional

If provided, use variable-length epochs defined by start markers (from marker_definition) to end markers (end_codes). If None, use fixed-length epochs (default).

Returns:

pandas.DataFrame

A DataFrame containing the computed amplitude values and CLAM-NIBS target phase for each epoch.

Raises:

Exception

If the input raw data is not of type RawCLAM. If the method for computing amplitude is not supported. If the Raw object does not meet the requirements for the chosen method.

clamnibs.source module

clamnibs.source.compute_phase_tracking(raw, plot=False)[source]

Compute the phase lag between CLAM-NIBS and targeted brain oscillations.

Parameters:

rawRawCLAM

The RawCLAM object containing the raw data to analyze.

plotbool, optional

Whether to plot the phase tracking results (default is False).

Returns:

float

The mean differene between the targeted phase lag and the actual phase lag, computed across all targeted phase lags.

Raises:

Exception

If the input raw data is not of type RawCLAM. If the data is not filtered into the target frequency range. If the function is called on data without CLAM-NIBS.

clamnibs.source.compute_single_trial_amplitude(raw, measure='hilbert_amp', end_codes=None)[source]

Compute single-trial amplitude of target oscillation for each CLAM-NIBS target phase.

Parameters:

rawRawCLAM

The RawCLAM object containing the raw data to analyze.

measurestr, optional
The method used to compute amplitude modulation. It can be one of the following:
  • ‘hilbert_amp’: Amplitude estimation based on Hilbert transform (default).

end_codeslist of int or None, optional

If provided, use variable-length epochs defined by start markers (from marker_definition) to end markers (end_codes). If None, use fixed-length epochs (default).

Returns:

pandas.DataFrame

A DataFrame containing the computed amplitude values and CLAM-NIBS target phase for each epoch.

Raises:

Exception

If the input raw data is not of type RawCLAM. If the method for computing amplitude is not supported. If the Raw object does not meet the requirements for the chosen method.

clamnibs.source.compute_single_trial_psd(raw, end_codes=None)[source]

Compute single-trial power spectral density of target oscillation for each CLAM-NIBS target phase.

Parameters:

rawRawCLAM

The RawCLAM object containing the raw data to analyze.

end_codeslist of int or None, optional

If provided, use variable-length epochs defined by start markers (from marker_definition) to end markers (end_codes). If None, use fixed-length epochs (default).

Returns:

pandas.DataFrame

A DataFrame containing the computed power spectral density along with CLAM-NIBS target phase for each epoch.

Raises:

Exception

If the input raw data is not of type RawCLAM. If the Raw object does not meet the requirements for the chosen method.

clamnibs.stats module

clamnibs.stats.average_over_trials(df, agg_func=<function nanmean>)[source]

Average over trials for each participant and target phase.

Parameters:

dfpandas.DataFrame

The DataFrame containing the data to be averaged.

agg_funccallable

The function used to average the data (e.g. np.nanmean or np.nanmedian).

Returns:

pandas.DataFrame

The DataFrame with averaged values.

clamnibs.stats.extract_psd_measure(freqs, psd, l_freq_target, h_freq_target, measure='power')[source]

Extract the specified measure from the power spectral density (PSD) using FOOOF.

Parameters:

freqsarray-like

The frequencies corresponding to the PSD values.

psdarray-like

The PSD values.

l_freq_targetfloat

The lower frequency limit of the target frequency range.

h_freq_targetfloat

The higher frequency limit of the target frequency range.

measurestr, optional (default=’power’)

The measure to extract (‘power’, ‘frequency’, or ‘aperiodic’).

Returns:

float

The extracted measure value.

clamnibs.stats.get_network_modulation_amp_phase(df_network_results, df_network_data)[source]

Get amplitude (depth) and optimal phase of modulation of connectivity in a network.

Parameters:

df_network_results: pandas.DataFrame

The dataframe containing the connections which were modulated at the participant- or group-level.

df_network_data: pandas.DataFrame

The dataframe containing the connectivity matrix for each trial and participant.

clamnibs.stats.test_modulation(df_data, test_level='participant', measure='power', agg_func=<function nanmean>, plot=False, plot_mode='box_strip')[source]

Test phase-dependent modulation of arbitrary outcome measure (e.g. power).

This function performs a permutation test to identify phase-dependent modulation of the outcome measure by CLAM-NIBS, and plots the results.

Parameters:

df_datapandas.DataFrame

The DataFrame containing outcome measure per participant, or per epoch for each participant.

test_levelstr, optional (default=’participant’)

The level at which the test should be performed (‘participant’, ‘group_same’, or ‘group_different’). If test_level=’participant’, a separate test for phase-dependent modulation

is performed for each participant, such that a sinusoidal function is fit to the data averaged over trials within each phase bin.

If test_level=’group_same’, a group-level test is performed, where the optimal target phase is

assumed to be the same for all participants, such that a sinusoidal function is fit to the data averaged over trials and participants within each phase bin.

If test_level=’group_different’, a group-level test is performed, where the optimal target phase

is assumed to be different for each participant, such that the fitting is performed at the participant level, but the test statistic (modulation amplitude) is averaged over participants.

measurestr, optional (default=’power’)

The outcome measure employed.

agg_funccallable, optimal (default=np.nanmean)

The function used to aggregate across trials within each phase bin (e.g. np.nanmean or np.nanstd).

plotstr or bool, optional (default=False)

If string, the plot(s) will be saved at that path. If True, a figure will be created but not shown or saved. If False, no figure will be created.

plot_modestr, optional (default=’box_strip’)

The plotting mode. If all data points should be shown, use ‘box_strip’ for a boxplot and stripplot. If data points should only be visualized as aggregated measures (e.g. accuracy across all trials or

variability across all ECG RR intervals), use ‘bar’ for a barplot.

Raises:

Exception:

If the test level is not ‘participant’ or ‘group’

clamnibs.stats.test_modulation_psd(df_data, test_level='participant', measure='power', freq_lim_tol=0, plot=False, plot_mode='box_strip')[source]

Test phase-dependent modulation of power, frequency, or aperiodic exponent from power spectral density.

This function performs a permutation test to identify phase-dependent modulation of the outcome measure by CLAM-NIBS, and plots the results.

Parameters:

df_datapandas.DataFrame

The DataFrame containing outcome measure per participant, or per epoch for each participant.

test_levelstr, optional (default=’participant’)

The level at which the test should be performed (‘participant’, ‘group_same’, or ‘group_different’). If test_level=’participant’, a separate test for phase-dependent modulation

is performed for each participant, such that a sinusoidal function is fit to the data averaged over trials within each phase bin.

If test_level=’group_same’, a group-level test is performed, where the optimal target phase is

assumed to be the same for all participants, such that a sinusoidal function is fit to the data averaged over trials and participants within each phase bin.

If test_level=’group_different’, a group-level test is performed, where the optimal target phase

is assumed to be different for each participant, such that the fitting is performed at the participant level, but the test statistic (modulation amplitude) is averaged over participants.

measurestr, optional (default=’power’)

The outcome measure employed (‘power’, ‘frequency’, or ‘aperiodic’).

freq_lim_tolfloat, optional (default=0)

The tolerance by which assessed peaks in the power spectrum can deviate in frequency from the target frequency range set in the data.

plotstr or bool, optional (default=False)

If string, the plot(s) will be saved at that path. If True, a figure will be created but not shown or saved. If False, no figure will be created.

plot_modestr, optional (default=’box_strip’)

The plotting mode. If all data points should be shown, use ‘box_strip’ for a boxplot and stripplot. If data points should only be visualized as aggregated measures (e.g. accuracy across all trials or variability across all ECG RR intervals), use ‘bar’ for a barplot.

Raises:

Exception:

If the test level is not ‘participant’ or ‘group’

clamnibs.stats.test_sensor_cluster_modulation(df_data, info, test_level='participant', measure='power', threshold_percentile=95, plot=False)[source]

Test phase-dependent modulation of arbitrary outcome measure (e.g. power) at the sensor level.

This function performs a cluster-based permutation test to identify clusters of sensors whose value of the outcome measure is modulated by CLAM-NIBS, and plots the results.

Parameters:

df_datapandas.DataFrame

The DataFrame containing outcome measure (for all sensors) per participant, or per epoch for each participant.

infomne.Info

The Info object for topographic plotting.

test_levelstr, optional (default=’participant’)

The level at which the test should be performed (‘participant’, ‘group_same’, or ‘group_different’). If test_level=’participant’, a separate test for phase-dependent modulation

is performed for each participant, such that a sinusoidal function is fit to the data averaged over trials within each phase bin.

If test_level=’group_same’, a group-level test is performed, where the optimal target phase is

assumed to be the same for all participants, such that a sinusoidal function is fit to the data averaged over trials and participants within each phase bin.

If test_level=’group_different’, a group-level test is performed, where the optimal target phase

is assumed to be different for each participant, such that the fitting is performed at the participant level, but the test statistic (modulation amplitude) is averaged over participants.

measurestr, optional (default=’power’)

The outcome measure employed.

plotstr or bool, optional (default=False)

If string, the plot(s) will be saved at that path. If True, a figure will be created but not shown or saved. If False, no figure will be created.

Raises:

Exception:

If the test level is not ‘participant’ or ‘group’

clamnibs.stats.test_sensor_network_modulation(df_data, info, test_level='participant', measure='phase_lag_index', threshold_percentile=95)[source]

Test phase-dependent modulation of functional connectivity at the sensor level.

This function performs a network-based permutation test to identify networks whose connectivity is modulated by CLAM-NIBS, and plots the results.

Parameters:

df_datapandas.DataFrame

The DataFrame containing connectivity matrices per participant, or per epoch for each participant.

infomne.Info

The Info object for topographic plotting.

test_levelstr, optional (default=’participant’)

The level at which the test should be performed (‘participant’, ‘group_same’, or ‘group_different’). If test_level=’participant’, a separate test for phase-dependent modulation

is performed for each participant, such that a sinusoidal function is fit to the data averaged over trials within each phase bin.

If test_level=’group_same’, a group-level test is performed, where the optimal target phase is

assumed to be the same for all participants, such that a sinusoidal function is fit to the data averaged over trials and participants within each phase bin.

If test_level=’group_different’, a group-level test is performed, where the optimal target phase

is assumed to be different for each participant, such that the fitting is performed at the participant level, but the test statistic (modulation amplitude) is averaged over participants.

measurestr, optional (default=’phase_lag_index’)

The connectivity measure employed.

plotstr or bool, optional (default=False)

If string, the plot(s) will be saved at that path. If True, a figure will be created but not shown or saved. If False, no figure will be created.

Raises:

Exception:

If the test level is not ‘participant’ or ‘group’

clamnibs.viz module

clamnibs.viz.plot_modulation_amp_corr(df_amp_phase_results)[source]

Plot correlation of amplitude (depth) of modulation of two outcome measures cross participants.

Parameters:

df_amp_phase_results: pandas.DataFrame

The dataframe containing the amplitude (depth) of modulation for each participant and outcome measure.

clamnibs.viz.plot_network_modulation_topo(df_network_results, n_conns, participant, info)[source]

Plot modulated network as connections between sensors on a topoplot.

Parameters:

df_network_results: pandas.DataFrame

The dataframe containing the connections which were modulated at the participant- or group-level.

n_connsint

The number of connections to plot. The n_conns most strongly modulated connections will be plotted.

participantstr

The participant in which the modulated network was identified. Can be ‘group’ for a group-level plot.

infomne.Info

The Info object for topographic plotting.

clamnibs.viz.plot_network_modulation_values(df_network_results, df_network_data, participant_identified_in, participant_applied_to)[source]

Plot connectivity values averaged within each modulated network as a box-/stripplot featuring each target phase.

Parameters:

df_network_results: pandas.DataFrame

The dataframe containing the connections which were modulated at the participant- or group-level.

df_network_data: pandas.DataFrame

The dataframe containing the connectivity matrix for each trial and participant.

participant_identified_instr

The participant in which the network was identified. This network mask will be applied to the data and plotted. Can be ‘group’ for group-level network.

participant_applied_tostr

The participant to whose data the network mask should be applied for plotting. Can be ‘group’ for group-level data.

clamnibs.viz.set_bads(obj, default_bads)[source]

Interactive tool to mark bad channels in EEG data.

This function provides an interactive visualization to mark bad channels in EEG data. It displays a scalp plot with the channels labeled, allowing the user to click on channels to mark them as bad.

Parameters:

objRawCLAM or EpochsCLAM object

The RawCLAM or EpochsCLAM object containing EEG data.

default_bads: list of str

The channels that are marked bad by default

Raises:

Exception:

If the input object is not an instance of RawCLAM or EpochsCLAM.

Notes:

  • This function requires Matplotlib to display the interactive visualization.

  • Bad channels are marked by clicking on the corresponding channel in the plot.

  • The plot window must be closed to finalize the selection of bad channels.

  • The updated list of bad channels is stored in the bads attribute of the input object.