Analyzing the Brain Waves Data Using Python

blog image

The brain waves play a crucial role in sending signals to different parts of the body. Analyzing this data helps scientists uncover the intricacies and complexities of the human brain and provide solutions to help people with brain-related disorders. We’ll discuss brain waves and ways to use Python to analyze this data. 

The human brain is a key organ to keep us functioning and active throughout our lives. We know that the concepts of artificial intelligence, deep learning, and artificial neural networks are derived from the working of the human brain. ANNs replicate the patterns and designs of the neural networks in the brain to allow the machines to perceive this and analyze data as the human brain does.

This, in turn, helps doctors and scientists use advanced technology to understand the complexities of the human brain and identify activity related to brain diseases. We’ll deal with one such method to study the functioning of the brain and analyze the signals it sends to other parts of the body. 

The brain constantly generates waves of electrical activity. The pattern of the waves changes based on the emotion a person experiences at that point. Devices like EEG kits are used to detect and record wave patterns. Computer programming languages like Python can be used to analyze this data. It helps determine how alert or focused a person is. By processing large datasets with such information, scientists can identify the causes/ reasons for brain diseases and find ways to cure them. 

Let’s start by reading more about brain waves and the types before learning how Python helps analyze the brain wave data. 


What are Brain Waves? 

Brain waves are the electrical pulses used by neurons to communicate with each other. The neurons use electrical impulses to send signals about different human emotions and behaviors. 

The frequency of each brain wave is different, depending on the emotion felt and displayed by the person. Measured in hertz (Hz) or cycles per second, we have slow and fast brain waves released by the neurons. The brain waves are given individual names to differentiate one from another based on frequency. 


Types of Brain Waves

There are five types of brain waves, with delta being the slowest and gamma being the fastest. The level of human awareness is determined by the frequency/ speed of the brain waves. 

Delta Brain Waves 

As the slowest of all, these high-amplitude brain waves have a frequency of 1 to 3 Hz and are experienced by humans when they are asleep. 

Theta Brain Waves

The Theta waves have a frequency range of 4 to 7 Hz and are found when a person is in a dreamy state. When the waves are close to the lower end, they represent the state when a person hovers between sleep and consciousness. It’s also known as the twilight state. Theta waves, in general, signify that mental inefficiency or that the person is either too relaxed or blanked out (zoned out) at that moment. 

Alpha Brain Waves

The alpha brain waves have a frequency range of 8 to 12 Hz. These are larger and slower, representing a relaxed or calm state of mind for a person ready to get into action if the need arises. The alpha brain waves are generated when someone feels peaceful after closing their eyes and picturing something they like. 

Beta Brain Waves

Beta brain waves are faster and smaller, with a frequency range of 13 to 38 Hz. These waves imply that the person is focused on something. They signify alertness, where the person is in their senses and displays all signs of concentration and mental activity. 

Gamma Brain Waves

Gamma brain waves are the fastest ones, with a frequency range of 38 to 42 Hz. These are subtle compared to the other brain waves and work on the consciousness and perception of the person. The waves occur when a person is highly alert and can feel every minute change in their surroundings. 

Waveforms of Different Brain Waves:

Waveforms of Different Brain Waves:
Waveforms of Different Brain Waves

Capturing Brain Waves

EEG (Electroencephalography) is a popular and most used method to capture brain waves and record the electrogram of the electrical activity on the scalp. It represents the macroscopic activity of the brain waves inside the brain. The electrodes are placed on the scalp to record the activity. EEG is typically a non-invasive process. However, Electrocorticography (Intracranial EEG) is an invasive process. 

The method measures the fluctuations in the voltage of the ionic current released within the neurons. In clinical terms, EEG is the recording of spontaneous electrical activity in the brain over a period. This data is collected through the numerous electrodes placed on the scalp of a person. 

The focus of the diagnosis is either on spectral content or the event-related potentials, during a particular duration or for a particular event. Spectral content, on the other hand, analyzes the type of neural oscillations or the brain waves. 


Applications Used to Analyze Brain Waves 

Two major applications analyze the brain waves, where each application focuses on a different aspect of analysis. 

Emotion Analysis 

