From 97eadf23b51f0f853c977b7cca285c298e9cbcfa Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Thu, 20 Mar 2025 09:31:16 -0500 Subject: [PATCH 01/18] test only embedded --- doc/source/index.rst | 4 +- examples/embedding_n_remote/README.txt | 7 +- .../embedding_n_remote/embedding_remote.py | 118 ------------------ 3 files changed, 5 insertions(+), 124 deletions(-) diff --git a/doc/source/index.rst b/doc/source/index.rst index f425395e2..d45287ac5 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -32,7 +32,7 @@ Python API to interact with `Ansys Mechanical`_ (FEA software for structural eng .. grid-item-card:: Examples :fa:`scroll` :padding: 2 2 2 2 - :link: examples/index + :link: examples/gallery_examples/index :link-type: doc Dive into examples created using PyMechanical. @@ -110,7 +110,7 @@ Python API to interact with `Ansys Mechanical`_ (FEA software for structural eng :maxdepth: 3 getting_started/index - examples/index + examples/gallery_examples/index user_guide_session/index user_guide_embedding/index user_guide_scripting/index diff --git a/examples/embedding_n_remote/README.txt b/examples/embedding_n_remote/README.txt index c7653224b..cfbc8e3bf 100644 --- a/examples/embedding_n_remote/README.txt +++ b/examples/embedding_n_remote/README.txt @@ -1,5 +1,4 @@ -Embedding and Remote Session Example -==================================== +Examples +======== -This code, which uses the same example, first demonstrates how to use -an embedding instance and then demonstrates how to use a remote session. \ No newline at end of file +Simple example to demonstrates how to use PyMechanical. \ No newline at end of file diff --git a/examples/embedding_n_remote/embedding_remote.py b/examples/embedding_n_remote/embedding_remote.py index 50a3f82a9..9d84e7977 100644 --- a/examples/embedding_n_remote/embedding_remote.py +++ b/examples/embedding_n_remote/embedding_remote.py @@ -29,124 +29,6 @@ """ -############################################################################### -# -------------- -# Remote Session -# -------------- - - -############################################################################### -# Download required files -# ~~~~~~~~~~~~~~~~~~~~~~~ -# Download the required files. Print the file paths for the geometry file and -# script file. - -import os - -from ansys.mechanical.core import launch_mechanical -from ansys.mechanical.core.examples import download_file - -geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") -print(f"Downloaded the geometry file to: {geometry_path}") - -script_file_path = download_file("remote_script.py", "pymechanical", "embedding") -print(f"Downloaded the script file to: {script_file_path}") - - -############################################################################### -# -# Launch Mechanical -# ~~~~~~~~~~~~~~~~~ -# Launch a new Mechanical session in batch, setting ``cleanup_on_exit`` to -# ``False``. To close this Mechanical session when finished, this example -# must call the ``mechanical.exit()`` method. - -import os - -from ansys.mechanical.core import launch_mechanical - -# Launch mechanical -mechanical = launch_mechanical(batch=True, loglevel="DEBUG") -print(mechanical) - - -############################################################################### -# Initialize variable for workflow -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Set the ``part_file_path`` variable on the server for later use. -# Make this variable compatible for Windows, Linux, and Docker containers. - -project_directory = mechanical.project_directory -print(f"project directory = {project_directory}") - -# Upload the file to the project directory. -mechanical.upload(file_name=geometry_path, file_location_destination=project_directory) - -# Build the path relative to project directory. -base_name = os.path.basename(geometry_path) -combined_path = os.path.join(project_directory, base_name) -part_file_path = combined_path.replace("\\", "\\\\") -mechanical.run_python_script(f"part_file_path='{part_file_path}'") - -# Verify the path -result = mechanical.run_python_script("part_file_path") -print(f"part_file_path on server: {result}") - - -############################################################################### -# Run mechanical automation script -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Run remote_script.py in the mechanical remote session. - -mechanical.run_python_script_from_file(script_file_path) - - -############################################################################### -# Get list of generated files -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -list_files = mechanical.list_files() -for file in list_files: - print(file) - - -############################################################################### -# Write the file contents to console -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -def write_file_contents_to_console(path, number_lines=-1): - count = 1 - with open(path, "rt") as file: - for line in file: - if number_lines == -1 or count <= number_lines: - print(line, end="") - count = count + 1 - else: - break - - -############################################################################### -# Download files back to local working directory -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -dest_dir = "download" -dest_dir = os.path.join(os.getcwd(), dest_dir) -for file in list_files: - downloaded = mechanical.download(file, target_dir=dest_dir) - if file.endswith(".out"): - print("contents of ", downloaded, " : ") - write_file_contents_to_console(downloaded[0], number_lines=-1) - - -############################################################################### -# Exit remote session -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Close the Mechanical instance. - -mechanical.exit() - -############################################################################### # ----------------- # Embedded Instance # ----------------- From 51e6e9e653925fec20e1985e36b2684ff19f4844 Mon Sep 17 00:00:00 2001 From: pyansys-ci-bot <92810346+pyansys-ci-bot@users.noreply.github.com> Date: Thu, 20 Mar 2025 15:33:14 +0000 Subject: [PATCH 02/18] chore: adding changelog file 1125.test.md [dependabot-skip] --- doc/changelog.d/1125.test.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 doc/changelog.d/1125.test.md diff --git a/doc/changelog.d/1125.test.md b/doc/changelog.d/1125.test.md new file mode 100644 index 000000000..df929e776 --- /dev/null +++ b/doc/changelog.d/1125.test.md @@ -0,0 +1 @@ +example refactor \ No newline at end of file From deeb8ce5a624afa52b8ac432d7fa59a5688b51aa Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Thu, 20 Mar 2025 11:41:43 -0500 Subject: [PATCH 03/18] test 3d plot --- doc/source/conf.py | 6 +++++- examples/embedding_n_remote/embedding_remote.py | 6 +----- pyproject.toml | 4 ++++ 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/doc/source/conf.py b/doc/source/conf.py index d7c994454..052fbc4d6 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -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 @@ -20,6 +22,8 @@ # necessary when building the sphinx gallery pymechanical.BUILDING_GALLERY = True +pyvista.BUILDING_GALLERY = True +pyvista.OFF_SCREEN = True # Whether or not to build the cheatsheet BUILD_CHEATSHEET = True @@ -175,7 +179,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), } diff --git a/examples/embedding_n_remote/embedding_remote.py b/examples/embedding_n_remote/embedding_remote.py index 9d84e7977..93354d187 100644 --- a/examples/embedding_n_remote/embedding_remote.py +++ b/examples/embedding_n_remote/embedding_remote.py @@ -29,10 +29,6 @@ """ -# ----------------- -# Embedded Instance -# ----------------- - ############################################################################### # Download the geometry file @@ -76,7 +72,7 @@ geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() geometry_import_preferences.ProcessNamedSelections = True geometry_import.Import(geometry_file, geometry_import_format, geometry_import_preferences) - +app.plot() ############################################################################### # Assign material diff --git a/pyproject.toml b/pyproject.toml index c12b0d854..d7d8944fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -81,6 +81,10 @@ doc = [ "sphinx-notfound-page==1.1.0", "sphinxcontrib-websupport==2.0.0", "sphinxemoji==0.3.1", + "pyvista[jupyter]>=0.39.1", + "ipyvtklink==0.2.3", + "ansys-tools-visualization-interface>=0.2.6", + "usd-core==24.11" ] viz = [ "ansys-tools-visualization-interface>=0.2.6", From ef449a7b7094118587d421d76af20596f1546283 Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Mon, 24 Mar 2025 09:34:41 -0500 Subject: [PATCH 04/18] add tips --- .pre-commit-config.yaml | 2 +- examples/00_tips/readme.txt | 5 ++ examples/00_tips/tips_01.py | 75 ++++++++++++++++++++++ examples/00_tips/tips_02.py | 120 ++++++++++++++++++++++++++++++++++++ examples/00_tips/tips_03.py | 76 +++++++++++++++++++++++ 5 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 examples/00_tips/readme.txt create mode 100644 examples/00_tips/tips_01.py create mode 100644 examples/00_tips/tips_02.py create mode 100644 examples/00_tips/tips_03.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index bd9332426..02af1d846 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -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 diff --git a/examples/00_tips/readme.txt b/examples/00_tips/readme.txt new file mode 100644 index 000000000..2439d4a82 --- /dev/null +++ b/examples/00_tips/readme.txt @@ -0,0 +1,5 @@ +Tips +==== + +This section showcases some of the useful functions that can be used +in PyMechanical embedding workflow. diff --git a/examples/00_tips/tips_01.py b/examples/00_tips/tips_01.py new file mode 100644 index 000000000..05d58dfc2 --- /dev/null +++ b/examples/00_tips/tips_01.py @@ -0,0 +1,75 @@ +# 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 +---------------- + +Visualize 3D imported geometry +""" + +# %% +# Import necessary libraries +# ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +from ansys.mechanical.core import App +from ansys.mechanical.core.examples import delete_downloads, download_file + +# %% +# Embed mechanical and set global variables + +app = App() +app.update_globals(globals()) +print(app) + + +# %% +# Download and import geometry +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Download geometry + +geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") + +# %% +# Import geometry + +geometry_import = Model.GeometryImportGroup.AddGeometryImport() +geometry_import.Import(geometry_path) + +# %% +# Visualize in 3D +# ~~~~~~~~~~~~~~~ + +app.plot() + +# %% +# .. note:: +# This visualization is currently available only for geometry and on version 24R2 or later + +# %% +# Cleanup +# ~~~~~~~ + +delete_downloads() +app.new() diff --git a/examples/00_tips/tips_02.py b/examples/00_tips/tips_02.py new file mode 100644 index 000000000..4982998e0 --- /dev/null +++ b/examples/00_tips/tips_02.py @@ -0,0 +1,120 @@ +# 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 +------------ + +Export image and display +""" + +# %% +# Import necessary libraries +# ~~~~~~~~~~~~~~~~~~~~~~~~~~ + +import os + +from ansys.mechanical.core import App +from ansys.mechanical.core.examples import delete_downloads, download_file + +# %% +# Embed Mechanical and set global variables + +app = App() +app.update_globals(globals()) +print(app) + + +# %% +# Download and import geometry +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Download geometry + +geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") + +# %% +# Import geometry + +geometry_import = Model.GeometryImportGroup.AddGeometryImport() +geometry_import.Import(geometry_path) + +# %% +# Configure graphics for image export +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# Orientation +Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) + +# Export format +image_export_format = GraphicsImageExportFormat.PNG + +# Resolution and background +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 if needed +ExtAPI.Graphics.Camera.Rotate(180, CameraAxisType.ScreenY) + + +# %% +# Custom function for displaying the image +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +from matplotlib import image as mpimg +from matplotlib import pyplot as plt + +# Temporary directory to save the image +cwd = os.path.join(os.getcwd(), "out") + + +def display_image(image_name): + plt.figure(figsize=(16, 9)) + plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) + plt.xticks([]) + plt.yticks([]) + plt.axis("off") + plt.show() + + +# %% +# Export and display the image +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# Fits the geometry in the viewing area +Graphics.Camera.SetFit() + +Graphics.ExportImage(os.path.join(cwd, "geometry.png"), image_export_format, settings_720p) + +# Display the image using matplotlib +display_image("geometry.png") + +# %% +# Cleanup +# ~~~~~~~ + +delete_downloads() +app.new() diff --git a/examples/00_tips/tips_03.py b/examples/00_tips/tips_03.py new file mode 100644 index 000000000..fddffaf27 --- /dev/null +++ b/examples/00_tips/tips_03.py @@ -0,0 +1,76 @@ +# 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_03: + +Project tree +-------------------- + +Display the heirarchial Mechanical project structure. +""" + +# %% +# Import necessary libraries +# ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +from ansys.mechanical.core import App +from ansys.mechanical.core.examples import delete_downloads, download_file + +# %% +# Embed Mechanical and set global variables + +app = App() +app.update_globals(globals()) +print(app) + + +# %% +# Download the mechdb file +# ~~~~~~~~~~~~~~~~~~~~~~~~ + +mechdb_path = download_file("graphics_test.mechdb", "pymechanical", "test_files") + +# %% +# Load the mechdb file inside Mechanical + +app.open(mechdb_path) + +# %% +# Display the project tree +# ~~~~~~~~~~~~~~~~~~~~~~~~ + +app.print_tree() + +# %% +# Display the tree only under the first analysis +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +app.print_tree(Model.Analyses[0]) + + +# %% +# Cleanup +# ~~~~~~~ + +delete_downloads() +app.new() From 08b57f17de79baa255d3dbae388a9a085636afba Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Thu, 27 Mar 2025 10:09:34 -0500 Subject: [PATCH 05/18] update globals --- examples/embedding_n_remote/embedding_remote.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/embedding_n_remote/embedding_remote.py b/examples/embedding_n_remote/embedding_remote.py index 93354d187..4e5098318 100644 --- a/examples/embedding_n_remote/embedding_remote.py +++ b/examples/embedding_n_remote/embedding_remote.py @@ -37,7 +37,7 @@ import os -import ansys.mechanical.core as mech +from ansys.mechanical.core import App from ansys.mechanical.core.examples import download_file geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") @@ -50,7 +50,8 @@ # Find the mechanical installation path & version. # Open an embedded instance of Mechanical and set global variables. -app = mech.App(globals=globals()) +app = App() +app.update_globals(globals()) print(app) From c24a764d452ef9a9903edfba580492797625fc2d Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Mon, 31 Mar 2025 10:27:36 -0500 Subject: [PATCH 06/18] update dep --- .github/workflows/ci_cd.yml | 2 +- pyproject.toml | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml index 8016aec42..351dc3117 100644 --- a/.github/workflows/ci_cd.yml +++ b/.github/workflows/ci_cd.yml @@ -634,7 +634,7 @@ jobs: run: | . /env/bin/activate pip install uv - uv pip install -e .[doc] + uv pip install -e .[doc,viz] - name: Build docs env: diff --git a/pyproject.toml b/pyproject.toml index d7d8944fa..cb69422e1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -85,6 +85,8 @@ doc = [ "ipyvtklink==0.2.3", "ansys-tools-visualization-interface>=0.2.6", "usd-core==24.11" + "pyvista[jupyter]>=0.39.1", + "ipyvtklink==0.2.3", ] viz = [ "ansys-tools-visualization-interface>=0.2.6", From 214f426b10893601b409002c89fcc428ae4c3b35 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 31 Mar 2025 15:28:48 +0000 Subject: [PATCH 07/18] chore: auto fixes from pre-commit hooks --- doc/source/conf.py | 7 +++--- src/ansys/mechanical/core/__init__.py | 17 ++++++-------- src/ansys/mechanical/core/embedding/app.py | 11 +++++---- .../mechanical/core/embedding/background.py | 2 +- .../mechanical/core/embedding/cleanup_gui.py | 2 +- .../mechanical/core/embedding/imports.py | 12 ++-------- .../mechanical/core/embedding/initializer.py | 4 ++-- .../core/embedding/logger/__init__.py | 3 ++- .../mechanical/core/embedding/rpc/__init__.py | 5 +--- .../mechanical/core/embedding/rpc/client.py | 3 ++- .../mechanical/core/embedding/rpc/server.py | 4 ++-- .../mechanical/core/embedding/runtime.py | 2 +- src/ansys/mechanical/core/embedding/ui.py | 7 +++--- .../core/embedding/viz/embedding_plotter.py | 2 +- src/ansys/mechanical/core/errors.py | 2 +- src/ansys/mechanical/core/ide_config.py | 2 +- src/ansys/mechanical/core/launcher.py | 1 - src/ansys/mechanical/core/logging.py | 4 ++-- src/ansys/mechanical/core/mechanical.py | 23 +++++++------------ src/ansys/mechanical/core/misc.py | 2 +- src/ansys/mechanical/core/pool.py | 13 ++++------- src/ansys/mechanical/core/run.py | 5 ++-- tests/conftest.py | 4 ++-- tests/embedding/test_app.py | 8 +++---- tests/embedding/test_app_libraries.py | 2 +- tests/embedding/test_appdata.py | 2 +- tests/test_cli.py | 7 +++--- tests/test_logging.py | 2 +- tests/test_mechanical.py | 2 +- 29 files changed, 70 insertions(+), 90 deletions(-) diff --git a/doc/source/conf.py b/doc/source/conf.py index 052fbc4d6..68e207f01 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -8,17 +8,18 @@ # -- Path setup -------------------------------------------------------------- -from datetime import datetime import os import warnings +from datetime import datetime -from ansys_sphinx_theme import ansys_favicon, get_version_match import pyvista +from ansys_sphinx_theme import ansys_favicon, get_version_match from pyvista.plotting.utilities.sphinx_gallery import DynamicScraper from sphinx_gallery.sorting import FileNameSortKey import ansys.mechanical.core as pymechanical -from ansys.mechanical.core.embedding.initializer import SUPPORTED_MECHANICAL_EMBEDDING_VERSIONS +from ansys.mechanical.core.embedding.initializer import \ + SUPPORTED_MECHANICAL_EMBEDDING_VERSIONS # necessary when building the sphinx gallery pymechanical.BUILDING_GALLERY = True diff --git a/src/ansys/mechanical/core/__init__.py b/src/ansys/mechanical/core/__init__.py index 3a4d86edf..dd1a59ad9 100644 --- a/src/ansys/mechanical/core/__init__.py +++ b/src/ansys/mechanical/core/__init__.py @@ -24,8 +24,8 @@ import logging import os -from ansys.tools.path import find_mechanical import appdirs +from ansys.tools.path import find_mechanical USER_DATA_PATH = appdirs.user_data_dir(appname="ansys_mechanical_core", appauthor="Ansys") """User data directory.""" @@ -46,16 +46,13 @@ from ansys.mechanical.core._version import __version__ - # import few classes / functions -from ansys.mechanical.core.mechanical import ( - Mechanical, - change_default_mechanical_path, - close_all_local_instances, - connect_to_mechanical, - get_mechanical_path, - launch_mechanical, -) +from ansys.mechanical.core.mechanical import (Mechanical, + change_default_mechanical_path, + close_all_local_instances, + connect_to_mechanical, + get_mechanical_path, + launch_mechanical) try: from ansys.mechanical.core.embedding import App, global_variables diff --git a/src/ansys/mechanical/core/embedding/app.py b/src/ansys/mechanical/core/embedding/app.py index e6339b70a..1869b4756 100644 --- a/src/ansys/mechanical/core/embedding/app.py +++ b/src/ansys/mechanical/core/embedding/app.py @@ -25,19 +25,21 @@ import atexit import os -from pathlib import Path import shutil import typing import warnings +from pathlib import Path from ansys.mechanical.core import LOG from ansys.mechanical.core.embedding import initializer, runtime from ansys.mechanical.core.embedding.addins import AddinConfiguration from ansys.mechanical.core.embedding.appdata import UniqueUserProfile -from ansys.mechanical.core.embedding.imports import global_entry_points, global_variables +from ansys.mechanical.core.embedding.imports import (global_entry_points, + global_variables) from ansys.mechanical.core.embedding.poster import Poster from ansys.mechanical.core.embedding.ui import launch_ui -from ansys.mechanical.core.embedding.warnings import connect_warnings, disconnect_warnings +from ansys.mechanical.core.embedding.warnings import (connect_warnings, + disconnect_warnings) if typing.TYPE_CHECKING: # Make sure to run ``ansys-mechanical-ideconfig`` to add the autocomplete settings to VS Code @@ -403,7 +405,8 @@ def plotter(self) -> None: # TODO Check if anything loaded inside app or else show warning and return - from ansys.mechanical.core.embedding.viz.embedding_plotter import to_plotter + from ansys.mechanical.core.embedding.viz.embedding_plotter import \ + to_plotter return to_plotter(self) diff --git a/src/ansys/mechanical/core/embedding/background.py b/src/ansys/mechanical/core/embedding/background.py index e834126b0..368b8acf1 100644 --- a/src/ansys/mechanical/core/embedding/background.py +++ b/src/ansys/mechanical/core/embedding/background.py @@ -28,9 +28,9 @@ import typing import ansys.mechanical.core as mech +import ansys.mechanical.core.embedding.utils as utils from ansys.mechanical.core.embedding import initializer from ansys.mechanical.core.embedding.poster import Poster -import ansys.mechanical.core.embedding.utils as utils def _exit(background_app: "BackgroundApp"): diff --git a/src/ansys/mechanical/core/embedding/cleanup_gui.py b/src/ansys/mechanical/core/embedding/cleanup_gui.py index 511f72e0b..b402bdca8 100644 --- a/src/ansys/mechanical/core/embedding/cleanup_gui.py +++ b/src/ansys/mechanical/core/embedding/cleanup_gui.py @@ -21,10 +21,10 @@ # SOFTWARE. """Clean up temporary mechdb files after GUI is closed.""" -from pathlib import Path import shutil import sys import time +from pathlib import Path import psutil diff --git a/src/ansys/mechanical/core/embedding/imports.py b/src/ansys/mechanical/core/embedding/imports.py index 179e9743c..4dbeaad04 100644 --- a/src/ansys/mechanical/core/embedding/imports.py +++ b/src/ansys/mechanical/core/embedding/imports.py @@ -55,16 +55,8 @@ def global_variables(app: "ansys.mechanical.core.App", enums: bool = False) -> t # Import modules if the app is initialized if is_initialized(): from ansys.mechanical.core.embedding.global_importer import ( - Ansys, - MechanicalEnums, - Point, - Point2D, - Point3D, - Quantity, - SectionPlane, - System, - Vector3D, - ) + Ansys, MechanicalEnums, Point, Point2D, Point3D, Quantity, + SectionPlane, System, Vector3D) vars["Quantity"] = Quantity vars["System"] = System diff --git a/src/ansys/mechanical/core/embedding/initializer.py b/src/ansys/mechanical/core/embedding/initializer.py index 51e97795a..c6e371d02 100644 --- a/src/ansys/mechanical/core/embedding/initializer.py +++ b/src/ansys/mechanical/core/embedding/initializer.py @@ -21,12 +21,12 @@ # SOFTWARE. """Initializer for Mechanical embedding. Sets up paths and resolvers.""" -from importlib.metadata import distribution import os -from pathlib import Path import platform import sys import warnings +from importlib.metadata import distribution +from pathlib import Path from ansys.mechanical.core.embedding.loader import load_clr from ansys.mechanical.core.embedding.resolver import resolve diff --git a/src/ansys/mechanical/core/embedding/logger/__init__.py b/src/ansys/mechanical/core/embedding/logger/__init__.py index 9b7ac8100..c4523b309 100644 --- a/src/ansys/mechanical/core/embedding/logger/__init__.py +++ b/src/ansys/mechanical/core/embedding/logger/__init__.py @@ -53,7 +53,8 @@ import typing from ansys.mechanical.core.embedding import initializer -from ansys.mechanical.core.embedding.logger import environ, linux_api, sinks, windows_api +from ansys.mechanical.core.embedding.logger import (environ, linux_api, sinks, + windows_api) LOGGING_SINKS: typing.Set[int] = set() """Constant for logging sinks.""" diff --git a/src/ansys/mechanical/core/embedding/rpc/__init__.py b/src/ansys/mechanical/core/embedding/rpc/__init__.py index 2fb3584f1..986239346 100644 --- a/src/ansys/mechanical/core/embedding/rpc/__init__.py +++ b/src/ansys/mechanical/core/embedding/rpc/__init__.py @@ -23,10 +23,7 @@ """RPC and Mechanical service implementation.""" from .client import Client from .default_server import DefaultServiceMethods, MechanicalDefaultServer -from .server import ( - MechanicalEmbeddedServer, - MechanicalService, -) +from .server import MechanicalEmbeddedServer, MechanicalService from .utils import get_remote_methods, remote_method # todo - combine Server and MechanicalService diff --git a/src/ansys/mechanical/core/embedding/rpc/client.py b/src/ansys/mechanical/core/embedding/rpc/client.py index a364c9952..f89d53f8e 100644 --- a/src/ansys/mechanical/core/embedding/rpc/client.py +++ b/src/ansys/mechanical/core/embedding/rpc/client.py @@ -27,7 +27,8 @@ import rpyc -from ansys.mechanical.core.embedding.rpc.utils import PYMECHANICAL_DEFAULT_RPC_PORT +from ansys.mechanical.core.embedding.rpc.utils import \ + PYMECHANICAL_DEFAULT_RPC_PORT from ansys.mechanical.core.mechanical import DEFAULT_CHUNK_SIZE diff --git a/src/ansys/mechanical/core/embedding/rpc/server.py b/src/ansys/mechanical/core/embedding/rpc/server.py index 85d9abb92..26c884243 100644 --- a/src/ansys/mechanical/core/embedding/rpc/server.py +++ b/src/ansys/mechanical/core/embedding/rpc/server.py @@ -27,12 +27,12 @@ import typing import rpyc -from rpyc.utils.server import ThreadedServer import toolz +from rpyc.utils.server import ThreadedServer +import ansys.mechanical.core.embedding.utils from ansys.mechanical.core.embedding.app import App from ansys.mechanical.core.embedding.background import BackgroundApp -import ansys.mechanical.core.embedding.utils from .utils import MethodType, get_free_port, get_remote_methods diff --git a/src/ansys/mechanical/core/embedding/runtime.py b/src/ansys/mechanical/core/embedding/runtime.py index e61ef46ad..d3c503773 100644 --- a/src/ansys/mechanical/core/embedding/runtime.py +++ b/src/ansys/mechanical/core/embedding/runtime.py @@ -22,8 +22,8 @@ """Runtime initialize for pythonnet in embedding.""" -from importlib.metadata import distribution import os +from importlib.metadata import distribution from ansys.mechanical.core.embedding.logger import Logger diff --git a/src/ansys/mechanical/core/embedding/ui.py b/src/ansys/mechanical/core/embedding/ui.py index 77418039a..262d14eab 100644 --- a/src/ansys/mechanical/core/embedding/ui.py +++ b/src/ansys/mechanical/core/embedding/ui.py @@ -21,14 +21,13 @@ # SOFTWARE. """Run Mechanical UI from Python.""" +import sys +import tempfile +import typing from pathlib import Path - # Subprocess is needed to launch the GUI and clean up the process on close. # Excluding bandit check. from subprocess import Popen # nosec: B404 -import sys -import tempfile -import typing class UILauncher: diff --git a/src/ansys/mechanical/core/embedding/viz/embedding_plotter.py b/src/ansys/mechanical/core/embedding/viz/embedding_plotter.py index ab03db7f1..2210a743d 100644 --- a/src/ansys/mechanical/core/embedding/viz/embedding_plotter.py +++ b/src/ansys/mechanical/core/embedding/viz/embedding_plotter.py @@ -29,9 +29,9 @@ import Ansys # isort: skip -from ansys.tools.visualization_interface import Plotter import numpy as np import pyvista as pv +from ansys.tools.visualization_interface import Plotter from .utils import bgr_to_rgb_tuple, get_nodes_and_coords diff --git a/src/ansys/mechanical/core/errors.py b/src/ansys/mechanical/core/errors.py index b3d53a9d2..3ee45d105 100644 --- a/src/ansys/mechanical/core/errors.py +++ b/src/ansys/mechanical/core/errors.py @@ -22,9 +22,9 @@ """PyMechanical-specific errors.""" -from functools import wraps import signal import threading +from functools import wraps from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous diff --git a/src/ansys/mechanical/core/ide_config.py b/src/ansys/mechanical/core/ide_config.py index b6c8b1597..1b5b7adf9 100644 --- a/src/ansys/mechanical/core/ide_config.py +++ b/src/ansys/mechanical/core/ide_config.py @@ -24,11 +24,11 @@ import json import os -from pathlib import Path import re import site import sys import warnings +from pathlib import Path import ansys.tools.path as atp import click diff --git a/src/ansys/mechanical/core/launcher.py b/src/ansys/mechanical/core/launcher.py index f1514adb7..b21b543eb 100644 --- a/src/ansys/mechanical/core/launcher.py +++ b/src/ansys/mechanical/core/launcher.py @@ -23,7 +23,6 @@ """Launch Mechanical in batch or UI mode.""" import errno import os - # Subprocess is needed to start the backend. Excluding bandit check. import subprocess # nosec: B404 diff --git a/src/ansys/mechanical/core/logging.py b/src/ansys/mechanical/core/logging.py index c2a323157..3d111a133 100644 --- a/src/ansys/mechanical/core/logging.py +++ b/src/ansys/mechanical/core/logging.py @@ -130,11 +130,11 @@ """ -from copy import copy -from datetime import datetime import logging import sys import weakref +from copy import copy +from datetime import datetime # Default configuration LOG_LEVEL = logging.DEBUG diff --git a/src/ansys/mechanical/core/mechanical.py b/src/ansys/mechanical/core/mechanical.py index c659b02a9..8a17f3e51 100644 --- a/src/ansys/mechanical/core/mechanical.py +++ b/src/ansys/mechanical/core/mechanical.py @@ -22,10 +22,8 @@ """Connect to Mechanical gRPC server and issues commands.""" import atexit -from contextlib import closing import datetime import fnmatch -from functools import wraps import glob import os import pathlib @@ -35,9 +33,11 @@ import threading import time import typing -from typing import Optional import warnings import weakref +from contextlib import closing +from functools import wraps +from typing import Optional import ansys.api.mechanical.v0.mechanical_pb2 as mechanical_pb2 import ansys.api.mechanical.v0.mechanical_pb2_grpc as mechanical_pb2_grpc @@ -46,19 +46,12 @@ import ansys.mechanical.core as pymechanical from ansys.mechanical.core import LOG -from ansys.mechanical.core.errors import ( - MechanicalExitedError, - MechanicalRuntimeError, - VersionError, - protect_grpc, -) +from ansys.mechanical.core.errors import (MechanicalExitedError, + MechanicalRuntimeError, VersionError, + protect_grpc) from ansys.mechanical.core.launcher import MechanicalLauncher -from ansys.mechanical.core.misc import ( - check_valid_ip, - check_valid_port, - check_valid_start_instance, - threaded, -) +from ansys.mechanical.core.misc import (check_valid_ip, check_valid_port, + check_valid_start_instance, threaded) # Check if PyPIM is installed try: diff --git a/src/ansys/mechanical/core/misc.py b/src/ansys/mechanical/core/misc.py index eecb68cf7..356e20503 100644 --- a/src/ansys/mechanical/core/misc.py +++ b/src/ansys/mechanical/core/misc.py @@ -22,9 +22,9 @@ """Contain miscellaneous functions and methods at the module level.""" -from functools import wraps import os import socket +from functools import wraps from threading import Thread diff --git a/src/ansys/mechanical/core/pool.py b/src/ansys/mechanical/core/pool.py index 17fb2bf79..c8f718c7c 100644 --- a/src/ansys/mechanical/core/pool.py +++ b/src/ansys/mechanical/core/pool.py @@ -29,15 +29,10 @@ from ansys.tools.path import version_from_path from ansys.mechanical.core.errors import VersionError -from ansys.mechanical.core.mechanical import ( - _HAS_ANSYS_PIM, - _HAS_TQDM, - LOG, - MECHANICAL_DEFAULT_PORT, - get_mechanical_path, - launch_mechanical, - port_in_use, -) +from ansys.mechanical.core.mechanical import (_HAS_ANSYS_PIM, _HAS_TQDM, LOG, + MECHANICAL_DEFAULT_PORT, + get_mechanical_path, + launch_mechanical, port_in_use) from ansys.mechanical.core.misc import threaded, threaded_daemon if _HAS_TQDM: diff --git a/src/ansys/mechanical/core/run.py b/src/ansys/mechanical/core/run.py index ea6ea7ece..426f3cccf 100644 --- a/src/ansys/mechanical/core/run.py +++ b/src/ansys/mechanical/core/run.py @@ -23,17 +23,18 @@ """Convenience CLI to run mechanical.""" import asyncio -from asyncio.subprocess import PIPE import os import sys import typing import warnings +from asyncio.subprocess import PIPE import ansys.tools.path as atp import click from ansys.mechanical.core.embedding.appdata import UniqueUserProfile -from ansys.mechanical.core.feature_flags import get_command_line_arguments, get_feature_flag_names +from ansys.mechanical.core.feature_flags import (get_command_line_arguments, + get_feature_flag_names) DRY_RUN = False """Dry run constant.""" diff --git a/tests/conftest.py b/tests/conftest.py index 3c78d3f11..4e0570f6a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,24 +23,24 @@ import datetime import os import pathlib -from pathlib import Path import platform import shutil import subprocess import sys import time +from pathlib import Path import ansys.tools.path as atp import pytest import ansys.mechanical.core as pymechanical +import ansys.mechanical.core.run from ansys.mechanical.core import LocalMechanicalPool from ansys.mechanical.core._version import SUPPORTED_MECHANICAL_VERSIONS from ansys.mechanical.core.embedding.addins import AddinConfiguration from ansys.mechanical.core.errors import MechanicalExitedError from ansys.mechanical.core.examples import download_file from ansys.mechanical.core.misc import get_mechanical_bin -import ansys.mechanical.core.run # to run tests with multiple markers # pytest -q --collect-only -m "remote_session_launch" diff --git a/tests/embedding/test_app.py b/tests/embedding/test_app.py index 6a5b33a49..eb337cd11 100644 --- a/tests/embedding/test_app.py +++ b/tests/embedding/test_app.py @@ -22,19 +22,19 @@ """Miscellaneous embedding tests""" import os -from pathlib import Path import shutil import subprocess import sys -from tempfile import NamedTemporaryFile import time +from pathlib import Path +from tempfile import NamedTemporaryFile import pytest +import ansys.mechanical.core.embedding.utils as utils from ansys.mechanical.core.embedding.app import is_initialized from ansys.mechanical.core.embedding.cleanup_gui import cleanup_gui from ansys.mechanical.core.embedding.ui import _launch_ui -import ansys.mechanical.core.embedding.utils as utils @pytest.mark.embedding @@ -59,8 +59,8 @@ def test_deprecation_warning(embedded_app): @pytest.mark.embedding def test_app_save_open(embedded_app, tmp_path: pytest.TempPathFactory): """Test save and open of the Application class.""" - import System import clr # noqa: F401 + import System # save without a save_as throws an exception with pytest.raises(System.Exception): diff --git a/tests/embedding/test_app_libraries.py b/tests/embedding/test_app_libraries.py index 842f4e6e3..5d667f8db 100644 --- a/tests/embedding/test_app_libraries.py +++ b/tests/embedding/test_app_libraries.py @@ -25,8 +25,8 @@ import os import sys -from ansys.tools.path import get_mechanical_path import pytest +from ansys.tools.path import get_mechanical_path from ansys.mechanical.core.embedding import add_mechanical_python_libraries diff --git a/tests/embedding/test_appdata.py b/tests/embedding/test_appdata.py index a18a79daf..8d5ab1093 100644 --- a/tests/embedding/test_appdata.py +++ b/tests/embedding/test_appdata.py @@ -23,8 +23,8 @@ """Embedding tests related to app data""" import os -from pathlib import Path import sys +from pathlib import Path from unittest import mock import pytest diff --git a/tests/test_cli.py b/tests/test_cli.py index de0e76183..6818ee7f8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -21,16 +21,17 @@ # SOFTWARE. import os -from pathlib import Path import subprocess import sys +from pathlib import Path import ansys.tools.path as atp -from click.testing import CliRunner import pytest +from click.testing import CliRunner from ansys.mechanical.core.ide_config import cli as ideconfig_cli -from ansys.mechanical.core.ide_config import get_stubs_location, get_stubs_versions +from ansys.mechanical.core.ide_config import (get_stubs_location, + get_stubs_versions) from ansys.mechanical.core.run import _cli_impl STUBS_LOC = get_stubs_location() diff --git a/tests/test_logging.py b/tests/test_logging.py index 270e75b8c..a52b02850 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -26,10 +26,10 @@ import re import pytest +from conftest import HAS_GRPC from ansys.mechanical.core import LOG # Global logger from ansys.mechanical.core import logging -from conftest import HAS_GRPC ## Notes # Use the next fixtures for: diff --git a/tests/test_mechanical.py b/tests/test_mechanical.py index b60ff24ee..0a127b590 100644 --- a/tests/test_mechanical.py +++ b/tests/test_mechanical.py @@ -26,12 +26,12 @@ import re import ansys.tools.path +import conftest import pytest import ansys.mechanical.core as pymechanical import ansys.mechanical.core.errors as errors import ansys.mechanical.core.misc as misc -import conftest @pytest.mark.remote_session_connect From ca95c3a0892b9577a2f09b717a2e5d7a0b10cd82 Mon Sep 17 00:00:00 2001 From: klmcadams <58492561+klmcadams@users.noreply.github.com> Date: Mon, 31 Mar 2025 16:43:20 -0400 Subject: [PATCH 08/18] add -e to xvfb-run for error logging --- .github/workflows/ci_cd.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml index 351dc3117..34dd68a4d 100644 --- a/.github/workflows/ci_cd.yml +++ b/.github/workflows/ci_cd.yml @@ -400,9 +400,9 @@ jobs: run: | . /env/bin/activate if [ "${{ needs.container-stability-check.outputs.container_stable_exit }}" = "true" ]; then - xvfb-run mechanical-env pytest -m embedding -s --junitxml test_results${{ matrix.python-version }}.xml + xvfb-run -e mechanical-env pytest -m embedding -s --junitxml test_results${{ matrix.python-version }}.xml else - xvfb-run mechanical-env pytest -m embedding -s --junitxml test_results${{ matrix.python-version }}.xml || true + xvfb-run -e mechanical-env pytest -m embedding -s --junitxml test_results${{ matrix.python-version }}.xml || true fi - name: Upload coverage results @@ -652,9 +652,9 @@ jobs: output_file=doc_$1_output.txt if [ "${{ needs.container-stability-check.outputs.container_stable_exit }}" = "true" ]; then - xvfb-run mechanical-env make -C doc $1 + xvfb-run -e mechanical-env make -C doc $1 else - xvfb-run mechanical-env make -C doc $1 > $output_file 2>&1 || true + xvfb-run -e mechanical-env make -C doc $1 > $output_file 2>&1 || true cat $output_file echo done running make validate_output $output_file From 870828f030b5029ec2343fdf0c6f90ff0cf97be2 Mon Sep 17 00:00:00 2001 From: klmcadams <58492561+klmcadams@users.noreply.github.com> Date: Tue, 1 Apr 2025 11:01:20 -0400 Subject: [PATCH 09/18] fix pyproject.toml --- pyproject.toml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index cb69422e1..bb7a32034 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,7 +53,7 @@ tests = [ "pytest==8.3.5", "pytest-cov==6.0.0", "pytest-print==1.1.0", - "psutil==7.0.0" + "psutil==7.0.0", ] doc = [ "sphinx==8.2.3", @@ -84,9 +84,7 @@ doc = [ "pyvista[jupyter]>=0.39.1", "ipyvtklink==0.2.3", "ansys-tools-visualization-interface>=0.2.6", - "usd-core==24.11" - "pyvista[jupyter]>=0.39.1", - "ipyvtklink==0.2.3", + "usd-core==24.11", ] viz = [ "ansys-tools-visualization-interface>=0.2.6", From 5d90eeb362506d095c1eaa1299a8b618c3477c44 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 15:02:11 +0000 Subject: [PATCH 10/18] chore: auto fixes from pre-commit hooks --- doc/source/conf.py | 7 +++--- src/ansys/mechanical/core/__init__.py | 17 ++++++++------ src/ansys/mechanical/core/embedding/app.py | 11 ++++----- .../mechanical/core/embedding/background.py | 2 +- .../mechanical/core/embedding/cleanup_gui.py | 2 +- .../mechanical/core/embedding/imports.py | 12 ++++++++-- .../mechanical/core/embedding/initializer.py | 4 ++-- .../core/embedding/logger/__init__.py | 3 +-- .../mechanical/core/embedding/rpc/client.py | 3 +-- .../mechanical/core/embedding/rpc/server.py | 4 ++-- .../mechanical/core/embedding/runtime.py | 2 +- src/ansys/mechanical/core/embedding/ui.py | 7 +++--- .../core/embedding/viz/embedding_plotter.py | 2 +- src/ansys/mechanical/core/errors.py | 2 +- src/ansys/mechanical/core/ide_config.py | 2 +- src/ansys/mechanical/core/launcher.py | 1 + src/ansys/mechanical/core/logging.py | 4 ++-- src/ansys/mechanical/core/mechanical.py | 23 ++++++++++++------- src/ansys/mechanical/core/misc.py | 2 +- src/ansys/mechanical/core/pool.py | 13 +++++++---- src/ansys/mechanical/core/run.py | 5 ++-- tests/conftest.py | 4 ++-- tests/embedding/test_app.py | 8 +++---- tests/embedding/test_app_libraries.py | 2 +- tests/embedding/test_appdata.py | 2 +- tests/test_cli.py | 7 +++--- tests/test_logging.py | 2 +- tests/test_mechanical.py | 2 +- 28 files changed, 86 insertions(+), 69 deletions(-) diff --git a/doc/source/conf.py b/doc/source/conf.py index 68e207f01..052fbc4d6 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -8,18 +8,17 @@ # -- Path setup -------------------------------------------------------------- +from datetime import datetime import os import warnings -from datetime import datetime -import pyvista 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 -from ansys.mechanical.core.embedding.initializer import \ - SUPPORTED_MECHANICAL_EMBEDDING_VERSIONS +from ansys.mechanical.core.embedding.initializer import SUPPORTED_MECHANICAL_EMBEDDING_VERSIONS # necessary when building the sphinx gallery pymechanical.BUILDING_GALLERY = True diff --git a/src/ansys/mechanical/core/__init__.py b/src/ansys/mechanical/core/__init__.py index dd1a59ad9..3a4d86edf 100644 --- a/src/ansys/mechanical/core/__init__.py +++ b/src/ansys/mechanical/core/__init__.py @@ -24,8 +24,8 @@ import logging import os -import appdirs from ansys.tools.path import find_mechanical +import appdirs USER_DATA_PATH = appdirs.user_data_dir(appname="ansys_mechanical_core", appauthor="Ansys") """User data directory.""" @@ -46,13 +46,16 @@ from ansys.mechanical.core._version import __version__ + # import few classes / functions -from ansys.mechanical.core.mechanical import (Mechanical, - change_default_mechanical_path, - close_all_local_instances, - connect_to_mechanical, - get_mechanical_path, - launch_mechanical) +from ansys.mechanical.core.mechanical import ( + Mechanical, + change_default_mechanical_path, + close_all_local_instances, + connect_to_mechanical, + get_mechanical_path, + launch_mechanical, +) try: from ansys.mechanical.core.embedding import App, global_variables diff --git a/src/ansys/mechanical/core/embedding/app.py b/src/ansys/mechanical/core/embedding/app.py index 1869b4756..e6339b70a 100644 --- a/src/ansys/mechanical/core/embedding/app.py +++ b/src/ansys/mechanical/core/embedding/app.py @@ -25,21 +25,19 @@ import atexit import os +from pathlib import Path import shutil import typing import warnings -from pathlib import Path from ansys.mechanical.core import LOG from ansys.mechanical.core.embedding import initializer, runtime from ansys.mechanical.core.embedding.addins import AddinConfiguration from ansys.mechanical.core.embedding.appdata import UniqueUserProfile -from ansys.mechanical.core.embedding.imports import (global_entry_points, - global_variables) +from ansys.mechanical.core.embedding.imports import global_entry_points, global_variables from ansys.mechanical.core.embedding.poster import Poster from ansys.mechanical.core.embedding.ui import launch_ui -from ansys.mechanical.core.embedding.warnings import (connect_warnings, - disconnect_warnings) +from ansys.mechanical.core.embedding.warnings import connect_warnings, disconnect_warnings if typing.TYPE_CHECKING: # Make sure to run ``ansys-mechanical-ideconfig`` to add the autocomplete settings to VS Code @@ -405,8 +403,7 @@ def plotter(self) -> None: # TODO Check if anything loaded inside app or else show warning and return - from ansys.mechanical.core.embedding.viz.embedding_plotter import \ - to_plotter + from ansys.mechanical.core.embedding.viz.embedding_plotter import to_plotter return to_plotter(self) diff --git a/src/ansys/mechanical/core/embedding/background.py b/src/ansys/mechanical/core/embedding/background.py index 368b8acf1..e834126b0 100644 --- a/src/ansys/mechanical/core/embedding/background.py +++ b/src/ansys/mechanical/core/embedding/background.py @@ -28,9 +28,9 @@ import typing import ansys.mechanical.core as mech -import ansys.mechanical.core.embedding.utils as utils from ansys.mechanical.core.embedding import initializer from ansys.mechanical.core.embedding.poster import Poster +import ansys.mechanical.core.embedding.utils as utils def _exit(background_app: "BackgroundApp"): diff --git a/src/ansys/mechanical/core/embedding/cleanup_gui.py b/src/ansys/mechanical/core/embedding/cleanup_gui.py index b402bdca8..511f72e0b 100644 --- a/src/ansys/mechanical/core/embedding/cleanup_gui.py +++ b/src/ansys/mechanical/core/embedding/cleanup_gui.py @@ -21,10 +21,10 @@ # SOFTWARE. """Clean up temporary mechdb files after GUI is closed.""" +from pathlib import Path import shutil import sys import time -from pathlib import Path import psutil diff --git a/src/ansys/mechanical/core/embedding/imports.py b/src/ansys/mechanical/core/embedding/imports.py index 4dbeaad04..179e9743c 100644 --- a/src/ansys/mechanical/core/embedding/imports.py +++ b/src/ansys/mechanical/core/embedding/imports.py @@ -55,8 +55,16 @@ def global_variables(app: "ansys.mechanical.core.App", enums: bool = False) -> t # Import modules if the app is initialized if is_initialized(): from ansys.mechanical.core.embedding.global_importer import ( - Ansys, MechanicalEnums, Point, Point2D, Point3D, Quantity, - SectionPlane, System, Vector3D) + Ansys, + MechanicalEnums, + Point, + Point2D, + Point3D, + Quantity, + SectionPlane, + System, + Vector3D, + ) vars["Quantity"] = Quantity vars["System"] = System diff --git a/src/ansys/mechanical/core/embedding/initializer.py b/src/ansys/mechanical/core/embedding/initializer.py index c6e371d02..51e97795a 100644 --- a/src/ansys/mechanical/core/embedding/initializer.py +++ b/src/ansys/mechanical/core/embedding/initializer.py @@ -21,12 +21,12 @@ # SOFTWARE. """Initializer for Mechanical embedding. Sets up paths and resolvers.""" +from importlib.metadata import distribution import os +from pathlib import Path import platform import sys import warnings -from importlib.metadata import distribution -from pathlib import Path from ansys.mechanical.core.embedding.loader import load_clr from ansys.mechanical.core.embedding.resolver import resolve diff --git a/src/ansys/mechanical/core/embedding/logger/__init__.py b/src/ansys/mechanical/core/embedding/logger/__init__.py index c4523b309..9b7ac8100 100644 --- a/src/ansys/mechanical/core/embedding/logger/__init__.py +++ b/src/ansys/mechanical/core/embedding/logger/__init__.py @@ -53,8 +53,7 @@ import typing from ansys.mechanical.core.embedding import initializer -from ansys.mechanical.core.embedding.logger import (environ, linux_api, sinks, - windows_api) +from ansys.mechanical.core.embedding.logger import environ, linux_api, sinks, windows_api LOGGING_SINKS: typing.Set[int] = set() """Constant for logging sinks.""" diff --git a/src/ansys/mechanical/core/embedding/rpc/client.py b/src/ansys/mechanical/core/embedding/rpc/client.py index f89d53f8e..a364c9952 100644 --- a/src/ansys/mechanical/core/embedding/rpc/client.py +++ b/src/ansys/mechanical/core/embedding/rpc/client.py @@ -27,8 +27,7 @@ import rpyc -from ansys.mechanical.core.embedding.rpc.utils import \ - PYMECHANICAL_DEFAULT_RPC_PORT +from ansys.mechanical.core.embedding.rpc.utils import PYMECHANICAL_DEFAULT_RPC_PORT from ansys.mechanical.core.mechanical import DEFAULT_CHUNK_SIZE diff --git a/src/ansys/mechanical/core/embedding/rpc/server.py b/src/ansys/mechanical/core/embedding/rpc/server.py index 26c884243..85d9abb92 100644 --- a/src/ansys/mechanical/core/embedding/rpc/server.py +++ b/src/ansys/mechanical/core/embedding/rpc/server.py @@ -27,12 +27,12 @@ import typing import rpyc -import toolz from rpyc.utils.server import ThreadedServer +import toolz -import ansys.mechanical.core.embedding.utils from ansys.mechanical.core.embedding.app import App from ansys.mechanical.core.embedding.background import BackgroundApp +import ansys.mechanical.core.embedding.utils from .utils import MethodType, get_free_port, get_remote_methods diff --git a/src/ansys/mechanical/core/embedding/runtime.py b/src/ansys/mechanical/core/embedding/runtime.py index d3c503773..e61ef46ad 100644 --- a/src/ansys/mechanical/core/embedding/runtime.py +++ b/src/ansys/mechanical/core/embedding/runtime.py @@ -22,8 +22,8 @@ """Runtime initialize for pythonnet in embedding.""" -import os from importlib.metadata import distribution +import os from ansys.mechanical.core.embedding.logger import Logger diff --git a/src/ansys/mechanical/core/embedding/ui.py b/src/ansys/mechanical/core/embedding/ui.py index 262d14eab..77418039a 100644 --- a/src/ansys/mechanical/core/embedding/ui.py +++ b/src/ansys/mechanical/core/embedding/ui.py @@ -21,13 +21,14 @@ # SOFTWARE. """Run Mechanical UI from Python.""" -import sys -import tempfile -import typing from pathlib import Path + # Subprocess is needed to launch the GUI and clean up the process on close. # Excluding bandit check. from subprocess import Popen # nosec: B404 +import sys +import tempfile +import typing class UILauncher: diff --git a/src/ansys/mechanical/core/embedding/viz/embedding_plotter.py b/src/ansys/mechanical/core/embedding/viz/embedding_plotter.py index 2210a743d..ab03db7f1 100644 --- a/src/ansys/mechanical/core/embedding/viz/embedding_plotter.py +++ b/src/ansys/mechanical/core/embedding/viz/embedding_plotter.py @@ -29,9 +29,9 @@ import Ansys # isort: skip +from ansys.tools.visualization_interface import Plotter import numpy as np import pyvista as pv -from ansys.tools.visualization_interface import Plotter from .utils import bgr_to_rgb_tuple, get_nodes_and_coords diff --git a/src/ansys/mechanical/core/errors.py b/src/ansys/mechanical/core/errors.py index 3ee45d105..b3d53a9d2 100644 --- a/src/ansys/mechanical/core/errors.py +++ b/src/ansys/mechanical/core/errors.py @@ -22,9 +22,9 @@ """PyMechanical-specific errors.""" +from functools import wraps import signal import threading -from functools import wraps from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous diff --git a/src/ansys/mechanical/core/ide_config.py b/src/ansys/mechanical/core/ide_config.py index 1b5b7adf9..b6c8b1597 100644 --- a/src/ansys/mechanical/core/ide_config.py +++ b/src/ansys/mechanical/core/ide_config.py @@ -24,11 +24,11 @@ import json import os +from pathlib import Path import re import site import sys import warnings -from pathlib import Path import ansys.tools.path as atp import click diff --git a/src/ansys/mechanical/core/launcher.py b/src/ansys/mechanical/core/launcher.py index b21b543eb..f1514adb7 100644 --- a/src/ansys/mechanical/core/launcher.py +++ b/src/ansys/mechanical/core/launcher.py @@ -23,6 +23,7 @@ """Launch Mechanical in batch or UI mode.""" import errno import os + # Subprocess is needed to start the backend. Excluding bandit check. import subprocess # nosec: B404 diff --git a/src/ansys/mechanical/core/logging.py b/src/ansys/mechanical/core/logging.py index 3d111a133..c2a323157 100644 --- a/src/ansys/mechanical/core/logging.py +++ b/src/ansys/mechanical/core/logging.py @@ -130,11 +130,11 @@ """ +from copy import copy +from datetime import datetime import logging import sys import weakref -from copy import copy -from datetime import datetime # Default configuration LOG_LEVEL = logging.DEBUG diff --git a/src/ansys/mechanical/core/mechanical.py b/src/ansys/mechanical/core/mechanical.py index 8a17f3e51..c659b02a9 100644 --- a/src/ansys/mechanical/core/mechanical.py +++ b/src/ansys/mechanical/core/mechanical.py @@ -22,8 +22,10 @@ """Connect to Mechanical gRPC server and issues commands.""" import atexit +from contextlib import closing import datetime import fnmatch +from functools import wraps import glob import os import pathlib @@ -33,11 +35,9 @@ import threading import time import typing +from typing import Optional import warnings import weakref -from contextlib import closing -from functools import wraps -from typing import Optional import ansys.api.mechanical.v0.mechanical_pb2 as mechanical_pb2 import ansys.api.mechanical.v0.mechanical_pb2_grpc as mechanical_pb2_grpc @@ -46,12 +46,19 @@ import ansys.mechanical.core as pymechanical from ansys.mechanical.core import LOG -from ansys.mechanical.core.errors import (MechanicalExitedError, - MechanicalRuntimeError, VersionError, - protect_grpc) +from ansys.mechanical.core.errors import ( + MechanicalExitedError, + MechanicalRuntimeError, + VersionError, + protect_grpc, +) from ansys.mechanical.core.launcher import MechanicalLauncher -from ansys.mechanical.core.misc import (check_valid_ip, check_valid_port, - check_valid_start_instance, threaded) +from ansys.mechanical.core.misc import ( + check_valid_ip, + check_valid_port, + check_valid_start_instance, + threaded, +) # Check if PyPIM is installed try: diff --git a/src/ansys/mechanical/core/misc.py b/src/ansys/mechanical/core/misc.py index 356e20503..eecb68cf7 100644 --- a/src/ansys/mechanical/core/misc.py +++ b/src/ansys/mechanical/core/misc.py @@ -22,9 +22,9 @@ """Contain miscellaneous functions and methods at the module level.""" +from functools import wraps import os import socket -from functools import wraps from threading import Thread diff --git a/src/ansys/mechanical/core/pool.py b/src/ansys/mechanical/core/pool.py index c8f718c7c..17fb2bf79 100644 --- a/src/ansys/mechanical/core/pool.py +++ b/src/ansys/mechanical/core/pool.py @@ -29,10 +29,15 @@ from ansys.tools.path import version_from_path from ansys.mechanical.core.errors import VersionError -from ansys.mechanical.core.mechanical import (_HAS_ANSYS_PIM, _HAS_TQDM, LOG, - MECHANICAL_DEFAULT_PORT, - get_mechanical_path, - launch_mechanical, port_in_use) +from ansys.mechanical.core.mechanical import ( + _HAS_ANSYS_PIM, + _HAS_TQDM, + LOG, + MECHANICAL_DEFAULT_PORT, + get_mechanical_path, + launch_mechanical, + port_in_use, +) from ansys.mechanical.core.misc import threaded, threaded_daemon if _HAS_TQDM: diff --git a/src/ansys/mechanical/core/run.py b/src/ansys/mechanical/core/run.py index 426f3cccf..ea6ea7ece 100644 --- a/src/ansys/mechanical/core/run.py +++ b/src/ansys/mechanical/core/run.py @@ -23,18 +23,17 @@ """Convenience CLI to run mechanical.""" import asyncio +from asyncio.subprocess import PIPE import os import sys import typing import warnings -from asyncio.subprocess import PIPE import ansys.tools.path as atp import click from ansys.mechanical.core.embedding.appdata import UniqueUserProfile -from ansys.mechanical.core.feature_flags import (get_command_line_arguments, - get_feature_flag_names) +from ansys.mechanical.core.feature_flags import get_command_line_arguments, get_feature_flag_names DRY_RUN = False """Dry run constant.""" diff --git a/tests/conftest.py b/tests/conftest.py index 4e0570f6a..3c78d3f11 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,24 +23,24 @@ import datetime import os import pathlib +from pathlib import Path import platform import shutil import subprocess import sys import time -from pathlib import Path import ansys.tools.path as atp import pytest import ansys.mechanical.core as pymechanical -import ansys.mechanical.core.run from ansys.mechanical.core import LocalMechanicalPool from ansys.mechanical.core._version import SUPPORTED_MECHANICAL_VERSIONS from ansys.mechanical.core.embedding.addins import AddinConfiguration from ansys.mechanical.core.errors import MechanicalExitedError from ansys.mechanical.core.examples import download_file from ansys.mechanical.core.misc import get_mechanical_bin +import ansys.mechanical.core.run # to run tests with multiple markers # pytest -q --collect-only -m "remote_session_launch" diff --git a/tests/embedding/test_app.py b/tests/embedding/test_app.py index eb337cd11..6a5b33a49 100644 --- a/tests/embedding/test_app.py +++ b/tests/embedding/test_app.py @@ -22,19 +22,19 @@ """Miscellaneous embedding tests""" import os +from pathlib import Path import shutil import subprocess import sys -import time -from pathlib import Path from tempfile import NamedTemporaryFile +import time import pytest -import ansys.mechanical.core.embedding.utils as utils from ansys.mechanical.core.embedding.app import is_initialized from ansys.mechanical.core.embedding.cleanup_gui import cleanup_gui from ansys.mechanical.core.embedding.ui import _launch_ui +import ansys.mechanical.core.embedding.utils as utils @pytest.mark.embedding @@ -59,8 +59,8 @@ def test_deprecation_warning(embedded_app): @pytest.mark.embedding def test_app_save_open(embedded_app, tmp_path: pytest.TempPathFactory): """Test save and open of the Application class.""" - import clr # noqa: F401 import System + import clr # noqa: F401 # save without a save_as throws an exception with pytest.raises(System.Exception): diff --git a/tests/embedding/test_app_libraries.py b/tests/embedding/test_app_libraries.py index 5d667f8db..842f4e6e3 100644 --- a/tests/embedding/test_app_libraries.py +++ b/tests/embedding/test_app_libraries.py @@ -25,8 +25,8 @@ import os import sys -import pytest from ansys.tools.path import get_mechanical_path +import pytest from ansys.mechanical.core.embedding import add_mechanical_python_libraries diff --git a/tests/embedding/test_appdata.py b/tests/embedding/test_appdata.py index 8d5ab1093..a18a79daf 100644 --- a/tests/embedding/test_appdata.py +++ b/tests/embedding/test_appdata.py @@ -23,8 +23,8 @@ """Embedding tests related to app data""" import os -import sys from pathlib import Path +import sys from unittest import mock import pytest diff --git a/tests/test_cli.py b/tests/test_cli.py index 6818ee7f8..de0e76183 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -21,17 +21,16 @@ # SOFTWARE. import os +from pathlib import Path import subprocess import sys -from pathlib import Path import ansys.tools.path as atp -import pytest from click.testing import CliRunner +import pytest from ansys.mechanical.core.ide_config import cli as ideconfig_cli -from ansys.mechanical.core.ide_config import (get_stubs_location, - get_stubs_versions) +from ansys.mechanical.core.ide_config import get_stubs_location, get_stubs_versions from ansys.mechanical.core.run import _cli_impl STUBS_LOC = get_stubs_location() diff --git a/tests/test_logging.py b/tests/test_logging.py index a52b02850..270e75b8c 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -26,10 +26,10 @@ import re import pytest -from conftest import HAS_GRPC from ansys.mechanical.core import LOG # Global logger from ansys.mechanical.core import logging +from conftest import HAS_GRPC ## Notes # Use the next fixtures for: diff --git a/tests/test_mechanical.py b/tests/test_mechanical.py index 0a127b590..b60ff24ee 100644 --- a/tests/test_mechanical.py +++ b/tests/test_mechanical.py @@ -26,12 +26,12 @@ import re import ansys.tools.path -import conftest import pytest import ansys.mechanical.core as pymechanical import ansys.mechanical.core.errors as errors import ansys.mechanical.core.misc as misc +import conftest @pytest.mark.remote_session_connect From 1794a23f3d237bff735d83e8c8ab806f9273e573 Mon Sep 17 00:00:00 2001 From: klmcadams <58492561+klmcadams@users.noreply.github.com> Date: Tue, 1 Apr 2025 11:19:14 -0400 Subject: [PATCH 11/18] remove duplicate dependencies --- pyproject.toml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index bb7a32034..329dc731b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,8 +83,6 @@ doc = [ "sphinxemoji==0.3.1", "pyvista[jupyter]>=0.39.1", "ipyvtklink==0.2.3", - "ansys-tools-visualization-interface>=0.2.6", - "usd-core==24.11", ] viz = [ "ansys-tools-visualization-interface>=0.2.6", From 72dda2ede05127f79a9fc432dd3f8342913c48de Mon Sep 17 00:00:00 2001 From: klmcadams <58492561+klmcadams@users.noreply.github.com> Date: Tue, 1 Apr 2025 11:30:33 -0400 Subject: [PATCH 12/18] remove -e --- .github/workflows/ci_cd.yml | 8 ++++---- src/ansys/mechanical/core/embedding/initializer.py | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml index 34dd68a4d..351dc3117 100644 --- a/.github/workflows/ci_cd.yml +++ b/.github/workflows/ci_cd.yml @@ -400,9 +400,9 @@ jobs: run: | . /env/bin/activate if [ "${{ needs.container-stability-check.outputs.container_stable_exit }}" = "true" ]; then - xvfb-run -e mechanical-env pytest -m embedding -s --junitxml test_results${{ matrix.python-version }}.xml + xvfb-run mechanical-env pytest -m embedding -s --junitxml test_results${{ matrix.python-version }}.xml else - xvfb-run -e mechanical-env pytest -m embedding -s --junitxml test_results${{ matrix.python-version }}.xml || true + xvfb-run mechanical-env pytest -m embedding -s --junitxml test_results${{ matrix.python-version }}.xml || true fi - name: Upload coverage results @@ -652,9 +652,9 @@ jobs: output_file=doc_$1_output.txt if [ "${{ needs.container-stability-check.outputs.container_stable_exit }}" = "true" ]; then - xvfb-run -e mechanical-env make -C doc $1 + xvfb-run mechanical-env make -C doc $1 else - xvfb-run -e mechanical-env make -C doc $1 > $output_file 2>&1 || true + xvfb-run mechanical-env make -C doc $1 > $output_file 2>&1 || true cat $output_file echo done running make validate_output $output_file diff --git a/src/ansys/mechanical/core/embedding/initializer.py b/src/ansys/mechanical/core/embedding/initializer.py index 51e97795a..ff0c7d77e 100644 --- a/src/ansys/mechanical/core/embedding/initializer.py +++ b/src/ansys/mechanical/core/embedding/initializer.py @@ -130,9 +130,9 @@ def __check_for_mechanical_env(): """Embedding in linux platform must use mechanical-env.""" if platform.system() == "Linux" and os.environ.get("PYMECHANICAL_EMBEDDING") != "TRUE": raise Exception( - "On linux, embedding an instance of the Mechanical process using" + "On Linux, embedding an instance of the Mechanical process using " "the App class requires running python inside of a Mechanical environment." - "Use the `mechanical-env` script to do this. For more information, refer to:" + "Use the `mechanical-env` script to do this. For more information, refer to: " "https://mechanical.docs.pyansys.com/version/stable/" "getting_started/running_mechanical.html#embed-a-mechanical-instance" ) From 82945148ac2a1b18792a430912e9585b819638ad Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Thu, 10 Apr 2025 12:42:45 +0530 Subject: [PATCH 13/18] pyvista dir --- doc/source/conf.py | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/source/conf.py b/doc/source/conf.py index d8d06ade0..5729c5615 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -65,6 +65,7 @@ "sphinx_copybutton", "sphinx_design", "sphinxemoji.sphinxemoji", + "pyvista.ext.viewer_directive", ] if pymechanical.BUILDING_GALLERY: From 03f4791aca32ea96960e643cf373af238c8f7db1 Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Thu, 10 Apr 2025 12:43:44 +0530 Subject: [PATCH 14/18] doc build --- .github/workflows/ci_cd.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml index 351dc3117..bd693b5c5 100644 --- a/.github/workflows/ci_cd.yml +++ b/.github/workflows/ci_cd.yml @@ -634,7 +634,7 @@ jobs: run: | . /env/bin/activate pip install uv - uv pip install -e .[doc,viz] + uv pip install -e .[doc,graphics] - name: Build docs env: From 04dd4d7fd14635a47cbf062648668ee7b6aaea1c Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Fri, 11 Apr 2025 14:40:50 +0530 Subject: [PATCH 15/18] empty From b0b64a1ee70c9c31cd0e0256b5181ca86eb8657c Mon Sep 17 00:00:00 2001 From: pyansys-ci-bot <92810346+pyansys-ci-bot@users.noreply.github.com> Date: Wed, 18 Jun 2025 14:57:12 +0000 Subject: [PATCH 16/18] chore: adding changelog file 1125.test.md [dependabot-skip] --- doc/changelog.d/1125.test.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/changelog.d/1125.test.md b/doc/changelog.d/1125.test.md index df929e776..d36d7a952 100644 --- a/doc/changelog.d/1125.test.md +++ b/doc/changelog.d/1125.test.md @@ -1 +1 @@ -example refactor \ No newline at end of file +Example refactor \ No newline at end of file From 5f4d77e1f76d12ab2996cd429b02b7243b87cbd5 Mon Sep 17 00:00:00 2001 From: dkunhamb Date: Wed, 18 Jun 2025 09:58:33 -0500 Subject: [PATCH 17/18] only tips --- examples/00_tips/tips_01.py | 41 ++-- examples/00_tips/tips_02.py | 84 +++++--- examples/00_tips/tips_03.py | 30 +-- examples/embedding_n_remote/README.txt | 4 - .../embedding_n_remote/embedding_remote.py | 183 ------------------ 5 files changed, 91 insertions(+), 251 deletions(-) delete mode 100644 examples/embedding_n_remote/README.txt delete mode 100644 examples/embedding_n_remote/embedding_remote.py diff --git a/examples/00_tips/tips_01.py b/examples/00_tips/tips_01.py index 05d58dfc2..325e74e50 100644 --- a/examples/00_tips/tips_01.py +++ b/examples/00_tips/tips_01.py @@ -1,4 +1,4 @@ -# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates. +# Copyright (C) 2023 - 2025 ANSYS, Inc. and/or its affiliates. # SPDX-License-Identifier: MIT # # @@ -25,41 +25,41 @@ 3D visualization ---------------- -Visualize 3D imported geometry +The following example demonstrates how to visualize imported geometry in 3D. """ # %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - +# Import the necessary libraries +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from ansys.mechanical.core import App from ansys.mechanical.core.examples import delete_downloads, download_file # %% -# Embed mechanical and set global variables +# Initialize the embedded application +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -app = App() -app.update_globals(globals()) +app = App(globals=globals()) print(app) - # %% -# Download and import geometry -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download geometry +# Download and import the geometry file +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# %% +# Download the geometry file geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") # %% -# Import geometry +# Define the model and import the geometry file +model = app.Model -geometry_import = Model.GeometryImportGroup.AddGeometryImport() +geometry_import = model.GeometryImportGroup.AddGeometryImport() geometry_import.Import(geometry_path) # %% -# Visualize in 3D -# ~~~~~~~~~~~~~~~ +# Visualize the model in 3D +# ~~~~~~~~~~~~~~~~~~~~~~~~~ app.plot() @@ -68,8 +68,11 @@ # This visualization is currently available only for geometry and on version 24R2 or later # %% -# Cleanup -# ~~~~~~~ +# Clean up the files and app +# ~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Delete the downloaded files delete_downloads() -app.new() + +# Close the app +app.close() \ No newline at end of file diff --git a/examples/00_tips/tips_02.py b/examples/00_tips/tips_02.py index 4982998e0..70765bc80 100644 --- a/examples/00_tips/tips_02.py +++ b/examples/00_tips/tips_02.py @@ -1,4 +1,4 @@ -# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates. +# Copyright (C) 2023 - 2025 ANSYS, Inc. and/or its affiliates. # SPDX-License-Identifier: MIT # # @@ -25,35 +25,42 @@ Export image ------------ -Export image and display +The following example demonstrates how to export an image of the imported geometry +and display it using matplotlib. """ # %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Import the necessary libraries +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -import os +from pathlib import Path from ansys.mechanical.core import App from ansys.mechanical.core.examples import delete_downloads, download_file # %% -# Embed Mechanical and set global variables +# Initialize the embedded application +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Create an instance of the App class app = App() + +# Update the global variables app.update_globals(globals()) -print(app) +# Print the app to ensure it is working +print(app) # %% -# Download and import geometry -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download geometry +# Download and import the geometry file +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# %% +# Download the geometry file geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") # %% -# Import geometry +# Import the geometry file geometry_import = Model.GeometryImportGroup.AddGeometryImport() geometry_import.Import(geometry_path) @@ -62,13 +69,13 @@ # Configure graphics for image export # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Orientation -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) +# Set the orientation of the camera +ExtAPI.Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) -# Export format +# Set the image export format image_export_format = GraphicsImageExportFormat.PNG -# Resolution and background +# Configure the export settings for the image settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution settings_720p.Background = GraphicsBackgroundType.White @@ -76,24 +83,34 @@ settings_720p.Height = 720 settings_720p.CurrentGraphicsDisplay = False -# Rotate the geometry if needed -ExtAPI.Graphics.Camera.Rotate(180, CameraAxisType.ScreenY) - +# Rotate the geometry on the Y-axis +Graphics.Camera.Rotate(180, CameraAxisType.ScreenY) # %% -# Custom function for displaying the image -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Create a function to display the image +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from matplotlib import image as mpimg from matplotlib import pyplot as plt -# Temporary directory to save the image -cwd = os.path.join(os.getcwd(), "out") +# Directory to save the image +output_path = Path.cwd() / "out" + +def display_image(image_name) -> None: + """Display the image using matplotlib. -def display_image(image_name): + 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(os.path.join(cwd, image_name))) + plt.imshow(mpimg.imread(str(image_path))) plt.xticks([]) plt.yticks([]) plt.axis("off") @@ -104,17 +121,22 @@ def display_image(image_name): # Export and display the image # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Fits the geometry in the viewing area +# Fit the geometry in the viewing area Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "geometry.png"), image_export_format, settings_720p) +# Export the image +geometry_image = output_path / "geometry.png" +Graphics.ExportImage(str(geometry_image), image_export_format, settings_720p) -# Display the image using matplotlib -display_image("geometry.png") +# Display the image +display_image(geometry_image.name) # %% -# Cleanup -# ~~~~~~~ +# Clean up the downloaded files and app +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Delete the downloaded files delete_downloads() -app.new() + +# Close the app +app.close() \ No newline at end of file diff --git a/examples/00_tips/tips_03.py b/examples/00_tips/tips_03.py index fddffaf27..9d8cd7baf 100644 --- a/examples/00_tips/tips_03.py +++ b/examples/00_tips/tips_03.py @@ -1,4 +1,4 @@ -# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates. +# Copyright (C) 2023 - 2025 ANSYS, Inc. and/or its affiliates. # SPDX-License-Identifier: MIT # # @@ -23,27 +23,25 @@ """.. _ref_tips_03: Project tree --------------------- +------------ -Display the heirarchial Mechanical project structure. +The following example demonstrates how to print the heirarchial Mechanical project structure. """ # %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - +# Import the necessary libraries +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from ansys.mechanical.core import App from ansys.mechanical.core.examples import delete_downloads, download_file # %% -# Embed Mechanical and set global variables +# Initialize the embedded application +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -app = App() -app.update_globals(globals()) +app = App(globals=globals()) print(app) - # %% # Download the mechdb file # ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -65,12 +63,16 @@ # Display the tree only under the first analysis # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -app.print_tree(Model.Analyses[0]) +first_analysis = app.Model.Analyses[0] +app.print_tree(first_analysis) # %% -# Cleanup -# ~~~~~~~ +# Clean up the downloaded files and app +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Delete the downloaded files delete_downloads() -app.new() + +# Close the app +app.close() \ No newline at end of file diff --git a/examples/embedding_n_remote/README.txt b/examples/embedding_n_remote/README.txt deleted file mode 100644 index cfbc8e3bf..000000000 --- a/examples/embedding_n_remote/README.txt +++ /dev/null @@ -1,4 +0,0 @@ -Examples -======== - -Simple example to demonstrates how to use PyMechanical. \ No newline at end of file diff --git a/examples/embedding_n_remote/embedding_remote.py b/examples/embedding_n_remote/embedding_remote.py deleted file mode 100644 index 4e5098318..000000000 --- a/examples/embedding_n_remote/embedding_remote.py +++ /dev/null @@ -1,183 +0,0 @@ -# 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_embedding_remote: - -Remote & Embedding Example --------------------------- -This code, which uses the same example, first demonstrates how to use -a remote session and then demonstrates how to use an embedding instance. - -""" - - -############################################################################### -# Download the geometry file -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download Valve.pmdb. - -import os - -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import download_file - -geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") -print(f"Downloaded the geometry file to: {geometry_path}") - - -############################################################################### -# Embed Mechanical and set global variables -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Find the mechanical installation path & version. -# Open an embedded instance of Mechanical and set global variables. - -app = App() -app.update_globals(globals()) -print(app) - - -############################################################################### -# Add Static Analysis -# ~~~~~~~~~~~~~~~~~~~ -# Add static analysis to the Model. - -analysis = Model.AddStaticStructuralAnalysis() - - -############################################################################### -# Import geometry -# ~~~~~~~~~~~~~~~ - -geometry_file = geometry_path -geometry_import = Model.GeometryImportGroup.AddGeometryImport() -geometry_import_format = Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import.Import(geometry_file, geometry_import_format, geometry_import_preferences) -app.plot() - -############################################################################### -# Assign material -# ~~~~~~~~~~~~~~~ - -matAssignment = Model.Materials.AddMaterialAssignment() -tempSel = ExtAPI.SelectionManager.CreateSelectionInfo( - Ansys.ACT.Interfaces.Common.SelectionTypeEnum.GeometryEntities -) -bodies = [ - body - for body in ExtAPI.DataModel.Project.Model.Geometry.GetChildren( - Ansys.Mechanical.DataModel.Enums.DataModelObjectCategory.Body, True - ) -] -geobodies = [body.GetGeoBody() for body in bodies] -ids = System.Collections.Generic.List[System.Int32]() -[ids.Add(item.Id) for item in geobodies] -tempSel.Ids = ids -matAssignment.Location = tempSel -matAssignment.Material = "Structural Steel" - - -############################################################################### -# Define mesh settings -# ~~~~~~~~~~~~~~~~~~~~ - -mesh = Model.Mesh -mesh.ElementSize = Quantity("25 [mm]") -mesh.GenerateMesh() - - -############################################################################### -# Define boundary conditions -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -fixedSupport = analysis.AddFixedSupport() -fixedSupport.Location = ExtAPI.DataModel.GetObjectsByName("NSFixedSupportFaces")[0] - -frictionlessSupport = analysis.AddFrictionlessSupport() -frictionlessSupport.Location = ExtAPI.DataModel.GetObjectsByName("NSFrictionlessSupportFaces")[0] - -pressure = analysis.AddPressure() -pressure.Location = ExtAPI.DataModel.GetObjectsByName("NSInsideFaces")[0] - -inputs_quantities = [Quantity("0 [s]"), Quantity("1 [s]")] -output_quantities = [Quantity("0 [Pa]"), Quantity("15 [MPa]")] - -inputs_quantities_2 = System.Collections.Generic.List[Ansys.Core.Units.Quantity]() -[inputs_quantities_2.Add(item) for item in inputs_quantities] - -output_quantities_2 = System.Collections.Generic.List[Ansys.Core.Units.Quantity]() -[output_quantities_2.Add(item) for item in output_quantities] - -pressure.Magnitude.Inputs[0].DiscreteValues = inputs_quantities_2 -pressure.Magnitude.Output.DiscreteValues = output_quantities_2 - - -############################################################################### -# Solve model -# ~~~~~~~~~~~ - -Model.Solve(True) -solution = analysis.Solution - -assert solution.Status == SolutionStatusType.Done - -############################################################################### -# Add results -# ~~~~~~~~~~~ - -solution.AddTotalDeformation() -solution.AddEquivalentStress() -solution.EvaluateAllResults() - - -############################################################################### -# Save model -# ~~~~~~~~~~ - -project_directory = ExtAPI.DataModel.Project.ProjectDirectory -print(f"project directory = {project_directory}") -ExtAPI.DataModel.Project.SaveAs(os.path.join(project_directory, "file.mechdb")) - - -############################################################################### -# Export result values to a text file -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -fileExtension = r".txt" -results = solution.GetChildren( - Ansys.Mechanical.DataModel.Enums.DataModelObjectCategory.Result, True -) - -for result in results: - fileName = str(result.Name) - print(f"filename: {fileName}") - path = os.path.join(project_directory, fileName + fileExtension) - print(path) - result.ExportToTextFile(f"{path}") - print("Exported Text file Contents", path) - try: - write_file_contents_to_console(path, number_lines=20) - except: - print(os.listdir(project_directory)) - -app.close() From efcac220347f5b308eb2fe1be9865b3d648bfc7b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 18 Jun 2025 14:58:51 +0000 Subject: [PATCH 18/18] chore: auto fixes from pre-commit hooks --- examples/00_tips/tips_01.py | 4 ++-- examples/00_tips/tips_02.py | 4 ++-- examples/00_tips/tips_03.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/00_tips/tips_01.py b/examples/00_tips/tips_01.py index 325e74e50..dae8602bc 100644 --- a/examples/00_tips/tips_01.py +++ b/examples/00_tips/tips_01.py @@ -1,4 +1,4 @@ -# Copyright (C) 2023 - 2025 ANSYS, Inc. and/or its affiliates. +# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates. # SPDX-License-Identifier: MIT # # @@ -75,4 +75,4 @@ delete_downloads() # Close the app -app.close() \ No newline at end of file +app.close() diff --git a/examples/00_tips/tips_02.py b/examples/00_tips/tips_02.py index 70765bc80..1b66d47d8 100644 --- a/examples/00_tips/tips_02.py +++ b/examples/00_tips/tips_02.py @@ -1,4 +1,4 @@ -# Copyright (C) 2023 - 2025 ANSYS, Inc. and/or its affiliates. +# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates. # SPDX-License-Identifier: MIT # # @@ -139,4 +139,4 @@ def display_image(image_name) -> None: delete_downloads() # Close the app -app.close() \ No newline at end of file +app.close() diff --git a/examples/00_tips/tips_03.py b/examples/00_tips/tips_03.py index 9d8cd7baf..d896faa3c 100644 --- a/examples/00_tips/tips_03.py +++ b/examples/00_tips/tips_03.py @@ -1,4 +1,4 @@ -# Copyright (C) 2023 - 2025 ANSYS, Inc. and/or its affiliates. +# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates. # SPDX-License-Identifier: MIT # # @@ -75,4 +75,4 @@ delete_downloads() # Close the app -app.close() \ No newline at end of file +app.close()