• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

neurospin-deepinsight / brainprep / 19471672015

18 Nov 2025 03:32PM UTC coverage: 79.472% (+0.02%) from 79.449%
19471672015

push

github

AGrigis
doc: fix documentation.

1444 of 1817 relevant lines covered (79.47%)

0.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

50.68
/brainprep/interfaces/plotting.py
1
##########################################################################
2
# NSAp - Copyright (C) CEA, 2021 - 2025
3
# Distributed under the terms of the CeCILL-B license, as published by
4
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
5
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
6
# for details.
7
##########################################################################
8

9
"""
10
Plotting functions.
11
"""
12

13
import itertools
1✔
14

15
import matplotlib.pyplot as plt
1✔
16
import nibabel
1✔
17
import numpy as np
1✔
18
import pandas as pd
1✔
19
import seaborn as sns
1✔
20
from nilearn import plotting
1✔
21

22
from ..reporting import log_runtime
1✔
23
from ..typing import (
1✔
24
    Directory,
25
    File,
26
)
27
from ..utils import (
1✔
28
    coerceparams,
29
    outputdir,
30
)
31
from ..wrappers import pywrapper
1✔
32

33

34
@coerceparams
1✔
35
@outputdir
1✔
36
@log_runtime(
1✔
37
    bunched=False)
38
@pywrapper
1✔
39
def plot_defacing_mosaic(
1✔
40
        im_file: File,
41
        mask_file: File,
42
        output_dir: Directory,
43
        entities: dict,
44
        dryrun: bool = False) -> tuple[File]:
45
    """
46
    Generates a defacing mosaic image by overlaying a mask on an anatomical
47
    image.
48

49
    Parameters
50
    ----------
51
    im_file : File
52
        Path to the anatomical image.
53
    mask_file : File
54
        Path to the defacing mask.
55
    output_dir : Directory
56
        Directory where the mosaic image will be saved.
57
    entities : dict
58
        A dictionary of parsed BIDS entities including modality.
59
    dryrun : bool
60
        If True, skip actual computation and file writing. Default False.
61

62
    Returns
63
    -------
64
    mosaic_file : File
65
        Path to the saved mosaic image.
66
    """
67
    basename = "sub-{sub}_ses-{ses}_run-{run}_mod-T1w_deface".format(
1✔
68
        **entities)
69
    mosaic_file = output_dir / f"{basename}mosaic.png"
1✔
70

71
    if not dryrun:
1✔
72
        plotting.plot_roi(
×
73
            mask_file,
74
            bg_img=im_file,
75
            display_mode="z",
76
            cut_coords=25,
77
            black_bg=True,
78
            alpha=0.6,
79
            colorbar=False,
80
            output_file=mosaic_file
81
        )
82
        arr = plt.imread(mosaic_file)
×
83
        cut = int(arr.shape[1] / 5)
×
84
        plt.figure()
×
85
        arr = np.concatenate(
×
86
            [arr[:, idx * cut: (idx + 1) * cut] for idx in range(5)], axis=0)
87
        plt.imshow(arr)
×
88
        plt.axis("off")
×
89
        plt.savefig(mosaic_file)
×
90

91
    return (mosaic_file, )
1✔
92

93

94
@coerceparams
1✔
95
@outputdir
1✔
96
@log_runtime(
1✔
97
    bunched=False)
98
@pywrapper
1✔
99
def plot_histogram(
1✔
100
        table_file: File,
101
        col_name: str,
102
        output_dir: Directory,
103
        bar_coords: list[float] | None = None,
104
        dryrun: bool = False) -> tuple[File]:
105
    """
106
    Generates a histogram image with optional vertical bars.
107

108
    Parameters
109
    ----------
110
    table_file : File
111
        TSV table containing the data to be displayed.
112
    col_name : str
113
        Name of the column containing the histogram data.
114
    output_dir : Directory
115
        Directory where the image with the histogram will be saved.
116
    bar_coords: list[float] | None
117
        Coordianates of vertical lines to be displayed in red. Default None.
118
    dryrun : bool
119
        If True, skip actual computation and file writing. Default False.
120

121
    Returns
122
    -------
123
    histogram_file : File
124
        Generated image with the histogram.
125
    """
126
    histogram_file = output_dir / f"histogram_{col_name}.png"
1✔
127

128
    if not dryrun:
1✔
129

130
        data = pd.read_csv(
×
131
            histogram_file,
132
            sep="\t",
133
        )
134
        arr = data[col_name].astype(float)
×
135
        arr = arr[~np.isnan(arr)]
×
136
        arr = arr[~np.isinf(arr)]
×
137

138
        _, ax = plt.subplots()
×
139
        sns.histplot(
×
140
            arr,
141
            color="gray",
142
            alpha=0.6,
143
            ax=ax,
144
            kde=True,
145
            stat="density",
146
            label=col_name,
147
        )
148
        for x_coord in bar_coords or []:
×
149
            ax.axvline(x=x_coord, color="red")
×
150
        ax.spines["right"].set_visible(False)
×
151
        ax.spines["top"].set_visible(False)
×
152
        ax.legend()
×
153

154
        plt.savefig(histogram_file)
×
155

156
    return (histogram_file, )
1✔
157

158

159
@coerceparams
1✔
160
@outputdir
1✔
161
@log_runtime(
1✔
162
    bunched=False)
163
@pywrapper
1✔
164
def plot_brainparc(
1✔
165
        wm_mask_file: File,
166
        gm_mask_file: File,
167
        csf_mask_file: File,
168
        brain_mask_file: File,
169
        output_dir: Directory,
170
        entities: dict,
171
        dryrun: bool = False) -> tuple[File]:
172
    """
173

174
    Parameters
175
    ----------
176
    wm_mask_file : File
177
        Binary mask of white matter regions.
178
    gm_mask_file : File
179
        Binary mask of gray matter regions.
180
    csf_mask_file : File
181
        Binary mask of cerebrospinal fluid regions.
182
    brain_mask_file : File
183
        Binary brain mask file.
184
    output_dir : Directory
185
        FreeSurfer working directory containing all the subjects.
186
    entities : dict
187
        A dictionary of parsed BIDS entities including modality.
188
    dryrun : bool
189
        If True, skip actual computation and file writing. Default False.
190

191
    Returns
192
    -------
193
    brainparc_image_file : File
194
        Image of the GM mask and GM, WM, CSF tissues histograms.
195
    """
196
    basename = "sub-{sub}_ses-{ses}_run-{run}_brainparc".format(
1✔
197
        **entities)
198
    brainparc_image_file = output_dir / f"{basename}.png"
1✔
199

200
    if not dryrun:
1✔
201

202
        subject = f"run-{entities['run']}"
×
203
        anat_file = output_dir / subject / "mri" / "norm.mgz"
×
204

205
        fig, axs = plt.subplots(2)
×
206
        plotting.plot_roi(
×
207
            roi_img=gm_mask_file,
208
            bg_img=anat_file,
209
            alpha=0.3,
210
            figure=fig,
211
            axes=axs[0],
212
        )
213

214
        anat_arr = nibabel.load(anat_file).get_fdata()
×
215
        mask_arr = nibabel.load(brain_mask_file).get_fdata()
×
216
        bins = np.histogram_bin_edges(
×
217
            anat_arr[mask_arr],
218
            bins="auto",
219
        )
220
        palette = itertools.cycle(sns.color_palette("Set1"))
×
221
        for name, path in [("WM", wm_mask_file),
×
222
                           ("GM", gm_mask_file),
223
                           ("CSF", csf_mask_file)]:
224
            mask = nibabel.load(path).get_fdata().astype(int)
×
225
            sns.histplot(
×
226
                anat_arr[mask],
227
                bins=bins,
228
                color=next(palette),
229
                alpha=0.6,
230
                ax=axs[1],
231
                kde=True,
232
                stat="density",
233
                label=name,
234
            )
235
        axs[1].spines["right"].set_visible(False)
×
236
        axs[1].spines["top"].set_visible(False)
×
237
        axs[1].legend()
×
238

239
        plt.subplots_adjust(wspace=0, hspace=0, top=0.9, bottom=0.1)
×
240
        plt.savefig(brainparc_image_file)
×
241

242
    return (brainparc_image_file, )
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc