-
Notifications
You must be signed in to change notification settings - Fork 1
/
meg2mat.py
69 lines (58 loc) · 2.1 KB
/
meg2mat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import click
# from mne import read_ctf
import contextlib
import sys
from mne import find_layout
from os.path import commonprefix as cprfx
from os.path import split, splitext, exists, join
from os import makedirs
from mne.io import Raw as Raw_fif
from mne.io import read_raw_ctf as Raw_ctf
from scipy.io import savemat
import numpy as np
@contextlib.contextmanager
def nostdout():
# -- Works both in python2 and python3 -- #
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
# --------------------------------------- #
save_stdout = sys.stdout
sys.stdout = StringIO()
yield
sys.stdout = save_stdout
@click.command()
@click.argument('save_path', type=click.Path())
@click.argument('meg_files', nargs=-1)
@click.option('--flat/--no-flat', default=False)
def cli(meg_files, save_path, flat):
'''Convert fif or ds to .mat format'''
common_prefix = split(cprfx(meg_files))[0] + '/'
for meg_file in meg_files:
# click.echo(meg_file)
base, ext = splitext(meg_file)
new_base = base.replace(common_prefix, '')
if flat:
new_base = new_base.replace('/','_')
# click.echo(new_base)
new_base = join(save_path, new_base)
if ext == '.fif':
with nostdout():
raw = Raw_fif(meg_file, preload=True, add_eeg_ref=False)
elif ext == '.ds':
with nostdout():
raw = Raw_ctf(meg_file, preload=True)
else:
click.echo('ERROR: UNKNOWN FORMAT FOR {}'.format(meg_file))
meg_raw = raw.pick_types(meg=True, ref_meg=False)
data, times = meg_raw[:,:]
ch_names = meg_raw.info['ch_names']
la = find_layout(meg_raw.info)
pos = la.pos[:,:2]
pos_filt = np.array([pos[i,:] for i in range(len(pos)) if la.names[i] in ''.join(raw.info['ch_names'])])
# click.echo(pos)
new_path,_ = split(new_base)
if not exists(new_path):
makedirs(new_path)
savemat(new_base + '.mat', {'data': data, 'times': times, 'chnames': ch_names, 'chxy': pos_filt})