Modules

eeg

ectmetrics.eeg.DEFAULTS = {'add_noise': True, 'filters': {'bandpass': {'apply': True, 'options': {'highcut': 40, 'lowcut': 1}}, 'lowpass': {'apply': True, 'options': {'cutoff_freq': 30}}, 'notch': {'apply': True, 'options': {'notch_freq': 60}}}, 'immediate_seizure': True, 'sampling_frequency': 200, 'seizure_duration': 21, 'signal_duration': 28, 'stim_duration_ms': 1000, 'stim_time': 0}

Default settings for EEG signal generation.

This dictionary contains default parameters that can be used to generate simulated EEG signals. Each key represents a specific setting, which can be adjusted according to the needs of the user.

Keys: - signal_duration: int

Total duration of the signal in seconds.

  • sampling_frequency: int

    Sampling rate in Hz.

  • stim_time: int

    Time of stimulation in seconds.

  • stim_duration_ms: int

    Duration of stimulation in milliseconds.

  • seizure_duration: int

    Duration of the seizure in seconds.

  • add_noise: bool

    Whether to add background noise.

  • immediate_seizure: bool

    Whether to start the seizure immediately or after stimulation.

  • filters: dict

    Dictionary specifying which filters to apply.

ectmetrics.eeg.generate(signal_duration=28, sampling_frequency=200, stim_time=0, stim_duration_ms=1000, seizure_duration=21, add_noise=True, immediate_seizure=True, filters={'bandpass': {'apply': True, 'options': {'highcut': 40, 'lowcut': 1}}, 'lowpass': {'apply': True, 'options': {'cutoff_freq': 30}}, 'notch': {'apply': True, 'options': {'notch_freq': 60}}}, eeg_name=None)

Generate a simulated EEG signal with optional stimulation, seizure, and postictal phases for two channels.

Parameters

signal_durationfloat, optional

Total duration of the signal in seconds. Default is DEFAULTS['signal_duration'].

sampling_frequencyint, optional

Sampling rate in Hz. Default is DEFAULTS['sampling_frequency'].

stim_timefloat, optional

Time of stimulation in seconds. Default is DEFAULTS['stim_time'].

stim_duration_msint, optional

Duration of stimulation in milliseconds. Default is DEFAULTS['stim_duration_ms'].

seizure_durationfloat, optional

Duration of the seizure in seconds. Default is DEFAULTS['seizure_duration'].

add_noisebool, optional

Whether to add background noise. Default is DEFAULTS['add_noise'].

immediate_seizurebool, optional

Whether to start the seizure immediately or after stimulation. Default is DEFAULTS['immediate_seizure'].

filtersdict, optional

Dictionary specifying which filters to apply. Filters are defined as follows: - ‘bandpass’: {‘apply’: bool, ‘options’: {‘highcut’: float, ‘lowcut’: float}} - ‘lowpass’: {‘apply’: bool, ‘options’: {‘cutoff_freq’: float}} - ‘notch’: {‘apply’: bool, ‘options’: {‘notch_freq’: float}} Default is DEFAULTS['filters'].

eeg_namestr, optional

Name of the EEG file to save, if provided. Default is None.

Returns

dict

A dictionary containing the following keys: - ‘name’: str, Name of the EEG file. - ‘signals’: numpy.ndarray, 2D numpy array containing the simulated EEG signals for both channels. - ‘channels’: list of int, List of EEG channel indices. - ‘x-axis’: numpy.ndarray, Time array corresponding to the EEG signal. - ‘sampling_frequency’: int, The sampling frequency of the EEG signal. - ‘timepoints’: dict, A dictionary with the following keys:

  • ‘stim_startpoint’: int, The index where stimulation starts.

  • ‘seizure_startpoint’: int, The index where the seizure starts.

  • ‘seizure_endpoint’: int, The index where the seizure ends.

  • ‘filters’: dict, The applied filter configuration.

Notes

The function generates an EEG signal with customizable noise, filters, and event phases (stimulation, seizure, postictal). Filtering options include bandpass, lowpass, and notch filters that can be applied based on the configuration in the filters dictionary.

Example

>>> eeg.generate(signal_duration=28, sampling_frequency=200, stim_time=5, 
                 stim_duration_ms=500, seizure_duration=10, add_noise=True, 
                 immediate_seizure=False, filters={'bandpass': {'apply': True, 
                 'options': {'highcut': 40, 'lowcut': 1}}, 'lowpass': {'apply': True, 
                 'options': {'cutoff_freq': 30}}, 'notch': {'apply': True, 
                 'options': {'notch_freq': 60}}}, eeg_name='example_eeg')
