# Spectral Connectivity of Each Epoch

**URL:** <https://mne.discourse.group/t/spectral-connectivity-of-each-epoch/3521>\
**Category:** Support & Discussions\
**Tags:** eeg\
**Created:** [August 10, 2021, 3:35pm UTC](https://mne.discourse.group/t/spectral-connectivity-of-each-epoch/3521 "2021-08-10T15:35:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![balandongiv](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/balandongiv/32/104_2.png) [@balandongiv](https://mne.discourse.group/u/balandongiv)\
**Post date:** [August 10, 2021, 3:35pm UTC](https://mne.discourse.group/t/spectral-connectivity-of-each-epoch/3521/1 "2021-08-10T15:35:39Z")

</div>

This is extension regarding my old post about [Return Spectral Connectivity of Each Epoch](https://mne.discourse.group/t/return-spectral-connectivity-of-each-epoch-disarmed/2368). Since Im unable to add an answer on that post, I will create new one instead.

Spectral Connectivity of Each Epoch can be found under the function `connectivity_per_epochs ()`.For comparison, the typical MNE python implementation over trials is included which can be accessed via `connectivity_average_epochs ()`

```python
import mne
from mne.connectivity import spectral_connectivity
from mne.viz import circular_layout, plot_connectivity_circle
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

def data_setting ():
    # Formating setting
    label_names = ['FP1', 'FP2', 'F3', 'F4', 'F7', 'F8', 'C3', 'C4',
                   'T3', 'T4', 'O1', 'O2']

    Freq_Bands = {"delta": [1.25, 4.0],"theta": [4.0, 8.0],
                  "alpha": [8.0, 13.0],"beta": [13.0, 30.0],"gamma": [30.0, 49.0]}

    lh_labels = ['FP1', 'F7', 'F3', 'C3', 'T3', 'O1']
    rh_labels = ['FP2', 'F8', 'F4', 'C4', 'T4', 'O2']

    connectivity_methods = ["coh"]
    set_data = {'label_names': label_names, 'Freq_Bands': Freq_Bands, 'lh_labels': lh_labels,
                'rh_labels': rh_labels, 'connectivity_methods': connectivity_methods}

    return set_data

def create_epochs (set_data):
    # Generate data
    np.random.seed ( 42 )
    n_epochs = 5
    n_channels = len ( set_data ['label_names'] )
    n_times = 1000
    data = np.random.rand ( n_epochs, n_channels, n_times )
    # Set sampling freq
    sfreq = 256 # A reasonable random choice

    # 10Hz sinus waves with random phase differences in each channel and epoch
    # Generate 10Hz sinus waves to show difference between connectivity
    # over time and over trials. Here we expect con over time = 1
    for i in range ( n_epochs ):
        for c in range ( n_channels ):
            wave_freq = 10
            epoch_len = n_times / sfreq
            # Introduce random phase for each channel
            phase = np.random.rand ( 1 ) * 10
            # Generate sinus wave
            x = np.linspace ( -wave_freq * epoch_len * np.pi + phase,
                              wave_freq * epoch_len * np.pi + phase, n_times )
            data [i, c] = np.squeeze ( np.sin ( x ) )

    return mne.EpochsArray ( data, mne.create_info ( ch_names=set_data ['label_names'],
                                                     ch_types=['eeg'] * len ( set_data ['label_names'] ),
                                                     sfreq=sfreq ) )

def define_freq_bands (set_data):
    # Define freq bands
    return tuple (
        [list ( set_data ['Freq_Bands'].values () ) [f] [0] for f in
         range ( len ( set_data ['Freq_Bands'] ) )] ), tuple (
        [list ( set_data ['Freq_Bands'].values () ) [f] [1] for f in range ( len ( set_data ['Freq_Bands'] ) )] )

def _connectivity_average_epochs (epochs=None, set_data=None):
    # # Calculate PLV a - the MNE python implementation is over trials
    fmin, fmax = define_freq_bands ( set_data )

    con, freqs, times, n_epochs, n_tapers = spectral_connectivity (
        epochs, method=set_data ['connectivity_methods'],
        mode="multitaper", sfreq=epochs.info ['sfreq'], fmin=fmin, fmax=fmax,
        faverage=False, verbose=0 )

    return con, epochs.ch_names

def _connectivity_per_epochs (epochs, set_data):
    # # Calculate PLV for each trial
    fmin, fmax = define_freq_bands ( set_data )

    all_con = []
    for epoch in epochs:
        con_each, freqs, times, n_epochs, n_tapers = spectral_connectivity (
            [epoch], method=set_data ['connectivity_methods'],
            mode="multitaper", sfreq=epochs.info ['sfreq'], fmin=fmin, fmax=fmax,
            faverage=False, verbose=0 )
        all_con.append ( con_each )

    return all_con, epochs.ch_names

def plot_conn (conmat, all_ch, idx, bands, set_data):
    # Generate circular graph
    node_order = set_data ['lh_labels'] + set_data ['rh_labels']
    node_angles = circular_layout ( all_ch, node_order, start_pos=90,
                                    group_boundaries=[0, len ( all_ch ) // 2] )

    fig = plt.figure ( num=None, figsize=(8, 8), facecolor='black' )

    canvas = FigureCanvas ( fig )
    plot_connectivity_circle ( conmat, all_ch, n_lines=300,
                               node_angles=node_angles,
                               title=f'All-to-All Connectivity_ band_{bands}', fig=fig )

    canvas.draw ()
    s, (width, height) = canvas.print_to_buffer ()
    im0 = np.frombuffer ( s, np.uint8 ).reshape ( (height, width, 4) )
    return im0

set_data = data_setting ()

def connectivity_average_epochs ():
    con, all_ch = _connectivity_average_epochs ( epochs=create_epochs ( set_data ), set_data=set_data )

    all_fig = [plot_conn ( con [:, :, idx], all_ch, idx, band, set_data ) for idx, band in
               enumerate ( ["delta", "theta", "alpha", "beta", "gamma"] )]

    plt.imsave ( 'connectivity_average_epochs.png', np.hstack ( all_fig ) )

def connectivity_per_epochs ():
    con_per_epochs, all_ch = _connectivity_per_epochs ( epochs=create_epochs ( set_data ), set_data=set_data )

    for idx_epoch, con in enumerate ( con_per_epochs ):
        all_fig = [plot_conn ( con [:, :, idx], all_ch, idx, band, set_data ) for idx, band in
                   enumerate ( ["delta", "theta", "alpha", "beta", "gamma"] )]

        plt.imsave ( f'epoch_{idx_epoch}_per_epoch_connectivity.png', np.hstack ( all_fig ) )

connectivity_average_epochs ()
connectivity_per_epochs ()

```

This will produced

connectivity\_average\_epochs

 ![connectivity_average_epochs](https://global.discourse-cdn.com/free1/uploads/mne/original/1X/c9172da4a935556175124dbbf4bbf4954cb6fef7.png)

The connectivity for epoch index 0,1,2,3,4 are as below

 ![epoch_0_per_epoch_connectivity](https://global.discourse-cdn.com/free1/uploads/mne/original/1X/3c473d5428442f3cb8623d05eaae472bf181ba12.png)  
epoch 0

 ![epoch_1_per_epoch_connectivity](https://global.discourse-cdn.com/free1/uploads/mne/original/1X/2c7ce92c27d9a18643b30bcfcaa2cdf550982a07.png)

epoch 1

 ![epoch_2_per_epoch_connectivity](https://global.discourse-cdn.com/free1/uploads/mne/original/1X/2b8f827e1475e306ab0a894f9cfe9f74f3ec2ef9.png)

epoch 2

 ![epoch_3_per_epoch_connectivity](https://global.discourse-cdn.com/free1/uploads/mne/original/1X/d40642d98a8c2256a099ac905de3b98b0abb1d19.png)

epoch 3

 ![epoch_4_per_epoch_connectivity](https://global.discourse-cdn.com/free1/uploads/mne/original/1X/8905bf82d62e7176c7f6a08fb7139a9d2aa3c0e5.png)

epoch 4

Should this step and output is correct, maybe either of the expert can confirm and close this thread.

Related discussion:

> [@\[mne-python\] use spectral\_connectivity on a single	epoch](https://mne.discourse.group/t/mne-python-use-spectral-connectivity-on-a-single-epoch/785/3):
>
> hi mads, just call spectral\_connectivity on each epoch. for k in range(len(epochs)): &nbsp;&nbsp;&nbsp;&nbsp;out = spectral\_connectivity(epochs[k], ...) &nbsp;&nbsp;&nbsp;&nbsp;.... Arent' these all measures that are defined across epochs?? or something along these lines. HTH Alex \> Hi all, \> \> Using mne-python, is it possible to use spectral\_connectivity on a \> single epoch at a time. \> \> I have a single subject and I would like to calculate the Phase-Locking \> Value (or similar "connectivity" measure) on single tri…

> [@Return Spectral Connectivity of Each Epoch {Disarmed}](https://mne.discourse.group/t/return-spectral-connectivity-of-each-epoch-disarmed/2368):
>
> External Email - Use Caution Dear Group, The objective is to compute frequency connectivity measures. Say we have 70 epochs of an event with the id 1, and I would like the connectivity measures each of the epoch. However, I noticed the spectral\_connectivity() return an average connectivity measures value of all the 70 epochs (please correct this if I'm wrong). I have checked the documentation ([https://secure-web.cisco.com/1Gf0PHvuRFQv76oTm1ABAUmOVTk9MHhrw8EqhEsEaoAUypEMpA6HoZzm56S1KPbJP…](https://secure-web.cisco.com/1Gf0PHvuRFQv76oTm1ABAUmOVTk9MHhrw8EqhEsEaoAUypEMpA6HoZzm56S1KPbJP5SlpoAgAq2VR3Rp7Ff96ecibUq67Ro5_CpoEd2PrLVeUR9X8pll0HRaEtCw-w3Wk1yFJueGe9mvLz9JVUmRILxV_g4JI9Azx-FJHJrQMLcu7I0qOlVytQuIoXA_-3GF-oFjDMZ-OvC3PmMSoQv5Bmg/https%3A%2F%2Fmne.tools%2Fstable%2Fgenerated%2Fmne.connectivity.spectral_connectivity.h)

> [@Questionable connectivity output when feeding epoch by epoch into the spectral\_connectivity module](https://mne.discourse.group/t/questionable-connectivity-output-when-feeding-epoch-by-epoch-into-the-spectral-connectivity-module/2649):
>
> MNE-Python version: 0.21.2 WSL Ubuntu: The objective is to compute the spectral connectivity measures for each of the epoch as discussed [here](https://mne.discourse.group/t/return-spectral-connectivity-of-each-epoch-disarmed/2368). Along the pipeline, the list of epochs will be croped in between x duration and each epoch will be extracted and feed separately into the spectral\_connectivity module. For example, the epochs will trimed between tmin=-60 and tmax=-56. For the sake of the discussion, let us calculate the spectral\_connectivity of the epoch with index 0 as shown per th…

> [@Phase Lag Index connectivity using single epoch](https://mne.discourse.group/t/phase-lag-index-connectivity-using-single-epoch/1420):
>
> Hi, The PLI requires multiple epochs/trials to give a meaningful result, since it essentially measures the variability of phase differences across trials. By definition, a single epoch has no variability so this explains your result. If you only have a single epoch, then measures like the PLI are not appropriate. (I can't look it up right now, but most likely Figure 6 did indeed show a result from several epochs.) Cheers Sarang

---

<div class="post-metadata">

**Author:** ![drammock](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/drammock/32/4_2.png) [@drammock](https://mne.discourse.group/u/drammock)\
**Post date:** [August 12, 2021, 9:55pm UTC](https://mne.discourse.group/t/spectral-connectivity-of-each-epoch/3521/2 "2021-08-12T21:55:03Z")

</div>

it’s not entirely clear what your question is here, but it looks like you’re posting more than 100 lines of code and asking “did I do this right?” It is unlikely that you will get a good answer when asking your question this way, because it simply takes too much time/effort for others to read through and understand what you did, with no guidance as to which parts you’re unsure of. Please consider revising your question to summarize what you’re trying to do (simulate data with an expected connectivity structure, and test that you can recover it?) and what you want help with (the simulation? interpreting the plots? something else?)

---

<div class="post-metadata">

**Author:** ![balandongiv](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/balandongiv/32/104_2.png) [@balandongiv](https://mne.discourse.group/u/balandongiv)\
**Post date:** [August 13, 2021, 7:26am UTC](https://mne.discourse.group/t/spectral-connectivity-of-each-epoch/3521/3 "2021-08-13T07:26:41Z")

</div>

Hi, I notice question about calculating `Spectral Connectivity of Each Epoch` have been pop up several time. The intention was to share possible way of addressing this issue. Kindly delete this OP if does not meet the mne Q&A requirement
