Skip to content

DOCS: Refactor examples #1260

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

Merged
merged 21 commits into from
Jul 31, 2025
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
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
4 changes: 2 additions & 2 deletions .github/workflows/ci_cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -585,10 +585,10 @@ jobs:

doc-build:
name: Documentation
runs-on: public-ubuntu-latest-8-cores
runs-on: public-ubuntu-latest-16-cores
container:
image: ${{ needs.revn-variations.outputs.test_container }}
options: --entrypoint /bin/bash
options: --shm-size=2g --entrypoint /bin/bash
needs: [style, doc-style, revn-variations, container-stability-check]

steps:
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ repos:
tests/scripts/run_python_error.py |
tests/scripts/run_python_success.py |
tests/scripts/log_message.py |
examples/embedding_n_remote/embedding_remote.py
examples/.*$
)$

- repo: https://github.com/pre-commit/pre-commit-hooks
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/1260.documentation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Refactor examples
18 changes: 13 additions & 5 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import warnings

from ansys_sphinx_theme import ansys_favicon, get_version_match
import pyvista
from pyvista.plotting.utilities.sphinx_gallery import DynamicScraper
from sphinx_gallery.sorting import FileNameSortKey

import ansys.mechanical.core as pymechanical
Expand All @@ -21,6 +23,13 @@
# necessary when building the sphinx gallery
pymechanical.BUILDING_GALLERY = True

# Ensure that offscreen rendering is used for docs generation
pyvista.OFF_SCREEN = True

# necessary when building the sphinx gallery
pyvista.BUILDING_GALLERY = True


# Whether or not to build the cheatsheet
BUILD_CHEATSHEET = True if os.environ.get("BUILD_EXAMPLES", "true") == "true" else False

Expand Down Expand Up @@ -60,6 +69,8 @@
"sphinx_autodoc_typehints",
"sphinx_copybutton",
"sphinx_design",
"pyvista.ext.plot_directive",
"pyvista.ext.viewer_directive",
]

if pymechanical.BUILDING_GALLERY:
Expand Down Expand Up @@ -175,8 +186,7 @@
# path to your examples scripts
"examples_dirs": ["../../examples/"],
# path where to save gallery generated examples
"gallery_dirs": ["examples/gallery_examples"],
# Pattern to search for example files
"gallery_dirs": ["examples/gallery_examples"], # Pattern to search for example files
"filename_pattern": r"\.py",
# Remove the "Download all examples" button from the top level gallery
"download_all_examples": False,
Expand All @@ -186,7 +196,7 @@
"backreferences_dir": None,
# Modules for which function level galleries are created. In
"doc_module": "ansys-mechanical-core",
"image_scrapers": ("matplotlib"),
"image_scrapers": (DynamicScraper(), "matplotlib"),
"ignore_pattern": "flycheck*",
"thumbnail_size": (350, 350),
}
Expand Down Expand Up @@ -229,7 +239,6 @@
"sidebar_pages": ["changelog", "index"],
},
"ansys_sphinx_theme_autoapi": {"project": project, "templates": "_templates/autoapi"},
"navigation_depth": 10,
}

if BUILD_CHEATSHEET:
Expand All @@ -245,7 +254,6 @@

html_sidebars = {
"changelog": [],
"examples/index": [],
"contributing": [],
}

Expand Down
31 changes: 14 additions & 17 deletions doc/source/examples/index.rst
Original file line number Diff line number Diff line change
@@ -1,30 +1,27 @@
.. _ref_examples:

========
Examples
========

Here are examples using Mechanical with the ``ansys-mechanical-core`` library through
an embedded instance or remote session.
Here is a series of examples using Mechanical with the ``ansys-mechanical-core`` library.

.. grid:: 1 2 2 2
.. === EXAMPLES Gallery ===

.. grid-item-card:: Embedding Examples
:padding: 2 2 2 2
:link: https://embedding.examples.mechanical.docs.pyansys.com/examples/index.html
..
We have to include this rather than include it in a tree.

Uses PyMechanical to embed an instance of Mechanical directly within Python as a Python object.
.. include:: gallery_examples/index.rst
:start-line: 2

.. grid-item-card:: Remote Session Examples
:padding: 2 2 2 2
:link: https://examples.mechanical.docs.pyansys.com/examples/index.html
.. === REMOTE SESSIONS EXAMPLES ===

Uses PyMechanical as a client to a remote Mechanical instance.
.. toctree::
:hidden:
:maxdepth: 3