ectmetrics.eeg.import_eeg(file_path, name=None)

Import EEG data from an EDF file and return it as a dictionary.

Parameters

file_pathstr

The path to the EDF file containing the EEG data.

namestr, optional

Name for the EEG data. If None, the first signal label from the file will be used as the name.

Returns

eegdict

A dictionary containing the EEG data with the following keys: - ‘name’ : str

The name assigned to the EEG data (either provided or the first signal label).

  • ‘signals’numpy.ndarray

    A 2D array containing the EEG signal data for all channels (shape: [n_channels, n_samples]).

  • ‘channels’list of int

    A list of channel indices corresponding to the signals.

  • ‘x-axis’numpy.ndarray

    Time vector corresponding to the EEG signal data.

  • ‘sampling_frequency’float

    The sampling frequency of the EEG signals in Hz.

Raises

FileNotFoundError

If the specified file_path does not exist.

ValueError

If the EDF file is invalid or does not contain EEG data.

Notes

This function requires the pyedflib library to read EDF files. Ensure that the library is installed in your environment. The time vector is generated based on the number of samples and the sampling frequency.

Examples

>>> eeg = import_eeg('path/to/eeg_data.edf')
>>> print(eeg['signals'])  # Access the EEG signal data
>>> print(eeg['sampling_frequency'])  # Access the sampling frequency
ectmetrics.eeg.plot(eeg, metrics=None)

Plot two-channel EEG signals with stimulation and seizure markers.

Parameters

eegdict

A dictionary containing EEG data with the following keys: - ‘name’ : str

The name of the EEG dataset.

  • ‘signals’numpy.ndarray

    A 2D array containing EEG signal data for all channels (shape: [n_channels, n_samples]).

  • ‘x-axis’numpy.ndarray

    Time vector corresponding to the EEG signal data.

  • ‘timepoints’dict

    A dictionary containing the following keys: - ‘stim_startpoint’ : int

    The sample index where stimulation starts.

    • ‘seizure_startpoint’int

      The sample index where the seizure starts.

    • ‘seizure_endpoint’int

      The sample index where the seizure ends.

  • ‘sampling_frequency’float

    The sampling frequency of the EEG signals in Hz.

metricslist of dict, optional

A list of metrics to plot on the EEG signals. Each metric dictionary should contain: - ‘name’ : str

The name of the metric.

  • ‘timepoints’dict

    A dictionary with either of the following: - ‘startpoint’ : int

    The sample index where the metric starts.

    • ‘endpoint’int

      The sample index where the metric ends.

    • ‘timepoint’int

      The sample index of a specific point in time related to the metric.

Example

>>> eeg_data = import_eeg('path/to/eeg_data.edf')  # Assuming this function is defined
>>> metrics = [{'name': 'Metric 1', 'timepoints': {'startpoint': 500, 'endpoint': 600}}]
>>> plot(eeg_data, metrics)

Notes

This function requires the matplotlib library for plotting. Ensure that the library is installed in your environment.

metric

ectmetrics.metric.metric(eeg, segment_length=256, metrics_list=None, seizure_duration=None, frequency_bands=None, debug=False)

Main function to calculate various seizure metrics based on the provided EEG data.

This function computes specified seizure metrics for given EEG signals, allowing customization of segment length, metrics to calculate, and frequency bands. It validates inputs and organizes the computation of metrics based on the specified list.

Parameters

eegdict

A dictionary containing EEG data with the following keys: - ‘signals’: A numpy array of EEG signals. - ‘sampling_frequency’: The sampling frequency of the EEG signals in Hz. - ‘timepoints’: A dictionary containing ‘seizure_startpoint’ and ‘seizure_endpoint’.

segment_lengthint, optional

Length of segments for calculation (default is set to DEFAULTS[‘segment_length’]).

metrics_listlist, optional

List specifying which metrics to calculate. It can contain metric names (strings) or dictionaries that specify the metric name and parameters.

seizure_durationint, optional

Duration of the seizure (not currently used but may be relevant for future metrics).

frequency_bandsdict, optional

Frequency bands for calculations (default includes common EEG bands).

debugbool, optional

If True, prints debug information to aid in tracing the computation (default is False).

Returns

resultslist

A list of dictionaries containing calculated metrics with the following structure: - name: The name of the metric. - value: The calculated value of the metric. - timepoints: A dictionary containing relevant timepoints. - unit: The unit of measurement. - description: A brief description of the metric.

Raises

ValueError

If any input data is invalid or if metrics cannot be calculated due to missing data.

Examples

>>> from ectmetrics.eeg import generate
>>> eeg_data = generate(signal_duration = 28, seizure_duration = 21, sampling_frequency = 200)
>>> result_metrics = metric(eeg_data, metrics_list=['asei', 'sei'], debug=True)
>>> print(result_metrics)
ectmetrics.metric.metric_asei(eeg_signals, eeg_channel, sampling_frequency, seizure_startpoint, seizure_endpoint, debug=False)

Calculate the Average Seizure Energy Index (ASEI) for a given EEG signal.

This function computes the Average Seizure Energy Index (ASEI) based on the provided EEG signals, focusing on a specified channel during a seizure event.

Parameters:

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channelint

The index of the EEG channel to analyze.

sampling_frequencyfloat

The sampling frequency of the EEG signal in Hz.

seizure_startpointfloat

The start point of the seizure in seconds.

seizure_endpointfloat

The end point of the seizure in seconds.

debugbool, optional

If True, prints debug information (default is False).

Returns:

dict

A dictionary containing the calculated ASEI metric, including: - name: The name of the metric (‘asei’). - value: The calculated ASEI value. - timepoints: A dictionary with the start and end points of the seizure. - unit: The unit of measurement (‘μV²’). - description: A brief description of the metric.

Raises:

Exception

If an error occurs during the calculation, an error message is printed, and None is returned.

Examples:

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data
>>> result = metric_asei(eeg_data, eeg_channel=0, sampling_frequency=256,
...                          seizure_startpoint=1.0, seizure_endpoint=2.0, debug=True)
>>> print(result)
ectmetrics.metric.metric_coh(eeg_signals, eeg_channel, sampling_frequency, segment_length, seizure_startpoint, n_consecutive_segments, debug=False)

Calculate the Maximum Sustained Coherence (COH) between two EEG channels during a seizure.

COH measures the degree of synchronization between the EEG signals of two channels over specified segments, focusing on the delta frequency band (0.78 - 3.5 Hz).

Parameters

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channellist[int]

A list containing the indices of the two EEG channels to analyze.

sampling_frequencyfloat

The sampling frequency of the EEG signals in Hz.

segment_lengthint

Length of each segment in samples.

seizure_startpointint

The start index of the seizure segment in samples.

n_consecutive_segmentsint

Number of consecutive segments to consider for coherence calculation.

debugbool, optional

If True, prints debug information (default is False).

Returns

dict

A dictionary containing the calculated COH metric, including: - name: The name of the metric (‘coh’). - value: The maximum sustained coherence value as a percentage. - timepoints: A dictionary with start and end points of the coherence measurement in samples. - unit: The unit of measurement (‘%’). - description: A brief description of the metric.

Raises

ValueError

If the signal is shorter than the required number of segments or if COH cannot be calculated.

Examples

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data for 2 channels
>>> coherence_result = metric_coh(eeg_data, eeg_channel=[0, 1], sampling_frequency=256,
...                                    segment_length=64, seizure_startpoint=50, n_consecutive_segments=4, debug=True)
>>> print(coherence_result)
ectmetrics.metric.metric_eia(eeg_signals, eeg_channel, segment_length, seizure_startpoint, seizure_endpoint, debug=False)

Calculate the Early Ictal Amplitude (EIA) for a given EEG signal segment.

The EIA represents the average absolute amplitude of the first eight segments of the seizure.

Parameters

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channelint

The index of the EEG channel to analyze.

segment_lengthint

Length of each segment in samples.

seizure_startpointint

The start point of the seizure in samples.

seizure_endpointfloat

The end time of the seizure in seconds.

debugbool, optional

If True, prints debug information (default is False).

Returns

dict

A dictionary containing the calculated EIA metric, including: - name: The name of the metric (‘eia’). - value: The calculated EIA value. - timepoints: A dictionary with the start and end points of the calculation. - unit: The unit of measurement (‘μV’). - description: A brief description of the metric.

Raises

ValueError

If the seizure segment is less than eight segments long.

Examples

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data
>>> eia_result = metric_eia(eeg_data, eeg_channel=0, segment_length=64,
...                            seizure_startpoint=50, seizure_endpoint=3.0, debug=True)
>>> print(eia_result)
ectmetrics.metric.metric_mia(eeg_signals, eeg_channel, segment_length, seizure_startpoint, seizure_endpoint, debug=False)

Calculate the Midictal Amplitude (MIA) for a given EEG signal segment.

The MIA represents the maximum average absolute amplitude of sequences of eight segments within the seizure period.

Parameters

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channelint

The index of the EEG channel to analyze.

segment_lengthint

Length of each segment in samples.

seizure_startpointint

The start point of the seizure in samples.

seizure_endpointfloat

The end time of the seizure in seconds.

debugbool, optional

If True, prints debug information (default is False).

Returns

dict

A dictionary containing the calculated MIA metric, including: - name: The name of the metric (‘mia’). - value: The calculated MIA value. - timepoints: A dictionary with the start and end points of the calculation. - unit: The unit of measurement (‘μV’). - description: A brief description of the metric.

Raises

ValueError

If the seizure segment is less than eight segments long or if no valid amplitudes can be calculated.

Examples

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data
>>> mia_result = metric_mia(eeg_data, eeg_channel=0, segment_length=64,
...                            seizure_startpoint=50, seizure_endpoint=3.0, debug=True)
>>> print(mia_result)
ectmetrics.metric.metric_msp(eeg_signals, eeg_channel, sampling_frequency, segment_length, seizure_startpoint, seizure_endpoint, frequency_bands, debug=False)

Calculate the Maximum Sustained Power (MSP) of EEG signals within a specified seizure segment.

The MSP represents the maximum average power over consecutive segments during a seizure, calculated using the Fast Fourier Transform (FFT).

Parameters

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channelint

The index of the EEG channel to analyze.

sampling_frequencyint

The sampling frequency of the signal in Hz.

segment_lengthint

Length of each segment in samples.

seizure_startpointint

The start point of the seizure in samples.

seizure_endpointfloat

The end time of the seizure in seconds.

frequency_bandsdict

A dictionary containing frequency bands for FFT power calculation, with keys as band names and values as tuples defining the frequency range (e.g., {‘alpha’: (8, 12), ‘beta’: (12, 30), ‘total’: (0, 40)}).

debugbool, optional

If True, prints debug information (default is False).

Returns

dict

A dictionary containing the calculated MSP metric, including: - name: The name of the metric (‘msp’). - value: The calculated MSP value. - timepoints: A dictionary with the start and end points of the calculation. - unit: The unit of measurement (‘μV²/Hz’). - description: A brief description of the metric.

Raises

ValueError

If the seizure segment is less than eight segments long or if no valid power values can be calculated.

Examples

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data
>>> frequency_bands = {'alpha': (8, 12), 'beta': (12, 30), 'total': (0, 40)}
>>> msp_result = metric_msp(eeg_data, eeg_channel=0, sampling_frequency=256,
...                             segment_length=64, seizure_startpoint=50, seizure_endpoint=3.0,
...                             frequency_bands=frequency_bands, debug=True)
>>> print(msp_result)
ectmetrics.metric.metric_psi(eeg_signals, eeg_channel, sampling_frequency, segment_length, seizure_endpoint, debug=False)

Calculate the Postictal Suppression Index (PSI) for a given EEG signal.

The PSI quantifies the level of suppression in the EEG signal following a seizure, comparing the amplitude of ictal (during the seizure) and non-ictal (after the seizure) segments.

Parameters

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channelint

The index of the EEG channel to analyze.

sampling_frequencyfloat

The sampling frequency of the EEG signal in Hz.

segment_lengthint

Length of each segment in samples.

seizure_endpointfloat

The end time of the seizure in seconds.

debugbool, optional

If True, prints debug information (default is False).

Returns

dict

A dictionary containing the calculated PSI metric, including: - name: The name of the metric (‘psi’). - value: The calculated PSI value. - timepoints: A dictionary with the start and end points of the calculation. - unit: The unit of measurement (‘%’). - description: A brief description of the metric.

Raises

ValueError

If calculated indices are out of bounds of the EEG signal.

Examples

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data
>>> psi_result = metric_psi(eeg_data, eeg_channel=0, sampling_frequency=256,
...                           segment_length=64, seizure_endpoint=3.0, debug=True)
>>> print(psi_result)
ectmetrics.metric.metric_sei(eeg_signals, eeg_channel, sampling_frequency, segment_length, seizure_startpoint, seizure_endpoint, asei=None, debug=False)

Calculate the Seizure Energy Index (SEI) based on the Average Seizure Energy Index (ASEI).

This function computes the SEI for a specified EEG channel during a seizure event, utilizing the ASEI to quantify the energy associated with the seizure duration.

Parameters

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channelint

The index of the EEG channel to analyze.

sampling_frequencyfloat

The sampling frequency of the EEG signal in Hz.

segment_lengthfloat

The length of the segment in seconds (used for potential future extensions).

seizure_startpointfloat

The start point of the seizure in seconds.

seizure_endpointfloat

The end point of the seizure in seconds.

aseifloat, optional

The Average Seizure Energy Index in microvolts squared. If not provided, it will be calculated.

debugbool, optional

