Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/changes/latest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ Bugs

- Fix bug with :func:`mne.chpi.compute_chpi_locs` where all cHPI coils being off would lead to an empty array of the wrong dimensionality (:gh:`8956` by `Eric Larson`_)

- Fix bug with :func:`mne.extract_label_time_course` where labels, STCs, and the source space were not checked for compatible ``subject`` attributes (:gh:`9284` by `Eric Larson`_)

- Fix compatibility bugs with :mod:`mne_realtime` (:gh:`8845` by `Eric Larson`_)

- Fix bug with `mne.viz.Brain` where non-inflated surfaces had an X-offset imposed by default (:gh:`8794` by `Eric Larson`_)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@
subjects_dir=subjects_dir)

# Average the source estimates within each label of the cortical parcellation
# and each sub structures contained in the src space
# If mode = 'mean_flip' this option is used only for the cortical label
# and each sub-structure contained in the source space.
# When mode = 'mean_flip', this option is used only for the cortical labels.
src = inverse_operator['src']
label_ts = mne.extract_label_time_course(
stcs, labels_parc, src, mode='mean_flip', allow_empty=True,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
This example computes the coherence between a seed in the left
auditory cortex and the rest of the brain based on single-trial
MNE-dSPM inverse solutions.

"""
# Author: Martin Luessi <[email protected]>
#
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
The connectivity is computed between 4 labels across the spectrum
between 7.5 Hz and 40 Hz.
"""

# Authors: Alexandre Gramfort <[email protected]>
#
# License: BSD (3-clause)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
=============================================

Compute envelope correlations of orthogonalized activity
:footcite:`HippEtAl2012,KhanEtAl2018` in source
space using resting state CTF data.
:footcite:`HippEtAl2012,KhanEtAl2018` in source space using resting state
CTF data.
"""

# Authors: Eric Larson <[email protected]>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
====================================================

Compute envelope correlations of orthogonalized activity
:footcite:`HippEtAl2012,KhanEtAl2018` in source
space using resting state CTF data in a volume source space.
:footcite:`HippEtAl2012,KhanEtAl2018` in source space using resting state
CTF data in a volume source space.
"""

# Authors: Eric Larson <[email protected]>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@
# Average the source estimates within each label using sign-flips to reduce
# signal cancellations, also here we return a generator
src = inverse_operator['src']
label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip',
return_generator=True)
label_ts = mne.extract_label_time_course(
stcs, labels, src, mode='mean_flip', return_generator=True)

fmin = 8.
fmax = 13.
Expand Down
1 change: 0 additions & 1 deletion examples/connectivity/plot_mne_inverse_psi_visual.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
#
# License: BSD (3-clause)


import numpy as np

import mne
Expand Down
1 change: 1 addition & 0 deletions mne/commands/tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ def test_setup_source_space(tmpdir):
assert mne_setup_source_space.run()


@pytest.mark.slowtest
@testing.requires_testing_data
def test_setup_forward_model(tmpdir):
"""Test mne setup_forward_model."""
Expand Down
2 changes: 2 additions & 0 deletions mne/io/tests/test_raw.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,7 @@ def test_test_raw_reader():
_test_raw_reader(_read_raw_arange, test_scaling=False, test_rank='less')


@pytest.mark.slowtest
def test_describe_print():
"""Test print output of describe method."""
fname = Path(__file__).parent / "data" / "test_raw.fif"
Expand All @@ -600,6 +601,7 @@ def test_describe_print():


