Skip to content
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

feat: enable matplotlib and plotly in examples #567

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
087be44
feat: enable plotly in examples
jorgepiloto Oct 23, 2024
73a8d09
fix: section underscore
jorgepiloto Oct 23, 2024
583c786
Merge branch 'main' into feat/plotly
jorgepiloto Oct 23, 2024
facb1ab
docs: add sphinx gallery nb
Revathyvenugopal162 Oct 25, 2024
6b1bf23
chore: adding changelog file 567.added.md [dependabot-skip]
pyansys-ci-bot Oct 25, 2024
f084e3b
fix: include sphinx-gallery notebooks
jorgepiloto Oct 25, 2024
b7fe30f
fix: codespell to ignore code-cells in notebook
jorgepiloto Oct 25, 2024
8f1122b
fix: table in rst
jorgepiloto Oct 25, 2024
0864663
fix: indentation
jorgepiloto Oct 25, 2024
e09d2ab
Merge branch 'main' into feat/plotly
jorgepiloto Oct 25, 2024
4f04b0c
Merge branch 'main' into feat/plotly
Revathyvenugopal162 Oct 28, 2024
eca38f5
docs: add table rst
Revathyvenugopal162 Oct 28, 2024
ef09fb0
docs: add direct link to gallery
Revathyvenugopal162 Oct 28, 2024
0a7a69f
docs: remove rst
Revathyvenugopal162 Oct 28, 2024
c6379e8
docs: add hook
Revathyvenugopal162 Oct 28, 2024
b8f39d3
docs: revert hooks
Revathyvenugopal162 Oct 29, 2024
487c2f9
docs: revert the pyvista plot
Revathyvenugopal162 Oct 29, 2024
6839ffc
docs: add docstring
Revathyvenugopal162 Oct 29, 2024
1146206
fix: revert duplicated fixed
Revathyvenugopal162 Oct 29, 2024
910a2e2
Update doc/source/conf.py
Revathyvenugopal162 Oct 30, 2024
d1ffe52
Update doc/source/examples/sphinx-gallery/sphinx-gallery.py
Revathyvenugopal162 Oct 30, 2024
7f5ec9f
fix: cleanup the gallery
Revathyvenugopal162 Oct 30, 2024
abbaeb1
Merge branch 'main' into feat/plotly
Revathyvenugopal162 Oct 31, 2024
0b37006
Merge branch 'main' into feat/plotly
Revathyvenugopal162 Oct 31, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ repos:
rev: v2.3.0
hooks:
- id: codespell
exclude: doc/source/examples/nbsphinx/jupyter-notebook.ipynb

- repo: https://github.com/pre-commit/mirrors-prettier
rev: 'v4.0.0-alpha.8'
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/567.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
feat: enable matplotlib and plotly in examples
42 changes: 31 additions & 11 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
from datetime import datetime
import os
from pathlib import Path
from typing import List
from typing import Dict, List

from github import Github
import plotly.io as pio
import pyvista
import requests
from sphinx.application import Sphinx
from sphinx.builders.latex import LaTeXBuilder

from ansys_sphinx_theme import (
Expand All @@ -24,6 +26,8 @@
watermark,
)

pio.renderers.default = "sphinx_gallery"

THIS_PATH = Path(__file__).parent.resolve()
EXAMPLE_PATH = (THIS_PATH / "examples" / "sphinx_examples").resolve()

Expand Down Expand Up @@ -133,8 +137,8 @@
exclude_patterns = [
"links.rst",
"examples/sphinx-gallery/README.rst",
"examples/gallery-examples/*.ipynb",
"sg_execution_times.rst",
"examples/gallery-examples/*.ipynb",
]
rst_epilog = ""
with Path.open(THIS_PATH / "links.rst", "r") as f:
Expand Down Expand Up @@ -180,7 +184,8 @@ def extract_example_links(
list
List of example links.
"""
g = Github()
token = os.getenv("GITHUB_TOKEN")
g = Github(token)
repo = g.get_repo(repo_fullname)
contents = repo.get_contents(path_relative_to_root)
if not isinstance(contents, list):
Expand Down Expand Up @@ -233,8 +238,6 @@ def download_and_process_files(example_links: List[str]) -> List[str]:

if not BUILD_EXAMPLES:
exclude_patterns.extend(["examples.rst", "examples/**", "examples/api/**"])


else:
# Autoapi examples
extensions.append("ansys_sphinx_theme.extension.autoapi")
Expand All @@ -246,34 +249,39 @@ def download_and_process_files(example_links: List[str]) -> List[str]:
"package_depth": 1,
}

import plotly.io as pio
from plotly.io._sg_scraper import plotly_sg_scraper

pio.renderers.default = "sphinx_gallery"
Revathyvenugopal162 marked this conversation as resolved.
Show resolved Hide resolved

# Gallery of examples
extensions.extend(["nbsphinx", "sphinx_gallery.gen_gallery"])
sphinx_gallery_conf = {
# path to your examples scripts
"examples_dirs": ["examples/sphinx-gallery"],
"examples_dirs": ["examples/sphinx-gallery/"],
# path where to save gallery generated examples
"gallery_dirs": ["examples/gallery-examples"],
Revathyvenugopal162 marked this conversation as resolved.
Show resolved Hide resolved
# Pattern to search for example files
"filename_pattern": r"sphinx_gallery\.py",
"filename_pattern": r"\.py",
# Remove the "Download all examples" button from the top level gallery
"download_all_examples": False,
# Modules for which function level galleries are created. In
"image_scrapers": ("pyvista", "matplotlib"),
"image_scrapers": ("pyvista", "matplotlib", plotly_sg_scraper),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding this one.

"default_thumb_file": "source/_static/pyansys_light_square.png",
"capture_repr": ("_repr_html_", "__repr__"),
}
pyvista.BUILDING_GALLERY = True
pyvista.OFF_SCREEN = True

nbsphinx_prolog = """
Download this example as a :download:`Jupyter notebook </{{ env.docname }}.ipynb>`.

----
"""
nbsphinx_execute = "always"
nbsphinx_thumbnails = {
"examples/nbsphinx/jupyter-notebook": "_static/pyansys_light_square.png",
}

pyvista.BUILDING_GALLERY = True

# Third party examples
example_links = extract_example_links(
"executablebooks/sphinx-design",
Expand All @@ -292,3 +300,15 @@ def download_and_process_files(example_links: List[str]) -> List[str]:

jinja_contexts["examples"] = {"inputs_examples": file_names}
jinja_contexts["admonitions"] = {"inputs_admonitions": admonitions_links}


def revert_exclude_patterns(app, env):
"""Revert the exclude patterns."""
excluded_pattern = env.config.exclude_patterns
excluded_pattern.remove("examples/gallery-examples/*.ipynb")
env.config.exclude_patterns = excluded_pattern


def setup(app: Sphinx) -> Dict:
"""Sphinx hooks to add to the setup."""
app.connect("env-updated", revert_exclude_patterns)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice hack, @Revathyvenugopal162!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add some information about it. Whether it is a docstring or similar.

1,399 changes: 1,396 additions & 3 deletions doc/source/examples/nbsphinx/jupyter-notebook.ipynb

Large diffs are not rendered by default.

64 changes: 53 additions & 11 deletions doc/source/examples/sphinx-gallery/sphinx-gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,42 @@
plotter.title = "3D Sphere Visualization"
plotter.show()

###############################################################################
# Figures with Matplotlib
# ~~~~~~~~~~~~~~~~~~~~~~~
# This example shows how to render a figure using Matplotlib.

import matplotlib.pyplot as plt
import numpy as np

time = np.linspace(0, 2 * np.pi, 100)

fig, ax = plt.subplots()
ax.plot(time, np.cos(time), color="blue", label=r"$\cos{(t)}$")
ax.plot(time, np.sin(time), color="red", label=r"$\sin{(t)}$")

ax.set_xlabel("Time [time units]")
ax.set_ylabel("Amplitude [distance units]")
ax.set_title("Trigonometric functions")

plt.show()

###############################################################################
# Figures with Plotly
# ~~~~~~~~~~~~~~~~~~~
# This example shows how to render a figure using Matplotlib.
Revathyvenugopal162 marked this conversation as resolved.
Show resolved Hide resolved

import plotly
import plotly.graph_objs as go

time = np.linspace(0, 2 * np.pi, 100)

cos_trace = go.Scatter(x=time, y=np.cos(time), mode="lines", name="cos(t)")
sin_trace = go.Scatter(x=time, y=np.sin(time), mode="lines", name="sin(t)")

fig = go.Figure(data=[cos_trace, sin_trace])
plotly.io.show(fig)

###############################################################################
# Render equations using IPython ``math``
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand All @@ -80,18 +116,22 @@
Latex(r"This is a \LaTeX{} equation: $a^2 + b^2 = c^2$")

###############################################################################
# Render a table in markdown
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
# This is an example to render a table inside the markdown with Sphinx-Gallery.
# Render a table
# ~~~~~~~~~~~~~~
# This is an example to render a table with Sphinx-Gallery.
#
# +--------------------------------+--------------------------------+------------------------------+
# | A | B | A and B |
# +================================+================================+==============================+
# | False | False | False |
# +--------------------------------+--------------------------------+------------------------------+
# | True | False | False |
# +--------------------------------+--------------------------------+------------------------------+
# | False | True | False |
# +--------------------------------+--------------------------------+------------------------------+
# | True | True | True |
# +--------------------------------+--------------------------------+------------------------------+
#
# ====== ====== =======
# A B A and B
# ====== ====== =======
# False False False
# True False False
# False True False
# True True True
# ====== ====== =======

###############################################################################
# Render a table using pandas
Expand All @@ -112,3 +152,5 @@
df.head()

###############################################################################

# %%
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,13 @@ autoapi = [
]
doc = [
"jupytext==1.16.4",
"matplotlib==3.9.2",
"notebook==7.2.2",
"nbsphinx==0.9.5",
"numpydoc==1.8.0",
"pandas==2.2.3",
"Pillow>=9.0",
"plotly==5.24.1",
"PyGitHub==2.4.0",
"pyvista[jupyter]==0.44.1",
"requests==2.32.3",
Expand Down
Loading