本文整理汇总了Python中mne.utils.get_subjects_dir函数的典型用法代码示例。如果您正苦于以下问题:Python get_subjects_dir函数的具体用法?Python get_subjects_dir怎么用?Python get_subjects_dir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_subjects_dir函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_datasets_basic
def test_datasets_basic(tmpdir):
"""Test simple dataset functions."""
# XXX 'hf_sef' and 'misc' do not conform to these standards
for dname in ('sample', 'somato', 'spm_face', 'testing', 'opm',
'bst_raw', 'bst_auditory', 'bst_resting', 'multimodal',
'bst_phantom_ctf', 'bst_phantom_elekta', 'kiloword',
'mtrf', 'phantom_4dbti',
'visual_92_categories', 'fieldtrip_cmc'):
if dname.startswith('bst'):
dataset = getattr(datasets.brainstorm, dname)
check_name = 'brainstorm.%s' % (dname,)
else:
dataset = getattr(datasets, dname)
check_name = dname
if dataset.data_path(download=False) != '':
assert isinstance(dataset.get_version(), str)
assert datasets.utils.has_dataset(check_name)
else:
assert dataset.get_version() is None
assert not datasets.utils.has_dataset(check_name)
print('%s: %s' % (dname, datasets.utils.has_dataset(check_name)))
tempdir = str(tmpdir)
# don't let it read from the config file to get the directory,
# force it to look for the default
with modified_env(**{'_MNE_FAKE_HOME_DIR': tempdir, 'SUBJECTS_DIR': None}):
assert (datasets.utils._get_path(None, 'foo', 'bar') ==
op.join(tempdir, 'mne_data'))
assert get_subjects_dir(None) is None
_set_montage_coreg_path()
sd = get_subjects_dir()
assert sd.endswith('MNE-fsaverage-data')
示例2: dissolve_label
def dissolve_label(labels, source, targets, subjects_dir=None,
hemi='both'):
"""
Assign every point from source to the target that is closest to it.
Parameters
----------
labels : list
List of labels (as returned by mne.read_annot).
source : str
Name of the source label (without hemi affix).
targets : list of str
List of target label names (without hemi affix).
subjects_dir : str
subjects_dir.
hemi : 'both', 'lh', 'rh'
Hemisphere(s) for which to dissolve the label.
Notes
-----
Modifies ``labels`` in-place, returns None.
"""
subjects_dir = get_subjects_dir(subjects_dir)
subject = labels[0].subject
if hemi == 'both':
hemis = ('lh', 'rh')
elif hemi == 'lh' or hemi == 'rh':
hemis = (hemi,)
else:
raise ValueError("hemi=%r" % hemi)
idx = {l.name: i for i, l in enumerate(labels)}
rm = set()
for hemi in hemis:
fpath = os.path.join(subjects_dir, subject, 'surf', hemi + '.inflated')
points, _ = mne.read_surface(fpath)
src_name = '-'.join((source, hemi))
src_idx = idx[src_name]
rm.add(src_idx)
src_label = labels[src_idx]
tgt_names = ['-'.join((name, hemi)) for name in targets]
tgt_idxs = [idx[name] for name in tgt_names]
tgt_labels = [labels[i] for i in tgt_idxs]
tgt_points = [points[label.vertices] for label in tgt_labels]
vert_by_tgt = {i: [] for i in xrange(len(targets))}
for src_vert in src_label.vertices:
point = points[src_vert:src_vert + 1]
dist = [cdist(point, pts).min() for pts in tgt_points]
tgt = np.argmin(dist)
vert_by_tgt[tgt].append(src_vert)
for i, label in enumerate(tgt_labels):
new_vertices = vert_by_tgt[i]
label.vertices = np.union1d(label.vertices, new_vertices)
for i in sorted(rm, reverse=True):
del labels[i]
示例3: fix_annot_names
def fix_annot_names(subject, parc, clean_subject=None, clean_parc=None, hemi="both", subjects_dir=None):
"""Fix for Freesurfer's mri_surf2surf corrupting label names in annot files
Notes
-----
Requires nibabel > 1.3.0 for annot file I/O
"""
# process args
subjects_dir = get_subjects_dir(subjects_dir)
if clean_subject is None:
clean_subject = subject
if clean_parc is None:
clean_parc = parc
fpaths, hemis = _get_annot_fname(None, subject, hemi, parc, subjects_dir)
clean_fpaths, _ = _get_annot_fname(None, clean_subject, hemi, clean_parc, subjects_dir)
for fpath, clean_fpath, hemi in izip(fpaths, clean_fpaths, hemis):
labels, ctab, names = read_annot(fpath)
_, _, clean_names = read_annot(clean_fpath)
if all(n == nc for n, nc in izip(names, clean_names)):
continue
if len(clean_names) != len(names):
err = "Different names in %s annot files: %s vs. " "%s" % (hemi, str(names), str(clean_names))
raise ValueError(err)
for clean_name, name in izip(clean_names, names):
if not name.startswith(clean_name):
err = "%s does not start with %s" % (str(name), clean_name)
raise ValueError(err)
write_annot(fpath, labels, ctab, clean_names)
示例4: freeview_bem_surfaces
def freeview_bem_surfaces(subject, subjects_dir, method):
"""View 3-Layers BEM model with Freeview.
Parameters
----------
subject : string
Subject name
subjects_dir : string
Directory containing subjects data (Freesurfer SUBJECTS_DIR)
method : string
Can be 'flash' or 'watershed'.
"""
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
if subject is None:
raise ValueError("subject argument is None.")
subject_dir = op.join(subjects_dir, subject)
if not op.isdir(subject_dir):
raise ValueError("Wrong path: '{}'. Check subjects-dir or"
"subject argument.".format(subject_dir))
env = os.environ.copy()
env['SUBJECT'] = subject
env['SUBJECTS_DIR'] = subjects_dir
if 'FREESURFER_HOME' not in env:
raise RuntimeError('The FreeSurfer environment needs to be set up.')
mri_dir = op.join(subject_dir, 'mri')
bem_dir = op.join(subject_dir, 'bem')
mri = op.join(mri_dir, 'T1.mgz')
if method == 'watershed':
bem_dir = op.join(bem_dir, 'watershed')
outer_skin = op.join(bem_dir, '%s_outer_skin_surface' % subject)
outer_skull = op.join(bem_dir, '%s_outer_skull_surface' % subject)
inner_skull = op.join(bem_dir, '%s_inner_skull_surface' % subject)
else:
if method == 'flash':
bem_dir = op.join(bem_dir, 'flash')
outer_skin = op.join(bem_dir, 'outer_skin.surf')
outer_skull = op.join(bem_dir, 'outer_skull.surf')
inner_skull = op.join(bem_dir, 'inner_skull.surf')
# put together the command
cmd = ['freeview']
cmd += ["--volume", mri]
cmd += ["--surface", "%s:color=red:edgecolor=red" % inner_skull]
cmd += ["--surface", "%s:color=yellow:edgecolor=yellow" % outer_skull]
cmd += ["--surface",
"%s:color=255,170,127:edgecolor=255,170,127" % outer_skin]
run_subprocess(cmd, env=env, stdout=sys.stdout)
print("[done]")
示例5: _fs_subjects
def _fs_subjects(arg, exclude=[], subjects_dir=None):
if '*' in arg:
subjects_dir = get_subjects_dir(subjects_dir)
subjects = fnmatch.filter(os.listdir(subjects_dir), arg)
subjects = filter(os.path.isdir, subjects)
for subject in exclude:
if subject in subjects:
subjects.remove(subject)
else:
subjects = [arg]
return subjects
示例6: plot_stc_time_point
def plot_stc_time_point(stc, subject, limits=[5, 10, 15], time_index=0,
surf='inflated', measure='dSPM', subjects_dir=None):
"""Plot a time instant from a SourceEstimate using matplotlib
The same could be done with mayavi using proper 3D.
Parameters
----------
stc : instance of SourceEstimate
The SourceEstimate to plot.
subject : string
The subject name (only needed if surf is a string).
time_index : int
Time index to plot.
surf : str, or instance of surfaces
Surface to use (e.g., 'inflated' or 'white'), or pre-loaded surfaces.
measure : str
The label for the colorbar. None turns the colorbar off.
subjects_dir : str, or None
Path to the SUBJECTS_DIR. If None, the path is obtained by using
the environment variable SUBJECTS_DIR.
"""
subjects_dir = get_subjects_dir(subjects_dir)
pl.figure(facecolor='k', figsize=(8, 5))
hemis = ['lh', 'rh']
if isinstance(surf, str):
surf = [read_surface(op.join(subjects_dir, subject, 'surf',
'%s.%s' % (h, surf))) for h in hemis]
my_cmap = mne_analyze_colormap(limits)
for hi, h in enumerate(hemis):
coords = surf[hi][0][stc.vertno[hi]]
if hi == 0:
vals = stc_all_cluster_vis.lh_data[:, time_index]
else:
vals = stc_all_cluster_vis.rh_data[:, time_index]
ax = pl.subplot(1, 2, 1 - hi, axis_bgcolor='none')
pl.tick_params(labelbottom='off', labelleft='off')
flipper = -1 if hi == 1 else 1
sc = ax.scatter(flipper * coords[:, 1], coords[:, 2], c=vals,
vmin=-limits[2], vmax=limits[2], cmap=my_cmap,
edgecolors='none', s=5)
ax.set_aspect('equal')
pl.axis('off')
try:
pl.tight_layout(0)
except:
pass
if measure is not None:
cax = pl.axes([0.85, 0.15, 0.025, 0.15], axisbg='k')
cb = pl.colorbar(sc, cax, ticks=[-limits[2], 0, limits[2]])
cb.set_label(measure, color='w')
pl.setp(pl.getp(cb.ax, 'yticklabels'), color='w')
pl.draw()
pl.show()
示例7: mri_annotation2label
def mri_annotation2label(subject='*', annot='aparc',
dest=os.path.join("{sdir}", "label", "{annot}"),
hemi='*', subjects_dir=None):
"""
Calls ``mri_annotation2label`` (`freesurfer wiki
<http://surfer.nmr.mgh.harvard.edu/fswiki/mri_annotation2label>`_)
mri_dir : str(path)
Path containing mri subject directories (freesurfer's ``SUBJECTS_DIR``).
subject : str
Name of the subject ('*' uses fnmatch to find folders in ``mri_dir``).
annot : str
Name of the annotation file (e.g., ``'aparc'``, ...).
dest : str(path)
Destination for the label files. {sdir}" and "{annot}" are filled in
appropriately.
hemi : 'lh' | 'rh' | '*'
Hemisphere to process; '*' proceses both.
"""
hemis = _fs_hemis(hemi)
subjects = _fs_subjects(subject)
subjects_dir = get_subjects_dir(subjects_dir)
# progress monitor
i_max = len(subjects) * len(hemis)
if len(subjects) > 1:
prog = ui.progress_monitor(i_max, "mri_annotation2label", "")
else:
prog = None
for subject in subjects:
sdir = os.path.join(subjects_dir, subject)
outdir = dest.format(sdir=sdir, annot=annot)
for hemi in hemis:
if prog:
prog.message("Processing: %s - %s" % (subject, hemi))
cmd = [get_bin("freesurfer", "mri_annotation2label"),
'--annotation', annot,
'--subject', subject,
'--hemi', hemi,
'--outdir', outdir,
]
_run(cmd, cwd=subjects_dir)
if prog:
prog.advance()
示例8: run
def run():
from mne.commands.utils import get_optparser
parser = get_optparser(__file__)
subject = os.environ.get('SUBJECT')
subjects_dir = get_subjects_dir()
parser.add_option("-s", "--subject", dest="subject",
help="Subject name", default=subject)
parser.add_option("-d", "--subjects-dir", dest="subjects_dir",
help="Subjects directory", default=subjects_dir)
parser.add_option("-m", "--method", dest="method",
help=("Method used to generate the BEM model. "
"Can be flash or watershed."), metavar="FILE")
options, args = parser.parse_args()
subject = options.subject
subjects_dir = options.subjects_dir
method = options.method
freeview_bem_surfaces(subject, subjects_dir, method)
示例9: _run
def _run(subjects_dir, subject, force, overwrite, no_decimate, verbose=None):
this_env = copy.copy(os.environ)
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
this_env['SUBJECTS_DIR'] = subjects_dir
this_env['SUBJECT'] = subject
if 'FREESURFER_HOME' not in this_env:
raise RuntimeError('The FreeSurfer environment needs to be set up '
'for this script')
incomplete = 'warn' if force else 'raise'
subj_path = op.join(subjects_dir, subject)
if not op.exists(subj_path):
raise RuntimeError('%s does not exist. Please check your subject '
'directory path.' % subj_path)
mri = 'T1.mgz' if op.exists(op.join(subj_path, 'mri', 'T1.mgz')) else 'T1'
logger.info('1. Creating a dense scalp tessellation with mkheadsurf...')
def check_seghead(surf_path=op.join(subj_path, 'surf')):
surf = None
for k in ['lh.seghead', 'lh.smseghead']:
this_surf = op.join(surf_path, k)
if op.exists(this_surf):
surf = this_surf
break
return surf
my_seghead = check_seghead()
if my_seghead is None:
run_subprocess(['mkheadsurf', '-subjid', subject, '-srcvol', mri],
env=this_env)
surf = check_seghead()
if surf is None:
raise RuntimeError('mkheadsurf did not produce the standard output '
'file.')
bem_dir = op.join(subjects_dir, subject, 'bem')
if not op.isdir(bem_dir):
os.mkdir(bem_dir)
dense_fname = op.join(bem_dir, '%s-head-dense.fif' % subject)
logger.info('2. Creating %s ...' % dense_fname)
_check_file(dense_fname, overwrite)
surf = mne.bem._surfaces_to_bem(
[surf], [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1],
incomplete=incomplete)[0]
mne.write_bem_surfaces(dense_fname, surf)
levels = 'medium', 'sparse'
tris = [] if no_decimate else [30000, 2500]
if os.getenv('_MNE_TESTING_SCALP', 'false') == 'true':
tris = [len(surf['tris'])] # don't actually decimate
for ii, (n_tri, level) in enumerate(zip(tris, levels), 3):
logger.info('%i. Creating %s tessellation...' % (ii, level))
logger.info('%i.1 Decimating the dense tessellation...' % ii)
with ETSContext():
points, tris = mne.decimate_surface(points=surf['rr'],
triangles=surf['tris'],
n_triangles=n_tri)
dec_fname = dense_fname.replace('dense', level)
logger.info('%i.2 Creating %s' % (ii, dec_fname))
_check_file(dec_fname, overwrite)
dec_surf = mne.bem._surfaces_to_bem(
[dict(rr=points, tris=tris)],
[mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1], rescale=False,
incomplete=incomplete)
mne.write_bem_surfaces(dec_fname, dec_surf)
示例10: _stc_to_label
def _stc_to_label(stc, src, smooth, subjects_dir=None):
"""Compute a label from the non-zero sources in an stc object.
Parameters
----------
stc : SourceEstimate
The source estimates.
src : SourceSpaces | str | None
The source space over which the source estimates are defined.
If it's a string it should the subject name (e.g. fsaverage).
Can be None if stc.subject is not None.
smooth : int
Number of smoothing iterations.
subjects_dir : str | None
Path to SUBJECTS_DIR if it is not set in the environment.
Returns
-------
labels : list of Labels | list of list of Labels
The generated labels. If connected is False, it returns
a list of Labels (one per hemisphere). If no Label is available
in a hemisphere, None is returned. If connected is True,
it returns for each hemisphere a list of connected labels
ordered in decreasing order depending of the maximum value in the stc.
If no Label is available in an hemisphere, an empty list is returned.
"""
src = stc.subject if src is None else src
if isinstance(src, string_types):
subject = src
else:
subject = stc.subject
if isinstance(src, string_types):
subjects_dir = get_subjects_dir(subjects_dir)
surf_path_from = op.join(subjects_dir, src, 'surf')
rr_lh, tris_lh = read_surface(op.join(surf_path_from,
'lh.white'))
rr_rh, tris_rh = read_surface(op.join(surf_path_from,
'rh.white'))
rr = [rr_lh, rr_rh]
tris = [tris_lh, tris_rh]
else:
if not isinstance(src, SourceSpaces):
raise TypeError('src must be a string or a set of source spaces')
if len(src) != 2:
raise ValueError('source space should contain the 2 hemispheres')
rr = [1e3 * src[0]['rr'], 1e3 * src[1]['rr']]
tris = [src[0]['tris'], src[1]['tris']]
labels = []
cnt = 0
for hemi_idx, (hemi, this_vertno, this_tris, this_rr) in enumerate(
zip(['lh', 'rh'], stc.vertices, tris, rr)):
this_data = stc.data[cnt:cnt + len(this_vertno)]
e = mesh_edges(this_tris)
e.data[e.data == 2] = 1
n_vertices = e.shape[0]
e = e + sparse.eye(n_vertices, n_vertices)
clusters = [this_vertno[np.any(this_data, axis=1)]]
cnt += len(this_vertno)
clusters = [c for c in clusters if len(c) > 0]
if len(clusters) == 0:
this_labels = None
else:
this_labels = []
colors = _n_colors(len(clusters))
for c, color in zip(clusters, colors):
idx_use = c
for k in range(smooth):
e_use = e[:, idx_use]
data1 = e_use * np.ones(len(idx_use))
idx_use = np.where(data1)[0]
label = Label(idx_use, this_rr[idx_use], None, hemi,
'Label from stc', subject=subject,
color=color)
this_labels.append(label)
this_labels = this_labels[0]
labels.append(this_labels)
return labels
示例11: labels_from_mni_coords
def labels_from_mni_coords(seeds, extent=30., subject='fsaverage',
surface='white', mask=None, subjects_dir=None,
parc=None):
"""Create a parcellation from seed coordinates in MNI space
Parameters
----------
seeds : dict
Seed coordinates. Keys are label names, including -hemi tags. values
are seeds (array_like of shape (3,) or (3, n_seeds)).
extent : scalar
Extent of the label in millimeters (maximum distance from the seed).
subject : str
MRI-subject to use (default 'fsaverage').
surface : str
Surface to use (default 'white').
mask : None | str
A parcellation used to mask the parcellation under construction.
subjects_dir : str
SUBJECTS_DIR.
parc : None | str
Name of the parcellation under construction (only used for error
messages).
"""
name_re = re.compile("\w+-(lh|rh)$")
if not all(name.endswith(('lh', 'rh')) for name in seeds):
err = ("Names need to end in 'lh' or 'rh' so that the proper "
"hemisphere can be selected")
raise ValueError(err)
# load surfaces
subjects_dir = get_subjects_dir(subjects_dir)
fpath = os.path.join(subjects_dir, subject, 'surf', '.'.join(('%s', surface)))
surfs = {hemi: mne.read_surface(fpath % hemi) for hemi in ('lh', 'rh')}
# prepare seed properties for mne.grow_labels
vertices = []
names = []
hemis = []
for name, coords_ in seeds.iteritems():
m = name_re.match(name)
if not m:
raise ValueError("Invalid seed name in %r parc: %r. Names must "
"conform to the 'xxx-lh' or 'xxx-rh' scheme."
% (parc, name))
coords = np.atleast_2d(coords_)
if coords.ndim != 2 or coords.shape[1] != 3:
raise ValueError("Invalid coordinate specification for seed %r in "
"parc %r: %r. Seeds need to be specified as "
"arrays with shape (3,) or (n_seeds, 3)."
% (name, parc, coords_))
hemi = m.group(1)
seed_verts = []
for coord in coords:
dist = np.sqrt(np.sum((surfs[hemi][0] - coord) ** 2, axis=1))
seed_verts.append(np.argmin(dist))
vertices.append(seed_verts)
names.append(name)
hemis.append(hemi == 'rh')
# grow labels
labels = mne.grow_labels(subject, vertices, extent, hemis, subjects_dir,
1, False, names, surface)
# apply mask
if mask is not None:
mlabels = mne.read_labels_from_annot(subject, mask,
subjects_dir=subjects_dir)
unknown = {l.hemi: l for l in mlabels if l.name.startswith('unknown-')}
for label in labels:
rm = unknown[label.hemi]
if np.any(np.in1d(label.vertices, rm.vertices)):
label.vertices = np.setdiff1d(label.vertices, rm.vertices, True)
return labels
示例12: write_labels_to_annot
def write_labels_to_annot(labels, subject=None, parc=None, overwrite=False,
subjects_dir=None, annot_fname=None,
colormap='hsv', hemi='both'):
"""Create a FreeSurfer annotation from a list of labels
FIX: always write both hemispheres
Parameters
----------
labels : list with instances of mne.Label
The labels to create a parcellation from.
subject : str | None
The subject for which to write the parcellation for.
parc : str | None
The parcellation name to use.
overwrite : bool
Overwrite files if they already exist.
subjects_dir : string, or None
Path to SUBJECTS_DIR if it is not set in the environment.
annot_fname : str | None
Filename of the .annot file. If not None, only this file is written
and 'parc' and 'subject' are ignored.
colormap : str
Colormap to use to generate label colors for labels that do not
have a color specified.
hemi : 'both' | 'lh' | 'rh'
The hemisphere(s) for which to write *.annot files (only applies if
annot_fname is not specified; default is 'both').
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
Notes
-----
Vertices that are not covered by any of the labels are assigned to a label
named "unknown".
"""
subjects_dir = get_subjects_dir(subjects_dir)
# get the .annot filenames and hemispheres
annot_fname, hemis = _get_annot_fname(annot_fname, subject, hemi, parc,
subjects_dir)
if not overwrite:
for fname in annot_fname:
if op.exists(fname):
raise ValueError('File %s exists. Use "overwrite=True" to '
'overwrite it' % fname)
# prepare container for data to save:
to_save = []
# keep track of issues found in the labels
duplicate_colors = []
invalid_colors = []
overlap = []
no_color = (-1, -1, -1, -1)
no_color_rgb = (-1, -1, -1)
for hemi, fname in zip(hemis, annot_fname):
hemi_labels = [label for label in labels if label.hemi == hemi]
n_hemi_labels = len(hemi_labels)
if n_hemi_labels == 0:
ctab = np.empty((0, 4), dtype=np.int32)
ctab_rgb = ctab[:, :3]
else:
hemi_labels.sort(key=lambda label: label.name)
# convert colors to 0-255 RGBA tuples
hemi_colors = [no_color if label.color is None else
tuple(int(round(255 * i)) for i in label.color)
for label in hemi_labels]
ctab = np.array(hemi_colors, dtype=np.int32)
ctab_rgb = ctab[:, :3]
# make color dict (for annot ID, only R, G and B count)
labels_by_color = defaultdict(list)
for label, color in zip(hemi_labels, ctab_rgb):
labels_by_color[tuple(color)].append(label.name)
# check label colors
for color, names in labels_by_color.items():
if color == no_color_rgb:
continue
if color == (0, 0, 0):
# we cannot have an all-zero color, otherw. e.g. tksurfer
# refuses to read the parcellation
msg = ('At least one label contains a color with, "r=0, '
'g=0, b=0" value. Some FreeSurfer tools may fail '
'to read the parcellation')
logger.warning(msg)
if any(i > 255 for i in color):
msg = ("%s: %s (%s)" % (color, ', '.join(names), hemi))
invalid_colors.append(msg)
if len(names) > 1:
msg = "%s: %s (%s)" % (color, ', '.join(names), hemi)
duplicate_colors.append(msg)
# replace None values (labels with unspecified color)
#.........这里部分代码省略.........