-
Notifications
You must be signed in to change notification settings - Fork 286
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add _repr_html_ for Iris cubes #2918
Changes from all commits
1178590
0f1dd68
908e41c
ec4072d
c2821ba
8074245
63136ef
060d163
793a9e6
ffc0d40
86edc2e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
* Added ``repr_html`` functionality to the :class:`~iris.cube.Cube` to provide | ||
a rich html representation of cubes in Jupyter notebooks. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,308 @@ | ||
# (C) British Crown Copyright 2018, Met Office | ||
# | ||
# This file is part of Iris. | ||
# | ||
# Iris is free software: you can redistribute it and/or modify it under | ||
# the terms of the GNU Lesser General Public License as published by the | ||
# Free Software Foundation, either version 3 of the License, or | ||
# (at your option) any later version. | ||
# | ||
# Iris is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
# GNU Lesser General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Lesser General Public License | ||
# along with Iris. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
""" | ||
Definitions of how Iris objects should be represented. | ||
|
||
""" | ||
|
||
from __future__ import (absolute_import, division, print_function) | ||
from six.moves import (filter, input, map, range, zip) # noqa | ||
|
||
import re | ||
|
||
|
||
class CubeRepresentation(object): | ||
""" | ||
Produce representations of a :class:`~iris.cube.Cube`. | ||
|
||
This includes: | ||
|
||
* ``_html_repr_``: a representation of the cube as an html object, | ||
available in Jupyter notebooks. Specifically, this is presented as an | ||
html table. | ||
|
||
""" | ||
|
||
_template = """ | ||
<style> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ideally we wouldn't re-define the style each time we do a repr. I think there is (should be) a hook for this somewhere, but I did a similar hack for the matplotlib notebook backend and it does work effectively. |
||
a.iris {{ | ||
text-decoration: none !important; | ||
}} | ||
table.iris {{ | ||
white-space: pre; | ||
border: 1px solid; | ||
border-color: #9c9c9c; | ||
font-family: monaco, monospace; | ||
}} | ||
th.iris {{ | ||
background: #303f3f; | ||
color: #e0e0e0; | ||
border-left: 1px solid; | ||
border-color: #9c9c9c; | ||
font-size: 1.05em; | ||
min-width: 50px; | ||
max-width: 125px; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we increase this, or even remove altogether? The effect of this width is that we can get some really ugly column rendering (e.g. ```model_level_number``) |
||
}} | ||
tr.iris :first-child {{ | ||
border-right: 1px solid #9c9c9c !important; | ||
}} | ||
td.iris-title {{ | ||
background: #d5dcdf; | ||
border-top: 1px solid #9c9c9c; | ||
font-weight: bold; | ||
}} | ||
.iris-word-cell {{ | ||
text-align: left !important; | ||
white-space: pre; | ||
}} | ||
.iris-subheading-cell {{ | ||
padding-left: 2em !important; | ||
}} | ||
.iris-inclusion-cell {{ | ||
padding-right: 1em !important; | ||
}} | ||
.iris-panel-body {{ | ||
padding-top: 0px; | ||
}} | ||
.iris-panel-title {{ | ||
padding-left: 3em; | ||
}} | ||
.iris-panel-title {{ | ||
margin-top: 7px; | ||
}} | ||
</style> | ||
<table class="iris" id="{id}"> | ||
{header} | ||
{shape} | ||
{content} | ||
</table> | ||
""" | ||
|
||
def __init__(self, cube): | ||
self.cube = cube | ||
self.cube_id = id(self.cube) | ||
self.cube_str = str(self.cube) | ||
|
||
self.str_headings = { | ||
'Dimension coordinates:': None, | ||
'Auxiliary coordinates:': None, | ||
'Derived coordinates:': None, | ||
'Scalar coordinates:': None, | ||
'Attributes:': None, | ||
'Cell methods:': None, | ||
} | ||
self.dim_desc_coords = ['Dimension coordinates:', | ||
'Auxiliary coordinates:', | ||
'Derived coordinates:'] | ||
|
||
# Important content that summarises a cube is defined here. | ||
self.shapes = self.cube.shape | ||
self.scalar_cube = self.shapes == () | ||
self.ndims = self.cube.ndim | ||
|
||
self.name = self.cube.name().title().replace('_', ' ') | ||
self.names = self._dim_names() | ||
self.units = self.cube.units | ||
|
||
def _get_dim_names(self): | ||
""" | ||
Get dimension-describing coordinate names, or '--' if no coordinate] | ||
describes the dimension. | ||
|
||
Note: borrows from `cube.summary`. | ||
|
||
""" | ||
# Create a set to contain the axis names for each data dimension. | ||
dim_names = list(range(len(self.cube.shape))) | ||
|
||
# Add the dim_coord names that participate in the associated data | ||
# dimensions. | ||
for dim in range(len(self.cube.shape)): | ||
dim_coords = self.cube.coords(contains_dimension=dim, | ||
dim_coords=True) | ||
if dim_coords: | ||
dim_names[dim] = dim_coords[0].name() | ||
else: | ||
dim_names[dim] = '--' | ||
return dim_names | ||
|
||
def _dim_names(self): | ||
if self.scalar_cube: | ||
dim_names = ['(scalar cube)'] | ||
else: | ||
dim_names = self._get_dim_names() | ||
return dim_names | ||
|
||
def _get_lines(self): | ||
return self.cube_str.split('\n') | ||
|
||
def _get_bits(self, bits): | ||
""" | ||
Parse the body content (`bits`) of the cube string in preparation for | ||
being converted into table rows. | ||
|
||
""" | ||
left_indent = re.split(r'\w+', bits[1])[0] | ||
|
||
# Get heading indices within the printout. | ||
start_inds = [] | ||
for hdg in self.str_headings.keys(): | ||
heading = '{}{}'.format(left_indent, hdg) | ||
try: | ||
start_ind = bits.index(heading) | ||
except ValueError: | ||
continue | ||
else: | ||
start_inds.append(start_ind) | ||
# Mark the end of the file. | ||
start_inds.append(0) | ||
|
||
# Retrieve info for each heading from the printout. | ||
for i0, i1 in zip(start_inds[:-1], start_inds[1:]): | ||
str_heading_name = bits[i0].strip() | ||
if i1 != 0: | ||
content = bits[i0 + 1: i1] | ||
else: | ||
content = bits[i0 + 1:] | ||
self.str_headings[str_heading_name] = content | ||
|
||
def _make_header(self): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would be great to have column highlighting too. See https://stackoverflow.com/questions/16967366/how-do-i-highlight-an-html-table-column-with-bootstrap. Note: not in this PR. |
||
""" | ||
Make the table header. This is similar to the summary of the cube, | ||
but does not include dim shapes. These are included on the next table | ||
row down, and produced with `make_shapes_row`. | ||
|
||
""" | ||
# Header row. | ||
tlc_template = \ | ||
'<th class="iris iris-word-cell">{self.name} ({self.units})</th>' | ||
top_left_cell = tlc_template.format(self=self) | ||
cells = ['<tr class="iris">', top_left_cell] | ||
for dim_name in self.names: | ||
cells.append( | ||
'<th class="iris iris-word-cell">{}</th>'.format(dim_name)) | ||
cells.append('</tr>') | ||
return '\n'.join(cell for cell in cells) | ||
|
||
def _make_shapes_row(self): | ||
"""Add a row to show data / dimensions shape.""" | ||
title_cell = \ | ||
'<td class="iris-word-cell iris-subheading-cell">Shape</td>' | ||
cells = ['<tr class="iris">', title_cell] | ||
for shape in self.shapes: | ||
cells.append( | ||
'<td class="iris iris-inclusion-cell">{}</td>'.format(shape)) | ||
cells.append('</td>') | ||
return '\n'.join(cell for cell in cells) | ||
|
||
def _make_row(self, title, body=None, col_span=0): | ||
""" | ||
Produce one row for the table body; i.e. | ||
<tr><td>Coord name</td><td>x</td><td>-</td>...</tr> | ||
|
||
`body` contains the content for each cell not in the left-most (title) | ||
column. | ||
If None, indicates this row is a title row (see below). | ||
`title` contains the row heading. If `body` is None, indicates | ||
that the row contains a sub-heading; | ||
e.g. 'Dimension coordinates:'. | ||
`col_span` indicates how many columns the string should span. | ||
|
||
""" | ||
row = ['<tr class="iris">'] | ||
template = ' <td{html_cls}>{content}</td>' | ||
if body is None: | ||
# This is a title row. | ||
# Strip off the trailing ':' from the title string. | ||
title = title.strip()[:-1] | ||
row.append( | ||
template.format(html_cls=' class="iris-title iris-word-cell"', | ||
content=title)) | ||
# Add blank cells for the rest of the rows. | ||
for _ in range(self.ndims): | ||
row.append(template.format(html_cls=' class="iris-title"', | ||
content='')) | ||
else: | ||
# This is not a title row. | ||
# Deal with name of coord/attr etc. first. | ||
sub_title = '\t{}'.format(title) | ||
row.append(template.format( | ||
html_cls=' class="iris-word-cell iris-subheading-cell"', | ||
content=sub_title)) | ||
# One further item or more than that? | ||
if col_span != 0: | ||
html_cls = ' class="{}" colspan="{}"'.format('iris-word-cell', | ||
col_span) | ||
row.append(template.format(html_cls=html_cls, content=body)) | ||
else: | ||
# "Inclusion" - `x` or `-`. | ||
for itm in body: | ||
row.append(template.format( | ||
html_cls=' class="iris-inclusion-cell"', | ||
content=itm)) | ||
row.append('</tr>') | ||
return row | ||
|
||
def _make_content(self): | ||
elements = [] | ||
for k, v in self.str_headings.items(): | ||
if v is not None: | ||
# Add the sub-heading title. | ||
elements.extend(self._make_row(k)) | ||
for line in v: | ||
# Add every other row in the sub-heading. | ||
if k in self.dim_desc_coords: | ||
body = re.findall(r'[\w-]+', line) | ||
title = body.pop(0) | ||
colspan = 0 | ||
else: | ||
split_point = line.index(':') | ||
title = line[:split_point].strip() | ||
body = line[split_point + 2:].strip() | ||
colspan = self.ndims | ||
elements.extend( | ||
self._make_row(title, body=body, col_span=colspan)) | ||
return '\n'.join(element for element in elements) | ||
|
||
def repr_html(self): | ||
"""The `repr` interface for Jupyter.""" | ||
# Deal with the header first. | ||
header = self._make_header() | ||
|
||
# Check if we have a scalar cube. | ||
if self.scalar_cube: | ||
shape = '' | ||
# We still need a single content column! | ||
self.ndims = 1 | ||
else: | ||
shape = self._make_shapes_row() | ||
|
||
# Now deal with the rest of the content. | ||
lines = self._get_lines() | ||
# If we only have a single line `cube_str` we have no coords / attrs! | ||
# We need to handle this case specially. | ||
if len(lines) == 1: | ||
content = '' | ||
else: | ||
self._get_bits(lines) | ||
content = self._make_content() | ||
|
||
return self._template.format(header=header, | ||
id=self.cube_id, | ||
shape=shape, | ||
content=content) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We will want this to have a screenshot when it comes to cutting the release.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could use the image above?