Skip to content

Synchronize __repr__() and _repr_html_() #9830

Closed

Description

@cbrnr

TIL that Info has a dedicated HTML representation, which is 🔥. However, I don't like that it doesn't show the same information as the standard text representation, for example:
Screen Shot 2021-10-11 at 15 50 49
Specifically, I really miss the channel names and I don't like that MEG types are always listed, but ideally there should be no differences at all except for a nicer rendering in HTML. WDYT?

Activity

  1. agramfort commented on Oct 11, 2021

    @agramfort
    SponsorMember
  2. larsoner commented on Oct 11, 2021

    @larsoner
    Member

    No strong feeling from me. With the HTML we might be able to get away with more information even if we try to make it more consistent, for example we could probably do a 3-column table that has key / description / value (currently it's description / value), and keep the console more compact and closer to code with just key / value (what it is now).

  3. agramfort commented on Oct 11, 2021

    @agramfort
    SponsorMember
  4. drammock commented on Oct 11, 2021

    @drammock
    Member

    I propose:

    1. adding a key column as @larsoner suggests. Personally I'd but it in between the description and the value, possibly even as a parenthetical like "Highpass (highpass)" or "Sampling frequency (sfreq)"
    2. suppressing things like 0 magnetometer
    3. formatting the good channels to be \n separated instead of comma-separated (I think this was recently done by @larsoner for some other field in one of the other __html_repr__ methods? why not here too). If this is done, we should drop the words "and" and "channels" too
    4. not sure what to do about harmonizing which fields are actually shown; to me it makes sense that they would match as @cbrnr suggests, but maybe there's a good reason they don't?
  5. agramfort commented on Oct 11, 2021

    @agramfort
    SponsorMember
  6. cbrnr commented on Oct 12, 2021

    @cbrnr
    ContributorAuthor

    Ideally, we should only have to maintain __repr__ and just put its contents in a nice HTML table. I don't like that currently they contain different fields. I'm not even sure we need a description column for the fields when we could just use the keys (they should be self-explanatory and if not they are documented).

  7. cbrnr commented on Oct 12, 2021

    @cbrnr
    ContributorAuthor

    Maybe just something like this:

        def _repr_html_(self, caption=None):
            """Summarize info for HTML representation."""
            html = ''
            if isinstance(caption, str):
                html += f'<h4>{caption}</h4>\n'
            html += '<table class="table table-hover table-striped table-sm table-responsive small">\n'  # noqa
            for row in repr(self).split('\n')[1:-1]:
                key, value = row.split(':')
                html += '<tr>\n'
                html += f'<th>{key.strip()}</th>\n'
                html += f'<td>{value.strip()}</td>\n'
            html += '</table>'
            return html

    Which looks like:

    Screen Shot 2021-10-12 at 08 59 35

  8. changed the title [-]Synchronize `Info.__repr__()` and `Info._repr_html_()`[/-] [+]Synchronize `__repr__()` and `_repr_html_()`[/+] on Oct 12, 2021
  9. cbrnr commented on Oct 12, 2021

    @cbrnr
    ContributorAuthor

    BTW, the same applies to Raw and Epochs. I think that the two reprs should contain the same pieces of information.

  10. hoechenberger commented on Oct 12, 2021

    @hoechenberger
    Member

    @cbrnr In my current PR #9828 on adding ICA to Report, I also reworked ICA.__repr__ and added ICA._repr_html_. To reduce code duplication and improve consistency between the two, I took the following approach:

    def _get_infos_for_repr(self):
    @dataclass
    class _InfosForRepr:
    # XXX replace with Optional[Literal['raw data', 'epochs'] once we
    # drop support for Py 3.7
    fit_on: Optional[str]
    # XXX replace with fit_method: Literal['fastica', 'infomax',
    # 'extended-infomax', 'picard'] once we drop support for Py 3.7
    fit_method: str
    fit_n_iter: Optional[int]
    fit_n_samples: Optional[int]
    fit_n_components: Optional[int]
    fit_n_pca_components: Optional[int]
    fit_explained_variance: Optional[float]
    ch_types: List[str]
    excludes: List[str]
    if self.current_fit == 'unfitted':
    fit_on = None
    elif self.current_fit == 'raw':
    fit_on = 'raw data'
    else:
    fit_on = 'epochs'
    fit_method = self.method
    fit_n_iter = getattr(self, 'n_iter_', None)
    fit_n_samples = getattr(self, 'n_samples_', None)
    fit_n_components = getattr(self, 'n_components_', None)
    fit_n_pca_components = getattr(self, 'pca_components_', None)
    if fit_n_pca_components is not None:
    fit_n_pca_components = len(self.pca_components_)
    fit_explained_variance = getattr(self, 'pca_explained_variance_', None)
    if fit_explained_variance is not None:
    abs_vars = self.pca_explained_variance_
    rel_vars = abs_vars / abs_vars.sum()
    fit_explained_variance = rel_vars[:fit_n_components].sum()
    if self.info is not None:
    ch_types = [c for c in _DATA_CH_TYPES_SPLIT if c in self]
    else:
    ch_types = []
    if self.exclude:
    excludes = [self._ica_names[i] for i in self.exclude]
    else:
    excludes = []
    infos_for_repr = _InfosForRepr(
    fit_on=fit_on,
    fit_method=fit_method,
    fit_n_iter=fit_n_iter,
    fit_n_samples=fit_n_samples,
    fit_n_components=fit_n_components,
    fit_n_pca_components=fit_n_pca_components,
    fit_explained_variance=fit_explained_variance,
    ch_types=ch_types,
    excludes=excludes
    )
    return infos_for_repr
    def __repr__(self):
    """ICA fit information."""
    infos = self._get_infos_for_repr()
    s = (f'{infos.fit_on or "no"} decomposition, '
    f'method: {infos.fit_method}')
    if infos.fit_on is not None:
    s += (
    f' (fit in {infos.fit_n_iter} iterations on '
    f'{infos.fit_n_samples} samples), '
    f'{infos.fit_n_components} ICA components '
    f'explaining {round(infos.fit_explained_variance * 100, 1)} % '
    f'of variance '
    f'({infos.fit_n_pca_components} PCA components used), '
    f'channel types: {", ".join(infos.ch_types)}, '
    f'{len(infos.excludes) or "no"} sources marked for exclusion'
    )
    return f'<ICA | {s}>'
    def _repr_html_(self):
    infos = self._get_infos_for_repr()
    html = ica_template.substitute(
    fit_on=infos.fit_on,
    method=infos.fit_method,
    n_iter=infos.fit_n_iter,
    n_samples=infos.fit_n_samples,
    n_components=infos.fit_n_components,
    n_pca_components=infos.fit_n_pca_components,
    explained_variance=infos.fit_explained_variance,
    ch_types=infos.ch_types,
    excludes=infos.excludes
    )
    return html

    I'm -1 on adding a key column as this will force us to do a 1-to-1 mapping between rows and keys or attributes, which I think is not practical:

    • We have _html_repr_ for many more objects than just Info
    • Here in the Fit row, I actually combine 3 fields, so it's impossible to have a 1-to-1 mapping:

    Screen Shot 2021-10-13 at 00 13 05

    Also I'm adding info that's just not present in the object itself (i.e., is calculated), namely Explained variance

  11. hoechenberger commented on Oct 12, 2021

    @hoechenberger
    Member

    I want to add that my concern re 1-to-1 mapping can be disregarded if we're only talking about Info.

  12. cbrnr commented on Oct 13, 2021

    @cbrnr
    ContributorAuthor

    I find it very strange to show different pieces of information depending on which backend is used. What exactly is the reason why showing exactly the same information is not feasible? The HTML repr is also just text which should easily fit in a terminal. This should not just synced for Info, but also for Raw, Epochs, and ICA(I don't think we have more).

  13. hoechenberger commented on Oct 13, 2021

    @hoechenberger
    Member

    What exactly is the reason why showing exactly the same information is not feasible?

    HTML repr allows us to present data in true tables (that we will make collapsible soon, too), while you'll typically want a very concise repr on the terminal. Data can also be styled beyond just a tabular alignment in HTML, while this stuff isn't easy without introducing new dependencies on the terminal (e.g., via rich)

    Also I think that when adding some of the HTML reprs, we didn't want to / dare to change the existing repr() output, but still wanted to take advantage of the features HTML offers.

  14. hoechenberger commented on Oct 13, 2021

    @hoechenberger
    Member

    That said, +1 on ensuring they're more synchronous, but please don't make the HTML repr just an ugly HTML-ified copy of the text repr. It can do much better than that.

  15. cbrnr commented on Oct 13, 2021

    @cbrnr
    ContributorAuthor

    I'm still -1 on using different reprs. I can already imagine the confusion when people notice that the output (repr) of an object in the interactive interpreter is widely different from inside a notebook. If you want to add nice HTML summaries I'd really prefer if that had its own dedicated method (e.g. raw.print_html() or even raw.print()). Changing the default repr is asking for trouble.

  16. 25 remaining items

  17. cbrnr commented on Sep 13, 2022

    @cbrnr
    ContributorAuthor

    I would like to res this issue because I think the current dissociation between the two reprs are still very confusing (at least to me). Specifically, when writing some tutorial in a notebook-like environment, people should see the exact same output whether they are in a REPL or a notebook. In general, I prefer the REPL, but I write my tutorial with Quarto (which uses Jupyter notebook under the hood), so when I tell people to run e.g.

    raw.info
    

    I would like to see the REPL __repr__() and not _repr_html_().

    Could we add a config option to disable all _repr_html_()? I think we should because AFAIK it is not possible to change this behavior on the IPython side (https://stackoverflow.com/questions/73540055/how-can-i-force-repr-instead-of-repr-html-in-jupyter-notebooks).

  18. hoechenberger commented on Sep 13, 2022

    @hoechenberger
    Member

    @cbrnr +1 for adding a configuration option if Jupyter doesn't support this. The default should IMHO still be to use HTML repr in a Jupyter environment.

  19. cbrnr commented on Sep 13, 2022

    @cbrnr
    ContributorAuthor

    This would be great! And yes, HTML can remain the default for notebook envs.

    Does anyone have an idea how to implement this technically? I briefly looked at how it's done in Scikit-learn, but couldn't really figure it out so I guess this will be a larger change.

    I will also ask the IPython devs if they think this could be added on their end. Doesn't make a lot of sense that every package has to implement that.

  20. hoechenberger commented on Sep 13, 2022

    @hoechenberger
    Member

    Does anyone have an idea how to implement this technically? I briefly looked at how it's done in Scikit-learn, but couldn't really figure it out so I guess this will be a larger change.

    Could you not simply do something like this:

    def _repr_html_(self):
        if config.no_html_repr:
            return repr(self)

    ?

  21. cbrnr commented on Sep 13, 2022

    @cbrnr
    ContributorAuthor

    Unfortunately, this doesn't work (nothing gets printed). It seems like it's not just the returned value that's needed by the notebook.

  22. hoechenberger commented on Sep 13, 2022

    @hoechenberger
  23. hoechenberger commented on Sep 13, 2022

    @hoechenberger
    Member

    @cbrnr I assume you'll have to escape the < etc symbols

  24. hoechenberger commented on Sep 13, 2022

    @hoechenberger
    Member

    @cbrnr I assume you'll have to escape the < etc symbols

    Yep.

    # %%
    class Test:
        def __repr__(self) -> str:
            return '<foobar>'
    
        def _repr_html_(self) -> str:
            return repr(self)
    
    
    test = Test()
    test

    prints nothing.

    But this works:

    # %%
    import html
    
    class Test:
        def __repr__(self) -> str:
            return '<foobar>'
    
        def _repr_html_(self) -> str:
            return html.escape(
                repr(self)
            )
    
    
    test = Test()
    test

    Screen Shot 2022-09-13 at 13 46 27

  25. cbrnr commented on Sep 13, 2022

    @cbrnr
    ContributorAuthor

    Nice! So I guess we have a plan then! I will prepare a PR soon! Thanks a lot!

  26. cbrnr commented on Sep 13, 2022

    @cbrnr
    ContributorAuthor

    Line breaks \n should not be escaped though – is this possible?

  27. cbrnr commented on Sep 13, 2022

    @cbrnr
    ContributorAuthor

    The font is also not a fixed-width font, which ideally would be nice to have as well...

  28. cbrnr commented on Sep 13, 2022

    @cbrnr
    ContributorAuthor

    This should do it:

    import html
    
    class Test:
        def __repr__(self) -> str:
            return '<foo>\n<bar>'
    
        def _repr_html_(self) -> str:
            r = "<pre>" + html.escape(repr(self)) + "</pre>"
            return r.replace("\n", "<br/>")
    
    
    test = Test()
    test
  29. modified the milestones: 1.2, 1.3 on Sep 13, 2022
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions