Problems in Implementing the EEG and Topomap Connectivity Calculation

Hello everyone,

I am currently working on the analysis of EEG data connectivity and have encountered difficulties while implementing the following code snippet:

import pandas as pd
import mne
import numpy as np
dado= pd.read_csv("/content/drive/MyDrive/Dados EEG/dado1.csv")
from matplotlib import pyplot as plt
channels =  ['Fp1','F7','F3','T3','C3','T5','P3','O1','O2','P4','T6','C4','T4','F4','F8','Fp2']
df = pd.read_csv("/content/drive/MyDrive/Dados EEG/dado1.csv", delimiter=",")
columns_to_drop = ["Time:512Hz", "Epoch", "Event Id", "Event Date", "Event Duration"]
df = df.drop(columns=columns_to_drop, errors='ignore')
df = df.dropna()
data = df.to_numpy()
print(f"Número de colunas nos dados após remoção: {data.shape[1]}")
montage = mne.channels.make_standard_montage('standard_1020')
info = mne.create_info(ch_names=channels, sfreq=512, ch_types='eeg')
raw =, info)
raw.set_montage(montage)"/content/drive/MyDrive/Dados EEG/data.fif", overwrite=True)
raw.plot_sensors(sphere=(0.00, 0.02, 0.03, 0.11),show_names=True)

freqs_notch = [60]
raw.notch_filter(freqs=freqs_notch, picks='eeg', filter_length='auto', phase='zero', verbose=True)

freqs_bandpass = [0.5, 99]
raw.filter(l_freq=freqs_bandpass[0], h_freq=freqs_bandpass[1], fir_design='firwin', verbose=True)


raw.plot_psd(fmax=200, average=True,xscale='log')

plt.text(-0.1, 0.5, va='center', rotation='vertical', fontsize=12, transform=plt.gca().transAxes)

freq_bands = {'Delta': (1, 4),
              'Theta': (4, 8),
              'Alpha': (8, 13),
              'Beta': (13, 30),
              'Gamma': (30, 50),
              'Super Gamma': (70, 90)}
extrapolations = ["local"]
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
axes = axes.flatten()
all_band_data = []

for i, (banda, (baixa, alta)) in enumerate(freq_bands.items()):
    raw_banda = raw.copy().filter(l_freq=baixa, h_freq=alta, method='iir', verbose=False)
    dados_banda = raw_banda.get_data()[:, 0]

    # Armazenando os dados da banda no vetor

    im, _ = mne.viz.plot_topomap(dados_banda,, axes=axes[i], sphere=(0.00, 0.02, 0.03, 0.11),cmap="Spectral_r", names=channels, contours=5, show=False)
    axes[i].set_title(f'Banda {banda}')
vmin = float('inf')
vmax = float('-inf')
for freq in range(len(dados_banda)):
    vmin = min(vmin, np.min(dados_banda[freq]))
    vmax = max(vmax, np.max(dados_banda[freq]))

norma = plt.Normalize(vmin=vmin, vmax=vmax)
cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.7])
cbar = plt.colorbar(im, cax=cbar_ax,
                    norm=norma)"uV²", fontsize=12)

plt.suptitle('Topomaps para Diferentes Bandas de Frequência', fontsize=16)
plt.tight_layout(rect=[0, 0, 0.9, 0.95])

I did a separate coherence calculation in another analysis:

canal_1 = 3
canal_2 = 4

resultados_coerencia = []
confianca = 0.95
for conjunto_dados in range(num_datasets):

    dados_canal_1 = dados_eeg_filtrado[:, canal_1, conjunto_dados]
    dados_canal_2 = dados_eeg_filtrado[:, canal_2, conjunto_dados]

    frequencies, coherence_values = coherence(dados_canal_1, dados_canal_2, fs=fs, window='hann', nperseg=janela, noverlap=overlap)

resultados_coerencia = np.array(resultados_coerencia)
L = num_datasets
epsilon = 1 - (1 - confianca) ** (1 / (L-1))
limite_confianca = 1 - epsilon

plt.figure(figsize=(12, 6))
for i in range(num_datasets):
    plt.plot(frequencies, resultados_coerencia[i], label=f'Conjunto de Dados {i+1}')

plt.axhline(y=limite_confianca, color='r', linestyle='--', label=f'Limite de Confiança ({int(confianca*100)}%)')

plt.title(f'Coerência entre Canal {canal_1 + 1} e Canal {canal_2 + 1} para Cada Conjunto de Dados com Limite de Confiança')
plt.xlabel('Frequência (Hz)')
plt.xlim(0, 14)
plt.ylim(0, 1)

Additionally, I am interested in creating a topomap to visualize connectivity. If anyone has experience with this and can guide me through the necessary steps, I would be very grateful.

Thank you in advance for any help or suggestions!

you could have a look at this: MNE-Connectivity — MNE-Connectivity 0.6.0 documentation

you are more likely to receive help if you detail what your exact problems are, and what steps you have already taken to solve them.

Furthermore, it is important to properly format your questions using the styling provided in the forum (for example, that code blocks are formatted as such). I have done that for you here now. Good luck!