def test_render_add_sections(renderer, tmp_path): """Test adding figures/images to section.""" tempdir = str(tmp_path) report = Report(subjects_dir=subjects_dir) # Check add_figure functionality fig = plt.plot([1, 2], [1, 2])[0].figure report.add_figure(fig=fig, title='evoked response', image_format='svg') assert 'caption' not in report._content[-1].html report.add_figure(fig=fig, title='evoked with caption', caption='descr') assert 'caption' in report._content[-1].html # Check add_image with png img_fname = op.join(tempdir, 'testimage.png') fig.savefig(img_fname) report.add_image(image=img_fname, title='evoked response') with pytest.raises(FileNotFoundError, match='No such file or directory'): report.add_image(image='foobar.xxx', title='H') evoked = read_evokeds(evoked_fname, condition='Left Auditory', baseline=(-0.2, 0.0)) fig = plot_alignment(evoked.info, trans_fname, subject='sample', subjects_dir=subjects_dir) report.add_figure(fig=fig, title='random image') assert (repr(report)) fname = op.join(str(tmp_path), 'test.html') report.save(fname, open_browser=False) assert len(report) == 4
def test_render_report_extra(renderer_pyvistaqt, tmp_path, invisible_fig): """Test SVG and projector rendering separately.""" # ... otherwise things are very slow tempdir = str(tmp_path) raw_fname_new = op.join(tempdir, 'temp_raw.fif') shutil.copyfile(raw_fname, raw_fname_new) report = Report(info_fname=raw_fname_new, subjects_dir=subjects_dir, projs=True, image_format='svg') with pytest.warns(RuntimeWarning, match='Cannot render MRI'): report.parse_folder(data_path=tempdir, on_error='raise', n_time_points_evokeds=2, raw_butterfly=False, stc_plot_kwargs=stc_plot_kwargs, topomap_kwargs=topomap_kwargs) assert repr(report) report.data_path = tempdir fname = op.join(tempdir, 'report.html') report.save(fname=fname, open_browser=False) assert op.isfile(fname) html = Path(fname).read_text(encoding='utf-8') # Projectors in Raw.info assert 'SSP Projectors' in html
def test_render_non_fiff(tmp_path): """Test rendering non-FIFF files for mne report.""" tempdir = str(tmp_path) fnames_in = [bdf_fname, edf_fname] fnames_out = [] for fname in fnames_in: basename = op.basename(fname) basename, ext = op.splitext(basename) fname_out = f'{basename}_raw{ext}' outpath = op.join(tempdir, fname_out) shutil.copyfile(fname, outpath) fnames_out.append(fname_out) report = Report() report.parse_folder(data_path=tempdir, render_bem=False, on_error='raise', raw_butterfly=False) # Check correct paths and filenames content_names = [element.name for element in report._content] for fname in fnames_out: assert (op.basename(fname) in [op.basename(x) for x in content_names]) assert len(report._content) == len(fnames_out) report.data_path = tempdir fname = op.join(tempdir, 'report.html') report.save(fname=fname, open_browser=False) html = Path(fname).read_text(encoding='utf-8') assert 'test_raw.bdf' in html assert 'test_raw.edf' in html
def test_render_mri_without_bem(tmpdir): """Test rendering MRI without BEM for mne report.""" tempdir = str(tmpdir) os.mkdir(op.join(tempdir, 'sample')) os.mkdir(op.join(tempdir, 'sample', 'mri')) shutil.copyfile(mri_fname, op.join(tempdir, 'sample', 'mri', 'T1.mgz')) report = Report(info_fname=raw_fname, subject='sample', subjects_dir=tempdir) with pytest.raises(RuntimeError, match='No matching files found'): report.parse_folder(tempdir, render_bem=False) with pytest.warns(RuntimeWarning, match='No BEM surfaces found'): report.parse_folder(tempdir, render_bem=True, mri_decim=20) assert 'BEM surfaces' in [element.name for element in report._content] report.save(op.join(tempdir, 'report.html'), open_browser=False)
def test_survive_pickle(tmp_path): """Testing functionality of Report-Object after pickling.""" tempdir = str(tmp_path) raw_fname_new = op.join(tempdir, 'temp_raw.fif') shutil.copyfile(raw_fname, raw_fname_new) # Pickle report object to simulate multiprocessing with joblib report = Report(info_fname=raw_fname_new) pickled_report = pickle.dumps(report) report = pickle.loads(pickled_report) # Just test if no errors occur report.parse_folder(tempdir, render_bem=False) save_name = op.join(tempdir, 'report.html') report.save(fname=save_name, open_browser=False)
def test_add_custom_js(tmp_path): """Test adding custom JavaScript to the report.""" tempdir = str(tmp_path) fname = op.join(tempdir, 'report.html') fig = plt.figure() # Empty figure report = Report() report.add_figure(fig=fig, title='Test section') custom_js = ('function hello() {\n' ' alert("Hello, report!");\n' '}') report.add_custom_js(js=custom_js) assert custom_js in report.include report.save(fname, open_browser=False) html = Path(fname).read_text(encoding='utf-8') assert custom_js in html
def test_add_custom_css(tmp_path): """Test adding custom CSS rules to the report.""" tempdir = str(tmp_path) fname = op.join(tempdir, 'report.html') fig = plt.figure() # Empty figure report = Report() report.add_figure(fig=fig, title='Test section') custom_css = '.report_custom { color: red; }' report.add_custom_css(css=custom_css) assert custom_css in report.include report.save(fname, open_browser=False) html = Path(fname).read_text(encoding='utf-8') assert custom_css in html
def test_render_mri(renderer, tmpdir): """Test rendering MRI for mne report.""" tempdir = str(tmpdir) trans_fname_new = op.join(tempdir, 'temp-trans.fif') for a, b in [[trans_fname, trans_fname_new]]: shutil.copyfile(a, b) report = Report(info_fname=raw_fname, subject='sample', subjects_dir=subjects_dir) report.parse_folder(data_path=tempdir, mri_decim=30, pattern='*') fname = op.join(tempdir, 'report.html') report.save(fname, open_browser=False) html = Path(fname).read_text(encoding='utf-8') assert 'data-mne-tags=" bem "' in html assert repr(report) report.add_bem(subject='sample', title='extra', tags=('foo',), subjects_dir=subjects_dir, decim=30) report.save(fname, open_browser=False, overwrite=True) html = Path(fname).read_text(encoding='utf-8') assert 'data-mne-tags=" bem "' in html assert 'data-mne-tags=" foo "' in html
def test_multiple_figs(tmpdir): """Test adding a slider with a series of figures to a Report.""" tempdir = str(tmpdir) report = Report(info_fname=raw_fname, subject='sample', subjects_dir=subjects_dir) figs = _get_example_figures() report.add_figure(fig=figs, title='my title') assert report._content[0].name == 'my title' report.save(op.join(tempdir, 'report.html'), open_browser=False) with pytest.raises(ValueError): report.add_figure(fig=figs, title='title', caption=['wug']) with pytest.raises(ValueError, match='Number of captions.*must be equal to.*figures'): report.add_figure(fig=figs, title='title', caption='wug') # Smoke test that SVG with unicode can be added report = Report() fig, ax = plt.subplots() ax.set_xlabel('µ') report.add_figure(fig=[fig] * 2, title='title', image_format='svg')
def test_render_report(renderer_pyvistaqt, tmp_path, invisible_fig): """Test rendering *.fif files for mne report.""" tempdir = str(tmp_path) raw_fname_new = op.join(tempdir, 'temp_raw.fif') raw_fname_new_bids = op.join(tempdir, 'temp_meg.fif') ms_fname_new = op.join(tempdir, 'temp_ms_raw.fif') event_fname_new = op.join(tempdir, 'temp_raw-eve.fif') cov_fname_new = op.join(tempdir, 'temp_raw-cov.fif') proj_fname_new = op.join(tempdir, 'temp_ecg-proj.fif') fwd_fname_new = op.join(tempdir, 'temp_raw-fwd.fif') inv_fname_new = op.join(tempdir, 'temp_raw-inv.fif') nirs_fname_new = op.join(tempdir, 'temp_raw-nirs.snirf') for a, b in [[raw_fname, raw_fname_new], [raw_fname, raw_fname_new_bids], [ms_fname, ms_fname_new], [events_fname, event_fname_new], [cov_fname, cov_fname_new], [ecg_proj_fname, proj_fname_new], [fwd_fname, fwd_fname_new], [inv_fname, inv_fname_new], [nirs_fname, nirs_fname_new]]: shutil.copyfile(a, b) # create and add -epo.fif and -ave.fif files epochs_fname = op.join(tempdir, 'temp-epo.fif') evoked_fname = op.join(tempdir, 'temp-ave.fif') # Speed it up by picking channels raw = read_raw_fif(raw_fname_new) raw.pick_channels(['MEG 0111', 'MEG 0121', 'EEG 001', 'EEG 002']) raw.del_proj() raw.set_eeg_reference(projection=True).load_data() epochs = Epochs(raw, read_events(events_fname), 1, -0.2, 0.2) epochs.save(epochs_fname, overwrite=True) # This can take forever, so let's make it fast # Also, make sure crop range is wide enough to avoid rendering bug evoked = epochs.average() with pytest.warns(RuntimeWarning, match='tmax is not in Evoked'): evoked.crop(0.1, 0.2) evoked.save(evoked_fname) report = Report(info_fname=raw_fname_new, subjects_dir=subjects_dir, projs=False, image_format='png') with pytest.warns(RuntimeWarning, match='Cannot render MRI'): report.parse_folder(data_path=tempdir, on_error='raise', n_time_points_evokeds=2, raw_butterfly=False, stc_plot_kwargs=stc_plot_kwargs, topomap_kwargs=topomap_kwargs) assert repr(report) # Check correct paths and filenames fnames = glob.glob(op.join(tempdir, '*.fif')) fnames.extend(glob.glob(op.join(tempdir, '*.snirf'))) titles = [op.basename(x) for x in fnames if not x.endswith('-ave.fif')] titles.append(f'{op.basename(evoked_fname)}: {evoked.comment}') content_names = [element.name for element in report._content] for title in titles: assert title in content_names assert (''.join(report.html).find(title) != -1) assert len(report._content) == len(fnames) # Check saving functionality report.data_path = tempdir fname = op.join(tempdir, 'report.html') report.save(fname=fname, open_browser=False) assert (op.isfile(fname)) html = Path(fname).read_text(encoding='utf-8') # Evoked in `evoked_fname` assert f'{op.basename(evoked_fname)}: {evoked.comment}' in html assert 'Topographies' in html assert 'Global field power' in html assert len(report._content) == len(fnames) # Check saving same report to new filename report.save(fname=op.join(tempdir, 'report2.html'), open_browser=False) assert (op.isfile(op.join(tempdir, 'report2.html'))) # Check overwriting file report.save(fname=op.join(tempdir, 'report.html'), open_browser=False, overwrite=True) assert (op.isfile(op.join(tempdir, 'report.html'))) # Check pattern matching with multiple patterns pattern = ['*proj.fif', '*eve.fif'] with pytest.warns(RuntimeWarning, match='Cannot render MRI'): report.parse_folder(data_path=tempdir, pattern=pattern, raw_butterfly=False) assert (repr(report)) fnames = glob.glob(op.join(tempdir, '*.raw')) + \ glob.glob(op.join(tempdir, '*.raw')) content_names = [element.name for element in report._content] for fname in fnames: assert (op.basename(fname) in [op.basename(x) for x in content_names]) assert (''.join(report.html).find(op.basename(fname)) != -1) with pytest.raises(ValueError, match='Invalid value'): Report(image_format='foo') with pytest.raises(ValueError, match='Invalid value'): Report(image_format=None) # ndarray support smoke test report.add_figure(fig=np.zeros((2, 3, 3)), title='title') with pytest.raises(TypeError, match='It seems you passed a path'): report.add_figure(fig='foo', title='title')