Coverage for nilearn/plotting/tests/test_img_plotting/test_plot_roi.py: 0%
50 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-16 12:32 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-16 12:32 +0200
1"""Tests for :func:`nilearn.plotting.plot_roi`."""
3# ruff: noqa: ARG001
5import matplotlib.pyplot as plt
6import numpy as np
7import pandas as pd
8import pytest
9from nibabel import Nifti1Image
11from nilearn.conftest import _affine_mni
12from nilearn.image.resampling import coord_transform
13from nilearn.plotting import plot_roi
16def demo_plot_roi(**kwargs):
17 """Demo plotting an ROI."""
18 data = np.zeros((91, 109, 91))
19 # Color a asymmetric rectangle around Broca area.
20 x, y, z = -52, 10, 22
21 x_map, y_map, z_map = coord_transform(
22 x, y, z, np.linalg.inv(_affine_mni())
23 )
24 data[
25 int(x_map) - 5 : int(x_map) + 5,
26 int(y_map) - 3 : int(y_map) + 3,
27 int(z_map) - 10 : int(z_map) + 10,
28 ] = 1
29 img = Nifti1Image(data, _affine_mni())
30 plot_roi(img, title="Broca's area", **kwargs)
33@pytest.mark.parametrize("view_type", ["contours", "continuous"])
34@pytest.mark.parametrize("threshold", [0.5, 0.2])
35@pytest.mark.parametrize("alpha", [0.7, 0.1])
36@pytest.mark.parametrize(
37 "display_mode,cut_coords", [("ortho", None), ("z", 3), ("x", [2.0, 10])]
38)
39def test_plot_roi_view_types(
40 matplotlib_pyplot,
41 view_type,
42 threshold,
43 alpha,
44 display_mode,
45 cut_coords,
46):
47 """Smoke-test for plot_roi.
49 Tests different combinations of parameters `view_type`,
50 `threshold`, and `alpha`.
51 """
52 kwargs = {}
53 if view_type == "contours":
54 kwargs["linewidth"] = 2.0
55 demo_plot_roi(
56 view_type=view_type,
57 threshold=threshold,
58 alpha=alpha,
59 display_mode=display_mode,
60 cut_coords=cut_coords,
61 **kwargs,
62 )
65def test_plot_roi_no_int_64_warning(matplotlib_pyplot, recwarn):
66 """Make sure that no int64 warning is thrown."""
67 demo_plot_roi()
68 for _ in range(len(recwarn)):
69 x = recwarn.pop()
70 if issubclass(x.category, UserWarning):
71 assert "image contains 64-bit ints" not in str(x.message)
74def test_plot_roi_view_type_error(matplotlib_pyplot):
75 """Test error message for invalid view_type."""
76 with pytest.raises(ValueError, match="Unknown view type:"):
77 demo_plot_roi(view_type="flled")
80def test_demo_plot_roi_output_file(matplotlib_pyplot, tmp_path):
81 """Tests plot_roi file saving capabilities."""
82 filename = tmp_path / "test.png"
83 out = demo_plot_roi(output_file=filename)
84 assert out is None
87def test_cmap_with_one_level(matplotlib_pyplot, shape_3d_default, affine_eye):
88 """Test we can handle cmap with only 1 level.
90 Regression test for
91 https://github.com/nilearn/nilearn/issues/4255
92 """
93 array_data = np.zeros(shape_3d_default)
94 array_data[0, 1, 1] = 1
96 img = Nifti1Image(array_data, affine_eye)
98 clust_ids = list(np.unique(img.get_fdata())[1:])
100 cmap = plt.get_cmap("tab20", len(clust_ids))
102 plot_roi(img, alpha=0.8, colorbar=True, cmap=cmap)
105def test_cmap_as_lookup_table(img_labels):
106 """Test colormap passed as BIDS lookup table."""
107 lut = pd.DataFrame(
108 {"index": [0, 1], "name": ["foo", "bar"], "color": ["#000", "#fff"]}
109 )
110 plot_roi(img_labels, cmap=lut)
112 lut = pd.DataFrame({"index": [0, 1], "name": ["foo", "bar"]})
113 with pytest.warns(
114 UserWarning, match="No 'color' column found in the look-up table."
115 ):
116 plot_roi(img_labels, cmap=lut)