Skip to content

Commit

Permalink
Merge pull request #543 from GavinHuttley/develop
Browse files Browse the repository at this point in the history
MAINT: custom sphinx gallery renderer
  • Loading branch information
GavinHuttley committed Feb 20, 2020
2 parents 15beb0a + 71d71fb commit 6fd6bdb
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/cogent3/draw/drawable.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import pathlib

import numpy

Expand Down Expand Up @@ -52,6 +53,44 @@ def get_domain(total, element, is_y, space=0.01):
return domains[element]


def _customise_sphinx_gallery_renderer():
# this is an ugly hack to get around plotly's NOT robust handling of script path
# for automated file naming
import inspect
from plotly.io._renderers import renderers
from plotly.io import _base_renderers as base_render

class SphinxGalleryRenderer(base_render.ExternalRenderer):
def render(self, fig_dict):
# use the environment variable
# DOCUTILSCONFIG to get the location of the sphinx root doc dir
# and select the stack filename whose path is a sibling directory
# based on the maxinum number of matches to the root path
sphinx_root = pathlib.Path(os.environ.get("DOCUTILSCONFIG", "")).absolute()
sphinx_root = sphinx_root.resolve()
stack = inspect.stack()
max_match = 0
for level in stack:
# parent directory
path = pathlib.Path(level.filename).absolute().resolve()
for i, (a, b) in enumerate(zip(path.parts, sphinx_root.parts)):
if a != b:
break

if i > max_match:
max_match = i
filename = str(path)

filename_root, _ = os.path.splitext(filename)
filename_html = filename_root + ".html"
filename_png = filename_root + ".png"
figure = base_render.return_figure_from_figure_or_data(fig_dict, True)
_ = base_render.write_html(fig_dict, file=filename_html)
base_render.write_image(figure, filename_png)

renderers["sphinx_gallery"] = SphinxGalleryRenderer()


def _show_(cls, renderer=None, **kwargs):
"""display figure
Expand All @@ -69,6 +108,9 @@ def _show_(cls, renderer=None, **kwargs):
"""
from plotly.io import show

if renderer == "sphinx_gallery":
_customise_sphinx_gallery_renderer()

if renderer is None and PLOTLY_RENDERER is None:
renderer = "notebook_connected+plotly_mimetype"
elif renderer is None:
Expand Down

0 comments on commit 6fd6bdb

Please sign in to comment.