@requires_pandas
@pytest.mark.slowtest
def test_describe_df():
"""Test returned data frame of describe method."""
fname = Path(__file__).parent / "data" / "test_raw.fif"
Expand Down
4 changes: 2 additions & 2 deletions mne/label.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def __init__(self, vertices=(), pos=None, values=None, hemi=None,
self.hemi = hemi
self.comment = comment
self.verbose = verbose
self.subject = _check_subject(None, subject, False)
self.subject = _check_subject(None, subject, raise_error=False)
self.color = color
self.name = name
self.filename = filename
Expand Down Expand Up @@ -2249,7 +2249,7 @@ def labels_to_stc(labels, values, tmin=0, tstep=1, subject=None, src=None,
else:
kind = src.kind
subject = _check_subject(
src._subject, subject, kind='source space subject',
src._subject, subject, first_kind='source space subject',
raise_error=False)
_check_option('source space kind', kind, ('surface', 'volume'))
if kind == 'volume':
Expand Down
1 change: 1 addition & 0 deletions mne/minimum_norm/tests/test_inverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@ def test_localization_bias_free(bias_params_free, method, lower, upper,
_assert_free_ori_match(ori, max_idx, lower_ori, upper_ori)


@pytest.mark.slowtest
def test_apply_inverse_sphere(evoked):
"""Test applying an inverse with a sphere model (rank-deficient)."""
evoked.pick_channels(evoked.ch_names[:306:8])
Expand Down
20 changes: 16 additions & 4 deletions mne/source_estimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,7 @@ def __init__(self, data, vertices, tmin, tstep,
self._kernel_removed = False
self._times = None
self._update_times()
self.subject = _check_subject(None, subject, False)
self.subject = _check_subject(None, subject, raise_error=False)

def __repr__(self): # noqa: D105
s = "%d vertices" % (sum(len(v) for v in self.vertices),)
Expand Down Expand Up @@ -2861,6 +2861,9 @@ def _temporary_vertices(src, vertices):

def _check_stc_src(stc, src):
if stc is not None and src is not None:
_check_subject(
src._subject, stc.subject, raise_error=False,
first_kind='source space subject', second_kind='stc.subject')
for s, v, hemi in zip(src, stc.vertices, ('left', 'right')):
n_missing = (~np.in1d(v, s['vertno'])).sum()
if n_missing:
Expand Down Expand Up @@ -2892,6 +2895,14 @@ def _prepare_label_extraction(stc, labels, src, mode, allow_empty, use_sparse):

bad_labels = list()
for li, label in enumerate(labels):
subject = label['subject'] if use_sparse else label.subject
# stc and src can each be None
_check_subject(
subject, getattr(stc, 'subject', None), raise_error=False,
first_kind='label.subject', second_kind='stc.subject')
_check_subject(
subject, getattr(src, '_subject', None), raise_error=False,
first_kind='label.subject', second_kind='source space subject')
if use_sparse:
assert isinstance(label, dict)
vertidx = label['csr']
Expand Down Expand Up @@ -2976,6 +2987,7 @@ def _volume_labels(src, labels, mri_resolution):
# given volumetric source space when used with extract_label_time_course
from .label import Label
assert src.kind == 'volume'
subject = src._subject
extra = ' when using a volume source space'
_import_nibabel('use volume atlas labels')
_validate_type(labels, ('path-like', list, tuple), 'labels' + extra)
Expand Down Expand Up @@ -3036,7 +3048,7 @@ def _volume_labels(src, labels, mri_resolution):
for k, v in labels.items():
mask = atlas_data == v
csr = interp[mask]
out_labels.append(dict(csr=csr, name=k))
out_labels.append(dict(csr=csr, name=k, subject=subject))
nnz += csr.shape[0] > 0
else:
# Use nearest values
Expand All @@ -3045,7 +3057,7 @@ def _volume_labels(src, labels, mri_resolution):
del src
src_values = _get_atlas_values(vol_info, rr[vertno])
vertices = [vertno[src_values == val] for val in labels.values()]
out_labels = [Label(v, hemi='lh', name=val)
out_labels = [Label(v, hemi='lh', name=val, subject=subject)
for v, val in zip(vertices, labels.keys())]
nnz = sum(len(v) != 0 for v in vertices)
logger.info('%d/%d atlas regions had at least one vertex '
Expand Down Expand Up @@ -3308,7 +3320,7 @@ def stc_near_sensors(evoked, trans, subject, distance=0.01, mode='sum',
# convert head positions -> coord_frame MRI
pos = apply_trans(trans, pos)

subject = _check_subject(None, subject, False)
subject = _check_subject(None, subject, raise_error=False)
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
if src is None: # fake a full surface one
rrs = [read_surface(op.join(subjects_dir, subject,
Expand Down
51 changes: 51 additions & 0 deletions mne/tests/test_source_estimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1791,3 +1791,54 @@ def test_scale_morph_labels(kind, scale, monkeypatch, tmpdir):
else:
corr = np.corrcoef(label_tc.ravel(), label_tc_to.ravel())[0, 1]
assert 0.93 < corr < 0.96, scale


@testing.requires_testing_data
@pytest.mark.parametrize('kind', [
'surface',
pytest.param('volume', marks=[pytest.mark.slowtest,
requires_version('nibabel')]),
])
def test_label_extraction_subject(kind):
"""Test that label extraction subject is treated properly."""
if kind == 'surface':
inv = read_inverse_operator(fname_inv)
labels = read_labels_from_annot(
'sample', subjects_dir=subjects_dir)
labels_fs = read_labels_from_annot(
'fsaverage', subjects_dir=subjects_dir)
labels_fs = [label for label in labels_fs
if not label.name.startswith('unknown')]
assert all(label.subject == 'sample' for label in labels)
assert all(label.subject == 'fsaverage' for label in labels_fs)
assert len(labels) == len(labels_fs) == 68
n_labels = 68
else:
assert kind == 'volume'
inv = read_inverse_operator(fname_inv_vol)
inv['src'][0]['subject_his_id'] = 'sample' # modernize
labels = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')
labels_fs = op.join(subjects_dir, 'fsaverage', 'mri', 'aseg.mgz')
n_labels = 46
src = inv['src']
assert src.kind == kind
assert src._subject == 'sample'
ave = read_evokeds(fname_evoked)[0].apply_baseline((None, 0)).crop(0, 0.01)
assert len(ave.times) == 4
stc = apply_inverse(ave, inv)
assert stc.subject == 'sample'
ltc = extract_label_time_course(stc, labels, src)
stc.subject = 'fsaverage'
with pytest.raises(ValueError, match=r'source spac.*not match.* stc\.sub'):
extract_label_time_course(stc, labels, src)
stc.subject = 'sample'
assert ltc.shape == (n_labels, 4)
if kind == 'volume':
with pytest.raises(RuntimeError, match='atlas.*not match.*source spa'):
extract_label_time_course(stc, labels_fs, src)
else:
with pytest.raises(ValueError, match=r'label\.sub.*not match.* stc\.'):
extract_label_time_course(stc, labels_fs, src)
stc.subject = None
with pytest.raises(ValueError, match=r'label\.sub.*not match.* sourc'):
extract_label_time_course(stc, labels_fs, src)
29 changes: 16 additions & 13 deletions mne/utils/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,21 +179,24 @@ def _check_fname(fname, overwrite=False, must_exist=False, name='File',
return str(op.abspath(fname))


def _check_subject(class_subject, input_subject, raise_error=True,
kind='class subject attribute'):
def _check_subject(first, second, *, raise_error=True,
first_kind='class subject attribute',
second_kind='input subject'):
"""Get subject name from class."""
if input_subject is not None:
_validate_type(input_subject, 'str', "subject input")
if class_subject is not None and input_subject != class_subject:
raise ValueError('%s (%r) did not match input subject (%r)'
% (kind, class_subject, input_subject))
return input_subject
elif class_subject is not None:
_validate_type(class_subject, 'str',
"Either subject input or %s" % (kind,))
return class_subject
if second is not None:
_validate_type(second, 'str', "subject input")
if first is not None and first != second:
raise ValueError(
f'{first_kind} ({repr(first)}) did not match '
f'{second_kind} ({second})')
return second
elif first is not None:
_validate_type(
first, 'str', f"Either {second_kind} subject or {first_kind}")
return first
elif raise_error is True:
raise ValueError('Neither subject input nor %s was a string' % (kind,))
raise ValueError(f'Neither {second_kind} subject nor {first_kind} '
'was a string')
return None


Expand Down
10 changes: 5 additions & 5 deletions mne/viz/_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -1755,7 +1755,7 @@ def plot_source_estimates(stc, subject=None, surface='inflated', hemi='lh',
_validate_type(stc, _BaseSourceEstimate, 'stc', 'source estimate')
subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,
raise_error=True)
subject = _check_subject(stc.subject, subject, True)
subject = _check_subject(stc.subject, subject)
_check_option('backend', backend,
['auto', 'matplotlib', 'mayavi', 'pyvista'])
plot_mpl = backend == 'matplotlib'
Expand Down Expand Up @@ -1797,7 +1797,7 @@ def _plot_stc(stc, subject, surface, hemi, colormap, time_label,
vec = stc._data_ndim == 3
subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,
raise_error=True)
subject = _check_subject(stc.subject, subject, True)
subject = _check_subject(stc.subject, subject)

backend = _get_3d_backend()
del _get_3d_backend
Expand Down Expand Up @@ -2012,7 +2012,7 @@ def _load_subject_mri(mri, stc, subject, subjects_dir, name):
from nibabel.spatialimages import SpatialImage
_validate_type(mri, ('path-like', SpatialImage), name)
if isinstance(mri, str):
subject = _check_subject(stc.subject, subject, True)
subject = _check_subject(stc.subject, subject)
mri = nib.load(_check_mri(mri, subject, subjects_dir))
return mri

Expand Down Expand Up @@ -2132,7 +2132,7 @@ def plot_volume_source_estimates(stc, src, subject=None, subjects_dir=None,
del src
_print_coord_trans(Transform('mri_voxel', 'ras', img.affine),
prefix='Image affine ', units='mm', level='debug')
subject = _check_subject(src_subject, subject, True, kind=kind)
subject = _check_subject(src_subject, subject, first_kind=kind)
stc_ijk = np.array(
np.unravel_index(stc.vertices[0], img.shape[:3], order='F')).T
assert stc_ijk.shape == (len(stc.vertices[0]), 3)
Expand Down Expand Up @@ -2263,7 +2263,7 @@ def _onclick(event, params, verbose=None):
params['fig'].canvas.draw()

if mode == 'glass_brain':
subject = _check_subject(stc.subject, subject, True)
subject = _check_subject(stc.subject, subject)
ras_mni_t = read_ras_mni_t(subject, subjects_dir)
if not np.allclose(ras_mni_t['trans'], np.eye(4)):
_print_coord_trans(
Expand Down
2 changes: 1 addition & 1 deletion tools/get_minimal_commands.sh
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ else
export DYLD_LIBRARY_PATH=${MNE_ROOT}/lib:$DYLD_LIBRARY_PATH
if [ "${GITHUB_ACTIONS}" == "true" ]; then
echo "DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}" >> "$GITHUB_ENV";
wget https://dl.bintray.com/xquartz/downloads/XQuartz-2.7.11.dmg
wget https://github.com/XQuartz/XQuartz/releases/download/XQuartz-2.7.11/XQuartz-2.7.11.dmg
sudo hdiutil attach XQuartz-2.7.11.dmg
sudo installer -package /Volumes/XQuartz-2.7.11/XQuartz.pkg -target /
sudo ln -s /opt/X11 /usr/X11
Expand Down
6 changes: 3 additions & 3 deletions tutorials/source-modeling/plot_visualize_stc.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@
fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')

###############################################################################
# Then, we read the stc from file
# Then, we read the stc from file.
stc = mne.read_source_estimate(fname_stc, subject='sample')

###############################################################################
# This is a :class:`SourceEstimate <mne.SourceEstimate>` object
# This is a :class:`SourceEstimate <mne.SourceEstimate>` object.
print(stc)

###############################################################################
Expand All @@ -50,7 +50,7 @@
clim=dict(kind='value', lims=[3, 6, 9]))

###############################################################################
# You can also morph it to fsaverage and visualize it using a flatmap
# You can also morph it to fsaverage and visualize it using a flatmap.

# sphinx_gallery_thumbnail_number = 3
stc_fs = mne.compute_source_morph(stc, 'sample', 'fsaverage', subjects_dir,
Expand Down