If True, prints debug information (default is False).

Returns

dict

A dictionary containing the calculated SEI metric, including: - name: The name of the metric (‘sei’). - value: The calculated SEI value. - timepoints: A dictionary with the start and end points of the seizure. - unit: The unit of measurement (‘μV²·s’). - description: A brief description of the metric.

Raises

Exception

If an error occurs during the calculation, an error message is printed, and None is returned.

Examples

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data
>>> sei_result = metric_sei(eeg_data, eeg_channel=0, sampling_frequency=256,
...                            segment_length=2.0, seizure_startpoint=1.0,
...                            seizure_endpoint=3.0, asei=10.0, debug=True)
>>> print(sei_result)
ectmetrics.metric.metric_ttpc(eeg_signals, eeg_channel, sampling_frequency, segment_length, seizure_startpoint, n_consecutive_segments, coh_startpoint=None, coh_endpoint=None, debug=False)

Calculate the Time to Peak Coherence (TTPC) during a seizure segment.

TTPC is defined as the time taken to reach the peak coherence value between two EEG channels.

Parameters

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channellist[int]

A list containing the indices of the two EEG channels to analyze.

sampling_frequencyfloat

The sampling frequency of the EEG signals in Hz.

segment_lengthint

Length of each segment in samples.

seizure_startpointint

The start index of the seizure segment in samples.

n_consecutive_segmentsint

Number of consecutive segments to consider for coherence calculation.

coh_startpointint, optional

The startpoint of coherence measurement. If not provided, will be calculated from coherence results.

coh_endpointint, optional

The endpoint of coherence measurement. If not provided, will be calculated from coherence results.

debugbool, optional

If True, prints debug information (default is False).

Returns

dict

A dictionary containing the calculated TTPC metric, including: - name: The name of the metric (‘ttpc’). - value: The time to peak coherence in seconds. - timepoints: A dictionary with the calculated timepoint in samples. - unit: The unit of measurement (‘s’). - description: A brief description of the metric.

Raises

ValueError

If the coherence startpoint or endpoint values are invalid or cannot be calculated.

Examples

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data for 2 channels
>>> ttp_result = metric_ttpc(eeg_data, eeg_channel=[0, 1], sampling_frequency=256,
...                              segment_length=64, seizure_startpoint=50, n_consecutive_segments=4, debug=True)
>>> print(ttp_result)
ectmetrics.metric.metric_ttpp(eeg_signals, eeg_channel, sampling_frequency, segment_length, seizure_startpoint, seizure_endpoint, frequency_bands, msp_startpoint=None, msp_endpoint=None, debug=False)

Calculate the Time to Peak Power (TTPP) for EEG signals during a seizure.

TTPP is the time taken to reach the peak power during a seizure event, calculated based on the Maximum Sustained Power (MSP).

Parameters

eeg_signalsnumpy.ndarray

A 2D numpy array containing the EEG signals, where each row corresponds to a different channel.

eeg_channelint

The index of the EEG channel to analyze.

sampling_frequencyint

The sampling frequency of the signal in Hz.

segment_lengthint

Length of each segment in samples.

seizure_startpointint

The start point of the seizure in samples.

seizure_endpointfloat

The end time of the seizure in seconds.

frequency_bandsdict

A dictionary containing frequency bands for FFT power calculation, with keys as band names and values as tuples defining the frequency range (e.g., {‘alpha’: (8, 12), ‘beta’: (12, 30), ‘total’: (0, 40)}).

msp_startpointint, optional

Start point of the maximum sustained suppression sample; if None, it will be calculated.

msp_endpointint, optional

Endpoint of the maximum sustained suppression sample; if None, it will be calculated.

debugbool, optional

If True, prints debug information (default is False).

Returns

dict

A dictionary containing the calculated TTPP metric, including: - name: The name of the metric (‘ttpp’). - value: The calculated TTPP value in seconds. - timepoints: A dictionary with the timepoint of TTPP in samples. - unit: The unit of measurement (‘s’). - description: A brief description of the metric.

Raises

ValueError

If the MSP start point or endpoint values are invalid or if an error occurs during the MSP calculation.

Examples

>>> eeg_data = np.random.randn(2, 1000)  # Simulated EEG data
>>> frequency_bands = {'alpha': (8, 12), 'beta': (12, 30), 'total': (0, 40)}
>>> ttpp_result = metric_ttpp(eeg_data, eeg_channel=0, sampling_frequency=256,
...                               segment_length=64, seizure_startpoint=50, seizure_endpoint=3.0,
...                               frequency_bands=frequency_bands, debug=True)
>>> print(ttpp_result)