import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from scipy.fft import fft, ifft
Chapter 17
Chapter 17
Analyzing Neural Time Series Data
Python code for Chapter 17 – converted from original Matlab by AE Studio (and ChatGPT)
Original Matlab code by Mike X Cohen
This code accompanies the book, titled “Analyzing Neural Time Series Data” (MIT Press).
Using the code without following the book may lead to confusion, incorrect data analyses, and misinterpretations of results.
Mike X Cohen and AE Studio assume no responsibility for inappropriate or incorrect use of this code.
Import necessary libraries
Figure 17.1
# Load data
= loadmat('../data/sampleEEGdata.mat')['EEG'][0, 0]
EEG
# Define parameters for figure 17.1
= 6
num_frex = np.logspace(np.log10(4), np.log10(30), num_frex)
frex = 6 / (2 * np.pi * frex)
s = np.arange(-1, 1 + 1/EEG['srate'][0][0], 1/EEG['srate'][0][0])
time
# Initialize wavelets
= np.zeros((num_frex, len(time)), dtype=complex)
mwaves = np.zeros((num_frex, len(time)), dtype=complex)
swaves
# Create Morlet wavelets and s-transforms
for fi in range(num_frex):
= np.exp(2 * 1j * np.pi * frex[fi] * time) * np.exp(-time**2 / (2 * (s[fi]**2)))
mwaves[fi, :] = np.exp(2 * 1j * np.pi * frex[fi] * time) * np.exp(-time**2 * frex[fi]**2 / 2)
swaves[fi, :]
# Additional parameters for convolution
= np.arange(-1, 1 + 1/EEG['srate'][0][0], 1/EEG['srate'][0][0])
time = len(time)
n_wavelet = EEG['pnts'][0][0] * EEG['trials'][0][0]
n_data = n_wavelet + n_data - 1
n_conv = (len(time) - 1) // 2
half_wave
# FFT of EEG data
= fft(EEG['data'][63, :, :].flatten('F'), n_conv)
eegfft
# Convolution
= ifft(fft(mwaves[4, :], n_conv) * eegfft)
eegconv = eegconv[half_wave:-half_wave]
eegconv
# Reshape to time X trials and compute power
= np.log10(np.abs(np.reshape(eegconv, (EEG['pnts'][0][0], EEG['trials'][0][0]), 'F')**2))
eegpower
# Plotting the results for figure 17.1
plt.figure()'times'][0], eegpower[:, 49])
plt.plot(EEG[-400, 1200])
plt.xlim([2, 4.5])
plt.ylim([= np.percentile(eegpower.flatten('F'), 95)
threshold =threshold, color='k')
plt.axhline(yf"power at electrode {EEG['chanlocs'][0][63]['labels'][0]} at {frex[4]:.4f} Hz")
plt.title( plt.show()
Figure 17.2
=(12, 6))
plt.figure(figsizefor i in range(num_frex):
2, 3, i+1)
plt.subplot(
plt.plot(time, np.real(mwaves[i, :]))'r.')
plt.plot(time, np.real(swaves[i, :]), -1, 1])
plt.xlim([-1, 1])
plt.ylim([f"{frex[i]:.4f} Hz")
plt.title(
plt.tight_layout() plt.show()