Skip to content

IndexError in rdm_plot._contour_coords when contour mask touches matrix edges #485

@XuShaobo-py

Description

@XuShaobo-py

Describe the bug
When plotting an RDM with a contour mask that includes the outermost edges of the matrix (e.g., an all-True mask), the _contour_coords function throws an IndexError.

This occurs because the contour-drawing algorithm checks the state of neighboring cells to find boundaries, but it lacks boundary condition checks. When a mask cell is located at the absolute edge of the matrix, checking its outer neighbor results in an out-of-bounds index.

To Reproduce

import matplotlib.pyplot as plt
import numpy as np
from rsatoolbox.rdm.rdms import RDMs
from rsatoolbox.vis.rdm_plot import show_rdm, Symmetry

n_conditions = 9
n_utv = int(n_conditions * (n_conditions - 1) / 2)  

dissim_utv = np.random.rand(n_utv)
rdms = RDMs(
    dissimilarities=dissim_utv,
    dissimilarity_measure='random'
)

mask = np.ones(n_utv, dtype=bool)  # Masking all upper triangular values as True, including the edges

show_rdm(
    rdms,
    vmin=0,
    vmax=1,
    show_colorbar=None,
    contour=mask,
    contour_symmetry=Symmetry.UPPER
)
plt.show()

Versions

  • rsatoolbox 0.3.2
  • python 3.11

Fix
In line 410 of rsatoolbox.vis.rdm_plot.py, change this line:

if not mask_t[(x+neighbor[0], y+neighbor[1])]:

to

nx, ny = x + neighbor[0], y + neighbor[1]
if nx < 0 or ny < 0 or nx >= mask_t.shape[0] or ny >= mask_t.shape[1] or not mask_t[(nx, ny)]:

This will fix the bug and create a rdm plot as follows:

Image

stack trace

Traceback (most recent call last):
  File "...\rsatoolbox\vis\rdm_plot.py", line 173, in _plot_multi_rdm
    handles[p]["image"] = _show_rdm_panel(conf.for_single(rdm_index), ax_array[r, c])
  File "...\rsatoolbox\vis\rdm_plot.py", line 322, in _show_rdm_panel
    _contour(conf, ax)
  File "...\rsatoolbox\vis\rdm_plot.py", line 360, in _contour
    for (x1, y1, x2, y2) in _contour_coords(conf.contour_mask, -0.5):
  File "...\rsatoolbox\vis\rdm_plot.py", line 410, in _contour_coords
    if not mask_t[(x+neighbor[0], y+neighbor[1])]:
IndexError: index 9 is out of bounds for axis 0 with size 9

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions