cannot import name 'compute_psd' from 'mne'

In the python code of epilepsy detetion, after the code of section 1, the codes of section 2 are written with the use of the function ‘psd_welch’ of the ‘mne.time_frequency’ module.

Section 1:

!pip install mne -q

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

meta_df= pd.read_csv(‘C:\Users\user\Desktop\Python Project\EEGs_Guinea-Bissau\metadata_guineabissau.csv’)

display(meta_df)

#now i need to seprate Epilepsy vs Control subjects
EP_sub=meta_df[‘subject.id’][meta_df[‘Group’]==‘Epilepsy’]
CT_sub=meta_df[‘subject.id’][meta_df[‘Group’]==‘Control’]

#read csv files
Epilepsy=[pd.read_csv(‘EEGs_Guinea-Bissau/signal-{}.csv.gz’.format(i), compression=‘gzip’) for i in EP_sub]
Control=[pd.read_csv(‘EEGs_Guinea-Bissau/signal-{}.csv.gz’.format(i), compression=‘gzip’) for i in CT_sub]

Epilepsy[0].head()

#remove non eeg channels
Epilepsy=[i.iloc[:,1:15] for i in Epilepsy]
Control=[i.iloc[:,1:15] for i in Control]

import mne
def convertDF2MNE(sub):
info = mne.create_info(list(sub.columns), ch_types=[‘eeg’] * len(sub.columns), sfreq=128)
info.set_montage(‘standard_1020’)
data=mne.io.RawArray(sub.T, info)
data.set_eeg_reference()
data.filter(l_freq=0.1,h_freq=45)
epochs=mne.make_fixed_length_epochs(data,duration=5,overlap=1)
epochs=epochs.drop_bad()

return epochs

%%capture
#Convert each dataframe to mne object
Epilepsy=[convertDF2MNE(i) for i in Epilepsy]
Control=[convertDF2MNE(i) for i in Control]

%%capture
#concatenate the epochs
Epilepsy_epochs=mne.concatenate_epochs(Epilepsy)
Control_epochs=mne.concatenate_epochs(Control)

Epilepsy_group=np.concatenate([[i]*len(Epilepsy[i]) for i in range(len(Epilepsy))])#create a list of list where each sub list corresponds to subject_no
Control_group=np.concatenate([[i]*len(Control[i]) for i in range(len(Control))])#create a list of list where each sub list corresponds to subject_no

Epilepsy_label=np.concatenate([[0]*len(Epilepsy[i]) for i in range(len(Epilepsy))])
Control_label=np.concatenate([[1]*len(Control[i]) for i in range(len(Control))])

Epilepsy_group.shape,Control_group.shape,Epilepsy_label.shape,Control_label.shape

#combine data
data=mne.concatenate_epochs([Epilepsy_epochs,Control_epochs])
group=np.concatenate((Epilepsy_group,Control_group))
label=np.concatenate((Epilepsy_label,Control_label))
print(len(data),len(group),len(label))

Section 2:

from mne.time_frequency import psd_welch
def eeg_power_band(epochs):

# specific frequency bands

FREQ_BANDS = {"delta": [0.5, 4.5],
              "theta": [4.5, 8.5],
              "alpha": [8.5, 11.5],
              "sigma": [11.5, 15.5],
              "beta": [15.5, 30],
              "gamma": [30, 45],
              }

psds, freqs = psd_welch(epochs, picks='eeg', fmin=0.5, fmax=45) # Compute the PSD using the Welch method
psds /= np.sum(psds, axis=-1, keepdims=True)    # Normalize the PSDs

X = [x]#For each frequency band, compute the mean PSD in that band
for fmin, fmax in FREQ_BANDS.values():
    psds_band = psds[:, :, (freqs >= fmin) & (freqs < fmax)].mean(axis=-1)# Compute the mean PSD in each frequency band.
    X.append(psds_band)

return np.concatenate(X, axis=1)   #Concatenate the mean PSDs for each band into a single feature vector

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

%%capture
features=[ ]
for d in range(len(data)):# get features from each epoch and save in a list
features.append(eeg_power_band(data[d]))

convert list to array

features=np.concatenate(features)
features.shape

#do 5 fold cross validation
clf=RandomForestClassifier()
accuracies=cross_val_score(clf, features,label,groups=group,cv=5)
print(‘Five fold accuracies’,accuracies)
print(‘Average accuracy’,np.mean(accuracies))

Output should be like this :
Five fold accuracies [0.71380697 0.69953052 0.63782696 0.73105298 0.69014085]
Average accuracy 0.6944716556712932

*** Now how can I convert the ‘section 2’ of the aforementioned code with the ‘compute_psd()’ method of the ‘Raw’ or ‘Epochs’ object so that no error is faced, since the function ‘psd_welch’ is no longer available in the ‘mne.time_frequency’ module. This is because the function was deprecated in version 1.2 of MNE and removed in version 1.3. # My mentioned code is copied from internet from a github platform, ( https://github.com/talhaanwarch/youtube-tutorials/blob/main/eeg_epilepsy.ipynb)
i am a rookie in this field. He used this ‘mne.time_frequency’. But at present time, this is not working.

N.B.: The result should remain same and no error must be occurred in the output. Please help me out, I am in a great trouble for this. **My jupyter notebook version is: 3.11.4 | packaged by Anaconda, Inc. | (main, Jul 5 2023, 13:38:37) [MSC v.1916 64 bit (AMD64)] ##Operating system: Windows 11 ** You can download the data set from- https://zenodo.org/record/1252141/files/EEGs_Guinea-Bissau.zip

Please read How to correctly format your question and edit your post accordingly.

1 Like