.. grid:: 1
Remote Sessions <https://examples.mechanical.docs.pyansys.com/index.html>

.. grid-item-card:: Embedding Instance & Remote Session Example
:padding: 2 2 2 2
:link: gallery_examples/embedding_n_remote/embedding_remote.html

Demonstrates the same model setup in both an embedded instance and remote session,
as well as examples using a combination of embedded instances and remote sessions.
.. include:: remote_session_examples/index.rst
:start-line: 2
8 changes: 8 additions & 0 deletions doc/source/examples/remote_session_examples/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.. _ref_remote_session_examples:

Remote session examples
------------------------

Remote session examples demonstrate the basic simulation capabilities of Mechanical using remote sessions.

For more information, see `Remote sessions examples <pymechanical_remote_ex_all_>`_.
3 changes: 3 additions & 0 deletions examples/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
00_utilities/out/
01_basic/out/
02_advanced/out/
5 changes: 5 additions & 0 deletions examples/00_utilities/readme.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Utilities
---------

This section showcases some of the useful functions that can be used
with PyMechanical.
78 changes: 78 additions & 0 deletions examples/00_utilities/tips_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

""".. _ref_tips_01:

3D visualization
----------------
localtoc
The following example demonstrates how to visualize imported geometry in 3D.
"""

# %%
# Import the necessary libraries
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

from ansys.mechanical.core import App
from ansys.mechanical.core.examples import delete_downloads, download_file

# %%
# Initialize the embedded application
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

app = App(globals=globals())
print(app)

# %%
# Download and import the geometry file
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# %%
# Download the geometry file
geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding")

# %%
# Define the model and import the geometry file
model = app.Model

geometry_import = model.GeometryImportGroup.AddGeometryImport()
geometry_import.Import(geometry_path)

# %%
# Visualize the model in 3D
# ~~~~~~~~~~~~~~~~~~~~~~~~~

app.plot()

# %%
# .. note::
# This visualization is currently available only for geometry and on version 24R2 or later

# %%
# Clean up the files and app
# ~~~~~~~~~~~~~~~~~~~~~~~~~~

# Delete the downloaded files
delete_downloads()

# Close the app
app.close()
139 changes: 139 additions & 0 deletions examples/00_utilities/tips_02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

""".. _ref_tips_02:

Export image
------------

The following example demonstrates how to export an image of the imported geometry
and display it using matplotlib.
"""

# %%
# Import the necessary libraries
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

from pathlib import Path

from ansys.mechanical.core import App
from ansys.mechanical.core.examples import delete_downloads, download_file

# %%
# Initialize the embedded application
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Create an instance of the App class
app = App(globals=globals())

# Print the app to ensure it is working
print(app)

# %%
# Download and import the geometry file
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# %%
# Download the geometry file
geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding")

# %%
# Import the geometry file

geometry_import = Model.GeometryImportGroup.AddGeometryImport()
geometry_import.Import(geometry_path)

# %%
# Configure graphics for image export
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Set the orientation of the camera
ExtAPI.Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso)

# Set the image export format
image_export_format = GraphicsImageExportFormat.PNG

# Configure the export settings for the image
settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings()
settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution
settings_720p.Background = GraphicsBackgroundType.White
settings_720p.Width = 1280
settings_720p.Height = 720
settings_720p.CurrentGraphicsDisplay = False

# Rotate the geometry on the Y-axis
Graphics.Camera.Rotate(180, CameraAxisType.ScreenY)

# %%
# Create a function to display the image
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

from matplotlib import image as mpimg
from matplotlib import pyplot as plt

# Directory to save the image
output_path = Path.cwd() / "out"


def display_image(image_name) -> None:
"""Display the image using matplotlib.

Parameters
----------
image_name : str
The name of the image file to display.
"""
# Create the full path to the image
image_path = output_path / image_name

# Plot the figure and display the image
plt.figure(figsize=(16, 9))
plt.imshow(mpimg.imread(str(image_path)))
plt.xticks([])
plt.yticks([])
plt.axis("off")
plt.show()


# %%
# Export and display the image
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Fit the geometry in the viewing area
Graphics.Camera.SetFit()

# Export the image
geometry_image = output_path / "geometry.png"
Graphics.ExportImage(str(geometry_image), image_export_format, settings_720p)

# Display the image
display_image(geometry_image.name)

# %%
# Clean up the downloaded files and app
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Delete the downloaded files
delete_downloads()

# Close the app
app.close()
Loading
Loading