-
Notifications
You must be signed in to change notification settings - Fork 15
/
core.py
552 lines (456 loc) · 18.4 KB
/
core.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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Reports builder for BIDS-Apps.
Generalizes report generation across BIDS-Apps
"""
from pathlib import Path
import re
from itertools import compress
from collections import defaultdict
from pkg_resources import resource_filename as pkgrf
from bids.layout import BIDSLayout, add_config_paths
import jinja2
from nipype.utils.filemanip import copyfile
# Add a new figures spec
try:
add_config_paths(figures=pkgrf("aslprep", "niworkflows/data/nipreps.json"))
except ValueError as e:
if "Configuration 'figures' already exists" != str(e):
raise
PLURAL_SUFFIX = defaultdict(str("s").format, [("echo", "es")])
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>
""",
]
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):
"""
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 layout from a ``Report``
object.
.. testsetup::
>>> cwd = os.getcwd()
>>> os.chdir(tmpdir)
>>> from pkg_resources import resource_filename
>>> from shutil import copytree
>>> from bids.layout import BIDSLayout
>>> test_data_path = resource_filename('niworkflows', 'tests/data/work')
>>> testdir = Path(tmpdir)
>>> data_dir = copytree(test_data_path, str(testdir / 'work'))
>>> out_figs = testdir / 'out' / 'fmriprep'
>>> bl = BIDSLayout(str(testdir / 'work' / 'reportlets'),
... config='figures', validate=False)
.. doctest::
>>> bl.get(subject='01', desc='reconall') # doctest: +ELLIPSIS
[<BIDSFile filename='.../fmriprep/sub-01/figures/sub-01_desc-reconall_T1w.svg'>]
>>> len(bl.get(subject='01', space='.*', regex_search=True))
2
>>> r = Reportlet(bl, out_figs, config={
... 'title': 'Some Title', 'bids': {'datatype': 'figures', 'desc': 'reconall'},
... 'description': 'Some description'})
>>> r.name
'datatype-figures_desc-reconall'
>>> r.components[0][0].startswith('<img')
True
>>> r = Reportlet(bl, out_figs, config={
... 'title': 'Some Title', 'bids': {'datatype': 'figures', 'desc': 'reconall'},
... 'description': 'Some description', 'static': False})
>>> r.name
'datatype-figures_desc-reconall'
>>> r.components[0][0].startswith('<object')
True
>>> r = Reportlet(bl, out_figs, config={
... 'title': 'Some Title', 'bids': {'datatype': 'figures', 'desc': 'summary'},
... 'description': 'Some description'})
>>> r.components[0][0].startswith('<h3')
True
>>> r.components[0][1] is None
True
>>> r = Reportlet(bl, out_figs, config={
... 'title': 'Some Title',
... 'bids': {'datatype': 'figures', 'space': '.*', 'regex_search': True},
... 'caption': 'Some description {space}'})
>>> sorted(r.components)[0][1]
'Some description MNI152NLin2009cAsym'
>>> sorted(r.components)[1][1]
'Some description MNI152NLin6Asym'
>>> r = Reportlet(bl, out_figs, config={
... 'title': 'Some Title',
... 'bids': {'datatype': 'fmap', 'space': '.*', 'regex_search': True},
... 'caption': 'Some description {space}'})
>>> r.is_empty()
True
.. testcleanup::
>>> os.chdir(cwd)
"""
def __init__(self, layout, out_dir, config=None):
if not config:
raise RuntimeError("Reportlet must have a config object")
# PY35: Sorted config dict for consistent behavior
self.name = config.get(
"name", "_".join("%s-%s" % i for i in sorted(config["bids"].items()))
)
self.title = config.get("title")
self.subtitle = config.get("subtitle")
self.description = config.get("description")
# Query the BIDS layout of reportlets
files = layout.get(**config["bids"])
self.components = []
for bidsfile in files:
src = Path(bidsfile.path)
ext = "".join(src.suffixes)
desc_text = config.get("caption")
contents = None
if ext == ".html":
contents = src.read_text().strip()
elif ext == ".svg":
entities = dict(bidsfile.entities)
if desc_text:
desc_text = desc_text.format(**entities)
try:
html_anchor = src.relative_to(out_dir)
except ValueError:
html_anchor = src.relative_to(Path(layout.root).parent)
dst = out_dir / html_anchor
dst.parent.mkdir(parents=True, exist_ok=True)
copyfile(src, dst, copy=True, use_hardlink=True)
contents = SVG_SNIPPET[config.get("static", True)].format(html_anchor)
# Our current implementations of dynamic reportlets do this themselves,
# however I'll leave the code here since this is potentially something we
# will want to transfer from every figure generator to this location.
# The following code misses setting preserveAspecRatio="xMidYMid meet"
# if not is_static:
# # Remove height and width attributes from initial <svg> tag
# svglines = out_file.read_text().splitlines()
# expr = re.compile(r' (height|width)=["\'][0-9]+(\.[0-9]*)?[a-z]*["\']')
# for l, line in enumerate(svglines[:6]):
# if line.strip().startswith('<svg'):
# newline = expr.sub('', line)
# svglines[l] = newline
# out_file.write_text('\n'.join(svglines))
# break
if contents:
self.components.append((contents, desc_text))
def is_empty(self):
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. This object maintains a BIDSLayout to index
all reportlets.
.. testsetup::
>>> cwd = os.getcwd()
>>> os.chdir(tmpdir)
>>> from pkg_resources import resource_filename
>>> from shutil import copytree
>>> from bids.layout import BIDSLayout
>>> test_data_path = resource_filename('niworkflows', 'tests/data/work')
>>> testdir = Path(tmpdir)
>>> data_dir = copytree(test_data_path, str(testdir / 'work'))
>>> out_figs = testdir / 'out' / 'fmriprep'
.. doctest::
>>> robj = Report(testdir / 'out', 'madeoutuuid', subject_id='01', packagename='fmriprep',
... reportlets_dir=testdir / 'work' / 'reportlets')
>>> robj.layout.get(subject='01', desc='reconall') # doctest: +ELLIPSIS
[<BIDSFile filename='.../figures/sub-01_desc-reconall_T1w.svg'>]
>>> robj.generate_report()
0
>>> len((testdir / 'out' / 'fmriprep' / 'sub-01.html').read_text())
36693
.. testcleanup::
>>> os.chdir(cwd)
"""
def __init__(
self,
out_dir,
run_uuid,
config=None,
out_filename="report.html",
packagename=None,
reportlets_dir=None,
subject_id=None,
):
self.root = Path(reportlets_dir or out_dir)
# Initialize structuring elements
self.sections = []
self.errors = []
self.out_dir = Path(out_dir)
self.out_filename = out_filename
self.run_uuid = run_uuid
self.packagename = packagename
self.subject_id = subject_id
if subject_id is not None:
self.subject_id = (
subject_id[4:] if subject_id.startswith("sub-") else subject_id
)
self.out_filename = f"sub-{self.subject_id}.html"
# Default template from aslprep.niworkflows
self.template_path = Path(pkgrf("aslprep", "niworkflows/reports/report.tpl"))
self._load_config(Path(config or pkgrf("aslprep", "niworkflows/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 = self.packagename or settings.get("package", None)
if self.packagename is not None:
self.root = self.root / self.packagename
self.out_dir = self.out_dir / self.packagename
if self.subject_id is not None:
self.root = self.root / "sub-{}".format(self.subject_id)
if "template_path" in settings:
self.template_path = config.parent / settings["template_path"]
self.index(settings["sections"])
def init_layout(self):
self.layout = BIDSLayout(self.root, config="figures", validate=False)
def index(self, config):
"""
Traverse the reports config definition and instantiate reportlets.
This method also places figures in their final location.
"""
# Initialize a BIDS layout
self.init_layout()
for subrep_cfg in config:
# First determine whether we need to split by some ordering
# (ie. sessions / tasks / runs), which are separated by commas.
orderings = [
s for s in subrep_cfg.get("ordering", "").strip().split(",") if s
]
entities, list_combos = self._process_orderings(orderings, self.layout)
if not list_combos: # E.g. this is an anatomical reportlet
reportlets = [
Reportlet(self.layout, self.out_dir, config=cfg)
for cfg in subrep_cfg["reportlets"]
]
else:
# Do not use dictionary for queries, as we need to preserve ordering
# of ordering columns.
reportlets = []
for c in list_combos:
# do not display entities with the value None.
c_filt = list(filter(None, c))
ent_filt = list(compress(entities, c))
# Set a common title for this particular combination c
title = "Reports for: %s." % ", ".join(
[
'%s <span class="bids-entity">%s</span>'
% (ent_filt[i], c_filt[i])
for i in range(len(c_filt))
]
)
for cfg in subrep_cfg["reportlets"]:
cfg["bids"].update({entities[i]: c[i] for i in range(len(c))})
rlet = Reportlet(self.layout, self.out_dir, config=cfg)
if not rlet.is_empty():
rlet.title = title
title = None
reportlets.append(rlet)
# Filter out empty reportlets
reportlets = [r for r in reportlets if not r.is_empty()]
if reportlets:
sub_report = SubReport(
subrep_cfg["name"],
isnested=bool(list_combos),
reportlets=reportlets,
title=subrep_cfg.get("title"),
)
self.sections.append(sub_report)
# Populate errors section
error_dir = (
self.out_dir / "sub-{}".format(self.subject_id) / "log" / self.run_uuid
)
if error_dir.is_dir():
from ..utils.misc import read_crashfile
self.errors = [read_crashfile(str(f)) for f in error_dir.glob("crash*.*")]
def generate_report(self):
"""Once the Report has been indexed, the final HTML can be generated"""
logs_path = self.out_dir / "logs"
boilerplate = []
boiler_idx = 0
if (logs_path / "CITATION.html").exists():
text = (
re.compile("<body>(.*?)</body>", re.DOTALL | re.IGNORECASE)
.findall((logs_path / "CITATION.html").read_text())[0]
.strip()
)
boilerplate.append(
(boiler_idx, "HTML", f'<div class="boiler-html">{text}</div>')
)
boiler_idx += 1
if (logs_path / "CITATION.md").exists():
text = (logs_path / "CITATION.md").read_text()
boilerplate.append((boiler_idx, "Markdown", f"<pre>{text}</pre>\n"))
boiler_idx += 1
if (logs_path / "CITATION.tex").exists():
text = (
re.compile(
r"\\begin{document}(.*?)\\end{document}", re.DOTALL | re.IGNORECASE
)
.findall((logs_path / "CITATION.tex").read_text())[0]
.strip()
)
boilerplate.append(
(
boiler_idx,
"LaTeX",
f"""<pre>{text}</pre>
<h3>Bibliography</h3>
<pre>{Path(pkgrf(self.packagename, 'data/boilerplate.bib')).read_text()}</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, errors=self.errors, 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")
return len(self.errors)
@staticmethod
def _process_orderings(orderings, layout):
"""
Generate relevant combinations of orderings with observed values.
Arguments
---------
orderings : :obj:`list` of :obj:`list` of :obj:`str`
Sections prescribing an ordering to select across sessions, acquisitions, runs, etc.
layout : :obj:`bids.layout.BIDSLayout`
The BIDS layout
Returns
-------
entities: :obj:`list` of :obj:`str`
The relevant orderings that had unique values
value_combos: :obj:`list` of :obj:`tuple`
Unique value combinations for the entities
"""
# get a set of all unique entity combinations
all_value_combos = {
tuple(bids_file.get_entities().get(k, None) for k in orderings)
for bids_file in layout.get()
}
# remove the all None member if it exists
none_member = tuple([None for k in orderings])
if none_member in all_value_combos:
all_value_combos.remove(tuple([None for k in orderings]))
# see what values exist for each entity
unique_values = [
{value[idx] for value in all_value_combos} for idx in range(len(orderings))
]
# if all values are None for an entity, we do not want to keep that entity
keep_idx = [
False if (len(val_set) == 1 and None in val_set) or not val_set else True
for val_set in unique_values
]
# the "kept" entities
entities = list(compress(orderings, keep_idx))
# the "kept" value combinations
value_combos = [
tuple(compress(value_combo, keep_idx)) for value_combo in all_value_combos
]
# sort the value combinations alphabetically from the first entity to the last entity
value_combos.sort(
key=lambda entry: tuple(
str(value) if value is not None else "0" for value in entry
)
)
return entities, value_combos
def run_reports(
out_dir,
subject_label,
run_uuid,
config=None,
reportlets_dir=None,
packagename=None,
):
"""
Run the reports.
.. testsetup::
>>> cwd = os.getcwd()
>>> os.chdir(tmpdir)
>>> from pkg_resources import resource_filename
>>> from shutil import copytree
>>> test_data_path = resource_filename('niworkflows', 'tests/data/work')
>>> testdir = Path(tmpdir)
>>> data_dir = copytree(test_data_path, str(testdir / 'work'))
>>> (testdir / 'fmriprep').mkdir(parents=True, exist_ok=True)
.. doctest::
>>> run_reports(testdir / 'out', '01', 'madeoutuuid', packagename='fmriprep',
... reportlets_dir=testdir / 'work' / 'reportlets')
0
.. testcleanup::
>>> os.chdir(cwd)
"""
return Report(
out_dir,
run_uuid,
config=config,
subject_id=subject_label,
packagename=packagename,
reportlets_dir=reportlets_dir,
).generate_report()
def generate_reports(
subject_list, output_dir, run_uuid, config=None, work_dir=None, packagename=None
):
"""Execute run_reports on a list of subjects."""
reportlets_dir = None
if work_dir is not None:
reportlets_dir = Path(work_dir) / "reportlets"
report_errors = [
run_reports(
output_dir,
subject_label,
run_uuid,
config=config,
packagename=packagename,
reportlets_dir=reportlets_dir,
)
for subject_label in subject_list
]
errno = sum(report_errors)
if errno:
import logging
logger = logging.getLogger("cli")
error_list = ", ".join(
"%s (%d)" % (subid, err)
for subid, err in zip(subject_list, report_errors)
if err
)
logger.error(
"Preprocessing did not finish successfully. Errors occurred while processing "
"data from participants: %s. Check the HTML reports for details.",
error_list,
)
return errno