Skip to content

Commit c62a58c

Browse files
docs: initialize Sphinx Gallery (#2508)
* rename existing `_samples/` * conf * ignore * skimage * thumbnail * notes * dummy file * makedirs * header --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 85962a0 commit c62a58c

15 files changed

+117
-20
lines changed

.azure/gpu-unittests.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ jobs:
219219
echo "Processing $fn example..."
220220
python $fn
221221
done
222-
workingDirectory: "examples/"
222+
workingDirectory: "_samples/"
223223
# skip for PR if there is nothing to test, note that outside PR there is default 'unittests'
224224
condition: and(succeeded(), ne(variables['TEST_DIRS'], ''))
225225
displayName: "Examples"

.github/workflows/docs-build.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ jobs:
6565
- name: Full build for deployment
6666
if: github.event_name != 'pull_request'
6767
run: echo "SPHINX_FETCH_ASSETS=1" >> $GITHUB_ENV
68+
- name: Disable Gallery build
69+
if: matrix.target != 'html'
70+
run: echo "SPHINX_ENABLE_GALLERY=0" >> $GITHUB_ENV
6871
- name: make ${{ matrix.target }}
6972
working-directory: ./docs
7073
run: make ${{ matrix.target }} --debug --jobs $(nproc) SPHINXOPTS="-W --keep-going"

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ coverage.xml
6060
docs/_build/
6161
docs/source/api/
6262
docs/source/generated/
63+
docs/source/gallery/
6364
docs/source/*.md
6465
docs/source/_static/fetched-s3-assets
6566

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ fig3, ax3 = acc.plot(values)
335335
<img src="docs/source/_static/images/plot_example.png" width="1000">
336336
</p>
337337

338-
For examples of plotting different metrics try running [this example file](examples/plotting.py).
338+
For examples of plotting different metrics try running [this example file](_samples/plotting.py).
339339

340340
## Contribute!
341341

File renamed without changes.
File renamed without changes.
File renamed without changes.

docs/source/conf.py

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
SPHINX_MOCK_REQUIREMENTS = int(os.environ.get("SPHINX_MOCK_REQUIREMENTS", True))
3131
SPHINX_FETCH_ASSETS = int(os.environ.get("SPHINX_FETCH_ASSETS", False))
3232
SPHINX_PIN_RELEASE_VERSIONS = int(os.getenv("SPHINX_PIN_RELEASE_VERSIONS", False))
33+
SPHINX_ENABLE_GALLERY = int(os.getenv("SPHINX_ENABLE_GALLERY", True))
3334

3435
html_favicon = "_static/images/icon.svg"
3536

@@ -128,15 +129,22 @@ def _set_root_image_path(page_path: str) -> None:
128129
"sphinx.ext.autosummary",
129130
"sphinx.ext.napoleon",
130131
"sphinx.ext.mathjax",
131-
"myst_parser",
132132
"sphinx.ext.autosectionlabel",
133-
"nbsphinx",
133+
"sphinx.ext.githubpages",
134134
"sphinx_autodoc_typehints",
135135
"sphinx_paramlinks",
136-
"sphinx.ext.githubpages",
137-
"lai_sphinx_theme.extensions.lightning",
136+
"myst_parser",
138137
"matplotlib.sphinxext.plot_directive",
138+
"lai_sphinx_theme.extensions.lightning",
139139
]
140+
if SPHINX_ENABLE_GALLERY:
141+
extensions.append("sphinx_gallery.gen_gallery")
142+
else:
143+
# write a dummy file as placeholder
144+
path_gallery = os.path.join(_PATH_HERE, "gallery")
145+
os.makedirs(path_gallery, exist_ok=True)
146+
with open(os.path.join(path_gallery, "index.rst"), "w") as fopen:
147+
fopen.write("Gallery is disabled\n===================")
140148

141149
# Set that source code from plotting is always included
142150
plot_include_source = True
@@ -146,13 +154,19 @@ def _set_root_image_path(page_path: str) -> None:
146154
# Add any paths that contain templates here, relative to this directory.
147155
templates_path = ["_templates"]
148156

149-
# https://berkeley-stat159-f17.github.io/stat159-f17/lectures/14-sphinx..html#conf.py-(cont.)
150-
# https://stackoverflow.com/questions/38526888/embed-ipython-notebook-in-sphinx-document
151-
# I execute the notebooks manually in advance. If notebooks test the code,
152-
# they should be run at build time.
153-
nbsphinx_execute = "never"
154-
nbsphinx_allow_errors = True
155-
nbsphinx_requirejs_path = ""
157+
sphinx_gallery_conf = {
158+
"examples_dirs": os.path.join(_PATH_ROOT, "examples"), # path to your example scripts
159+
"gallery_dirs": "gallery", # path to where to save gallery generated output
160+
"filename_pattern": ".",
161+
"ignore_pattern": r"__init__\.py",
162+
"example_extensions": {".py"},
163+
"line_numbers": True,
164+
"promote_jupyter_magic": True,
165+
"matplotlib_animations": True,
166+
"abort_on_example_error": True,
167+
# 'only_warn_on_example_error': True
168+
"thumbnail_size": (400, 280),
169+
}
156170

157171
myst_update_mathjax = False
158172

@@ -162,7 +176,7 @@ def _set_root_image_path(page_path: str) -> None:
162176
".rst": "restructuredtext",
163177
".txt": "markdown",
164178
".md": "markdown",
165-
".ipynb": "nbsphinx",
179+
# ".ipynb": "nbsphinx",
166180
}
167181

168182
# The master toctree document.

docs/source/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ Or directly from conda
129129

130130
pages/quickstart
131131
all-metrics
132+
gallery/index
132133
pages/overview
133134
pages/plotting
134135
pages/implement

examples/README.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
TorchMetrics' gallery
2+
=====================
3+
4+
Welcome to a comprehensive guide on leveraging TorchMetrics, that facilitates the precise and consistent evaluation of machine learning models. As an integral tool for developers and researchers, TorchMetrics offers an array of metrics critical for assessing model performance across a variety of applications. Whether you are fine-tuning a neural network, comparing model iterations, or tracking performance improvements, this page provides a gallery of real-world applications where Torch Metrics can be effectively implemented.
5+
6+
By touring through this application gallery, users can gain insights into how TorchMetrics is utilized across different sectors and scale settings, empowering them with the knowledge to implement metrics effectively in their own projects. Whether your interest lies in academic research or commercial product development, the examples provided here will help demonstrate the versatility and utility of Torch Metrics in enhancing machine learning model assessment.

examples/image/README.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Image domain
2+
============
3+
4+
Image-domain metrics are pivotal for gauging the performance of models in tasks like object detection, and segmentation. TorchMetrics provides a suite of specialized metrics designed for these purposes. Using these image-specific metrics from Torch Metrics helps in developing more precise and robust image-based models, ensuring that performance evaluations are both meaningful and directly applicable to practical vision tasks.
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
Spatial Correlation Coefficient
3+
===============================
4+
5+
The Spatial Correlation Coefficient can be applied to compare the spatial structure of two images, which can be valuable in various domains such as medical imaging, remote sensing, and quality assessment in manufacturing or design processes.
6+
7+
Let's consider a use case in medical imaging where Spatial Correlation Coefficient is used to compare the spatial correlation between a reference image and a reconstructed medical scan.
8+
This can be particularly relevant in evaluating the accuracy of image reconstruction techniques or assessing the quality of medical imaging data.
9+
"""
10+
11+
# %%
12+
# Here's a hypothetical Python example demonstrating the usage of the Spatial Correlation Coefficient to compare two medical images:
13+
14+
import matplotlib.pyplot as plt
15+
import numpy as np
16+
import torch
17+
from skimage.data import shepp_logan_phantom
18+
from skimage.transform import iradon, radon, rescale
19+
from torchmetrics.image import SpatialCorrelationCoefficient
20+
21+
# %%
22+
# Create a Shepp-Logan phantom image
23+
phantom = shepp_logan_phantom()
24+
phantom = rescale(phantom, scale=512 / 400) # Rescaling to 512x512
25+
26+
# %%
27+
# Simulate projection data (sinogram) using Radon transform
28+
theta = np.linspace(0.0, 180.0, max(phantom.shape), endpoint=False)
29+
sinogram = radon(phantom, theta=theta)
30+
31+
# %%
32+
# Perform reconstruction using the inverse Radon transform
33+
reconstruction = iradon(sinogram, theta=theta, circle=True)
34+
35+
# %%
36+
# Display the results
37+
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 4))
38+
ax1.set_title("Original")
39+
ax1.imshow(phantom, cmap=plt.cm.Greys_r)
40+
ax2.set_title("Radon transform (Sinogram)")
41+
ax2.imshow(sinogram, cmap=plt.cm.Greys_r, extent=(0, 180, 0, sinogram.shape[0]), aspect="equal")
42+
ax3.set_title("Reconstruction from sinogram")
43+
ax3.imshow(reconstruction, cmap=plt.cm.Greys_r)
44+
fig.tight_layout()
45+
46+
# %%
47+
# Convert the images to PyTorch tensors
48+
phantom_tensor = torch.from_numpy(phantom).float().unsqueeze(0).unsqueeze(0)
49+
reconstructed_tensor = torch.from_numpy(reconstruction).float().unsqueeze(0).unsqueeze(0)
50+
51+
# %%
52+
# Calculating the Spatial Correlation Coefficient
53+
scc = SpatialCorrelationCoefficient()
54+
score = scc(preds=reconstructed_tensor, target=phantom_tensor)
55+
56+
print(f"Spatial Correlation Coefficient between the images: {score}")
57+
fig.suptitle(f"Spatial Correlation Coefficient: {score:.5}", y=-0.01)

pyproject.toml

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,18 +55,24 @@ unfixable = ["F401"]
5555
[tool.ruff.lint.per-file-ignores]
5656
"setup.py" = ["ANN202", "ANN401"]
5757
"docs/source/conf.py" = ["A001", "D103"]
58+
"examples/*" = [
59+
"E501", # Line too long (XXX > 120)
60+
"D205", # 1 blank line required between summary line and description
61+
"D212", # [*] Multi-line docstring summary should start at the first line
62+
"D415", # First line should end with a period, question mark, or exclamation point
63+
]
5864
"src/**" = [
5965
"ANN401",
60-
"S310", # todo: Audit URL open for permitted schemes. Allowing use of `file:` or custom schemes is often unexpected. # todo
61-
]
66+
"S310", # todo: Audit URL open for permitted schemes. Allowing use of `file:` or custom schemes is often unexpected.
67+
]
6268
"tests/**" = [
6369
"ANN001",
6470
"ANN201",
6571
"ANN202",
6672
"ANN401",
6773
"S101",
68-
"S301", # todo: `pickle` and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue # todo
69-
]
74+
"S301", # todo: `pickle` and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue
75+
]
7076

7177
[tool.ruff.lint.pydocstyle]
7278
# Use Google-style docstrings.

requirements/_docs.txt

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
sphinx ==5.3.0
22
myst-parser ==1.0.0
3-
nbsphinx ==0.9.3
43
pandoc ==2.3
54
docutils ==0.19
65
sphinxcontrib-fulltoc >=1.0
@@ -10,6 +9,7 @@ sphinx-autodoc-typehints ==1.23.0
109
sphinx-paramlinks ==0.6.0
1110
sphinx-togglebutton ==0.3.2
1211
sphinx-copybutton ==0.5.2
12+
sphinx-gallery ==0.15.0
1313

1414
lightning >=1.8.0, <2.3.0
1515
lightning-utilities ==0.11.2
@@ -23,4 +23,9 @@ pydantic > 1.0.0, < 3.0.0
2323
-r image.txt
2424
-r multimodal.txt
2525
-r text.txt
26-
-r text_test.txt
26+
27+
# Gallery extra requirements
28+
# --------------------------
29+
# todo: until this has resolution - https://github.com/sphinx-gallery/sphinx-gallery/issues/1290
30+
# Image
31+
scikit-image ~=0.21

0 commit comments

Comments
 (0)