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.

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}")
Downloaded the geometry file to: /github/home/.local/share/ansys_mechanical_core/examples/Valve.pmdb
Downloaded the script file to: /github/home/.local/share/ansys_mechanical_core/examples/remote_script.py

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)
Ansys Mechanical [Ansys Mechanical Enterprise]
Product Version:242
Software build date: 06/03/2024 09:35:09

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}")
project directory = /tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/

Uploading Valve.pmdb to dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/.:   0%|          | 0.00/774k [00:00<?, ?B/s]
Uploading Valve.pmdb to dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/.: 100%|██████████| 774k/774k [00:00<00:00, 288MB/s]
part_file_path on server: /tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/Valve.pmdb

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)
/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file.mechdb
/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/.mech_lock
/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/solve.out
/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/MatML.xml
/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERepOutput.xml
/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/ds.dat
/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERep.xml
/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/file0.err

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)
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file.mechdb to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/file.mechdb:   0%|          | 0.00/6.81M [00:00<?, ?B/s]
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file.mechdb to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/file.mechdb: 100%|██████████| 6.81M/6.81M [00:00<00:00, 373MB/s]

Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/.mech_lock to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/.mech_lock:   0%|          | 0.00/17.0 [00:00<?, ?B/s]
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/.mech_lock to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/.mech_lock: 100%|██████████| 17.0/17.0 [00:00<00:00, 1.35kB/s]

Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/solve.out to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/solve.out:   0%|          | 0.00/10.6k [00:00<?, ?B/s]
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/solve.out to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/solve.out: 100%|██████████| 10.6k/10.6k [00:00<00:00, 64.7MB/s]
contents of  ['/__w/pymechanical/pymechanical/examples/embedding_n_remote/download/solve.out']  :

 Ansys Mechanical Enterprise


 *------------------------------------------------------------------*
 |                                                                  |
 |   W E L C O M E   T O   T H E   A N S Y S (R)  P R O G R A M     |
 |                                                                  |
 *------------------------------------------------------------------*




 ***************************************************************
 *         ANSYS MAPDL 2024 R2          LEGAL NOTICES          *
 ***************************************************************
 *                                                             *
 * Copyright 1971-2024 Ansys, Inc.  All rights reserved.       *
 * Unauthorized use, distribution or duplication is            *
 * prohibited.                                                 *
 *                                                             *
 * Ansys is a registered trademark of Ansys, Inc. or its       *
 * subsidiaries in the United States or other countries.       *
 * See the Ansys, Inc. online documentation or the Ansys, Inc. *
 * documentation CD or online help for the complete Legal      *
 * Notice.                                                     *
 *                                                             *
 ***************************************************************
 *                                                             *
 * THIS ANSYS SOFTWARE PRODUCT AND PROGRAM DOCUMENTATION       *
 * INCLUDE TRADE SECRETS AND CONFIDENTIAL AND PROPRIETARY      *
 * PRODUCTS OF ANSYS, INC., ITS SUBSIDIARIES, OR LICENSORS.    *
 * The software products and documentation are furnished by    *
 * Ansys, Inc. or its subsidiaries under a software license    *
 * agreement that contains provisions concerning               *
 * non-disclosure, copying, length and nature of use,          *
 * compliance with exporting laws, warranties, disclaimers,    *
 * limitations of liability, and remedies, and other           *
 * provisions.  The software products and documentation may be *
 * used, disclosed, transferred, or copied only in accordance  *
 * with the terms and conditions of that software license      *
 * agreement.                                                  *
 *                                                             *
 * Ansys, Inc. is a UL registered                              *
 * ISO 9001:2015 company.                                      *
 *                                                             *
 ***************************************************************
 *                                                             *
 * This product is subject to U.S. laws governing export and   *
 * re-export.                                                  *
 *                                                             *
 * For U.S. Government users, except as specifically granted   *
 * by the Ansys, Inc. software license agreement, the use,     *
 * duplication, or disclosure by the United States Government  *
 * is subject to restrictions stated in the Ansys, Inc.        *
 * software license agreement and FAR 12.212 (for non-DOD      *
 * licenses).                                                  *
 *                                                             *
 ***************************************************************



 *------------------------------------------------------------------*
 |                    Ansys Product Improvement                     |
 |                                                                  |
 |   Ansys Product Improvement Program helps improve Ansys          |
 |   products. Participating in this program is like filling out a  |
 |   survey. Without interrupting your work, the software reports   |
 |   anonymous usage information such as errors, machine and        |
 |   solver statistics, features used, etc. to Ansys. We never      |
 |   use the data to identify or contact you.                       |
 |   The data does NOT contain:                                     |
 |   - Any personally identifiable information including names,     |
 |     IP addresses, file names, part names, etc.                   |
 |   - Any information about your geometry or design specific       |
 |     inputs.                                                      |
 |   You can stop participation at any time. To change your         |
 |   selection go to Help >> Ansys Product Improvement Program      |
 |   in the GUI.                                                    |
 |   For more information about the Ansys Privacy Policy, please    |
 |   check: http://www.ansys.com/privacy                            |
 |                                                                  |
 *------------------------------------------------------------------*


 2024 R2

 Point Releases and Patches installed:

 Ansys, Inc. License Manager 2024 R2
 LS-DYNA 2024 R2
 Core WB Files 2024 R2
 Mechanical Products 2024 R2


          *****  MAPDL COMMAND LINE ARGUMENTS  *****
  BATCH MODE REQUESTED (-b)    = NOLIST
  INPUT FILE COPY MODE (-c)    = COPY
  DISTRIBUTED MEMORY PARALLEL REQUESTED
       4 PARALLEL PROCESSES REQUESTED WITH SINGLE THREAD PER PROCESS
    TOTAL OF     4 CORES REQUESTED
  INPUT FILE NAME              = /tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/StaticStructural/dummy.dat
  OUTPUT FILE NAME             = /tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/StaticStructural/solve.out
  START-UP FILE MODE           = NOREAD
  STOP FILE MODE               = NOREAD

 RELEASE= 2024 R2              BUILD= 24.2      UP20240603   VERSION=LINUX x64
 CURRENT JOBNAME=file0  22:33:14  NOV 18, 2024 CP=      0.239


 *** FATAL ***                           CP =       0.254   TIME= 22:33:14
 The requested number of distributed-memory processes (4) exceeds the
 number of physical processors that are available (2) on machine:
 218b142ddeff.  The use of virtual processors is not recommended.  It
 is required that you use a maximum of 2 distributed-memory processes
 on this machine.

 ************************************************************************
 The above error is non-recoverable by ANSYS
  ANSYS run terminated by the indicated error
  Current data base saved if possible.
 ************************************************************************

