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:241
Software build date: 11/27/2023 10:24:20

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/AnsysMechE6EA/Project_Mech_Files/

Uploading Valve.pmdb to 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/.:   0%|          | 0.00/774k [00:00<?, ?B/s]
Uploading Valve.pmdb to 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/.: 100%|██████████| 774k/774k [00:00<00:00, 237MB/s]
part_file_path on server: /tmp/ANSYS.root.1/AnsysMechE6EA/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/AnsysMechE6EA/Project_Mech_Files/file.mechdb
/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/.mech_lock
/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/file0.err
/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/ds.dat
/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/MatML.xml
/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/solve.out
/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERepOutput.xml
/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERep.xml

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

Downloading 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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, 59.9kB/s]

Downloading 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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, 4.21MB/s]

Downloading 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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, 366MB/s]

Downloading 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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, 112MB/s]

Downloading 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/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, 50.8MB/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 R1          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 R1

 Point Releases and Patches installed:

 Ansys, Inc. License Manager 2024 R1
 Structures 2024 R1
 LS-DYNA 2024 R1
 Mechanical Products 2024 R1


          *****  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/AnsysMechE6EA/Project_Mech_Files/StaticStructural/dummy.dat
  OUTPUT FILE NAME             = /tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/StaticStructural/solve.out
  START-UP FILE MODE           = NOREAD
  STOP FILE MODE               = NOREAD

 RELEASE= 2024 R1              BUILD= 24.1      UP20231106   VERSION=LINUX x64
 CURRENT JOBNAME=file0  17:56:33  APR 23, 2024 CP=      0.232


 *** FATAL ***                           CP =       0.243   TIME= 17:56:33
 The requested number of distributed-memory processes (4) exceeds the
 number of physical processors that are available (2) on machine:
 0b64c480586d.  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 R1            Build: 24.1       Update: UP20231106   Platform: LINUX x64
Date Run: 04/23/2024   Time: 17:56     Process ID: 14923
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)
          Intel(R) Math Kernel Library Version 2020.0.0 Product Build 20191122
          BLAS Library supplied by AMD BLIS

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.10 for Linux* OS


GPU Acceleration: Not Requested

Job Name: file0
Input File: dummy.dat

  Core                Machine Name   Working Directory
 -----------------------------------------------------
     0                0b64c480586d   /tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/StaticStructural
     1                0b64c480586d   /tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/StaticStructural
     2                0b64c480586d   /tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/StaticStructural
     3                0b64c480586d   /tmp/ANSYS.root.1/AnsysMechE6EA/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.3 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 R1         Build 24.1         UP20231106    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.253       Time  =  17:56:33          |
 |        Elapsed Time (sec) =          1.000       Date  =  04/23/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:
 0b64c480586d.  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 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERepOutput.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/CAERepOutput.xml:   0%|          | 0.00/789 [00:00<?, ?B/s]
Downloading 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERepOutput.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/CAERepOutput.xml: 100%|██████████| 789/789 [00:00<00:00, 3.33MB/s]

Downloading 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERep.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/CAERep.xml:   0%|          | 0.00/28.5k [00:00<?, ?B/s]
Downloading 127.0.0.1:10000:/tmp/ANSYS.root.1/AnsysMechE6EA/Project_Mech_Files/file_Mech_Files/StaticStructural/CAERep.xml to /__w/pymechanical/pymechanical/examples/embedding_n_remote/download/CAERep.xml: 100%|██████████| 28.5k/28.5k [00:00<00:00, 140MB/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()
globals().update(mech.global_variables(app))
print(app)
/env/lib/python3.10/site-packages/clr_loader/mono.py:180: UserWarning: Hosting Mono versions before v6.12 is known to be problematic. If the process crashes shortly after you see this message, try updating Mono to at least v6.12.
  warnings.warn(
Ansys Mechanical [Ansys Mechanical Enterprise]
Product Version:241
Software build date: 11/27/2023 10:24:20

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

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

Gallery generated by Sphinx-Gallery