Skip to content

MNE-report integration with 3D viz is broken #8717

Closed

Description

@jasmainak

When I do the following:

import os
import os.path as op

import numpy as np
import matplotlib.pyplot as plt

from mayavi import mlab

import mne
from mne.viz import use_3d_backend
from mne.datasets import sample

data_path = sample.data_path()
sample_dir = os.path.join(data_path, 'MEG', 'sample')
subjects_dir = os.path.join(data_path, 'subjects')

fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')

stc = mne.read_source_estimate(fname_stc, subject='sample')

initial_time = 0.1

with use_3d_backend('mayavi'):
    brain = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                     clim=dict(kind='value', lims=[3, 6, 9]))

report = mne.Report()
report.add_figs_to_section(mlab.gcf(), 'caption')

I get:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/Documents/github_repos/mne-python/tutorials/source-modeling/plot_visualize_stc.py in <module>
     29 report = mne.Report()
     30 fig = mlab.gcf()
---> 31 report.add_figs_to_section(mlab.gcf(), 'caption')
     32 
     33 sfdfdfd

~/Documents/github_repos/mne-python/mne/report.py in add_figs_to_section(self, figs, captions, section, scale, image_format, comments, replace)
   1110             img_klass = self._sectionvars[section]
   1111 
-> 1112             img = _fig_to_img(fig, image_format, scale)
   1113             html = image_template.substitute(img=img, id=global_id,
   1114                                              div_klass=div_klass,

~/Documents/github_repos/mne-python/mne/report.py in _fig_to_img(fig, image_format, scale, **kwargs)
     72     elif not isinstance(fig, Figure):
     73         from .viz.backends.renderer import backend, MNE_3D_BACKEND_TESTING
---> 74         backend._check_3d_figure(figure=fig)
     75         if not MNE_3D_BACKEND_TESTING:
     76             img = backend._take_3d_screenshot(figure=fig)

~/Documents/github_repos/mne-python/mne/viz/backends/_pyvista.py in _check_3d_figure(figure)
    845 def _check_3d_figure(figure):
    846     if not isinstance(figure, _Figure):
--> 847         raise TypeError('figure must be an instance of _Figure.')
    848 
    849 

TypeError: figure must be an instance of _Figure.

The error is very cryptic. If you do set_3d_backend at the beginning of the script, it works.

Also, having the figure handle easily accessible via brain.fig for both backends and then being able to pass that into the report will be a gamechanger.

Activity

  1. jasmainak commented on Jan 8, 2021

    @jasmainak
    MemberAuthor

    Another request, while we're on the topic of MNE-report. If we could have the report.plot_alignment publicly exposed that would be great. So that I don't have to run report.parse_folder. Not sure anyone really uses that method anymore.

  2. GuillaumeFavelier commented on Jan 8, 2021

    @GuillaumeFavelier
    Contributor

    Since #8220, the default 3d backend is pyvista.

    So looking at your script, this behaviour is expected. At first, the default backend (pyvista) is set then during the use_3d_backend context, mayavi is used. Finally, out of this context, the previous 3d backend is restored which is pyvista.

    This is shown in the first part of the log:

    Using pyvista 3d backend.
    
    Using mayavi 3d backend.
    
    Using pyvista 3d backend.
    

    Then:

    Embedding : jquery.js
    Embedding : jquery-ui.min.js
    Embedding : bootstrap.min.js
    Embedding : jquery-ui.min.css
    Embedding : bootstrap.min.css
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    /tmp/bug.py in <module>
         26 
         27 report = mne.Report()
    ---> 28 report.add_figs_to_section(mlab.gcf(), 'caption')
    
    ~/source/mne-python/mne/report.py in add_figs_to_section(self, figs, captions, section, scale, image_format, comments, replace)
       1110             img_klass = self._sectionvars[section]
       1111 
    -> 1112             img = _fig_to_img(fig, image_format, scale)
       1113             html = image_template.substitute(img=img, id=global_id,
       1114                                              div_klass=div_klass,
    
    ~/source/mne-python/mne/report.py in _fig_to_img(fig, image_format, scale, **kwargs)
         72     elif not isinstance(fig, Figure):
         73         from .viz.backends.renderer import backend, MNE_3D_BACKEND_TESTING
    ---> 74         backend._check_3d_figure(figure=fig)
         75         if not MNE_3D_BACKEND_TESTING:
         76             img = backend._take_3d_screenshot(figure=fig)
    
    ~/source/mne-python/mne/viz/backends/_pyvista.py in _check_3d_figure(figure)
        845 def _check_3d_figure(figure):
        846     if not isinstance(figure, _Figure):
    --> 847         raise TypeError('figure must be an instance of _Figure.')
        848 
        849 
    
    TypeError: figure must be an instance of _Figure.
    

    It basically means that the figures are not compatible since they don't come from the same backend. This is why the issue is solved by set_3d_backend.

    Another way to solve this is:

    with use_3d_backend('mayavi'):
        brain = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                         clim=dict(kind='value', lims=[3, 6, 9]))
    
        report = mne.Report()  # indent here
        report.add_figs_to_section(mlab.gcf(), 'caption')  # and here

    For short, this is a tricky behaviour of use_3d_backend. What to do?

    • remove use_3d_backend altogether to avoid these?
    • improve the doc in some way?
  3. GuillaumeFavelier commented on Jan 8, 2021

    @GuillaumeFavelier
    Contributor

    Also, having the figure handle easily accessible via brain.fig for both backends and then being able to pass that into the report will be a gamechanger.

    We can't change PySurfer architecture but we can maybe add a public function to do this @larsoner? (The function would take a brain as parameter and fetch the fig in the private parameters).

  4. larsoner commented on Jan 8, 2021

    @larsoner
    Member

    I'm not sure that mixing Mayavi and PyVista results is really a use case we want to support. It seems like the easy fix here is to do set_3d_backend at the beginning. @jasmainak would that work for you? Then we just need to detect that the backend switched and raise an error for people. This is much simpler than trying to support mixed-backend use cases...

  5. jasmainak commented on Jan 8, 2021

    @jasmainak
    MemberAuthor

    But why does MNE-report care if the figure is an instance of the current backend or not? Does it support the use of figures from pyvista backend? The docstrings seems to suggest not. I thought it was designed in a way that any mlab figure should work, don't see what is the relationship with current backend.

    Regarding mixed-backends, I do need to switch back and forth because not all functions are supported everywhere. For example, the stc.plot_3d doesn't seem to work with mayavi backend.

  6. jasmainak commented on Jan 8, 2021

    @jasmainak
    MemberAuthor

    We can't change PySurfer architecture but we can maybe add a public function to do this @larsoner? (The function would take a brain as parameter and fetch the fig in the private parameters).

    any idea why the figure handles are so convoluted to get in pyvista ? I briefly looked at the API, didn't seem straightforward. To expand a bit, my scripts produce 10-15 plots and ideally, I would like to bother to put a report.add_figs_to_section after every figure. What I do is the following:

    report = mne.Report()
    for fignum in plt.get_fignums():
        fig = plt.figure(fignum)
        report.add_figs_to_section(fig, f'Figure {fignum}')
        plt.close(fignum)

    Unfortunately, it seems a similar API is not available for Pyvista or Mayavi although mayavi does seem to mirror the matplotlib API to some extent with functions like mlab.gcf(). So, in summary, my feeling is that this should be fixed in pyvista end but you make the judgement call in the end :)

  7. larsoner commented on Jan 8, 2021

    @larsoner
    Member

    I'd rather make it so that people can use PyVista for everything. Why do you need Mayavi plots?

  8. jasmainak commented on Jan 8, 2021

    @jasmainak
    MemberAuthor

    umm ... not sure why I went on that path. I think because I couldn't figure out how to add the stc plot with pyvista to the report. With mayavi, there is mlab.gcf ...

  9. larsoner commented on Jan 8, 2021

    @larsoner
    Member

    Okay let's make this PyVista experience better rather than deal with Mayavi + PyVista mixing. @GuillaumeFavelier can you advise and update docs and maybe functions in a way that would have made things less painful for @jasmainak ?

  10. agramfort commented on Jan 9, 2021

    @agramfort
    SponsorMember
  11. GuillaumeFavelier commented on Jan 11, 2021

    @GuillaumeFavelier
    Contributor

    But why does MNE-report care if the figure is an instance of the current backend or not?

    We decided a while back to offer a dynamic 3d backend selection (set_3d_backend, use_3d_backend, ...etc). This way, the user does not have much constraints (it even allows mixed-backends) and it's flexible enough for the development of new backends (and I did work on a few before we settled for PyVista). For short, this design introduces a dependency in report to the current/selected 3d backend.

    Regarding mixed-backends, I do need to switch back and forth because not all functions are supported everywhere.

    You seem to have to a lot of experience with both backends. I am sad to hear that not one backend satisfies all your needs but this is what we are working towards so for example, PRs are welcome to update the feature table of Brain and set_3d_backend. The more I am aware of what is lacking, the better it is :)

    Does it support the use of figures from pyvista backend?

    Yes it does but considering:

    I couldn't figure out how to add the stc plot with pyvista to the report.

    and my recent interactions with @hoechenberger, this can definitely be improved 😅 !

  12. GuillaumeFavelier commented on Jan 11, 2021

    @GuillaumeFavelier
    Contributor

    let's make this PyVista experience better

    The great majority of 3d plot functions return a fig but stc.plot returns an instance of Brain. This behaviour is different and I think a function to produce the fig in a backend-agnostic way could help with the situation.

    any idea why the figure handles are so convoluted to get in pyvista ?

    BTW, this is homemade cooking to mimic Mayavi's behaviour. It's not supported by PyVista natively. Any feedback to improve it is welcome of course.

  13. larsoner commented on Oct 22, 2021

    @larsoner
    Member

    Closing this as it should be taken care of as part of #9753

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions