'Extract PSD features from a 3D array that contains EEG data

I am new to EEG signal processing and I am trying to implement a function that calculates PSD features using Python.

The input of this function is a NumPy 3D-array called "trials", with size (240, 2047, 16) that contains EEG data in this form: (trials x time x channels)

I need to extract PSD features for the whole trial, for each channel and return an array of all the results.

Fs is 512Hz

This is my code so far:

from scipy import signal

def PSD(trials):
    psd = []
    fs = 512.
    
    for i in range(len(trials)):
        for j in range(len(trials[i])):
            f, Pxx = signal.welch(trials[i][j], fs, nperseg = 16)
            psd.append(Pxx)
        

    psd = np.array(psd)

    return psd

Is there a more efficient way to implement this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source