+--------------------- M A P D L   S T A T I S T I C S ------------------------+

Release: 2024 R2            Build: 24.2       Update: UP20240603   Platform: LINUX x64
Date Run: 11/18/2024   Time: 22:33     Process ID: 16192
Operating System: Ubuntu 20.04.6 LTS

Processor Model: AMD EPYC 7763 64-Core Processor

Compiler: Intel(R) Fortran Compiler Classic Version 2021.9  (Build: 20230302)
          Intel(R) C/C++ Compiler Classic Version 2021.9  (Build: 20230302)
          AOCL-BLAS 4.2.1 Build 20240303

Number of processes requested           :    4
Number of threads per process requested :    1
Total number of cores requested         :    4 (Distributed Memory Parallel)
MPI Type: INTELMPI
MPI Version: Intel(R) MPI Library 2021.11 for Linux* OS


GPU Acceleration: Not Requested

Job Name: file0
Input File: dummy.dat

  Core                Machine Name   Working Directory
 -----------------------------------------------------
     0                218b142ddeff   /tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/StaticStructural
     1                218b142ddeff   /tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/StaticStructural
     2                218b142ddeff   /tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/StaticStructural
     3                218b142ddeff   /tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/StaticStructural



Total CPU time for main thread                    :        0.6 seconds
Total CPU time summed for all threads             :        0.3 seconds

Elapsed time spent obtaining a license            :        0.5 seconds
Elapsed time spent pre-processing model (/PREP7)  :        0.0 seconds
Elapsed time spent solution - preprocessing       :        0.0 seconds
Elapsed time spent computing solution             :        0.0 seconds
Elapsed time spent solution - postprocessing      :        0.0 seconds
Elapsed time spent post-processing model (/POST1) :        0.0 seconds


