Importing MATLAB Files into Python: A Step-by-Step Guide for EEG Data Analysis with MNE

Electroencephalography (EEG) is a powerful tool for studying the human brain’s electrical activity. It allows researchers to measure and analyze the electrical signals generated by the brain, providing valuable insights into cognitive processes, sleep patterns, and neurological disorders. MATLAB has been a popular choice for EEG data analysis due to its comprehensive set of signal processing toolboxes, tailored for various aspects of EEG research.

However, Python has emerged as a leading language in the field of data analysis, offering extensive libraries and frameworks that are well-suited for working with EEG data. Python’s versatility, ease of use, and its dedicated EEG analysis packages, like MNE (Machines for Neural Experiments), have attracted researchers and data analysts to explore this powerful language for their EEG research.

MNE, specifically designed for EEG data analysis, provides a comprehensive set of functions and tools that enable researchers to efficiently preprocess, analyze, and visualize EEG signals. By leveraging Python and MNE, researchers can harness the full potential of their EEG data while benefiting from Python’s broader scientific computing ecosystem.

In this blog post, we will delve into the realm of EEG data analysis using Python, focusing on the import and processing of .mat files – a common file format used in MATLAB. We will guide you through the step-by-step process of importing .mat files into Python, extracting the EEG data, creating the necessary MNE data structure, and conducting basic preprocessing and visualization tasks using the versatile capabilities of MNE.

By the end of this blog post, you will have a solid understanding of how to seamlessly transition from MATLAB to Python for EEG data analysis, allowing you to tap into Python’s vast array of data analysis tools and techniques while leveraging the specialized functionalities offered by MNE. So, let’s embark on this enlightening journey and unlock the potential of EEG data analysis using Python and MNE!

Step 1:

Before we dive into the exciting world of EEG data import and processing, let’s take a moment to ensure that you have all the necessary libraries installed on your machine. Don’t worry; the installation process is straightforward.

To begin, you’ll need to have Python (version 3.x) and pip, the Python package installer, installed on your machine. If you haven’t done so already, you can download the latest version of Python from the official Python website (https://www.python.org/downloads/). Pip is usually bundled with Python, so you should already have it if you installed Python using the official installer.

Once you have Python and pip set up, open your command prompt (Windows) or terminal (macOS/Linux) to execute the following command:

pip install mne scipy numpy matplotlib

This command will use pip to install the required libraries for our EEG data analysis. Let’s take a closer look at each of these libraries:

  • MNE (Machines for Neural Experiments): MNE is a powerful Python package designed specifically for EEG and other neurophysiological data analysis. It provides a wide range of functions for data preprocessing, filtering, artifact removal, time-frequency analysis, and visualization.
  • scipy: scipy is a scientific computing library in Python that offers a variety of scientific and numerical routines. We will use it for loading MATLAB (.mat) files and other necessary numerical computations.
  • numpy: numpy is the fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a vast collection of mathematical functions. We will use numpy extensively for data manipulation and array operations.
  • matplotlib: matplotlib is a popular Python visualization library that helps us create a wide range of plots and visualizations. We will use it to plot EEG signals, visualize spectrograms, and more.

Once the installation is complete, you’re all set to proceed with importing and processing EEG data in Python using MNE and the other essential libraries we just installed. So let’s move on to the fun part of analyzing EEG data!

Step 2:

Now that we have the necessary libraries installed, let’s proceed to load our EEG data from the .mat file into Python. To accomplish this, we will be utilizing the loadmat function from the scipy.io module.

Here’s an example code snippet that demonstrates how to load a .mat file:

import scipy.io as sio

data = sio.loadmat("path_to_your_file.mat")

In the above code, you need to replace “path_to_your_file.mat” with the actual file path on your system. Ensure that you have your .mat file saved in the appropriate directory or provide the complete file path if it is in a different location.

The loadmat function reads the .mat file and imports its contents into a dictionary-like object called data. Each variable in the .mat file becomes a key-value pair in the data dictionary, where the variable’s name serves as the key and its corresponding data as the value.

To access the specific EEG data stored in the .mat file, you can refer to it using its variable name. For instance, if the EEG data is stored in a variable named “eeg_data” in the .mat file, you can retrieve it from the data dictionary as follows:

eeg_data = data['eeg_data']

With this step, you have successfully loaded the data from the .mat file into Python, making it accessible for further data analysis and processing.

It’s important to note that the structure of the data dictionary will depend on the organization and variable names within your specific .mat file. Therefore, it is advisable to examine the structure of the data dictionary using the keys() function or visual inspection to identify and access the desired EEG data or other variables present in the file.

Now that we have successfully imported our EEG data, let’s continue our journey to explore the subsequent steps of creating an MNE data structure, preprocessing the data, and ultimately gaining insightful knowledge about the brain’s electrical activity.

Step 3:

Once the .mat file is loaded into Python, the next step is to extract the EEG data from it. EEG data is typically organized as a multidimensional array, with dimensions representing channels, time samples, and trials.

Assuming that the EEG data variable is named “eeg_data” in the .mat file, you can extract it using the following code:

eeg_data = data['eeg_data']

In this code, the data dictionary, obtained from loading the .mat file, is accessed with the key ‘eeg_data’ to retrieve the EEG data stored within.

To gain a better understanding of the structure of the extracted data, it’s essential to extract and analyze its dimensions. In the example below, we extract the relevant dimensions of the EEG data:

n_channels = eeg_data.shape[0]
n_time_samples = eeg_data.shape[1]
n_trials = eeg_data.shape[2]

Here, we use the shape attribute to determine the size of each dimension in the eeg_data array. The first dimension eeg_data.shape[0] represents the number of channels, the second dimension eeg_data.shape[1] represents the number of time samples, and the third dimension eeg_data.shape[2] represents the number of trials.

Extracting these dimensions is crucial as they provide vital information about the structure of the EEG data. Understanding the number of channels, time samples, and trials enables us to perform specific analyses, such as identifying the electrodes involved, determining the duration of the recording, or exploring trial-related effects.

By extracting and analyzing the dimensions of the EEG data, you empower yourself to navigate through the data and perform more sophisticated analyses based on your research goals and hypotheses.

With the EEG data successfully extracted and its dimensions determined, we can move on to the next step, where we will create an MNE data structure to facilitate further analysis and visualization.

Step 4:

To process the EEG data using the MNE library, we need to create an MNE data structure that will allow us to take advantage of the powerful analysis and visualization capabilities it provides. We can achieve this by utilizing the RawArray function provided by MNE. Let’s see how we can create the MNE data structure:

import mne

# Create MNE information object
sampling_rate = 1000  # Replace with the actual sampling rate of your data
info = mne.create_info(ch_names=[f"ch_{i + 1}" for i in range(n_channels)],
                       sfreq=sampling_rate,
                       ch_types='eeg')

In the code snippet above, we use the create_info function from the MNE library to create an MNE information object (info). The info object contains essential information about the EEG data, such as the channel names, the sampling frequency (sfreq), and the channel types (ch_types).

In this example, we assume that the sampling rate of the data is 1000 Hz. Make sure to replace sampling_rate with the actual sampling rate of your data.

The ch_names parameter takes a list comprehension to create channel names based on the number of channels extracted from the EEG data. In this case, we generate channel names as ch_1ch_2ch_3, and so on, corresponding to the number of channels (n_channels).

Next, let’s create the MNE Raw object by passing the EEG data (eeg_data) and the info object to the RawArray function:

raw = mne.io.RawArray(eeg_data, info)

The RawArray function creates an MNE Raw object, which is the primary data structure used in MNE for storing and manipulating raw EEG data. By passing the EEG data (eeg_data) and the info object to RawArray, we create a raw object that contains the EEG data along with the associated channel information.

With the MNE data structure ready, we can now leverage MNE’s extensive functionalities for preprocessing, analyzing, and visualizing the EEG data. We can explore various preprocessing steps such as filtering, artifact removal, epoching, and perform advanced analyses like time-frequency analysis or source localization using this MNE data structure.

In the next section, we will dive into the preprocessing and visualization of EEG data using the MNE library, taking advantage of the flexibility and efficiency it provides.

Step 5

Once you have your EEG data in the MNE data structure, you can perform various preprocessing steps and visualize the data using the rich functionality provided by MNE. Let’s explore an example that demonstrates how to apply a bandpass filter to the data and plot a single EEG channel:

# Apply a bandpass filter from 1Hz to 40Hz
raw.filter(1, 40, method='iir')

In the above code snippet, we use the filter method provided by the raw object to apply a bandpass filter to the EEG data. The filter function allows us to specify the desired frequency range by providing the lower and upper cutoff frequencies (1Hz and 40Hz, respectively, in this example). The method parameter is set to ‘iir’, indicating the use of an Infinite Impulse Response (IIR) filter, which is commonly used for EEG data filtering.

Filtering the EEG data is an important preprocessing step that helps remove unwanted noise and extract the desired frequency components for analysis. By applying the bandpass filter, we retain the EEG activity within the specified frequency range, which is often relevant for studying brain rhythms and cognitive processes.

After preprocessing the data, let’s visualize the raw EEG signal for a specific channel:

raw.plot(duration=10.0, scalings={'eeg': 75e-6}, n_channels=1)

In the code snippet above, we use the plot method provided by the raw object to visualize the EEG data. The duration parameter specifies the duration of the data to be displayed (in seconds), and the scalings parameter allows us to adjust the scaling for different channel types. In this example, we set the scaling factor for the ‘eeg’ channel type to 75e-6, which determines the amplitude range of the plotted data.

The n_channels parameter allows us to specify the number of channels to be displayed simultaneously. In this case, we set it to 1 to plot a single EEG channel. You can adjust this parameter according to your requirements.

By applying preprocessing steps like filtering and visualizing the data, we gain valuable insights into the EEG signals and can identify patterns, artifacts, or interesting characteristics. These steps serve as a foundation for subsequent analyses, such as event-related potential (ERP) extraction, spectral analysis, and the investigation of brain dynamics.

In conclusion, MNE provides a wide range of preprocessing and visualization functions, enabling us to explore, understand, and interpret EEG data effectively. The flexibility and comprehensive features of MNE empower researchers to gain insights into the intricate workings of the human brain through EEG analysis.

Conclusion

In this blog post, we embarked on a journey to bridge the gap between MATLAB and Python by exploring the process of importing .mat files commonly used in MATLAB for EEG data analysis and utilizing Python’s MNE software package. Through these steps, we demonstrated how to unleash the potential of EEG data analysis using Python and MNE.

By importing .mat files into Python, we gained access to a plethora of additional libraries and tools for data analysis. Leveraging the MNE package, we created an MNE data structure, which serves as the foundation for applying a wide range of analysis techniques to EEG data.

We took you through the steps of loading the .mat file into Python using the scipy.io library, extracting the EEG data from the loaded file, and creating an MNE data structure using the RawArray function. This allowed us to preprocess the data, applying essential techniques such as filtering. We also demonstrated how to visualize the EEG data using the powerful visualization capabilities of MNE.

Python is a language known for its extensive libraries and community support, providing almost limitless possibilities for data analysis. By combining it with MNE, we unlocked the full potential of EEG data analysis and opened the doors to exploring the fascinating world of brain activity.

Now armed with the knowledge of how to import .mat files into Python and process them using MNE, you have the tools to delve into EEG research with confidence and expand your horizons in cognitive neuroscience. Python’s versatility and the extensive capabilities of MNE allow you to conduct in-depth analysis, unravel brain dynamics, and gain insights into the mysteries of the human mind.

So, don’t hesitate – import your .mat files, embark on this exciting journey, and witness the power of Python and MNE unravel the secrets hidden within your EEG data. Happy EEG data analysis!


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *