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 all 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
56 changes: 43 additions & 13 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
from datetime import datetime
import os
from pathlib import Path
from typing import List
from typing import Dict, List

from github import Github
import pyvista
import requests
from sphinx.application import Sphinx
from sphinx.builders.latex import LaTeXBuilder

from ansys_sphinx_theme import (
Expand Down Expand Up @@ -133,8 +134,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 +181,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 +235,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 @@ -245,35 +245,38 @@ def download_and_process_files(example_links: List[str]) -> List[str]:
"own_page_level": "function",
"package_depth": 1,
}
try:
import plotly
import plotly.io
except ImportError:
plotly = None

# 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"],
"gallery_dirs": ["examples/gallery-examples/"],
# 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"),
"default_thumb_file": "source/_static/pyansys_light_square.png",
"image_scrapers": ("matplotlib", "pyvista"),
}
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 +295,30 @@ 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.

Parameters
----------
app : Sphinx
Sphinx application instance.
env : BuildEnvironment
The build environment.

Notes
-----
Remove the examples/gallery-examples/*.ipynb pattern from the exclude patterns.
When the nbsphinx extension is enabled, the exclude patterns are modified
to exclude the examples/gallery-examples/*.ipynb pattern. This function reverts
the exclude patterns to their original state.
"""
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)
1,399 changes: 1,396 additions & 3 deletions doc/source/examples/nbsphinx/jupyter-notebook.ipynb

Large diffs are not rendered by default.

66 changes: 55 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,44 @@
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 Plotly.

import plotly.graph_objs as go

# More info: https://plotly.com/python/renderers/

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])

fig

###############################################################################
# Render equations using IPython ``math``
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand All @@ -80,18 +118,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 +154,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