+------------------ E N D   M A P D L   S T A T I S T I C S -------------------+


 *-----------------------------------------------------------------------------*
 |                                                                             |
 |                               RUN COMPLETED                                 |
 |                                                                             |
 |-----------------------------------------------------------------------------|
 |                                                                             |
 |  Ansys MAPDL 2024 R2         Build 24.2         UP20240603    LINUX x64     |
 |                                                                             |
 |-----------------------------------------------------------------------------|
 |                                                                             |
 |  Database Requested(-db)  1024 MB     Scratch Memory Requested      1024 MB |
 |  Maximum Database Used       1 MB     Maximum Scratch Memory Used      1 MB |
 |                                                                             |
 |-----------------------------------------------------------------------------|
 |                                                                             |
 |        CP Time      (sec) =          0.265       Time  =  22:33:14          |
 |        Elapsed Time (sec) =          2.000       Date  =  11/18/2024        |
 |                                                                             |
 *-----------------------------------------------------------------------------*

 ERROR: Worker process(es) with rank(s) solve have encountered a FATAL error.
   The information below was gathered from the file*.out output file(s).
   Please review the worker process output file(s) listed below for more
   details on this error.

 FATAL error message: solve.out
 The requested number of distributed-memory processes (4) exceeds the
 number of physical processors that are available (2) on machine:
 218b142ddeff.  The use of virtual processors is not recommended.  It
 is required that you use a maximum of 2 distributed-memory processes
 on this machine.

Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/MatML.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/MatML.xml:   0%|          | 0.00/23.3k [00:00<?, ?B/s]
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/MatML.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/MatML.xml: 100%|██████████| 23.3k/23.3k [00:00<00:00, 138MB/s]

Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERepOutput.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/CAERepOutput.xml:   0%|          | 0.00/862 [00:00<?, ?B/s]
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERepOutput.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/CAERepOutput.xml: 100%|██████████| 862/862 [00:00<00:00, 3.33MB/s]

Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/ds.dat to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/ds.dat:   0%|          | 0.00/4.85M [00:00<?, ?B/s]
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/ds.dat to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/ds.dat: 100%|██████████| 4.85M/4.85M [00:00<00:00, 358MB/s]

Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERep.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/CAERep.xml:   0%|          | 0.00/28.2k [00:00<?, ?B/s]
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERep.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/CAERep.xml: 100%|██████████| 28.2k/28.2k [00:00<00:00, 181MB/s]

Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/file0.err to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/file0.err:   0%|          | 0.00/896 [00:00<?, ?B/s]
Downloading dns:///127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMech257C/Project_Mech_Files/file_Mech_Files/StaticStructural/file0.err to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/file0.err: 100%|██████████| 896/896 [00:00<00:00, 3.52MB/s]

Exit remote session#

Close the Mechanical instance.

mechanical.exit()

Embedded Instance#

Download the geometry file#

Download Valve.pmdb.

import os

import ansys.mechanical.core as mech
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}")
Downloaded the geometry file to: /github/home/.local/share/ansys_mechanical_core/examples/Valve.pmdb

Embed Mechanical and set global variables#

Find the mechanical installation path & version. Open an embedded instance of Mechanical and set global variables.

app = mech.App()
app.update_globals(globals())
print(app)
Ansys Mechanical [Ansys Mechanical Enterprise]
Product Version:242
Software build date: 06/03/2024 09:35:09

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)

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

Add results#

solution = analysis.Solution
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"))
project directory = /tmp/ANSYS.root.1/AnsysMechF21F/Project_Mech_Files/

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()
filename: Total Deformation
/tmp/ANSYS.root.1/AnsysMechF21F/Project_Mech_Files/Total Deformation.txt
Exported Text file Contents /tmp/ANSYS.root.1/AnsysMechF21F/Project_Mech_Files/Total Deformation.txt
['file.mechdb', 'file_Mech_Files']
filename: Equivalent Stress
/tmp/ANSYS.root.1/AnsysMechF21F/Project_Mech_Files/Equivalent Stress.txt
Exported Text file Contents /tmp/ANSYS.root.1/AnsysMechF21F/Project_Mech_Files/Equivalent Stress.txt
['file.mechdb', 'file_Mech_Files']

Total running time of the script: (0 minutes 59.873 seconds)

Gallery generated by Sphinx-Gallery