# Problems in Implementing the EEG and Topomap Connectivity Calculation

**URL:** <https://mne.discourse.group/t/problems-in-implementing-the-eeg-and-topomap-connectivity-calculation/8230>\
**Category:** Support & Discussions\
**Tags:** eeg, visualization, connectivity\
**Created:** [January 29, 2024, 7:06pm UTC](https://mne.discourse.group/t/problems-in-implementing-the-eeg-and-topomap-connectivity-calculation/8230 "2024-01-29T19:06:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![leticiaainoan](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/leticiaainoan/32/3406_2.png) [@leticiaainoan](https://mne.discourse.group/u/leticiaainoan)\
**Post date:** [January 29, 2024, 7:06pm UTC](https://mne.discourse.group/t/problems-in-implementing-the-eeg-and-topomap-connectivity-calculation/8230/1 "2024-01-29T19:06:10Z")

</div>

Hello everyone,

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

```python
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 = mne.io.RawArray(data.T, info)
raw.set_montage(montage)
raw.save("/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.set_eeg_reference("average")

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)
plt.show()

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
    all_band_data.append(dados_banda)

    im, _ = mne.viz.plot_topomap(dados_banda, raw_banda.info, 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)
cbar.ax.set_title("uV²", fontsize=12)

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

```

I did a separate coherence calculation in another analysis:

```python
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.append(coherence_values)

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.ylabel('Coerência')
plt.xlim(0, 14)
plt.ylim(0, 1)
plt.legend()
plt.grid(True)
plt.show()

```

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!

---

<div class="post-metadata">

**Author:** ![sappelhoff](https://yyz2.discourse-cdn.com/free1/user_avatar/mne.discourse.group/sappelhoff/32/3276_2.png) [@sappelhoff](https://mne.discourse.group/u/sappelhoff)\
**Post date:** [February 19, 2024, 10:43am UTC](https://mne.discourse.group/t/problems-in-implementing-the-eeg-and-topomap-connectivity-calculation/8230/2 "2024-02-19T10:43:45Z")

</div>

> [@leticiaainoan](#):
>
> 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.

you could have a look at this: [MNE-Connectivity — MNE-Connectivity 0.6.0 documentation](https://mne.tools/mne-connectivity/stable/index.html)

> [@leticiaainoan](#):
>
> I am currently working on the analysis of EEG data connectivity and have encountered difficulties while implementing the following code snippet:

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!
