Skip to content

Commit

Permalink
[BUG, ENH] Improve error checking of plot_sensors_connectivity and …
Browse files Browse the repository at this point in the history
…add a `min_distance` parameter (mne-tools#221)

Co-authored-by: Eric Larson <[email protected]>
  • Loading branch information
tsbinns and larsoner authored Aug 1, 2024
1 parent a405ef8 commit 906ad82
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 18 deletions.
37 changes: 30 additions & 7 deletions mne_connectivity/viz/_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,14 @@

@fill_doc
def plot_sensors_connectivity(
info, con, picks=None, cbar_label="Connectivity", n_con=20, cmap="RdBu"
info,
con,
picks=None,
*,
cbar_label="Connectivity",
n_con=20,
cmap="RdBu",
min_distance=0.05,
):
"""Visualize the sensor connectivity in 3D.
Expand All @@ -37,9 +44,14 @@ def plot_sensors_connectivity(
n_con : int
Number of strongest connections shown. By default 20.
cmap : str | instance of matplotlib.colors.Colormap
Colormap for coloring connections by strength. If :class:`str`, must
be a valid Matplotlib colormap (i.e. a valid key of
``matplotlib.colormaps``). Default is ``"RdBu"``.
Colormap for coloring connections by strength. If :class:`str`, must be a valid
Matplotlib colormap (i.e. a valid key of `matplotlib.colormaps`). Default is
``"RdBu"``.
min_distance : float
The minimum distance required between two sensors to plot a connection between
them, in meters. Default is 0.05 (i.e. 5 cm).
.. versionadded:: 0.8
Returns
-------
Expand Down Expand Up @@ -70,6 +82,12 @@ def plot_sensors_connectivity(
f"size of the connectivity data ({len(con)})"
)

if min_distance <= 0:
raise ValueError(
"The minimum distance between sensors must be greater than 0 m, got "
f"{min_distance} m"
)

# Plot the sensor locations
sens_loc = [info["chs"][k]["loc"][:3] for k in picks]
sens_loc = np.array(sens_loc)
Expand All @@ -86,16 +104,21 @@ def plot_sensors_connectivity(
ii, jj = np.where(con >= threshold)

# Remove close connections
min_dist = 0.05 # exclude sensors that are less than 5cm apart
con_nodes = list()
con_val = list()
for i, j in zip(ii, jj):
if np.linalg.norm(sens_loc[i] - sens_loc[j]) > min_dist:
if np.linalg.norm(sens_loc[i] - sens_loc[j]) > min_distance:
con_nodes.append((i, j))
con_val.append(con[i, j])

con_val = np.array(con_val)

if con_val.size == 0:
raise ValueError(
f"None of the {n_con} strongest connections were at least {min_distance} m "
"apart. Try decreasing `min_distance` or increasing `n_con`, and check "
"that the coordinates of your channels in `info` are not NaNs"
)

# Show the connections as tubes between sensors
vmax = np.max(con_val)
vmin = np.min(con_val)
Expand Down
52 changes: 41 additions & 11 deletions mne_connectivity/viz/tests/test_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,15 @@ def test_plot_sensors_connectivity(renderer):
"""Test plotting of sensors connectivity."""
data_path = data_dir
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")

raw = mne.io.read_raw_fif(raw_fname)
info = raw.info
picks = mne.pick_types(
raw.info, meg="grad", eeg=False, stim=False, eog=True, exclude="bads"
)
n_channels = len(picks)
con = np.random.RandomState(42).randn(n_channels, n_channels)
info = raw.info
with pytest.raises(TypeError, match="must be an instance of Info"):
plot_sensors_connectivity(info="foo", con=con, picks=picks)
with pytest.raises(ValueError, match="Connectivity data must be a 2D array"):
plot_sensors_connectivity(info=info, con=np.expand_dims(con, 3), picks=picks)
with pytest.raises(ValueError, match="2D array of shape (n_channels, n_channels)"):
plot_sensors_connectivity(info=info, con=con[:, :-1], picks=picks)
with pytest.raises(ValueError, match="does not correspond to the size"):
plot_sensors_connectivity(info=info, con=con[::2, ::2], picks=picks)
rng = np.random.default_rng(42)
con = rng.standard_normal((n_channels, n_channels))

cmap = "viridis"
fig = plot_sensors_connectivity(info=info, con=con, picks=picks, cmap=cmap)
# check colormap
Expand All @@ -45,3 +38,40 @@ def test_plot_sensors_connectivity(renderer):
# check title
title = list(fig.plotter.scalar_bars.values())[0].GetTitle()
assert title == "Connectivity"


@testing.requires_testing_data
def test_plot_sensors_connectivity_error_catch(renderer):
"""Test `plot_sensors_connectivity` catches errors."""
# Get data to plot
data_path = data_dir
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")
raw = mne.io.read_raw_fif(raw_fname)
info = raw.info
picks = mne.pick_types(
raw.info, meg="grad", eeg=False, stim=False, eog=True, exclude="bads"
)
n_channels = len(picks)
rng = np.random.default_rng(42)
con = rng.standard_normal((n_channels, n_channels))

# Check errors caught
# bad Info type
with pytest.raises(TypeError, match="must be an instance of Info"):
plot_sensors_connectivity(info="foo", con=con, picks=picks)
# bad connectivity array shape
with pytest.raises(ValueError, match="Connectivity data must be a 2D array"):
plot_sensors_connectivity(info=info, con=np.expand_dims(con, 2), picks=picks)
with pytest.raises(ValueError, match=r"array of shape \(n_channels, n_channels\)"):
plot_sensors_connectivity(info=info, con=con[:, :-1], picks=picks)
# mismatched channels and picks
with pytest.raises(ValueError, match="does not correspond to the size"):
plot_sensors_connectivity(info=info, con=con[::2, ::2], picks=picks)
# bad minimum distance
with pytest.raises(ValueError, match="distance between sensors must be greater"):
plot_sensors_connectivity(info=info, con=con, picks=picks, min_distance=0)
with pytest.raises(ValueError, match="distance between sensors must be greater"):
plot_sensors_connectivity(info=info, con=con, picks=picks, min_distance=-1)
# no surviving connections for minimum distance
with pytest.raises(ValueError, match=r"No.*connections were at least.*apart"):
plot_sensors_connectivity(info=info, con=con, picks=picks, min_distance=1e6)

0 comments on commit 906ad82

Please sign in to comment.