Human emotions are determined by the brain. The brain waves carry messages with emotions that make the person feel something. This ‘emotion’ can be understood by analyzing brain waves. However, the concept of emotion and what it represents varies from one person to another based on cultural and environmental backgrounds. A classification algorithm is vital to accurately analyze the emotional aspect of brain waves. 

Brain-Computer Interface (BCI) 

The function of BCIs is to collect the brain waves, analyze the messages, translate the messages to commands and relay them to the output devices. BCIs don’t use neuromuscular pathways for this process. That’s because the purpose of using BCIs is to restore the functioning of the neuromuscular pathways in people suffering from brain diseases. 

For example, cerebral palsy, stroke, amyotrophic lateral sclerosis, or spinal cord injury can damage the pathways and affect the transmission of brain waves. BCIs aim to restore the damage done so that the person can regain the lost functioning of their organs and are used during the rehabilitation period. 

The initial demonstrations dealt with electroencephalography-based spelling and single-neuron-based device control. Scientists went on use intracortical, electrocorticographic, electroencephalographic, and other brain signals based on the complexity of controls. Robotic arms, prosthetics, etc., are controlled using these techniques.  


What are the Applications of Brain-Computer Interfaces? 

The advancement in science and technology has made BCIs popular with scientists. The brain-computer interfaces are used in different applications such as: 

Controlling Devices by Thought (Using the Brain)

Portable EEG acquisition devices like Emotiv EPOC collect signals from EEG signals. The raw signals are denoised (removing noise from an image/ signal) using the DWT method (Discrete Wavelet Transform). Then, the CCA method (Canonical Correlation Analysis) is used to extract and classify the signals. The results of classification are translated into commands. These commands control the smart devices at home. 

In short, a person can send commands and control a smart home device just by thinking about it. There’s no need to say the words aloud.  

Driving by Thinking About It

The BCIs enable physically impaired people to control their vehicles through thought. A mobile EEG device is used to record the brain signals, process them, and send commands to the output device, which performs the necessary actions. 

It’s a kind of brain reader that translates the thoughts to actions of a third party associated with the person. For example, a person with a physical disability can control the movement of a wheelchair or automate the driving of a car through their thoughts. 

The Audi AI:ME and Aicon allow the passengers to operate the graphical interface through not only touch and voice control but also through an eye-tracking system (as in just by looking at it). Infrared sensors are used to identify the exact spot where the passenger is focusing on. 

Neuralink (Embedding Computer inside the Brain)

Neuralink Corporation is a neurotechnology company co-founded by Elon Musk. The company develops implantable BMIs (brain-machine interfaces) that can be embedded into the brain to translate brain waves from neurons directly to the devices connected with the BMI. The company has hired several high-profile neuroscientists to work on designing the perfect BMI chip. While the human experiments were supposed to begin in 2020, the process has been delayed to start in 202. The BMI chips are said to be very thin at 4 to 6μm in width. 


Analyzing Brain Waves Data Using Python 

Let’s look at the two ways to analyze the brain waves data using Python

Using MNE Library in Python 

MNE-Python is an open-source module used to process, analyze, and visualize functional neuroimaging data. 

Step 1: Install Necessary Libraries

# Installing MNE library that contains brain related data

!pip install mne

!pip install pyvista

!pip install vtk

Step 2: Importing and Downloading Brain waves data for Data Analysis

# Importing mne libraries 

import os

import numpy as np

import mne

# Downloading brain waves datasets

sample_data_folder = mne.datasets.sample.data_path()

sample_data_evk_file = os.path.join(sample_data_folder, ‘MEG’, ‘sample’,

‘sample_audvis-ave.fif’)

evokeds_list = mne.read_evokeds(sample_data_evk_file, baseline=(None, 0),

                                proj=True, verbose=False)# Show the condition names, and reassure ourselves that baseline correction has been applied.

for e in evokeds_list:

print(f’Condition: {e.comment}, baseline: {e.baseline}’)

Step 3: Plotting different brain waves data

#plotting different brain waves data

conds = (‘aud/left’, ‘aud/right’, ‘vis/left’, ‘vis/right’)

evks = dict(zip(conds, evokeds_list))

evks[‘aud/left’].plot(exclude=[])

Output:

Plotting different brain waves data - Output

Step 4: Plotting the MEG Data

evks[‘aud/left’].plot(picks=’mag’, spatial_colors=True, gfp=True)

Output:

Output - Plotting the MEG Data

Step 5: Plotting average field values on Scalp using scalp topographies

times = np.linspace(0.05, 0.13, 5)

evks[‘aud/left’].plot_topomap(ch_type=’mag’, times=times, colorbar=True)

Output:

Output - Plotting average field values on Scalp using scalp topographies

Step 6: Calculating and plotting the average mean of EEG

defcustom_func(x):

return x.max(axis=1)

for combine in (‘mean’, ‘median’, ‘gfp’, custom_func):

mne.viz.plot_compare_evokeds(evks, picks=’eeg’, combine=combine)

Output:

Output - Calculating and plotting average mean of EEG

Step 7: Plotting the MEG Data

mne.viz.plot_compare_evokeds(evks, picks=’MEG 1811′, colors=dict(aud=0, vis=1),

linestyles=dict(left=’solid’, right=’dashed’))

temp_list = list()

for idx, _comment inenumerate((‘foo’, ‘foo’, ”, None, ‘bar’), start=1):

_evk = evokeds_list[0].copy()

_evk.comment = _comment

_evk.data *= idx # so we can tell the traces apart

temp_list.append(_evk)

mne.viz.plot_compare_evokeds(temp_list, picks=’mag’)

evks[‘vis/right’].plot_image(picks=’meg’)

mne.viz.plot_compare_evokeds(evks, picks=’eeg’, colors=dict(aud=0, vis=1),

linestyles=dict(left=’solid’, right=’dashed’),

                             axes=’topo’, styles=dict(aud=dict(linewidth=1),

vis=dict(linewidth=1)))

mne.viz.plot_evoked_topo(evokeds_list)

subjects_dir = os.path.join(sample_data_folder, ‘subjects’)

sample_data_trans_file = os.path.join(sample_data_folder, ‘MEG’, ‘sample’,

‘sample_audvis_raw-trans.fif’)

Step 8: Plotting 3d Field Maps

maps = mne.make_field_map(evks[‘aud/left’], trans=sample_data_trans_file,

                          subject=’sample’, subjects_dir=subjects_dir)

evks[‘aud/left’].plot_field(maps, time=0.1)

Output:

Output - Plotting 3d Field Maps

Using Deep CNN Network 

No-Sang Kwak and a few others have proposed using SSVEP (signals that are natural responses to visual stimulation at specific frequencies) classifier that uses a convolutional neural network (CNN-1). The classifier had two hidden layers (with a kernel size of 1*8 & 11*1) and an outer layer of five units. Each unit represented a different action for the exoskeleton movement. It had a learning speed of 0.1 with a normal distribution of initialized weights.

Here’s a look at the processing methods to compare the performance of CNN-1: 

  • CNN-2: 

The CNN-2 architecture is the same as CNN-1except that it has a fully connected layer with three extra units before the outer layer. 

  • CCA (Canonical Correlation Analysis):

This popular method is used to find the correlation between the signal and the target frequency. It has always been a go-to option for SSVEP classification. 

  • MSI (Multivariate Synchronisation Index):  

This estimates the sync between two signals and uses it as an index to decode stimulus frequency. 

  • Feedforward Neural Network: 

It is a 3-layer fully connected feedforward NN that provides future-oriented solutions instead of simply saying yes or no to a question. 

  • CCA-KNN (CCA+ k- Nearest Neighbors):  

This uses a combination of CCA with the k-nearest neighbors (KNN) algorithm which is used to solve regression and classification problems in machine learning. 


Conclusion

Analyzing the brain waves data using Python gives scientists more information about the process works and ways to find alternate devices that help people suffering from brain diseases that affect the transmission of brain waves or prevent the organ from performing the action as per the orders sent through the brain waves. 

Scientists can find a way to improve the quality of living for people with brain diseases and help them lead independent lives by relying on advanced technology. 

Leave a Reply

DMCA.com Protection Status

Get a Free Data Analysis Done!

Need experts help with your data? Drop Your Query And Get a 30 Minutes Consultation at $0.

They have the experience and agility to understand what’s possible and deliver to our expectations.

Drop Your Concern!