-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconf.py
472 lines (395 loc) · 17 KB
/
conf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# Configuration file for the Sphinx_PyAEDT documentation builder.
# -- Project information -----------------------------------------------------
import datetime
from importlib import import_module
import os
from pathlib import Path
from pprint import pformat
import shutil
from typing import Any
from sphinx.application import Sphinx
from sphinx.config import Config
from ansys_sphinx_theme import (
ansys_favicon,
ansys_logo_white,
ansys_logo_white_cropped,
latex,
watermark,
)
from docutils import nodes
from docutils.parsers.rst import Directive
import numpy as np
import pyvista
from sphinx import addnodes
from sphinx.builders.latex import LaTeXBuilder
from sphinx.util import logging
LaTeXBuilder.supported_image_types = ["image/png", "image/pdf", "image/svg+xml"]
logger = logging.getLogger(__name__)
path = Path(__file__).parent.parent.parent / "examples"
EXAMPLES_DIRECTORY = path.resolve()
REPOSITORY_NAME = "pyaedt-examples"
USERNAME = "ansys"
BRANCH = "main"
DOC_PATH = "doc/source"
project = "pyaedt-examples"
copyright = f"(c) 2021 - {datetime.datetime.now().year} ANSYS, Inc. All rights reserved"
author = "Ansys Inc."
cname = os.getenv("DOCUMENTATION_CNAME", "nocname.com")
release = version = "0.1.dev0"
# -- Connect functions (hooks) to Sphinx events -----------------------------
class PrettyPrintDirective(Directive):
"""Renders a constant using ``pprint.pformat`` and inserts into the document."""
required_arguments = 1
def run(self):
module_path, member_name = self.arguments[0].rsplit(".", 1)
member_data = getattr(import_module(module_path), member_name)
code = pformat(member_data, 2, width=68)
literal = nodes.literal_block(code, code)
literal["language"] = "python"
return [addnodes.desc_name(text=member_name), addnodes.desc_content("", literal)]
# Sphinx generic event hooks
def directory_size(directory_path: Path):
"""Compute the size (in mega bytes) of a directory.
Parameters
----------
directory_path : pathlib.Path
Path to the directory to evaluate.
"""
res = 0
for path, _, files in os.walk(directory_path):
for f in files:
fp = os.path.join(path, f)
res += os.stat(fp).st_size
# Convert in mega bytes
res /= 1e6
return res
def copy_examples_structure(app: Sphinx, config: Config):
"""Copy root directory examples structure into the doc/source/examples directory.
Everything is copied except for python file. This is because we are manually
converting them into notebook in another Sphinx hook.
Parameters
----------
app : sphinx.application.Sphinx
Sphinx instance containing all the configuration for the documentation build.
config : sphinx.config.Config
Configuration file abstraction.
"""
destination_dir = Path(app.srcdir, "examples").resolve()
logger.info(f"Copying examples structures of {EXAMPLES_DIRECTORY} into {destination_dir}.")
# NOTE: Only remove the examples directory if the workflow isn't tagged as coupling HTML and PDF build.
if not bool(int(os.getenv("SPHINXBUILD_HTML_AND_PDF_WORKFLOW", "0"))):
if os.path.exists(destination_dir):
size = directory_size(destination_dir)
logger.info(f"Directory {destination_dir} ({size} MB) already exist, removing it.")
shutil.rmtree(destination_dir, ignore_errors=True)
logger.info(f"Directory removed.")
ignore_python_files = lambda _, files: [file for file in files if file.endswith(".py")]
shutil.copytree(EXAMPLES_DIRECTORY, destination_dir, ignore=ignore_python_files, dirs_exist_ok=True)
logger.info(f"Copy performed.")
def adjust_image_path(app: Sphinx, docname, source):
"""Adjust the HTML label used to insert images in the examples.
The following path makes the examples in the root directory work:
# <img src="../../doc/source/_static/diff_via.png" width="500">
However, examples fail when used through the documentation build because
reaching the associated path should be "../../_static/diff_via.png".
Indeed, the directory ``_static`` is automatically copied into the output directory
``_build/html/_static``.
Parameters
----------
app : sphinx.application.Sphinx
Sphinx instance containing all the configuration for the documentation build.
"""
# Get the full path to the document
docpath = os.path.join(app.srcdir, docname)
# Check if this is a PY example file
if not os.path.exists(docpath + ".py") or not docname.startswith("examples"):
return
logger.info(f"Changing HTML image path in '{docname}.py' file.")
source[0] = source[0].replace("../../doc/source/_static", "../../_static")
def check_pandoc_installed(app: Sphinx, config: Config):
"""Ensure that pandoc is installed
Parameters
----------
app : sphinx.application.Sphinx
Sphinx instance containing all the configuration for the documentation build.
config : sphinx.config.Config
Configuration file abstraction.
"""
import pypandoc
try:
pandoc_path = pypandoc.get_pandoc_path()
pandoc_dir = os.path.dirname(pandoc_path)
if pandoc_dir not in os.environ["PATH"].split(os.pathsep):
logger.info("Pandoc directory is not in $PATH.")
os.environ["PATH"] += os.pathsep + pandoc_dir
logger.info(f"Pandoc directory '{pandoc_dir}' has been added to $PATH")
except OSError:
logger.error("Pandoc was not found, please add it to your path or install pypandoc-binary")
# NOTE: The list of skipped files requires to be updated every time a new example
# with GIF content is created or removed.
def skip_gif_examples_to_build_pdf(app: Sphinx):
"""Callback function for builder-inited event.
Add examples showing GIF to the list of excluded files when building PDF files.
Parameters
----------
app :
The application object representing the Sphinx process.
"""
if app.builder.name == "latex":
logger.info("Examples with animations are skipped when building with latex.")
app.config.exclude_patterns.extend(
[
r".*Maxwell2D_Transient\.py",
r".*Maxwell2D_DCConduction\.py",
r".*Hfss_Icepak_Coupling\.py",
]
)
def remove_examples(app: Sphinx, exception: None | Exception):
"""Remove the doc/source/examples directory created during documentation build.
Parameters
----------
app : sphinx.application.Sphinx
Sphinx instance containing all the configuration for the documentation build.
"""
# NOTE: Only remove the examples if the workflow isn't tagged as coupling HTML and PDF build.
if not bool(int(os.getenv("SPHINXBUILD_HTML_AND_PDF_WORKFLOW", "0"))):
destination_dir = Path(app.srcdir) / "examples"
size = directory_size(destination_dir)
logger.info(f"Removing directory {destination_dir} ({size} MB).")
shutil.rmtree(destination_dir, ignore_errors=True)
logger.info(f"Directory removed.")
def remove_doctree(app: Sphinx, exception: None | Exception):
"""Remove the .doctree directory created during the documentation build.
Parameters
----------
app : sphinx.application.Sphinx
Sphinx instance containing all the configuration for the documentation build.
exception : None or Exception
Exception raised during the build process.
"""
# NOTE: Only remove the doctree if the workflow isn't tagged as coupling HTML and PDF build.
if not bool(int(os.getenv("SPHINXBUILD_HTML_AND_PDF_WORKFLOW", "0"))):
size = directory_size(app.doctreedir)
logger.info(f"Removing doctree {app.doctreedir} ({size} MB).")
shutil.rmtree(app.doctreedir, ignore_errors=True)
logger.info(f"Doctree removed.")
def convert_examples_into_notebooks(app):
"""Convert light style script into notebooks and disable execution if needed."""
import subprocess
import nbformat
DESTINATION_DIR = Path(app.srcdir, "examples").resolve()
EXAMPLES = EXAMPLES_DIRECTORY.glob("**/*.py")
EXAMPLES_TO_NOT_EXECUTE = (
"03_gui_manipulation.py",
"05_electrothermal.py",
)
# NOTE: Only convert the examples if the workflow isn't tagged as coupling HTML and PDF build.
if not bool(int(os.getenv("SPHINXBUILD_HTML_AND_PDF_WORKFLOW", "0"))) or app.builder.name == "html":
count = 0
for example in EXAMPLES:
count += 1
example_path = str(example).split("examples" + os.sep)[-1]
notebook_path = example_path.replace(".py", ".ipynb")
output = subprocess.run(
[
"jupytext",
"--to",
"ipynb",
str(example),
"--output",
str(DESTINATION_DIR / notebook_path),
],
capture_output=True,
)
if output.returncode != 0:
logger.error(f"Error converting {example} to script")
logger.error(output.stderr)
# Disable execution if required
basename = os.path.basename(example)
if basename in EXAMPLES_TO_NOT_EXECUTE:
logger.warning(f"Disable execution of example {basename}.")
with open(str(DESTINATION_DIR / notebook_path), "r") as f:
nb = nbformat.read(f, as_version=nbformat.NO_CONVERT)
if "nbsphinx" not in nb.metadata:
nb.metadata["nbsphinx"] = {}
nb.metadata["nbsphinx"]["execute"] = "never"
with open(str(DESTINATION_DIR / notebook_path), "w", encoding="utf-8") as f:
nbformat.write(nb, f)
if count == 0:
logger.warning("No python examples found to convert to scripts")
else:
logger.info(f"Converted {count} python examples to scripts")
def setup(app):
"""Run different hook functions during the documentation build."""
app.add_directive("pprint", PrettyPrintDirective)
# Configuration inited hooks
app.connect("config-inited", check_pandoc_installed)
app.connect("config-inited", copy_examples_structure)
# Builder inited hooks
app.connect("builder-inited", convert_examples_into_notebooks)
app.connect("builder-inited", skip_gif_examples_to_build_pdf)
# Source read hook
app.connect("source-read", adjust_image_path)
# Build finished hooks
# app.connect("build-finished", remove_examples)
app.connect("build-finished", remove_doctree)
# -- General configuration ---------------------------------------------------
# Add any extension module names here as strings.
extensions = [
"sphinx.ext.graphviz",
"sphinx.ext.mathjax",
"sphinx.ext.inheritance_diagram",
"sphinx.ext.intersphinx",
"sphinx.ext.autodoc",
"sphinx.ext.todo",
"sphinx.ext.autosummary",
"sphinx.ext.coverage",
"sphinx_copybutton",
"sphinx_design",
"nbsphinx",
"recommonmark",
"numpydoc",
]
# Intersphinx mapping
intersphinx_mapping = {
"python": ("https://docs.python.org/3.11", None),
"scipy": ("https://docs.scipy.org/doc/scipy/reference", None),
"numpy": ("https://numpy.org/devdocs", None),
"matplotlib": ("https://matplotlib.org/stable", None),
"imageio": ("https://imageio.readthedocs.io/en/stable", None),
"pandas": ("https://pandas.pydata.org/pandas-docs/stable", None),
"pytest": ("https://docs.pytest.org/en/stable", None),
}
toc_object_entries_show_parents = "hide"
html_show_sourcelink = True
# numpydoc configuration
numpydoc_use_plots = True
numpydoc_show_class_members = False
numpydoc_xref_param_type = True
numpydoc_validate = True
numpydoc_validation_checks = {
# general
"GL06", # Found unknown section
"GL07", # Sections are in the wrong order.
"GL08", # The object does not have a docstring
"GL09", # Deprecation warning should precede extended summary
"GL10", # reST directives {directives} must be followed by two colons
# Return
"RT04", # Return value description should start with a capital letter"
"RT05", # Return value description should finish with "."
# Summary
"SS01", # No summary found
"SS02", # Summary does not start with a capital letter
"SS03", # Summary does not end with a period
"SS04", # Summary contains heading whitespaces
"SS05", # Summary must start with infinitive verb, not third person
# Parameters
"PR10", # Parameter "{param_name}" requires a space before the colon
# separating the parameter name and type",
}
# Copy button customization ---------------------------------------------------
# exclude traditional Python prompts from the copied code
copybutton_prompt_text = r">>> ?|\.\.\. "
copybutton_prompt_is_regexp = True
# The language for content autogenerated.
language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = [
"conf.py",
]
# -- Options for HTML output -------------------------------------------------
source_suffix = {".rst": "restructuredtext", ".md": "markdown"}
# The master toctree document.
master_doc = "index"
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# Execute notebooks before conversion
nbsphinx_execute = "always"
# Allow errors to help debug.
nbsphinx_allow_errors = False
# NbSphinx customization
nbsphinx_thumbnails = {
"examples/01-Modeling-Setup/Configurations": "_static/thumbnails/configuration_file_icepak.png",
"examples/01-Modeling-Setup/CoordinateSystem": "_static/thumbnails/coordinate_system.png",
"examples/01-Modeling-Setup/Polyline_Primitives": "_static/thumbnails/polyline.png",
"examples/02-HFSS/HFSS_FSS_unitcell": "_static/thumbnails/unitcell.png",
"examples/04-Layout/hfss_3d_layout/03_gui_manipulation": "_static/thumbnails/user_interface.png",
"examples/08-Circuit/Circuit_Siwave_Multizones": "_static/thumbnails/multizone.png",
"examples/08-Circuit/Circuit_Subcircuit_Example": "_static/thumbnails/subcircuit.png",
"examples/08-Circuit/Create_Netlist": "_static/thumbnails/netlist.png",
"examples/09-Multiphysics/Circuit_HFSS_Icepak_Coupling": "_static/thumbnails/ring.png",
"examples/10-EMIT/ComputeInterferenceType": "_static/thumbnails/interference.png",
"examples/10-EMIT/ComputeProtectionLevels": "_static/thumbnails/protection.png",
"examples/10-EMIT/EMIT_Example": "_static/thumbnails/emit.png",
"examples/10-EMIT/EMIT_HFSS_Example": "_static/thumbnails/emit_hfss.png",
"examples/11-twin_builder/static_rom_creation_and_visualization": "_static/thumbnails/static_rom.png",
"examples/12-general/com_analysis": "_static/thumbnails/com_eye.png",
}
nbsphinx_custom_formats = {
".py": ["jupytext.reads", {"fmt": ""}],
}
# Pyvista customization
# Must be less than or equal to the XVFB window size
pyvista.global_theme["window_size"] = np.array([1024, 768])
# Save figures in specified directory
pyvista.FIGURE_PATH = os.path.join(os.path.abspath("./images/"), "auto-generated/")
if not os.path.exists(pyvista.FIGURE_PATH):
os.makedirs(pyvista.FIGURE_PATH)
# -- Options for HTML output -------------------------------------------------
html_short_title = html_title = "PyAEDT Examples"
html_theme = "ansys_sphinx_theme"
html_favicon = ansys_favicon
html_context = {
"display_github": True, # Integrate GitHub
"github_user": USERNAME,
"github_repo": REPOSITORY_NAME,
"github_version": BRANCH,
"doc_path": DOC_PATH,
}
# specify the location of your github repo
html_theme_options = {
"logo": "ansys",
"github_url": f"https://github.com/{USERNAME}/{REPOSITORY_NAME}",
"show_prev_next": False,
"collapse_navigation": True,
"use_edit_page_button": True,
"show_breadcrumbs": True,
"additional_breadcrumbs": [
("PyAnsys", "https://docs.pyansys.com/"),
("PyAEDT", "https://aedt.docs.pyansys.com/"),
],
"icon_links": [
{
"name": "Support",
"url": f"https://github.com/{USERNAME}/{REPOSITORY_NAME}/discussions",
"icon": "fa fa-comment fa-fw",
},
],
}
html_static_path = ["_static"]
# These paths are either relative to html_static_path
# or fully qualified paths (eg. https://...)
html_css_files = [
"css/custom.css",
"css/highlight.css",
]
# -- Options for LaTeX output ------------------------------------------------
# additional logos for the latex coverpage
latex_additional_files = [watermark, ansys_logo_white, ansys_logo_white_cropped]
# change the preamble of latex with customized title page
# variables are the title of pdf, watermark
latex_elements = {"preamble": latex.generate_preamble(html_title)}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
f"{project}.tex",
f"{project} documentation",
author,
"manual",
),
]