[med-svn] [python-mne] 169/353: code cleanup
Yaroslav Halchenko
debian at onerussian.com
Fri Nov 27 17:24:52 UTC 2015
This is an automated email from the git hooks/post-receive script.
yoh pushed a commit to tag 0.4
in repository python-mne.
commit 41f3d55a61c5bb4925defa07537b5d840fae8bdd
Author: Martin Luessi <mluessi at nmr.mgh.harvard.edu>
Date: Tue May 1 13:47:37 2012 -0400
code cleanup
---
bin/mne_compute_proj_ecg.py | 37 ++++++++----
bin/mne_compute_proj_eog.py | 37 ++++++++----
mne/preprocessing/maxfilter.py | 34 +++++++----
mne/preprocessing/ssp.py | 131 +++++++++++++++++------------------------
4 files changed, 129 insertions(+), 110 deletions(-)
diff --git a/bin/mne_compute_proj_ecg.py b/bin/mne_compute_proj_ecg.py
index 1418810..945ea5c 100755
--- a/bin/mne_compute_proj_ecg.py
+++ b/bin/mne_compute_proj_ecg.py
@@ -9,8 +9,8 @@ $mne_compute_proj_ecg.py -i sample_audvis_raw.fif -c "MEG 1531" --l-freq 1 --h-f
# Authors : Alexandre Gramfort, Ph.D.
# Martin Luessi, Ph.D.
-import sys
import os
+import sys
import mne
@@ -43,8 +43,8 @@ if __name__ == '__main__':
help="Filter high cut-off frequency in Hz",
default=35)
parser.add_option("-p", "--preload", dest="preload",
- help="Temporary file used during computaion",
- default='tmp.mmap')
+ help="Temporary file used during computaion (to save memory)",
+ default=True)
parser.add_option("-a", "--average", dest="average", action="store_true",
help="Compute SSP after averaging",
default=False)
@@ -72,12 +72,14 @@ if __name__ == '__main__':
parser.add_option("--avg-ref", dest="avg_ref", action="store_true",
help="Add EEG average reference proj",
default=False)
- parser.add_option("--existing", dest="include_existing", action="store_true",
- help="Inlucde the SSP projectors currently in the fiff file",
- default=True)
+ parser.add_option("--exclproj", dest="excl_proj", action="store_true",
+ help="Exclude the SSP projectors currently in the fiff file",
+ default=False)
parser.add_option("--bad", dest="bad_fname",
help="Text file containing bad channels list (one per line)",
default=None)
+ parser.add_option("--event-id", dest="event_id", type="int",
+ help="ID to use for events", default=999)
options, args = parser.parse_args()
@@ -104,8 +106,9 @@ if __name__ == '__main__':
eeg=1e-6 * float(options.rej_eeg),
eog=1e-6 * float(options.rej_eog))
avg_ref = options.avg_ref
- include_existing = options.include_existing
+ excl_proj = options.excl_proj
bad_fname = options.bad_fname
+ event_id = options.event_id
if bad_fname is not None:
bads = [w.rstrip().split()[0] for w in open(bad_fname).readlines()]
@@ -125,8 +128,20 @@ if __name__ == '__main__':
else:
ecg_proj_fname = prefix + '_ecg_proj.fif'
- mne.preprocessing.compute_proj_ecg(raw_in, tmin, tmax,
- n_grad, n_mag, n_eeg, l_freq, h_freq, average, preload,
- filter_length, n_jobs, ch_name, reject, bads,
- avg_ref, include_existing, ecg_proj_fname, ecg_event_fname)
+ raw = mne.fiff.Raw(raw_in, preload=preload)
+
+ projs, events = mne.preprocessing.compute_proj_ecg(raw, tmin, tmax,
+ n_grad, n_mag, n_eeg, l_freq, h_freq, average,
+ filter_length, n_jobs, ch_name, reject,
+ bads, avg_ref, excl_proj, event_id)
+
+ raw.close()
+
+ if isinstance(preload, str) and os.path.exists(preload):
+ os.remove(preload)
+
+ print "Writing ECG projections in %s" % ecg_proj_fname
+ mne.write_proj(ecg_proj_fname, projs)
+ print "Writing ECG events in %s" % ecg_event_fname
+ mne.write_events(ecg_event_fname, events)
diff --git a/bin/mne_compute_proj_eog.py b/bin/mne_compute_proj_eog.py
index cfaf345..1fe27c4 100755
--- a/bin/mne_compute_proj_eog.py
+++ b/bin/mne_compute_proj_eog.py
@@ -9,8 +9,8 @@ $mne_compute_proj_eog.py -i sample_audvis_raw.fif --l-freq 1 --h-freq 100 --rej-
# Authors : Alexandre Gramfort, Ph.D.
# Martin Luessi, Ph.D.
-import sys
import os
+import sys
import mne
@@ -43,8 +43,8 @@ if __name__ == '__main__':
help="Filter high cut-off frequency in Hz",
default=35)
parser.add_option("-p", "--preload", dest="preload",
- help="Temporary file used during computaion",
- default='tmp.mmap')
+ help="Temporary file used during computaion (to save memory)",
+ default=True)
parser.add_option("-a", "--average", dest="average", action="store_true",
help="Compute SSP after averaging",
default=False)
@@ -65,16 +65,18 @@ if __name__ == '__main__':
default=50)
parser.add_option("--rej-eog", dest="rej_eog",
help="EOG rejection parameter in uV (peak to peak amplitude)",
- default=250)
+ default=1e9)
parser.add_option("--avg-ref", dest="avg_ref", action="store_true",
help="Add EEG average reference proj",
default=False)
- parser.add_option("--existing", dest="include_existing", action="store_true",
- help="Inlucde the SSP projectors currently in the fiff file",
- default=True)
+ parser.add_option("--exclproj", dest="excl_proj", action="store_true",
+ help="Exclude the SSP projectors currently in the fiff file",
+ default=False)
parser.add_option("--bad", dest="bad_fname",
help="Text file containing bad channels list (one per line)",
default=None)
+ parser.add_option("--event-id", dest="event_id", type="int",
+ help="ID to use for events", default=999)
options, args = parser.parse_args()
@@ -100,8 +102,9 @@ if __name__ == '__main__':
eeg=1e-6 * float(options.rej_eeg),
eog=1e-6 * float(options.rej_eog))
avg_ref = options.avg_ref
- include_existing = options.include_existing
+ excl_proj = options.excl_proj
bad_fname = options.bad_fname
+ event_id = options.event_id
if bad_fname is not None:
bads = [w.rstrip().split()[0] for w in open(bad_fname).readlines()]
@@ -121,8 +124,20 @@ if __name__ == '__main__':
else:
eog_proj_fname = prefix + '_eog_proj.fif'
- mne.preprocessing.compute_proj_eog(raw_in, tmin, tmax,
- n_grad, n_mag, n_eeg, l_freq, h_freq, average, preload,
+ raw = mne.fiff.Raw(raw_in, preload=preload)
+
+ projs, events = mne.preprocessing.compute_proj_eog(raw, tmin, tmax,
+ n_grad, n_mag, n_eeg, l_freq, h_freq, average,
filter_length, n_jobs, reject, bads,
- avg_ref, include_existing, eog_proj_fname, eog_event_fname)
+ avg_ref, excl_proj, event_id)
+
+ raw.close()
+
+ if isinstance(preload, str) and os.path.exists(preload):
+ os.remove(preload)
+
+ print "Writing EOG projections in %s" % eog_proj_fname
+ mne.write_proj(eog_proj_fname, projs)
+ print "Writing EOG events in %s" % eog_event_fname
+ mne.write_events(eog_event_fname, events)
diff --git a/mne/preprocessing/maxfilter.py b/mne/preprocessing/maxfilter.py
index 35d86bd..5c41233 100644
--- a/mne/preprocessing/maxfilter.py
+++ b/mne/preprocessing/maxfilter.py
@@ -8,8 +8,7 @@ import os
from warnings import warn
import numpy as np
-import scipy as sp
-from scipy.optimize import fmin_powell
+from scipy import optimize, linalg
from ..fiff import Raw
from ..fiff.constants import FIFF
@@ -57,7 +56,7 @@ def fit_sphere_to_headshape(info):
cost_fun = lambda x, hsp:\
np.sum((np.sqrt(np.sum((hsp - x[:3]) ** 2, axis=1)) - x[3]) ** 2)
- x_opt = fmin_powell(cost_fun, x0, args=(hsp,))
+ x_opt = optimize.fmin_powell(cost_fun, x0, args=(hsp,))
origin_head = x_opt[:3]
radius = x_opt[3]
@@ -68,7 +67,7 @@ def fit_sphere_to_headshape(info):
or trans['to'] != FIFF.FIFFV_COORD_HEAD:
raise RuntimeError('device to head transform not found')
- head_to_dev = sp.linalg.inv(trans['trans'])
+ head_to_dev = linalg.inv(trans['trans'])
origin_device = 1e3 * np.dot(head_to_dev,
np.r_[1e-3 * origin_head, 1.0])[:3]
@@ -81,6 +80,11 @@ def fit_sphere_to_headshape(info):
return radius, origin_head, origin_device
+def _mxwarn(msg):
+ warn('Possible MaxFilter bug: %s, more info: '
+ 'http://imaging.mrc-cbu.cam.ac.uk/meg/maxbugs' % msg)
+
+
def apply_maxfilter(in_fname, out_fname, origin=None, frame='device',
bad=None, autobad='off', skip=None, force=False,
st=False, st_buflen=16.0, st_corr=0.96, mv_trans=None,
@@ -106,13 +110,14 @@ def apply_maxfilter(in_fname, out_fname, origin=None, frame='device',
frame: string ('device' or 'head')
Coordinate frame for head center
- bad: string (or None)
- List of static bad channels (logical chnos, e.g.: 0323 1042 2631)
+ bad: string, list (or None)
+ List of static bad channels. Can be a list with channel names, or a
+ string with channels (names or logical channel numbers)
autobad: string ('on', 'off', 'n')
Sets automated bad channel detection on or off
- skip: string (or None)
+ skip: string or a list of float-tuples (or None)
Skips raw data sequences, time intervals pairs in sec,
e.g.: 0 30 120 150
@@ -171,10 +176,6 @@ def apply_maxfilter(in_fname, out_fname, origin=None, frame='device',
"""
# check for possible maxfilter bugs
- def _mxwarn(msg):
- warn('Possible MaxFilter bug: %s, more info: '
- 'http://imaging.mrc-cbu.cam.ac.uk/meg/maxbugs' % msg)
-
if mv_trans is not None and mv_comp:
_mxwarn("Don't use '-trans' with head-movement compensation "
"'-movecomp'")
@@ -208,11 +209,20 @@ def apply_maxfilter(in_fname, out_fname, origin=None, frame='device',
% (in_fname, out_fname, frame, origin))
if bad is not None:
- cmd += '-bad %s ' % bad
+ # format the channels
+ if not isinstance(bad, list):
+ bad = bad.split()
+ bad = map(str, bad)
+ bad_logic = [ch[3:] if ch.startswith('MEG') else ch for ch in bad]
+ bad_str = ' '.join(bad_logic)
+
+ cmd += '-bad %s ' % bad_str
cmd += '-autobad %s ' % autobad
if skip is not None:
+ if isinstance(skip, list):
+ skip = ' '.join(['%0.3f %0.3f' % (s[0], s[1]) for s in skip])
cmd += '-skip %s ' % skip
if force:
diff --git a/mne/preprocessing/ssp.py b/mne/preprocessing/ssp.py
index 01c4ba3..9c5aa98 100644
--- a/mne/preprocessing/ssp.py
+++ b/mne/preprocessing/ssp.py
@@ -6,26 +6,27 @@
import os
-from .. import Epochs, compute_proj_evoked, compute_proj_epochs, \
- write_events, write_proj
+from .. import Epochs, compute_proj_evoked, compute_proj_epochs
from ..fiff import Raw, pick_types, make_eeg_average_ref_proj
from ..artifacts import find_ecg_events, find_eog_events
-def _compute_exg_proj(mode, in_fif_fname, tmin, tmax,
+def _compute_exg_proj(mode, raw, tmin, tmax,
n_grad, n_mag, n_eeg, l_freq, h_freq,
- average, preload, filter_length, n_jobs, ch_name,
- reject, bads, avg_ref, include_existing,
- proj_fname, event_fname):
+ average, filter_length, n_jobs, ch_name,
+ reject, bads, avg_ref, excl_proj, event_id):
"""Compute SSP/PCA projections for ECG or EOG artifacts
+ Note: raw has to be constructed with preload=True (or string)
+ Warning: raw will be modified by this function
+
Parameters
----------
mode: sting ('ECG', or 'EOG')
What type of events to detect
- in_fif_fname: string
- Input Raw FIF file
+ raw: mne.fiff.Raw
+ Raw input file
tmin: float
Time before event in second
@@ -51,9 +52,6 @@ def _compute_exg_proj(mode, in_fif_fname, tmin, tmax,
average: bool
Compute SSP after averaging
- preload: string (or True)
- Temporary file used during computaion
-
filter_length: int
Number of taps to use for filtering
@@ -72,14 +70,11 @@ def _compute_exg_proj(mode, in_fif_fname, tmin, tmax,
avg_ref: bool
Add EEG average reference proj
- include_existing: bool
- Inlucde the SSP projectors currently in the fiff file
-
- proj_fname: string (or None)
- Filename to use for projectors (not saved if None)
+ excl_proj: bool
+ Exclude the SSP projectors currently in the fiff file
- event_fname: string
- Filename to use for events (not saved if None)
+ event_id: int
+ ID to use for events
Returns
-------
@@ -89,25 +84,27 @@ def _compute_exg_proj(mode, in_fif_fname, tmin, tmax,
events : ndarray
Detected events
"""
- # Reading fif File
- raw = Raw(in_fif_fname, preload=preload)
+ if not raw._preloaded:
+ raise ValueError('raw needs to be preloaded, use preload=True in constructor')
- if include_existing:
- projs = raw.info['projs']
- else:
+ if excl_proj:
projs = []
+ else:
+ projs = raw.info['projs']
+ print ('Including %d SSP projectors from %s'
+ % (len(projs), in_fif_fname))
if avg_ref:
- print "Adding average EEG reference projection."
+ print 'Adding average EEG reference projection.'
eeg_proj = make_eeg_average_ref_proj(raw.info)
projs.append(eeg_proj)
if mode == 'ECG':
print 'Running ECG SSP computation'
- events, _, _ = find_ecg_events(raw, ch_name=ch_name)
+ events, _, _ = find_ecg_events(raw, ch_name=ch_name, event_id=event_id)
elif mode == 'EOG':
print 'Running EOG SSP computation'
- events = find_eog_events(raw)
+ events = find_eog_events(raw, event_id=event_id)
else:
ValueError("mode must be 'ECG' or 'EOG'")
@@ -147,33 +144,26 @@ def _compute_exg_proj(mode, in_fif_fname, tmin, tmax,
if preload is not None and os.path.exists(preload):
os.remove(preload)
- if event_fname is not None:
- print "Writing events in %s" % event_fname
- write_events(event_fname, events)
-
- if proj_fname is not None:
- print "Writing projections in %s" % proj_fname
- write_proj(proj_fname, projs)
-
print 'Done.'
return projs, events
-def compute_proj_ecg(in_fif_fname, tmin=-0.2, tmax=0.4,
+def compute_proj_ecg(raw, tmin=-0.2, tmax=0.4,
n_grad=2, n_mag=2, n_eeg=2, l_freq=1.0, h_freq=35.0,
- average=False, preload="tmp.mmap",
- filter_length=2048, n_jobs=1, ch_name=None,
+ average=False, filter_length=2048, n_jobs=1, ch_name=None,
reject=dict(grad=2000e-13, mag=3000e-15, eeg=50e-6,
- eog=250e-6), bads=None,
- avg_ref=False, include_existing=False,
- ecg_proj_fname=None, ecg_event_fname=None):
+ eog=250e-6), bads=None, avg_ref=False, excl_proj=True,
+ event_id=999):
"""Compute SSP/PCA projections for ECG artifacts
+ Note: raw has to be constructed with preload=True (or string)
+ Warning: raw will be modified by this function
+
Parameters
----------
- in_fif_fname: string
- Input Raw FIF file
+ raw: mne.fiff.Raw
+ Raw input file
tmin: float
Time before event in second
@@ -199,9 +189,6 @@ def compute_proj_ecg(in_fif_fname, tmin=-0.2, tmax=0.4,
average: bool
Compute SSP after averaging
- preload: string (or True)
- Temporary file used during computaion
-
filter_length: int
Number of taps to use for filtering
@@ -220,14 +207,11 @@ def compute_proj_ecg(in_fif_fname, tmin=-0.2, tmax=0.4,
avg_ref: bool
Add EEG average reference proj
- include_existing: bool
- Inlucde the SSP projectors currently in the fiff file
+ excl_proj: bool
+ Exclude the SSP projectors currently in the fiff file
- ecg_proj_fname: string (or None)
- Filename to use for projectors (not saved if None)
-
- ecg_event_fname: string (or None)
- Filename to use for events (not saved if None)
+ event_id: int
+ ID to use for events
Returns
-------
@@ -238,29 +222,29 @@ def compute_proj_ecg(in_fif_fname, tmin=-0.2, tmax=0.4,
Detected ECG events
"""
- projs, ecg_events = _compute_exg_proj('ECG', in_fif_fname, tmin, tmax,
+ projs, ecg_events = _compute_exg_proj('ECG', raw, tmin, tmax,
n_grad, n_mag, n_eeg, l_freq, h_freq,
- average, preload, filter_length, n_jobs, ch_name,
- reject, bads, avg_ref, include_existing,
- ecg_proj_fname, ecg_event_fname)
+ average, filter_length, n_jobs, ch_name,
+ reject, bads, avg_ref, excl_proj, event_id)
return projs, ecg_events
-def compute_proj_eog(in_fif_fname, tmin=-0.15, tmax=0.15,
+def compute_proj_eog(raw, tmin=-0.15, tmax=0.15,
n_grad=2, n_mag=2, n_eeg=2, l_freq=1.0, h_freq=35.0,
- average=False, preload="tmp.mmap",
- filter_length=2048, n_jobs=1,
+ average=False, filter_length=2048, n_jobs=1,
reject=dict(grad=2000e-13, mag=3000e-15, eeg=50e-6,
- eog=250e-6), bads=None,
- avg_ref=False, include_existing=False,
- ecg_proj_fname=None, ecg_event_fname=None):
+ eog=1e9), bads=None, avg_ref=False, excl_proj=True,
+ event_id=998):
"""Compute SSP/PCA projections for EOG artifacts
+ Note: raw has to be constructed with preload=True (or string)
+ Warning: raw will be modified by this function
+
Parameters
----------
- in_fif_fname: string
- Input Raw FIF file
+ raw: mne.fiff.Raw
+ Raw input file
tmin: float
Time before event in second
@@ -304,14 +288,11 @@ def compute_proj_eog(in_fif_fname, tmin=-0.15, tmax=0.15,
avg_ref: bool
Add EEG average reference proj
- include_existing: bool
- Inlucde the SSP projectors currently in the fiff file
+ excl_proj: bool
+ Exclude the SSP projectors currently in the fiff file
- eog_proj_fname: string (or None)
- Filename to use for projectors (not saved if None)
-
- eog_event_fname: string (or None)
- Filename to use for events (not saved if None)
+ event_id: int
+ ID to use for events
Returns
-------
@@ -322,11 +303,9 @@ def compute_proj_eog(in_fif_fname, tmin=-0.15, tmax=0.15,
Detected ECG events
"""
- projs, eog_events = _compute_exg_proj('EOG', in_fif_fname, tmin, tmax,
+ projs, eog_events = _compute_exg_proj('EOG', raw, tmin, tmax,
n_grad, n_mag, n_eeg, l_freq, h_freq,
- average, preload, filter_length, n_jobs, None,
- reject, bads, avg_ref, include_existing,
- ecg_proj_fname, ecg_event_fname)
+ average, filter_length, n_jobs, None,
+ reject, bads, avg_ref, excl_proj, event_id)
return projs, eog_events
-
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-med/python-mne.git
More information about the debian-med-commit
mailing list