Analyze EEG data#
This notebook will help you prepare the figures for your EEG lab report.
To run this notebook:
Export two separate LabChart Text File (.txt) of 30 seconds of data for both eyes open and closed.
Upload the file to Colab.
Change the filename below to match the name of your file.
import numpy as np
# Change the filenames to EXACTLY match your files
closed_filename = 'EEG_Trial1_EyesClosed.txt'
open_filename = 'EEG_Trial1_EyesOpen.txt'
sampling_freq = 400
# Define column names
columns = ['time', 'recording']
# Use numpy genfromtxt to import both files
closed_data = np.genfromtxt(closed_filename, dtype=float, usecols=(0,1), skip_header=6, delimiter='\t', names=columns, encoding = 'unicode_escape')
open_data = np.genfromtxt(open_filename, dtype=float, usecols=(0,1), skip_header=6, delimiter='\t', names=columns, encoding = 'unicode_escape')
# Define a function to remove nan values
def nan_helper(y):
return np.isnan(y), lambda z: z.nonzero()[0]
# Save recording & timestamps as variables
closed_timestamps = closed_data['time']
closed_recording = closed_data['recording']
nans, x = nan_helper(closed_recording)
closed_recording[nans]= np.interp(x(nans), x(~nans), closed_recording[~nans])
open_timestamps = open_data['time']
open_recording = open_data['recording']
nans, x = nan_helper(open_recording)
open_recording[nans]= np.interp(x(nans), x(~nans), open_recording[~nans])
closed_recording
array([-125.95 , -124.95 , -139.2875 , ..., 69.21875, 63.8625 ,
59.76875])
Remove 60 Hz line noise#
Electrical outlets and equipment in the room run on 60 Hz alternating current, and this “line noise” often shows up in EEG recordings as a large, sharp peak at 60 Hz. Below, we’ll apply a notch filter, which removes a very narrow band of frequencies around 60 Hz while leaving the rest of the signal (including alpha waves at 8–13 Hz) untouched.
This step is totally optional and you should skip it if you applied a Notch filter in LabChart.
Notes:
The
quality_factorcontrols how narrow the notch is. Higher values remove a narrower band of frequencies.After this cell,
closed_recordingandopen_recordingcontain the filtered data, so every step below uses the filtered signal. The original data are saved asclosed_recording_rawandopen_recording_rawin case you want to compare them.
from scipy import signal
notch_freq = 60 # Frequency to remove (Hz)
quality_factor = 30 # Higher values make a narrower notch
# Design the notch filter
b, a = signal.iirnotch(notch_freq, quality_factor, sampling_freq)
# Save copies of the unfiltered recordings
closed_recording_raw = closed_recording.copy()
open_recording_raw = open_recording.copy()
# Apply the filter forwards and backwards (filtfilt) so the signal isn't shifted in time
closed_recording = signal.filtfilt(b, a, closed_recording_raw)
open_recording = signal.filtfilt(b, a, open_recording_raw)
Plot the data#
Now, we can plot the data! First, let’s make an interactive plot so you can scroll through your whole recording and look for interesting features (like alpha waves).
How to use the interactive plot:
Click and drag on the plot to scroll left and right through time.
Drag the edges of the gray window in the slider under the plot to change how many seconds are shown, or drag the window itself to move through the recording.
Scroll (or pinch on a trackpad) to zoom in and out.
Double-click the plot to reset the view to the full recording.
Hover over the trace to see exact time & voltage values.
Notes:
To explore your eyes open data, change
closed_timestampstoopen_timestampsandclosed_recordingtoopen_recording.window_secsets how many seconds are shown when the plot first appears.
# Import interactive plotting package
import plotly.graph_objects as go
# Change the variables below if you'd like to explore eyes open instead
timestamps = closed_timestamps
recording = closed_recording
window_sec = 5 # Number of seconds shown when the plot first appears
fig = go.Figure(go.Scatter(x=timestamps, y=recording, mode='lines', line=dict(width=1)))
fig.update_layout(
height=450,
template='simple_white',
dragmode='pan', # Click & drag scrolls through time
xaxis=dict(title='Time (s)', # You may need to change the x label!
range=[timestamps[0], timestamps[0] + window_sec],
rangeslider=dict(visible=True, thickness=0.12)),
yaxis=dict(title='Voltage', fixedrange=False), # You may need to change the y label!
margin=dict(l=60, r=20, t=30, b=40))
fig.show(config={'scrollZoom': True})
Once you’ve found a section of data you’d like to show in your lab report, use the cell below to make a static figure of it.
Notes:
You may want to change the x and y labels below.
Change the numbers in
plt.xlimto the time window you want to show – for example, to zoom into alpha waves.You can use this same cell to plot your eyes open data by changing
closed_timestampstoopen_timestampsandclosed_recordingtoopen_recording.
# Import plotting packages
import matplotlib.pyplot as plt
# Set up figure
fig,ax = plt.subplots(figsize=(10,4))
# Change the variables below if you'd like to plot eyes open instead
plt.plot(closed_timestamps,closed_recording)
# You may need to change the x label!
plt.xlabel('Time')
# You may need to change the y label!
plt.ylabel('Voltage')
# You can uncomment the line below to restrict the x axis plotting -- for example, to zoom into alpha waves
plt.xlim([45,50])
plt.show()
Calculate the power spectrum of our EEG data#
Below, we’ll implement a fast Fourier transform (fft) to see the frequencies in our data.
# Calculate the fourier transform of complex signal
ft = np.fft.fft(closed_recording)/len(closed_timestamps) # Compute the fft, normalized by time
# Find frequency values for the x axis
nyq = sampling_freq/2 # Determine the nyquist frequency
# Create freq bins for plotting by creating a vector from 0 to nyquist, with as many points as in fft
fx_bins = np.linspace(0,nyq,int(np.floor(len(closed_recording)/2))+1)
# plotting up to 200 Hz
plt.figure(figsize=(8, 6))
plt.plot(fx_bins[0:1500],abs(ft[0:1500]))
plt.ylabel('Power (V^2 / Hz)')
plt.xlabel('Frequency (Hz)')
plt.title('FFT of our EEG signal')
plt.show()
Hmm, this is interesting but a bit noisy. Maybe we need a method that is better than the simple fast fourier transform for this type of data. Thankfully, there’s a way to smooth out our fft without losing too much information.
The most widely-used method to do that is Welch’s Method, which consists in averaging consecutive Fourier transform of small windows of the signal, with or without overlapping. Basically, we calculate the fft of a signal across a few sliding windows, and then calculate the mean PSD from all the sliding windows. This is how LabChart generates the power spectral density plot as well!
The freqs vector contains the x-axis (frequency bins) and the psd vector contains the y-axis (power spectral density). The units of the power spectral density here are V^2 per Hz, reflecting that these values are for a particular frequency range.
Notes:
Check that the values here are almost identical to your PSD in LabChart. If not, you may need to change the y-axis labels.
If you’d like to plot both the eyes opened and closed data, you can uncomment the three lines indicated below.
You can change the x limit by uncommenting & editing the
plt.xlimline.
from scipy import signal
# Define sliding window length (4 seconds, which will give us 2 full cycles at 0.5 Hz)
win = 4 * sampling_freq
freqs, psd = signal.welch(closed_recording, sampling_freq, nperseg=win)
# Plot the power spectrum
plt.figure(figsize=(8, 6))
plt.plot(freqs, psd)
# Uncomment the lines below to plot two lines
#open_freqs, open_psd = signal.welch(open_recording, sampling_freq, nperseg=win)
#plt.plot(open_freqs, open_psd)
#plt.legend(['Closed','Open'])
plt.xlabel('Frequency (Hz)')
plt.ylabel('Power spectral density (pV^2 / Hz)')
#plt.xlim([0,75]) # Change x limit
plt.title("Welch's PSD")
plt.show()
Generate & plot spectrogram#
As a final step, we can plot a spectrogram of our signal. This is a common way to visualize EEG signals. The spectrogram results from doing the FFT on the snippet of the signal that falls into a “window,” plotting the frequency content in the window, then moving the window in time and plotting the frequency content again (and again) until the window has moved across the entire signal.
Scaling the spectrogram
Similar to how we needed to scale the spectrogram in LabChart, we’ll need to rescale the spectrogram here. The code below will automatically pick a vmax from the data, but you can also set it manually.
wind = np.hanning(1024) # Create a "hanning" window with a given binning window size
# Create the spectrogram
# Change closed to open below to generate for open
f, tt, Sxx = signal.spectrogram(closed_recording,sampling_freq,wind,len(wind),len(wind)-1)
# Automatically pick a vmax from the data (99th percentile of power values),
# so the color scale adapts to your recording instead of needing manual tuning.
# You can still set this by hand instead, e.g. vmax = 0.1
vmax = np.percentile(Sxx, 99)
# Plot the spectrogram
fig = plt.figure()
# You can change cmap & vmax if you want
plt.pcolormesh(tt,f,Sxx,cmap='viridis',vmax=vmax)
plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (sec)')
# plt.ylim([0,75]) # set the ylimit
cbar = plt.colorbar()
cbar.ax.set_ylabel('Power ($V^2$)')
plt.show()