-
Notifications
You must be signed in to change notification settings - Fork 56
/
base.py
479 lines (394 loc) · 16.1 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# STATEMENT OF CHANGES: This file is derived from sources licensed under the Apache-2.0 terms,
# and this file has been changed.
# The original file this work derives from is found at:
# https://github.com/nipreps/niworkflows/blob/9905f90110879ed4123ea291f512b0a60d7ba207/niworkflows/reports/core.py
#
# [May 2023] CHANGES:
# * Replace BIDSlayout with code that uses the nimare Dataset and MetaResult class.
#
# ORIGINAL WORK'S ATTRIBUTION NOTICE:
#
# Copyright 2021 The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Reports builder for NiMARE's MetaResult object."""
import textwrap
from glob import glob
from pathlib import Path
import jinja2
from pkg_resources import resource_filename as pkgrf
from nimare.meta.cbma.base import CBMAEstimator
from nimare.reports.figures import (
gen_table,
plot_clusters,
plot_coordinates,
plot_heatmap,
plot_interactive_brain,
plot_mask,
plot_static_brain,
)
SVG_SNIPPET = [
"""\
<object class="svg-reportlet" type="image/svg+xml" data="./{0}">
Problem loading figure {0}. If the link below works, please try \
reloading the report in your browser.</object>
</div>
<div class="elem-filename">
Get figure file: <a href="./{0}" target="_blank">{0}</a>
</div>
""",
"""\
<img class="svg-reportlet" src="./{0}" style="width: 100%" />
</div>
<div class="elem-filename">
Get figure file: <a href="./{0}" target="_blank">{0}</a>
</div>
""",
]
IFRAME_SNIPPET = """\
<iframe id="igraph" scrolling="no" style="border:none;" seamless="seamless" \
src="./{0}" height="800" width="100%"></iframe>
"""
PARAMETERS_DICT = {
"kernel_transformer__fwhm": "FWHM",
"kernel_transformer__sample_size": "Sample size",
"kernel_transformer__r": "Sphere radius (mm)",
"kernel_transformer__value": "Value for sphere",
"null_method": "Null method",
"n_iters": "Number of iterations",
"n_cores": "Number of cores",
"fwe": "Family-wise error rate (FWE) correction",
"fdr": "False discovery rate (FDR) correction",
"method": "Method",
"alpha": "Alpha",
}
SUMMARY_TEMPLATE = """\
<ul class="elem-desc">
<li>Number of studies: {n_exps:d}</li>
<li>Number of studies included: {n_exps_sel:d}</li>
<li>Number of foci: {n_foci:d} </li>
<li>Number of foci outside the mask: {n_foci_nonbrain:d} </li>
</ul>
<details>
<summary>Studies excluded</summary><br />
<p>{exc_ids}</p>
</details>
"""
ESTIMATOR_TEMPLATE = """\
<ul class="elem-desc">
<li>Kernel Transformer: {kernel_transformer}{ker_params_text}</li>
{est_params_text}
</ul>
"""
CORRECTOR_TEMPLATE = """\
<ul class="elem-desc">
<li> Correction Method: {correction_method}</li>
{cor_params_text}
<li>Parameters: {ext_params_text}</li>
</ul>
"""
DIAGNOSTIC_TEMPLATE = """\
<h2 class="sub-report-group">Target image: {target_image}</h2>
<ul class="elem-desc">
<li>Voxel-level threshold: {voxel_thresh}</li>
<li>Cluster size threshold: {cluster_threshold}</li>
<li>Number of cores: {n_cores}</li>
</ul>
"""
def _gen_est_summary(obj, out_filename):
"""Generate html with parameter use in obj (e.g., estimator)."""
params_dict = obj.get_params()
est_params = {k: v for k, v in params_dict.items() if not k.startswith("kernel_transformer")}
ker_params = {k: v for k, v in params_dict.items() if k.startswith("kernel_transformer__")}
ker_params_text = ["<ul>"]
for k, v in ker_params.items():
ker_params_text.append(f"<li>{PARAMETERS_DICT[k]}: {v}</li>")
ker_params_text.append("</ul>")
ker_params_text = "".join(ker_params_text)
est_params_text = []
for k, v in est_params.items():
est_params_text.append(f"<li>{PARAMETERS_DICT[k]}: {v}</li>")
est_params_text = "".join(est_params_text)
summary_text = ESTIMATOR_TEMPLATE.format(
kernel_transformer=str(params_dict["kernel_transformer"]),
ker_params_text=ker_params_text,
est_params_text=est_params_text,
)
(out_filename).write_text(summary_text, encoding="UTF-8")
def _gen_cor_summary(obj, out_filename):
"""Generate html with parameter use in obj (e.g., corrector)."""
params_dict = obj.get_params()
cor_params_text = []
for k, v in params_dict.items():
cor_params_text.append(f"<li>{PARAMETERS_DICT[k]}: {v}</li>")
cor_params_text = "".join(cor_params_text)
ext_params_text = ["<ul>"]
for k, v in obj.parameters.items():
ext_params_text.append(f"<li>{PARAMETERS_DICT[k]}: {v}</li>")
ext_params_text.append("</ul>")
ext_params_text = "".join(ext_params_text)
summary_text = CORRECTOR_TEMPLATE.format(
correction_method=PARAMETERS_DICT[obj._correction_method],
cor_params_text=cor_params_text,
ext_params_text=ext_params_text,
)
(out_filename).write_text(summary_text, encoding="UTF-8")
def _gen_diag_summary(obj, out_filename):
"""Generate html with parameter use in obj (e.g., diagnostics)."""
diag_dict = obj.get_params()
summary_text = DIAGNOSTIC_TEMPLATE.format(**diag_dict)
(out_filename).write_text(summary_text, encoding="UTF-8")
def _no_clusts_found(out_filename):
"""Generate html with single text."""
null_text = '<h4 style="color:#A30000">No significant clusters found</h4>'
(out_filename).write_text(null_text, encoding="UTF-8")
def _no_maps_found(out_filename):
"""Generate html with single text."""
null_text = """\
<h4 style="color:#A30000">No significant voxels were found above the threshold</h4>
"""
(out_filename).write_text(null_text, encoding="UTF-8")
def _gen_fig_summary(img_key, threshold, out_filename):
summary_text = f"""\
<h2 class="sub-report-group">Corrected meta-analytic map: {img_key}</h2>
<ul class="elem-desc">
<li>Voxel-level threshold: {threshold}</li>
</ul>
"""
(out_filename).write_text(summary_text, encoding="UTF-8")
def _gen_summary(dset, out_filename):
"""Generate preliminary checks from dataset for the report."""
mask = dset.masker.mask_img
sel_ids = dset.get_studies_by_mask(mask)
sel_dset = dset.slice(sel_ids)
n_foci = dset.coordinates.shape[0]
n_foci_sel = sel_dset.coordinates.shape[0]
n_foci_nonbrain = n_foci - n_foci_sel
n_exps = len(dset.ids)
n_exps_sel = len(sel_dset.ids)
exc_ids = list(set(dset.ids) - set(sel_dset.ids))
exc_ids_str = ", ".join(exc_ids)
summary_text = SUMMARY_TEMPLATE.format(
n_exps=n_exps,
n_exps_sel=n_exps_sel,
n_foci=n_foci,
n_foci_nonbrain=n_foci_nonbrain,
exc_ids=exc_ids_str,
)
(out_filename).write_text(summary_text, encoding="UTF-8")
def _gen_figures(results, img_key, diag_name, threshold, fig_dir):
"""Generate html and png objects for the report."""
# Plot brain images if not empty
if (results.maps[img_key] > threshold).any():
img = results.get_map(img_key)
plot_interactive_brain(img, fig_dir / "corrector_figure-interactive.html", threshold)
plot_static_brain(img, fig_dir / "corrector_figure-static.png", threshold)
else:
_no_maps_found(fig_dir / "corrector_figure-non.html")
# Plot clusters table if cluster_table is not empty
cluster_table = results.tables[f"{img_key}_tab-clust"]
if cluster_table is not None and not cluster_table.empty:
gen_table(cluster_table, fig_dir / "diagnostics_tab-clust_table.html")
# Get label maps
lbl_name = "_".join(img_key.split("_")[1:])
lbl_name = "_" + lbl_name if lbl_name else lbl_name
for tail in ["positive", "negative"]:
lbl_key = f"label{lbl_name}_tail-{tail}"
if lbl_key in results.maps:
label_map = results.get_map(lbl_key)
plot_clusters(label_map, fig_dir / f"diagnostics_tail-{tail}_figure.png")
else:
_no_clusts_found(fig_dir / "diagnostics_tab-clust_table.html")
# Plot heatmap if contribution_table is not empty
if f"{img_key}_diag-{diag_name}_tab-counts" in results.tables:
contribution_table = results.tables[f"{img_key}_diag-{diag_name}_tab-counts"]
if contribution_table is not None and not contribution_table.empty:
contribution_table = contribution_table.set_index("id")
plot_heatmap(
contribution_table,
fig_dir / f"diagnostics_diag-{diag_name}_tab-counts_figure.html",
)
class Element(object):
"""Just a basic component of a report."""
def __init__(self, name, title=None):
self.name = name
self.title = title
class Reportlet(Element):
"""Reportlet holds the content of a SubReports.
A reportlet has title, description and a list of components with either an
HTML fragment or a path to an SVG file, and possibly a caption. This is a
factory class to generate Reportlets reusing the config object from a ``Report``
object.
"""
def __init__(self, out_dir, config=None):
if not config:
raise RuntimeError("Reportlet must have a config object")
bids_dict = config["bids"]
# value and suffix are don't need the key, so removing from the bids conform name
keys_to_skip = ["value", "suffix"]
bids_name = "_".join("%s-%s" % i for i in bids_dict.items() if i[0] not in keys_to_skip)
bids_name = f"_{bids_name}" if bids_name else bids_name
bids_name = f"{bids_dict['value']}{bids_name}_{bids_dict['suffix']}"
self.name = config.get("name", bids_name)
self.title = config.get("title")
self.subtitle = config.get("subtitle")
self.description = config.get("description")
files = glob(str(out_dir / "figures" / f"{self.name}.*"))
self.components = []
for file in files:
src = Path(file)
ext = "".join(src.suffixes)
desc_text = config.get("caption")
iframe = config.get("iframe", False)
contents = None
html_anchor = src.relative_to(out_dir)
if ext == ".html":
contents = IFRAME_SNIPPET.format(html_anchor) if iframe else src.read_text()
elif ext == ".png":
contents = SVG_SNIPPET[config.get("static", True)].format(html_anchor)
if contents:
self.components.append((contents, desc_text))
def is_empty(self):
"""Check if the reportlet has no components."""
return len(self.components) == 0
class SubReport(Element):
"""SubReports are sections within a Report."""
def __init__(self, name, isnested=False, reportlets=None, title=""):
self.name = name
self.title = title
self.reportlets = reportlets or []
self.isnested = isnested
class Report:
"""The full report object.
.. versionadded:: 0.1.0
Parameters
----------
result : :obj:`~nimare.results.MetaResult`
A MetaResult produced by a coordinate- or image-based meta-analysis.
out_dir : :obj:`str`
Output directory in which to save the report.
out_filename : :obj:`str`, optional
The name of an html file to export the report to.
Default is 'report.html'.
"""
def __init__(
self,
results,
out_dir,
out_filename="report.html",
):
self.results = results
# Initialize structuring elements
self.sections = []
self.out_dir = Path(out_dir)
self.out_filename = out_filename
self.fig_dir = self.out_dir / "figures"
self.fig_dir.mkdir(parents=True, exist_ok=True)
# Generate summary text
_gen_summary(self.results.estimator.dataset, self.fig_dir / "preliminary_summary.html")
# Plot mask
plot_mask(
self.results.estimator.dataset.masker.mask_img,
self.fig_dir / "preliminary_figure-mask.png",
)
if issubclass(type(self.results.estimator), CBMAEstimator):
# Plot coordinates for CBMA estimators
plot_coordinates(
self.results.estimator.dataset.coordinates,
self.fig_dir / "preliminary_figure-static.png",
self.fig_dir / "preliminary_figure-interactive.html",
self.fig_dir / "preliminary_figure-legend.png",
)
_gen_est_summary(self.results.estimator, self.fig_dir / "estimator_summary.html")
_gen_cor_summary(self.results.corrector, self.fig_dir / "corrector_summary.html")
for diagnostic in self.results.diagnostics:
img_key = diagnostic.target_image
diag_name = diagnostic.__class__.__name__
threshold = diagnostic.voxel_thresh
_gen_fig_summary(img_key, threshold, self.fig_dir / "corrector_fig-summary.html")
_gen_diag_summary(
diagnostic, self.fig_dir / f"diagnostics_diag-{diag_name}_summary.html"
)
_gen_figures(self.results, img_key, diag_name, threshold, self.fig_dir)
# Default template from nimare
self.template_path = Path(pkgrf("nimare", "reports/report.tpl"))
self._load_config(Path(pkgrf("nimare", "reports/default.yml")))
assert self.template_path.exists()
def _load_config(self, config):
from yaml import safe_load as load
settings = load(config.read_text())
self.packagename = settings.get("package", None)
self.index(settings["sections"])
def index(self, config):
"""Traverse the reports config definition and instantiate reportlets.
This method also places figures in their final location.
"""
for subrep_cfg in config:
reportlets = [Reportlet(self.out_dir, config=cfg) for cfg in subrep_cfg["reportlets"]]
# Filter out empty reportlets
reportlets = [r for r in reportlets if not r.is_empty()]
if reportlets:
sub_report = SubReport(
subrep_cfg["name"],
isnested=False,
reportlets=reportlets,
title=subrep_cfg.get("title"),
)
self.sections.append(sub_report)
def generate_report(self):
"""Once the Report has been indexed, the final HTML can be generated."""
boilerplate = []
boiler_idx = 0
if hasattr(self.results, "description_"):
text = self.results.description_
references = self.results.bibtex_
text = textwrap.fill(text, 99)
boilerplate.append(
(
boiler_idx,
"LaTeX",
f"""<pre>{text}</pre>
<h3>Bibliography</h3>
<pre>{references}</pre>
""",
)
)
boiler_idx += 1
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(searchpath=str(self.template_path.parent)),
trim_blocks=True,
lstrip_blocks=True,
autoescape=False,
)
report_tpl = env.get_template(self.template_path.name)
report_render = report_tpl.render(sections=self.sections, boilerplate=boilerplate)
# Write out report
self.out_dir.mkdir(parents=True, exist_ok=True)
(self.out_dir / self.out_filename).write_text(report_render, encoding="UTF-8")
def run_reports(
results,
out_dir,
):
"""Run the reports.
.. versionadded:: 0.1.0
Parameters
----------
result : :obj:`~nimare.results.MetaResult`
A MetaResult produced by a coordinate- or image-based meta-analysis.
out_dir : :obj:`str`
Output directory in which to save the report.
"""
return Report(
results,
out_dir,
).generate_report()