-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathreport.py
4586 lines (4111 loc) · 144 KB
/
report.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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Generate self-contained HTML reports from MNE objects."""
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
from __future__ import annotations # only needed for Python ≤ 3.9
import base64
import copy
import dataclasses
import os
import os.path as op
import re
import time
import warnings
import webbrowser
from collections.abc import Sequence
from dataclasses import dataclass
from functools import partial
from io import BytesIO, StringIO
from pathlib import Path
from shutil import copyfile
import numpy as np
from .. import __version__ as MNE_VERSION
from .._fiff.meas_info import Info, read_info
from .._fiff.pick import _DATA_CH_TYPES_SPLIT
from .._freesurfer import _mri_orientation, _reorient_image
from ..cov import Covariance, read_cov
from ..defaults import _handle_default
from ..epochs import BaseEpochs, read_epochs
from ..event import read_events
from ..evoked import Evoked, read_evokeds
from ..forward import Forward, read_forward_solution
from ..html_templates import _get_html_template
from ..io import BaseRaw, read_raw
from ..io._read_raw import _get_supported as _get_extension_reader_map
from ..minimum_norm import InverseOperator, read_inverse_operator
from ..parallel import parallel_func
from ..preprocessing.ica import read_ica
from ..proj import read_proj
from ..source_estimate import SourceEstimate, read_source_estimate
from ..surface import dig_mri_distances
from ..transforms import Transform, read_trans
from ..utils import (
_check_ch_locs,
_check_fname,
_check_option,
_ensure_int,
_import_h5io_funcs,
_import_nibabel,
_path_like,
_pl,
_safe_input,
_validate_type,
_verbose_safe_false,
fill_doc,
get_subjects_dir,
logger,
sys_info,
use_log_level,
verbose,
warn,
)
from ..utils.spectrum import _split_psd_kwargs
from ..viz import (
Figure3D,
_get_plot_ch_type,
create_3d_figure,
get_3d_backend,
plot_alignment,
plot_compare_evokeds,
plot_cov,
plot_events,
plot_projs_joint,
plot_projs_topomap,
set_3d_view,
use_browser_backend,
)
from ..viz._brain.view import views_dicts
from ..viz._scraper import _mne_qt_browser_screenshot
from ..viz.misc import _get_bem_plotting_surfaces, _plot_mri_contours
from ..viz.utils import _ndarray_to_fig
_BEM_VIEWS = ("axial", "sagittal", "coronal")
# For raw files, we want to support different suffixes + extensions for all
# supported file formats
SUPPORTED_READ_RAW_EXTENSIONS = tuple(_get_extension_reader_map())
RAW_EXTENSIONS = []
for ext in SUPPORTED_READ_RAW_EXTENSIONS:
RAW_EXTENSIONS.append(f"raw{ext}")
if ext not in (".bdf", ".edf", ".set", ".vhdr"): # EEG-only formats
RAW_EXTENSIONS.append(f"meg{ext}")
RAW_EXTENSIONS.append(f"eeg{ext}")
RAW_EXTENSIONS.append(f"ieeg{ext}")
RAW_EXTENSIONS.append(f"nirs{ext}")
# Processed data will always be in (gzipped) FIFF format
VALID_EXTENSIONS = (
"sss.fif",
"sss.fif.gz",
"eve.fif",
"eve.fif.gz",
"cov.fif",
"cov.fif.gz",
"proj.fif",
"prof.fif.gz",
"trans.fif",
"trans.fif.gz",
"fwd.fif",
"fwd.fif.gz",
"epo.fif",
"epo.fif.gz",
"inv.fif",
"inv.fif.gz",
"ave.fif",
"ave.fif.gz",
"T1.mgz",
) + tuple(RAW_EXTENSIONS)
del RAW_EXTENSIONS
CONTENT_ORDER = (
"raw",
"events",
"epochs",
"ssp-projectors",
"evoked",
"covariance",
"coregistration",
"bem",
"forward-solution",
"inverse-operator",
"source-estimate",
)
html_include_dir = Path(__file__).parent / "js_and_css"
JAVASCRIPT = (html_include_dir / "report.js").read_text(encoding="utf-8")
CSS = (html_include_dir / "report.css").read_text(encoding="utf-8")
MAX_IMG_RES = 100 # in dots per inch
MAX_IMG_WIDTH = 850 # in pixels
def _get_data_ch_types(inst):
return [ch_type for ch_type in _DATA_CH_TYPES_SPLIT if ch_type in inst]
def _id_sanitize(title):
"""Sanitize title for use as DOM id."""
_validate_type(title, str, "title")
# replace any whitespace runs with underscores
title = re.sub(r"\s+", "_", title)
# replace any non-alphanumeric (plus dash and underscore) with underscores
# (this is very greedy but should be safe enough)
title = re.sub("[^a-zA-Z0-9_-]", "_", title)
return title
def _renderer(kind):
return _get_html_template("report", kind).render
###############################################################################
# HTML generation
def _html_header_element(*, lang, include, js, css, title, tags, mne_logo_img):
return _renderer("header.html.jinja")(
lang=lang,
include=include,
js=js,
css=css,
title=title,
tags=tags,
mne_logo_img=mne_logo_img,
)
def _html_footer_element(*, mne_version, date):
return _renderer("footer.html.jinja")(mne_version=mne_version, date=date)
def _html_toc_element(*, titles, dom_ids, tags):
return _renderer("toc.html.jinja")(titles=titles, dom_ids=dom_ids, tags=tags)
def _html_forward_sol_element(*, id_, repr_, sensitivity_maps, title, tags):
return _renderer("forward.html.jinja")(
id=id_,
repr=repr_,
sensitivity_maps=sensitivity_maps,
tags=tags,
title=title,
)
def _html_inverse_operator_element(*, id_, repr_, source_space, title, tags):
return _renderer("inverse.html.jinja")(
id=id_, repr=repr_, source_space=source_space, tags=tags, title=title
)
def _html_slider_element(
*, id_, images, captions, start_idx, image_format, title, tags, show, klass=""
):
captions_ = []
for caption in captions:
if caption is None:
caption = ""
captions_.append(caption)
del captions
return _renderer("slider.html.jinja")(
id=id_,
images=images,
captions=captions_,
tags=tags,
title=title,
start_idx=start_idx,
image_format=image_format,
klass=klass,
show="show" if show else "",
)
def _html_image_element(
*, id_, img, image_format, caption, show, div_klass, img_klass, title, tags
):
return _renderer("image.html.jinja")(
id=id_,
img=img,
caption=caption,
tags=tags,
title=title,
image_format=image_format,
div_klass=div_klass,
img_klass=img_klass,
show="show" if show else "",
)
def _html_code_element(*, id_, code, language, title, tags):
return _renderer("code.html.jinja")(
id=id_,
code=code,
language=language,
title=title,
tags=tags,
)
def _html_section_element(*, id_, div_klass, htmls, title, tags, show):
return _renderer("section.html.jinja")(
id=id_,
div_klass=div_klass,
htmls=htmls,
title=title,
tags=tags,
show="show" if show else "",
)
def _html_bem_element(
*,
id_,
div_klass,
html_slider_axial,
html_slider_sagittal,
html_slider_coronal,
title,
tags,
):
return _renderer("bem.html.jinja")(
id=id_,
div_klass=div_klass,
html_slider_axial=html_slider_axial,
html_slider_sagittal=html_slider_sagittal,
html_slider_coronal=html_slider_coronal,
title=title,
tags=tags,
)
def _html_element(*, id_, div_klass, html, title, tags, show):
return _renderer("html.html.jinja")(
id=id_,
div_klass=div_klass,
html=html,
title=title,
tags=tags,
show="show" if show else "",
)
@dataclass
class _ContentElement:
name: str
section: str | None
dom_id: str
tags: tuple[str]
html: str
def _check_tags(tags) -> tuple[str]:
# Must be iterable, but not a string
if isinstance(tags, str):
tags = (tags,)
elif isinstance(tags, Sequence | np.ndarray):
tags = tuple(tags)
else:
raise TypeError(
f"tags must be a string (without spaces or special characters) or "
f"an array-like object of such strings, but got {type(tags)} "
f"instead: {tags}"
)
# Check for invalid dtypes
bad_tags = [tag for tag in tags if not isinstance(tag, str)]
if bad_tags:
raise TypeError(
f"All tags must be strings without spaces or special characters, "
f"but got the following instead: "
f"{', '.join([str(tag) for tag in bad_tags])}"
)
# Check for invalid characters
invalid_chars = (" ", '"', "\n") # we'll probably find more :-)
bad_tags = []
for tag in tags:
for invalid_char in invalid_chars:
if invalid_char in tag:
bad_tags.append(tag)
break
if bad_tags:
raise ValueError(
f"The following tags contained invalid characters: "
f"{', '.join(repr(tag) for tag in bad_tags)}"
)
return tags
###############################################################################
# PLOTTING FUNCTIONS
def _constrain_fig_resolution(fig, *, max_width, max_res):
"""Limit the resolution (DPI) of a figure.
Parameters
----------
fig : matplotlib.figure.Figure
The figure whose DPI to adjust.
max_width : int | None
The max. allowed width, in pixels.
max_res : float | None
The max. allowed resolution, in DPI.
Returns
-------
Nothing, alters the figure's properties in-place.
"""
dpi = orig_dpi = fig.get_dpi()
# Limited by figure width?
if max_width is not None:
dpi = min(dpi, max_width / fig.get_size_inches()[0])
# Limited by resolution?
if max_res is not None:
dpi = min(dpi, max_res)
if orig_dpi != dpi:
fig.set_dpi(dpi)
def _fig_to_img(
fig,
*,
image_format="png",
own_figure=True,
max_width=MAX_IMG_WIDTH,
max_res=MAX_IMG_RES,
**mpl_kwargs,
):
"""Plot figure and create a binary image."""
# fig can be ndarray, mpl Figure, PyVista Figure
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
if isinstance(fig, np.ndarray):
# In this case, we are creating the fig, so we might as well
# auto-close in all cases
fig = _ndarray_to_fig(fig)
if own_figure:
_constrain_fig_resolution(fig, max_width=max_width, max_res=max_res)
own_figure = True # close the figure we just created
elif isinstance(fig, Figure):
if own_figure:
_constrain_fig_resolution(fig, max_width=max_width, max_res=max_res)
else:
# Don't attempt a mne_qt_browser import here (it might pull in Qt
# libraries we don't want), so use a probably good enough class name
# check instead
if fig.__class__.__name__ in ("MNEQtBrowser", "PyQtGraphBrowser"):
img = _mne_qt_browser_screenshot(fig, return_type="ndarray")
elif isinstance(fig, Figure3D):
from ..viz.backends.renderer import MNE_3D_BACKEND_TESTING, backend
backend._check_3d_figure(figure=fig)
if not MNE_3D_BACKEND_TESTING:
img = backend._take_3d_screenshot(figure=fig)
else: # Testing mode
img = np.zeros((2, 2, 3))
if own_figure:
backend._close_3d_figure(figure=fig)
else:
raise TypeError(
"figure must be an instance of np.ndarray, matplotlib Figure, "
"mne_qt_browser.figure.MNEQtBrowser, or mne.viz.Figure3D, got "
f"{type(fig)}"
)
fig = _ndarray_to_fig(img)
if own_figure:
_constrain_fig_resolution(fig, max_width=max_width, max_res=max_res)
own_figure = True # close the fig we just created
output = BytesIO()
dpi = fig.get_dpi()
logger.debug(
f"Saving figure with dimension {fig.get_size_inches()} inches with {dpi} dpi"
)
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
pil_kwargs = dict()
if image_format == "webp":
pil_kwargs.update(lossless=True, method=6)
elif image_format == "png":
pil_kwargs.update(optimize=True, compress_level=9)
if pil_kwargs:
# matplotlib modifies the passed dict, which is a bug
mpl_kwargs["pil_kwargs"] = pil_kwargs.copy()
mpl_format = image_format
if image_format == "ndarray":
mpl_format = "png"
fig.savefig(output, format=mpl_format, dpi=dpi, **mpl_kwargs)
if own_figure:
plt.close(fig)
# Remove alpha
if image_format not in ("svg", "ndarray"):
from PIL import Image
output.seek(0)
orig = Image.open(output)
if orig.mode == "RGBA":
background = Image.new("RGBA", orig.size, (255, 255, 255))
new = Image.alpha_composite(background, orig).convert("RGB")
output = BytesIO()
new.save(output, format=image_format, dpi=(dpi, dpi), **pil_kwargs)
if image_format == "ndarray":
output.seek(0)
output = plt.imread(output, format="png")
else:
output = output.getvalue()
if image_format == "svg":
output = output.decode("utf-8")
else:
output = base64.b64encode(output).decode("ascii")
return output
def _get_bem_contour_figs_as_arrays(
*, sl, n_jobs, mri_fname, surfaces, orientation, src, show, show_orientation, width
):
"""Render BEM surface contours on MRI slices.
Returns
-------
list of array
A list of NumPy arrays that represent the generated Matplotlib figures.
"""
parallel, p_fun, n_jobs = parallel_func(
_plot_mri_contours, n_jobs, max_jobs=len(sl), prefer="threads"
)
outs = parallel(
p_fun(
slices=s,
mri_fname=mri_fname,
surfaces=surfaces,
orientation=orientation,
src=src,
show=show,
show_orientation=show_orientation,
width=width,
slices_as_subplots=False,
)
for s in np.array_split(sl, n_jobs)
)
out = list()
for o in outs:
out.extend(o)
return out
def _iterate_trans_views(function, alpha, **kwargs):
"""Auxiliary function to iterate over views in trans fig."""
from ..viz.backends.renderer import MNE_3D_BACKEND_TESTING
# TODO: Eventually maybe we should expose the size option?
size = (80, 80) if MNE_3D_BACKEND_TESTING else (800, 800)
fig = create_3d_figure(size, bgcolor=(0.5, 0.5, 0.5))
from ..viz.backends.renderer import backend
try:
try:
return _itv(function, fig, surfaces={"head-dense": alpha}, **kwargs)
except OSError:
return _itv(function, fig, surfaces={"head": alpha}, **kwargs)
finally:
backend._close_3d_figure(fig)
def _itv(function, fig, *, max_width=MAX_IMG_WIDTH, max_res=MAX_IMG_RES, **kwargs):
from ..viz.backends.renderer import MNE_3D_BACKEND_TESTING, backend
function(fig=fig, **kwargs)
views = ("frontal", "lateral", "medial", "axial", "rostral", "coronal")
images = []
for view in views:
if not MNE_3D_BACKEND_TESTING:
set_3d_view(fig, **views_dicts["both"][view])
backend._check_3d_figure(fig)
im = backend._take_3d_screenshot(figure=fig)
else: # Testing mode
im = np.zeros((2, 2, 3))
images.append(im)
images = np.concatenate(
[np.concatenate(images[:3], axis=1), np.concatenate(images[3:], axis=1)], axis=0
)
try:
dists = dig_mri_distances(
info=kwargs["info"],
trans=kwargs["trans"],
subject=kwargs["subject"],
subjects_dir=kwargs["subjects_dir"],
on_defects="ignore",
)
caption = (
f"Average distance from {len(dists)} digitized points to "
f"head: {1e3 * np.mean(dists):.2f} mm"
)
except BaseException as e:
caption = "Distances could not be calculated from digitized points"
warn(f"{caption}: {e}")
img = _fig_to_img(images, image_format="png", max_width=max_width, max_res=max_res)
return img, caption
def _plot_ica_properties_as_arrays(
*, ica, inst, picks, n_jobs, max_width=MAX_IMG_WIDTH, max_res=MAX_IMG_RES
):
"""Parallelize ICA component properties plotting, and return arrays.
Returns
-------
outs : list of array
The properties plots as NumPy arrays.
"""
def _plot_one_ica_property(*, ica, inst, pick):
figs = ica.plot_properties(inst=inst, picks=pick, show=False)
assert len(figs) == 1
return _fig_to_img(
figs[0],
max_width=max_width,
max_res=max_res,
image_format="ndarray",
pad_inches=0,
)
parallel, p_fun, n_jobs = parallel_func(
func=_plot_one_ica_property, n_jobs=n_jobs, max_jobs=len(picks)
)
outs = parallel(p_fun(ica=ica, inst=inst, pick=pick) for pick in picks)
return outs
###############################################################################
# TOC FUNCTIONS
def _endswith(fname: str | Path, suffixes):
"""Aux function to test if file name includes the specified suffixes."""
if isinstance(suffixes, str):
suffixes = [suffixes]
if isinstance(fname, Path):
fname = fname.name
for suffix in suffixes:
for ext in SUPPORTED_READ_RAW_EXTENSIONS:
if fname.endswith(
(
f"-{suffix}{ext}",
f"-{suffix}{ext}",
f"_{suffix}{ext}",
f"_{suffix}{ext}",
)
):
return True
return False
_backward_compat_map = dict(
img_max_width=MAX_IMG_WIDTH,
img_max_res=MAX_IMG_RES,
collapse=(),
)
def open_report(fname, **params):
"""Read a saved report or, if it doesn't exist yet, create a new one.
The returned report can be used as a context manager, in which case any
changes to the report are saved when exiting the context block.
Parameters
----------
fname : path-like
The file containing the report, stored in the HDF5 format. If the file
does not exist yet, a new report is created that will be saved to the
specified file.
**params : kwargs
When creating a new report, any named parameters other than ``fname``
are passed to the ``__init__`` function of the `Report` object. When
reading an existing report, the parameters are checked with the
loaded report and an exception is raised when they don't match.
Returns
-------
report : instance of Report
The report.
"""
fname = str(_check_fname(fname=fname, overwrite="read", must_exist=False))
if op.exists(fname):
# Check **params with the loaded report
read_hdf5, _ = _import_h5io_funcs()
state = read_hdf5(fname, title="mnepython")
for param in params:
if param not in state:
if param in _backward_compat_map:
state[param] = _backward_compat_map[param]
else:
raise ValueError(f"The loaded report has no attribute {param}")
if params[param] != state[param]:
raise ValueError(
f"Attribute '{param}' of loaded report ({params[param]}) does not "
f"match the given parameter ({state[param]})."
)
report = Report()
report.__setstate__(state)
else:
report = Report(**params)
# Keep track of the filename in case the Report object is used as a context
# manager.
report.fname = fname
return report
###############################################################################
# HTML scan renderer
mne_logo_path = Path(__file__).parents[1] / "icons" / "mne_icon-cropped.png"
mne_logo = base64.b64encode(mne_logo_path.read_bytes()).decode("ascii")
_ALLOWED_IMAGE_FORMATS = ("png", "svg", "webp")
def _check_image_format(rep, image_format):
"""Ensure fmt is valid."""
if rep is None or image_format is not None:
allowed = list(_ALLOWED_IMAGE_FORMATS) + ["auto"]
extra = ""
_check_option("image_format", image_format, allowed_values=allowed, extra=extra)
else:
image_format = rep.image_format
if image_format == "auto":
image_format = "webp"
return image_format
@fill_doc
class Report:
r"""Object for rendering HTML.
Parameters
----------
info_fname : None | str
Name of the file containing the info dictionary.
%(subjects_dir)s
subject : str | None
Subject name.
title : str
Title of the report.
cov_fname : None | str
Name of the file containing the noise covariance.
%(baseline_report)s
Defaults to ``None``, i.e. no baseline correction.
image_format : 'png' | 'svg' | 'webp' | 'auto'
Default image format to use (default is ``'auto'``, which will use
``'webp'`` if available and ``'png'`` otherwise).
``'svg'`` uses vector graphics, so fidelity is higher but can increase
file size and browser image rendering time as well.
.. versionadded:: 0.15
.. versionchanged:: 1.3
Added support for ``'webp'`` format, removed support for GIF, and
set the default to ``'auto'``.
raw_psd : bool | dict
If True, include PSD plots for raw files. Can be False (default) to
omit, True to plot, or a dict to pass as ``kwargs`` to
:meth:`mne.time_frequency.Spectrum.plot`.
.. versionadded:: 0.17
.. versionchanged:: 1.4
kwargs are sent to ``spectrum.plot`` instead of ``raw.plot_psd``.
projs : bool
Whether to include topographic plots of SSP projectors, if present in
the data. Defaults to ``False``.
.. versionadded:: 0.21
img_max_width : int | None
Maximum image width in pixels.
.. versionadded:: 1.9
img_max_res : float | None
Maximum image resolution in dots per inch.
.. versionadded:: 1.9
collapse : tuple of str | str
Tuple of elements to collapse by default. Defaults to an empty tuple.
For now the only option it can contain is "section".
.. versionadded:: 1.9
%(verbose)s
Attributes
----------
info_fname : None | str
Name of the file containing the info dictionary.
%(subjects_dir)s
subject : str | None
Subject name.
title : str
Title of the report.
cov_fname : None | str
Name of the file containing the noise covariance.
%(baseline_report)s
Defaults to ``None``, i.e. no baseline correction.
image_format : str
Default image format to use.
.. versionadded:: 0.15
raw_psd : bool | dict
If True, include PSD plots for raw files. Can be False (default) to
omit, True to plot, or a dict to pass as ``kwargs`` to
:meth:`mne.time_frequency.Spectrum.plot`.
.. versionadded:: 0.17
.. versionchanged:: 1.4
kwargs are sent to ``spectrum.plot`` instead of ``raw.plot_psd``.
projs : bool
Whether to include topographic plots of SSP projectors, if present in
the data. Defaults to ``False``.
.. versionadded:: 0.21
%(verbose)s
html : list of str
Contains items of html-page.
include : list of str
Dictionary containing elements included in head.
fnames : list of str
List of file names rendered.
sections : list of str
List of sections.
lang : str
language setting for the HTML file.
img_max_width : int | None
Maximum image width in pixels.
.. versionadded:: 1.9
img_max_res : float | None
Maximum image resolution in dots per inch.
.. versionadded:: 1.9
collapse : tuple of str
Tuple of elements to collapse by default. See above.
.. versionadded:: 1.9
Notes
-----
See :ref:`tut-report` for an introduction to using ``mne.Report``.
.. versionadded:: 0.8.0
"""
@verbose
def __init__(
self,
info_fname=None,
subjects_dir=None,
subject=None,
title=None,
cov_fname=None,
baseline=None,
image_format="auto",
raw_psd=False,
projs=False,
*,
img_max_width=MAX_IMG_WIDTH,
img_max_res=MAX_IMG_RES,
collapse=(),
verbose=None,
):
self.info_fname = str(info_fname) if info_fname is not None else None
self.cov_fname = str(cov_fname) if cov_fname is not None else None
self.baseline = baseline
if subjects_dir is not None:
subjects_dir = get_subjects_dir(subjects_dir)
if subjects_dir is not None:
subjects_dir = str(subjects_dir)
self.subjects_dir = subjects_dir
self.subject = subject
self.title = title
self.image_format = _check_image_format(None, image_format)
self.projs = projs
# dom_id is mostly for backward compat and testing nowadays
self._dom_id = 0
self._dup_limit = 10000 # should be enough duplicates
self._content = []
self.include = []
self.lang = "en-us" # language setting for the HTML file
self.img_max_width = img_max_width
self.img_max_res = img_max_res
self.collapse = collapse
if not isinstance(raw_psd, bool) and not isinstance(raw_psd, dict):
raise TypeError(f"raw_psd must be bool or dict, got {type(raw_psd)}")
self.raw_psd = raw_psd
self._init_render() # Initialize the renderer
self.fname = None # The name of the saved report
self.data_path = None
@property
def img_max_width(self):
return self._img_max_width
@img_max_width.setter
def img_max_width(self, value):
_validate_type(value, ("int-like", None), "img_max_width")
if value is not None:
value = int(value)
if value < 1:
raise ValueError(f"img_max_width must be at least 1, got {value}")
self._img_max_width = value
@property
def img_max_res(self):
return self._img_max_res
@img_max_res.setter
def img_max_res(self, value):
_validate_type(value, ("numeric", None), "img_max_res")
if value is not None:
value = float(value)
if value < 1:
raise ValueError(f"img_max_res must be at least 1, got {value}")
self._img_max_res = value
@property
def collapse(self):
return self._collapse
@collapse.setter
def collapse(self, value):
_validate_type(value, (list, tuple, str), "collapse")
if isinstance(value, str):
value = [value]
for vi, v in enumerate(value):
_validate_type(v, str, f"collapse[{vi}]")
_check_option(f"collapse[{vi}]", v, ("section",))
self._collapse = tuple(value)
def __repr__(self):
"""Print useful info about report."""
htmls, _, titles, _ = self._content_as_html()
items = self._content
s = "<Report"
s += f" | {len(titles)} title{_pl(titles)}"
s += f" | {len(items)} item{_pl(items)}"
if self.title is not None:
s += f" | {self.title}"
if len(titles) > 0:
titles = [f" {t}" for t in titles] # indent
tr = max(len(s), 50) # trim to larger of opening str and 50
titles = [f"{t[: tr - 2]} …" if len(t) > tr else t for t in titles]
# then trim to the max length of all of these
tr = max(len(title) for title in titles)
tr = max(tr, len(s))
b_to_mb = 1.0 / (1024.0**2)
content_element_mb = [len(html) * b_to_mb for html in htmls]
total_mb = f"{sum(content_element_mb):0.1f}"
content_element_mb = [
f"{sz:0.1f}".rjust(len(total_mb)) for sz in content_element_mb
]
s = f"{s.ljust(tr + 1)} | {total_mb} MB"
s += "\n" + "\n".join(
f"{title[:tr].ljust(tr + 1)} | {sz} MB"
for title, sz in zip(titles, content_element_mb)
)
s += "\n"
s += ">"
return s
def __len__(self):
"""Return the number of files processed by the report.
Returns
-------
n_files : int
The number of files processed.
"""
return len(self._content)
@staticmethod
def _get_state_params():
# Which attributes to store in and read from HDF5 files
return (
"baseline",
"cov_fname",
"include",
"_content",
"image_format",
"info_fname",
"_dom_id",
# dup_limit omitted because we never change it from default
"raw_psd",
"projs",
"subjects_dir",
"subject",
"title",
"data_path",
"lang",
"fname",
"img_max_width",
"img_max_res",
"collapse",
)
def _get_dom_id(self, *, section, title, extra_exclude=None):
"""Get unique ID for content to append to the DOM."""
_validate_type(title, str, "title")
_validate_type(section, (str, None), "section")
if section is not None:
title = f"{section}-{title}"
dom_id = _id_sanitize(title)
del title, section
# find a new unique ID
dom_ids = set(c.dom_id for c in self._content)
if extra_exclude:
assert isinstance(extra_exclude, set), type(extra_exclude)
dom_ids.update(extra_exclude)
if dom_id not in dom_ids:
return dom_id
for ii in range(1, self._dup_limit): # should be enough duplicates...
dom_id_inc = f"{dom_id}-{ii}"
if dom_id_inc not in dom_ids:
return dom_id_inc
# But let's not fail if the limit is low
self._dom_id += 1
return f"global-{self._dom_id}"
def _validate_topomap_kwargs(self, topomap_kwargs):
_validate_type(topomap_kwargs, (dict, None), "topomap_kwargs")
topomap_kwargs = dict() if topomap_kwargs is None else topomap_kwargs
return topomap_kwargs
def _validate_input(self, items, captions, tag, comments=None):
"""Validate input."""
if not isinstance(items, list | tuple):
items = [items]