Skip to content

Instantly share code, notes, and snippets.

@jgondin
Forked from sylvchev/convert_eeg_mat_fif.py
Created November 13, 2017 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgondin/1281ea2b5e39454cce36e8c87fa1b1f6 to your computer and use it in GitHub Desktop.
Save jgondin/1281ea2b5e39454cce36e8c87fa1b1f6 to your computer and use it in GitHub Desktop.
EEG files save in GDF are convert in Matlab format with BioSig. This code convert the .mat files in pickled gzip and FIF files, ready to be used in Python with MNE.
from __future__ import print_function
from scipy.io import loadmat
from os import listdir
from numpy import nan_to_num
import pickle
import gzip
import sys
import mne
def convert_to_pz(fname):
"""Open and convert EEG mat file to pickled gzip file.
Parameters
----------
fname : string, name of the mat file, without the .mat
Returns
-------
s : ndarray, shape(time samples, channels)
The EEG signal
"""
print ("Loading"+fname+".mat file: ")
o = loadmat(fname+'.mat', struct_as_record=True)
print ('Done')
s = nan_to_num(o['s'])
sample_rate = o['SampleRate']
channels_name = o['label']
print ('Writing '+fname+'.pz file: ')
with gzip.open(fname+'_raw.pz', 'wb') as f:
p = {'raw_signal': s, 'sample_rate': sample_rate,
'channels_name': channels_name}
pickle.dump(p, f)
print ('done')
return s
def convert_to_fif(fname, s, id):
"""Convert a signal and save it under fname.fif
Parameters
----------
fname : string, name of the mat file, without the .mat
s : ndarray, shape(time samples, channels)
The EEG signal
id : int, subject identifier
"""
print ('Warning: the channels name are harcoded, change if needed!')
channel_names = ['Oz', 'C1', 'Pz', 'C2', 'P2', 'EOG1', 'P4', 'Cz']
channel_types = 5 * ['eeg'] + ['eog'] + 2*['eeg']
sfreq = 256
montage = 'standard_1020'
info = mne.create_info(channel_names, sfreq, channel_types, montage)
raw = mne.io.RawArray(s.T, info)
raw.info['description'] = 'Tests for Ellis car'
raw.info['experimenter'] = 'Julian Devaux Cindric et Babacar Diankha'
raw.info['subject_info'] = {'id':id, 'his_id':'S'+str(id)}
raw.info['line_freq'] = 50.
raw.info['custom_ref_applied'] = True
print ('Writing '+fname+'.fif file: ', end='')
raw.save(fname+'.fif', overwrite=True)
print ('done')
if __name__ == '__main__':
if len(sys.argv) != 2:
print ('Usage: ' + sys.argv[0] + ' filename')
sys.exit(1)
fname = sys.argv[1]
s = convert_to_pz(fname)
convert_to_fif(fname, s, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment