Skip to content

Commit

Permalink
CLEANUP: remove unused definitions
Browse files Browse the repository at this point in the history
  • Loading branch information
christianbrodbeck committed Mar 1, 2017
1 parent 6e46c6e commit 6324994
Show file tree
Hide file tree
Showing 3 changed files with 1 addition and 239 deletions.
2 changes: 1 addition & 1 deletion eelbrain/_utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
from .basic import (deprecated, IdDict, intervals, LazyProperty, keydefaultdict,
from .basic import (deprecated, intervals, LazyProperty, keydefaultdict,
n_decimals, natsorted, log_level, set_log_level)
from .system import caffeine
23 changes: 0 additions & 23 deletions eelbrain/_utils/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,29 +106,6 @@ def next(self):
return self.seq[self.i - 1], self.seq[self.i]


class IdDict(dict):
"""
Dictionary to code a certain type of items to Ids; id_dict[item] returns
the Id for item if item has previously been added; otherwise it generates
a new Id (its length)
"""
def __missing__(self, key):
new_id = len(self)
while new_id in self.values():
new_id += 1

super(IdDict, self).__setitem__(key, new_id)
return new_id

def __setitem__(self, key, value):
if value in self.values():
raise ValueError("Value already assigned: %r" % value)
elif key in self:
raise KeyError("Key already assigned: %r" % key)
else:
super(IdDict, self).__setitem__(key, value)


class LazyProperty(object):
"http://blog.pythonisito.com/2008/08/lazy-descriptors.html"
def __init__(self, func):
Expand Down
215 changes: 0 additions & 215 deletions eelbrain/_utils/subp.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@
import fnmatch
import logging
import os
import re
import shutil
import subprocess
import tempfile

import mne
from mne.utils import get_subjects_dir, run_subprocess
Expand Down Expand Up @@ -107,71 +104,6 @@ def command_exists(cmd):
stderr=subprocess.PIPE) == 0


# classes for files ---

class edf_file:
"""
Converts an "eyelink data format" (.edf) file to a temporary directory
and parses its content.
"""
def __init__(self, path):
# convert
if not os.path.exists(path):
err = "File does not exist: %r" % path
raise ValueError(err)

self.source_path = path
self.temp_dir = tempfile.mkdtemp()
cmd = [get_bin('edfapi', 'edf2asc'), # options in Manual p. 106
'-t', # use only tabs as delimiters
'-e', # outputs event data only
'-nse', # blocks output of start events
'-p', self.temp_dir, # writes output with same name to <path> directory
path]

_run(cmd)

# find asc file
name, _ = os.path.splitext(os.path.basename(path))
ascname = os.path.extsep.join((name, 'asc'))
self.asc_path = os.path.join(self.temp_dir, ascname)
self.asc_file = open(self.asc_path)
self.asc_str = self.asc_file.read()

# find trigger events
# MSG time msg... ID
re_trigger = re.compile(r'\bMSG\t(\d+)\tMEG Trigger: (\d+)')
self.triggers = re_trigger.findall(self.asc_str)

# find artifacts
# type start end
re_artifact = re.compile(r'\b(ESACC|EBLINK)\t[LR]\t(\d+)\t(\d+)')
self.artifacts = re_artifact.findall(self.asc_str)

def __del__(self):
shutil.rmtree(self.temp_dir)

def __repr__(self):
return 'edf_file(%r)' % self.source_path


def _format_path(path, fmt, is_new=False):
"helper function to format the path to mne files"
if not isinstance(path, basestring):
path = os.path.join(*path)

if fmt:
path = path.format(**fmt)

# test the path
path = os.path.expanduser(path)
if is_new or os.path.exists(path):
return path
else:
raise IOError("%r does not exist" % path)


def open_in_finder(path):
"""Open ``path`` in the finder"""
os.system('open %s' % path)
Expand Down Expand Up @@ -232,57 +164,6 @@ def fs_home_problem(fs_home):
"mri_surf2surf)" % fs_home)


def process_raw(raw, save='{raw}_filt', args=['projoff'], rm_eve=True, **kwargs):
"""
Calls ``mne_process_raw`` to process raw fiff files. All
options can be submitted in ``args`` or as kwargs (for a description of
the options, see mne manual 2.7.3, ch. 4 / p. 41)
raw : str(path)
Source file.
save : str(path)
Destination file. ``'{raw}'`` will be replaced with the raw file path
without the extension.
args : list of str
Options that do not require a value (e.g., to specify ``--filteroff``,
use ``args=['filteroff']``).
rm_eve : bool
Remove the event file automatically generated by ``mne_process_raw``
**kwargs:**
``mne_process_raw`` options that require values (see example).
Example::
>>> process_raw('/some/file_raw.fif', highpass=8, lowpass=12)
"""
raw_name, _ = os.path.splitext(raw)
eve_file = '%s-eve.fif' % raw_name
if raw_name.endswith('_raw'):
raw_name = raw_name[:-4]

save = save.format(raw=raw_name)

cmd = [get_bin('mne', 'mne_process_raw'),
'--raw', raw,
'--save', save]

for arg in args:
cmd.append('--%s' % arg)

for key, value in kwargs.iteritems():
cmd.append('--%s' % key)
cmd.append(value)

_run(cmd)
if rm_eve:
try:
os.remove(eve_file)
except Exception as err:
print("Could not remove %r" % eve_file)
print(err)


def _run(cmd, v=None, cwd=None, block=True):
"""Run a command
Expand Down Expand Up @@ -501,102 +382,6 @@ def run_mne_browse_raw(fif_dir, subject=None, subjects_dir=None, modal=False):
_run_mne_gui('mne_browse_raw', fif_dir, modal, subject, subjects_dir)


def do_forward_solution(paths=dict(rawfif=None,
mri_sdir=None,
fwd='{fif}-fwd.fif',
bem=None,
src=None,
trans=None),
overwrite=False, v=1):
"""
MNE Handbook 3.13
"""
fif_file = paths.get('rawfif')
mri_sdir = paths.get('mri_sdir')
fwd_file = paths.get('fwd')
bem_file = paths.get('bem')
src_file = paths.get('src')
trans_file = paths.get('trans')

mri_dir, mri_subject = os.path.split(mri_sdir)

fif_name, _ = os.path.splitext(fif_file)
fwd_file = fwd_file.format(fif=fif_name)

os.environ['SUBJECTS_DIR'] = mri_dir
cmd = [get_bin('mne', "mne_do_forward_solution"),
'--subject', mri_subject,
'--src', src_file,
'--bem', bem_file,
# '--mri', mri_cor_file, # MRI description file containing the MEG/MRI coordinate transformation.
'--mri', trans_file, # MRI description file containing the MEG/MRI coordinate transformation.
# '--trans', trans_file, # head->MRI coordinate transformation (obviates --mri).
'--meas', fif_file, # provides sensor locations and coordinate transformation between the MEG device coordinates and MEG head-based coordinates.
'--fwd', fwd_file, # '--destdir', target_file_dir, # optional
'--megonly']

if overwrite:
cmd.append('--overwrite')
elif os.path.exists(fwd_file):
raise IOError("fwd file at %r already exists" % fwd_file)

out, err = _run(cmd, v=v)
if os.path.exists(fwd_file):
return fwd_file
else:
err = "fwd-file not created"
err = '\n'.join([err, "command out:", out])
raise RuntimeError(err)


def do_inverse_operator(fwd_file, cov_file, inv_file='{cov}inv.fif',
loose=False, fixed=False):
cov, _ = os.path.splitext(cov_file)
if cov.endswith('cov'):
cov = cov[:-3]

inv_file = inv_file.format(cov=cov)

cmd = [get_bin('mne', "mne_do_inverse_operator"),
'--fwd', fwd_file,
'--meg', # Employ MEG data in the inverse calculation. If neither --meg nor --eeg is set only MEG channels are included.
'--depth',
'--megreg', 0.1,
'--noisecov', cov_file,
'--inv', inv_file, # Save the inverse operator decomposition here.
]

if loose:
cmd.extend(['--loose', loose])
elif fixed:
cmd.append('--fixed')

_, err = _run(cmd)
if not os.path.exists(inv_file):
raise RuntimeError('\n'.join(["inv-file not created", err]))


def mne_make_morph_maps(s_to='fsaverage', s_from=None, redo=False, subjects_dir=None):
"""
s_to, s_from : str | None
None -> all subejcts
"""
cmd = [get_bin('mne', "mne_make_morph_maps")]
if not s_to or not s_from:
cmd.append('--all')
if s_to:
cmd.extend(('--to', s_to))
if s_from:
cmd.extend(('--from', s_from))
if redo:
cmd.appen('--redo')
if subjects_dir:
os.environ['SUBJECTS_DIR'] = subjects_dir
_run(cmd)


# freesurfer---


Expand Down

0 comments on commit 6324994

Please sign in to comment.