Ansys Scripting in Mechanical Guide
Ansys Scripting in Mechanical Guide
ANSYS, Ansys Workbench, AUTODYN, CFX, FLUENT and any and all ANSYS, Inc. brand, product, service and feature
names, logos and slogans are registered trademarks or trademarks of ANSYS, Inc. or its subsidiaries located in the
United States or other countries. ICEM CFD is a trademark used by ANSYS, Inc. under license. CFX is a trademark
of Sony Corporation in Japan. All other brand, product, service and feature names or trademarks are the property
of their respective owners. FLEXlm and FLEXnet are trademarks of Flexera Software LLC.
Disclaimer Notice
THIS ANSYS SOFTWARE PRODUCT AND PROGRAM DOCUMENTATION INCLUDE TRADE SECRETS AND ARE CONFID-
ENTIAL AND PROPRIETARY PRODUCTS OF ANSYS, INC., ITS SUBSIDIARIES, OR LICENSORS. The software products
and documentation are furnished by ANSYS, Inc., its subsidiaries, or affiliates 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. and ANSYS Europe, Ltd. are UL registered ISO 9001: 2015 companies.
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).
Third-Party Software
See the legal information in the product help files for the complete Legal Notice for ANSYS proprietary software
and third-party software. If you are unable to access the Legal Notice, contact ANSYS, Inc.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. iii
Scripting in Mechanical Guide
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
iv of ANSYS, Inc. and its subsidiaries and affiliates.
Scripting in Mechanical Guide
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. v
Scripting in Mechanical Guide
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
vi of ANSYS, Inc. and its subsidiaries and affiliates.
Scripting in Mechanical Guide
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. vii
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
viii of ANSYS, Inc. and its subsidiaries and affiliates.
Scripting Quick Start
Scripting refers to the use of a programming language to interact with and modify a software product.
Scripting can also be used to automate routine tasks. In Ansys Mechanical, you can use Ansys ACT and
Mechanical Python APIs (Application Programming Interfaces).
Scripting Introduction
Key Usage Concepts
Threading
Using Scripts to Create User-Defined Buttons
Using the Python Code Object
Using the Python Result Object
Additional Resources
Scripting Introduction
This section provides introductory information about scripting in Mechanical:
Mechanical Scripting View
Autocompletion
Snippets
Keyboard Shortcuts
Recording APIs
Debugging Scripts and Extensions
Scope Selection for ACT Extensions
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 3
Scripting Introduction
Note:
• The Scripting view initially opens in a locked position to the right of the graphics
view. You can click the header bar and drag this view to anywhere in Mechanical,
dropping it into a new locked position. By double-clicking the header bar, you can
toggle between the locked position and a floating window. You can resize and move
the floating window as needed.
• If you have ACT extensions loaded and debug mode is enabled, below the Shell area,
a tab displays for each loaded extension so that you can set the scope. For more in-
formation, see Scope Selection for ACT Extensions (p. 29).
• You can revert to the ACT Console by changing the scripting view preference under
File > Options > Mechanical > UI Options > New Scripting UI. Mechanical must be
restarted to see the scripting view change.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
4 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical Scripting View
Toolbar
The toolbar for the Editor provides several buttons:
1. New Script: Clears the name, description, and script boxes, providing you with a new script
template in which to work.
2. Open Script: Opens a script, which is any Python file (*.py), from disk.
5. Start Debugger: This runs the script in debug mode. See the Debugging (p. 24) section for
more information.
6. Start Recording: Automatically create APIs by recoding the actions that you take. For example,
inserting a load or a result. This option also includes a drop-down menu where you can select
to active the Camera and/or Graphics filters. See descriptions for these options in the Default
Settings (p. 8) topic below.
7. Insert Snippet (Ctrl+I): Open the snippet inserter (p. 16). This option includes a drop-down
menu for the Promote Script to Snippet and Open Snippet Editor options. Both of the
options open the Snippet Editor (p. 17). For the promotion option, certain fields are automat-
ically completed in the Editor.
8. Show Button Editor: Opens the Button Editor. This option includes a drop-down menu with
the option Promote Script to Button that opens the Button Editor with certain fields
automatically completed using the information from the script in the Editor. For more inform-
ation, see Creating User-Defined Buttons in the Mechanical User's Guide.
9. Default Settings: Display the Default Settings (p. 8) dialog (see below). This dialog enables
you to specify the default settings for recording and what is displayed of the Shell pane.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 5
Scripting Introduction
Content Area
The content area is where you write scripts, such as the example Pressure illustrated below.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
6 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical Scripting View
The content area provides autocompletion (p. 10) and the following shortcuts:
Script Tabs
A script "Tab" displays at the bottom of the pane. You can now work on multiple scripts at the same
time using tabs. You add new tabs using the + button and delete tabs using the x button that displays
when you hover over a tab. When you open a new script, it will now open in a new tab. When you
have multiple tabs, you can switch between scripts.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 7
Scripting Introduction
Default Settings
Selecting the Default Options button displays the following dialog.
Settings include:
• Camera: Selecting this option enables you to capture all movements (pan/rotate) made on
the model in the Geometry window are recorded.
• Graphics: Selecting this option enables you to capture certain Graphical Toolbar options and
display features while recording. Examples include turning the ruler on and off, creating Section
Planes, and selecting the Thick Shells and Beams options.
• Auto Scroll: As entries or recordings are made in the script pane, the pane automatically scrolls
as new content is added.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
8 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical Scripting View
• Comments: Selected by default, unchecking this option turns off the automatic comments
(green text) that are added for each API entry or recording.
See the Working with the Shell (p. 9) section for a description of the Shell filters provided via the
dialog. These same filters are available from the Shell pane Shell Content Filter option.
Toolbar
The toolbar for the Shell provides these buttons:
1. Clear Contents: Clears the contents of the Shell. This can also be done by executing the
command clear inside the Shell.
2. Insert Snippet: Opens the snippet inserter (p. 16) in context of the Shell.
3. Shell Preferences: Displays a drop-down menu for indicating whether to hide the output,
input, errors, and warnings. All check boxes are cleared by default so that the output, input,
errors, and warnings are all shown.
4. Content area: Area in which you enter and execute single-line or multi-line commands. This
area provides autocompletion (p. 10).
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 9
Scripting Introduction
Text Item
Color
Gray Output
Red Error
Yellow Warning
Context Menu
There is a context menu associated with the commands that have been executed. To display this
context menu, place the mouse cursor over the executed command and right-click.
• Replay: Re-inserts the executed command in the content area for execution.
Shortcuts:
The Shell provides these shortcuts:
Autocompletion
The text editor in the Editor, Snippet Editor (p. 17), and the input field in the Shell all provide autocom-
pletion.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
10 of ANSYS, Inc. and its subsidiaries and affiliates.
Autocompletion
Autocompletion Tooltips
When you place the mouse cursor over any property or method in the list of suggestions provided, the
tooltip displays information about this item. The following image shows the tooltip for the property
Models.
Color Syntax
Green Accessibility
Purple Type
Orange Warning
Blue Argument
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 11
Scripting Introduction
Properties
General formatting for properties follow:
Methods
General formatting for methods follow:
Additional Information
Tootltips can also provide:
• Prototype information for methods when cursor is inside brackets and indexers when cursor
is inside square brackets
– Prototypes for overloaded methods (accessed by pressing the arrows in the prototype
tooltip)
The tooltip for an overloaded method is a list of all members from all overloaded methods.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
12 of ANSYS, Inc. and its subsidiaries and affiliates.
Snippets
Tooltip Examples
The following images show two different tooltip examples for the method Equals in two different
stages of using autocompletion:
Keyboard Shortcuts:
The tooltip provides these keyboard shortcuts:
Snippets
Snippets are code or code templates that you can quickly and easily insert in the command line, saving
you from repetitive typing. As you write scripts, you can insert any of the snippets that Ansys supplies.
Additionally, you can begin building your own library of snippets to either supplement or replace supplied
snippets with your own custom snippets.
Supplied Snippets
Descriptions follow of all supplied snippets:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 13
Scripting Introduction
The snippet ExtAPI inserts ExtAPI. in the command line, providing you with immediate access to
the ACT API. From the autocomplete options in the tooltip, you can then begin selecting members
to build your command.
The snippet Snippet Template provides sample code for swapping two variables. The comments
explain how a snippet can contain editable fields, which are automatically selected for modification
when the snippet is inserted. When a field is selected, you can type a new value to override the default
value or let the default value remain. Pressing the Tab key moves the cursor to the next editable
field.
– project=DataModel.Project.Model.Connections
– project=DataModel.Project.Model.NamedSelections
The snippets Mesh and Geometry provide examples of easier methods for accessing first-level
objects.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
14 of ANSYS, Inc. and its subsidiaries and affiliates.
Snippets
• Quantity. Inserts Quantity("1 [mm]", providing a command method in which you can
declare values. Three examples follow:
pres = DataModel.Project.Model.Analyses[0].AddPressure()
Lastly, the folder Examples provides snippets that you can use as templates. For example, the snippet
Add Pressure shows how to create a pressure on the first face of the first body of the first part.
For example, in Snippet Template, the first editable field (foo) is highlighted.
Typing something changes the foo value to whatever you type (value1). Notice that both foo
values change to value1 in one operation.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 15
Scripting Introduction
Pressing the Tab key moves the cursor to the next editable field, causing bar to be highlighted.
Typing something changes the bar value to whatever you type (value2). Notice that both bar
values change to value2 in one operation.
To define an editable field, you must use the following notation: ${#:default_value}, where #
is the index of the field. For the first editable field, the value is 1. To reference an editable field that
is already defined, you simply need to specify its index (${#}) as shown in the following figure for
the snippet Geometry.
Snippet Inserter
The snippet inserter can be accessed in the context of the Editor or the Shell. You can use the buttons
on the toolbar or the keyboard shortcut Ctrl + i to open the snippet inserter. It will open wherever
your cursor is in the script. Once the snippet inserter is opened, you can use the mouse or the keyboard
to interact with it.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
16 of ANSYS, Inc. and its subsidiaries and affiliates.
Snippets
Mouse Interaction
Using the mouse, you can simply click snippets to insert them into the Editor. If you click a snippet
folder, it opens so that you can see the snippets inside it. As you browse folders, the text in the search
box displays your current file path:
Clicking the back button for the search box returns you to your last location.
Keyboard Interaction
You can use the search box to search or browse snippets. As seen in the following figure, if you type
Ex, the snippet inserter displays all snippets and snippet folders that include Ex in their names. From
there, you can use the Tab or Enter key to select a snippet or a snippet folder.
Deleting the text in the search box or using the keyboard shortcut Alt + ← returns you to your last
location.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 17
Scripting Introduction
2. Name input field: Specifies the name or both the folder and name to which to save the
snippet. Examples follow:
• To save a snippet named Quick Add to the root folder for snippets, the name input
field would look like this:
Note:
Root folder refers to the place where you start out when browsing
snippets. For reference, the snippet ExtAPI is in the root folder.
• To save this same snippet to the folder Examples, the name input field would look
like this:
Note:
When you click an existing folder, the Snippet Manager inserts the
path to this folder in the name input field so that the snippet will be
saved to this folder. You can also manually type the path to the folder.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
18 of ANSYS, Inc. and its subsidiaries and affiliates.
Snippets
4. Content area: Where you write the snippet that is to be inserted when the snippet inserter
is used.
5. Snippet Manager: Opens a view where you can manage your snippets.
Descriptions follow for the two buttons in the lower left corner of the Snippet Manager:
a. Import snippet collection: Opens a dialog box for you to select the snippet collection
file. The Snippet Manager supports XML and JSON files. The XML files can be files
that were exported using the ACT Console. The JSON files are snippet collections
that are imported using the Snippet Manager. Importing snippet collection files will
add the snippets that they contain to your existing snippets.
b. Export snippet collection: Exports all snippets in the Snippet Manager to a JSON
file.
Note:
The Snippet Manager displays the Click To Add Folder option as the last node In
every folder. You can click this option to create a new folder in the current folder.
The other options available to you in the Snippet Manager depend on whether you place the mouse
cursor over a snippet or a snippet folder.
When you place the mouse cursor over a snippet, buttons are available for either editing or deleting
the snippet:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 19
Scripting Introduction
1. Edit snippet: Opens the snippet in the Snippet Editor so that you can view and make changes
to the snippet.
Caution:
Deleting a snippet from the Snippet Manager also removes it from the
snippet inserter.
When you place the mouse cursor over a folder, buttons are available for browsing the folder and
either editing or deleting the folder:
2. Edit folder: Makes the folder name editable so that you can change it.
Caution:
Keyboard Shortcuts
The following topics summarize the keyboard shortcuts that are available.
Editor and Shell Keyboard Shortcuts
Text Editor Keyboard Shortcuts
Editor
The Editor supports Ctrl + F5 as a shortcut for executing the script.
Shell
The Shell supports the following shortcuts:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
20 of ANSYS, Inc. and its subsidiaries and affiliates.
Keyboard Shortcuts
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 21
Scripting Introduction
Selection Shortcuts
Key Action
Combination
Ctrl + A
Shift + ← Select all
Shift + → Select left
Ctrl + Shift + ← Select right
Ctrl + Shift + → Select word left
Shift + Home Select word right
Shift + End Select line start
Alt + Shift + → Select line end
Alt + Shift + ← Select to line end
Shift + ↑ Select to line
start
Shift + ↓ Select up
Shift + Page Up Select down
Shift + Page Select page up
Down
Ctrl + Shift + Select page
Home down
Ctrl + Shift + End Select to start
Ctrl + Shift + D Select to end
Ctrl + Shift + P Duplicate
selection
Multi-Cursor Shortcuts
Key Combination Action
Ctrl + Alt + ↑ Add multi-cursor above
Ctrl + Alt + ↓ Add multi-cursor below
Ctrl + Alt + → Add next occurrence to multi-selection
Ctrl + Alt + ← Add previous occurrence to multi-selection
Ctrl + Alt + Shift + Move multi-cursor from current line to the line above
↑
Ctrl + Alt + Shift + Move multi-cursor from current line to the line below
↓
Ctrl + Alt + Shift + Remove current occurrence from multi-selection and move to next
→
Ctrl + Alt + Shift + Remove current occurrence from multi-selection and move to previous
←
Ctrl + Shift + L Select all from multi-selection
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
22 of ANSYS, Inc. and its subsidiaries and affiliates.
Recording APIs
Go-To Shortcuts
Key Action
Combination
Page Up Go to page up
Page Down Go to page down
Ctrl + Home Go to start
Ctrl + End Go to end
Ctrl + L Go to line
Ctrl + P Go to matching
bracket
Folding Shortcuts
Key Combination Action
Alt + L, Ctrl + F1 Fold
selection
Alt + Shift + L, Ctrl + Shift + Unfold
F1
Other Shortcuts
Key Combination Action
Tab Indent
Shift + Tab Outdent
Ctrl + Z Undo
Ctrl + Shift + Y, Ctrl + Redo
Y
Ctrl + T Transpose letters
Ctrl + Shift + U Change to lower
case
Ctrl + U Change to upper
case
Insert Overwrite
Recording APIs
Selecting the Recording option on the toolbar enables you to automatically generate ("record") applic-
ation supported APIs based on the actions that you make in the application, such as contact surfaces,
loading, and the definition of results. For the animated example shown here, a Fixed Support and a
Pressure were added to the Outline. The recording feature captured these actions. This feature is a
convenient tool for API development. See the Default Settings (p. 8) topic in the Working with the Ed-
itor section for the filters available for this feature.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 23
Scripting Introduction
Points to Remember
• When you record and save API content for moving the model around in the Geometry window,
via the Camera Default Setting, those APIs are independent of the geometry. If you save movement
APIs (pan, rotate, etc.), they will execute of any model in the application.
• For saved script files, the order in which you record your actions and create APIs has consequence.
You need to ensure that all APIs support any redefinition or changes as you progress through a
recording.
Note:
This feature does not support every available API. Further development in this regard as well
as the improvement of the feature itself is ongoing and required.
Inserting Breakpoints
You can set breakpoints by selecting the field next to the line numbers (a red circle icon is displayed).
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
24 of ANSYS, Inc. and its subsidiaries and affiliates.
Debugging Scripts and Extensions
Important:
Breakpoints pause the script execution. When paused, you cannot interact with the Mechan-
ical user interface.
Exceptions
If there is an error in the script, an exception is thrown and a message displays describing the ex-
ception. Once you navigate from the message window, the line that includes the error is highlighted
with a marker next to the line number. When you hover over this marker, you can read the description
of the exception again.
When a script is run using the debugger and breakpoints have been inserted. The script will pause
at the breakpoints as it executes. You can then use debugging toolbar actions to proceed. The
current line of execution is highlighted in yellow, and an arrow is shown next to it.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 25
Scripting Introduction
1. Run Script/Continue (F5): Continue execution to the next breakpoint when script is paused
or re-start the debugging.
3. Step Into (F11): Pauses at the first line of the function you are stepping into.
4. Step Over (F10): Execute the currently selected function or statement and then step over to
the next line.
5. Step Out (F12): Continue execution to the next breakpoint or the next line after the function
returns.
Note:
The availability of toolbar actions changes based on the current state of the debugger.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
26 of ANSYS, Inc. and its subsidiaries and affiliates.
Debugging Scripts and Extensions
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 27
Scripting Introduction
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
28 of ANSYS, Inc. and its subsidiaries and affiliates.
Scope Selection for ACT Extensions
Debugging features are the same when working with an extension. Simply switch to the appropriate
extension tab in the scripting view and you will see all python scripts in the editor. The only difference
is, because extensions work based on callbacks, breakpoints are not encountered until you perform an
action in the interface that executes the callback.
Important:
If you change the script of an extension, you must save and then reload the extension before
rerunning/running the debugger. The application will prompt you to save the file if you make
and change and then run the debug tool. However, if you make a change and select the
Save button. You must also reload the extension using the Reload button in the ACT Devel-
opment group on the Automation tab.
Debugging Limitations
If you run the command import os in the debugger, an exception is generated. To avoid this issue,
you first need to turn on the Debug Mode option in the Extensions category of the Workbench Options
dialog available through the Tools menu. Once selected, you need to execute the command using Run
Script button. Following this you can use the debugging feature without producing an exception.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 29
Scripting Introduction
The following image shows the state of the tabs when supplied extensions AqwaLoadMapping and
AdditiveWizard are loaded:
Scopes are only shown if debug mode is enabled for ACT extensions. For more information, see Debug
Mode in the ACT Developer's Guide.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
30 of ANSYS, Inc. and its subsidiaries and affiliates.
Key Usage Concepts
Understanding these key concepts makes Mechanical's scripting easier to learn:
• Mechanical APIs can be used to access much of Mechanical, including tree objects and their
properties.
• It is important to understand a key but subtle distinction between two APIs related to the mesh:
– Model.Mesh accesses the object Mesh in the Mechanical tree, containing APIs for that
object's properties in the Details view. It can be used to add and access mesh controls.
• It is important to understand a key but subtle distinction between two APIs related to the geo-
metry:
• The underlying Geometry, much like the Tree, is hierarchical. For example, DataMod-
el.GeoData.Assemblies[0].Parts[0].Bodies[0].Volume accesses the volume for
the first part in the first (and only) assembly.
• All bodies have parts as their parents, even if they are not multibody parts. This is important to
understand in both GeoData and when traversing the object Geometry of the DataModel.
Although a part might be hidden from the Mechanical interface, the part is always there. For
more information, see Multibody Behavior and Associativity in the Ansys Mechanical User's Guide.
• For more information on accessing the properties of an object, including those for traversing
the geometry, mesh, simulation, and results, see Mechanical APIs (p. 43).
• It is often useful to store variables to access later rather than using the same API over and over.
For example, using the following three commands is better than duplicating the DataMod-
el.MeshByName(“Global”) expression in the second and third commands:
mesh = DataModel.MeshByName("Global")
mesh.ElementCount
mesh.NodeCount
• Looping is a fundamental concept in any scripting language. Within the object Geometry, you
can use loops to add, modify, or export property data. The following script loops over all contacts
and change their formulation to MPC:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 31
Key Usage Concepts
contact_region_list = DataModel.GetObjectsByType(DataModelObjectCategory.ContactRegion)
• The object Transaction() can be used to speed up a block of code that modifies multiple
objects. This object ensures that the tree is not refreshed and that only the bare minimum
graphics and validations occur while the transaction is in scope. The object Transaction()
should only be used around code blocks that do not require state updates, such as solving or
meshing. For example, to avoid redundant work from each addition, the following example use
the object Transaction() before code that adds many objects:
with Transaction():
for bodyId in bodyIds:
...
• If you cannot find what you want, check the attribute InternalObject. While the ACT API
has “wrapped” many useful aspects of Mechanical, it has not wrapped everything, for various
reasons. Many API objects have an InternalObject attribute that you can use to find addi-
tional capabilities that are not formally exposed in ACT.
For more information about how to complete many types of Mechanical tasks using scripts, see the
examples in these sections:
• Script Examples for Interacting with the Mechanical Session (p. 203)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
32 of ANSYS, Inc. and its subsidiaries and affiliates.
Threading
Although using Mechanical scripting APIs on a background thread might work in practice, the APIs are
generally not thread-safe, and race conditions might and often do occur when trying to access them
from a background thread.
It is still possible to only run parts of your code—namely those parts that do not use these APIs and
hence do not risk race conditions—on a background thread. To do so, you can offload work to a new
thread. A convenient way to do this is by using the InvokeBackground method exposed on Ex-
tAPI.Application. This method can only take a function without any arguments, but the following
technique can be used to pass in arguments to that function:
#function that is to be run in the background. It is safe because it does not using any of the Mechanical scriptin
def gradient(vectors)
print("Computing gradients of the vectors”)
Note:
A race condition is a software problem that can arise when concurrent code does not syn-
chronize data access and mutation. These conditions are by their nature difficult to identify
and reproduce, and they sometimes lead to seemingly random problems. There is no way
to predict the outcome of a race condition. Alarmingly, it is possible for code to work well
for years and then suddenly start to crash because of a race condition.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 33
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
34 of ANSYS, Inc. and its subsidiaries and affiliates.
Using Scripts to Create User-Defined Buttons
See the Creating User-Defined Buttons section of the Mechanical User's Guide for information about
how to create, edit, manage, export, and import, your own toolbar buttons.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 35
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
36 of ANSYS, Inc. and its subsidiaries and affiliates.
Using the Python Code Object
Review the Mechanical application Python Code object documentation. When inserted, an editor pane
displays and enables you to make script entries. This feature enables you to execute python code in
response to events occurring in Mechanical for a given workflow.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 37
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
38 of ANSYS, Inc. and its subsidiaries and affiliates.
Using the Python Result Object
Review the Mechanical application Python Result feature for capabilities that enable you to evaluate
output quantities by executing an Iron-python script based on the Data Processing Framework (DPF)
post-processing toolbox.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 39
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
40 of ANSYS, Inc. and its subsidiaries and affiliates.
Additional Resources
To help you use scripts in Mechanical, many resources are available.
• The installed Python scripts that Mechanical uses can be insightful. These scripts are in your
Ansys installation directory at .../aisol/DesignSpace/DSPages/Python. Useful scripts
include toolbar.py and selection.py. These scripts are run when using many of the options
in the Select group on the Mechanical ribbon's Selection tab. For more information, see Selection
Tab in the Ansys Mechanical User’s Guide.
• The ACT API Reference Guide provides descriptions of all ACT API objects, methods, and properties.
Note:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 41
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
42 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical APIs
Mechanical APIs (Application Programming Interfaces) provide access to the native functionality of Ansys
Mechanical.
Mechanical API Introduction
API Reference Guide
Mechanical API Notes
Object Access
Boundary Conditions
Worksheets
Graphics
Results
Other APIs
Mechanical API Introduction
Using APIs, you can access, modify, and add objects in the Mechanical tree (Project, Model, Analys-
is, and so on).
Note:
When you add an object using the API, the default values for properties in the Details view
in Mechanical are the same as when you add an object directly in Mechanical.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 45
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
46 of ANSYS, Inc. and its subsidiaries and affiliates.
API Reference Guide
Be sure to review the API Reference Guide for the descriptions of all API objects, methods, and properties.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 47
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
48 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical API Notes
The following topics provide Mechanical API migration notes and known issues and limitations:
Mechanical API Migration Notes
Mechanical API Known Issues and Limitations
Note:
For general ACT migration information, see Migration Notes in the ACT Developer's Guide.
For geometries in a Mechanical system that are linked to an External Model system, if a geo-
metry in Mechanical has a single body part, the part name will be the same as the body name.
Consequently, this query now returns two matches:
[x for x in DataModel.Tree.AllObjects if x.Name=="Surface Body 1(External Model)"]
Set/GetLoadCombinationType
Original:
sc = Model.AddSolutionCombination()
scdef = sc.Definition
scdef.SetLoadCombinationType(0,1)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 49
Mechanical API Notes
Migrated:
sc = Model.AddSolutionCombination()
scdef = sc.Definition
scdef.SetLoadCombinationType(0,LoadCombinationType.SRS)
Note:
For general ACT known issues and limitations, see Known Issues and Limitations in the ACT
Developer's Guide.
When using ACT to create a figure from the chart API, the following error prevents the graphics display
in the Mechanical window:
Object reference not set to an instance of an object.
As a workaround, add the following code to your script to create an empty window in which the chart
can display:
import clr
clr.AddReference("Ans.UI.Toolkit")
clr.AddReference("Ans.UI.Toolkit.Base")
import Ansys.UI.Toolkit
if Ansys.UI.Toolkit.Window.MainWindow == None:
Ansys.UI.Toolkit.Window.MainWindow = Ansys.UI.Toolkit.Window()
Custom results do not support using a geometric path as scoping. You can only use a selection of
nodes and elements as scoping.
When exporting results obtained from an external solver to a text file, the Include Node Location
option is not currently supported.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
50 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical API Known Issues and Limitations
You cannot currently combine results with the Solution Combination object to when using results
from an external solver.
The ACT postprocessing API does not support the compressed result file for Mechanical, which is
created by the Mechanical APDL command /FCOMP.
The ACT postprocessing API does not support a node merge action on the mesh.
The ACT postprocessing API does not account for the ShellPosition command for dealing with shell
bodies.
The ACT postprocessing API returns the results on orientation nodes when dealing with beam bodies,
even though these results are irrelevant.
When an element degenerates, the ACT Postprocessing API does not discard the degenerated nodes,
thereby resulting in some repeated result values. For example, when a HEX element (8 nodes) degen-
erates into a WEDGE element (6 nodes), the ACT Postprocessing API still returns result values on 8
nodes (out of which 2 values are repeated).
If you change Analysis Settings substep entries, to see this change reflected in the ACT Custom
results, you must run the Clear Generated Data option and re-solve your analysis.
– FileOpen
– FolderOpen
– PropertyTable
These controls are implemented using the Ansys UI Toolkit, which is currently not supported on Linux
when executed within Mechanical.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 51
Mechanical API Notes
When no extensions are loaded, there are some limitations on the Graphics API from the ACT
Console in Mechanical (and also in Ansys DesignModeler). For instance, Factory2D does not work.
Therefore, you should load one or more extensions before using the Graphics API from the ACT
Console.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
52 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Access
Using APIs, you can access Mechanical tree objects. The object representing the project node of the
tree is DataModel.Project.
Each object can have children that you access by using the property Children. For example, assume
that the Outline view in Mechanical looks like this:
To return all objects directly under the Project node, you enter this:
DataModel.Project.Children
Under the Project node is the Model node. Some examples follow for accessing Model child nodes:
Mesh = Model.Mesh
Connections = Model.Children[3]
To access all objects with a given name, you use the method GetObjectsByName:
DataModel.GetObjectsByName("name")
To access all objects if a given type, you use the method GetObjectsByType and pass the data
model object category (such as DataModelObjectCategory.Force) as an argument:
DataModel.GetObjectsByType(DataModelObjectCategory.Force)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 53
Object Access
Property Types
Each object in the tree might have properties that display in the Details view. The APIs use a handful
of types to refer to different kinds of properties. Descriptions and examples of the most common types
follow.
My_object.Location = my_selection
Tree
The Tree object provides access to the Mechanical tree.
To access this object, simply enter Tree. The following table provides a sampling of the APIs available
on this object. Some usage examples appear after the table. For a comprehensive listing of methods
and properties of the Tree, see Tree in the ACT Online API and XML Reference Guide.
Member Description
ActiveObjects Lists all selected objects. Read-only.
AllObjects Lists all of the objects available in the tree.
Read-only.
GetPathToFirstActiveObject Shows the full statement that must be typed to get
the selected object.
Refresh Refreshes the tree.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
54 of ANSYS, Inc. and its subsidiaries and affiliates.
Tree
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 55
Object Access
Here are some other helpful APIs for performing tasks in the tree:
• Iterating
for obj in Tree
• Sort
Tree.Sort()
Tree.ClearSort()
• Filter
Tree.Filter(tag="tagname")
Tree.Filter(state=ObjectState.Suppressed)
Tree.Filter(visibility=False)
Tree.ClearFilter
• Find
objects = Tree.Find(name="substring", state=ObjectState.Unsuppressed)
• Events
def myFunc(sender, args):...
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
56 of ANSYS, Inc. and its subsidiaries and affiliates.
Model Objects
Tree.OnActiveObjectChanged += myFunc
• Grouping
Tree.Group([obj1, obj2, obj3, ...])
Tree.HideAllGroupingFolders()
Tree.ShowAllGroupingFolders()
• Multi-select
Tree.Activate([obj1, obj2, obj3, ...])
Model Objects
The following topics describe the objects Geometry, Mesh, Connections, and Analysis and how
you can access and manipulate them:
Accessing and Manipulating the Geometry Object
Accessing and Manipulating the Mesh Object
Accessing and Manipulating the Connections Object
Accessing and Manipulating the Analysis Object
The Geometry object exposes several convenient methods for adding child objects. For example,
you can add a point mass to the Geometry object by calling the method AddPointMass.
point_mass = geometry.AddPointMass()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 57
Object Access
Combining the three previous actions, the geometry now contains a fully defined point mass.
You can export the Geometry object to an STL (STereoLithography) file, which is the most commonly
used file format in 3D printing. The following command exports the geometry object to an STL file.
Model.Geometry.ExportToSTL("C:\Temp\geoasstl.stl")
The result is the creation of a geometry file (geoasst1.stl) to the fully qualified directory path
(C:\Temp).
The Mesh object exposes several convenient methods to add mesh controls. For example, you can
create a meshing control that applies a patch-independent algorithm to the mesh by calling the
method AddAutomaticMethod.
mesh_method = mesh.AddAutomaticMethod()
Mesh control objects often require a valid scoping. You can satisfy this requirement by setting
the Location property:
my_selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
my_selection.Ids = [16]
mesh_method.Location = my_selection
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
58 of ANSYS, Inc. and its subsidiaries and affiliates.
Model Objects
mesh_method.MeshBasedDefeaturing = True
mesh_method.DefeaturingTolerance = Quantity("0.0001 [m]")
mesh_method.MinimumSizeLimit = Quantity("0.001 [m]")
mesh_method.NumberOfCellsAcrossGap = 1
mesh_method.CurvatureNormalAngle = Quantity("36 [degree]")
mesh_method.SmoothTransition = True
mesh_method.TetraGrowthRate = 1
Weld allows scripting. Weld scripting allows you to view and edit the erroring welds easily when
working with complex models. The Weld control functions can be accessed as follows:
weld.ControlType = WeldType.Seam #Sets the Weld Type as Continuous Seam (Seam). The other option available for
weld.Source = WeldSource.Geometry #Sets the Weld Source as Geometry. The other option available for Weld Source
weld.ModeledAs = WeldModeledAs.TentAndExtension #Sets the WeldModeledAs as Normal and Angled (Tent and Extension
weld.CreateUsing = WeldCreateUsing.Curves #Sets the WeldCreateUsing as Curves. This option is only available wh
Weld.TentDirection = WeldTentDirection.Normal #Sets the direction of tent. The other option available for WeldTe
weld.UseWorksheet = YesNoType.No #Enables the Worksheet if set to Yes.
weld.Suppressed = False
weld.AdjustWeldHeight = YesNoType.No #Enables AdjustWeldHeight if set to Yes.
weld.CreationCriteria = WeldCreationCriteria.Width #Sets the Creation Criteria as Width. The other option availa
weld = DataModel.GetObjectById(object_id) #Gets the object by its id.
weld.EdgeMeshSize = Quantity(9.0, "mm")#Provides the EdgeMeshSize.
weld.CreateOffsetLayer = YesNoType.Yes #Creates offset layers if set to Yes.
weld.OffsetLayerHeight = Quantity(9.0, "mm") #Sets the OffsetLayerHeight.
weld.NumberOfLayers = 1 #Sets the number of layers.
weld.OffsetLayerGrowthRate = 1.2 #Set the growth rate for offset layer.
weld.GenerateEndCaps = YesNoType.Yes #Generates triangular end-caps if set to Yes at the free ends of the welds.
weld.GenerateNamedSelection = WeldGeneratedNamedSelection.No # Sets the Generated NamedSelection. The other opti
weld.MaterialId = None # Sets the material by its id. Here, 0 denotes None and 10 denotes Structural Steel.
weld.ThicknessAssignment = WeldThickness.Automatic #Sets the weld thickness. The other options available for wel
weld.SharpAngle = Quantity(30, "deg") #Set the Sharp Angle. Here, the default angle is 30 degrees. You can set t
weld.ConnectionTolerance = Quantity(0, "mm")#Sets the Connection Tolerance. The default value is 0. You can set
weld.Smoothing = YesNoType.Yes #Set the Smoothing to Yes by default.
The Connections object exposes several convenient methods for adding connections. For example,
you can add a beam or set the contact type to frictionless on one of the model's contact regions:
beam = connections.AddBeam()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 59
Object Access
contact_region = connections.Children[0].Children[0]
contact_region.ContactType = ContactType.Frictionless
Beam objects require a valid scoping. You can satisfy this requirement by setting the appropriate
property. For a beam, you set the ReferenceLocation and MobileLocation properties:
reference_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
reference_scoping.Ids = [110]
beam.ReferenceLocation = reference_scoping
mobile_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
mobile_scoping.Ids = [38]
beam.MobileLocation = mobile_scoping
beam.ReferenceBehavior = LoadBehavior.Deformable
beam.ReferencePinballRegion = Quantity("0.001 [m]")
beam.Radius = Quantity("0.005 [m]")
beam.MobileZCoordinate = Quantity("6.5E-03 [m]")
beam.MobilePinballRegion = Quantity("0.001 [m]")
To access the first Analysis object in the tree and its settings:
analysis1 = Model.Analyses[0]
analysis_settings = analysis1.AnalysisSettings
The Analysis object exposes several convenient methods. For example, you can add boundary
conditions like bolt pretensions, loads, and fixed supports:
bolt = analysis1.AddBoltPretension()
pressure = analysis1.AddPressure()
force = analysis1.AddForce()
support = analysis1.AddFixedSupport()
Boundary condition objects often require a valid scoping. You can satisfy this requirement by setting
Location properties:
pressure_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
pressure_scoping.Ids = [220]
pressure.Location = pressure_scoping
force_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
force_scoping.Ids = [219]
force.Location = force_scoping
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
60 of ANSYS, Inc. and its subsidiaries and affiliates.
Analysis Settings Object
Step Controls
For the Step Controls, you can modify all of the properties without the need to change the Current
Step Number property.
Nonlinear Controls
For the Nonlinear Controls category, you can modify the various convergence properties that are
"step aware" (can vary per step) as well as Stabilization.
Output Controls
For the Output Controls category, you can modify the Store Results At property and its accompa-
nying Value property.
Note:
Review the Analysis Settings section for the above categories as well as the Steps and Step
Controls for Static and Transient Analyses section of the Mechanical User's Guide for additional
information about step-based properties and analyses.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 61
Object Access
This example modifies the Force Convergence property and sets its corresponding Value and Tolerance
properties.
This example modifies the Store Results At property and sets its corresponding Value property.
Object Traversal
The following topics describe how to traverse the objects Geometry, Mesh, and Results:
Traversing the Geometry
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
62 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Traversal
Note:
• The sample code in this section is taken from the supplied extension TraverseExten-
sion. You can download the package of extension examples from the developer help
panel for the ACT Start Page.
• For comprehensive information on interfaces and properties, see the Ansys ACT API Reference
Guide.
An example Python function to traverse geometry data follows. Here, an object of type IGeoData
is obtained from the object Analysis using the property GeoData. The object GeoData is then
used to access the list of IGeoAssembly with the property Assembly. For each of the objects in
this list, the property Parts is used to access the list of IGeoPart objects on the assembly. This
pattern is repeated through the hierarchy of the geometry down to the vertices of each edge.
def traversegeometry(analysis):
now = datetime.datetime.now()
f = open("C:\\geoDump.txt",'w')
f.write("*.*.*.*.*.*.*.*\n")
f.write(str(now)+"\n")
# --- IGeometry Interface
# +++ Properties and Methods
# +++ Assemblies
# +++ CellFromRefId
# +++ SelectedRefIds
geometry = analysis.GeoData
assemblies = geometry.Assemblies
assemblies_count = assemblies.Count
# --- IGeoAssembly Interface
# +++ Properties and Methods
# +++ Name
# +++ Parts
for assembly in assemblies:
assembly_name = assembly.Name
parts = assembly.Parts
parts_count = parts.Count
# --- IGeoPart Interface
# +++ Properties and Methods
# +++ Name
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 63
Object Access
# +++ Bodies
for part in parts:
part_name = part.Name
bodies = part.Bodies
bodies_count = bodies.Count
# --- IGeoBody Interface
# +++ Properties and Methods
# +++ Name
# +++ Vertices
# +++ Edges
# +++ Faces
# +++ Shells
# +++ Material
for body in bodies:
faces = body.Faces
faces_count = faces.Count
# --- IGeoFace Interface
# +++ Properties and Methods
# +++ Body
# +++ Shell
# +++ Vertices
# +++ Edges
# +++ Loops
# +++ Area
# +++ SurfaceType
# +++ PointAtParam
# +++ PointsAtParams
for face in faces:
edges = face.Edges
edges_count = edges.Count
# --- IGeoEdge Interface
# +++ Properties and Methods
# +++ Faces
# +++ Vertices
# +++ StartVertex
# +++ EndVertex
# +++ Length
# +++ CurveType
# +++ Extents
# +++ IsParamReversed
# +++ ParamAtPoint
# +++ PointAtParam
# +++ PointsAtParams
for edge in edges:
vertices = edge.Vertices
vertices_count = vertices.Count
# --- IGeoVertex Interface
# +++ Properties and Methods
# +++ Edges
# +++ Faces
# +++ Bodies
# +++ X
# +++ Y
# +++ Z
for vertex in vertices:
xcoord = vertex.X
ycoord = vertex.Y
zcoord = vertex.Z
try:
f.write(" Vertex: "+vertex.ToString()+", X = "+xcoord.ToString()+", Y = "+y
except:
continue
f.close()
return
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
64 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Traversal
An example Python function to traverse mesh data follows. Here, an object of type IMeshData is
obtained from the object Analysis using the property MeshData. The object IMeshData is then
used to access the list of element IDs with the property Elements. Using each of the element IDs
in the returned list, the method ElementbyId is called to access the element data with IElement.
This pattern is repeated for all of the nodes for each element. Finally, the coordinates of the nodes
are queried.
import datetime
def traversemesh(analysis):
now = datetime.datetime.now()
f = open("C"\\MeshDump.txt",'w')
f.write("*.*.*.*.*.*.*.*\n")
f.write(str(now)+"\n")
# --- IMesh Interface
# +++ Properties and Methods
# +++ MeshRegion
# +++ Node
# +++ Element
# +++ Nodes
# +++ Elements
# +++ NumNodes
# +++ NumElements
mesh = analysis.MeshData
elementids = mesh.ElementIds
# --- IElement Interface
# +++ Properties and Methods
# +++ Id
# +++ Type
# +++ Nodes
for elementid in elementids:
element = mesh.ElementById(elementid)
nodeids = element.NodeIds
# --- INode Interface
# +++ Properties and Methods
# +++ Id
# +++ X
# +++ Y
# +++ Z
# +++ Elements
for nodeid in nodeids:
node = mesh.NodeById(nodeid)
nodex = node.X
nodey = node.Y
nodez = node.Z
try:
f.write(" Element: "+elementid.ToString()+" Node: "+nodeid.ToString()+", X = "+nodex.ToStr
except:
continue
f.close()
return
Another example of traversing the mesh data follows. Only the elements of user-selected geometry
entities are considered. The property CurrentSelection on the Selection Manager can be used
to query the IDs of the selected geometry entities.
def elementcounter(analysis):
with open("C:\\SelectedMeshEntities.txt”,'w') as f:
geometry = analysis.GeoData
smgr = ExtAPI.SelectionManager
selectedids = smgr.CurrentSelection.Ids
mesh = analysis.MeshData
if selectedids.Count == 0:
fwrite("Nothing Selected!")
return
for selectedid in selectedids:
entity = geometry.GeoEntityById(selectedid)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 65
Object Access
meshregion = mesh.MeshRegionById(selectedid)
try:
numelem = meshregion.ElementCount
f.write("Entity of type: "+entity.Type.ToString()+
" contains "+numelem.ToString()+
" elements.")
except:
f.write("The mesh is empty!")
return
Traversing Results
The API for direct result access allows you to do postprocessing without result objects.
An example python function to compute minimum and maximum results follows. It begins by instan-
tiating a result reader using the method analysis.GetResultsData(). Results are retrieved
relative to the finite element model and queried using either the elementID (elemental result) or
the nodeID (nodal result). The displacement result U is a nodal result, whereas the stress result S is
a result on nodes of the elements. The displacement result stores a set of component values for each
node, where the component names are X, Y, and Z.
The function first iterates over the nodeIDs to compute the minimum and maximum values. It then
iterates over the elementIDs and the nodes of each element to compute the minimum and max-
imum values.
Note:
The second loop over the nodes is filtered to the corner nodes of the elements because
stress results are available only on these corner nodes.
num = 0
for nodeid in nodeids:
#
# Get the component displacements (X Y Z) for this node
#
dispvals = displacement.GetNodeValues(nodeid)
#
# Determine if the component diplacement (X Y Z) is min or max
#
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
66 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Traversal
if num == 0:
maxdispx = dispvals[0]
mindispx = dispvals[0]
maxdispy = dispvals[1]
mindispy = dispvals[1]
maxdispz = dispvals[2]
mindispz = dispvals[2]
num += 1
num = 0
for elementid in elementids:
element = meshObj.ElementById(elementid)
#
# Get the SXX stress component
#
stressval = stress.GetElementValues(elementid)
#
# Get the primary node ids for this element
#
nodeids = element.CornerNodeIds
for i in range(nodeids.Count):
#
# Get the SXX stress component at node "nodeid"
#
SXX = stressval[i]
#
# Determine if the SXX stress component is min or max
#
if num == 0:
maxsxx = SXX
minsxx = SXX
num += 1
#
# Write the results to the output
#
f.write("Max U,X:Y:Z = "+maxdispx.ToString()+" : "+maxdispy.ToString()+" : "+maxdispz.ToString()+"\n")
f.write("Min U,X:Y:Z = "+mindispx.ToString()+" : "+mindispy.ToString()+" : "+mindispz.ToString()+"\n")
f.write("Max SXX = "+maxsxx.ToString()+"\n")
f.write("Min SXX = "+minsxx.ToString()+"\n")
f.close()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 67
Object Access
To list all properties that could be in the Details view for an object of this type, including those that
are hidden, you enter:
rectbar.Properties
You can use property APIs to get the property’s unique internal name, caption, internal value, and
whether it is valid, visible, or read-only. You can also use APIName from the property APIs to see which
API can be used directly on rectbar for the given Details view property, if an API exists.
Tip:
To change the internal value for any property, even one not yet wrapped by an API,
you can specify the property's index value and then the current value and replacement
value, entering something like this:
obj.Properties[0].InternalValue = newValue
For a scripting example, see Get All Visible Properties for a Tree Object (p. 184).
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
68 of ANSYS, Inc. and its subsidiaries and affiliates.
Solver Data
This also adds the Parameter Set bar to the Workbench Project Schematic. Double-clicking the Para-
meter Set bar opens it so that you can see all input and output parameters in the project.
This method returns an instance of the DetailsViewParameter class. It can be used to query the
Workbench ID for the parameter in the Parameter Set bar. You can also query the object and property
name for which the parameter was created:
ID GetParameter(name)
Object GetParameter(name)
PropertyName GetParameter(name)
For a scripting example, see Parametrize a Property for a Tree Object (p. 184).
Solver Data
You can use SolverData APIs to get global items applicable to the solver or solver-related data specific
to an object. Currently, SolverData APIs are available only for the MAPDL solver.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 69
Object Access
The following topics describe ways of using SolverData APIs to get global items and object-specific
data:
Getting Global Items for Solver Data
Getting Object-Specific Data
Getting Object-Specific Data for Imported Objects
Important:
• NodeIdsByMaterialId
• ElementIdsByMaterialId
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
70 of ANSYS, Inc. and its subsidiaries and affiliates.
Solver Data
You can use SolverData APIs to retrieve object data for the following objects:
• AM Support
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 71
Object Access
• Beam Connection
• Bearing
• Body
• Contact Region
• Coordinate System
• Joint
• Layered Section
• Remote Point
• Spring
• Surface Coating
• Surface Load
For a scripting example, see Retrieve Object Details Using SolverData APIs (p. 191).
For example, you can use the imported coordinate system to get the collection of coordinate system
IDs for all rows present:
solution = Model.Analyses[0].Solution
solver_data = solution.SolverData
imported_coordinate_system = DataModel.GetObjectsByType(DataModelObjectCategory.ImportedCoordinateSystems)[0]
imported_coordinate_system_data = solver_data.GetObjectData(imported_coordinate_system)
imported_coordinate_system_data[0].SystemId
imported_coordinate_system_data[1].SystemId
imported_coordinate_system_data[2].SystemId
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
72 of ANSYS, Inc. and its subsidiaries and affiliates.
Solver Data
You can use SolverData APIs to retrieve object data for the following imported objects:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 73
Object Access
• Imported Contacts
Imported Contacts
STAT_STRUC = Model.Analyses[0]
SOLN = STAT_STRUC.Solution
SOLVER_DATA = SOLN.SolverData
imported_contacts = DataModel.GetObjectsByType(DataModelObjectCategory.ImportedContacts)[0]
imported_contacts_data = SOLVER_DATA.GetObjectData(imported_contacts)
imported_contacts_data[0].TargetId
imported_contacts_data[0].SourceId
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
74 of ANSYS, Inc. and its subsidiaries and affiliates.
Solver Data
SOLVER_DATA = SOLN.SolverData
imported_premeshed_bolt_pretension = DataModel.GetObjectsByType(DataModelObjectCategory.ImportedPremeshedBoltPre
imported_pbp_data = SOLVER_DATA.GetObjectData(imported_premeshed_bolt_pretension)
imported_pbp_data[0].PretensionNodeIds
imported_pbp_data[0].RealConstantIds
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 75
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
76 of ANSYS, Inc. and its subsidiaries and affiliates.
Boundary Conditions
Unlike many other tree objects, boundary conditions are defined using both the Details and Tabular
Data. This is because boundary conditions can be time, space, or frequency dependent. As such, the
APIs use a type of object called Field. Fields provide access to both independent and dependent variables
defined in the tabular data, as well as the function that can be defined in the Details view.
The APIs for editing boundary conditions mirror the actions that can be performed manually in the
Mechanical interface. With the API, you can:
• Set tabular data, which includes setting discrete input and output values
This section describes APIs that enable you to manipulate boundary condition fields.
Input and Output Variables
Variable Definition Types
Setting Input Loading Data Definitions
Setting Variable Definition Types
Setting Discrete Values for Variables
Adding a Load
Importing a Load from External Data
Extracting Min-Max Tabular Data for a Boundary Condition
Setting the Direction of a Boundary Condition
• Discrete. The variable contains a discontinuous set of values. By default, most variables are initially
defined as discrete. Tabular or constant boundary conditions are considered discrete in the API.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 77
Boundary Conditions
• Free. This variable definition type is available only for certain boundary conditions such as dis-
placements.
When you use the Field API to define a boundary condition field, it automatically opts for the least
complex loading data definition that is applicable to the input. For example, if a given input could be
defined as Constant (ramped) but you execute commands defining it as Tabular, the API defines the
input as Constant (ramped).
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
78 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Variable Definition Types
Note:
You can also change the variable definition type to Discrete or Free by using the property
Variable.DiscreteValues as described in Setting Discrete Values for Variables (p. 81).
In Mechanical, you can see that by default, the variable definition types for the displacement’s X, Y,
and Z components are set to Free.
You can verify this by executing the following commands one at a time.
d.XComponent.Output.DefinitionType
d.YComponent.Output.DefinitionType
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 79
Boundary Conditions
d.ZComponent.Output.DefinitionType
Note:
Even though the expression d.XComponent.Output would produce the same output
in the console when the component is Free, be aware that output is an instance of the
Variable class. This object is then converted into a string by the console. Appending
.DefinitionType to the expression yields the actual enum value.
d.YComponent.Output
• The Y Component is set to Tabular Data because tabular data is the least complex discrete loading
data definition that is applicable to this input.
• The Tabular Data window is now populated with output values of 0 and 0.
• In the Shell, you can verify that the variable definition type is set to Discrete.
• In the Shell, you can verify that the output values are 0 and 0.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
80 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Discrete Values for Variables
In the following figure, you can see that the Y Component is set back to Free and the Tabular Data
window is now empty.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 81
Boundary Conditions
Note:
Input values for a discrete variable must be in a sorted order as shown in this example:
Pressure.Magnitude.Inputs[0].DiscreteValues = [Quantity("0 [s]"), Quantity("1 [s]"), Quantity("2 [s]"), Qua
• The output cells for rows 3 through 7 have a yellow background. This is because values have not
been set for the output variable.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
82 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Discrete Values for Variables
In the Tabular Data window, only six rows now show once again. The value =0 is actually a repeat
of the value in the first row and does not correspond to an actual value stored for the variable. This
is because the tabular data in Mechanical always displays a row for time values that correspond to
step end times.
The following table shows the get behavior for the different variable definition types.
The following table shows the set behavior according to the list content provided to the property.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 83
Boundary Conditions
• Change the number of input values first, as the input value count is used
to determine the row count of the tabular data. Output values must then
comply with this number of rows.
The following figure shows a sample message.
The variable definition type can also be modified by setting the DiscreteValues property on
the variable. To set a variable to a particular variable type, you set the values that are consistent
with that variable type. Examples follow:
Adding a Load
You use the object Analysis to add a load. This topic describes adding loads to a static structural ana-
lysis.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
84 of ANSYS, Inc. and its subsidiaries and affiliates.
Adding a Load
support = static_structural.AddFixedSupport()
support_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
support_scoping.Ids = [104]
support.Location = support_scoping
To add and define the external and internal pressures exerted on the pipe and the force on a section
of the pipe:
pressure = static_structural.AddPressure()
pressure_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
pressure_scoping.Ids = [220]
pressure.Location = pressure_scoping
pressure.Magnitude.Output.Formula = '10*time'
pressure = static_structural.AddPressure()
pressure_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
pressure_scoping.Ids = [221]
pressure.Location = pressure_scoping
pressure.Magnitude.Output.DiscreteValues=[Quantity('6 [Pa]')]
force = static_structural.AddForce()
force_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
force_scoping.Ids = [219]
force.Location = force_scoping
force.Magnitude.Output.DiscreteValues=[Quantity('11.3 [N]'), Quantity('12.85 [N]')]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 85
Boundary Conditions
You can also change the force to be defined by components instead of by magnitude and set the values
of an individual component:
force.DefineBy = LoadDefineBy.Components
force.ZComponent.Output.DiscreteValues = [Quantity('0 [N]'),Quantity('-9 [N]')]
analysis_times=[0.,100.,200.,300.,400.,600.,800.,900.,1000.,1200.,1400.,1500.,1700.,1800.,2000.,2400.,2600.,3000.]
fc_scaling=[0.,1.,1.,1.,0.,0.,0.,1.,0.,1.,1.,1.,2.,1.,1.,1.,.5,.25,1.,1.]
at_scaling=[.25,1.,1.,.95,.95,1.,1.,1.2,1.2,1.,1.,.95,.95,.5,.5,.2,.2,1.,1.]
fc_id='File1:HTC1' # identifier for film coefficient (should match External Data definition)
at_id='File1:Temperature1' # identifier for ambient temperature (should match External Data definition)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
86 of ANSYS, Inc. and its subsidiaries and affiliates.
Importing a Load from External Data
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 87
Boundary Conditions
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
88 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting the Direction of a Boundary Condition
First, get the project model object, analysis object, force object, and the output variable with the applied
force variables:
mymodel = DataModel.Project.Model
anal = mymodel.Analyses[0]
f2 = anal.Children[2]
f2td = f2.Magnitude.Output
Next, get the tuple containing the minimum and maximum force quantities and then display these
quantities by entering the variable name of the tuple:
mnmxf2 = f2td.MinMaxDiscreteValues
mnmxf2
The variable mnxf2 is a tuple (pair) of quantities. Each element in the tuple can be gotten by using
the tuple's properties Item1 and Item2.
(0 [lbf])
(300 [lbf])
To set the direction of a load using the direction from a face or edge or between points:
sels = ExtAPI.SelectionManager.CurrentSelection
reversed = True
vec = Ansys.Mechanical.Selection.SelectionHelper.CreateVector3D(sels, reversed)
acceleration.Direction = vec
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 89
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
90 of ANSYS, Inc. and its subsidiaries and affiliates.
Worksheets
You can use Mechanical APIs to access or modify data that is displayed by the user interface in the
worksheet panel:
Named Selection Worksheet
Mesh Order Worksheet
Layered Section Worksheet
Bushing Joint Worksheet
Condensed Part Worksheet
The following topics describe how to use APIs to define a named selection worksheet:
Defining the Named Selection Worksheet
Adding New Criteria to the Named Selection Worksheet
When executed, this sample code creates the named selection object, renames it "Pipe," and automat-
ically sets the Define By to Worksheet. It also stores a variable of the NamedSelectionCriteria object
that can be used to manipulate the data in the worksheet.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 91
Worksheets
Further Worksheet specifications are required to completely define the Named Selection.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
92 of ANSYS, Inc. and its subsidiaries and affiliates.
Named Selection Worksheet
The NamedSelectionCriteria object behaves like a list and has standard list properties and
methods including Add(), Clear(), Count, Insert, Remove, and a [] indexer. You can use the
Add() method to add a NamedSelectionCriterion, which is the object for each element in the list
and controls the data of a single row in the worksheet.
This example defines a criterion to select bodies with a size value greater than 3.8e-5.
The method Generate on the NamedSelection object generates the selection based on the cri-
teria. After executing this method, observe that the pipe body is selected in the Graphics view. In
the Details view, the property Total Selection is set to 1 Body.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 93
Worksheets
This new criteria is defined to select bodies whose distance from a given coordinate system is less
than 3.8e-6. If you do not specify a coordinate system, it defaults to the global coordinate system.
After executing the Generate method, observe that the bolt body is now selected in the Graphics
view, along with the pipe body. In the Details view, the property Total Selection is set to 2 Bodies.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
94 of ANSYS, Inc. and its subsidiaries and affiliates.
Mesh Order Worksheet
• The named selections must have Entity Type set to Body. Other entity types are not supported.
• The Start Recording and Stop Recording buttons do not have APIs.
The examples in this section assume that you have already defined two or more named selections in
Mechanical. In the following figure, three named selections are defined.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 95
Worksheets
• The command SetNamedSelection sets the value in the Named Selection column to your
named selection variable ns1.
• The command SetActiveState sets Active State at the row index. This is indicated by the
check mark in the left column.
The following figure shows the mesh worksheet after the execution of these commands.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
96 of ANSYS, Inc. and its subsidiaries and affiliates.
Mesh Order Worksheet
To add a row for each of the other two named selections, ns2 and ns3, use these commands:
mws.AddRow()
mws.SetNamedSelection(1,ns2)
mws.SetActiveState(1,True)
mws.AddRow()
mws.SetNamedSelection(2,ns3.)
mws.SetActiveState(2,True)
The following figure shows the mesh worksheet after the two new rows have been added.
When you execute this command, the steps are processed one by one in the order specified by the
worksheet. For each step, the bodies identified by the named selection are meshed using the meshing
controls applied to them. By watching the mesh generation in the Graphics tab, you can see the order
in which each body is meshed.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 97
Worksheets
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
98 of ANSYS, Inc. and its subsidiaries and affiliates.
Mesh Order Worksheet
row_id =[2] #Add the row id. Here, the row id is 2. Multiple row id can be added with comma separation.
edgemesh_size=2.0 #Define the size of the edge mesh.
weld.SetWeldWorksheetEdgeMeshSize([row id], edgemesh_size)
row_id =[1] #Add the row id. Here, the row id is 2. Multiple row id can be added with comma separation.
weld_angle=30 #Define the weld angle.
weld.SetWeldWorksheetWeldAngle([row_id], weld_angle)
row_id = [1] #Add the row id. Multiple row id can be added with comma separation.
offset_layer_height = 30 #Define offset layer height.
weld.SetWeldWorksheetOffsetLayerHeight([row_id], offset_layer_height)
row_id = [1] #Specify the row id. Multiple row id can be added with comma separation.
num_layers = 1 #Define the required number of layers.
weld.SetWeldWorksheetNumLayers([row_id], num_layers)
row_id = [1] #Specify the row id. Multiple row id can be added with comma separation.
offset_layer_growth_rate = 1.3 #Define the growth rate for offset layer
weld.SetWeldWorksheetOffsetLayerGrowthRate([row_id], offset_layer_growth_rate)
row_id = [1] #Specify the row id. Multiple row id can be added with comma separation.
sharp_angle = 20 #Define the sharp angle.
weld.SetWeldWorksheetSharpAngle([row_id], sharp_angle)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 99
Worksheets
row_id = [1] #Specify the row id. Multiple row id can be added with comma separation.
absolute_tolerance= 10 #Define the absolute tolerance.
weld.SetWeldWorksheetAbsTol([row_id], absolute_tolerance)
row_id = [1] #Specify the row id. Multiple row id can be added with comma separation.
lapangle_tolerance= 10 #Define the lap angle tolerance.
weld. SetWeldWorksheetLapAngleTol([row_id], lapangle_tolerance)
row_id = [1] #Specify the row id. Multiple row id can be added with comma separation.
material_id= 10 #Specify the material id.
weld.SetWeldWorksheetMaterialId([row_id], material_id)
row_id = [10] #Specify the row id. Multiple row id can be added with comma separation.
smoothing= 0 #Set Smoothing to No. 0 is the default value. 1 - Enables Smoothing and 0 - Disables Smoothing.
weld.SetWeldWorksheetSmoothing([row_id], smoothing)
row_id = [3] #Specify the row id. Multiple row id can be added with comma separation.
generate_endcaps= 0 #Generates triangular end caps at the free ends of the weld.
weld.SetWeldWorksheetGenerateEndCaps(row_id, generate_endcaps)
• To control the data in the material column, use the GetMaterial or SetMaterial method.
• To control the data in the Thickness column, use the GetThickness or SetThickness
method.
• To control the data in the Angle column, use the GetAngle or SetAngle method.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
100 of ANSYS, Inc. and its subsidiaries and affiliates.
Condensed Part Worksheet
For example, to get the coefficient for the stiffness per unit Y at row index 1:
bws.GetBushingStiffnessPerUnitY(1)
The given index of 0 (zero) produces an error message because the cell indicated is in the upper right
triangle. As per the error message, the valid range of indices is 2 to 5, inclusive.
The following figure shows some of the many methods available for getting coefficients for damping
and stiffness using the Mechanical Scripting view's autocomplete feature.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 101
Worksheets
Because the index is 0, this sample code gets the first condensed part and stores a variable of the
CondensedPartInterfaces object that can be used to modify the data in the worksheet.
• Add()
• Clear()
• RemoveAt()
• Indexer
You can use the Add() method to add CondensedPartInterface, which is the object for each element
in the list and controls the data of a single row in the worksheet.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
102 of ANSYS, Inc. and its subsidiaries and affiliates.
Graphics
This section describes APIs related to graphics:
Setting Graphics View Options
Setting the Display Options for Annotations
Result Vector Display Options
Manipulating Graphics
Exporting Graphics
Exporting Result or Probe Animations
Creating Section Planes
Inserting Image Plane
Setting Model Lighting Properties
Manage Views with Model View Manager
Property Description
ShowLegend Gets or sets whether a legend is shown for the result object.
ShowTriad Gets or sets whether the triad is shown.
ShowRuler Gets or sets whether the ruler is shown.
Reset Resets the graphics view properties to the defaults.
ShowMesh Gets or sets whether to display the model’s mesh.
ShowRandomColors Gets or sets whether to show random colors for each object of the application.
ShowVertices Gets or sets whether to display all the vertices of the model.
ShowClustered- Gets or sets whether to display all closely clustered vertices of the model.
Vertices
ShowEdgeDirection Gets or sets whether to display the edge direction arrow.
ShowMeshConnection Gets or sets whether to display edge connection using a color scheme based
on the mesh connection information.
ShowThickEdgeScop- Gets or sets whether to thicken the display of edge scoping.
ing
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 103
Graphics
Property Description
ModelDisplay Gets or sets the model display options.
ModelColoring Gets or sets the model display coloring options.
RescaleAnnotations Rescales the size of annotations following a zoom in or zoom out of the model.
ShowCoordinateSys- Gets or sets whether to display all defined coordinate systems.
tems
ClusteredVertexTol- Gets or set the clustered vertices tolerance value.
erance
ShowBeamThickness Gets or sets whether to display the thickness of beams.
ShowShellThickness Gets or sets whether to display the thickness of shells.
ShowSPHExpansion Gets or sets whether to display the expansion for sph elements.
ShowRemotePointCon- Gets or sets whether to display the Remote Point Connections.
nections
Code Examples
This code hides the ruler and the triad and shows the legend for the active result:
Graphics.ViewOptions.ShowRuler = False
Graphics.ViewOptions.ShowLegend = True
Graphics.ViewOptions.ShowTriad = False
This code modifies the global view options settings by rescaling the annotations, setting the model
display by shaded exterior, model coloring by material, setting the clustered vertex tolerance to 0.5 and
displaying the clustered vertices:
Graphics.ViewOptions.RescaleAnnotations()
Graphics.ViewOptions.ModelDisplay = ModelDisplay.ShadedExterior
Graphics.ViewOptions.ModelColoring = ModelColoring.ByMaterial
Graphics.ViewOptions.ClusteredVertexTolerance = Quantity( 0.5, 'm')
Graphics.ViewOptions.ShowClusteredVertices = True
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
104 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Graphics View Options
This code displays connection lines between geometry and Remote Points or between supported remote
boundary conditions and Remote Points.
Graphics.ViewOptions.ShowRemotePointConnections = True
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 105
Graphics
For information about legend settings for Mechanical results, see Working with Legends (p. 152).
Property Description
PointMassS- Gets or sets the size for point mass annotation. (Small -Large; 1-100).
ize
SpringSize Gets or sets the size for spring annotation. (Small - Large; 1-100).
The following methods enables you to specify annotation node and element numbering.
Property Description
SetNodeNumbering Sets the begin, end, and increment values to display node numbering.
SetElementNumber- Sets the begin, end, and increment values to display element numbering.
ing
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
106 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting the Display Options for Annotations
Code Examples
This code example sets the visibility of all annotation labels to false and the Point Mass annotation to
true.
Graphics.ViewOptions.AnnotationPreferences.ShowLabels = False
Graphics.ViewOptions.AnnotationPreferences.ShowPointMasses = True
This code sets the size of Point Mass sphere. The supported size range is between 1-100. Although not
entered as a value, this sizing is also available using the Preferences option in the Annotation group
on the Display tab.
Graphics.ViewOptions.AnnotationPreferences.PointMassSize = 20
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 107
Graphics
This code example sets the visibility to show node numbers to true and displays the first 76 node
numbers incremented by a value 4.
Graphics.ViewOptions.AnnotationPreferences.ShowNodeNumbers = True
Graphics.ViewOptions.AnnotationPreferences.SetNodeNumbering(1,76,4)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
108 of ANSYS, Inc. and its subsidiaries and affiliates.
Result Vector Display Options
Additionally, to access result vector display options, you use the command VectorDisplay:
Graphics.ViewOptions.VectorDisplay
Property Description
LengthType Gets or sets the result vector length type.
DisplayType Gets or sets the result vector display type.
ControlDisplayDens- Gets or sets the ability to manually control the vector display density.
ity
DisplayDensity Gets or sets the vector display density in percentage.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 109
Graphics
Property Description
LengthMultiplier Gets or sets the vector length multiplier.
ShowTriadXAxis Gets or sets whether to display the X axis vector of the triad/tensor.
ShowTriadYAxis Gets or sets whether to display the Y axis vector of the triad/tensor.
ShowTriadZAxis Gets or sets whether to display the Z axis vector of the triad/tensor.
Code Examples
This code modifies the result vectors by changing the length type to proportional, setting the display
type to solid, setting the display density to 30.0%, and setting the length multiplier to 4.0:
Graphics.ViewOptions.VectorDisplay.LengthType = VectorLengthType.Proportional
Graphics.ViewOptions.VectorDisplay.DisplayType = VectorDisplayType.Solid
Graphics.ViewOptions.VectorDisplay.ControlDisplayDensity = True
Graphics.ViewOptions.VectorDisplay.DisplayDensity = 30.0
Graphics.ViewOptions.VectorDisplay.LengthMultiplier = 4.0
Manipulating Graphics
You can use the MechanicalCameraWrapper to manipulate the camera for precise control of model
visualization.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
110 of ANSYS, Inc. and its subsidiaries and affiliates.
Manipulating Graphics
The following properties together represent the state of the camera view:
Property Description
Focal- Gets or sets the focal point of the camera. Coordinates are in the global coordinate
Point system.
Scene- Gets or sets the scene height (in length units) that will be projected and fit to the
Height viewport.
Sce- Gets or sets the scene width (in length units) that will be projected and fit to the
neWidth viewport.
UpVector Gets or sets the vector pointing up from the focal point.
ViewVector Gets or sets the vector pointing from the focal point to the camera.
An example follows for using these properties to change the camera state:
camera.FocalPoint = Point((0.0,0.0,0.0), "mm")
camera.ViewVector = Vector3D(1.0,0.0,0.0)
camera.UpVector = Vector3D(0.0,1.0,0.0)
camera.SceneHeight = Quantity(100, “mm”)
camera.SceneWidth = Quantity(150, “mm”)
In addition to changing one or more specific properties, user-friendly methods are available for manip-
ulating the camera state.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 111
Graphics
Example 1
This code rotates the model by 30 degrees about the direction normal to the current screen display:
camera.Rotate(30, CameraAxisType.ScreenZ)
Example 2
These code samples fit the view to a selection (either a face with a known ID or a named selection).
#fit view to face #28
selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
selection.Ids = [28]
camera.SetFit(selection)
1. Open a model and zoom to fit. The SceneHeight and SceneWidth are equal to the
bounding box of the directed view. There is horizontal padding because the viewport boundary
is larger than the bounding box in that dimension.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
112 of ANSYS, Inc. and its subsidiaries and affiliates.
Manipulating Graphics
2. If you set SceneHeight and SceneWidth to one-third ( ) of their original values, the camera
zooms in. The deciding factor is SceneHeight because of the screen’s aspect ratio and orient-
ation. The scene, defined by SceneWidth and SceneHeight, is then scaled in or out, main-
taining the aspect ratio until the height equals the viewport height.
3. If you now resize the viewport panel to be taller and more slender, the scene defined by
SceneHeight and SceneWidth is then scaled in or out, maintaining the aspect ratio until
the width equals the viewport width.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 113
Graphics
4. Let’s say after point 1, you increase the SceneWidth to something beyond the model
bounding box (such that it includes the padding space).
5. If you enlarge the viewport panel in either direction, the scene parameters still hold their shape.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
114 of ANSYS, Inc. and its subsidiaries and affiliates.
Manipulating Graphics
UpVector Usage
Mathematically, the UpVector and ViewVector of the camera must be perpendicular. Together they
define the camera orientation, which in the following figure is shown by the green half-plane. However,
you can use the API to prescribe any UpVector that is not collinear with the ViewVector. The
camera orientation’s UpVector is then internally computed to use the projection (dashed line) of the
prescribed UpVector (blue line) onto the brown plane perpendicular to the ViewVector (black line).
The camera still reports back the prescribed UpVector with the UpVector property.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 115
Graphics
Note:
In the half-plane, there are an infinite number of prescribed UpVector choices that
result in the same computed UpVector.
Exporting Graphics
You can use the methods Export3D and ExportImage to export graphics to 3D model files (STL
and AVZ) and image files (PNG, JPG, TIF, BMP, and EPS).
To export graphics to model and image files, you use the following commands:
Command Description
Graphics.Export3D Exports the model to an STL or AVZ file.
Graphics.ExportIm- Exports the image to a PNG, JPG, or BMP file.
age[a]
[a] This method supports no GUI mode in Workbench.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
116 of ANSYS, Inc. and its subsidiaries and affiliates.
Exporting Result or Probe Animations
For information on changing the 3D model or image export settings, see Graphics3DExportSettings or
GraphicsImageExportSettings in the ACT API Reference Guide.
The following script exports the model with a white background to an AVZ file and exports the image
with enhanced resolution to a PNG file.
#export model to AVZ file with white background
setting3d = Ansys.Mechanical.Graphics.Graphics3DExportSettings()
setting3d.Background = GraphicsBackgroundType.White
Graphics.Export3D("c:\\avz_white.avz", Graphics3DExportFormat.AVZ, setting3d)
When exporting an animation to a video file, you can set the file name, format, and export settings.
• AnimationExportSettings sets the width and height properties for the file. When this is
not set, the resolution for the current graphics display is used to set the width and height.
Example 1
This code exports a result animation to a MP4 video file:
#Exporting a result animation to mp4 video file
totalDeform = DataModel.GetObjectsByName("Total Deformation")[0]
totalDeform.ExportAnimation("E:\\file.mp4",GraphicsAnimationExportFormat.MP4)
Example 2
This code exports a result animation to a WMV file with a specific resolution (width=1000,height=665):
#Exporting a result animation to wmv video file with given size
totalDeform1 = DataModel.GetObjectsByName("Total Deformation 1")[0]
settings = Ansys.Mechanical.Graphics.AnimationExportSettings(width = 1000, height = 665)
totalDeform1.ExportAnimation("E:\\file.wmv",GraphicsAnimationExportFormat.WMV,settings)
Animation Settings
To control the behavior of the animation for all results, you can specify global animation settings related
to the toolbar visible when the Animation feature is used:
Property Description
Graphics.ResultAnimationOp- Gets or sets the number of frames for the
tions.NumberOfFrames distributed result animation range type.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 117
Graphics
Property Description
Graphics.ResultAnimationOp- Gets or sets the range type of the result animation.
tions.Duration
Graphics.ResultAnimationOp- Gets or sets the number of cycles for the time
tions.TimeDecayCycles decay analysis.
Graphics.ResultAnimationOptions.Up-Gets or sets if the legend contours update at each
dateContourRangeAtEachFrame frame.
Graphics.ResultAnimationOp- Gets or sets the fit deformation scaling at each
tions.FitDeformationScalingToAnim- range for the full range for a result that has
ation multiple time steps.
To access the collection associated with the Section Planes window, you use this command:
Graphics.SectionPlanes
The items in the collection use the SectionPlane object. The following methods and properties can
be used to manipulate the collection:
Command Description
SectionPlanes.Add(SectionPlane) Add a new section plane to the collection.
SectionPlanes.Remove(Section- Remove a new section plane from the collection.
Plane)
SectionPlanes.RemoveAt(0) Remove a section plane at a given index.
SectionPlanes.Clear() Clear all the section planes from the collection.
section_plane = Section- Get a section plane at an index.
Planes[0]
Along with methods and properties to manipulate the collection, the SectionPlanes object has two
global properties that apply to all section planes. These global properties are shown in the Graphics
window:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
118 of ANSYS, Inc. and its subsidiaries and affiliates.
Creating Section Planes
Command Description
SectionPlanes.Capping Capping style of the section plane.
SectionPlanes.ShowWholeEle- Element visibility of the section plane.
ment
Command Description
Graphics.SectionPlanes[0].Center Center point of the section plane.
Graphics.SectionPlanes[0].Type Type of the section plane.
Graphics.SectionPlanes[0].Name Name of the section plane.
Graphics.SectionPlanes[0].Active Active state of the section plane.
Graphics.SectionPlanes[0].Direc- Normal direction of the section plane
tion
Example 1
This code creates a section plane and then both adds and changes the location:
from Ansys.Mechanical.Graphics import SectionPlane
location = [100, 150, 255]
sectionPlane = SectionPlane()
sectionPlane.Center = Point(location, 'mm')
sectionPlane.Direction = Vector3D(0, 0, 1)
sectionPlane.Name = "newPlane"
sectionPlane.Type = SectionPlaneType.AgainstDirection
Graphics.SectionPlanes.Add(sectionPlane)
location = [100, 150, 200]
sectionPlane.Center = Point(location, 'mm')
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 119
Graphics
Example 2
This code modifies the direction of the section plane:
sectionPlane.Direction = Vector3D(0, 1, 0)
Example 3
This code gets the existing section plane and changes its name:
sectionPlane = Graphics.SectionPlanes[1]
sectionPlane.Name = "Plane2"
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
120 of ANSYS, Inc. and its subsidiaries and affiliates.
Creating Section Planes
Example 4
As indicated earlier, while a SectionPlanes collection can have any number of SectionPlane
objects, no more than six SectionPlane objects can be active at once. Assume that your collection
holds six SectionPlane objects, which are all in an active state. If you try to add a new Section-
Plane object with the property Active set to True, the SectionPlane object is added to the
collection. However, the property Active is automatically set to False and an error message is shown:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 121
Graphics
While the collection now holds seven SectionPlane objects, only 6 are active. If you tried to activate
the seventh SectionPlane object by setting its property Active to True, the property is automat-
ically set back to False and an error message again displays that the limit of 6 active planes has been
reached:
Properties Description
Height Gets or sets the physical height of the image plane.
Width Gets or sets the physical width of the image plane.
PixelHeight Gets the pixel height of the plane's image.
PixelWidth Gets the pixel width of the plane's image.
ImageFile- Gets the file path for the rendered image.
Path
Import Sets the image which is rendered to this plane, specified by filePath. Upon
success, the ImageFilePath will be set to the filePath. Upon failure, ImageFilePath
will remain unchanged. Supported file formats include PNG, JPEG, BMP, and GIF.
If this is the first time an image has been set to this image plane and if Width
and Height were never modified, the image plane will be automatically sized
based on the model’s bounding box, respecting the image’s aspect ratio.
Translucency Gets or sets the translucency of the plane, as a percentage ranging from 0 to
100.
Coordin- Gets or sets the coordinate system object used for defining the plane’s location
ateSystem and orientation. This property is restricted to cartesian coordinate systems.
FlipHorizont- Gets or sets whether the rendered image on the plane should be flipped
ally horizontally.
FlipVertic- Gets or sets whether the rendered image on the plane should be flipped vertically.
ally
ShowAlways Gets or sets whether the image plane will be shown independent of the active
object in the tree.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
122 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Model Lighting Properties
Properties Description
Coordin- Gets or sets whether the annotation for the image’s coordinate system is
ateSystemVis- rendered.
ible
Example 1
`
Example 2
The following code changes the location of the image in the Geometry window.
# modifying location and dimensional properties of the image plane
imageOne.CoordinateSystem = csysObj # sets the bottom left corner of the plane at the CSYS’s location
imageOne.Width = Quantity(2.5, ‘m’) # sets world width of the plane
imageOne.Height = Quantity(250, ‘cm’) # sets world height of the plane
Example 3
The following code changes certain view properties of the object.
# modifying view properties of the image plane
imageOne.Translucency = 30 # sets the plane to 30% translucency (70% opacity)
imageOne.FlipHorizontally = True # flips the horizontal orientation of the rendered image (not of the physical pla
imageOne.FlipVertically = False # flips the vertical orientation of the rendered image (not of the physical plane)
imageOne.CoordinateSystemVisible = True # annotates the coordinate system the image is attached to
ImageOne.ShowAlways = True # allows the image to be rendered no matter what object is active in the tree
Property Description
Ambi- Gets or sets the ambient lighting
ent factor.
Dif- Gets or sets the diffuse lighting factor.
fuse
Specu- Gets or sets the specular lighting
lar factor.
Color Gets or sets the lighting color.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 123
Graphics
The following image shows model lighting properties being set in the Details view for the model:
Example 1
This code sets model lighting properties:
Model.Ambient = 0.5
Model.Diffuse = 0.3
Model.Specular = 0.2
Model.Color = 13796830
Example 2
When setting model lighting color, you can also use hex color codes, which are three-byte hexadecimal
numbers consisting of the prefix 0x followed by six digits. Each byte (or pair of characters) following
the prefix represents the intensity of red, green, and blue, respectively. For example, the hex color code
for white is 0xFFFFFF.
This code shows how to use a hex color code to specify a lilac shade ( ) for the model lighting color:
Model.Color = 0xD285DE
You can create a graphical view from current graphics using either a default name or a specified name.
To create a view using a default name:
view_manager.CreateView
The name assigned to the new view is View followed by the next sequential number. To create a view
using a specified name, where viewName is the name to assign to the new view:
view_manager.CreateView(string viewName)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
124 of ANSYS, Inc. and its subsidiaries and affiliates.
Manage Views with Model View Manager
You can apply a graphical view by specifying its name or index. To apply a view by specifying its name,
where viewLabel is the name of the view to apply:
view_manager.ApplyModelView(string viewLabel)
To apply a view by specifying its index, where viewIndex is the index of the listed view to apply:
view_manager.ApplyModelView(int viewIndex)
Additionally there are API’s to cover the other features of Model View Manager such as:
Deleting a view:
DeleteView(“Fit View”)
Renaming a view:
RenameView(“Fit View”, “New Name”)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 125
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
126 of ANSYS, Inc. and its subsidiaries and affiliates.
Results
In Mechanical, the Solution object contains results. To access the Solution object:
solution = Model.Analyses[0].Solution
The following topics describe ways of using the API to add and work with results:
Adding Results to a Solution Object
Accessing Contour Results for an Evaluated Result
Set Result Display Options
Working with Legends
total_deformation = solution.AddTotalDeformation()
analysis = Model.Analyses=[0]
analysis.Solve(True)
minimum_deformation = total_deformation.Minimum
maximum_deformation = total_deformation.Maximum
It results in a solved analysis indicating the values for the properties Minimum and Maximum for the
result Total Deformation.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 127
Results
• The node and element IDs are independent variables (unique identifiers) of the tabular result.
• The result value components are dependent variables (based on the independent variables).
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
128 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
• ElementalNodal: Results are calculated on the element but then interpolated onto the nodes
(like stresses)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 129
Results
Using PlotData you return a result data table for a contour result.
For a Nodal result, the results table displays only node information.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
130 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
For a Elemental result, the results table displays only node information.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 131
Results
For a Elemental Nodal result, the result table has both node and element information (unaveraged
results).
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
132 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
Similarly, you can generate result table for contour results with multiple components.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 133
Results
Example 1
The following script prints the independent The following script snippet prints the
columns of the result table. dependent columns of the result table.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
134 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
Example 2
The following script snippet prints the X component column, unit, count and a specific value of result
table.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 135
Results
Example 3
The following script snippet prints the hidden column (body ids) along with the result table for a
result.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
136 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
Example 4
For the PlotData result shown here:
The following script prints the third row of the result table for X and Y values by indexing each column.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 137
Results
Example 5
The following script prints the Time Steps included in the Static Structural analysis.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
138 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 139
Results
After the contour result scoped to specific entity is evaluated, the following code displays them in
tabular format.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
140 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 141
Results
The result is scoped to the X, Y, and Z coordinates of the path sampling points, and the following
code, once executed, displays them in tabular format.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
142 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 143
Results
For the Surface scoping, the following code displays the result in tabular format.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
144 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
Note:
PlotData displays result values along the X, Y and Z coordinates of the points on
the surface. Exporting surface results displays the result values per facet that creates
the surface and might have duplicate entries as facets share points. Hence the output
of PlotData might miss the point or element pairs present when exporting the
surface result.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 145
Results
The following code accesses the evaluated contour results in the tabular data interface:
result= Model.Analyses[0].Solution.Children[2]
result.PlotData
To view the beam cross section results, set Solution → Beam Section Resultsto Yes:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
146 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
After reevaluating the result, using PlotData to access the beam cross section result gets multiple
results across a single node:
• Results reflect how the application stores the result values, which means that they are not
converted to the user-specified unit system.
• Path results do not display the length across the path of the different points of the path (S
parameter). However, you can retrieve this information by exporting the results to a text file.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 147
Results
• If the path does not have results in all of the nodes (such as through a hole), the empty spaces
currently display huge values (DBL_MAX).
• PlotData displays a snapshot of the result values stored in the application. If you change
properties in the Details view, you must reevaluate and then call PlotData again to get the
updated result values.
Property Description
Deforma- Gets or sets the deformation scale multiplier for the result.
tion-
ScaleMulti-
plier
Deforma- Gets or sets the deformation scale multiplier to either Auto Scale (DeformationScal-
tionScal- ing.Auto) or True Scale (DeformationScaling.True).
ing
ShowMinim- Gets or sets whether to display the result minimum value annotation label.
um
ShowMaxim- Gets or sets whether to display the result maximum value annotation label.
um
Geo- Gets or sets the result geometry view.
metryView
Contour- Gets or sets the result contour view.
View
ExtraMod- Gets or sets the result edge display option.
elDisplay
IsoSurface- Gets or sets the capping value for Capped ISO surface view.
Value
Capping- Gets or sets the result capping type.
Type
ScopingDis- Gets or sets the result scoping display.
play
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
148 of ANSYS, Inc. and its subsidiaries and affiliates.
Set Result Display Options
Examples
Example 1
Or...
Graphics.ViewOptions.ResultPreference.DeformationScaleMultiplier = 10
Graphics.ViewOptions.ResultPreference.DeformationScaling = MechanicalEnums.Graphics.DeformationScaling.Auto
• True (True Scale): A multiplier for the actual deformation of the model.
• Auto (Auto Scale): A multiplier for an application controlled computation for an Auto Scale
of the model.
The example deformations illustrated below demonstrate how an undeformed model is deformed
with the True Scale and an Auto Scale factors.
Undeformed
True Scale
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 149
Results
Auto Scale
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
150 of ANSYS, Inc. and its subsidiaries and affiliates.
Set Result Display Options
Example 2
Example 3
When you scope the result to the bodies shown below, the following code sets the:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 151
Results
You can use legend settings objects to perform such operations as:
• Constructing an independent legend settings object and apply it to the current result
• Copying legend settings from one result object and apply it to another result
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
152 of ANSYS, Inc. and its subsidiaries and affiliates.
Working with Legends
Property Description
LegendOrientation Gets or sets the legend orientation.
ShowDateAndTime Gets or sets whether the date and time is shown.
ShowMinMax Gets or sets whether the minimum and
maximum values are shown.
ShowDeformingScaling Gets or sets whether the deformation scaling is
shown.
Reset Resets the global legend settings to the defaults.
This code changes the legend orientation to horizontal and hides the deformation scaling:
gls = Graphics.GlobalLegendSettings
gls.LegendOrientation = LegendOrientationType.Horizontal
gls.ShowDateAndTime = True
gls.ShowMinMax = True
gls.ShowDeformingScaling = False
Note:
You can only manipulate the legend of the result that is currently active.
These properties are available for the object for result-specific legend settings:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 153
Results
Property Description
NumberOfBands Gets or sets the number of bands on the legend.
AllScientificNotation Gets or sets whether result values are to display
in scientific notation.
Digits Gets or sets the number of significant digits.
ColorScheme Gets or sets the color scheme for the legend.
SemiTransparency Gets or sets whether the legend is
semi-transparent.
LogarithmiScale Gets or sets whether the result values are
distributed in a logarithmic scale.
HighFidelity Gets or sets whether the high fidelity mode is
on.
GetLowerBound Gets the lower bound value of the specified
band.
SetLowerBound Sets the lower bound value of the specified
band.
GetUpperBound Gets the upper bound value of the specified
band.
SetUpperBound Sets the upper bound value of the specified
band.
GetBandColor Gets the color of the specified band.
SetBandColor Sets the color of the specified band.
GetBandColorAuto Gets whether the color of the specified band is
set to Automatic.
SetBandColorAuto Sets the color of the specified band to Automat-
ic.
ResetColors Resets all colors to default values.
ExportLegend Exports the legend settings to an XML file.
Reset Resets all legend customizations to default
values.
This code modifies many result-specific legend settings for the current result object, including
whether result values are to display in scientific notation, number of bands, color scheme, and semi-
transparency, and it then exports these settings to an XML file:
legendSettings = Ansys.Mechanical.Graphics.Tools.CurrentLegendSettings()
legendSettings.AllScientificNotation = False
legendSettings.Digits = 4
legendSettings.NumberOfBands = 7
legendSettings.ColorScheme = LegendColorSchemeType.ReverseGrayScale
legendSettings.SemiTransparency = True
legendSettings.SetLowerBound(0, Quantity(2.38e-8,'m'))
legendSettings.SetUpperBound(0, Quantity(3.38e-8,'m'))
legendSettings.SetUpperBound(1, Quantity(4.38e-8,'m'))
legendSettings.SetUpperBound(2, Quantity(5.38e-8,'m'))
legendSettings.SetBandColor(0, Ansys.Mechanical.DataModel.Constants.Colors.Gray)
legendSettings.SetBandColor(1, Ansys.Mechanical.DataModel.Constants.Colors.Blue)
legendSettings.SetBandColor(2, Ansys.Mechanical.DataModel.Constants.Colors.Cyan)
legendSettings.SetBandColor(3, Ansys.Mechanical.DataModel.Constants.Colors.Green)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
154 of ANSYS, Inc. and its subsidiaries and affiliates.
Working with Legends
legendSettings.SetBandColor(4, Ansys.Mechanical.DataModel.Constants.Colors.Yellow)
legendSettings.SetBandColor(5, Ansys.Mechanical.DataModel.Constants.Colors.Red)
legendSettings.SetBandColor(6, Ansys.Mechanical.DataModel.Constants.Colors.White)
legendSettings.ExportLegend("E://file.xml")
Note:
The following figure shows the legend using the original settings versus the modified settings.
To create the object with the standalone legend settings, you use the command LegendSettings:
legendSettings = Ansys.Mechanical.Graphics.Tools.LegendSettings()
If you want to assign a default unit system, in the command, you would enter the unit system inside
the parentheses:
legendSettings = Ansys.Mechanical.Graphics.Tools.LegendSettings("mm")
The object for the standalone legend settings has a default set of band values (from 0 to 9) and a
default color scheme (Rainbow). You can set or modify any other properties that you care about. It
is also possible to set the minimum and maximum for the standalone legend to mimic the minimum
and maximum of a result:
legendSettings.SetMinMax(Quantity(1,'m'),Quantity(100,'m'))
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 155
Results
If result-specific legend settings have been exported to an XML file, you can import these settings to
create standalone legend settings:
legendSettings = Graphics.ImportLegend("E://file.xml",'m')
Copying Legends
You can copy the legend settings from the current result onto an object for standalone legend settings.
Conversely, you can create an object for standalone legend settings and then copy it onto a current
result. These capabilities allow you to reuse a set of legend settings in various places.
Method Description
MakeCopy() Returns a standalone LegendSettings object
that is a copy of the current result's legend.
CopyTo() Copies a standalone LegendSettings object
onto the current result's legend.
SetMinMax Gets or sets whether the minimum and maximum
values are shown.
Example 1
This code creates a standalone LegendSettings object using the current result's legend:
# Navigate to a Total deformation object
totalDeform = DataModel.GetObjectsByName("Total Deformation")[0]
# Make a copy of its legend settings
totDefLegend = Ansys.Mechanical.Graphics.Tools.CurrentLegendSettings().MakeCopy()
Example 2
This code copies a standalone LegendSettings object onto the current result’s legend:
# Create a standalone legend settings object
legendSetting = Ansys.Mechanical.Graphics.Tools.LegendSettings()
legendSetting.NumberOfBands = 3
legendSetting.SetBandColor(1, Ansys.Mechanical.DataModel.Constants.Colors.Red)
These copy operations can also be used for copying legends between different results.
Example 3
This code copies the legend from one result object onto another:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
156 of ANSYS, Inc. and its subsidiaries and affiliates.
Working with Legends
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 157
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
158 of ANSYS, Inc. and its subsidiaries and affiliates.
Other APIs
The following topics describe other Mechanical APIs of particular interest:
Mechanical Interface and Ribbon Tab Manipulation
Command Snippets
Object Tags
Solve Process Settings
Message Window
Ray Casting on Geometry
Interacting with Legacy JScript
Data Processing Framework
It allows you to control the ACT development, Button Editor, and ACT extension-defined ribbon tabs.
It cannot be used to control other toolbars or to create new buttons, ribbon tabs, or toolbars.
• Each object has fields such as Name, Caption, Visibility, and child to access entries.
• Each child has the following properties: Caption, Enabled, Entries, EntryType, Name,
and Visible.
The Boolean fields Visible and Enabled can be set to show or hide so that you can control the
availability of the buttons depending on the current context.
Command Snippets
CommandSnippet provides control of the Commands object. You use the method AddCommandSnip-
pet() to insert a new child command snippet in the project tree:
sol = Model.Analyses[0].Solution
cs = sol.AddCommandSnippet()
cs.Input = "/COM, New input"
cs.AppendText("\n/POST1")
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 159
Other APIs
You can also use ImportTextFile(string to import content from a text file or use ExportText-
File(string) to export a command snippet to a text file.
Object Tags
You can use APIs to access object tags and to add or remove them:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
160 of ANSYS, Inc. and its subsidiaries and affiliates.
Ray Casting on Geometry
This script accesses and changes some details from the second solve configuration:
config2 = ExtAPI.Application.SolveConfigurations["My Computer, Background"]
x = config2.Default
y = config2.Settings.License
z = config2.SolveProcessSettings.ManualSolverMemorySettings.Workspace
config2.SolveProcessSettings.ManualLinuxSettings.UserName = "jane.doe"
config2.SolveProcessSettings.MaxNumberOfCores = 12
This script accesses some details from the first RSM queue:
queue1 = ExtAPI.Application.RSMQueues[0]
x = queue1.Name
y = queue1.HPCConfiguration
Message Window
The Message window API uses a collection called Messages. You can use this API to access individual
messages and their data and operate on the collection to add and remove messages:
• Add a message:
msg = Ansys.Mechanical.Application.Message("Problem!", MessageSeverityType.Error)
ExtAPI.Application.Messages.Add(msg)
To perform ray casting in Mechanical, use the method CastRayOnGeometry(), calling it like this:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 161
Other APIs
Ansys.Mechanical.Selection.SelectionHelper.CastRayOnGeometry
GeometryRayCastSettings can be used to customize the behavior of the ray cast algorithm. It contains
the following properties:
Example 1
This code creates a bound vector from which the ray cast originates and then casts it into the geometry
as indicated earlier:
a_point = Point([2000,2000,2000], 'pm')
a_vector = Vector3D(-1,0,0)
a_bound_vector = Ansys.Mechanical.Math.BoundVector(a_point, a_vector)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
162 of ANSYS, Inc. and its subsidiaries and affiliates.
Ray Casting on Geometry
The result is used to create (or modify) a coordinate system by setting its PrimaryAxisDirection,
Origin, and OriginDefinedBy to the output BoundVector to create a coordinate system for
each geometry hit, visualizing the hit points and directions from the ray cast:
geom_hit = Ansys.Mechanical.Selection.SelectionHelper.CastRayOnGeometry(a_bound_vector)
for geom in geom_hit:
print("\nNew geometry collision - " + str(geom.Entity.Type))
print(geom.HitVector.Vector)
print(geom.HitVector.Origin)
cordS.PrimaryAxisDirection = geom.HitVector.Vector
cordS.Origin = geom.HitVector.Origin.Location
cordS.OriginDefineBy = CoordinateSystemAlignmentType.Fixe
Example 2
This code shows an example of changing ray cast settings, run with the same for loop in the second
block as in the previous example:
a_point = Point([2000,2000,2000], 'pm')
a_vector = Vector3D(-1,0,0)
a_bound_vector = Ansys.Mechanical.Math.BoundVector(a_point, a_vector)
cast_settings = Ansys.Mechanical.Selection.GeometryRayCastSettings()
cast_settings.HitBodies = True
cast_settings.HitFaces = False
geom_hit = Ansys.Mechanical.Selection.SelectionHelper.CastRayOnGeometry(a_bound_vector, cast_settings)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 163
Other APIs
In the following code example, nothing is returned because returnFromScript() is not used:
x = ExtAPI.Application.ScriptByName("jscript").ExecuteCommand("""var x=1""")
However, if you use the function returnFromScript(), you can return the value of x from the
JScript back to the Python code:
x = ExtAPI.Application.ScriptByName("jscript").ExecuteCommand("""var x=1
returnFromScript(x)""")
In this case, x now holds the value 1 because this value was passed into the Python code from the
returnFromScript() function.
• Int
• Double
• Boolean
• String
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
164 of ANSYS, Inc. and its subsidiaries and affiliates.
Interacting with Legacy JScript
Known Limitations
The following limitations exist:
Example
The JScript that follows includes many functions for returning different types of variables:
script = """
function returnInt(){
return 10;
}
Function returnDouble(){
return 3.14;
}
function returnString(){
return "Testing J Script";
}
function returnBool(){
return true;
}
var innerDict = new ActiveXObject("Scripting.Dictionary");
function returnList(){
var x = 10;
var y = 20;
var str = "thirty"
var nullVal = null;
var boolVal = true;
var innerList1 = [1 ,2, 3, "str", [1, "str", 2]];
var innerList2 = [[1], [1,2,3,[1,5,6]]];
innerDict.Add("Testing", 1);
function returnLongList(){
var longList = [];
for(var i= 0; i<65535; i++){
longList[i] = i;
}
return longList;
}
function returnDict(){
var dict = new ActiveXObject("Scripting.Dictionary");
var listTry = [1,2,3]
dict.Add("string", "strTest");
dict.Add("int", 1);
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 165
Other APIs
dict.Add("bool", true);
dict.Add("null", null);
dict.Add("list", [1,2,3])
dict.Add(1, "int");
dict.Add(true, "bool");
dict.Add([1,2,3], "list");
innerDict.Add("Testing", 1);
dict.Add("dict", innerDict);
return dict;
}
var retVal = returnInt();
returnFromScript(retVal );
""")
As demonstrated, you can set the variable retVal to whatever is returned from some function. You
can then pass the variable retVal into returnFromScript() to return it to the Python code.
Return a list
The function returnList() can be used as a reference when returning lists from the JScript code.
Return a dictionary
The function returnDict() can be used as a reference when returning dictionaries from the
JScript code.
To pass in a value to the JScript code from Python code, you embed string values of Python code
in the script.
The goal of this first example is to pass an integer value (5) to the JScript code from the Python
code and then increment it by 1 in the JScript code and return the new value (6) to the Python
code.
x = 5
script = """
var x = """ + str(x) + """;
x++;
returnFromScript(x);
"""
x = ExtAPI.Application.ScriptByName("jscript").ExecuteCommand(script)
The goal of this second example is to pass a list (1, 2, 3, 5) to the JScript code from the Python code
and then update the fourth element and return the updated list (1, 2, 3, 10) to the Python code.
x = [1, 2, 3, 5]
script = """
var x = """ + str(x) + """;
x[3] = 10;
returnFromScript(x);
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
166 of ANSYS, Inc. and its subsidiaries and affiliates.
Data Processing Framework
"""
x = ExtAPI.Application.ScriptByName("jscript").ExecuteCommand(script)
Note:
To pass in a Boolean value from Python to JScript, you must first convert it to a string
and then make the string all lowercase because Booleans in Python start with an upper-
case character where in JScript they start with a lowercase character.
Introduction
The Data Processing Framework (DPF) is a tool that enables you to access and transform simulation
data using customizable workflows. In the ACT console, with the IPython API of DPF, you can load results
from Mechanical systems, apply post processing, and access data. DPF concepts:
• The data is contained in an entity called a Field. Fields can be grouped into a Fields Container
to describe an analysis, such as "time steps for transient" or "harmonic analysis."
• The data is transformed by Operators that can be combined to define Workflows. Each Operator
applies an elementary operation on the data.
DPF documentation is available in the ACT console. Available Operators with their descriptions and the
required inputs/outputs are listed in this documentation. See the Available Operators menu. The docu-
mentation describes the entities used to contain the data (see Main data types) and the APIs available
to explore the data with examples (see APIs).
Generate Documentation
Use the following function to generate DPF’s html documentation. This documentation contains examples
and the library of Operators.
mech_dpf.help()
This function returns the path of the generated documentation. Copy and paste the path into a browser
to view the documentation.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 167
Other APIs
mech_dpf.setExtAPI(ExtAPI)
Access Results
Select a geometric entity in the Geometry and run the following to display the node and/or element
IDs for the selected geometry:
my_nodes_scoping = mech_dpf.GetNodesScoping()
my_elements_scoping = mech_dpf.GetElementScoping()
Examples
This example shows how to read a displacement field on a selected geometry at a given time step and
computes its normal.
import mech_dpf
import Ans.DataProcessing as dpf
mech_dpf.help()
mech_dpf.setExtAPI(ExtAPI)
my_data_sources = mech_dpf.GetDataSources()
read_disp_op = dpf.operators.result.displacement()
read_disp_op.inputs.data_sources.Connect(my_data_sources)
read_disp_op.inputs.time_scoping.Connect(my_time_scoping)
read_disp_op.inputs.mesh_scoping.Connect(my_nodes_scoping)
norm_op = dpf.operators.math.norm_fc()
norm_op.inputs.fields_container.Connect(read_disp_op.outputs.fields_container)
my_u_norm_fc = norm_op.outputs.fields_container.GetData()
u_norm_1 = my_u_norm_fc.GetFieldByTimeId(1)
This example shows how to read a stress field on a selected geometry, average the elemental nodal
stress on the nodes and compute its Von Mises equivalent.
import mech_dpf
import Ans.DataProcessing as dpf
mech_dpf.help()
mech_dpf.setExtAPI(ExtAPI)
my_data_sources = mech_dpf.GetDataSources()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
168 of ANSYS, Inc. and its subsidiaries and affiliates.
Data Processing Framework
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 169
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
170 of ANSYS, Inc. and its subsidiaries and affiliates.
Scripting Examples
This section provides many examples of scripts that you can use to easily complete both common and
novel tasks in Mechanical. Scripts are organized by three main categories, though some scripts overlap
categories.
When logged into your Ansys customer account, you can search solutions for additional script examples
using the following filter selections:
To further limit the solutions shown, you can use the search box at the top of the page.
Script Examples for Selection
Script Examples for Interacting with Tree Objects
Script Examples for Interacting with the Mechanical Session
Script Examples for Interacting with Results
Examples Using the Python Code Object
End-to-End Analysis Examples
Script Examples for Selection
The following scripts are for making selections in Mechanical:
Select Geometry or Mesh in the Graphics Window
Get Tree Object of a Body Corresponding to a Selected Body
Get GeoData Body Corresponding to a Tree Object of a Body
Query Mesh Information for Active Selection
Use an Existing Graphics Selection on a Result Object
Calculate Sum of Volume, Area, and Length of Scoped Entities
Create a Named Selection from the Scoping of a Group of Objects
Create a Named Selection that Selects All Faces at a Specified Location
Rescope a Solved Result Based on the Active Node or Element Selection
Scope a Boundary Condition to a Named Selection
Add a Joint Based on Proximity of Two Named Selections
Print Selected Element Faces
Get Normal of a Face
Create a Selection Based on the Location of Nodes in Y
Create Aligned Coordinate Systems in a Motor
You might need to be in the wireframe mode to see the selected nodes.
# Clear the current selection and select some mesh nodes
ExtAPI.SelectionManager.ClearSelection()
mySel = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.MeshNodes)
mySel.Ids = [1,2,3,4] # These are the IDs of any node entities
ExtAPI.SelectionManager.NewSelection(mySel)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 173
Script Examples for Selection
Code:
myIds = ExtAPI.SelectionManager.CurrentSelection.Ids
geoBody = DataModel.GeoData.GeoEntityById(myIds[0])
treeBody = Model.Geometry.GetBody(geoBody)
Code:
treeBody = Model.Geometry.Children[0].Children[0]
geoBody = treeBody.GetGeoBody()
Code:
# Macro to demonstrate how to query mesh information for the active selection
meshData = DataModel.MeshDataByName("Global")
sel=ExtAPI.SelectionManager.CurrentSelection
refIds = sel.Ids
This example works best when selecting nodes and elements while already viewing a result.
Code:
mysel = ExtAPI.SelectionManager.CurrentSelection
myres = Tree.FirstActiveObject
myres.ClearGeneratedData()
myres.Location = mysel
myres.EvaluateAllResults()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
174 of ANSYS, Inc. and its subsidiaries and affiliates.
Create a Named Selection that Selects All Faces at a Specified Location
Code:
sum = 0
Code:
selmgr=ExtAPI.SelectionManager
selmgr.ClearSelection()
contacts = DataModel.GetObjectsByType(DataModelObjectCategory.ContactRegion)
for contact in contacts:
selmgr.AddSelection(contact.SourceLocation)
selmgr.AddSelection(contact.TargetLocation)
total=selmgr.CurrentSelection.Ids.Count
Model.AddNamedSelection()
Code:
NS1 = DataModel.Project.Model.AddNamedSelection()
NS1.ScopingMethod = GeometryDefineByType.Worksheet
GenerationCriteria = NS1.GenerationCriteria
Criterion1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
Criterion1.Action = SelectionActionType.Add
Criterion1.EntityType = SelectionType.GeoFace
Criterion1.Criterion = SelectionCriterionType.LocationY
Criterion1.Operator = SelectionOperatorType.Equal
Criterion1.Value = Quantity("0 [m]")
GenerationCriteria.Add(Criterion1)
Criterion2 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 175
Script Examples for Selection
Criterion2.Action = SelectionActionType.Add
Criterion2.EntityType = SelectionType.GeoFace
Criterion2.Criterion = SelectionCriterionType.LocationZ
Criterion2.Operator = SelectionOperatorType.Equal
Criterion2.Value = Quantity("0 [m]")
GenerationCriteria.Add(Criterion2)
NS1.Generate()
Code:
selmgr = ExtAPI.SelectionManager
loc = selmgr.CurrentSelection
res = Tree.FirstActiveObject
if (isRegularResult or isCustomResult):
newRes = res.Duplicate()
newRes.ClearGeneratedData()
newRes.Location=loc
newRes.EvaluateAllResults()
else:
print "Selected Object is not a Result!"
Code:
# Macro to demonstrate the ability to create a fixed support and then scope it to a Named Selection
#
ns = DataModel.GetObjectsByName("myFaces")
# make sure only 1 named selection was found
if (ns.Count != 1):
print("A single Named Selection was not Found!")
else:
if (analysis.PhysicsType != PhysicsType.Mechanical):
print("The first analysis isn't structural")
else:
# Finally create a fixed support and scope it to the Named Selection
mySupport = analysis.AddFixedSupport()
mySupport.Location=ns[0]
print("Done creating a Fixed Support and Scoping to a Named Selection")
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
176 of ANSYS, Inc. and its subsidiaries and affiliates.
Add a Joint Based on Proximity of Two Named Selections
Code:
import math
jh1 = DataModel.GetObjectsByName("jh1")[0] #named selection object of faces to become the single joint refer
jh2 = DataModel.GetObjectsByName("jh2")[0] #named selection object of faces from which the two closest will
group = DataModel.GetObjectsByName("Connection Group")[0] #connection group to hold all of the joints that a
geo = DataModel.GeoData
face_ids1 = jh1.Location.Ids #face ids in jh1
face_ids2 = jh2.Location.Ids #face ids in jh2
def get_min_indeces(face_centroid1):
#array to hold the index and distance to face1_center for two closest faces in face_centroids2
min_indeces = [None, None]
#replace that item with the current face if the distance is smaller
if distance < min_indeces[larger_dist_index][1]:
min_indeces[larger_dist_index] = (index, distance)
return min_indeces
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 177
Script Examples for Selection
joint = group.AddJoint()
reference_selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
reference_selection.Ids = [face_id1]
mobile_selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
mobile_selection.Ids = face_ids
joint.ReferenceLocation = reference_selection
joint.MobileLocation = mobile_selection
Code:
# Purpose of the script: prints selected element faces area
g_elementTypeToElemFaceNodeIndices = {
ElementTypeEnum.kTri3 : [ [ 0, 1, 2 ] ],
ElementTypeEnum.kTri6 : [ [ 0, 1, 2, 4, 5, 6 ] ],
ElementTypeEnum.kQuad4 : [ [ 0, 1, 2, 4 ] ],
ElementTypeEnum.kQuad8 : [ [ 0, 1, 2, 4, 5, 6, 7, 8 ] ],
ElementTypeEnum.kTet4 : [ [ 0, 1, 3 ], [ 1, 2, 3 ], [ 2, 0, 3 ], [ 0, 2, 1 ] ],
ElementTypeEnum.kTet10 : [ [ 0, 1, 3, 4, 8, 7 ], [ 1, 2, 3, 5, 9, 8 ], [ 2, 0, 3, 6, 7, 9 ], [ 0, 2, 1, 6, 5,
ElementTypeEnum.kPyramid5 : [ [ 0, 3, 2, 1 ], [ 0, 1, 4 ], [ 1, 2, 4 ], [ 3, 4, 2 ], [ 0, 4, 3 ] ],
ElementTypeEnum.kPyramid13 : [ [ 0, 3, 2, 1, 8, 7, 6, 5 ], [ 0, 1, 4, 5, 10, 9 ], [ 1, 2, 4, 6, 11, 10 ], [ 3,
ElementTypeEnum.kWedge6 : [ [ 0, 2, 1 ], [ 3, 4, 5 ], [ 0, 1, 4, 3 ], [ 1, 2, 5, 4 ], [ 0, 3, 5, 2 ] ],
ElementTypeEnum.kWedge15 : [ [ 0, 2, 1, 8, 7, 6 ], [ 3, 4, 5, 9, 10, 11 ], [ 0, 1, 4, 3, 6, 13, 9, 12 ], [ 1,
ElementTypeEnum.kHex8 : [ [ 0, 1, 5, 4 ], [ 1, 2, 6, 5 ], [ 2, 3, 7, 6 ], [ 3, 0, 4, 7 ], [ 0, 3, 2, 1 ], [ 4,
ElementTypeEnum.kHex20 : [ [ 0, 1, 5, 4, 8, 17, 12, 16 ], [ 1, 2, 6, 5, 9, 18, 13, 17 ], [ 2, 3, 7, 6, 10, 19,
}
def Norm(vec):
return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2])
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
178 of ANSYS, Inc. and its subsidiaries and affiliates.
Create a Selection Based on the Location of Nodes in Y
def GetCurrentSelectedElementFaces():
current_selection = ExtAPI.SelectionManager.CurrentSelection
if current_selection.SelectionType == SelectionTypeEnum.MeshElementFaces:
element_ids = current_selection.Ids
element_face_indices = current_selection.ElementFaceIndices
return (element_ids, element_face_indices)
elif current_selection.SelectionType == SelectionTypeEnum.MeshElements:
element_ids = current_selection.Ids
element_face_indices = [0 for i in element_ids]
return (element_ids, element_face_indices)
else:
return ([], [])
def PrintCurrentSelectedElementFacesElementFacesArea():
(element_ids, element_face_indices) = GetCurrentSelectedElementFaces()
if len(element_ids) < 1:
print('No element faces selected')
return
text = ''
for i in range(len(element_ids)):
area = GetElementFaceArea(element_ids[i], element_face_indices[i])
text += 'element id={0}, faceIndex={1}, area={2}\n'.format(element_ids[i], element_face_indices[i], area)
print(text)
PrintCurrentSelectedElementFacesElementFacesArea()
Code:
face_id = 20 #Current selection in ExtAPI.SelectionManager.CurrentSelection
point = (.01,.015,0.) #point in xyz space in the CAD unit system
#get the projected point on the geometry (a curvilinar abscissa for an edge, (u,v) for a face)
u,v = face.ParamAtPoint(point)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 179
Script Examples for Selection
Code:
# Get access to mesh
mesh = DataModel.MeshDataByName(ExtAPI.DataModel.MeshDataNames[0])
selected_node_ids = set() # Empty set
for node in mesh.Nodes:
tolerance = 0.0001 # 0.1 mm
y_location = 0.0130
if (node.Y >= y_location - tolerance) and (node.Y <= y_location + tolerance):
selected_node_ids.add(node.Id)
# Create selection
selection_info = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.MeshNodes)
for selected_node_id in selected_node_ids:
selection_info.Ids.Add(selected_node_id)
ExtAPI.SelectionManager.NewSelection(selection_info)
Note:
The following script example is model-specific. Click to download the archived Ansys
projecthere.
Code:
# Get all faces and vertices of named selections
face_named_selection = Model.NamedSelections.Children[0] # First named selection, of faces
face_ids = face_named_selection.Ids
start_vertex_named_selection = Model.NamedSelections.Children[1] # Second named selection, of vertices
start_vertex_ids = start_vertex_named_selection.Ids
end_vertex_named_selection = Model.NamedSelections.Children[2] # Third named selection, of vertices
end_vertex_ids = end_vertex_named_selection.Ids
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
180 of ANSYS, Inc. and its subsidiaries and affiliates.
Create Aligned Coordinate Systems in a Motor
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 181
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
182 of ANSYS, Inc. and its subsidiaries and affiliates.
Script Examples for Interacting with Tree Objects
The following scripts are for interacting with tree objects in Mechanical:
Delete an Object
Refresh the Tree
Clear the Mesh
Get All Visible Properties for a Tree Object
Parametrize a Property for a Tree Object
Create Construction Lines from Cylindrical Faces
Update Geometries for all Construction Lines
Create Material Assignment from Body Materials
Count the Number of Contacts
Suppress Duplicate Contacts
Verify Contact Size
Set Pinball to 5mm for all Frictionless Contacts
Use a Named Selection as Scoping of a Load or Support
Suppress Bodies Contained in a Given Named Selection
Rename a Named Selection Based on Scoping
Modify the Scoping on a Group of Objects
Change Tabular Data Values of a Standard Load or Support
Duplicate an Harmonic Result Object
Retrieve Object Details Using SolverData APIs
Evaluate Spring Reaction Forces
Export a Result Object to an STL File
Export Result Images to Files
Tag and Group Result Objects Based on Scoping and Load Steps
Work with Solution Combinations
Create a Pressure Load
Create a Convection Load
Create Node Merge Object at a Symmetry Plane
Access Contour Results for an Evaluated Result
Write Contour Results to a Text File
Access Contour Results at Individual Nodes/Elements
Set Arbitrary Coordinate System Properties
Transform Coordinate Systems (with Math)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 183
Script Examples for Interacting with Tree Objects
Delete an Object
Goal: Delete a selected object from the tree.
Code:
ObjToDelete.Delete()
Code:
Tree.Refresh()
The following one-line script enables you to clear your generated mesh.
Code
# Clears generated mesh
Model.Mesh.ClearGeneratedData()
Code:
force = Model.Analyses[0].AddForce()
for forceProperty in force.VisibleProperties:
print(forceProperty.Caption + " | " + forceProperty.StringValue)
Code:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
184 of ANSYS, Inc. and its subsidiaries and affiliates.
Update Geometries for all Construction Lines
hydrostaticPressure = Model.Analyses[0].AddHydrostaticPressure()
fluidDensity = hydrostaticPressure.CreateParameter("FluidDensity")
fluidDensity.ID
The following script example enables you to create a Construction Line using cylindrical faces
and the axis to rotation (parallel to global Y) about those faces. This is essentially an abstraction
of a bolt.
Code
# From a selection of cylindrical faces, create construction line on the cylinder's axis
curSel=ExtAPI.SelectionManager.CurrentSelection
construction_geometry = Model.ConstructionGeometry
if construction_geometry == None:
construction_geometry = Model.AddConstructionGeometry()
if face.SurfaceType != GeoSurfaceTypeEnum.GeoSurfaceCylinder:
continue;
mid1=face.Edges[0].Centroid
mid2=face.Edges[1].Centroid
construction_line = construction_geometry.AddConstructionLine()
[global_points_1] = construction_line.CreatePoints([mid1])
[global_points_2] = construction_line.CreatePoints([mid2])
edge_collection = construction_line.CreateStraightLines([global_points_1, global_points_2], [(0, 1)])
with Transaction():
construction_line.AddToGeometry()
The following script example enables you to update Construction Line geometries.
Code
# Automatically update all geometries of all construction lines
constructionLines=ExtAPI.DataModel.GetObjectsByType(Ansys.ACT.Automation.Mechanical.ConstructionLines.Construct
with Transaction():
for constLine in constructionLines:
constLine.UpdateGeometry()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 185
Script Examples for Interacting with Tree Objects
The following script example creates a Material Assignment object, specifies object properties,
and assigns a material to all bodies of your model.
Code
# Clears generated mesh
# Single line script to be used to create a user button and possibly a keyboard shortcut
Code:
contacts = DataModel.GetObjectsByType(DataModelObjectCategory.ContactRegion)
numContacts = contacts.Count
print("There are %s contact regions" % (numContacts) )
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
186 of ANSYS, Inc. and its subsidiaries and affiliates.
Suppress Duplicate Contacts
The following script example examines your model to determine if duplicate contact pairs exist
and if so, automatically suppresses the duplicate pair. A duplicate pair is a contact pair where
the Source and Target scoping are interchangeable, that is, the same.
Code
# Scan contacts to find duplicate pairs.
contLocation={}
duplicateCont={}
# create dictionary will all sources and locations from all contacts
for cont in contacts:
l1=[]
l2=[]
for id in cont.SourceLocation.Ids:
l1.append(id)
for id in cont.TargetLocation.Ids:
l2.append(id)
contLocation[cont.ObjectId]=[l1,l2]
dupList=[]
# Now check for duplicates
for cont in sorted(contLocation.keys()):
# Retrieve source and location
source1=contLocation[cont][0]
target1=contLocation[cont][1]
for contTest in sorted(contLocation.keys()):
if contTest != cont and contTest not in dupList: # Don't check contact with itself, don't check if alre
# Retrieve source and location for test contacts
source2=contLocation[contTest][0]
target2=contLocation[contTest][1]
if (source1==source2 and target1==target2) or (source2==target1 and source1==target2):
# Contacts are duplicate of each other, add to duplicateCont dictionary if not already identified
if cont in duplicateCont.keys():
curList=duplicateCont[cont]
curList.append(contTest)
d1={cont: curList}
duplicateCont.update(d1)
else:
duplicateCont[cont]=[contTest]
# This list contains all contacts already identified as duplicate to avoid double detection
dupList.append(contTest)
dupList.append(cont)
msgCont=''
# Prepare message with list of duplicate contacts and suppress duplicated ones
for cont in duplicateCont.keys():
cont1=ExtAPI.DataModel.GetObjectById(cont)
# create list with all IDs to check if there are duplicates with a different order
for dup in duplicateCont[cont]:
cont2=ExtAPI.DataModel.GetObjectById(dup)
msgCont+=cont2.Name + ' is a duplicate of ' + cont1.Name + '\n'
cont2.Suppressed=True
if msgCont=='':
# If message is empty, no duplicates have been found
msg = Ansys.Mechanical.Application.Message('No duplicate contacts found', MessageSeverityType.Warning)
ExtAPI.Application.Messages.Add(msg)
else:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 187
Script Examples for Interacting with Tree Objects
Code:
geom=DataModel.GeoData
contacts = DataModel.GetObjectsByType(DataModelObjectCategory.ContactRegion)
with Transaction():
for cont in contacts:
source_area = 0
sourcenum = cont.SourceLocation.Ids.Count
for x in range(0,sourcenum):
myface = geom.GeoEntityById(cont.SourceLocation.Ids[x])
source_area = source_area + myface.Area
target_area = 0
targetnum = cont.TargetLocation.Ids.Count
for x in range(0,targetnum):
myface = geom.GeoEntityById(cont.TargetLocation.Ids[x])
target_area = target_area + myface.Area
Code:
with Transaction():
contacts = DataModel.GetObjectsByType(DataModelObjectCategory.ContactRegion)
changeCount = 0
for cont in contacts:
if (cont.ContactType == ContactType.Frictionless) :
cont.PinballRegion = ContactPinballType.Radius
cont.PinballRadius = Quantity("5[mm]")
changeCount = changeCount + 1
print "Done with macro, changed %s contact regions" % (changeCount)
Code:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
188 of ANSYS, Inc. and its subsidiaries and affiliates.
Rename a Named Selection Based on Scoping
load = Model.Analyses[0].AddPressure
ns = Model.NamedSelections.Children[0]
load.Location = ns
Code:
ns = Model.NamedSelections.Children[0] # selected a named selection containing bodies
bodyIds = ns.Location.Ids
with Transaction():
for bodyId in bodyIds:
geoBody = DataModel.GeoData.GeoEntityById(bodyId)
body = Model.Geometry.GetBody(geoBody)
body.Suppressed = True
print "Done with Macro"
When executed, the example code shown below automatically identifies the Named Selections objects
in the Outline and renames them based on the scoping specified in the Geometry Selection property.
This code renames the existing Named Selections using the number of geometric entities or mesh en-
tities included in the scoping as well as the entity type. For example: 5 Bodies, 1 Face, 75 Elements.
Example Code:
named_selections = DataModel.GetObjectsByType(DataModelObjectCategory.NamedSelection)
print named_selections.Count
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 189
Script Examples for Interacting with Tree Objects
Illustrated Example
Before Script After Script
Code:
with Transaction():
for obj in Tree.ActiveObjects:
loc = obj.Location
loc.Ids.RemoveAt(1)
obj.Location = loc
Code:
pressureLoad = Model.Analyses[0].AddPressure()
pressureLoad.Magnitude.Output.DiscreteValues = [Quantity('0 [MPa]'),Quantity('10 [MPa]')]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
190 of ANSYS, Inc. and its subsidiaries and affiliates.
Evaluate Spring Reaction Forces
Code:
# nDiv is the number of results you want to create on a 360 basis,
# so setting to 30 will create a result every 12 degrees(360/30)
nDiv = 30
angleInc = 360/nDiv
BaseResult = Tree.FirstActiveObject
for n in range(0,nDiv+1):
angle = Quantity(str(n*angleInc) + ' [degree]')
newResult = BaseResult.Duplicate()
newResult.SweepingPhase = angle
newResult.Name = 'Sweep At ' + str(n*angleInc)
Code:
#Solver data in a solved analysis
solution = Model.Analyses[0].Solution
solver_data = solution.SolverData
solver_data.MaxElementId
solver_data.MaxNodeId
solver_data.MaxElementType
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 191
Script Examples for Interacting with Tree Objects
Code:
# Get access to solver data
analysis = Model.Analyses[0]
solver_data = analysis.Solution.SolverData
spring_data = solver_data.GetObjectData(spring)
element_id = spring_data.ElementId
fForce = spring_results.GetElementValues(element_id)
print(fForce[0])
Code:
result = Model.Analyses[0].Solution.Children[1]
result.ExportToSTLFile("E:\\test.stl")
Code:
# get a list of all the results in the project
results = DataModel.GetObjectsByType(DataModelObjectCategory.Result)
# export the result to avz file using the result name for the filename
avzFilename = "D:\\Images\\" + result.Name + ".avz"
Graphics.Export3D(avzFileName)
Tag and Group Result Objects Based on Scoping and Load Steps
Goal:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
192 of ANSYS, Inc. and its subsidiaries and affiliates.
Tag and Group Result Objects Based on Scoping and Load Steps
Code:
# Get the number of steps for the analysis
analysis_settings = Model.Analyses[0].AnalysisSettings
number_of_steps = analysis_settings.NumberOfSteps
with Transaction():
# Create tags that will be used later for finding objects
tag2 = Ansys.Mechanical.Application.ObjectTag("Bolt")
tag3 = Ansys.Mechanical.Application.ObjectTag("U Sum")
tag4 = Ansys.Mechanical.Application.ObjectTag("EQV")
DataModel.ObjectTags.Add(tag2)
DataModel.ObjectTags.Add(tag3)
DataModel.ObjectTags.Add(tag4)
# For each step add the desired result objects with appropriate settings
for step in range(1, number_of_steps):
u_result = solution.AddTotalDeformation()
u_result.Name = "Total Deformation @ " + str(step) + " sec"
u_result.DisplayTime = analysis_settings.GetStepEndTime(step)
# Apply tags
tag3.AddObject(u_result)
s_result = solution.AddEquivalentStress()
s_result.Name = "Eqv Stress @ " + str(step) + " sec"
tag4.AddObject(s_result)
s_result = solution.AddEquivalentStress()
s_result.Name = "Bolt Stress @ " + str(step) + " sec"
s_result.Location = bolt
tag2.AddObject(s_result)
tag4.AddObject(s_result)
tag2_list = tag2.Objects
tag3_list = tag3.Objects
tag4_list = tag4.Objects
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 193
Script Examples for Interacting with Tree Objects
group = Tree.Group(s_Bolt)
group.Name = "Stress (Bolt)"
Tree.Activate([solution])
Code:
# get the environments, an alternative would be via Model.Analyses
envs = DataModel.GetObjectsByType(DataModelObjectCategory.Analysis)
# create a solution combination object; By default it will come with 1 base case and 1 combination
sc = Model.AddSolutionCombination()
# Any property on a base case can be set using an index and value
scdef.SetBaseCaseAnalysis(0, envs[0])
scdef.SetBaseCaseTime(0,1)
# You can even pass in the Base Case settings to the constructor (Arguments are name, analysis, time)
scdef.AddBaseCase("BC 3", envs[1], 2)
# Any property on a load combination can be set using an index and value
scdef.SetLoadCombinationType(0,1)
# You can even pass in the Load Combination settings to the constructor (Arguments are name, type)
scdef.AddLoadCombination("LC3", 1)
Code:
#The following example creates a pressure on the first face of the first body for the first part.
pressure = Model.Analyses[0].AddPressure()
part = Model.Geometry.Children
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
194 of ANSYS, Inc. and its subsidiaries and affiliates.
Create Node Merge Object at a Symmetry Plane
body1 = part1.Children[0]
face1 = body1.GetGeoBody().Faces[0] # Get the first face of the body.
selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
selection.Entities = [face1]
pressure.Location = selection
pressure.Magnitude.Inputs[0].DiscreteValues = [Quantity("0 [s]"), Quantity("1 [s]")]
pressure.Magnitude.Output.DiscreteValues = [Quantity("10 [Pa]"), Quantity("20 [Pa]")]
The following script creates a convection load on the first Named Selection listed in the Named
Selections folder in the Outline using example values and Units.
Code
try:
named_sel = Model.NamedSelections.Children[0]
except:
ExtAPI.Log.WriteWarning("Named Selection not found")
convection = Model.Analyses[0].AddConvection()
if named_sel != None:
convection.Location = named_sel
Code:
# Purpose of the script: create a node merge object on models with a (plane) symmetry
# How to use: select a coordinate that defines a symmetry plane (origin axisX, axisY)
# then the script will create a node merge object with faces automatically selected
def GetSelectedCoordinateSystem():
if Tree.ActiveObjects.Count != 1
return None
obj = Tree.FirstActiveObject
if not obj.Path.StartsWith('/Project/Model/Coordinate Systems'):
return None
return obj
facesPlus = []
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 195
Script Examples for Interacting with Tree Objects
facesMinus = []
for part in parts:
for body in part.Bodies:
distBody = GetSignedDistanceFromPointToPlane(body.Centroid, planeOrigin, planeNormal)
for face in body.Faces:
distFace = GetSignedDistanceFromPointToPlane(face.Centroid, planeOrigin, planeNormal)
if abs(distFace) <= maximumDistanceToPlane:
if distBody >= 0:
facesPlus.append(face)
else:
facesMinus.append(face)
return (facesPlus, facesMinus)
def AddNodeMergeObject():
meshEdits = DataModel.GetObjectsByType(DataModelObjectCategory.MeshEdit)
if meshEdits.Count > 0:
meshEdit = meshEdits[0]
else:
meshEdit = Model.AddMeshEdit()
meshEdit.AddNodeMerge()
nodeMergeObj = DataModel.GetObjectsByType(DataModelObjectCategory.NodeMerge)[0]
return nodeMergeObj
def GetGeometryBoundingBoxLength():
geom = Model.Geometry
lengthQuantity = geom.LengthX*geom.LengthX + geom.LengthY*geom.LengthY + geom.LengthZ*geom.LengthZ
return lengthQuantity.Value
def ShowError(errString):
ExtAPI.Application.ScriptByName("jscript").ExecuteCommand("WBScript.Out('" + errString + "', 1)")
def CreateNodeMergeAtPlane():
try:
csObj = GetSelectedCoordinateSystem()
if csObj is None:
raise Exception("Select a coordinate system that defines the symmetry plane as (origin, AxiX, AxisY)")
planeOrigin = csObj.Origin
planeNormal = csObj.ZAxis
maximumDistanceToPlane = GetGeometryBoundingBoxLength() * 1e-5
facesColls = FindFacesClosestToPlane(planeOrigin, planeNormal, maximumDistanceToPlane)
nodeMergeObj = AddNodeMergeObject()
primarySel = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
primarySel.Entities = facesColls[0]
secondarySel = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
secondarySel.Entities = facesColls[1]
nodeMergeObj.MasterLocation = primarySel
nodeMergeObj.SlaveLocation = secondarySel
except Exception as ex:
ShowError("Error: {0}".format(ex))
Code:
Model=ExtAPI.DataModel.Project.Model
#select the result object on the tree
result=Tree.FirstActiveObject
#First result item can also be accessed with
result=Model.Analyses[0].Solution.Children[1]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
196 of ANSYS, Inc. and its subsidiaries and affiliates.
Access Contour Results at Individual Nodes/Elements
Code:
Model=ExtAPI.DataModel.Project.Model
#select the result object on the tree
result=Tree.FirstActiveObject
resultValues= result.PlotData["Values"]
nodeList=result.PlotData["Node"]
with open('C:\Users\Admin\Desktop\Testfile.txt','w') as testfile:
for ii in range(len(nodeList)):
a=nodeList[ii]
b=resultValues[ii]
wrt=str(ii)+'\t'+str(a)+"\t"+str(b)+"\n"
testfile.write(wrt)
Code:
Model=ExtAPI.DataModel.Project.Model
if nodes[index]==nodeID:
return resultValue[index]
else:
print("Given NodeID doesn't exist in result set")
findNodeResult(3,plotDataResult)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 197
Script Examples for Interacting with Tree Objects
2. Specify values for an arbitrary origin. This specifies the Details properties Origin X, Origin Y,
and Origin Z.
3. Set an arbitrary direction vector. This specifies the Details properties X Axis Data, Y Axis Data,
and Z Axis Data.
Important:
The ability to set arbitrary direction vectors is only available through scripting.
Example Code
# Create a new coordinate system
csys = Model.CoordinateSystems.AddCoordinateSystem()
Code:
import units
import math
origin = destination_coordinate_system.Origin
x_axis = destination_coordinate_system.XAxis
y_axis = destination_coordinate_system.YAxis
z_axis = destination_coordinate_system.ZAxis
user_coordinates = []
user_coordinates.append(x_axis[0]*(global_coordinates[0] - factor*origin[0]) +
x_axis[1]*(global_coordinates[1] - factor*origin[1]) +
x_axis[2]*(global_coordinates[2] - factor*origin[2]))
user_coordinates.append(y_axis[0]*(global_coordinates[0] - factor*origin[0]) +
y_axis[1]*(global_coordinates[1] - factor*origin[1]) +
y_axis[2]*(global_coordinates[2] - factor*origin[2]))
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
198 of ANSYS, Inc. and its subsidiaries and affiliates.
Select Objects By Name
user_coordinates.append(z_axis[0]*(global_coordinates[0] - factor*origin[0]) +
z_axis[1]*(global_coordinates[1] - factor*origin[1]) +
z_axis[2]*(global_coordinates[2] - factor*origin[2]))
if destination_coordinate_system.CoordinateSystemType == CoordinateSystemTypeEnum.Cartesian:
return user_coordinates
elif destination_coordinate_system.CoordinateSystemType == CoordinateSystemTypeEnum.Cylindrical:
r = sqrt(user_coordinates[0] * user_coordinates[0] + user_coordinates[1] * user_coordinates[1])
theta = math.degrees(math.atan(user_coordinates[1] / user_coordinates[0]))
z = user_coordinates[2]
return [r, theta, z]
origin = destination_coordinate_system.Origin
x_axis = destination_coordinate_system.XAxis
y_axis = destination_coordinate_system.YAxis
z_axis = destination_coordinate_system.ZAxis
identity = Matrix4D()
transformation = identity.CreateSystem(x_axis_vector,y_axis_vector,z_axis_vector)
global_coordinates = [20,40,60]
localCS = Model.CoordinateSystems.Children[1]
print(localCoordinates1)
print(localCoordinates2)
The following script examples enable you to select an object based on its name.
Code
# Goal: Get the first body whose name contains the specified number
def GetBodyByPartNumber(number):
bodies = DataModel.Project.Model.Geometry.GetChildren(DataModelObjectCategory.Body, True)
for body in bodies:
if str(number) in body.Name:
return body
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 199
Script Examples for Interacting with Tree Objects
return object_list
# Goal: Get the first Named Selection whose name contains the specified string
def GetNamedSelectionByName(name,AcceptPartial = False):
try:
NSs = ExtAPI.DataModel.Project.Model.NamedSelections.Children
except:
return None
for ns in NSs:
if ns.Name.ToLower() == name.ToLower():
return ns
if AcceptPartial and (name.ToLower() in ns.Name.ToLower()):
return ns
ExtAPI.Log.WriteWarning("Named Selection not found: "+str(name))
return None
# Goal: Get Named Selections whose name contains the specified string
def GetNamedSelectionsByName(name,AcceptPartial = False):
try:
NSs = ExtAPI.DataModel.Project.Model.NamedSelections.Children
except:
return []
if AcceptPartial:
return [ns for ns in NSs if name.ToLower() in ns.Name.ToLower()]
else:
return [ns for ns in NSs if ns.Name.ToLower() == name.ToLower()]
Export Figures
Goal
The following script enables you to automatically export any Figures included in your analysis
to a specified folder. Figures are often useful for examining results.
Code
# Export to jpeg files a selection of figures from the tree
# Pictures are stored in the corresponding analysis folder
# Created by P. Thieffry
# Last update: 2021/04/14
clr.AddReference("Ans.UI.Toolkit.Base")
clr.AddReference("Ans.UI.Toolkit")
from Ansys.UI.Toolkit import *
figures=ExtAPI.DataModel.Tree.ActiveObjects
if (figures.Count == 0):
mess_line1 = 'Please select at least one figure'
MessageBox.Show(mess_line1)
pass
if (figures[0].GetType()!= Ansys.ACT.Automation.Mechanical.Figure):
mess_line1 = 'Please select figure(s)'
MessageBox.Show(mess_line1)
pass
import wbjn
cmd = 'returnValue(GetUserFilesDirectory())'
user_dir = wbjn.ExecuteCommand(ExtAPI,cmd)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
200 of ANSYS, Inc. and its subsidiaries and affiliates.
Export Figures
if fig.GetType() != Ansys.ACT.Automation.Mechanical.Figure:
continue
ExtAPI.DataModel.Tree.Activate(fig)
anWD=ExtAPI.DataModel.AnalysisById(0).WorkingDir
filename=user_dir+'\\'+'Figure - '+fig.Parent.Name+'.jpg'
ExtAPI.Graphics.ExportImage(filename)
msg = Ansys.Mechanical.Application.Message('Figure for '+fig.Parent.Name+' stored in folder '+user_dir, Mes
ExtAPI.Application.Messages.Add(msg)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 201
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
202 of ANSYS, Inc. and its subsidiaries and affiliates.
Script Examples for Interacting with the Mechanical
Session
The following scripts are for interacting with the Mechanical session:
Remesh a Model Multiple Times and Track Metrics
Perform Solution While Specifying Solution Handler and the Number of Cores
Scan Results, Suppress Any with Invalid Display Times, and Evaluate
Check Version
Check Operating Environment
Search for Keyword and Export
Modify Export Setting
Pan the Camera
Functions to Draw
Export All Result Animations
Get User Files Directory
Display an Arrow at the Centroid of Selected Faces
Compute Shortest Distance Between Two Faces
Display Extensions Loaded in Mechanical
Code:
from time import clock, time
for x in range(0, 5):
Model.ClearGeneratedData()
t1 = time()
Model.Mesh.GenerateMesh()
t2 = time()
print "Stats for mesh %d, elapsed time=%d" % (x+1, t2-t1)
print Model.Mesh.Nodes
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 203
Script Examples for Interacting with the Mechanical Session
3. Tracks how long each solution takes when solved using a different number of cores.
Code
# Get the existing My Computer, Background solve configuration
config = ExtAPI.Application.SolveConfigurations["My Computer, Background"]
config.SetAsDefault()
Scan Results, Suppress Any with Invalid Display Times, and Evaluate
Goal: Scan all result objects in your first analysis, suppress any results with invalid display times, and
then evaluate all results.
Code:
aset = Model.Analyses[0].AnalysisSettings
OrigStep = aset.CurrentStepNumber
aset.CurrentStepNumber = aset.NumberOfSteps
FinalTime = aset.StepEndTime
aset.CurrentStepNumber = OrigStep
sol = Model.Analyses[0].Solution
for obj in sol.Children:
if hasattr(obj,"DisplayTime"):
if obj.DisplayTime > FinalTime:
obj.Suppressed = True
sol.EvaluateAllResults()
Check Version
Goal: Check the version in which your user is operating.
Code:
clr.AddReference("Ans.Utilities")
import Ansys.Utilities
from Ansys.Utilities import ApplicationConfiguration
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
204 of ANSYS, Inc. and its subsidiaries and affiliates.
Pan the Camera
---
ansysVersion = ApplicationConfiguration.DefaultConfiguration.VersionInfo.VersionString
Code:
clr.AddReference("Ans.Utilities")
import Ansys.Utilities
from Ansys.Utilities import ApplicationConfiguration
---
isUnix = ApplicationConfiguration.DefaultConfiguration.IsUnix
Code:
path = "C:\\"
n = 0
Code:
ExtAPI.Application.ScriptByName("jscript").ExecuteCommand('WB.PreferenceMgr.Preference("PID_Show_Node_Numbers") =
Code:
camera = Graphics.Camera
up_vector = camera.UpVector
view_vector = camera.ViewVector
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 205
Script Examples for Interacting with the Mechanical Session
#get the 2D CSYS in the screen plane based on the computed UpVector, derived from the prescribed one.
plane_right = up_vector.CrossProduct(view_vector) # the “x” axis of the 2D CSYS.
plane_up = up_vector - (up_vector.DotProduct(view_vector)) * view_vector # the “y” axis of the 2D CSYS.
#construct the pan vector in the screen plane (Use the units from Graphics.Unit).
pan_right = 100
pan_up = 100
pan_vector = plane_right * pan_right + plane_up * pan_up
#set the new focal point by adding the pan vector to the original focal point.
pan_origin = camera.FocalPoint.Location
new_x, new_y, new_z = (pan_origin[0] + pan_vector[0], pan_origin[1] + pan_vector[1], pan_origin[2] + pan_vector[2]
camera.FocalPoint = Point([new_x, new_y, new_z], Graphics.Unit)
Functions to Draw
Goal: Add several example draw functions that can be used to draw entities in the Mechanical graphics
window.
Code:
def DrawElements():
elems = DataModel.MeshDataByName('Global').Elements
elem = Graphics.Scene.Factory3D.CreateMesh(list(elems)[:5])
elem.Color = 0xA00ABC
def DrawBody():
body = DataModel.GeoData.Assemblies[0].Parts[0].Bodies[0]
geo = Graphics.Scene.Factory3D.CreateGeometry(body)
geo.Color = 0xAAA000
def DrawFace():
face = DataModel.GeoData.Assemblies[0].Parts[0].Bodies[0].Faces[0]
geo = Graphics.Scene.Factory3D.CreateGeometry(face)
geo.Color = 0xABCABC
def DrawEdge():
edge = DataModel.GeoData.Assemblies[0].Parts[0].Bodies[0].Faces[0].Edges[1]
geo = Graphics.Scene.Factory3D.CreateGeometry(edge)
geo.LineWeight = 14
geo.VertexColor = 0x0000AA
geo.VertexSize = 15
geo.Color = 0x000ABC
def DrawVertex():
vertex = DataModel.GeoData.Assemblies[0].Parts[0].Bodies[0].Faces[0].Edges[0].Vertices[0]
geo = Graphics.Scene.Factory3D.CreateGeometry(vertex)
geo.Color = 0xBACBAC
def DrawTriad():
triad = Graphics.Scene.Factory3D.CreateTriad(1.0)
def DrawArrow():
Vector3D = Graphics.CreateVector3D
arrow = Graphics.Scene.Factory3D.CreateArrow(0.5)
arrow.Color = 0xFFABC0
arrow.Transformation3D.Translate(Vector3D(0.5, 0.5, 1))
def DrawBox():
box = Graphics.Scene.Factory3D.CreateBox(2.0, 3.0, 4.0)
box.Color = 0xFF0ABC
def DrawCircle():
cone = Graphics.Scene.Factory3D.CreateCircle(0.5)
cone.Color = 0xAAACCC
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
206 of ANSYS, Inc. and its subsidiaries and affiliates.
Functions to Draw
def DrawCone():
cone = Graphics.Scene.Factory3D.CreateCone(3.0, 2.0, 1.0)
cone.Color = 0xABC000
def DrawCylinder():
cone = Graphics.Scene.Factory3D.CreateCylinder(0.5, 2)
cone.Color = 0xAAA000
def DrawDisc():
cone = Graphics.Scene.Factory3D.CreateDisc(0.5)
cone.Color = 0xAAABBB
def DrawQuad():
sphere = Graphics.Scene.Factory3D.CreateQuad(0.33, 0.33)
sphere.Color = 0xFFA000
def DrawShell():
shell = Graphics.Scene.Factory3D.CreateShell([1., 1., 1. ,2., 1., 1., 1., 1. ,2.], [0., 1., 0., 0., 1., 0., 0.
shell.Color = 0xFFFFFF
def DrawSphere():
sphere = Graphics.Scene.Factory3D.CreateSphere(0.33)
sphere.Color = 0xFF0A00
def DrawPolyline3D():
Point2D = Graphics.CreatePixelPoint
Point3D = Graphics.CreateWorldPoint
Vector3D = Graphics.CreateVector3D
with Graphics.Suspend():
p1 = Point2D(10, 10)
p2 = Point2D(10, 100)
p3 = Point2D(100, 100)
p4 = Point2D(100, 10)
coll = Graphics.Scene.CreateChildCollection()
l1 = coll.Factory2D.CreatePolyline([p1, p2, p3, p4])
l1.Closed = True
p5 = Point2D(0, 0)
p6 = Point2D(100, 100)
l2 = Graphics.Scene.Factory2D.CreatePolyline([p5, p6])
p7 = Point2D(20, 40)
text = Graphics.Scene.Factory2D.CreateText(p7, "Hello World 3D")
wp1 = Point3D(0, 5, 0)
wp2 = Point3D(0, 0, 0)
wp3 = Point3D(5, 0, 0)
coll = Graphics.Scene.CreateChildCollection()
l1 = coll.Factory3D.CreatePolyline([wp1, wp2])
l2 = coll.Factory3D.CreatePolyline([wp2, wp3])
points = []
for i in range(10):
for j in range(10):
for k in range(10):
points.Add(Point3D(float(i)/float(10), float(j)/float(10),float(k)/float(10)))
coll.Factory3D.CreatePoint(points, 4)
return True
for i in range(5):
for j in range(5):
for k in range(5):
point = Point3D(float(i)/float(2), float(j)/float(2),float(k)/float(2))
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 207
Script Examples for Interacting with the Mechanical Session
def DrawPolyline2D():
Point2D = Graphics.CreatePixelPoint
Point3D = Graphics.CreateWorldPoint
with Graphics.Suspend():
p1 = Point2D(10, 10)
p2 = Point2D(10, 100)
p3 = Point2D(100, 100)
p4 = Point2D(100, 10)
coll = Graphics.Scene.CreateChildCollection()
l1 = coll.Factory2D.CreatePolyline([p1, p2, p3, p4])
l1.Closed = True
p5 = Point2D(0,0)
p6 = Point2D(100,100)
l2 = Graphics.Scene.Factory2D.CreatePolyline([p5, p6])
p7 = Point2D(20,40)
text = Graphics.Scene.Factory2D.CreateText(p7, "Hello World 2D")
wp1 = Point3D(0,5,0)
wp2 = Point3D(0,0,0)
wp3 = Point3D(5,0,0)
coll = Graphics.Scene.CreateChildCollection()
l1 = coll.Factory3D.CreatePolyline([wp1, wp2])
l2 = coll.Factory3D.CreatePolyline([wp2, wp3])
points = []
for i in range(10):
for j in range(10):
points.Add(Point2D(float(i)/float(10), float(j)/float(10)))
coll.Factory2D.CreatePoint(points, 4)
def DrawText2D(pixX,pixY,color):
Point2D = Graphics.CreatePixelPoint
with Graphics.Suspend():
p7 = Point2D(pixX,pixY)
text = Graphics.Scene.Factory2D.CreateText(p7, "Hello World 2D")
text.Color = color
def DrawText3D(x,y,z,color):
Point3D = Graphics.CreateWorldPoint
with Graphics.Suspend():
p7 = Point3D(x,y,z)
text = Graphics.Scene.Factory3D.CreateText3D(p7, "Hello World 3D")
text.Color = color
Code:
#Set camera and view
cam = Graphics.Camera
cam.SetSpecificViewOrientation(ViewOrientationType.Right)
#Animation settings
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
208 of ANSYS, Inc. and its subsidiaries and affiliates.
Display an Arrow at the Centroid of Selected Faces
Graphics.ResultAnimationOptions.NumberOfFrames = 10
Graphics.ResultAnimationOptions.Duration = Quantity(2, 's')
settings = Ansys.Mechanical.Graphics.AnimationExportSettings(width = 1000, height = 665)
The following script queries the Workbench application for the directory path for user files.
Code
import wbjn
cmd = 'returnValue(GetUserFilesDirectory())'
user_dir = wbjn.ExecuteCommand(ExtAPI,cmd)
print user_dir
The following script creates an arrow annotation and places it at the centroid on each specified
face. The length of each arrow is half of the value of the Bounding Box of the face.
Code
for geoId in ExtAPI.SelectionManager.CurrentSelection.Ids :
geoEntity=ExtAPI.DataModel.GeoData.GeoEntityById(geoId)
if geoEntity.Type != GeoCellTypeEnum.GeoFace :
print("Only faces are supported")
continue
# Create the arrow, set size at half the bounding box length of the face
bbox = geoEntity.GetBoundingBox()
sizeCAD = sqrt((bbox[0]-bbox[3])**2 + (bbox[1]-bbox[4])**2 + (bbox[2]-bbox[5])**2)
arrow = ExtAPI.Graphics.Scene.Factory3D.CreateArrow(sizeCAD/2)
arrow.Visible = False
# Set the color to red
arrow.Color=0xFF0000
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 209
Script Examples for Interacting with the Mechanical Session
ExtAPI.Graphics.Scene.Visible = True
arrow.Visible = True
print user_dir
The following script enables you to calculate the shortest distance between two faces.
Code
# Compute distance between two faces
import math
import units
clr.AddReference("Ans.UI.Toolkit.Base")
clr.AddReference("Ans.UI.Toolkit")
from Ansys.UI.Toolkit import *
# Utility functions
def distance(p1,p2):
return math.sqrt((p2[0]-p1[0])**2+(p2[1]-p1[1])**2+(p2[2]-p1[2])**2)
def dotProduct(v1,v2):
return v2[0]*v1[0]+v2[1]*v1[1]+v2[2]*v1[2]
def vecLength(vec):
return math.sqrt(vec[0]**2+vec[1]**2+vec[2]**2)
class BoundingBoxData:
# Class to compute geometric elements of a bounding box such as elementary vectors, edge length and midpoint
# Assumes ABCDEFGH points where A is origin, G is diagonal point, orientation triad is AB / AC /AE
def __init__(self,face):
bbox=face.GetBoundingBox()
self.Face=face
self.Origin=[bbox[0],bbox[1],bbox[2]]
self.Diagonal=[bbox[3],bbox[4],bbox[5]]
self.Midpoint=[0.5*(self.Diagonal[0]+self.Origin[0]),0.5*(self.Diagonal[1]+self.Origin[1]),0.5*(self.Di
pointB=[bbox[3],bbox[1],bbox[2]]
pointC=[bbox[0],bbox[4],bbox[2]]
pointE=[bbox[0],bbox[1],bbox[5]]
self.vecX=[pointB[0]-self.Origin[0],pointB[1]-self.Origin[1],pointB[2]-self.Origin[2]]
self.vecY=[pointC[0]-self.Origin[0],pointC[1]-self.Origin[1],pointC[2]-self.Origin[2]]
self.vecZ=[pointE[0]-self.Origin[0],pointE[1]-self.Origin[1],pointE[2]-self.Origin[2]]
self.xlength=distance(pointB,self.Origin)
self.ylength=distance(pointC,self.Origin)
self.zlength=distance(pointE,self.Origin)
for i in range(0,3):
if self.xlength != 0.: self.vecX[i]=self.vecX[i]/self.xlength
if self.ylength != 0.: self.vecY[i]=self.vecY[i]/self.ylength
if self.zlength != 0.: self.vecZ[i]=self.vecZ[i]/self.zlength
def CheckPointInBox(self,point):
# Check if a point [x,y,z] lies within the bounding box
isInside=True
vector=[point[0]-self.Midpoint[0],point[1]-self.Midpoint[1],point[2]-self.Midpoint[2]]
if self.xlength != 0:
checkX=abs(dotProduct(vector,self.vecX))-self.xlength/2<=1e-8
else:
checkX=abs(point[0]-self.Origin[0])<1e-8
if self.ylength != 0:
checkY=abs(dotProduct(vector,self.vecY))-self.ylength/2<=1e-8
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
210 of ANSYS, Inc. and its subsidiaries and affiliates.
Compute Shortest Distance Between Two Faces
else:
checkY=abs(point[1]-self.Origin[1])<1e-8
if self.zlength != 0:
checkZ=abs(dotProduct(vector,self.vecZ))-self.zlength/2<=1e-8
else:
checkZ=abs(point[2]-self.Origin[2])<1e-8
return isInside
def checkEdgeDistance(edge,bbox):
# Compute distance between an edge and a face
# edge and face from bbox are the ones to compare
# bbox is the boundingboxdata object related to face
# start_vertex holds the coordinates of the end vertex of the edge to start from when scanning the edge (in [x,
#
mindist=1e31
face=bbox.Face
while p0<=1:
vert=edge.PointAtParam(p0) # get point at p0
pa=face.ParamAtPoint((vert[0],vert[1],vert[2])) # project on face
pt=face.PointAtParam(pa[0],pa[1]) # from (u,v), compute projection coordinates
if bbox.CheckPointInBox(pt): # verify if projection is on the face or not using bounding box
dist=distance(vert,pt)
if dist<mindist:
mindist=dist
p0=p0+deltaP
return mindist
curSel=ExtAPI.SelectionManager.CurrentSelection
face=ExtAPI.DataModel.GeoData.GeoEntityById(curSel.Ids[0])
if face.Type != GeoCellTypeEnum.GeoFace:
MessageBox.Show(mess_line1)
pass
edgef1=f1.Edges
edgef2=f2.Edges
edgef1Id=[]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 211
Script Examples for Interacting with the Mechanical Session
edgef2Id=[]
for edge in edgef2:
edgef2Id.append(edge.Id)
# Collect vertices from the two faces - if no vertices, retrieve points from edges
vertf1=[]
if len(f1.Vertices)!=0:
for vert in f1.Vertices:
vertf1.append([vert.X,vert.Y,vert.Z])
else:
for edge in edgef1:
for i in range(0,len(edge.Points)/3):
vertf1.append([edge.Points[3*i],edge.Points[3*i+1],edge.Points[3*i+2]])
vertf2=[]
if len(f2.Vertices)!=0:
for vert in f2.Vertices:
vertf2.append([vert.X,vert.Y,vert.Z])
else:
for edge in edgef2:
for i in range(0,len(edge.Points)/3):
vertf2.append([edge.Points[3*i],edge.Points[3*i+1],edge.Points[3*i+2]])
# Run 4 trials:
# - f1 vertices projected on f2
# - f2 vertices projected on f1
# - f1 vertices projected on edges of f2
# - f2 vertices projected on edges of f1
if mindist!=1e31: # a minimum has been found, scan edges related to closest vertex to see if a closer location
for vert in f1.Vertices:
if vert.X==minVertex[0] and vert.Y==minVertex[1] and vert.Z==minVertex[2]:
for edge in vert.Edges: # scan edges related to closest vertex
if edge.Id in edgef1Id: # scan only edges related to face 1
mindist2=checkEdgeDistance(edge,bbox2)
if mindist2 < mindist:
mindist=mindist2
minSource='f1vf2mod'
if minSource=='f2vf1': # a minimum has been found, scan edges related to closest vertex to see if a closer loca
for vert in f2.Vertices:
if vert.X==minVertex[0] and vert.Y==minVertex[1] and vert.Z==minVertex[2]:
for edge in vert.Edges:
if edge.Id in edgef2Id:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
212 of ANSYS, Inc. and its subsidiaries and affiliates.
Display Extensions Loaded in Mechanical
mindist2=checkEdgeDistance(edge,bbox1)
if mindist2 < mindist:
mindist=mindist2
minSource='f2vf1mod'
length_unit=ExtAPI.DataModel.GeoData.Unit
curUnit=ExtAPI.DataModel.CurrentUnitFromQuantityName("Length")
# Display result
mess_line = 'Computed distance (approx) = ' + str(round(mindist_curUnit,3)) + ' ' + str(curUnit)+'\n'
#mess_line += '(found '+minDistSource[minSource]+')\n'
MessageBox.Show(mess_line)
This script displays a message box that lists all of extensions that you have loaded into Mechanical.
Example Code:
to_print = "List of Loaded Extensions: \n"
extensions = ExtAPI.ExtensionManager.Extensions
for extension in extensions:
to_print = to_print + extension.Name + '\n'
MessageBox.Show(to_print)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 213
Script Examples for Interacting with the Mechanical Session
Illustrated Example
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
214 of ANSYS, Inc. and its subsidiaries and affiliates.
Script Examples for Interacting with Results
The following scripts are for generating results in the Mechanical application:
Retrieve Stress Results
Create Probe Principal Stresses from a Node Selection
Finding Hot Spots
Code:
reader = Model.Analyses[0].GetResultsData()
reader.CurrentResultSet=1
S=reader.GetResult("S")
S.GetElementValues(1)
reader.Dispose()
Important:
Principal stresses obtained from the above script could differ from the same value calculated
in Mechanical.
In Mechanical, the component values are first averaged from the elements at a common
node, and then the principal stress values are calculated from the averaged components.
(Similar to AVPRIN,0 in Mechanical APDL).
The following script inserts a Probe for Principal Stresses and specifies a node for solution.
Code
# Retrieve principal stresses from a selection of nodes and display in a message box
import math
import units
import mech_dpf
import Ans.DataProcessing as dpf
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 215
Script Examples for Interacting with Results
clr.AddReference("Ans.UI.Toolkit.Base")
clr.AddReference("Ans.UI.Toolkit")
from Ansys.UI.Toolkit import *
curSel=ExtAPI.SelectionManager.CurrentSelection
meshData=ExtAPI.DataModel.Project.Model.Analyses[0].MeshData
scoping=dpf.Scoping()
scoping.Ids = curSel.Ids
scoping.Location=dpf.enums.location.nodal
an1=ExtAPI.DataModel.AnalysisByName(ExtAPI.DataModel.AnalysisNames[0])
rstFile=an1.WorkingDir+'file.rst'
dataSource = dpf.DataSources(rstFile)
stressOp1 = dpf.operators.result.stress_principal_1()
stressOp2 = dpf.operators.result.stress_principal_2()
stressOp3 = dpf.operators.result.stress_principal_3()
stressOp1.inputs.data_sources.Connect(dataSource)
stressOp2.inputs.data_sources.Connect(dataSource)
stressOp3.inputs.data_sources.Connect(dataSource)
stressOp1.inputs.mesh_scoping.Connect(scoping)
stressOp2.inputs.mesh_scoping.Connect(scoping)
stressOp3.inputs.mesh_scoping.Connect(scoping)
stressData1=stressOp1.outputs.fields_container.GetData()[0]
stressData2=stressOp2.outputs.fields_container.GetData()[0]
stressData3=stressOp3.outputs.fields_container.GetData()[0]
stressData=[]
# Display result
mess_line='Node\tS1\tS2\tS3\n'
for sd in stressData:
mess_line+=str(sd[0])+'\t'+str(round(sd[1],2))+'\t'+str(round(sd[2],2))+'\t'+str(round(sd[3],2))+'\n'
MessageBox.Show(mess_line)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
216 of ANSYS, Inc. and its subsidiaries and affiliates.
Finding Hot Spots
The script specifies the insertion of seven labels. The script places the first label at the result’s maximum
value, and each subsequent label is placed at a distance of 0.01 (script line 25) in between each node.
This distance between labels makes sure that all labels will not be clustered around the maximum value.
The unit for this distance is based on what you have selected in your analysis. For the example above,
the selected unit is meters. In addition, and again based on the currently selected unit of measure, the
result threshold is 20 (script line 27). This means that no result value (or label) below this threshold is
included.
import mech_dpf
import Ans.DataProcessing as dpf
def nodeDist(cur_node,nodes_dict,test_dist):
# Compute distance between a reference node (cur_node) and
# a set of nodes nodes_dict and check vs a test distance (test_dist)
# if any of the nodes in nodes_dict is close to cur_node within
# less than test_dist, then return False. Otherwise cur_node is
# away from each node in nodes_dict by at least test_dist
test=True
for nodeId in nodes_dict.keys():
test_node=nodes_dict[nodeId]
dist=0.
for i in range(0,3):
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 217
Script Examples for Interacting with Results
dist+=(test_node[i]-cur_node[i])**2
if (dist<=test_dist**2):
test=False
break
return test
# Temporary operator
currentMises = vmises.outputs.getfields_container()
if not(currentMises.Data):
ExtAPI.Application.LogWarning('Threshold value exceeds maximum stress. Please set a lower value for "thresholdSt
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
218 of ANSYS, Inc. and its subsidiaries and affiliates.
Finding Hot Spots
# node if node is far enough from all other nodes, add to labels
# otherwise, we simply ignore this maximum
maxNodes[maxNodeId]=nodeCoord
maxPairs[maxValue]=maxNodeId
numFound+=1
else:
# first label at maximum value
# Retrieve max value and corresponding node from maxData operator
maxValue=maxData.Data[0]
maxNodeId=maxData.ScopingIds[0]
# Start population data in maxPairs (maxvalue:node id)
# and maxNodes (node id: x,y,z)
maxPairs[maxValue]=maxNodeId
node=mesh.NodeById(maxNodeId)
maxNodes[maxNodeId]=[node.X, node.Y,node.Z]
numFound+=1
if numFound==0:
ExtAPI.Application.LogWarning('Could not find any hotspots. You should set "thresholdStress" variable or "minDis
else:
# Create labels on result object
with Transaction():
labelsForRes = Graphics.LabelManager.GetObjectLabels(resultObject)
Graphics.LabelManager.DeleteLabels(labelsForRes)
for node in maxPairs.values():
probeLabel = Graphics.LabelManager.CreateProbeLabel(resultObject)
probeLabel.Scoping.Node = node
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 219
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
220 of ANSYS, Inc. and its subsidiaries and affiliates.
Examples Using the Python Code Object
The following script examples are for use with the Python Code object:
After Object Changed Filtering
Send a Warning Message
Export a Boundary Condition
Update Following Mesh Generation
Check Property Values
Change Material Property
Print Message to ACT Log
Property Provider Example
Parameterize Coordinate System Transformation
Specify and Parameterize Bolt Pretension Loads
Goal: This Python script checks to see if the object that was changed is for a given category. Spe-
cifically, it checks whether a Pressure object was changed and if so, it prints its name to the log file.
The script drops any events that are not associated with the Pressure object. To view the log file,
from the Workbench Project page, select Extensions > View Log File.
Code
def after_object_changed(this, object_changed, property_name):# Do not edit this line
"""
Called after an object is changed.
Keyword Arguments :
this -- the datamodel object instance of the python code object you are currently editing in the tree
object_changed -- The object that was changed
property_name -- The property that was changed
"""
# To access properties created using the Property Provider, please use the following command.
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name")
# To access scoping properties use the following to access geometry scoping and named selection respectivel
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name/Geometry Selection")
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name/Named Selection")
# If you are intereseted in when pressure changes in any way, you can ignore all other object changed event
# using the line below.
if object_changed.DataModelObjectCategory != DataModelObjectCategory.Pressure:
return
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 221
Examples Using the Python Code Object
pass
The following script sends a warning message if a contact has been changed. It retrieves the contact's
name, changed property and new value.
Code
def after_object_changed(this, object_changed, property_name):# Do not edit this line
"""
Called after an object is changed.
Keyword Arguments :
this -- this python object
object_changed -- The object that was changed
property_name -- The property that was changed
"""
# The If statement allows to act only when a certain type of object has been changed
if (object_changed.GetType()==Ansys.ACT.Automation.Mechanical.Connections.ContactRegion):
msg = Ansys.Mechanical.Application.Message('You changed the following object : '+object_changed.Name+
'\n Property '+property_name+' has been set to '+str(getattr(object_changed,property_name)), MessageSev
ExtAPI.Application.Messages.Add(msg)
This script demonstrates how to export displacements to a text file once the simulation is solved.
Output of the script is an ASCII file with node number, XYZ location and UX/UY/UZ values over the
entire model.
Code
def after_post(this, solution):# Do not edit this line
"""
Called after post processing.
Keyword Arguments :
this -- this python object
solution -- Solution
"""
# This script shows how to export displacements in a text file once a simulation has been run
# Output of the script is an ASCII file with node number, XYZ location and UX/UY/UZ values over
# the entire model
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
222 of ANSYS, Inc. and its subsidiaries and affiliates.
Update Following Mesh Generation
import os
solution=ExtAPI.DataModel.GetObjectsByName('Solution')[0]
# We assume a static analysis with one load step, retrieve actual deformation data from rst
disp=displacements.outputs.fields_container.GetData()[0]
# Loop over nodes and write to txt file in user_files directory from project
outFileName=os.path.join(analysis.WorkingDir,'..\\..\\..\\user_files\\exported_disp.txt')
f_out=open(outFileName,'w')
f_out.write('# Node \t X\tY\tZ\tUX\tUY\tUZ\n')
for nid in sorted(nodeIds):
node=meshData.NodeById(nid) # Node data for nid
nodeDisp=disp.GetEntityDataById(nid) # displacement from node nid
f_out.write(str(nid)+'\t'+str(node.X)+'\t'+str(node.Y)+'\t'+str(node.Z)+
'\t'+str(nodeDisp[0])+'\t'+str(nodeDisp[1])+'\t'+str(nodeDisp[2])+'\n')
f_out.close()
The following script demonstrates how to automatically update all imported pressures after the
mesh has been generated.
Code
def after_mesh_generated(this,mesh_object):# Do not edit this line
"""
Called after mesh has been generated.
Keyword Arguments :
this -- this python object
mesh_object -- The mesh object that was generated
"""
# Note: the script may not work if you are using shared licenses
# Once the mesh has been generated, get all Imported Pressures to automatically reimport them
# Be careful this could be a time consuming task if many imported loads need to be updated
importedLoads=ExtAPI.DataModel.GetObjectsByType(DataModelObjectCategory.ImportedPressure)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 223
Examples Using the Python Code Object
ild.Activate()
ild.ImportLoad()
The following script demonstrates how to check a pressure quantity and the material of a body.
The script outputs a message in the Mechanical Message pane.
Code
def before_solve(this, analysis):# Do not edit this line
"""
Called before solving the parent analysis.
Keyword Arguments :
this -- this python object
analysis -- Static Structural
"""
# This script shows how to check a pressure quantity and body material
# Output of the script is a messages in Mechanical messages
The following script demonstrates how to change a material property for a given body using get
body commands.
Code
"""
To insert command just after material definitions in /PREP7, use solver_input_file.WriteLine("!Your command")
Global Helpers:
this -- this python object
solver_input_file -- file stream that allows you to inject commands into the solver input file
solver_data -- data stucture that allows you to access information from the model such as current step, con
"""
# This script shows how to change a material property for a given body
solver_input_file.WriteLine("! Changing Young modulus for body: "+this.Parent.Name) # Just a comment in the ds.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
224 of ANSYS, Inc. and its subsidiaries and affiliates.
Property Provider Example
body_id=this.Parent.GetGeoBody().Id # retrieve the body in the tree with this.Parent, then get corresponding ge
matid=solver_data.GetMaterialSolverId(body_id) # This is the material Id for APDL
The following script demonstrates how to print debug messages to the ACT log. For more information
on how to access the ACT log, see the Debug Mode section of the ACT Developer's Guide.
Code
def after_object_changed(this, object_changed, property_name):# Do not edit this line
"""
Called after an object is changed.
Keyword Arguments :
this -- the datamodel object instance of the python code object you are currently editing in the tree
object_changed -- The object that was changed
property_name -- The property that was changed
"""
# To access properties created using the Property Provider, please use the following command.
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name")
# To access scoping properties use the following to access geometry scoping and named selection respectivel
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name/Geometry Selection")
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name/Named Selection")
# Write debug messages to the extension log using the following command
ExtAPI.Log.WriteMessage("Inside after_object_changed")
pass
This example has two parts: the Python entry and the Property Provider entry.
• Python: This part of the script retrieves all Python Code object properties and writes
them to the ds.dat file as comments.
• Property Provider: The code contained in the Property Provider tab defines property
definitions. The example below creates properties that are similar to what you would
see in a Force object.
Python Code
"""
To insert commands just prior to the Ansys SOLVE command, use solver_input_file.WriteLine("!Your command")
Global Helpers:
this -- the datamodel object instance of the python code object you are currently editing in the tree
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 225
Examples Using the Python Code Object
solver_input_file -- file stream that allows you to inject commands into the solver input file
solver_data -- data stucture that allows you to access information from the model such as current step, con
"""
# To access properties created using the Property Provider, please use the following command.
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name")
# To access scoping properties use the following to access geometry scoping and named selection respectively:
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name/Geometry Selection")
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name/Named Selection")
properties = this.PropertyProvider.GetProperties()
for prop in properties:
line = "!" + prop.Name + " " + prop.ValueString
solver_input_file.WriteLine(line)
this.PropertyProvider = None
# comment the return below to allow the rest of the function definition to be executed and add properties
return
#Add an Expression property "Type" to the Definition2 group and set its value = "Force"
type = Definition.AddProperty("Type", Control.Expression )
type.Value = "Force"
#Create an instance of the custom ForceProperty that was created above and add it to the Definition2 group
force_prop = Definition.AddProperty("Force Property", "Force")
#Connects the provider instance back to the object by setting the PropertyProvider member on this, 'this' b
#current instance of the Python Code object.
this.PropertyProvider = Force
"""
The property_templates module is located in {YOUR_INSTALL_DIR}/DesignSpace/DSPages/Python/mech_templates
"""
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
226 of ANSYS, Inc. and its subsidiaries and affiliates.
Property Provider Example
class Provider(Ansys.ACT.Interfaces.Mechanical.IPropertyProvider):
"""
Provider template that implements IPropertyProvider to demonstrate the usage of IPropertyProvider.
It provides helper methods and classes that manage properties that can be dynamicall added to an object.
"""
# region These are callbacks that as a user you may want to modify to get specific behavior
def IsValid(self, prop):
"""
Called when checking the validity of a property, with the property instance.
"""
return True
return False
return True
class AnsGroup():
"""Helper group class to group properties, and provides methods to add properties to groups."""
provider = None
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 227
Examples Using the Python Code Object
Keyword Arguments :
name -- unique name for the scoping property
"""
Keyword Arguments :
name -- unique name for the force property
"""
force_prop = ForceProperty(name, self.name)
Keyword Arguments :
name -- unique name for the scoping property
prop_control -- one of the built in controls, or extended controls
module_name -- module where the control is defined
"""
prop_mod_globals = None
if(module_name != None):
if(module_name not in globals()):
raise Exception("Unknown module : " + module_name)
prop_mod_globals = globals()[module_name].get_globals()
else:
prop_mod_globals = globals()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
228 of ANSYS, Inc. and its subsidiaries and affiliates.
Property Provider Example
if(prop == None):
raise Exception("Issue while creating the property instance.")
#as a default make the property name the property display name
prop.DisplayName = name
return prop
def __init__(self):
pass
def GetProperties(self):
"""
Returns a list of properties in the order that they were added to the property provider.
"""
return [self.prop_map[propName] for propName in self.prop_list]
if name in self.prop_groups:
raise Exception("Group with name " + name + " already exists, please use a unique group name.")
#keep groups names so we can make sure no duplicate groups are added
self.prop_groups.add(name)
if(prop.Name in self.prop_map):
raise Exception("Property name must be unique, property with name '" + prop.Name + "' already exisi
self.prop_list.append(prop.Name)
self.prop_map[prop.Name] = prop
#end region
"""
Create a Force like object using PropertyProvider
"""
class ForceProperty:
"""
Class to create a custom Force property using a combination of different control types
"""
grouped_props = []
def __init__(self, name, groupName="Forcing"):
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 229
Examples Using the Python Code Object
def GetGroupedProps(self):
"""
Returns the properties list
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
230 of ANSYS, Inc. and its subsidiaries and affiliates.
Parameterize Coordinate System Transformation
"""
return self.grouped_props
return True
"""
Reload the properties at the end to make sure the class definition is executed before instantiation
"""
reload_props()
Code PyCode_OnAfterObjectChanged
def after_object_changed(this, object_changed, property_name):# Do not edit this line
"""
Called after an object is changed.
Keyword Arguments :
this -- the datamodel object instance of the python code object you are currently editing in the tree
object_changed -- The object that was changed
property_name -- The property that was changed
"""
# We ignore any changes other than changes made to the this python code object itself
# We listen for any changes made to this object so we can sync up paramterized properties
# with the coordinate system, everytime the design point updates happen
if this.DataModelObjectCategory != object_changed.DataModelObjectCategory:
return
# Sync up the paramterized properties on this object with the coordinate system
for prop in coordinate_system_props:
if prop.Name.find("Transform") != -1:
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 231
Examples Using the Python Code Object
newVal=this.GetCustomPropertyByPath("CS Transformations/"+prop.Caption)
prop.InternalValue=newVal
PyCode_OnBeforeSolve
def before_solve(this, analysis):# Do not edit this line
"""
Called before solving the parent analysis.
Keyword Arguments :
this -- the datamodel object instance of the python code object you are currently editing in the tree
analysis -- Static Structural
"""
# Log out the values of properties with the name that contain "Transform"
# to demonstrate the values for the coordinate system are parameterized
import os
import os.path
sys.path.append(os.getenv("TB_WORKING_DIRECTORY"))
WDIR = os.getenv("TB_WORKING_DIRECTORY")
fo2 = open(WDIR + "/DS_PYTHON_SNIPPET_019_Generated.log","a")
The following script demonstrates how to automatically set and parametrize the Preload value of
all the Bolt Pretension loads that are present in the analysis. Note that these loads need to have
the same name to be updated by the script. See an example (p. 233) of the executed script below.
Code
def after_object_changed(this, object_changed, property_name):# Do not edit this line
"""
Called after an object is changed.
Keyword Arguments :
this -- the datamodel object instance of the python code object you are currently editing in the tree
object_changed -- The object that was changed
property_name -- The property that was changed
"""
# To access properties created using the Property Provider, please use the following command.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
232 of ANSYS, Inc. and its subsidiaries and affiliates.
Specify and Parameterize Bolt Pretension Loads
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name")
# To access scoping properties use the following to access geometry scoping and named selection respectivel
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name/Geometry Selection")
# this.GetCustomPropertyByPath("your_property_group_name/your_property_name/Named Selection")
if (object_changed.Name != this.Name):
# The change is not on the Python code object, simply ignore
return
prets.Preload.Inputs[0].DiscreteValues = time_vals
prets.Preload.Output.DiscreteValues=preload_vals
Example
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 233
Examples Using the Python Code Object
Here is an example of the script with the corresponding Details of the Python object.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
234 of ANSYS, Inc. and its subsidiaries and affiliates.
Specify and Parameterize Bolt Pretension Loads
And here is a portion of the code that is included in the Property Provider pane for the example.
def reload_props():
this.PropertyProvider = None
"""
Sample code is provided below that shows how to:
1. Create an instance of the Provider. The Provider class is used to add custom properties to the detai
"""
# Create a property with control type Expression and a property with control type Double, and add it to the
double_prop = group.AddProperty("Preload (N)", Control.Double)
# Configure the double property to be parameterizable. As a default the property will be an input parameter
# However, by updating the ParameterType property, it can be configured to be a output parameter as well.
double_prop.CanParameterize = True
double_prop.ParameterType = ParameterType.Input
# Connects the provider instance back to the object by setting the PropertyProvider member on this, 'this'
# current instance of the Python Code object.
this.PropertyProvider = provider
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 235
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
236 of ANSYS, Inc. and its subsidiaries and affiliates.
End-to-End Analysis Examples
The following examples describe a sequence of APIs that perform a complete analysis for the given
analysis scenario.
Note:
These examples assume that you have the automatic contact detection option turned on.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 237
End-to-End Analysis Examples
Shape
Optimization (p. 307)
Miscellaneous Analyses/Features External Model
Random Vibration
Analysis (p. 334)
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_Static_Structural_Example_001_Geometry.agdb
• Mechanical_Static_Structural_Example_001_Script.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Static Struc-
tural system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanical_Stat-
ic_Structural_Example_001_Geometry.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_Static_Structural_Ex-
ample_001_Script.py.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
238 of ANSYS, Inc. and its subsidiaries and affiliates.
Static Structural Analysis
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Section 1 - Set up the Tree Object Items.
CS_GRP = Model.CoordinateSystems
STAT_STRUC = Model.Analyses[0]
ANALYSIS_SETTINGS = STAT_STRUC.Children[0]
SOLN= STAT_STRUC.Solution
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
ExtAPI.Application.ActiveAngleUnit = AngleUnitType.Radian
NS1 = Model.NamedSelections.Children[0]
NS2 = Model.NamedSelections.Children[1]
NS3 = Model.NamedSelections.Children[2]
NS4 = Model.NamedSelections.Children[3]
GCS = CS_GRP.Children[0]
LCS1 = CS_GRP.Children[1]
RMPT_GRP = Model.RemotePoints
RMPT_1 = RMPT_GRP.AddRemotePoint()
RMPT_1.Location = NS1
RMPT_1.XCoordinate=Quantity("7 [m]")
RMPT_1.YCoordinate=Quantity("0 [m]")
RMPT_1.ZCoordinate=Quantity("0 [m]")
MSH = Model.Mesh
MSH.ElementSize =Quantity("0.5 [m]")
MSH.GenerateMesh()
REM_FRC1 = STAT_STRUC.AddRemoteForce()
REM_FRC1.Location = RMPT_1
REM_FRC1.DefineBy =LoadDefineBy.Components
REM_FRC1.XComponent.Output.DiscreteValues = [Quantity("1e10 [N]")]
THERM_COND = STAT_STRUC.AddThermalCondition()
THERM_COND.Location = NS4
THERM_COND.Magnitude.Output.DefinitionType=VariableDefinitionType.Formula
THERM_COND.Magnitude.Output.Formula="50*(20+z)"
THERM_COND.XYZFunctionCoordinateSystem=LCS1
THERM_COND.RangeMinimum=Quantity("-20 [m]")
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 239
End-to-End Analysis Examples
THERM_COND.RangeMaximum=Quantity("1 [m]")
DIR_DEF = STAT_STRUC.Solution.AddDirectionalDeformation()
DIR_DEF.Location = NS1
DIR_DEF.NormalOrientation =NormalOrientationType.XAxis
TOT_DEF = STAT_STRUC.Solution.AddTotalDeformation()
DIR_DEF_MAX = DIR_DEF.Maximum.Value
DIR_DEF_MIN = DIR_DEF.Minimum.Value
TOT_DEF_MAX = TOT_DEF.Maximum.Value
TOT_DEF_MIN = TOT_DEF.Minimum.Value
FRC_REAC_PROBE_VAL = FRC_REAC_PROBE.XAxis.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following files:
• Static_Structural_Spatially_Varying.agdb
• Static_Structural_Spatially_Varying.py
Procedure
1. Open Workbench and insert a Static Structural system into the Project Schematic.
3. Enable the Named Selections check box under the Basic Geometry Options category.
4. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Static_Structural_Spatially_Varying.agdb.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
240 of ANSYS, Inc. and its subsidiaries and affiliates.
Static Structural Spatially Varying Load Analysis
6. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
7. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Static_Structural_Spatially_Varying.py.
8. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Scenario 1: Store main Tree Object items
MODEL = Model
GEOM = MODEL.Geometry
COORDINATE_SYSTEMS = Model.CoordinateSystems
MESH = Model.Mesh
NAMED_SELECTIONS = Model.NamedSelections
PARTS = GEOM.GetChildren(DataModelObjectCategory.Part,False)
for part in PARTS:
bodies = part.GetChildren(DataModelObjectCategory.Body, False)
for body in bodies:
if body.Name == "Part 1":
PART1 = body
STAT_STRUC = DataModel.Project.Model.Analyses[0]
ANALYSIS_SETTINGS = STAT_STRUC.AnalysisSettings
STAT_STRUC_SOLUTION = STAT_STRUC.Solution
#Scenario 4: Store Named Selections for applying load and boundary condition in structural analysis
tot_child_NS_GRP = NAMED_SELECTIONS.Children.Count
for i in range(0, tot_child_NS_GRP, 1):
ns = NAMED_SELECTIONS.Children[i].Name
if(ns=='NS_FACE1'):
NS_FACE1 = NAMED_SELECTIONS.Children[i]
if(ns=='NS_FACE2'):
NS_FACE2 = NAMED_SELECTIONS.Children[i]
if(ns=='NS_FACE3'):
NS_FACE3 = NAMED_SELECTIONS.Children[i]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 241
End-to-End Analysis Examples
PRESSURE.Magnitude.Output.Formula = "1e9*z"
PRESSURE.XYZFunctionCoordinateSystem = COORDINATE_SYSTEM
FORCE_REACTION_PROBE = STAT_STRUC_SOLUTION.AddForceReaction()
FORCE_REACTION_PROBE.BoundaryConditionSelection = FIXED_SUPPORT
FORCE_REACTION_PROBE.Orientation = COORDINATE_SYSTEM
MOMENT_REACTION_PROBE = STAT_STRUC_SOLUTION.AddMomentReaction()
MOMENT_REACTION_PROBE.BoundaryConditionSelection = FIXED_SUPPORT
MOMENT_REACTION_PROBE.Orientation = COORDINATE_SYSTEM
FORCE_REACTION_PROBE_Y=FORCE_REACTION_PROBE.YAxis.Value
MOMENT_REACTION_PROBE_X=MOMENT_REACTION_PROBE.XAxis.Value
MOMENT_REACTION_PROBE_TOTAL=MOMENT_REACTION_PROBE.Total.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following CAD
model and python files.
• Transient_Structural_001.x_t
• Transient_Structural_001.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
242 of ANSYS, Inc. and its subsidiaries and affiliates.
Transient Structural Analysis
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Transient
Structural system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Transient_Struc-
tural_001.x_t.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Transient_Structural_001.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Section 1 - Set up the Tree Object Items.
#Section 2 - Set Units.
#Section 3 - Select Frictionless Contact
#Section 4 - Create Named Selection
#Section 5 - Create Mesh Refinement
#Section 6 - Analysis Settings
#Section 7 - Define Boundary Conditions and Loads
#Section 8 - Insert Results
#Section 9 - Solve and Evaluate Results
CONT_REG = DataModel.Project.Model.Connections.Children[0]
MSH = DataModel.Project.Model.Mesh
TRANS_STRUC1 = DataModel.AnalysisByName("Transient")
ANA_SETTING1 = TRANS_STRUC1.AnalysisSettings
SOLN= TRANS_STRUC1.Solution
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
ExtAPI.Application.ActiveAngleUnit = AngleUnitType.Radian
CONT1 = CONT_REG.Children[0]
CONT1.ContactType = ContactType.Frictionless
CONT1.InterfaceTreatment =ContactInitialEffect.AdjustToTouch
NS1 = DataModel.Project.Model.AddNamedSelection()
NS1.ScopingMethod=GeometryDefineByType.Worksheet
NS1.Name = "MSH_ref_1"
GEN_CRT1 = NS1.GenerationCriteria
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 243
End-to-End Analysis Examples
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.GeoFace
CRT1.Criterion=SelectionCriterionType.Size
CRT1.Operator=SelectionOperatorType.Equal
CRT1.Value=Quantity('9397.9 [mm mm]')
GEN_CRT1.Add(CRT1)
NS1.Activate()
NS1.Generate()
NS1.Duplicate()
NS2= DataModel.Project.Model.NamedSelections.Children[1]
NS2.Name = "MSH_ref_2"
GEN_CRT2 = NS2.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
GEN_CRT2[0].Value=Quantity('62653 [mm^2]')
NS2.Activate()
NS2.Generate()
NS1.Duplicate()
NS3= DataModel.Project.Model.NamedSelections.Children[2]
NS3.Name = "cmpsnonlysupp"
GEN_CRT3 = NS3.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
GEN_CRT3[0].Value=Quantity('22555 [mm^2]')
NS3.Activate()
NS3.Generate()
NS1.Duplicate()
NS4= DataModel.Project.Model.NamedSelections.Children[3]
NS4.Name = "frctlsupp"
GEN_CRT4 = NS4.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
GEN_CRT4[0].Value=Quantity('32558 [mm^2]')
CRT2 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT2.Active=True
CRT2.Action=SelectionActionType.Add
CRT2.EntityType=SelectionType.GeoFace
CRT2.Criterion=SelectionCriterionType.Size
CRT2.Operator=SelectionOperatorType.Equal
CRT2.Value=Quantity('60155 [mm mm]')
GEN_CRT4.Add(CRT2)
CRT3 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT3.Active=True
CRT3.Action=SelectionActionType.Add
CRT3.EntityType=SelectionType.GeoFace
CRT3.Criterion=SelectionCriterionType.Size
CRT3.Operator=SelectionOperatorType.Equal
CRT3.Value=Quantity('7764.6 [mm mm]')
GEN_CRT4.Add(CRT3)
NS4.Activate()
NS4.Generate()
NS1.Duplicate()
NS5= DataModel.Project.Model.NamedSelections.Children[4]
NS5.Name = "DISP1"
GEN_CRT5 = NS5.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
GEN_CRT5[0].Value=Quantity('7764.6 [mm^2]')
NS5.Activate()
NS5.Generate()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
244 of ANSYS, Inc. and its subsidiaries and affiliates.
Transient Structural Analysis
SEL=ExtAPI.SelectionManager.AddSelection(NS1)
SEL1=ExtAPI.SelectionManager.CurrentSelection
CLRSEL = ExtAPI.SelectionManager.ClearSelection()
REFINEMENT1.Location = SEL1
REFINEMENT1.NumberOfRefinements = 1
ANA_SETTING1.Activate()
ANA_SETTING1.NumberOfSteps=2
ANA_SETTING1.CurrentStepNumber=1
ANA_SETTING1.StepEndTime=Quantity("1 [sec]")
ANA_SETTING1.InitialTimeStep=Quantity("0.5 [sec]")
ANA_SETTING1.MinimumTimeStep=Quantity("0.5 [sec]")
ANA_SETTING1.MaximumTimeStep=Quantity("0.5 [sec]")
ANA_SETTING1.CurrentStepNumber=2
ANA_SETTING1.StepEndTime=Quantity("2 [sec]")
ANA_SETTING1.InitialTimeStep=Quantity("0.5 [sec]")
ANA_SETTING1.MinimumTimeStep=Quantity("0.5 [sec]")
ANA_SETTING1.MaximumTimeStep=Quantity("0.5 [sec]")
ANA_SETTING1.NewtonRaphsonOption=NewtonRaphsonType.ProgramControlled
ANA_SETTING1.ForceConvergence=ConvergenceToleranceType.On
COMP_SUP = TRANS_STRUC1.AddCompressionOnlySupport()
COMP_SUP.Location = NS3
BEARING_LD = TRANS_STRUC1.AddBearingLoad()
BEARING_LD.Location = NS2
BEARING_LD.DefineBy = LoadDefineBy.Components
BEARING_LD.XComponent.Inputs[0].DiscreteValues = [Quantity("0 [sec]"), Quantity("1 [sec]"), Quantity("2 [sec]")]
BEARING_LD.XComponent.Output.DiscreteValues = [Quantity("1e5 [N]"), Quantity("2e5 [N]"), Quantity("3e5 [N]")]
FRIC_SUP = TRANS_STRUC1.AddFrictionlessSupport()
FRIC_SUP.Location = NS4
DISP1 = TRANS_STRUC1.AddDisplacement()
DISP1.Location = NS5
DISP1.DefineBy = LoadDefineBy.Components
DISP1.YComponent.Inputs[0].DiscreteValues = [Quantity("0 [sec]"), Quantity("1 [sec]"), Quantity("2 [sec]")]
DISP1.YComponent.Output.DiscreteValues = [Quantity("0.0 [m]"), Quantity("0.0 [m]"), Quantity("0.0 [m]")]
FRC_REAC_PROBE = TRANS_STRUC1.Solution.AddForceReaction()
FRC_REAC_PROBE.BoundaryConditionSelection = COMP_SUP
EQV_STRS_1 = TRANS_STRUC1.Solution.AddEquivalentStress()
STRS_TOOL_1 = TRANS_STRUC1.Solution.AddStressTool()
STRS_SAF_FCTR_1 = STRS_TOOL_1.AddSafetyFactor()
STRS_TOOL_1.StressLimitType = SafetyLimitType.UltimatePerMaterial
TRANS_STRUC1.Solution.Solve(True)
EQV_STRS_MAX_1 = EQV_STRS_1.MaximumOfMaximumOverTime.Value
EQV_STRS_MIN_1 = EQV_STRS_1.MinimumOfMinimumOverTime.Value
FRC_REAC_PROBE_VAL = FRC_REAC_PROBE.XAxis.Value
STRS_SAF_FCTR_1_VAL = STRS_SAF_FCTR_1.Minimum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 245
End-to-End Analysis Examples
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_Static_General_Joint_Example_Script.x_t
• Mechanical_Static_General_Joint_Example_Script.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Static Struc-
tural system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanical_Stat-
ic_General_Joint_Example_Script.x_t.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_Static_Structural_Ex-
ample_001_Script.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Scenario 1 - Set up the Units System
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
246 of ANSYS, Inc. and its subsidiaries and affiliates.
Static Structural General Joint Analysis
CONNECTION_GROUP = Model.Connections
MESH = Model.Mesh
STATIC_STRUCTURAL = Model.Analyses[0]
ANALYSIS_SETTINGS = STATIC_STRUCTURAL.Children[0]
STATIC_STRUCTURAL_SOLUTION = STATIC_STRUCTURAL.Solution
NS_FIXED_FACE = DataModel.Project.Model.AddNamedSelection()
NS_FIXED_FACE.ScopingMethod=GeometryDefineByType.Worksheet
NS_FIXED_FACE.Name = "NS_FIXED_FACE"
GEN_CRT1 = NS_FIXED_FACE.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.GeoFace
CRT1.Criterion=SelectionCriterionType.LocationZ
CRT1.Operator=SelectionOperatorType.Equal
CRT1.Value=Quantity('0.00 [m]')
GEN_CRT1.Add(CRT1)
NS_FIXED_FACE.Activate()
NS_FIXED_FACE.Generate()
NS_BC_FACE = DataModel.Project.Model.AddNamedSelection()
NS_BC_FACE.ScopingMethod=GeometryDefineByType.Worksheet
NS_BC_FACE.Name = "NS_BC_FACE"
GEN_CRT1 = NS_BC_FACE.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.GeoFace
CRT1.Criterion=SelectionCriterionType.LocationZ
CRT1.Operator=SelectionOperatorType.Equal
CRT1.Value=Quantity('20.00 [m]')
GEN_CRT1.Add(CRT1)
NS_BC_FACE.Activate()
NS_BC_FACE.Generate()
JOINT_GENERAL = CONNECTION_GROUP.AddJoint()
JOINT_GENERAL.ConnectionType = JointScopingType.BodyToGround
JOINT_GENERAL.Type = JointType.General
JOINT_GENERAL.TranslationZ = FixedOrFree.Free
JOINT_GENERAL.MobileLocation = NS_FIXED_FACE
# The below commands help in setting the rotational dofs
JOINT_GENERAL.Rotations = JointRotationDOFType.FreeAll
JOINT_GENERAL.Rotations = JointRotationDOFType.FixAll
DISPLACEMENT_BC = STATIC_STRUCTURAL.AddDisplacement()
DISPLACEMENT_BC.Location = NS_BC_FACE
DISPLACEMENT_BC.ZComponent.Output.DiscreteValues = [Quantity("0.01 [m]")]
DIRECTIONAL_DEFORMATION = STATIC_STRUCTURAL_SOLUTION.AddDirectionalDeformation()
DIRECTIONAL_DEFORMATION.NormalOrientation = NormalOrientationType.ZAxis
JOINT_PROBE_RELATIVE_DISPLACEMENT = STATIC_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_RELATIVE_DISPLACEMENT.BoundaryConditionSelection = JOINT_GENERAL
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 247
End-to-End Analysis Examples
JOINT_PROBE_RELATIVE_DISPLACEMENT.ResultType = ProbeResultType.DeformationProbe
JOINT_PROBE_RELATIVE_DISPLACEMENT.ResultSelection = ProbeDisplayFilter.ZAxis
STATIC_STRUCTURAL_SOLUTION.Solve(True)
DIRECTIONAL_DEFORMATION_MAX = DIRECTIONAL_DEFORMATION.Maximum.Value
DIRECTIONAL_DEFORMATION_MIN = DIRECTIONAL_DEFORMATION.Minimum.Value
JOINT_PROBE_RELATIVE_DISPLACEMENT_MAX = JOINT_PROBE_RELATIVE_DISPLACEMENT.MaximumZAxis.Value
JOINT_PROBE_RELATIVE_DISPLACEMENT_MIN = JOINT_PROBE_RELATIVE_DISPLACEMENT.MinimumZAxis.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_Static_Joint_002_Example.agbd
• Mechanical_Static_Joint_002_Example.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Static Struc-
tural system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanical_Stat-
ic_Joint_002_Example.agbd.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
248 of ANSYS, Inc. and its subsidiaries and affiliates.
Static Structural Universal Joint Analysis
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_Static_Joint_002_Example.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#===================================================================================================================
# ACT Mechanical API Example for General Joint as Translational
# Python Script Scenarios:
# 1. Set up the Unit Systems
# 2. Set up the Tree Object Items
# 3. Define Named Selections
# 4. Define General Joint as Translational
# 5. Define Mesh Settings
# 6. Insert Displacement BC
# 7. Insert Results
# 8. Solve and review the results
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
CONNECTION_GROUP = Model.Connections
MESH = Model.Mesh
STATIC_STRUCTURAL = Model.Analyses[0]
ANALYSIS_SETTINGS = STATIC_STRUCTURAL.Children[0]
STATIC_STRUCTURAL_SOLUTION = STATIC_STRUCTURAL.Solution
NS_FIXED_FACE = DataModel.Project.Model.AddNamedSelection()
NS_FIXED_FACE.ScopingMethod=GeometryDefineByType.Worksheet
NS_FIXED_FACE.Name = "NS_FIXED_FACE"
GEN_CRT1 = NS_FIXED_FACE.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.GeoFace
CRT1.Criterion=SelectionCriterionType.LocationZ
CRT1.Operator=SelectionOperatorType.Equal
CRT1.Value=Quantity('0.00 [m]')
GEN_CRT1.Add(CRT1)
NS_FIXED_FACE.Activate()
NS_FIXED_FACE.Generate()
NS_BC_FACE = DataModel.Project.Model.AddNamedSelection()
NS_BC_FACE.ScopingMethod=GeometryDefineByType.Worksheet
NS_BC_FACE.Name = "NS_BC_FACE"
GEN_CRT1 = NS_BC_FACE.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.GeoFace
CRT1.Criterion=SelectionCriterionType.LocationZ
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 249
End-to-End Analysis Examples
CRT1.Operator=SelectionOperatorType.Equal
CRT1.Value=Quantity('20.00 [m]')
GEN_CRT1.Add(CRT1)
NS_BC_FACE.Activate()
NS_BC_FACE.Generate()
JOINT_GENERAL = CONNECTION_GROUP.AddJoint()
JOINT_GENERAL.ConnectionType = JointScopingType.BodyToGround
JOINT_GENERAL.Type = JointType.General
JOINT_GENERAL.TranslationZ = FixedOrFree.Free
JOINT_GENERAL.MobileLocation = NS_FIXED_FACE
# The below commands help in setting the rotational dofs
JOINT_GENERAL.Rotations = JointRotationDOFType.FreeAll
JOINT_GENERAL.Rotations = JointRotationDOFType.FixAll
DISPLACEMENT_BC = STATIC_STRUCTURAL.AddDisplacement()
DISPLACEMENT_BC.Location = NS_BC_FACE
DISPLACEMENT_BC.ZComponent.Output.DiscreteValues = [Quantity("0.01 [m]")]
DIRECTIONAL_DEFORMATION = STATIC_STRUCTURAL_SOLUTION.AddDirectionalDeformation()
DIRECTIONAL_DEFORMATION.NormalOrientation = NormalOrientationType.ZAxis
JOINT_PROBE_RELATIVE_DISPLACEMENT = STATIC_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_RELATIVE_DISPLACEMENT.BoundaryConditionSelection = JOINT_GENERAL
JOINT_PROBE_RELATIVE_DISPLACEMENT.ResultType = ProbeResultType.DeformationProbe
JOINT_PROBE_RELATIVE_DISPLACEMENT.ResultSelection = ProbeDisplayFilter.ZAxis
STATIC_STRUCTURAL_SOLUTION.Solve(True)
DIRECTIONAL_DEFORMATION_MAX = DIRECTIONAL_DEFORMATION.Maximum.Value
DIRECTIONAL_DEFORMATION_MIN = DIRECTIONAL_DEFORMATION.Minimum.Value
JOINT_PROBE_RELATIVE_DISPLACEMENT_MAX = JOINT_PROBE_RELATIVE_DISPLACEMENT.MaximumZAxis.Value
JOINT_PROBE_RELATIVE_DISPLACEMENT_MIN = JOINT_PROBE_RELATIVE_DISPLACEMENT.MinimumZAxis.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
250 of ANSYS, Inc. and its subsidiaries and affiliates.
Transient Structural Cylindrical Joint Analysis
• Cylindrical_Joint_Example.agbd
• Cylindrical_Joint_Example.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Transient
Structural system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Cylindric-
al_Joint_Example.agbd.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Cylindrical_Joint_Example.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 - Set up the Units System
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardCGS
GEOMETRY = Model.Geometry
CONNECTION_GROUP = Model.Connections
MESH = Model.Mesh
TRANSIENT_STRUCTURAL = Model.Analyses[0]
ANALYSIS_SETTINGS = TRANSIENT_STRUCTURAL.Children[1]
TRANSIENT_STRUCTURAL_SOLUTION = TRANSIENT_STRUCTURAL.Solution
PART1 = GEOMETRY.Children[0].Children[0]
PART2 = GEOMETRY.Children[1].Children[0]
PART1.StiffnessBehavior = StiffnessBehavior.Rigid
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 251
End-to-End Analysis Examples
PART2.StiffnessBehavior = StiffnessBehavior.Rigid
NS_FACE_1 = DataModel.GetObjectsByName("NS_Face_1")[0]
NS_FACE_2 = DataModel.GetObjectsByName("NS_Face_2")[0]
NS_FACE_3 = DataModel.GetObjectsByName("NS_Face_3")[0]
NS_FORCE_1 = DataModel.GetObjectsByName("NS_Force_1")[0]
NS_FORCE_2 = DataModel.GetObjectsByName("NS_Force_2")[0]
CONNECTION_GROUP.Activate()
JOINT_CYLINDRICAL = CONNECTION_GROUP.AddJoint()
JOINT_CYLINDRICAL.Name = "CYLINDRICAL_JOINT"
JOINT_CYLINDRICAL.ConnectionType = JointScopingType.BodyToBody
JOINT_CYLINDRICAL.Type = JointType.Cylindrical
JOINT_CYLINDRICAL.ReferenceLocation = NS_FACE_3
JOINT_CYLINDRICAL.MobileLocation= NS_FACE_2
# User can set the value of Torsional Stiffness and Torsional Damping using below commands.
JOINT_CYLINDRICAL.TorsionalStiffness = Quantity ("1e6 [dyne cm deg^-1]")
JOINT_CYLINDRICAL.TorsionalDamping= Quantity ("1e6 [dyne cm s deg^-1]")
CONNECTION_GROUP.Activate()
JOINT_FIXED = CONNECTION_GROUP.AddJoint()
JOINT_FIXED.Name = "FIXED_JOINT"
JOINT_FIXED.ConnectionType = JointScopingType.BodyToGround
JOINT_FIXED.Type = JointType.Fixed
JOINT_FIXED.MobileLocation= NS_FACE_1
ANALYSIS_SETTINGS.Activate()
ANALYSIS_SETTINGS.AutomaticTimeStepping = AutomaticTimeStepping.Off
ANALYSIS_SETTINGS.TimeStep = Quantity("1e-2 [s]")
TRANSIENT_STRUCTURAL.Activate()
REMOTE_FORCE_BC = TRANSIENT_STRUCTURAL.AddRemoteForce()
REMOTE_FORCE_BC.Location = NS_FORCE_2
REMOTE_FORCE_BC.DefineBy = LoadDefineBy.Components
REMOTE_FORCE_BC.YComponent.Output.DiscreteValues = [Quantity("1e11 [dyne]")]
REMOTE_FORCE_BC.ZComponent.Output.DiscreteValues = [Quantity("1e11 [dyne]")]
DIRECTIONAL_DEFORMATION = TRANSIENT_STRUCTURAL_SOLUTION.AddDirectionalDeformation()
DIRECTIONAL_DEFORMATION.NormalOrientation = NormalOrientationType.ZAxis
JOINT_PROBE_RELATIVE_DISPLACEMENT = TRANSIENT_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_RELATIVE_DISPLACEMENT.BoundaryConditionSelection = JOINT_CYLINDRICAL
JOINT_PROBE_RELATIVE_DISPLACEMENT.ResultType = ProbeResultType.DeformationProbe
JOINT_PROBE_RELATIVE_DISPLACEMENT.ResultSelection = ProbeDisplayFilter.ZAxis
JOINT_PROBE_RELATIVE_VELOCITY = TRANSIENT_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_RELATIVE_VELOCITY.BoundaryConditionSelection = JOINT_CYLINDRICAL
JOINT_PROBE_RELATIVE_VELOCITY.ResultType = ProbeResultType.VelocityProbe
JOINT_PROBE_RELATIVE_VELOCITY.ResultSelection = ProbeDisplayFilter.ZAxis
JOINT_PROBE_RELATIVE_ACCELERATION = TRANSIENT_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_RELATIVE_ACCELERATION.BoundaryConditionSelection = JOINT_CYLINDRICAL
JOINT_PROBE_RELATIVE_ACCELERATION.ResultType = ProbeResultType.AccelerationProbe
JOINT_PROBE_RELATIVE_ACCELERATION.ResultSelection = ProbeDisplayFilter.ZAxis
JOINT_PROBE_RELATIVE_ROTATION = TRANSIENT_STRUCTURAL_SOLUTION.AddJointProbe()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
252 of ANSYS, Inc. and its subsidiaries and affiliates.
Symmetric Symmetry Analysis
JOINT_PROBE_RELATIVE_ROTATION.BoundaryConditionSelection = JOINT_CYLINDRICAL
JOINT_PROBE_RELATIVE_ROTATION.ResultType = ProbeResultType.RotationProbe
JOINT_PROBE_RELATIVE_ROTATION.ResultSelection = ProbeDisplayFilter.ZAxis
JOINT_PROBE_RELATIVE_ANGULAR_VELOCITY = TRANSIENT_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_RELATIVE_ANGULAR_VELOCITY.BoundaryConditionSelection = JOINT_CYLINDRICAL
JOINT_PROBE_RELATIVE_ANGULAR_VELOCITY.ResultType = ProbeResultType.AngularVelocityProbe
JOINT_PROBE_RELATIVE_ANGULAR_VELOCITY.ResultSelection = ProbeDisplayFilter.ZAxis
JOINT_PROBE_RELATIVE_ANGULAR_ACCELERATION = TRANSIENT_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_RELATIVE_ANGULAR_ACCELERATION.BoundaryConditionSelection = JOINT_CYLINDRICAL
JOINT_PROBE_RELATIVE_ANGULAR_ACCELERATION.ResultType = ProbeResultType.AngularAccelerationProbe
JOINT_PROBE_RELATIVE_ANGULAR_ACCELERATION.ResultSelection = ProbeDisplayFilter.ZAxis
JOINT_PROBE_TOTAL_FORCE = TRANSIENT_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_TOTAL_FORCE.BoundaryConditionSelection = JOINT_CYLINDRICAL
JOINT_PROBE_TOTAL_FORCE.ResultType = ProbeResultType.ForceReaction
JOINT_PROBE_TOTAL_FORCE.ResultSelection = ProbeDisplayFilter.YAxis
JOINT_PROBE_TOTAL_MOMENT = TRANSIENT_STRUCTURAL_SOLUTION.AddJointProbe()
JOINT_PROBE_TOTAL_MOMENT.BoundaryConditionSelection = JOINT_CYLINDRICAL
JOINT_PROBE_TOTAL_MOMENT.ResultType = ProbeResultType.MomentReaction
JOINT_PROBE_TOTAL_MOMENT.ResultSelection = ProbeDisplayFilter.YAxis
TRANSIENT_STRUCTURAL_SOLUTION.Solve(True)
JOINT_PROBE_RELATIVE_DISPLACEMENT_VAL = JOINT_PROBE_RELATIVE_DISPLACEMENT.ZAxis.Value
JOINT_PROBE_RELATIVE_VELOCITY_VAL = JOINT_PROBE_RELATIVE_VELOCITY.ZAxis.Value
JOINT_PROBE_RELATIVE_ACCELERATION_VAL = JOINT_PROBE_RELATIVE_ACCELERATION.ZAxis.Value
JOINT_PROBE_RELATIVE_ROTATION_VAL = JOINT_PROBE_RELATIVE_ROTATION.ZAxis.Value
JOINT_PROBE_RELATIVE_ANGULAR_VELOCITY_VAL = JOINT_PROBE_RELATIVE_ANGULAR_VELOCITY.ZAxis.Value
JOINT_PROBE_RELATIVE_ANGULAR_ACCELERATION_VAL = JOINT_PROBE_RELATIVE_ANGULAR_ACCELERATION.ZAxis.Value
JOINT_PROBE_TOTAL_FORCE_VAL = JOINT_PROBE_TOTAL_FORCE.YAxis.Value
JOINT_PROBE_TOTAL_MOMENT_VAL = JOINT_PROBE_TOTAL_MOMENT.YAxis.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following files.
• Symmetric_Symmetry.agdb
• Symmetric_Symmetry.xml
• Symmetric_Symmetry.py
Procedure
1. Open Workbench and insert a Static Structural system into the Project Schematic.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 253
End-to-End Analysis Examples
3. Select File > Import Engineering Data, navigate to the proper folder location and select Symmet-
ric_Symmetry.xml.
6. Enable the Named Selections check box under the Basic Geometry Options category.
7. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Symmetric_Symmetry.agdb.
9. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
10. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Symmetric_Symmetry.py.
11. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Scenario 1: Store main Tree Object items
MODEL = Model
GEOM = MODEL.Geometry
COORDINATE_SYSTEMS = Model.CoordinateSystems
MESH = Model.Mesh
PARTS = GEOM.GetChildren(DataModelObjectCategory.Part,False)
for part in PARTS:
bodies = part.GetChildren(DataModelObjectCategory.Body, False)
for body in bodies:
if body.Name == "Part 1":
PART1 = body
STAT_STRUC = DataModel.Project.Model.Analyses[0]
ANALYSIS_SETTINGS = STAT_STRUC.AnalysisSettings
STAT_STRUC_SOLUTION = STAT_STRUC.Solution
#Scenario 3: Insert Worksheet based Named Selections for applying Symmetric Symmetry and to setup Static Structural
# Create Named Selection for applying Symmetric Symmetry
FIRSTNS = DataModel.Project.Model.AddNamedSelection()
FIRSTNS.ScopingMethod=GeometryDefineByType.Worksheet
FIRSTNS.Name = "SELECTION2"
GEN_CRT1 = FIRSTNS.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.GeoFace
CRT1.Criterion=SelectionCriterionType.LocationY
CRT1.Operator=SelectionOperatorType.Equal
CRT1.Value=Quantity('0 [m]')
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
254 of ANSYS, Inc. and its subsidiaries and affiliates.
Symmetric Symmetry Analysis
GEN_CRT1.Add(CRT1)
FIRSTNS.Activate()
FIRSTNS.Generate()
# Add Pressure
PRESSURE = STAT_STRUC.AddPressure()
PRESSURE.Location = THIRDNS
PRESSURE.AppliedBy=LoadAppliedBy.SurfaceEffect
PRESSURE.Magnitude.Output.SetDiscreteValue(0,Quantity("-100 [Pa]"))
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 255
End-to-End Analysis Examples
NORMAL_STRESS = STAT_STRUC_SOLUTION.AddNormalStress()
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Linear_Periodic_Symmetry.agdb
• Linear_Periodic_Symmetry.py
Procedure
1. Open Workbench and insert a Static Structural system into the Project Schematic.
3. Enable the Named Selections check box under the Basic Geometry Options category.
4. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Linear_Periodic_Symmetry.agdb.
6. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
7. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Linear_Periodic_Symmetry.py.
8. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
256 of ANSYS, Inc. and its subsidiaries and affiliates.
Linear Periodic Symmetry Analysis
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Scenario 1: Store main Tree Object items
MODEL = Model
GEOM = MODEL.Geometry
COORDINATE_SYSTEMS = Model.CoordinateSystems
MESH = Model.Mesh
NAMED_SELECTIONS = Model.NamedSelections
PARTS = GEOM.GetChildren(DataModelObjectCategory.Part,False)
for part in PARTS:
bodies = part.GetChildren(DataModelObjectCategory.Body, False)
for body in bodies:
if body.Name == "Solid":
SOLID = body
STAT_STRUC = DataModel.Project.Model.Analyses[0]
ANALYSIS_SETTINGS = STAT_STRUC.AnalysisSettings
STAT_STRUC_SOLUTION = STAT_STRUC.Solution
#Scenario 3: Store Named Selections for applying Symmetry and to setup Static Structural analysis
tot_child_NS_GRP = NAMED_SELECTIONS.Children.Count
for i in range(0, tot_child_NS_GRP, 1):
ns = NAMED_SELECTIONS.Children[i].Name
if(ns=='Left_Face'):
LOW_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Right_Face'):
HIGH_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Base_Face'):
LOAD = NAMED_SELECTIONS.Children[i]
if(ns=='Top_Face'):
FIXED = NAMED_SELECTIONS.Children[i]
if(ns=='Front_Face'):
FRONT_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Back_Face'):
BACK_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Curved_Edges'):
CURVED_EDGES = NAMED_SELECTIONS.Children[i]
if(ns=='Straight_Edges'):
STRAIGHT_EDGES = NAMED_SELECTIONS.Children[i]
if(ns=='Short_Edges'):
SHORT_EDGES = NAMED_SELECTIONS.Children[i]
if(ns=='Mapping_Faces'):
MAPPING_FACES = NAMED_SELECTIONS.Children[i]
if(ns=='Vertex1'):
VERETX1 = NAMED_SELECTIONS.Children[i]
if(ns=='Vertex2'):
VERETX2 = NAMED_SELECTIONS.Children[i]
if(ns=='Vertex3'):
VERETX3 = NAMED_SELECTIONS.Children[i]
if(ns=='Vertex4'):
VERETX4 = NAMED_SELECTIONS.Children[i]
if(ns=='Vertex5'):
VERETX5 = NAMED_SELECTIONS.Children[i]
if(ns=='Vertex6'):
VERETX6 = NAMED_SELECTIONS.Children[i]
if(ns=='Vertex7'):
VERETX7 = NAMED_SELECTIONS.Children[i]
if(ns=='Vertex8'):
VERETX8 = NAMED_SELECTIONS.Children[i]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 257
End-to-End Analysis Examples
MESH_SIZE01 = MESH.AddSizing()
MESH_SIZE01.Location = CURVED_EDGES
MESH_SIZE01.Type = SizingType.NumberOfDivisions
MESH_SIZE01.NumberOfDivisions = 10
MESH_SIZE01.Behavior=SizingBehavior.Hard
MESH_SIZE02 = MESH_SIZE01.Duplicate()
MESH_SIZE02.Location = STRAIGHT_EDGES
MESH_SIZE02.NumberOfDivisions = 10
MESH_SIZE03 = MESH_SIZE02.Duplicate()
MESH_SIZE03.Location = SHORT_EDGES
MESH_SIZE03.NumberOfDivisions = 3
FACE_MESHING = MESH.AddFaceMeshing()
FACE_MESHING.Location = MAPPING_FACES
MESH.GenerateMesh()
# Add Pressure
PRESSURE = STAT_STRUC.AddPressure()
PRESSURE.Location = LOAD
PRESSURE.AppliedBy=LoadAppliedBy.SurfaceEffect
PRESSURE.DefineBy=LoadDefineBy.Components
PRESSURE.XComponent.Output.DiscreteValues = [Quantity("1e9 [dyne cm^-1 cm^-1]")]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
258 of ANSYS, Inc. and its subsidiaries and affiliates.
Cyclic Symmetry Analysis
FORCE_REACTION_PROBE.LocationMethod =LocationDefinitionMethod.BoundaryCondition
FORCE_REACTION_PROBE.BoundaryConditionSelection = FIXED_SUPPORT
#Deformation Result
TOTAL_DEF1_MIN = TOTAL_DEFORMATION1.Minimum.Value
TOTAL_DEF1_MAX = TOTAL_DEFORMATION1.Maximum.Value
TOTAL_DEF2_MIN = TOTAL_DEFORMATION2.Minimum.Value
TOTAL_DEF2_MAX = TOTAL_DEFORMATION2.Maximum.Value
TOTAL_DEF3_MIN = TOTAL_DEFORMATION3.Minimum.Value
TOTAL_DEF3_MAX = TOTAL_DEFORMATION3.Maximum.Value
TOTAL_DEF4_MIN = TOTAL_DEFORMATION4.Minimum.Value
TOTAL_DEF4_MAX = TOTAL_DEFORMATION4.Maximum.Value
TOTAL_DEF5_MIN = TOTAL_DEFORMATION5.Minimum.Value
TOTAL_DEF5_MAX = TOTAL_DEFORMATION5.Maximum.Value
FRC_REAC_PROBE_MAX_Y=FORCE_REACTION_PROBE.MaximumXAxis.Value
FRC_REAC_PROBE_TOTAL=FORCE_REACTION_PROBE.MaximumTotal.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Cyclic_Symmetry.agdb
• Cyclic_Symmetry.py
Procedure
1. Open Workbench and insert a Transient Thermal system into the Project Schematic.
2. Drag and drop an Static Structural system onto the Solution cell of the thermal analysis so that
the systems are linked as shown.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 259
End-to-End Analysis Examples
3. Right-click the Geometry cell of the thermal system and select Properties.
4. Enable the Named Selections check box under the Basic Geometry Options category.
5. Right-click the Geometry cell of the thermal system and select Import Geometry > Browse and
then navigate to the proper folder location and select Cyclic_Symmetry.agdb.
7. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
8. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Cyclic_Symmetry.py.
9. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Scenario 1: Store main Tree Object items
MODEL = Model
GEOM = MODEL.Geometry
COORDINATE_SYSTEMS = Model.CoordinateSystems
MESH = Model.Mesh
NAMED_SELECTIONS = Model.NamedSelections
PARTS = GEOM.GetChildren(DataModelObjectCategory.Part,False)
for part in PARTS:
bodies = part.GetChildren(DataModelObjectCategory.Body, False)
for body in bodies:
if body.Name == "Solid":
SOLID_BODY = body
if body.Name == "SurfaceBody":
SHELL_BODY = body
TRANS_THERM = DataModel.Project.Model.Analyses[0]
ANALYSIS_SETTINGS1 = TRANS_THERM.AnalysisSettings
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
260 of ANSYS, Inc. and its subsidiaries and affiliates.
Cyclic Symmetry Analysis
TRANS_THERM_SOLUTION = TRANS_THERM.Solution
STAT_STRUC = DataModel.Project.Model.Analyses[1]
ANALYSIS_SETTINGS2 = STAT_STRUC.AnalysisSettings
STAT_STRUC_SOLUTION = STAT_STRUC.Solution
#Scenario 4: Store Named Selections for applying Symmetry and to setup Thermal Stress analysis
tot_child_NS_GRP = NAMED_SELECTIONS.Children.Count
for i in range(0, tot_child_NS_GRP, 1):
ns = NAMED_SELECTIONS.Children[i].Name
if(ns=='Low_Face'):
LOW_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='High_Face'):
HIGH_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Pressure_Face'):
LOAD_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Fixed_Face'):
FIXED_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Front_Face'):
FRONT_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Back_Face'):
BACK_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Edges1'):
EDGES1 = NAMED_SELECTIONS.Children[i]
if(ns=='Edges2'):
EDGES2 = NAMED_SELECTIONS.Children[i]
if(ns=='Edges3'):
EDGES3 = NAMED_SELECTIONS.Children[i]
if(ns=='Low_Edge'):
LOW_EDGE = NAMED_SELECTIONS.Children[i]
if(ns=='High_Edge'):
HIGH_EDGE = NAMED_SELECTIONS.Children[i]
if(ns=='Shell_Face'):
SHELL_FACE = NAMED_SELECTIONS.Children[i]
if(ns=='Solid_Body'):
SOLID_BODY = NAMED_SELECTIONS.Children[i]
if(ns=='Shell_Body'):
SHELL_BODY = NAMED_SELECTIONS.Children[i]
FACE_MESHING = MESH.AddFaceMeshing()
FACE_MESHING.Location = SHELL_FACE
FACE_MESHING.Suppressed=True
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 261
End-to-End Analysis Examples
MESH_SIZE01 = MESH.AddSizing()
MESH_SIZE01.Location = EDGES1
MESH_SIZE01.Type = SizingType.NumberOfDivisions
MESH_SIZE01.NumberOfDivisions = 9
MESH_SIZE01.Behavior=SizingBehavior.Hard
MESH_SIZE01.Suppressed=True
MATCH_CONTROL01=MESH.AddMatchControl()
MATCH_CONTROL01.LowGeometrySelection=LOW_FACE
MATCH_CONTROL01.HighGeometrySelection=HIGH_FACE
MATCH_CONTROL01.HighCoordinateSystem=COORDINATE_SYSTEM
MATCH_CONTROL01.Suppressed=True
MATCH_CONTROL02=MESH.AddMatchControl()
MATCH_CONTROL02.LowGeometrySelection=LOW_EDGE
MATCH_CONTROL02.HighGeometrySelection=HIGH_EDGE
MATCH_CONTROL02.HighCoordinateSystem=COORDINATE_SYSTEM
MATCH_CONTROL02.Suppressed=True
MESH.GenerateMesh()
TEMPERATURE01 = TRANS_THERM.AddTemperature()
TEMPERATURE01.Location = FIXED_FACE
TEMPERATURE01.Magnitude.Output.DiscreteValues=[Quantity('5[C]')]
TEMPERATURE02 = TRANS_THERM.AddTemperature()
TEMPERATURE02.Location = SHELL_FACE
TEMPERATURE02.Magnitude.Output.DiscreteValues=[Quantity('30[C]')]
IMPORTED_BODY_TEMP01=IMPORTED_LOAD_GRP.Children[0]
IMPORTED_BODY_TEMP01.Location=SOLID_BODY
IMPORTED_BODY_TEMP02=IMPORTED_LOAD_GRP.AddImportedBodyTemperature()
IMPORTED_BODY_TEMP02.Location=SHELL_BODY
# Add Pressure
PRESSURE = STAT_STRUC.AddPressure()
PRESSURE.Location = LOAD_FACE
PRESSURE.AppliedBy=LoadAppliedBy.SurfaceEffect
PRESSURE.DefineBy=LoadDefineBy.Components
PRESSURE.XComponent.Output.DiscreteValues = [Quantity("2 [MPa]")]
TEMPERATURE01_RST = TRANS_THERM_SOLUTION.AddTemperature()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
262 of ANSYS, Inc. and its subsidiaries and affiliates.
Cyclic Symmetry Analysis
TRANS_THERM_SOLUTION.Activate()
TRANS_THERM_SOLUTION.Solve(True)
#Temperature Result
TEMPERATURE_RST_MIN = TEMPERATURE01_RST.Minimum.Value
TEMPERATURE_RST_MAX = TEMPERATURE01_RST.Maximum.Value
STAT_STRUC_SOLUTION.Activate()
STAT_STRUC_SOLUTION.Solve(True)
#Deformation Result
TOTAL_DEF_MIN = TOTAL_DEFORMATION.Minimum.Value
TOTAL_DEF_MAX = TOTAL_DEFORMATION.Maximum.Value
#Scenario 13: Suppress Cyclic Symmetry and insert Pre-Meshed Cyclic Region using local Coordinate System
SYMMETRY_REGION1.Suppressed=True
SYMMETRY_REGION2=SYMMETRY.AddPreMeshedCyclicRegion()
SYMMETRY_REGION2.CoordinateSystem=COORDINATE_SYSTEM
# Select Low and High Boundary with proper Coordinate System
SYMMETRY_REGION2.LowBoundaryLocation=LOW_FACE
SYMMETRY_REGION2.HighBoundaryLocation=HIGH_FACE
SYMMETRY_REGION2.NumberOfSectors=4
#Scenario 14: Activate few mesh controls to get mapping mesh and generate mesh
MESH.Activate()
#Activate few mesh controls to get mapped meshed on low and high faces
FACE_MESHING.Suppressed=False
MESH_SIZE01.Suppressed=False
MATCH_CONTROL01.Suppressed=False
MATCH_CONTROL02.Suppressed=False
MESH.GenerateMesh()
#Scenario 15: Solve and review Results using Pre-Meshed Cyclic Region
TRANS_THERM_SOLUTION.Activate()
TRANS_THERM_SOLUTION.Solve(True)
#Temperature Result
TEMPERATURE2_RST_MIN = TEMPERATURE01_RST.Minimum.Value
TEMPERATURE2_RST_MAX = TEMPERATURE01_RST.Maximum.Value
STAT_STRUC_SOLUTION.Activate()
STAT_STRUC_SOLUTION.Solve(True)
#Deformation Result
TOTAL_DEF2_MIN = TOTAL_DEFORMATION.Minimum.Value
TOTAL_DEF2_MAX = TOTAL_DEFORMATION.Maximum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 263
End-to-End Analysis Examples
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_Steady_State_Thermal_Example_001.agdb
• Mechanical_Steady_State_Thermal_Example_001.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Steady-State
Thermal system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanic-
al_Steady_State_Thermal_Example_001.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_Steady_State_Thermal_Ex-
ample_001.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario1 - Set up Unit System: Set up the Unit Systems to Metric (mm, kg, N, s, mV, mA),
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardNMM
# Scenario 2 - Set up the Tree Object Items: Define the parts, connections, mesh, Steady-State Thermal system, the a
PART1 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Part 1'][0]
PART2 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Part 2'][0]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
264 of ANSYS, Inc. and its subsidiaries and affiliates.
Steady-State Thermal Analysis
# Scenario 3 - Define Named Selections: Define the Named selections that will be used to define the Mesh Controls, t
NS_CONVECTION_FACE = DataModel.GetObjectsByName("NS_convection_face")[0]
NS_HG = DataModel.GetObjectsByName("NS_heat_generation")[0]
NS_RESULTS = DataModel.GetObjectsByName("NS_results")[0]
NS_ALL_BODIES = DataModel.GetObjectsByName("NS_all_bodies")[0]
# Scenario 4 - Define Mesh Settings: Set the mesh resolution to 3. Define mesh control with sweep method, mesh algor
MESH.Resolution = 3
MESH_METHOD = MESH.AddAutomaticMethod()
MESH_METHOD.Location = NS_ALL_BODIES
MESH_METHOD.Method = MethodType.Sweep
MESH_METHOD.Algorithm = MeshMethodAlgorithm.Axisymmetric
MESH_METHOD.MeshInCenter = 0
MESH_METHOD.SweepNumberDivisions = 24
MESH.GenerateMesh()
# Scenario 5 - Define Analysis Settings: Set the auto time stepping to on. Set the initial, minimum and maximum sub-
ANSLYSIS_SETTINGS.SetAutomaticTimeStepping(1, AutomaticTimeStepping.On)
ANSLYSIS_SETTINGS.DefineBy = TimeStepDefineByType.Substeps
ANSLYSIS_SETTINGS.InitialSubsteps = 20
ANSLYSIS_SETTINGS.MinimumSubsteps= 15
ANSLYSIS_SETTINGS.MaximumSubsteps = 50
# Scenario 6 - Insert Thermal loads: Insert and define Convection and Internal Heat Generation loads
CONVECTION = STEADY_STATE_THERMAL.AddConvection()
CONVECTION.Location = NS_CONVECTION_FACE
CONVECTION.FilmCoefficient.Output.DiscreteValues=[Quantity('3.2e-4[W mm^-1 mm^-1 C^-1]'), Quantity('1.04e-4[W mm^-1
CONVECTION.AmbientTemperature.Output.DiscreteValues=[Quantity('50 [C]'), Quantity('200 [C]')]
INTERNAL_HEAT_GENERATION = STEADY_STATE_THERMAL.AddInternalHeatGeneration()
INTERNAL_HEAT_GENERATION.Location = NS_ALL_BODIES
INTERNAL_HEAT_GENERATION.Magnitude.Output.SetDiscreteValue(0, Quantity(0.001592, "W mm^-1 mm^-1 mm^-1"))
# Scenario 7 - Insert Results: Insert a Temperature, Total Heat Flux and Reaction Probe results.
TEMPERATURE01 = SOLUTION.AddTemperature()
TEMPERATURE01.Location = NS_CONVECTION_FACE
TOTAL_HEAT_FLUX01 = SOLUTION.AddTotalHeatFlux()
TOTAL_HEAT_FLUX01.Location = NS_CONVECTION_FACE
TEMPERATURE02 = SOLUTION.AddTemperature()
TEMPERATURE02.Location = NS_RESULTS
TOTAL_HEAT_FLUX02 = SOLUTION.AddTotalHeatFlux()
TOTAL_HEAT_FLUX02.Location = NS_RESULTS
REACTION_PROBE = SOLUTION.AddReactionProbe()
REACTION_PROBE.BoundaryConditionSelection = CONVECTION
# Scenario 8 - Solve and Define the Results: Solve the system and set the results variables. Note the Scripting wind
SOLUTION.Solve(True)
TEMPERATURE01_MAX = TEMPERATURE01.Maximum.Value
TEMPERATURE02_MAX = TEMPERATURE02.Maximum.Value
TOTAL_HEAT_FLUX01_MAX = TOTAL_HEAT_FLUX01.Maximum.Value
TOTAL_HEAT_FLUX02_MAX = TOTAL_HEAT_FLUX02.Maximum.Value
REACTION_PROBE = REACTION_PROBE.Heat.Value
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 265
End-to-End Analysis Examples
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_Transient_Thermal_Example_001.agdb
• Mechanical_Transient_Thermal_Example_001.xml
• Mechanical_Transient_Thermal_Example_001.py
Procedure
1. Open Workbench and insert a Transient Thermal system into the Project Schematic.
3. Select File > Import Engineering Data, navigate to the proper folder location and select Mechan-
ical_Transient_Thermal_Example_001.xml.
5. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Mechanical_Transient_Thermal_Example_001.agdb.
7. Set the Analysis Type property to 2D. This property is contained in the Advanced Geometry
Options group.
9. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
10. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_Transient_Thermal_Example_001.py.
11. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
266 of ANSYS, Inc. and its subsidiaries and affiliates.
Transient Thermal Analysis
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario1 - Set up Unit System: Set up the Unit Systems to Metric (m, kg, N, s, V, A),
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
# Scenario 2 - Set up the Tree Object Items: Define the parts, connections, mesh, Transient Thermal system, the anal
GEOMETRY = Model.Geometry
PART1 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Surface Body 1'][0]
PART2 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Surface Body 2'][0]
MESH = Model.Mesh
TRANSIENT_THERMAL = DataModel.AnalysisByName("Transient Thermal")
ANSLYSIS_SETTINGS = TRANSIENT_THERMAL.AnalysisSettings
SOLUTION = TRANSIENT_THERMAL.Solution
# Scenario 3 - Define Named Selections: Define the Named selections that will be used to define the Mesh Controls, t
NS_BODY1 = DataModel.GetObjectsByName("Body1")[0]
NS_BODY2 = DataModel.GetObjectsByName("Body2")[0]
NS_EDGES2 = DataModel.GetObjectsByName("Edges2")[0]
NS_EDGE1 = DataModel.GetObjectsByName("Edge1")[0]
NS_EDGE2 = DataModel.GetObjectsByName("Edge2")[0]
# Scenario 4 Assign materials and define 2D behaviour: Assign materials to bodies. Define 2D behaviour as plane stre
GEOMETRY.Model2DBehavior = Model2DBehavior.PlaneStress
PART1.Material = 'Mechanical_Transient_Thermal_Example_001'
PART2.Material = 'Mechanical_Transient_Thermal_Example_001'
PART1.Thickness = Quantity('0.1 [m]')
PART2.Thickness = Quantity('0.1 [m]')
# Scenario 5 - Define Mesh Settings: Assign global mesh element size of 0.1 m. Assign mesh methods Quadrilateral Dom
# Scenario 6 - Define Analysis Settings: Set the auto time stepping to off with time step of 7 s. Set step end time
# Scenario 7 - Insert Thermal loads: Define Initial Temperature. Insert and define Temperature, Convection and Inter
INITIAL_TEMPERATURE = TRANSIENT_THERMAL.Children[0]
INITIAL_TEMPERATURE.InitialTemperatureValue = Quantity('50 [C]')
TEMPERATURE = TRANSIENT_THERMAL.AddTemperature()
TEMPERATURE.Location = NS_EDGES2
INITIAL_TEMPERATURE.InitialTemperatureValue = Quantity('50 [C]')
CONVECTION = TRANSIENT_THERMAL.AddConvection()
CONVECTION.Location = NS_EDGE1
CONVECTION.FilmCoefficient.Output.DiscreteValues=[Quantity('10 [W m^-1 m^-1 C^-1]'), Quantity('10 [W m^-1 m^-1 C^-1]
CONVECTION.AmbientTemperature.Output.DiscreteValues=[Quantity('20 [C]'), Quantity('20 [C]')]
INTERNAL_HEAT_GENERATION = TRANSIENT_THERMAL.AddInternalHeatGeneration()
INTERNAL_HEAT_GENERATION.Location = NS_BODY2
INTERNAL_HEAT_GENERATION.Magnitude.Inputs[0].DiscreteValues = [Quantity("0 [s]"), Quantity("10 [s]"), Quantity("30 [
INTERNAL_HEAT_GENERATION.Magnitude.Output.DiscreteValues = [Quantity(10000, "W m^-1 m^-1 m^-1"), Quantity(12000, "W
HEAT_FLUX = TRANSIENT_THERMAL.AddHeatFlux()
HEAT_FLUX.Location = NS_EDGE2
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 267
End-to-End Analysis Examples
TEMPERATURE01 = SOLUTION.AddTemperature()
TEMPERATURE01.Location = NS_EDGE2
TEMPERATURE01.DisplayTime = Quantity('200[s]')
TEMPERATURE02 = SOLUTION.AddTemperature()
TEMPERATURE02.Location = NS_EDGE2
# Scenario 9 - Solve and Define the Results: Solve the system and set the results variables. Note the Scripting wind
SOLUTION.Solve(True)
TEMPERATURE01_MAX = TEMPERATURE01.Maximum.Value
TEMPERATURE02_MAX = TEMPERATURE02.Maximum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Coupled_Field_Static_Example.agdb
• Coupled_Field_Static_Example.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Coupled Field
Static system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select
Coupled_Field_Static_Example.agdb.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
268 of ANSYS, Inc. and its subsidiaries and affiliates.
Coupled Field Static Analysis
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Coupled_Field_Static_Example.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Set up the Tree Object Items
GEOMETRY = Model.Geometry
COORDINATE_SYSTEM = Model.CoordinateSystems
CONNECTIONS = Model.Connections
MESH = Model.Mesh
COUPLED_FIELD_STATIC = ExtAPI.DataModel.AnalysisByName("Coupled Field Static")
ANALYSIS_SETTINGS = COUPLED_FIELD_STATIC.AnalysisSettings
SOLUTION = COUPLED_FIELD_STATIC.Solution
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 269
End-to-End Analysis Examples
REMOTE_DISPLACEMENT = COUPLED_FIELD_STATIC.AddRemoteDisplacement()
REMOTE_DISPLACEMENT.Location = NS_FIXED_RIGID
REMOTE_DISPLACEMENT.XComponent.Output.DiscreteValues = [Quantity("0 [mm]")]
REMOTE_DISPLACEMENT.YComponent.Output.DiscreteValues = [Quantity("0 [mm]")]
REMOTE_DISPLACEMENT.ZComponent.Output.DiscreteValues = [Quantity("0 [mm]")]
REMOTE_DISPLACEMENT.RotationX.Output.DiscreteValues = [Quantity("0 [deg]")]
REMOTE_DISPLACEMENT.RotationY.Output.DiscreteValues = [Quantity("0 [deg]")]
REMOTE_DISPLACEMENT.RotationZ.Output.DiscreteValues = [Quantity("0 [deg]")]
TEMPERATURE = COUPLED_FIELD_STATIC.AddTemperature()
TEMPERATURE.Location = NS_ROD_BODY
TEMPERATURE.Magnitude.Output.DiscreteValues = [Quantity('122 [C]')]
NORMAL_STRESS = SOLUTION.AddNormalStress()
NORMAL_STRESS.Location = CONST_SURF
NORMAL_STRESS.NormalOrientation = NormalOrientationType.ZAxis
THERMAL_STRAIN = SOLUTION.AddThermalStrain()
THERMAL_STRAIN.NormalOrientation=NormalOrientationType.ZAxis
THERMAL_STRAIN.Location = NS_ROD_BODY
MAXIMUM_DIRECTIONAL_DEFORMATION = DIRECTIONAL_DEFORMATION.Maximum.Value
MINIMUM_DIRECTIONAL_DEFORMATION = DIRECTIONAL_DEFORMATION.Minimum.Value
MAXIMUM_NORMAL_STRESS = NORMAL_STRESS.Maximum.Value
MAXIMUM_THERMAL_STRAIN = THERMAL_STRAIN.Maximum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
270 of ANSYS, Inc. and its subsidiaries and affiliates.
Coupled Field Harmonic Analysis
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Coupled_Field_Harmonic_Example.agdb
• Coupled_Field_Harmonic_Example.py
• Coupled_Field_Harmonic_Example_PZT.xml
• Coupled_Field_Harmonic_Example_Substrate.xml
Procedure
1. Open Workbench and insert a Coupled Field Harmonic system into the Project Schematic.
3. Select File > Import Engineering Data, navigate to the proper folder location and select
Coupled_Field_Harmonic_Example_PZT.xml. Repeat this for Coupled_Field_Harmon-
ic_Example_Substrate.xml.
5. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Coupled_Field_Harmonic_Example.agdb.
7. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
8. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Coupled_Field_Harmonic_Example.py.
9. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Set up the Tree Object Items
GEOMETRY = Model.Geometry
COORDINATE_SYSTEM = Model.CoordinateSystems
CONNECTIONS = Model.Connections
MESH = Model.Mesh
COUPLED_FIELD_HARMONIC = ExtAPI.DataModel.AnalysisByName("Coupled Field Harmonic")
ANALYSIS_SETTINGS = COUPLED_FIELD_HARMONIC.AnalysisSettings
SOLUTION = COUPLED_FIELD_HARMONIC.Solution
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 271
End-to-End Analysis Examples
PIEZO = GEOMETRY.Children[1].Children[0]
SUBSTRATE.Assignment='substrate_mat'
PIEZO.Assignment='PZT-5A'
VOLTAGE_COUPLING = COUPLED_FIELD_HARMONIC.AddVoltageCoupling()
VOLTAGE_COUPLING.Location = PIEZO_TOP
VOLTAGE_GROUND = COUPLED_FIELD_HARMONIC.AddVoltageGround()
VOLTAGE_GROUND.Location = PIEZO_BOTTOM
VOLTAGE = COUPLED_FIELD_HARMONIC.AddVoltage()
VOLTAGE.Location = VOLTAGE_COUPLING
VOLTAGE.Magnitude.Output.DiscreteValues = [Quantity('1 [V]')]
FREQUENCY_RESPONSE_VOLTAGE = SOLUTION.AddVoltageFrequencyResponse()
FREQUENCY_RESPONSE_VOLTAGE.Location = PIEZO_TOP
FREQUENCY_RESPONSE_CHARGE_REACTION = SOLUTION.AddChargeReactionFrequencyResponse()
FREQUENCY_RESPONSE_CHARGE_REACTION.BoundaryCondition = VOLTAGE
FREQUENCY_RESPONSE_IMPEDANCE = SOLUTION.AddImpedanceFrequencyResponse()
FREQUENCY_RESPONSE_IMPEDANCE.BoundaryCondition = VOLTAGE
FREQUENCY_RESPONSE_VOLTAGE.MaximumAmplitude.Value
FREQUENCY_RESPONSE_VOLTAGE.FrequencyAtMaximumAmplitude.Value
FREQUENCY_RESPONSE_VOLTAGE.PhaseAngle.Value
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
272 of ANSYS, Inc. and its subsidiaries and affiliates.
Coupled Field Transient Analysis
FREQUENCY_RESPONSE_VOLTAGE.RealAtMaximumAmplitude.Value
FREQUENCY_RESPONSE_VOLTAGE.ImaginaryAtMaximumAmplitude.Value
FREQUENCY_RESPONSE_CHARGE_REACTION.MaximumAmplitude.Value
FREQUENCY_RESPONSE_CHARGE_REACTION.FrequencyAtMaximumAmplitude.Value
FREQUENCY_RESPONSE_CHARGE_REACTION.PhaseAngle.Value
FREQUENCY_RESPONSE_CHARGE_REACTION.RealAtMaximumAmplitude.Value
FREQUENCY_RESPONSE_CHARGE_REACTION.ImaginaryAtMaximumAmplitude.Value
FREQUENCY_RESPONSE_IMPEDANCE.MaximumAmplitude.Value
FREQUENCY_RESPONSE_IMPEDANCE.FrequencyAtMaximumAmplitude.Value
FREQUENCY_RESPONSE_IMPEDANCE.PhaseAngle.Value
FREQUENCY_RESPONSE_IMPEDANCE.RealAtMaximumAmplitude.Value
FREQUENCY_RESPONSE_IMPEDANCE.ImaginaryAtMaximumAmplitude.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Coupled_Field_Transient_Example.agdb
• Coupled_Field_Transient_Example.py
• Coupled_Field_Transient_Example_Mat.xml
Procedure
1. Open Workbench and insert a Coupled Field Transient system into the Project Schematic.
3. Select File > Import Engineering Data, navigate to the proper folder location and select
Coupled_Field_Transient_Example_Mat.xml.
5. Set the Analysis Type property to 2D under the Advanced Geometry Options category.
6. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Coupled_Field_Transient_Example.agdb.
8. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 273
End-to-End Analysis Examples
9. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Coupled_Field_Transient_Example.py.
10. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Set up the Tree Object Items
GEOMETRY = Model.Geometry
COORDINATE_SYSTEM = Model.CoordinateSystems
CONNECTIONS = Model.Connections
MESH = Model.Mesh
COUPLED_FIELD_TRANSIENT = ExtAPI.DataModel.AnalysisByName("Coupled Field Transient")
ANALYSIS_SETTINGS = COUPLED_FIELD_TRANSIENT.AnalysisSettings
SOLUTION = COUPLED_FIELD_TRANSIENT.Solution
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
274 of ANSYS, Inc. and its subsidiaries and affiliates.
Coupled Field Modal Analysis
ANALYSIS_SETTINGS.MinimumSubsteps=5
ANALYSIS_SETTINGS.MaximumSubsteps=100
ANALYSIS_SETTINGS.StepEndTime=Quantity('130[s]')
ANALYSIS_SETTINGS.HeatConvergence=ConvergenceToleranceType.On
ANALYSIS_SETTINGS.HeatConvergenceValue=Quantity('0.01[W]')
ANALYSIS_SETTINGS.HeatConvergenceTolerance=1
ANALYSIS_SETTINGS.StructuralOnly=False
DISPLACEMENT2 = COUPLED_FIELD_TRANSIENT.AddDisplacement()
DISPLACEMENT2.Location = HORZ_EDGE2_NS
DISPLACEMENT2.YComponent.Output.DiscreteValues = [Quantity('0 [m]')]
DISPLACEMENT3 = COUPLED_FIELD_TRANSIENT.AddDisplacement()
DISPLACEMENT3.Location = VERT_EDGE1_NS.Location
DISPLACEMENT3.XComponent.Output.DiscreteValues = [Quantity('0.13 [m]')]
DISPLACEMENT3.YComponent.Output.DiscreteValues = [Quantity('0 [m]')]
PLASTIC_HEATING = COUPLED_FIELD_TRANSIENT.AddPlasticHeating()
PLASTIC_HEATING.Location = BODY_NS
PLASTIC_HEATING.PlasticWorkFraction = 0.9
COMMAND_SNIPPET = COUPLED_FIELD_TRANSIENT.AddCommandSnippet()
Cmds_1= "AUTOTS,OFF\nKBC,0\nTINTP,,,,1.0\nOUTRES,ALL,ALL"
COMMAND_SNIPPET.AppendText(Cmds_1)
MAXIMUM_TEMPERATURE = TEMPERATURE.Maximum.Value
MINIMUM_TEMPERATURE = TEMPERATURE.Minimum.Value
MAXIMUM_EQUIVALENT_PLASTIC_STRAIN = EQUIVALENT_PLASTIC_STRAIN.Maximum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Coupled_Field_Modal_Example.agdb
• Coupled_Field_Modal_Example.py
• Coupled_Field_Modal_Example_Mat1.xml
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 275
End-to-End Analysis Examples
Procedure
1. Open Workbench and insert a Coupled Field Modal system into the Project Schematic.
3. Select File > Import Engineering Data, navigate to the proper folder location and select
Coupled_Field_Modal_Example_Mat1.xml.
5. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Coupled_Field_Modal_Example.agdb.
7. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
8. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Coupled_Field_Modal_Example.py.
9. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Set up the Tree Object Items
GEOMETRY = Model.Geometry
COORDINATE_SYSTEM = Model.CoordinateSystems
CONNECTIONS = Model.Connections
MESH = Model.Mesh
COUPLED_FIELD_MODAL = ExtAPI.DataModel.AnalysisByName("Coupled Field Modal")
ANALYSIS_SETTINGS = COUPLED_FIELD_MODAL.AnalysisSettings
SOLUTION = COUPLED_FIELD_MODAL.Solution
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
276 of ANSYS, Inc. and its subsidiaries and affiliates.
Fracture Analysis: Semi-Elliptical Crack
TOTAL_DEFORMATION1.ReportedFrequency.Value
TOTAL_DEFORMATION2.ReportedFrequency.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Semi-Elliptical_Crack_Example_003.agdb
• Semi-Elliptical_Crack_Example_003.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 277
End-to-End Analysis Examples
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Static Struc-
tural system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Semi-Elliptic-
al_Crack_Example_003.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Semi-Elliptical_Crack_Example_003.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Store main Tree Object items
MODEL = Model
GEOMETRY = Model.Geometry
SOLID2 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Solid2'][0]
COORDINATE_SYSTEMS = Model.CoordinateSystems
GLOBAL_COORDINATE_SYSTEM = [i for i in COORDINATE_SYSTEMS.GetChildren[Ansys.ACT.Automation.Mechanical.CoordinateSyst
MESH = Model.Mesh
NAMED_SELECTIONS = ExtAPI.DataModel.Project.Model.NamedSelections
NS_PIPE_BODY = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.N
NS_FILET_FACE = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.
NS_VERTEX_FILET = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_PRESSURE_FACE = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
COORDINATE_SYSTEM.AddTransformation(TransformationType.Rotation, CoordinateSystemAxisType.PositiveZAxis)
COORDINATE_SYSTEM.SetTransformationValue(1, 22.2922)
COORDINATE_SYSTEM.AddTransformation(TransformationType.Rotation, CoordinateSystemAxisType.PositiveYAxis)
COORDINATE_SYSTEM.SetTransformationValue(2, 180)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
278 of ANSYS, Inc. and its subsidiaries and affiliates.
Fracture Analysis: Semi-Elliptical Crack
METHOD_MESH = MESH.AddAutomaticMethod()
METHOD_MESH.Location = NS_PIPE_BODY
METHOD_MESH.Method=MethodType.AllTriAllTet
SIZING_MESH = MESH.AddSizing()
SIZING_MESH.Location = NS_FILET_FACE
SIZING_MESH.ElementSize = Quantity('5 [mm]')
MESH.Activate()
MESH.GenerateMesh()
SEMI_ELLIPTICAL_CRACK = FRACTURE.AddSemiEllipticalCrack()
SEL=ExtAPI.SelectionManager.AddSelection(NS_PIPE_BODY)
SEL2=ExtAPI.SelectionManager.CurrentSelection
SEMI_ELLIPTICAL_CRACK.Location=SEL2
ExtAPI.SelectionManager.ClearSelection()
SEMI_ELLIPTICAL_CRACK.CoordinateSystem=COORDINATE_SYSTEM
SEMI_ELLIPTICAL_CRACK.MajorRadius = Quantity("18.4 [mm]")
SEMI_ELLIPTICAL_CRACK.MinorRadius = Quantity("9.5 [mm]")
SEMI_ELLIPTICAL_CRACK.LargestContourRadius= Quantity("2 [mm]")
SEMI_ELLIPTICAL_CRACK.CrackFrontDivisions = 35
SEMI_ELLIPTICAL_CRACK.CircumferentialDivisions = 18
SEMI_ELLIPTICAL_CRACK.CrackFacesNodes = True
SEMI_ELLIPTICAL_CRACK.ContactPairsNodes= True
FRACTURE.GenerateAllCrackMesh()
FRACTURE_TOOL = SOLUTION.AddFractureTool()
FRACTURE_TOOL.CrackSelection = SEMI_ELLIPTICAL_CRACK
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 279
End-to-End Analysis Examples
TOTAL_DEFORMATION.Activate()
MAX_TOTAL_DEFORMATION = TOTAL_DEFORMATION.Maximum.Value
SIFS_K1.Activate()
MIN_SIFS_K1_C6 = SIFS_K1.Minimum.Value
MAX_SIFS_K1_C6 = SIFS_K1.Maximum.Value
SIFS_K2.Activate()
MIN_SIFS_K2_C6 = SIFS_K2.Minimum.Value
MAX_SIFS_K2_C6 = SIFS_K2.Maximum.Value
SIFS_K3.Activate()
MIN_SIFS_K3_C6 = SIFS_K3.Minimum.Value
MAX_SIFS_K3_C6 = SIFS_K3.Maximum.Value
J_INTEGRAL.Activate()
MIN_J_INTEGRAL_C6 = J_INTEGRAL.Minimum.Value
MAX_J_INTEGRAL_C6 = J_INTEGRAL.Maximum.Value
MATERIAL_FORCE_X.Activate()
MIN_MATERIAL_FORCE_X_C6 = MATERIAL_FORCE_X.Minimum.Value
MAX_MATERIAL_FORCE_X_C6 = MATERIAL_FORCE_X.Maximum.Value
MATERIAL_FORCE_Y.Activate()
MIN_MATERIAL_FORCE_Y_C6 = MATERIAL_FORCE_Y.Minimum.Value
MAX_MATERIAL_FORCE_Y_C6 = MATERIAL_FORCE_Y.Maximum.Value
MATERIAL_FORCE_Z.Activate()
MIN_MATERIAL_FORCE_Z_C6 = MATERIAL_FORCE_Z.Minimum.Value
MAX_MATERIAL_FORCE_Z_C6 = MATERIAL_FORCE_Z.Maximum.Value
T_STRESS.Activate()
MIN_T_STRESS_C6 = T_STRESS.Minimum.Value
MAX_T_STRESS_C6 = T_STRESS.Maximum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following files.
Procedure
1. Open Workbench and insert a External Model system from the Component System category of
the Toolbox and place it in the Project Schematic.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
280 of ANSYS, Inc. and its subsidiaries and affiliates.
Fracture Analysis: SMART Crack Growth
3. Select the option in the Location column to open a dialog. Navigate to the proper folder location
and select SMART Crack Growth_Example_033.cdb.
5. Return to the Project tab and insert a Static Structural system into the Project Schematic.
7. Select File > Import Engineering Data, navigate to the proper folder location and select SMART
Crack Growth_Example_033.xml.
8. Return to the Project tab. Link the Setup cell of the External Model system to the Model cell of
the static analysis.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 281
End-to-End Analysis Examples
9. Select the Model cell of the static system and display the properties. Set the following properties:
• Unit Length = mm
10. Right-click the Model cell and first select Update Upstream Components option and then select
Refresh option.
11. Open Mechanical. Right-click the Model cell and select Edit.
12. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
13. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select SMART Crack Growth_Example_033.py.
14. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
282 of ANSYS, Inc. and its subsidiaries and affiliates.
Fracture Analysis: SMART Crack Growth
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Store main Tree Object items
MODEL = Model
GEOMETRY = Model.Geometry
BODY = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Solid Body 1(A2)'][0]
MAT_GRP = MODEL.Materials
MAT_BODY = [i for i in MAT_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) if i.Name == 'MAT1'][0]
COORDINATE_SYSTEMS = Model.CoordinateSystems
GLOBAL_COORDINATE_SYSTEM = [i for i in COORDINATE_SYSTEMS.GetChildren[Ansys.ACT.Automation.Mechanical.CoordinateSyst
MESH = Model.Mesh
NAMED_SELECTIONS = ExtAPI.DataModel.Project.Model.NamedSelections
NS_CRACK = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.Name
NS_CRACK_SUR01 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i
NS_CRACK_SUR02 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i
NS_LOAD01 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.Name
NS_LOAD02 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.Name
NS_SUPPORT01 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.N
NS_SUPPORT02 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.N
NS_CRACK_SUR01.Activate()
NS_CRACK_SUR01.ReadOnly = False
NS_CRACK_SUR01.Name= "Crack_TF_Nodes"
NS_CRACK_SUR02.Activate()
NS_CRACK_SUR02.ReadOnly = False
NS_CRACK_SUR02.Name= "Crack_BF_Nodes"
NS_LOAD01.Activate()
NS_LOAD01.ReadOnly = False
NS_LOAD01.Name= "Load_Nodes"
NS_LOAD02.Activate()
NS_LOAD02.ReadOnly = False
NS_LOAD02.Name= "Load2_Nodes"
NS_SUPPORT01.Activate()
NS_SUPPORT01.ReadOnly = False
NS_SUPPORT01.Name= "Support_Nodes"
NS_SUPPORT02.Activate()
NS_SUPPORT02.ReadOnly = False
NS_SUPPORT02.Name= "Support2_Nodes"
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 283
End-to-End Analysis Examples
NS_SUPPORT03.Name = "Support3_Nodes"
GEN_CRT1 = NS_SUPPORT03.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.MeshNode
CRT1.Criterion=SelectionCriterionType.LocationZ
CRT1.Operator=SelectionOperatorType.Equal
CRT1.Value=Quantity('0 [mm]')
GEN_CRT1.Add(CRT1)
CRT2 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT2.Active=True
CRT2.Action=SelectionActionType.Add
CRT2.EntityType=SelectionType.MeshNode
CRT2.Criterion=SelectionCriterionType.LocationZ
CRT2.Operator=SelectionOperatorType.Equal
CRT2.Value=Quantity('-12 [mm]')
GEN_CRT1.Add(CRT2)
NS_SUPPORT03.Activate()
NS_SUPPORT03.Generate()
FRACTURE.Activate()
PRE_MESHED_CRACK = FRACTURE.AddPreMeshedCrack()
PRE_MESHED_CRACK.CrackFront=NS_CRACK
PRE_MESHED_CRACK.CrackFacesNodes= True
PRE_MESHED_CRACK.TopFaceNodes=NS_CRACK_SUR01
PRE_MESHED_CRACK.BottomFaceNodes=NS_CRACK_SUR02
PRE_MESHED_CRACK.CoordinateSystem = GLOBAL_COORDINATE_SYSTEM
PRE_MESHED_CRACK.SolutionContours = 5
PRE_MESHED_CRACK.CrackSymmetry = False
STATIC_STRUCTURAL.Activate()
NODAL_DISPLACEMENT02 = STATIC_STRUCTURAL.AddNodalDisplacement()
NODAL_DISPLACEMENT02.Location = NS_SUPPORT02
NODAL_DISPLACEMENT02.XComponent.Output.DiscreteValues = [Quantity('0 [mm]')]
STATIC_STRUCTURAL.Activate()
NODAL_DISPLACEMENT03 = STATIC_STRUCTURAL.AddNodalDisplacement()
NODAL_DISPLACEMENT03.Location = NS_SUPPORT03
NODAL_DISPLACEMENT03.ZComponent.Output.DiscreteValues = [Quantity('0 [mm]')]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
284 of ANSYS, Inc. and its subsidiaries and affiliates.
Fracture Analysis: SMART Crack Growth
STATIC_STRUCTURAL.Activate()
NODAL_FORCE01 = STATIC_STRUCTURAL.AddNodalForce()
NODAL_FORCE01.Location = NS_LOAD01
NODAL_FORCE01.YComponent.Output.DiscreteValues = [Quantity('450 [N]')]
STATIC_STRUCTURAL.Activate()
NODAL_FORCE02 = STATIC_STRUCTURAL.AddNodalForce()
NODAL_FORCE02.Location = NS_LOAD02
NODAL_FORCE02.YComponent.Output.DiscreteValues = [Quantity('-450 [N]')]
SOLUTION.Activate()
FRACTURE_TOOL = SOLUTION.AddFractureTool()
FRACTURE_TOOL.CrackSelection = PRE_MESHED_CRACK
SIFS_K1.Activate()
SIFS_K1.ActiveContourEnd = 5
FRACTURE_TOOL.Activate()
CRACK_EXTENSION_PROBE01 = FRACTURE_TOOL.AddCrackExtensionProbe()
CRACK_EXTENSION_PROBE01.CrackLengthPercentage = 0
CRACK_EXTENSION_PROBE02 = CRACK_EXTENSION_PROBE01.Duplicate()
CRACK_EXTENSION_PROBE02.CrackLengthPercentage = 100
FRACTURE_TOOL.Activate()
NUM_OF_CYCLES_PROBE01 = FRACTURE_TOOL.AddNumberOfCyclesProbe()
NUM_OF_CYCLES_PROBE01.CrackLengthPercentage = 0
NUM_OF_CYCLES_PROBE02 = NUM_OF_CYCLES_PROBE01.Duplicate()
NUM_OF_CYCLES_PROBE02.CrackLengthPercentage = 100
FRACTURE_TOOL.Activate()
EQV_SIFS_RANGE_PROBE01 = FRACTURE_TOOL.AddEquivalentSIFSRangeProbe()
EQV_SIFS_RANGE_PROBE01.CrackLengthPercentage = 0
EQV_SIFS_RANGE_PROBE02 = EQV_SIFS_RANGE_PROBE01.Duplicate()
EQV_SIFS_RANGE_PROBE02.CrackLengthPercentage = 100
TOTAL_DEFORMATION.Activate()
MAX_TOTAL_DEFORMATION = TOTAL_DEFORMATION.Maximum.Value
CRACK_EXTENSION_PROBE01.Activate()
MIN_VOT_CRACK_EXT_P01 = CRACK_EXTENSION_PROBE01.MinimumValueOverTime.Value
MAX_VOT_CRACK_EXT_P01 = CRACK_EXTENSION_PROBE01.MaximumValueOverTime.Value
CRACK_EXTENSION_PROBE02.Activate()
MIN_VOT_CRACK_EXT_P02 = CRACK_EXTENSION_PROBE02.MinimumValueOverTime.Value
MAX_VOT_CRACK_EXT_P02 = CRACK_EXTENSION_PROBE02.MaximumValueOverTime.Value
NUM_OF_CYCLES_PROBE01.Activate()
MIN_VOT_NUM_CYC_P01 = NUM_OF_CYCLES_PROBE01.MinimumValueOverTime
MAX_VOT_NUM_CYC_P01 = NUM_OF_CYCLES_PROBE01.MaximumValueOverTime
NUM_OF_CYCLES_PROBE02.Activate()
MIN_VOT_NUM_CYC_P02 = NUM_OF_CYCLES_PROBE02.MinimumValueOverTime
MAX_VOT_NUM_CYC_P02 = NUM_OF_CYCLES_PROBE02.MaximumValueOverTime
EQV_SIFS_RANGE_PROBE01.Activate()
MIN_VOT_EQV_SIFS_RANGE_P01 = EQV_SIFS_RANGE_PROBE01.MinimumValueOverTime.Value
MAX_VOT_EQV_SIFS_RANGE_P01 = EQV_SIFS_RANGE_PROBE01.MaximumValueOverTime.Value
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 285
End-to-End Analysis Examples
EQV_SIFS_RANGE_PROBE02.Activate()
MIN_VOT_EQV_SIFS_RANGE_P02 = EQV_SIFS_RANGE_PROBE02.MinimumValueOverTime.Value
MAX_VOT_EQV_SIFS_RANGE_P02 = EQV_SIFS_RANGE_PROBE02.MaximumValueOverTime.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Contact_Debonding_Example.agdb
• Contact_Debonding_Example.py
• Contact_Debonding_Example_Mat1.xml
• Contact_Debonding_Example_Mat2.xml
Procedure
1. Open Workbench and insert a Static Structural system into the Project Schematic.
3. Select File > Import Engineering Data, navigate to the proper folder location and select Con-
tact_Debonding_Example_Mat1.xml. Repeat this for Contact_Debonding_Ex-
ample_Mat2.xml
6. Enable the Named Selections check box under the Basic Geometry Options category.
7. Set the Analysis Type property to 2D under the Advanced Geometry Options category.
8. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Contact_Debonding_Example.agdb.
10. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
286 of ANSYS, Inc. and its subsidiaries and affiliates.
Fracture Analysis: Contact Debonding
11. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Contact_Debonding_Example.py.
12. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Store main Tree Object items
MODEL = Model
GEOMETRY = Model.Geometry
PART = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Part 2'][0]
MAT_GRP = MODEL.Materials
MAT_BODY = [i for i in MAT_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) if i.Name == 'Interface B
MAT_CZM = [i for i in MAT_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) if i.Name == 'CZM Crack Ma
CONNECTIONS_GRP = ExtAPI.DataModel.Project.Model.Connections
CONTACTS = [i for i in CONNECTIONS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Connections.ConnectionGroup](True
CONTACT_REGION = [i for i in CONTACTS.GetChildren[Ansys.ACT.Automation.Mechanical.Connections.ContactRegion](True) i
MESH = Model.Mesh
NAMED_SELECTIONS = ExtAPI.DataModel.Project.Model.NamedSelections
NS_EDGE_HIGH = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.N
NS_EDGE_LOW = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.Na
NS_EDGES_SHORT = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i
NS_EDGES_LONG = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.
NS_EDGES_FIXED = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i
NS_VERTEX_DISP1 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_VERTEX_DISP2 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_FACES_BOTH = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.
SIZING_MESH = MESH.AddSizing()
SIZING_MESH.Location = NS_EDGES_SHORT
SIZING_MESH.ElementSize = Quantity('0.75 [mm]')
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 287
End-to-End Analysis Examples
SIZING_MESH.Behavior=SizingBehavior.Hard
SIZING_MESH2 = MESH.AddSizing()
SIZING_MESH2.Location = NS_EDGES_LONG
SIZING_MESH2.ElementSize = Quantity('0.5 [mm]')
SIZING_MESH2.Behavior=SizingBehavior.Hard
FACE_MESHING = MESH.AddFaceMeshing()
FACE_MESHING.Location = NS_FACES_BOTH
FACE_MESHING.Method=FaceMeshingMethod.Quadrilaterals
MESH.Activate()
MESH.GenerateMesh()
CONTACT_DEBONDING = FRACTURE.AddContactDebonding()
CONTACT_DEBONDING.Material= MAT_CZM.Name
CONTACT_DEBONDING.ContactRegion=CONTACT_REGION
STATIC_STRUCTURAL.Activate()
DISPLACEMENT = STATIC_STRUCTURAL.AddDisplacement()
DISPLACEMENT.Location = NS_VERTEX_DISP1
DISPLACEMENT.DefineBy = LoadDefineBy.Components
DISPLACEMENT.YComponent.Output.DiscreteValues=[Quantity('10 [mm]')]
STATIC_STRUCTURAL.Activate()
DISPLACEMENT2 = STATIC_STRUCTURAL.AddDisplacement()
DISPLACEMENT2.Location = NS_VERTEX_DISP2
DISPLACEMENT2.DefineBy = LoadDefineBy.Components
DISPLACEMENT2.YComponent.Output.DiscreteValues=[Quantity('-10 [mm]')]
FORCE_REACTION = SOLUTION.AddForceReaction()
FORCE_REACTION.BoundaryConditionSelection = DISPLACEMENT
DIRECTIONAL_DEFORMATION.Activate()
MIN_DIRECTIONAL_DEFORMATION = DIRECTIONAL_DEFORMATION.Minimum.Value
MAX_DIRECTIONAL_DEFORMATION = DIRECTIONAL_DEFORMATION.Maximum.Value
FORCE_REACTION.Activate()
Y_AXIS_FORCE_REACTION = FORCE_REACTION.YAxis.Value
MOT_Y_AXIS_FORCE_REACTION = FORCE_REACTION.MaximumYAxis.Value
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
288 of ANSYS, Inc. and its subsidiaries and affiliates.
Fracture Analysis: Interface Delamination
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Interface_Delamination_Example.agdb
• Interface_Delamination_Example.py
• Interface_Delamination_Example_Mat1.xml
• Interface_Delamination_Example_Mat2.xml
Procedure
1. Open Workbench and insert a Static Structural system into the Project Schematic.
3. Select File > Import Engineering Data, navigate to the proper folder location and select Inter-
face_Delamination_Example_Mat1.xml. Repeat this for Interface_Delamination_Ex-
ample_Mat2.xml
6. Enable the Named Selections check box under the Basic Geometry Options category.
7. Set the Analysis Type property to 2D under the Advanced Geometry Options category.
8. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Interface_Delamination_Example.agdb.
9. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
10. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
11. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Interface_Delamination_Example.py.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 289
End-to-End Analysis Examples
12. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Store main Tree Object items
MODEL = Model
GEOMETRY = Model.Geometry
PART = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Part 2'][0]
MAT_GRP = MODEL.Materials
MAT_BODY = [i for i in MAT_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) if i.Name == 'Interface B
MAT_CZM = [i for i in MAT_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) if i.Name == 'CZM Material
COORDINATE_SYSTEMS = Model.CoordinateSystems
GLOBAL_COORDINATE_SYSTEM = [i for i in COORDINATE_SYSTEMS.GetChildren[Ansys.ACT.Automation.Mechanical.CoordinateSyst
CONNECTIONS_GRP = ExtAPI.DataModel.Project.Model.Connections
CONTACTS = [i for i in CONNECTIONS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Connections.ConnectionGroup](True
CONTACT_REGION = [i for i in CONTACTS.GetChildren[Ansys.ACT.Automation.Mechanical.Connections.ContactRegion](True) i
MESH = Model.Mesh
NAMED_SELECTIONS = ExtAPI.DataModel.Project.Model.NamedSelections
NS_EDGE_HIGH = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.N
NS_EDGE_LOW = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.Na
NS_EDGES_SHORT = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i
NS_EDGES_LONG = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.
NS_EDGES_FIXED = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i
NS_VERTEX_DISP1 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_VERTEX_DISP2 = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_FACES_BOTH = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.
COORDINATE_SYSTEMS.Activate()
COORDINATE_SYSTEM2 = COORDINATE_SYSTEMS.AddCoordinateSystem()
COORDINATE_SYSTEM2.OriginLocation = NS_EDGE_LOW
COORDINATE_SYSTEM2.Name = 'Low Coordinate System'
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
290 of ANSYS, Inc. and its subsidiaries and affiliates.
Fracture Analysis: Interface Delamination
MESH.UseAdaptiveSizing=False
MESH.ElementSize = Quantity('0.75 [mm]')
MESH.Activate()
MATCH_CONTROL = MESH.AddMatchControl()
SEL=ExtAPI.SelectionManager.AddSelection(NS_EDGE_HIGH)
SEL2=ExtAPI.SelectionManager.CurrentSelection
MATCH_CONTROL.HighGeometrySelection = SEL2
ExtAPI.SelectionManager.ClearSelection()
SEL3=ExtAPI.SelectionManager.AddSelection(NS_EDGE_LOW)
SEL4=ExtAPI.SelectionManager.CurrentSelection
MATCH_CONTROL.LowGeometrySelection = SEL4
ExtAPI.SelectionManager.ClearSelection()
SIZING_MESH = MESH.AddSizing()
SIZING_MESH.Location = NS_EDGES_SHORT
SIZING_MESH.ElementSize = Quantity('0.75 [mm]')
SIZING_MESH.Behavior=SizingBehavior.Hard
SIZING_MESH2 = MESH.AddSizing()
SIZING_MESH2.Location = NS_EDGES_LONG
SIZING_MESH2.ElementSize = Quantity('0.5 [mm]')
SIZING_MESH2.Behavior=SizingBehavior.Hard
FACE_MESHING = MESH.AddFaceMeshing()
FACE_MESHING.Location = NS_FACES_BOTH
FACE_MESHING.Method=FaceMeshingMethod.Quadrilaterals
MESH.Activate()
MESH.GenerateMesh()
INTERFACE_DELAMINATION = FRACTURE.AddInterfaceDelamination()
INTERFACE_DELAMINATION.Method=DelaminationMethod.CZM
INTERFACE_DELAMINATION.Material= MAT_CZM.Name
INTERFACE_DELAMINATION.GenerationMethod=DelaminationGenerationMethod.MatchedMeshing
INTERFACE_DELAMINATION.MatchControl=MATCH_CONTROL
STATIC_STRUCTURAL.Activate()
DISPLACEMENT = STATIC_STRUCTURAL.AddDisplacement()
DISPLACEMENT.Location = NS_VERTEX_DISP1
DISPLACEMENT.DefineBy = LoadDefineBy.Components
DISPLACEMENT.YComponent.Output.DiscreteValues=[Quantity('10 [mm]')]
STATIC_STRUCTURAL.Activate()
DISPLACEMENT2 = STATIC_STRUCTURAL.AddDisplacement()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 291
End-to-End Analysis Examples
DISPLACEMENT2.Location = NS_VERTEX_DISP2
DISPLACEMENT2.DefineBy = LoadDefineBy.Components
DISPLACEMENT2.YComponent.Output.DiscreteValues=[Quantity('-10 [mm]')]
FORCE_REACTION = SOLUTION.AddForceReaction()
FORCE_REACTION.BoundaryConditionSelection = DISPLACEMENT
DIRECTIONAL_DEFORMATION.Activate()
MIN_DIRECTIONAL_DEFORMATION = DIRECTIONAL_DEFORMATION.Minimum.Value
MAX_DIRECTIONAL_DEFORMATION = DIRECTIONAL_DEFORMATION.Maximum.Value
FORCE_REACTION.Activate()
Y_AXIS_FORCE_REACTION = FORCE_REACTION.YAxis.Value
MOT_Y_AXIS_FORCE_REACTION = FORCE_REACTION.MaximumYAxis.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Harmonic_Acoustics_Example.agdb
• Harmonic_Acoustics_Example.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Harmonic
Acoustics system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Harmonic_Acous-
tics_Example.agdb.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
292 of ANSYS, Inc. and its subsidiaries and affiliates.
Harmonic Acoustic Analysis
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Harmonic_Acoustics_Example.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Scenario 1 Store all main tree nodes as variables
GEOMETRY = Model.Geometry
MESH = Model.Mesh
NAMED_SELECTIONS = Model.NamedSelections
CONNECTIONS = Model.Connections
SPEAKER_BOX.Suppressed = 1
PLATE.Suppressed = 1
FEA_DOMAIN.Material = "Air"
PML_REGION.Material= "Air"
SIZING2 = MESH.AddSizing()
SIZING2.Location = PML_BODY
SIZING2.ElementSize =Quantity('0.01 [m]')
MESH_METHOD1 = MESH.AddAutomaticMethod()
MESH_METHOD1.Location = FEA_BODY.Location
MESH_METHOD1.Method =MethodType.HexDominant
MESH_METHOD2 = MESH.AddAutomaticMethod()
MESH_METHOD2.Location = PML_BODY.Location
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 293
End-to-End Analysis Examples
MESH_METHOD2.Method =MethodType.HexDominant
#Scenario 6 Setup Harmonic Acoustics and defined Acoustic and PML regions
ANALYSIS_SETTINGS = Model.Analyses[0].AnalysisSettings
ANALYSIS_SETTINGS.RangeMaximum = Quantity('3000 [Hz]')
ANALYSIS_SETTINGS.SolutionIntervals = 1
ANALYSIS_SETTINGS.CalculateVelocity = True
ANALYSIS_SETTINGS.CalculateEnergy = True
ANALYSIS_SETTINGS.GeneralMiscellaneous = True
ANALYSIS_SETTINGS.FarFieldRadiationSurface =FarFieldRadiationSurfaceType.Manual
HARMONIC_ACOUSTICS = Model.Analyses[0]
ACOUSTIC_REGION1 = HARMONIC_ACOUSTICS.Children[2]
ACOUSTIC_REGION1.Location = FEA_BODY
ACOUSTIC_REGION2 = HARMONIC_ACOUSTICS.AddPhysicsRegion()
ACOUSTIC_REGION2.Location = PML_BODY
ACOUSTIC_REGION2.Acoustics = True
ACOUSTIC_REGION2.ArtificiallyMatchedLayers = ArtificiallyMatchedLayers.PML
MASS_SOURCE = HARMONIC_ACOUSTICS.AddAcousticMassSource()
MASS_SOURCE.Location = MASS_SOURCE_FACE
MASS_SOURCE.Magnitude.Output.DiscreteValues = [Quantity('0.01 [kg m-2 s-1]')]
ACOUST_PRESSURE = HARMONIC_ACOUSTICS.AddAcousticPressure()
ACOUST_PRESSURE.Location = PRESSURE_FACES
FARFFIELD_RAD_SURFACE = HARMONIC_ACOUSTICS.CreateAutomaticFarFieldRadiationSurfaces()
ACOUSTIC_PRESSURE_RESULT = SOLUTION.AddAcousticPressureResult()
ACOUSTIC_PRESSURE_RESULT.Location = FEA_BODY
SOUND_PRESSURE_LEVEL = SOLUTION.AddAcousticSoundPressureLevel()
SOUND_PRESSURE_LEVEL.Location = FEA_BODY
FAR_FIELD_SPL = SOLUTION.AddAcousticFarFieldSPL()
FAR_FIELD_SPL.SphereRadius = Quantity('1 [m]')
FAR_FIELD_SPL.ThetaAngleEnd = Quantity('90 [deg]')
FAR_FIELD_SPL.ThetaAngleNoOfDivisions = 90
FAR_FIELD_AWEIGHTED_SPL = SOLUTION.AddAcousticFarFieldAWeightedSPL()
FAR_FIELD_AWEIGHTED_SPL.SphereRadius = Quantity('1 [m]')
FAR_FIELD_AWEIGHTED_SPL.ThetaAngleEnd = Quantity('90 [deg]')
FAR_FIELD_AWEIGHTED_SPL.ThetaAngleNoOfDivisions = 90
PRESSURE_MAX = ACOUSTIC_PRESSURE_RESULT.Minimum.Value
PRESSURE_MIN = ACOUSTIC_PRESSURE_RESULT.Maximum.Value
SPL_MIN = SOUND_PRESSURE_LEVEL.Minimum.Value
SPL_MAX = SOUND_PRESSURE_LEVEL.Maximum.Value
FF_SPL_MIN = FAR_FIELD_SPL.Minimum.Value
FF_SPL_MAX = FAR_FIELD_SPL.Maximum.Value
FF_A_SPL_MIN = FAR_FIELD_AWEIGHTED_SPL.Minimum.Value
FF_A_SPL_MAX = FAR_FIELD_AWEIGHTED_SPL.Maximum.Value
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
294 of ANSYS, Inc. and its subsidiaries and affiliates.
Modal Acoustic Analysis
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_Modal_Acoustics_013_Geometry.agdb
• Mechanical_Modal_Acoustics_013_Script.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Modal
Acoustics system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanical_Mod-
al_Acoustics_013_Geometry.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_Modal_Acoustics_013_Script.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Scenario 1 Define main Tree node objects
GEOMETRY = Model.Geometry
MESH = Model.Mesh
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 295
End-to-End Analysis Examples
NS_GRP = Model.NamedSelections
FACE_MESH1 = MESH.AddFaceMeshing()
FACE_MESH1.Location = NS_SOLID_FACE1
FACE_MESH2 = MESH.AddFaceMeshing()
FACE_MESH2.Location = NS_ACST_FACE1
MESH_SIZE1 = MESH.AddSizing()
MESH_SIZE1.Location = NS_SOLID_BODY
MESH_SIZE1.ElementSize = Quantity('0.125 [in]')
MESH_SIZE2 = MESH.AddSizing()
MESH_SIZE2.Location = NS_ACOUSTIC_BODY
MESH_SIZE2.ElementSize = Quantity('5 [in]')
ANALYSIS_SETTINGS = Model.Analyses[0].AnalysisSettings
ANALYSIS_SETTINGS.IgnoreAcousticDamping = True
ACOUSTIC_REGION = MODAL_ACOUSTIC.Children[2]
ACOUSTIC_REGION.Location = NS_ACOUSTIC_BODY
ACOUSTIC_REGION.Acoustics = True
STRUCTURAL_REGION = MODAL_ACOUSTIC.AddPhysicsRegion()
STRUCTURAL_REGION.Location = NS_SOLID_BODY
STRUCTURAL_REGION.Structural = True
FLUID_SOLID_INTERFACE = MODAL_ACOUSTIC.AddFluidSolidInterface()
FLUID_SOLID_INTERFACE.Location = NS_FSI_FACE
ACOUSTIC_PRESSURE_RESULT_1 = SOLUTION.AddAcousticPressureResult()
ACOUSTIC_PRESSURE_RESULT_1.Location = NS_ACOUSTIC_BODY
ACOUSTIC_PRESSURE_RESULT_2 = SOLUTION.AddAcousticPressureResult()
ACOUSTIC_PRESSURE_RESULT_2.SetNumber = 2
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
296 of ANSYS, Inc. and its subsidiaries and affiliates.
Structural Optimization (Density Based) Analysis
FREQ1 = TOTAL_DEFORMATION_1.TabularData["Frequency"][0]
FREQ2 = TOTAL_DEFORMATION_1.TabularData["Frequency"][1]
FREQ3 = TOTAL_DEFORMATION_1.TabularData["Frequency"][2]
FREQ4 = TOTAL_DEFORMATION_1.TabularData["Frequency"][3]
FREQ5 = TOTAL_DEFORMATION_1.TabularData["Frequency"][4]
FREQ6 = TOTAL_DEFORMATION_1.TabularData["Frequency"][5]
PRESSURE_MAX = ACOUSTIC_PRESSURE_RESULT_1.Maximum.Value
PRESSURE_MIN = ACOUSTIC_PRESSURE_RESULT_1.Minimum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Topology_Optimization_Example_001.agdb
• Topology_Optimization_Example_001.py
Procedure
The following procedure assumes you understand how to add a system in Workbench and make changes
to system cells and properties as well as saving the support files to a known location.
1. Add a Static Structural analysis to the Project Schematic. Drag and drop a Structural Optimization
system onto the static system as shown.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 297
End-to-End Analysis Examples
2. Right-click the Geometry cell of the static system and select Import Geometry > Browse and select
the Topology_Optimization_Example_001.agdb file.
3. Right-click the Model cell and select Edit. This action launches the Mechanical application.
4. In Mechanical, select the Automation tab and select the Scripting option to open the Mechanical
Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Topology_Optimization_Example_001.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
298 of ANSYS, Inc. and its subsidiaries and affiliates.
Structural Optimization (Density Based) Analysis
Scripts Illustrated
In this example, the python file automatically performs the following actions:
MESH_METHOD1 = MESH.AddAutomaticMethod()
MESH_METHOD1.Location = Body_1
MESH_METHOD1.Method =MethodType.Sweep
MESH_METHOD1.Algorithm = MeshMethodAlgorithm.Axisymmetric
COORDINATE_SYSTEM2 = COORDINATE_SYSTEMS.AddCoordinateSystem()
COORDINATE_SYSTEM2.OriginLocation = Body_4
FIXED_SUPPORT1 = STATIC_STRUCTURAL.AddFixedSupport()
FIXED_SUPPORT1.Location = Fixed_Face_1
FIXED_SUPPORT2 = STATIC_STRUCTURAL.AddFixedSupport()
FIXED_SUPPORT2.Location = Fixed_Face_2
FORCE1 = STATIC_STRUCTURAL.AddForce()
FORCE1.Location = Force_Face
FORCE1.DefineBy = LoadDefineBy.Components
FORCE1.YComponent.Output.DiscreteValues = [Quantity("5000 [N]")]
FORCE1.ZComponent.Output.DiscreteValues = [Quantity("1000 [N]")]
SOLUTION1 = STATIC_STRUCTURAL.Solution
TOTAL_DEFORMATION = SOLUTION1.AddTotalDeformation()
EQUIVALENT_STRESS = SOLUTION1.AddEquivalentStress()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 299
End-to-End Analysis Examples
OPTIMIZATION_REGION1 = TOPOLOGY_OPTIMIZATION.Children[1]
OPTIMIZATION_REGION1.DesignRegionLocation = Optimization_Region_1
OPTIMIZATION_REGION1.BoundaryCondition = BoundaryConditionType.AllLoadsAndSupports
OPTIMIZATION_REGION1.OptimizationType = OptimizationType.TopologyDensity
# Mass Constraint
RESPONSE_CONSTRAINT1 = TOPOLOGY_OPTIMIZATION.Children[4]
RESPONSE_CONSTRAINT1.Location = OPTIMIZATION_REGION1
RESPONSE_CONSTRAINT1.PercentageToRetain = 40
MANUFACTURING_CONSTRAINT3 = TOPOLOGY_OPTIMIZATION.AddSymmetryManufacturingConstraint()
MANUFACTURING_CONSTRAINT3.Location = Body_2
MANUFACTURING_CONSTRAINT3.CoordinateSystem = COORDINATE_SYSTEM1
MANUFACTURING_CONSTRAINT3.Axis = CoordinateSystemAxisType.PositiveZAxis
MANUFACTURING_CONSTRAINT4 = TOPOLOGY_OPTIMIZATION.AddSymmetryManufacturingConstraint()
MANUFACTURING_CONSTRAINT4.Location = Body_3
MANUFACTURING_CONSTRAINT4.CoordinateSystem = GLOBAL_COORDINATE_SYSTEM
MANUFACTURING_CONSTRAINT4.Axis = CoordinateSystemAxisType.PositiveZAxis
MANUFACTURING_CONSTRAINT5 = TOPOLOGY_OPTIMIZATION.AddSymmetryManufacturingConstraint()
MANUFACTURING_CONSTRAINT5.Location = Body_3
MANUFACTURING_CONSTRAINT5.CoordinateSystem = GLOBAL_COORDINATE_SYSTEM
MANUFACTURING_CONSTRAINT5.Axis = CoordinateSystemAxisType.PositiveYAxis
MANUFACTURING_CONSTRAINT6 = TOPOLOGY_OPTIMIZATION.AddSymmetryManufacturingConstraint()
MANUFACTURING_CONSTRAINT6.Location = Body_4
MANUFACTURING_CONSTRAINT6.CoordinateSystem = COORDINATE_SYSTEM2
MANUFACTURING_CONSTRAINT6.Axis = CoordinateSystemAxisType.PositiveXAxis
MANUFACTURING_CONSTRAINT7 = TOPOLOGY_OPTIMIZATION.AddSymmetryManufacturingConstraint()
MANUFACTURING_CONSTRAINT7.Location = Body_4
MANUFACTURING_CONSTRAINT7.CoordinateSystem = COORDINATE_SYSTEM2
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
300 of ANSYS, Inc. and its subsidiaries and affiliates.
Structural Optimization (Level Set Based) Analysis
MANUFACTURING_CONSTRAINT7.Axis = CoordinateSystemAxisType.PositiveZAxis
TOPOLOGY_DENSITY1 = SOLUTION2.Children[1]
TOPOLOGY_DENSITY1.ScopingMethod = GeometryDefineByType.AllOptimizationRegions
# Insert Smoothing
SMOOTHING1 = TOPOLOGY_DENSITY1.AddSmoothing()
SOLUTION2.Solve(True)
TOPO_DENS1_OV = TOPOLOGY_DENSITY1.OriginalVolume.Value
TOPO_DENS1_FV = TOPOLOGY_DENSITY1.FinalVolume.Value
TOPO_DENS1_PVO = TOPOLOGY_DENSITY1.PercentVolumeOfOriginal
TOPO_DENS1_OM = TOPOLOGY_DENSITY1.OriginalMass.Value
TOPO_DENS1_FM = TOPOLOGY_DENSITY1.FinalMass.Value
TOPO_DENS1_PMO = TOPOLOGY_DENSITY1.PercentMassOfOriginal
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Structural_Optimization_Level_Set.agdb
• Structural_Optimization_Level_Set.py
Procedure
The following procedure assumes you understand how to add a system in Workbench and make changes
to system cells and properties as well as saving the support files to a known location.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 301
End-to-End Analysis Examples
1. Add a Static Structural analysis to the Project Schematic. Drag and drop a Structural Optimization
system onto the static system as shown.
2. Right-click the Geometry cell of the static system and select Import Geometry > Browse and select
the Structural_Optimization_Level_Set.agdb file.
3. Right-click the Model cell and select Edit. This action launches the Mechanical application.
4. In Mechanical, select the Automation tab and select the Scripting option to open the Mechanical
Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Structural_Optimization_Level_Set.py.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
302 of ANSYS, Inc. and its subsidiaries and affiliates.
Structural Optimization (Level Set Based) Analysis
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
FIXED_SUPPORT1 = STATIC_STRUCTURAL.AddFixedSupport()
FIXED_SUPPORT1.Location = Fixed_Support_1
FIXED_SUPPORT2 = STATIC_STRUCTURAL.AddFixedSupport()
FIXED_SUPPORT2.Location = Fixed_Support_2
FORCE1 = STATIC_STRUCTURAL.AddForce()
FORCE1.Location = Force
FORCE1.DefineBy = LoadDefineBy.Components
FORCE1.XComponent.Output.DiscreteValues = [Quantity("-1000 [N]")]
SOLUTION1 = STATIC_STRUCTURAL.Solution
TOTAL_DEFORMATION = SOLUTION1.AddTotalDeformation()
EQUIVALENT_STRESS = SOLUTION1.AddEquivalentStress()
OPTIMIZATION_REGION1 = TOPOLOGY_OPTIMIZATION.Children[1]
OPTIMIZATION_REGION1.BoundaryCondition = BoundaryConditionType.AllLoadsAndSupports
OPTIMIZATION_REGION1.OptimizationType = OptimizationType.TopologyLevelSet
# Mass Constraint
RESPONSE_CONSTRAINT1 = TOPOLOGY_OPTIMIZATION.Children[3]
RESPONSE_CONSTRAINT1.DefineBy = ResponseConstraintDefineBy.Range
RESPONSE_CONSTRAINT1.PercentageToRetainMin = 50
RESPONSE_CONSTRAINT1.PercentageToRetainMax = 70
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 303
End-to-End Analysis Examples
RESPONSE_CONSTRAINT2.ReactionForceCriteria = ReactionForceCriteriaType.Sum
RESPONSE_CONSTRAINT2.BoundType = TopoBoundType.LowerBound
RESPONSE_CONSTRAINT2.XComponentMax.Output.DiscreteValues=[Quantity ("500 [N]")]
TOPOLOGY_DENSITY1 = SOLUTION2.Children[1]
# Insert Smoothing
SMOOTHING1 = TOPOLOGY_DENSITY1.AddSmoothing()
SOLUTION2.Solve(True)
TOPO_DENS1_OV = TOPOLOGY_DENSITY1.OriginalVolume.Value
TOPO_DENS1_FV = TOPOLOGY_DENSITY1.FinalVolume.Value
TOPO_DENS1_PVO = TOPOLOGY_DENSITY1.PercentVolumeOfOriginal
TOPO_DENS1_OM = TOPOLOGY_DENSITY1.OriginalMass.Value
TOPO_DENS1_FM = TOPOLOGY_DENSITY1.FinalMass.Value
TOPO_DENS1_PMO = TOPOLOGY_DENSITY1.PercentMassOfOriginal
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Structural_Optimization_Lattice.agdb
• Structural_Optimization_Lattice.py
Procedure
The following procedure assumes you understand how to add a system in Workbench and make changes
to system cells and properties as well as saving the support files to a known location.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
304 of ANSYS, Inc. and its subsidiaries and affiliates.
Structural Optimization Lattice Analysis
1. Add a Static Structural analysis to the Project Schematic. Drag and drop a Structural Optimization
system onto the static system as shown.
2. Right-click the Geometry cell of the static system and select Import Geometry > Browse and select
the Structural_Optimization_Lattice.agdb file.
3. Right-click the Model cell and select Edit. This action launches the Mechanical application.
4. In Mechanical, select the Automation tab and select the Scripting option to open the Mechanical
Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Structural_Optimization_Lattice.py.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 305
End-to-End Analysis Examples
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
MESH_METHOD1 = MESH.AddAutomaticMethod()
MESH_METHOD1.Location = Body
MESH_METHOD1.Method =MethodType.MultiZone
MESH.GenerateMesh()
COORDINATE_SYSTEM1 = COORDINATE_SYSTEMS.AddCoordinateSystem()
COORDINATE_SYSTEM1.OriginLocation = Internal_Faces
FIXED_SUPPORT1 = STATIC_STRUCTURAL.AddFixedSupport()
FIXED_SUPPORT1.Location = Fixed_Support
PRESSURE1 = STATIC_STRUCTURAL.AddPressure()
PRESSURE1.Location = Pressure
PRESSURE1.Magnitude.Output.DiscreteValues = [Quantity("50 [Pa]")]
SOLUTION1 = STATIC_STRUCTURAL.Solution
TOTAL_DEFORMATION = SOLUTION1.AddTotalDeformation()
EQUIVALENT_STRESS = SOLUTION1.AddEquivalentStress()
OPTIMIZATION_REGION1 = TOPOLOGY_OPTIMIZATION.Children[1]
OPTIMIZATION_REGION1.BoundaryCondition = BoundaryConditionType.AllLoadsAndSupports
OPTIMIZATION_REGION1.OptimizationType = OptimizationType.Lattice
OPTIMIZATION_REGION1.LatticeType = LatticeType.Cubic
OPTIMIZATION_REGION1.LatticeMinDensity = 0.3
OPTIMIZATION_REGION1.LatticeMaxDensity = 0.8
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
306 of ANSYS, Inc. and its subsidiaries and affiliates.
Structural Optimization Shape Optimization Analysis
# Mass Constraint
RESPONSE_CONSTRAINT1 = TOPOLOGY_OPTIMIZATION.Children[3]
RESPONSE_CONSTRAINT1.DefineBy = ResponseConstraintDefineBy.Range
RESPONSE_CONSTRAINT1.PercentageToRetainMin = 30
RESPONSE_CONSTRAINT1.PercentageToRetainMax = 35
LATTICE_DENSITY1 = SOLUTION2.Children[1]
SOLUTION2.Solve(True)
LATTICE_DENS1_OV = LATTICE_DENSITY1.OriginalVolume.Value
LATTICE_DENS1_FV = LATTICE_DENSITY1.FinalVolume.Value
LATTICE_DENS1_PVO = LATTICE_DENSITY1.PercentVolumeOfOriginal
LATTICE_DENS1_OM = LATTICE_DENSITY1.OriginalMass.Value
LATTICE_DENS1_FM = LATTICE_DENSITY1.FinalMass.Value
LATTICE_DENS1_PMO = LATTICE_DENSITY1.PercentMassOfOriginal
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Structural_Optimization_Shape_Optimization.agdb
• Structural_Optimization_Shape_Optimization.py
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 307
End-to-End Analysis Examples
Procedure
The following procedure assumes you understand how to add a system in Workbench and make changes
to system cells and properties as well as saving the support files to a known location.
1. Add a Static Structural analysis to the Project Schematic. Drag and drop a Structural Optimization
system onto the static system as shown.
2. Right-click the Geometry cell of the static system and select Import Geometry > Browse and select
the Structural_Optimization_Shape_Optimization.agdb file.
3. Right-click the Model cell and select Edit. This action launches the Mechanical application.
4. In Mechanical, select the Automation tab and select the Scripting option to open the Mechanical
Scripting pane.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
308 of ANSYS, Inc. and its subsidiaries and affiliates.
Structural Optimization Shape Optimization Analysis
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Structural_Optimization_Shape_Optimization.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
MESH_METHOD1 = MESH.AddAutomaticMethod()
MESH_METHOD1.Location = Body
MESH_METHOD1.Method =MethodType.AllTriAllTet
MESH.GenerateMesh()
FIXED_SUPPORT1 = STATIC_STRUCTURAL.AddFixedSupport()
FIXED_SUPPORT1.Location = Fixed_Support
FORCE1 = STATIC_STRUCTURAL.AddForce()
FORCE1.Location = Force
FORCE1.DefineBy = LoadDefineBy.Components
FORCE1.ZComponent.Output.DiscreteValues = [Quantity("25000 [N]")]
SOLUTION1 = STATIC_STRUCTURAL.Solution
TOTAL_DEFORMATION = SOLUTION1.AddTotalDeformation()
EQUIVALENT_STRESS = SOLUTION1.AddEquivalentStress()
OPTIMIZATION_REGION1 = TOPOLOGY_OPTIMIZATION.Children[1]
OPTIMIZATION_REGION1.ExclusionRegionLocation = Exclusion
OPTIMIZATION_REGION1.OptimizationType = OptimizationType.Shape
OPTIMIZATION_REGION1.ShapeMoveLimitControl = TopoPropertyControlType.ProgramControlled
OPTIMIZATION_REGION1.MaxCumulatedDisplacementControl = TopoPropertyControlType.ProgramControlled
OPTIMIZATION_REGION1.MeshDeformationToleranceControl = TopoPropertyControlType.ProgramControlled
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 309
End-to-End Analysis Examples
# Mass Constraint
RESPONSE_CONSTRAINT1 = TOPOLOGY_OPTIMIZATION.Children[3]
RESPONSE_CONSTRAINT1.Suppressed = True
TOPOLOGY_DENSITY1 = SOLUTION2.Children[1]
SOLUTION2.Solve(True)
TOPO_DENS1_OV = TOPOLOGY_DENSITY1.OriginalVolume.Value
TOPO_DENS1_FV = TOPOLOGY_DENSITY1.FinalVolume.Value
TOPO_DENS1_PVO = TOPOLOGY_DENSITY1.PercentVolumeOfOriginal
TOPO_DENS1_OM = TOPOLOGY_DENSITY1.OriginalMass.Value
TOPO_DENS1_FM = TOPOLOGY_DENSITY1.FinalMass.Value
TOPO_DENS1_PMO = TOPOLOGY_DENSITY1.PercentMassOfOriginal
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_RBD_Contact_Example.agdb
• Mechanical_RBD_Contact_Example.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Rigid Dynamics
system into the tree.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
310 of ANSYS, Inc. and its subsidiaries and affiliates.
Rigid Dynamics: Contact Specification
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanic-
al_RBD_Contact_Example.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_RBD_Contact_Example.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Section 1 - Set up the Tree Object Items
connections = Model.Connections
transient_rbd = Model.Analyses[0]
analysis_settings = transient_rbd.Children[0]
mesh = Model.Mesh
solution = transient_rbd.Solution
ns_torus_surface = DataModel.GetObjectsByName("NS_torus_surface")[0]
ns_cone_surface = DataModel.GetObjectsByName("NS_cone_surface")[0]
ns_fixed_surface = DataModel.GetObjectsByName("NS_fixed_surface")[0]
contact = connections.AddContactRegion()
contact.SourceLocation = ns_torus_surface
contact.TargetLocation = ns_cone_surface
contact.ContactType = ContactType.Frictionless
contact.PinballRegion = ContactPinballType.ProgramControlled
contact.RestitutionFactor = 0.5
contact.RBDContactDetection = DSRBDContactDetection.kCDGeometryBased
fixed_joint = connections.AddJoint()
fixed_joint.ConnectionType=JointScopingType.BodyToGround
fixed_joint.Type = JointType.Fixed
fixed_joint.MobileLocation = ns_fixed_surface
mesh.PhysicsPreference = MeshPhysicsPreferenceType.Mechanical
mesh.ElementOrder=ElementOrder.Quadratic
mesh.ElementSize = Quantity("0.005 [m]")
mesh.Resolution = 4
mesh.GenerateMesh()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 311
End-to-End Analysis Examples
gravity = transient_rbd.AddEarthGravity()
gravity.Direction=GravityOrientationType.NegativeZAxis
total_contact_force_reaction = solution.AddForceReaction()
total_contact_force_reaction.LocationMethod=LocationDefinitionMethod.ContactRegion
total_contact_force_reaction.ContactRegionSelection = contact
total_contact_force_reaction.ContactForce=ContactForceType.Total
tangent_contact_force_reaction = solution.AddForceReaction()
tangent_contact_force_reaction.LocationMethod=LocationDefinitionMethod.ContactRegion
tangent_contact_force_reaction.ContactRegionSelection = contact
tangent_contact_force_reaction.ContactForce=ContactForceType.Tangent
normal_contact_force_reaction = solution.AddForceReaction()
normal_contact_force_reaction.LocationMethod=LocationDefinitionMethod.ContactRegion
normal_contact_force_reaction.ContactRegionSelection = contact
normal_contact_force_reaction.ContactForce=ContactForceType.Normal
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
ExtAPI.Application.ActiveAngleUnit = AngleUnitType.Radian
ExtAPI.Application.ActiveAngularVelocityUnit=AngularVelocityUnitType.RadianPerSecond
solution.Solve(True)
total_contact_force_reaction_z = total_contact_force_reaction.ZAxis.Value
total_contact_force_reaction_maximum_z = total_contact_force_reaction.MaximumZAxis.Value
tangent_contact_force_reaction_maximum_total = total_contact_force_reaction.MaximumTotal.Value
normal_contact_force_reaction_maximum_total = normal_contact_force_reaction.MaximumTotal.Value
normal_contact_force_reaction_minimum_z = normal_contact_force_reaction.MinimumZAxis.Value
energy_probe = solution.AddEnergyProbe()
solution.EvaluateAllResults()
maximum_potential_energy = energy_probe.MaximumPotentialEnergy.Value
maximum_kinetic_energy = energy_probe.MaximumKineticEnergy.Value
maximum_total_energy = energy_probe.MaximumTotalEnergy.Value
maximum_external_energy = energy_probe.MaximumExternalEnergy.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
312 of ANSYS, Inc. and its subsidiaries and affiliates.
Rigid Dynamics: Flexible Part Specification
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_RBD_Flexible_Part_Example.agdb
• Mechanical_RBD_Flexible_Part_Example.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Rigid Dynamics
system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanic-
al_RBD_Flexible_Part_Example.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_RBD_Flexible_Part_Example.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Section 1 - Set up the Tree Object Items
geometry = Model.Geometry
connections = Model.Connections
transient_rbd = Model.Analyses[0]
analysis_settings = transient_rbd.Children[0]
solution = transient_rbd.Solution
ns_face1 = DataModel.GetObjectsByName("NS_FACE1")[0]
ns_face2 = DataModel.GetObjectsByName("NS_FACE2")[0]
ns_cms1 = DataModel.GetObjectsByName("NS_CMS1")[0]
cms1 = geometry.Children[0].Children[0]
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 313
End-to-End Analysis Examples
solid = geometry.Children[1].Children[0]
cms1.StiffnessBehavior = StiffnessBehavior.Flexible
solid.Suppressed = True
general_revolute_joint = connections.AddJoint()
general_revolute_joint.ConnectionType=JointScopingType.BodyToGround
general_revolute_joint.Type = JointType.General
general_revolute_joint.MobileLocation = ns_face1
general_revolute_joint.Rotations = JointRotationDOFType.FreeX
general_all_free = connections.AddJoint()
general_all_free.ConnectionType=JointScopingType.BodyToGround
general_all_free.Type = JointType.General
general_all_free.TranslationX=FixedOrFree.Free
general_all_free.TranslationY=FixedOrFree.Free
general_all_free.TranslationZ=FixedOrFree.Free
general_all_free.Rotations=JointRotationDOFType.FreeAll
general_all_free.MobileLocation = ns_face2
condensed_geometry = Model.AddCondensedGeometry()
condensed_part = condensed_geometry.AddCondensedPart()
condensed_part.GeometrySelection = ns_cms1
condensed_part.NumberOfModes = 10
condensed_part.DetectCondensedPartInterface()
condensed_part.GenerateCondensedParts()
gravity = transient_rbd.AddEarthGravity()
gravity.Direction=GravityOrientationType.PositiveYAxis
expansion_settings = solution.Children[1]
expansion_settings.Activate()
expansion_settings_state = expansion_settings.GetExpansionState( condensed_part)
expansion_settings_state.Stress = True
expansion_settings_state.Displacement = True
expansion_settings.SetExpansionState( condensed_part, expansion_settings_state)
total_deformation = solution.AddTotalDeformation()
joint_probe_deformation = solution.AddJointProbe()
joint_probe_deformation.BoundaryConditionSelection = general_all_free
joint_probe_deformation.ResultType = ProbeResultType.DeformationProbe
equivalent_stress = solution.AddEquivalentStress()
middle_principal_strain = solution.AddMiddlePrincipalElasticStrain()
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
314 of ANSYS, Inc. and its subsidiaries and affiliates.
Rigid Dynamics: General Analysis
ExtAPI.Application.ActiveAngleUnit = AngleUnitType.Radian
ExtAPI.Application.ActiveAngularVelocityUnit=AngularVelocityUnitType.RadianPerSecond
# Section 12 - Solve the System and Define the Condensed Part Results
solution.Solve(True)
total_deformation_maximum = total_deformation.Maximum.Value
equivalent_stress_maximum = equivalent_stress.Maximum.Value
middle_principal_stress_maximum = middle_principal_strain.Maximum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_RBD_Geometry.agdb
• Mechanical_RBD_Script.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Rigid Dynamics
system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanic-
al_RBD_Geometry.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_RBD_Script.py.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 315
End-to-End Analysis Examples
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 - Set up the Tree Object Items
connections = Model.Connections
mesh = Model.Mesh
transient_rbd = Model.Analyses[0]
analysis_settings = transient_rbd.Children[0]
solution = transient_rbd.Solution
ns_sphere_surface = DataModel.GetObjectsByName("NS_sphere_surface")[0]
ns_concave_surface = DataModel.GetObjectsByName("NS_concave_surface")[0]
ns_fixed_surface = DataModel.GetObjectsByName("NS_fixed_surface")[0]
fixed_joint = connections.AddJoint()
fixed_joint.ConnectionType = JointScopingType.BodyToGround
fixed_joint.Type = JointType.Fixed
fixed_joint.MobileLocation = ns_fixed_surface
contact = connections.AddContactRegion()
contact.SourceLocation = ns_sphere_surface
contact.TargetLocation = ns_concave_surface
contact.RestitutionFactor = 0
mesh.Resolution = 4
mesh.ElementSize = Quantity("0.005 [m]")
mesh.GenerateMesh()
analysis_settings.NumberOfSteps = 1
analysis_settings.SetStepEndTime(1, Quantity("0.5 [s]"))
analysis_settings.SetAutomaticTimeStepping(1, AutomaticTimeStepping.On)
analysis_settings.SetInitialTimeStep(1, Quantity("0.0001 [s]"))
analysis_settings.SetMinimumTimeStep(1, Quantity("0.0000001 [s]"))
analysis_settings.SetMaximumTimeStep(1, Quantity("0.05 [s]"))
gravity = transient_rbd.AddEarthGravity()
gravity.Direction = GravityOrientationType.NegativeYAxis
total_deformation = solution.AddTotalDeformation()
joint_probe_total_moment = solution.AddJointProbe()
joint_probe_total_moment.BoundaryConditionSelection = fixed_joint
joint_probe_total_moment.ResultType = ProbeResultType.MomentReaction
joint_probe_total_moment.ResultSelection = ProbeDisplayFilter.XAxis
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
ExtAPI.Application.ActiveAngleUnit = AngleUnitType.Radian
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
316 of ANSYS, Inc. and its subsidiaries and affiliates.
Rigid Dynamics: Joint Specification
ExtAPI.Application.ActiveAngularVelocityUnit=AngularVelocityUnitType.RadianPerSecond
solution.Solve(True)
maximum_total_deformation = total_deformation.Maximum.Value
minimum_total_deformation = total_deformation.Minimum.Value
maximum_of_maximum_total_deformation = total_deformation.MaximumOfMaximumOverTime.Value
minimum_of_minimum_total_deformation = total_deformation.MaximumOfMaximumOverTime.Value
maximum_x_total_moment = joint_probe_total_moment.MaximumXAxis.Value
minimum_x_total_moment = joint_probe_total_moment.MinimumXAxis.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_RBD_Joint_Example.agdb
• Mechanical_RBD_Joint_Example.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Rigid Dynamics
system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanic-
al_RBD_Joint_Example.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 317
End-to-End Analysis Examples
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_RBD_Joint_Example.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Section 1 - Set up the Tree Object Items
connections = Model.Connections
transient_rbd = Model.Analyses[0]
analysis_settings = transient_rbd.Children[0]
solution = transient_rbd.Solution
ns_body_1 = DataModel.GetObjectsByName("NS_Body_1")[0]
ns_body_2 = DataModel.GetObjectsByName("NS_Body_2")[0]
ns_face_1 = DataModel.GetObjectsByName("NS_Face_1")[0]
ns_face_2 = DataModel.GetObjectsByName("NS_Face_2")[0]
ns_face_3 = DataModel.GetObjectsByName("NS_Face_3")[0]
ns_face_4 = DataModel.GetObjectsByName("NS_Face_4")[0]
ns_face_5 = DataModel.GetObjectsByName("NS_Face_5")[0]
contact = connections.Children[0].Children[0]
contact.Delete()
fixed_joint = connections.AddJoint()
fixed_joint.ConnectionType=JointScopingType.BodyToGround
fixed_joint.Type = JointType.Fixed
fixed_joint.MobileLocation = ns_face_1
general_joint = connections.AddJoint()
general_joint.ConnectionType=JointScopingType.BodyToBody
general_joint.Type = JointType.General
general_joint.ReferenceLocation = ns_face_2
general_joint.MobileLocation = ns_face_3
general_joint.TranslationX=FixedOrFree.Free
general_joint.TranslationY=FixedOrFree.Fixed
general_joint.TranslationZ=FixedOrFree.Fixed
general_joint.Rotations=JointRotationDOFType.FreeY
worksheet = general_joint.BushingWorksheet
worksheet.SetBushingStiffnessPerUnitX(0, 200)
worksheet.SetBushingDampingPerUnitX(0, 10)
general_joint.FrictionCoefficient = 0.1
general_joint.Radius = Quantity("1e-2[m]")
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
318 of ANSYS, Inc. and its subsidiaries and affiliates.
Rigid Dynamics: Variable Load Specification
reference_coordinate_system = general_joint.ReferenceCoordinateSystem
reference_coordinate_system.PrimaryAxis=CoordinateSystemAxisType.PositiveXAxis
reference_coordinate_system.PrimaryAxisDefineBy=CoordinateSystemAlignmentType.GlobalX
reference_coordinate_system.SecondaryAxis=CoordinateSystemAxisType.PositiveZAxis
reference_coordinate_system.SecondaryAxisDefineBy=CoordinateSystemAlignmentType.GlobalZ
gravity = transient_rbd.AddEarthGravity()
gravity.Direction=GravityOrientationType.PositiveXAxis
joint_total_force = solution.AddJointProbe()
joint_total_force.BoundaryConditionSelection = general_joint
joint_total_force.ResultType=ProbeResultType.ForceReaction
joint_elastic_force = solution.AddJointProbe()
joint_elastic_force.BoundaryConditionSelection = general_joint
joint_elastic_force.ResultType=ProbeResultType.ElasticForce
joint_damping_force = solution.AddJointProbe()
joint_damping_force.BoundaryConditionSelection = general_joint
joint_damping_force.ResultType=ProbeResultType.DampingForce
joint_relative_velocity = solution.AddJointProbe()
joint_relative_velocity.BoundaryConditionSelection = general_joint
joint_relative_velocity.ResultType=ProbeResultType.VelocityProbe
joint_relative_velocity.ResultSelection=ProbeDisplayFilter.XAxis
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
ExtAPI.Application.ActiveAngleUnit = AngleUnitType.Radian
ExtAPI.Application.ActiveAngularVelocityUnit=AngularVelocityUnitType.RadianPerSecond
solution.Solve(True)
joint_total_force_maximum = joint_total_force.MaximumTotal.Value
joint_elastic_force_final_total = joint_elastic_force.Total.Value
joint_elastic_force_final_x_axis = joint_elastic_force.XAxis.Value
joint_damping_force_maximum_total = joint_damping_force.MaximumTotal.Value
joint_relative_velocity_maximum_x = joint_relative_velocity.MaximumXAxis.Value
joint_elastic_force_maximum_total = joint_elastic_force.MaximumTotal.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Mechanical_RBD_Variable_Load_Example.agdb
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 319
End-to-End Analysis Examples
• Mechanical_RBD_Variable_Load_Example.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Rigid Dynamics
system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select Mechanic-
al_RBD_Variable_Load_Example.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_RBD_Variable_Load_Example.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Section 1 - Set up the Tree Object Items
connections = Model.Connections
transient_rbd = Model.Analyses[0]
analysis_settings = transient_rbd.Children[0]
solution = transient_rbd.Solution
ns_torus_surface = DataModel.GetObjectsByName("NS_torus_surface")[0]
ns_cone_surface = DataModel.GetObjectsByName("NS_cone_surface")[0]
torus_translational_joint = connections.AddJoint()
torus_translational_joint.ConnectionType=JointScopingType.BodyToGround
torus_translational_joint.Type = JointType.Translational
torus_translational_joint.MobileLocation = ns_torus_surface
cone_translational_joint = connections.AddJoint()
cone_translational_joint.ConnectionType=JointScopingType.BodyToGround
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
320 of ANSYS, Inc. and its subsidiaries and affiliates.
Rigid Dynamics: Variable Load Specification
cone_translational_joint.Type = JointType.Translational
cone_translational_joint.MobileLocation = ns_cone_surface
# Section 5 - Define the Spring connecting the Torus and the Cone
cone_torus_spring = connections.AddSpring()
cone_torus_spring.LongitudinalStiffness=Quantity("10 [N m-1]")
cone_torus_spring.Scope = SpringScopingType.BodyToBody
cone_torus_spring.ReferenceScopeLocation = ns_cone_surface
cone_torus_spring.MobileScopeLocation = ns_torus_surface
rigid_dynamics_measures = ExtAPI.DataModel.CreateObject('MeasuresFolder','VariableLoad')
body_measures_attributes = ExtAPI.DataModel.GetUserObjects('VariableLoad')[1].Attributes["measurements"]
joint_measures_attributes = ExtAPI.DataModel.GetUserObjects('VariableLoad')[2].Attributes["measurements"]
derived_measures_attributes = ExtAPI.DataModel.GetUserObjects('VariableLoad')[3].Attributes["measurements"]
# Section 8 - Insert a Measure Varying Joint Load to the Torus Translational Joint in X direction
measure_varying_joint_load_torus = transient_rbd.CreateLoadObject('MeasureJointLoad','VariableLoad')
measure_varying_joint_load_torus.Properties["JointSelection"].Value = str(torus_translational_joint.ObjectId)
measure_varying_joint_load_torus.Properties["JointDof"].Value = 'X'
measure_varying_joint_load_torus.Properties["OutputType"].Value = 'Table'
torus_table = measure_varying_joint_load_torus.Properties["OutputType"].Properties["Table"]
measure_value = torus_table.Properties["MeasureValue"]
magnitude = torus_table.Properties["Magnitude"]
torus_table.AddRow()
measure_value.Value = -0.1
magnitude.Value = 10
torus_table.SaveActiveRow()
torus_table.AddRow()
measure_value.Value = 0.1
magnitude.Value = -10
torus_table.SaveActiveRow()
measure_selection = measure_varying_joint_load_torus.Properties["MeasurementSelections"]
measure_selection.UpdateStateFreq = UpdateStateFreqEnum.UpdateEachTime
measure = measure_selection.Properties["MeasurementSelection"]
measure_selection.AddRow()
measure.Value = 'TorusTranslationX'
measure_selection.SaveActiveRow()
measure_varying_joint_load_torus.NotifyChange()
gravity = transient_rbd.AddEarthGravity()
total_deformation = solution.AddTotalDeformation()
solution.Solve(True)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 321
End-to-End Analysis Examples
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Steady_State_Electric_Conduction.agdb
• Steady_State_Electric_Conduction.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Static Struc-
tural system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select
Steady_State_Electric_Conduction.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Steady_State_Electric_Conduction.py.
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Section 1: Set up the Tree Object Items.
#Section 2: Mesh.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
322 of ANSYS, Inc. and its subsidiaries and affiliates.
Steady State Electric Conduction Analysis
#################################################
# Section 1 - Set up the Tree Object Items.
Geometry = Model.Geometry
Part1 = Geometry.Children[0]
Part2 = Geometry.Children[1]
Part3 = Geometry.Children[2]
Part4 = Geometry.Children[3]
ELEC = Model.Analyses[0]
ANA_SETTING = ELEC.Children[0]
SOLN = ELEC.Solution
#Section 2 - Mesh
MSH = Model.Mesh
MSH.ElementSize = Quantity("0.75[m]")
ANA_SETTING.SetAutomaticTimeStepping(2, AutomaticTimeStepping.Off)
ANA_SETTING.SetDefineBy(2, TimeStepDefineByType.Substeps)
ANA_SETTING.SetNumberOfSubSteps(2, 10)
ANA_SETTING.SetStoreResultsAt(2, TimePointsOptions.EquallySpacedPoints)
ANA_SETTING.SetStoreResulsAtValue(2, 5)
Face2 = DataModel.Project.Model.AddNamedSelection()
Face2.ScopingMethod=GeometryDefineByType.Worksheet
Face2.Name = "Face2"
GEN_CRT2 = Face2.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.GeoFace
CRT1.Criterion=SelectionCriterionType.LocationZ
CRT1.Operator=SelectionOperatorType.Equal
CRT1.Value=Quantity('0 [m]')
GEN_CRT2.Add(CRT1)
Face2.Activate()
Face2.Generate()
Body1 = DataModel.Project.Model.AddNamedSelection()
Body1.ScopingMethod=GeometryDefineByType.Worksheet
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 323
End-to-End Analysis Examples
Body1.Name = "Body1"
GEN_CRT3 = Body1.GenerationCriteria
CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion()
CRT1.Active=True
CRT1.Action=SelectionActionType.Add
CRT1.EntityType=SelectionType.GeoBody
CRT1.Criterion=SelectionCriterionType.LocationZ
CRT1.Operator=SelectionOperatorType.LessThan
CRT1.Value=Quantity('22 [m]')
GEN_CRT3.Add(CRT1)
Body1.Activate()
Body1.Generate()
ELEC_VOLT2 = SOLN.AddElectricVoltage()
ELEC_VOLT2.DisplayTime = Quantity("2[s]")
JOULE_HEAT = SOLN.AddJouleHeat()
JOULE_HEAT.DisplayTime = Quantity("1[s]")
JOULE_HEAT2 = SOLN.AddJouleHeat()
JOULE_HEAT2.DisplayTime = Quantity("2[s]")
DIR_ELEC_FLD_INT = SOLN.AddDirectionalElectricFieldIntensity()
DIR_ELEC_FLD_INT.NormalOrientation = NormalOrientationType.ZAxis
DIR_ELEC_FLD_INT.DisplayTime = Quantity("1[s]")
DIR_ELEC_FLD_INT2 = SOLN.AddDirectionalElectricFieldIntensity()
DIR_ELEC_FLD_INT2.NormalOrientation = NormalOrientationType.ZAxis
DIR_ELEC_FLD_INT2.DisplayTime = Quantity("2[s]")
DIR_CURR_DEN = SOLN.AddDirectionalCurrentDensity()
DIR_CURR_DEN.NormalOrientation = NormalOrientationType.ZAxis
DIR_CURR_DEN.DisplayTime = Quantity("1[s]")
DIR_CURR_DEN2 = SOLN.AddDirectionalCurrentDensity()
DIR_CURR_DEN2.NormalOrientation = NormalOrientationType.ZAxis
DIR_CURR_DEN2.DisplayTime = Quantity("2[s]")
REAC_PROBE = SOLN.AddEmagReactionProbe()
REAC_PROBE.BoundaryConditionSelection = VOLT_LD
REAC_PROBE.DisplayTime = Quantity("1[s]")
REAC_PROBE2 = SOLN.AddEmagReactionProbe()
REAC_PROBE2.BoundaryConditionSelection = VOLT_LD
REAC_PROBE2.DisplayTime = Quantity("2[s]")
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
324 of ANSYS, Inc. and its subsidiaries and affiliates.
Steady-State Thermal-Electric Conduction Analysis
ELEC_VOLT_VAL = ELEC_VOLT.Maximum.Value
ELEC_VOLT2_VAL = ELEC_VOLT2.Minimum.Value
JOULE_HEAT_VAL = JOULE_HEAT.Maximum.Value
JOULE_HEAT2_VAL = JOULE_HEAT2.Minimum.Value
DIR_ELEC_FLD_INT_VAL = DIR_ELEC_FLD_INT.Maximum.Value
DIR_ELEC_FLD_INT2_VAL = DIR_ELEC_FLD_INT2.Minimum.Value
DIR_CURR_DEN_VAL = DIR_CURR_DEN.Maximum.Value
DIR_CURR_DEN2_VAL = DIR_CURR_DEN2.Minimum.Value
REAC_PROBE_VAL = REAC_PROBE.Current.Value
REAC_PROBE2_VAL = REAC_PROBE2.Current.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following Ansys
DesignModeler and python files.
• Steady_State_Thermal_Electric_Conduction.agdb
• Steady_State_Thermal_Electric_Conduction.py
Procedure
1. Open Mechanical directly without importing a geometry or specifying an analysis type. This can
be done through Start Menu.
2. From the Analysis drop-down menu of the Insert group on the Home tab, insert a Static Struc-
tural system into the tree.
3. Select the Geometry object and select the Attach Geometry option from the Geometry group
on the Geometry Context tab. Navigate to the proper folder location and select
Steady_State_Thermal_Electric_Conduction.agdb.
4. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
5. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Steady_State_Thermal_Electric_Conduction.py.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 325
End-to-End Analysis Examples
6. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
#Section 1: Store the tree variables
#Section 2: Store the named selections
#section 3: Insert voltage load
#Section 4: Insert temperature and radiation loads
#Section 5: Insert results
#Section 6: Solve and review results
#Section 7: Define tabular Voltage & functional Voltage
#Section 8: Define tabular Temperature loads
#Section 9: Tabular Emissivity
#Section 10: Solve and review results
#=================================================================
RAD1 = THERM_ELEC.AddRadiation()
RAD1.Location = Face4
RAD1.Correlation = RadiationType.SurfaceToSurface
RAD2 = THERM_ELEC.AddRadiation()
RAD2.Location = Face7
RAD2.Correlation = RadiationType.SurfaceToSurface
RAD_PROBE1 = SOLN.AddRadiationProbe()
RAD_PROBE1.BoundaryConditionSelection = RAD1
RAD_PROBE2 = SOLN.AddRadiationProbe()
RAD_PROBE2.BoundaryConditionSelection = RAD2
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
326 of ANSYS, Inc. and its subsidiaries and affiliates.
Magnetostatic Analysis
TEMP_RST2_VAL = TEMP_RST2.Maximum.Value
TEMP_RST3_VAL = TEMP_RST3.Maximum.Value
RAD_PROBE1_VAL = RAD_PROBE1.EmittedRadiation.Value
RAD_PROBE2_VAL = RAD_PROBE2.EmittedRadiation.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
Magnetostatic Analysis
In this example, using the support files, you will insert a Magnetostatic analysis object into an undefined
Mechanical session and execute a sequence of python journal commands that will define and solve the
analysis.
This example begins in the Mechanical application. It requires you to download the following files.
• Magnetostatic_001.agdb
• Magnetostatic_001.py
• Magnetostatic_001_Mat1.xml
• Magnetostatic_001_Mat2.xml
Procedure
1. Open Workbench and insert a Magnetostatic system into the Project Schematic.
3. Select File > Import Engineering Data, navigate to the proper folder location and select Magneto-
static_001_Mat1.xml. Repeat this action for the Magnetostatic_001_Mat2.xml file.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 327
End-to-End Analysis Examples
5. Right-click the Geometry cell and select Import Geometry > Browse and then navigate to the
proper folder location and select Magnetostatic_001.agdb.
7. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
8. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Magnetostatic_001.py.
9. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario1 - Set up Unit System: Set up the Unit Systems to Metric (m, kg, N, s, V, A),
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
# Scenario 2 - Set up the Tree Object Items: Define the parts, connections, mesh, Magnetostatic system, the analysis
GEOMETRY = Model.Geometry
BODY1 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'air_body'][0]
BODY2 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'conductor'][0]
MESH = Model.Mesh
MAGNETOSTATIC = DataModel.AnalysisByName("Magnetostatic")
ANSLYSIS_SETTINGS = MAGNETOSTATIC.AnalysisSettings
SOLUTION = MAGNETOSTATIC.Solution
# Scenario 3 - Define Named Selections: Define the Named selections that will be used to define the Mesh Controls, t
NS_VOLUME1 = DataModel.GetObjectsByName("NS_Volume1")[0]
NS_VOLUME2 = DataModel.GetObjectsByName("NS_Volume2")[0]
NS_VOLUME = DataModel.GetObjectsByName("NS_Volume")[0]
NS_FACES5 = DataModel.GetObjectsByName("Faces5")[0]
NS_FACE1 = DataModel.GetObjectsByName("Face1")[0]
NS_FACE2 = DataModel.GetObjectsByName("Face2")[0]
# Scenario 4 Create Coordinate System: Create Coordinate System that will be used to define the results.
COORDINATE_SYSTEMS = Model.CoordinateSystems
GCS = COORDINATE_SYSTEMS.Children[0]
LCS = COORDINATE_SYSTEMS.AddCoordinateSystem()
LCS.OriginX = Quantity('0 [m]')
LCS.PrimaryAxis = CoordinateSystemAxisType.PositiveYAxis
LCS.AddTransformation(TransformationType.Rotation,CoordinateSystemAxisType.PositiveZAxis)
LCS.SetTransformationValue(1,-120)
BODY1.Material = 'Emag_Air'
BODY2.Material = 'Emag_Copper_Alloy'
# Scenario 6 - Define Mesh Settings: Assign Body Sizing with element size of 0.5 m.
BODY_SIZING = MESH.AddSizing()
BODY_SIZING.Location = NS_VOLUME
BODY_SIZING.ElementSize = Quantity('0.5 [m]')
MESH.GenerateMesh()
# Scenario 7 - Insert Magnetostatic loads: Insert and Magnetic Flux Parallel, Source Conductor with conductor type a
MAGNETIC_FLUX_PARALLEL = MAGNETOSTATIC.AddMagneticFluxParallel()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
328 of ANSYS, Inc. and its subsidiaries and affiliates.
Magnetostatic Analysis
MAGNETIC_FLUX_PARALLEL.Location = NS_FACES5
SOURCE_CONDUCTOR = MAGNETOSTATIC.AddSourceConductor()
SOURCE_CONDUCTOR.Location = NS_VOLUME2
SOURCE_CONDUCTOR.ConductorType = SourceConductorType.Solid
SOURCE_CONDUCTOR.NumberOfTurns = 1
SOURCE_CONDUCTOR_CURRENT = SOURCE_CONDUCTOR.AddCurrent()
SOURCE_CONDUCTOR_CURRENT.Location = NS_FACE1
SOURCE_CONDUCTOR_CURRENT.Magnitude.Output.DiscreteValues=[Quantity('0 [A]'), Quantity('-120 [A]')]
SOURCE_CONDUCTOR_VOLTAGE = SOURCE_CONDUCTOR.AddVoltage()
SOURCE_CONDUCTOR_VOLTAGE.Location = NS_FACE2
# Scenario 8 - Insert Results: Insert Directional Magnetic Field Intensity, Directional Magnetic Flux Density, Magne
DIRECTIONAL_MAGNETIC_FIELD_INTENSITY = SOLUTION.AddDirectionalMagneticFieldIntensity()
DIRECTIONAL_MAGNETIC_FIELD_INTENSITY.Location = NS_VOLUME1
DIRECTIONAL_MAGNETIC_FIELD_INTENSITY.NormalOrientation = NormalOrientationType.YAxis
DIRECTIONAL_MAGNETIC_FLUX_DENSITY = SOLUTION.AddDirectionalMagneticFluxDensity()
DIRECTIONAL_MAGNETIC_FLUX_DENSITY.Location = NS_VOLUME1
DIRECTIONAL_MAGNETIC_FLUX_DENSITY.NormalOrientation = NormalOrientationType.YAxis
DIRECTIONAL_FORCE01 = SOLUTION.AddMagneticDirectionalForces()
DIRECTIONAL_FORCE01.Location = NS_VOLUME2
DIRECTIONAL_FORCE02 = SOLUTION.AddMagneticDirectionalForces()
DIRECTIONAL_FORCE02.Location = NS_VOLUME2
DIRECTIONAL_FORCE02.NormalOrientation = NormalOrientationType.YAxis
DIRECTIONAL_FORCE03 = SOLUTION.AddMagneticDirectionalForces()
DIRECTIONAL_FORCE03.Location = NS_VOLUME2
DIRECTIONAL_FORCE03.NormalOrientation = NormalOrientationType.ZAxis
DIRECTIONAL_FORCE04 = SOLUTION.AddMagneticDirectionalForces()
DIRECTIONAL_FORCE04.Location = NS_VOLUME2
DIRECTIONAL_FORCE04.NormalOrientation = NormalOrientationType.YAxis
DIRECTIONAL_FORCE04.CoordinateSystem = LCS
DIRECTIONAL_FORCE05 = SOLUTION.AddMagneticDirectionalForces()
DIRECTIONAL_FORCE05.Location = NS_VOLUME2
DIRECTIONAL_FORCE05.NormalOrientation = NormalOrientationType.ZAxis
DIRECTIONAL_FORCE05.CoordinateSystem = LCS
FORCE_SUMMATION01 = SOLUTION.AddForceSummationProbe()
FORCE_SUMMATION01.GeometryLocation = NS_VOLUME2
FORCE_SUMMATION02 = SOLUTION.AddForceSummationProbe()
FORCE_SUMMATION02.GeometryLocation = NS_VOLUME2
FORCE_SUMMATION02.ResultSelection = ProbeDisplayFilter.YAxis
FORCE_SUMMATION03 = SOLUTION.AddForceSummationProbe()
FORCE_SUMMATION03.GeometryLocation = NS_VOLUME2
FORCE_SUMMATION03.ResultSelection = ProbeDisplayFilter.ZAxis
FORCE_SUMMATION04 = SOLUTION.AddForceSummationProbe()
FORCE_SUMMATION04.GeometryLocation = NS_VOLUME2
FORCE_SUMMATION04.ResultSelection = ProbeDisplayFilter.YAxis
FORCE_SUMMATION04.Orientation = LCS
FORCE_SUMMATION05 = SOLUTION.AddForceSummationProbe()
FORCE_SUMMATION05.GeometryLocation = NS_VOLUME2
FORCE_SUMMATION05.ResultSelection = ProbeDisplayFilter.ZAxis
FORCE_SUMMATION05.Orientation = LCS
TORQUE01 = SOLUTION.AddTorqueProbe()
TORQUE01.GeometryLocation = NS_VOLUME2
TORQUE02 = SOLUTION.AddTorqueProbe()
TORQUE02.GeometryLocation = NS_VOLUME2
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 329
End-to-End Analysis Examples
TORQUE02.ResultSelection = ProbeDisplayFilter.YAxis
TORQUE03 = SOLUTION.AddTorqueProbe()
TORQUE03.GeometryLocation = NS_VOLUME2
TORQUE03.ResultSelection = ProbeDisplayFilter.ZAxis
TORQUE04 = SOLUTION.AddTorqueProbe()
TORQUE04.GeometryLocation = NS_VOLUME2
TORQUE04.ResultSelection = ProbeDisplayFilter.YAxis
TORQUE04.Orientation = LCS
TORQUE05 = SOLUTION.AddTorqueProbe()
TORQUE05.GeometryLocation = NS_VOLUME2
TORQUE05.ResultSelection = ProbeDisplayFilter.ZAxis
TORQUE05.Orientation = LCS
# Scenario 9 - Solve and Define the Results: Solve the system and set the results variables. Note the Scripting wind
SOLUTION.Solve(True)
DIRECTIONAL_MAGNETIC_FIELD_INTENSITY_MAX = DIRECTIONAL_MAGNETIC_FIELD_INTENSITY.Maximum.Value
DIRECTIONAL_MAGNETIC_FLUX_DENSITY_MAX = DIRECTIONAL_MAGNETIC_FLUX_DENSITY.Maximum.Value
FORCE_SUMMATION01_X_AXIS = FORCE_SUMMATION01.XAxis.Value
FORCE_SUMMATION02_Y_AXIS = FORCE_SUMMATION02.YAxis.Value
FORCE_SUMMATION03_Z_AXIS = FORCE_SUMMATION03.ZAxis.Value
FORCE_SUMMATION04_Y_AXIS = FORCE_SUMMATION04.YAxis.Value
FORCE_SUMMATION05_Z_AXIS = FORCE_SUMMATION05.ZAxis.Value
TORQUE01_X_AXIS = TORQUE01.XAxis.Value
TORQUE02_Y_AXIS = TORQUE02.YAxis.Value
TORQUE03_Z_AXIS = TORQUE03.ZAxis.Value
TORQUE04_Y_AXIS = TORQUE04.YAxis.Value
TORQUE05_Z_AXIS = TORQUE05.ZAxis.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
• Mechanical_Post_Example.wbpz
• Mechanical_Post_Example.py
Procedure
1. Open the project file Mechanical_Post_Example.wbpz in the Workbench application.
2. Right-click the Model cell in the Project Schematic and the Edit option. This opens the project in
Mechanical.
3. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
330 of ANSYS, Inc. and its subsidiaries and affiliates.
Post Processing Options
4. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_Post_Graphics_Example_001.py.
5. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# -*- coding: UTF-8 -*-
#Scenario 1: Set up the Tree objects items and API base definitions. This step is necessary for all the API function
GEOM=Model.Geometry
MESH=Model.Mesh
STATIC_STRUCTURAL=Model.Analyses[0]
SOLUTION=STATIC_STRUCTURAL.Solution
CAMERA=Graphics.Camera
GRAPHICS_SETTINGS= Ansys.Mechanical.Graphics.GraphicsImageExportSettings()
LEGEND_SETTINGS=Ansys.Mechanical.Graphics.Tools.CurrentLegendSettings()
GLOBAL_SETTINGS=Graphics.GlobalLegendSettings
VIEW_OPTIONS=Graphics.ViewOptions
FOLDER_PATH='E:\\temp'
#Scenario 2: Insert results. This step would insert the results that we would use to demonstrate the different API a
TOTAL_DEFORMATION_RESULT=SOLUTION.AddTotalDeformation()
#Scenario 3: Setup the units system.
ExtAPI.Application.ActiveUnitSystem=MechanicalUnitSystem.StandardMKS
#Scenario 4: Clear and Solve
SOLUTION.ClearGeneratedData()
SOLUTION.Solve()
#Scenario 5: Change the Camera angles, Orientation and Export images. Change the export settings and repeat for a fe
#To fit the model to screen.
TOTAL_DEFORMATION_RESULT.Activate()
CAMERA.SetFit()
#To change the view to Front, back, Top etc., and export images with default settings. The images can be saved at a
CAMERA.SetSpecificViewOrientation(ViewOrientationType.Front)
Graphics.ExportImage(FOLDER_PATH +'\\ DEF1.png', GraphicsImageExportFormat.PNG, GRAPHICS_SETTINGS)
CAMERA.SetSpecificViewOrientation(ViewOrientationType.Back)
Graphics.ExportImage(FOLDER_PATH+'\\DEF2.png', GraphicsImageExportFormat.PNG, GRAPHICS_SETTINGS)
CAMERA.SetSpecificViewOrientation(ViewOrientationType.Right)
Graphics.ExportImage(FOLDER_PATH+'\\DEF3.png', GraphicsImageExportFormat.PNG, GRAPHICS_SETTINGS)
CAMERA.SetSpecificViewOrientation(ViewOrientationType.Left)
Graphics.ExportImage(FOLDER_PATH+'\\DEF4.png', GraphicsImageExportFormat.PNG, GRAPHICS_SETTINGS)
CAMERA.SetSpecificViewOrientation(ViewOrientationType.Top)
Graphics.ExportImage(FOLDER_PATH+'\\DEF5.png', GraphicsImageExportFormat.PNG, GRAPHICS_SETTINGS)
CAMERA.SetSpecificViewOrientation(ViewOrientationType.Bottom)
Graphics.ExportImage(FOLDER_PATH+'\\DEF6.png', GraphicsImageExportFormat.PNG, GRAPHICS_SETTINGS)
CAMERA.SetSpecificViewOrientation(ViewOrientationType.Iso)
Graphics.ExportImage(FOLDER_PATH+'\\DEF7.png', GraphicsImageExportFormat.PNG, GRAPHICS_SETTINGS)
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 331
End-to-End Analysis Examples
#Orient the legend horizontally, hide ruler, date and Time and triads.
GLOBAL_SETTINGS.LegendOrientation=LegendOrientationType.Horizontal
GLOBAL_SETTINGS.ShowDateAndTime=False
VIEW_OPTIONS.ShowTriad=False
VIEW_OPTIONS.ShowRuler=False
#Scenario 6: Change the Legend to display with different bands, scale, Color Scheme etc., and export those images as
#Change the number of bands in the legend to 4, color scale to Greyscale and change upper bound value of band 1 to a
LEGEND_SETTINGS.NumberOfBands=4
LEGEND_SETTINGS.ColorScheme=LegendColorSchemeType.GrayScale
LEGEND_SETTINGS.SetUpperBound(1,Quantity(0.4,'mm'))
#Scenario 9: Resetting to defaults. Execute this to unmake all the changes made in previous scenarios
LEGEND_SETTINGS.Reset()
Graphics.SectionPlanes.RemoveAt(0)
GLOBAL_SETTINGS.ShowDateAndTime=True
VIEW_OPTIONS.ShowTriad=True
VIEW_OPTIONS.ShowRuler=True
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
• Post_Processing_User_Defined_Results.wbpz
• Post_Processing_User_Defined_Results.py
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
332 of ANSYS, Inc. and its subsidiaries and affiliates.
Post Processing User Defined Results
Procedure
1. Open the project file Post_Processing_User_Defined_Results.wbpz in the Workbench
application.
2. Right-click the Model cell in the Project Schematic and the Edit option. This opens the project
in Mechanical.
3. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
4. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Post_Processing_User_Defined_Results.py.
5. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# -*- coding: UTF-8 -*-
#Scenario 1: Set up the Tree objects items and API base definitions. This step is necessary for all the API function
GEOM=Model.Geometry
MESH=Model.Mesh
STATIC_STRUCTURAL=Model.Analyses[0]
SOLUTION=STATIC_STRUCTURAL.Solution
#Scenario 2: Add different results from Tree. In this example we will add Total Deformation result, von Mises stress
TOTAL_DEFORMATION_RESULT=SOLUTION.AddTotalDeformation()
EQUIVALENT_STRESS_RESULT=SOLUTION.AddEquivalentStress()
NORMAL_STRESS=SOLUTION.AddNormalStress()
SEQV= SOLUTION.AddUserDefinedResult()
SEQV.Expression='SEQV'
SX= SOLUTION.AddUserDefinedResult()
SX.Expression='SX'
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 333
End-to-End Analysis Examples
SX.Identifier='SX_ID'
#Scenario 7: Use PlotData API to extract useful information from results. Here we show a snippet to access values at
SOLUTION.EvaluateAllResults()
PLOT_DATA_RESULT= EQUIVALENT_STRESS_RESULT.PlotData
def findNodeResult(nodeID,plotDataResult):
nodes=plotDataResult ['Node']
resultValue=plotDataResult ['Values']
if nodeID in nodes:
if nodes[index]==nodeID:
return resultValue[index]
else:
print("Given NodeID doesn't exist in result set")
VALUE2=findNodeResult(3, PLOT_DATA_RESULT)
print('The result value at node 3 is '+str(VALUE2))
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
• Mechanical_Random_Vibration_Example012_Geometry.agdb
• Mechanical_Random_Vibration_Example012_Script.py
Procedure
The following procedure assumes you understand how to add a system in Workbench and make changes
to system cells and properties as well as saving the support files to a known location.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
334 of ANSYS, Inc. and its subsidiaries and affiliates.
Random Vibration Analysis
2. Right-click the Solution cell of the Modal analysis and select Transfer Date To New > Random
Vibration. This links the two necessary systems.
3. This analysis requires a new material. Double-click the Engineering Data cell of the Modal analysis
to open the Engineering Data workspace.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 335
End-to-End Analysis Examples
7. Open the Isotropic Elasticity property and set the following values:
• Poisson's Ratio = 0
8. Return to the Project Schematic and select the Geometry cell of the Modal system. Right-click
and select Properties.
9. Under the Basic Geometry Options group of the properties, activate the Named Selections
property.
10. Right-click the Geometry cell and select Import Geometry > Browse and select the Mechanic-
al_Random_Vibration_Example012_Geometry.agdb file.
11. Right-click the Model cell and select Edit. This action launches the Mechanical application.
12. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
336 of ANSYS, Inc. and its subsidiaries and affiliates.
Random Vibration Analysis
13. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select Mechanical_Random_Vibration_Ex-
ample012_Script.py.
14. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Store main Tree Object items
MODEL = Model
GEOMETRY = Model.Geometry
ROD1 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Rod1'][0]
BLOCK1 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Block1'][0]
ROD2 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Rod2'][0]
BLOCK2 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Block2'][0]
ROD3 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Rod3'][0]
BLOCK3 = [x for x in ExtAPI.DataModel.Tree.AllObjects if x.Name == 'Block3'][0]
MATERIALS = MODEL.Materials
MATERIAL_RM = [i for i in MATERIALS.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) if i.Name == 'Rod_Ma
MATERIAL_SS = [i for i in MATERIALS.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) if i.Name == 'Struct
COORDINATE_SYSTEMS = Model.CoordinateSystems
GLOBAL_COORDINATE_SYSTEM = [i for i in COORDINATE_SYSTEMS.GetChildren[Ansys.ACT.Automation.Mechanical.CoordinateSyst
MESH = Model.Mesh
NAMED_SELECTIONS = ExtAPI.DataModel.Project.Model.NamedSelections
NS_BLOCK_SIDES = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i
NS_ROD_SIDES = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.N
NS_BASE = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if i.Name =
NS_BLOCK_ROD_SIDES = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True)
NS_BLOCK1_SIDES = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_BLOCK2_SIDES = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_BLOCK3_SIDES = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_BLOCK1_VERTEX = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_BLOCK2_VERTEX = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
NS_BLOCK3_VERTEX = [i for i in NAMED_SELECTIONS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) if
MODAL = DataModel.AnalysisByName("Modal")
ANALYSIS_SETTINGS_MODAL = MODAL.AnalysisSettings
SOLUTION_MODAL = MODAL.Solution
ROD1.Activate()
ROD1.BrickIntegrationScheme = BrickIntegrationScheme.Full
BLOCK1.Activate()
BLOCK1.BrickIntegrationScheme = BrickIntegrationScheme.Full
ROD2.Activate()
ROD2.BrickIntegrationScheme = BrickIntegrationScheme.Full
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 337
End-to-End Analysis Examples
BLOCK2.Activate()
BLOCK2.BrickIntegrationScheme = BrickIntegrationScheme.Full
ROD3.Activate()
ROD3.BrickIntegrationScheme = BrickIntegrationScheme.Full
BLOCK3.Activate()
BLOCK3.BrickIntegrationScheme = BrickIntegrationScheme.Full
ROD2.Activate()
ROD2.Material = MATERIAL_RM.Name
ROD3.Activate()
ROD3.Material = MATERIAL_RM.Name
MODEL.Activate()
REMOTE_POINT = MODEL.AddRemotePoint()
REMOTE_POINT.Location = NS_BLOCK2_SIDES
REMOTE_POINT.Behavior=LoadBehavior.Deformable
MODAL.Activate()
FRICTIONLESS_SUPPORT = MODAL.AddFrictionlessSupport()
FRICTIONLESS_SUPPORT.Location = NS_BLOCK_ROD_SIDES
TOTAL_DEFORMATION2_MODAL = SOLUTION_MODAL.AddTotalDeformation()
TOTAL_DEFORMATION2_MODAL.Mode = 2
TOTAL_DEFORMATION2_MODAL = SOLUTION_MODAL.AddTotalDeformation()
TOTAL_DEFORMATION2_MODAL.Mode = 3
ANALYSIS_SETTINGS_PSD.ConstantDamping=ConstantDampingType.Manual
ANALYSIS_SETTINGS_PSD.ConstantDampingRatio = 0
ANALYSIS_SETTINGS_PSD.StiffnessCoefficient = 0.0028
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
338 of ANSYS, Inc. and its subsidiaries and affiliates.
Random Vibration Analysis
DIRECTIONAL_VELOCITY_PSD = SOLUTION_PSD.AddDirectionalVelocityPSD()
DIRECTIONAL_VELOCITY_PSD.NormalOrientation=NormalOrientationType.XAxis
DIRECTIONAL_VELOCITY_PSD.ScaleFactor = ScaleFactorType.Sigma2
DIRECTIONAL_ACCELERATION_PSD = SOLUTION_PSD.AddDirectionalAccelerationPSD()
DIRECTIONAL_ACCELERATION_PSD.NormalOrientation=NormalOrientationType.XAxis
DIRECTIONAL_ACCELERATION_PSD.ScaleFactor = ScaleFactorType.Sigma3
NORMAL_ELASTIC_STRAIN_PSD = SOLUTION_PSD.AddNormalElasticStrain()
NORMAL_ELASTIC_STRAIN_PSD.NormalOrientation=NormalOrientationType.XAxis
NORMAL_ELASTIC_STRAIN_PSD.ScaleFactor = ScaleFactorType.Sigma1
NORMAL_STRESS_PSD = SOLUTION_PSD.AddNormalStress()
NORMAL_STRESS_PSD.NormalOrientation=NormalOrientationType.XAxis
NORMAL_STRESS_PSD.ScaleFactor = ScaleFactorType.Sigma1
SOLUTION_PSD.Activate()
RESPONSE_PSD_PROBE = SOLUTION_PSD.AddResponsePSD()
RESPONSE_PSD_PROBE.LocationMethod = LocationDefinitionMethod.CoordinateSystem
RESPONSE_PSD_PROBE.CoordinateSystemSelection=COORDINATE_SYSTEM
RESPONSE_PSD_PROBE.Reference=ResultRelativityType.Relative
RESPONSE_PSD_PROBE.ResultType = ProbeResultType.DeformationProbe
RESPONSE_PSD_PROBE.ResultSelection=ProbeDisplayFilter.XAxis
RESPONSE_PSD_PROBE2 = SOLUTION_PSD.AddResponsePSD()
RESPONSE_PSD_PROBE2.LocationMethod = LocationDefinitionMethod.RemotePoint
RESPONSE_PSD_PROBE2.RemotePointSelection = REMOTE_POINT
RESPONSE_PSD_PROBE2.Reference=ResultRelativityType.Relative
RESPONSE_PSD_PROBE2.ResultType = ProbeResultType.DeformationProbe
RESPONSE_PSD_PROBE2.ResultSelection=ProbeDisplayFilter.XAxis
SOLUTION_PSD.Activate()
SEL=ExtAPI.SelectionManager.AddSelection(NS_BLOCK3_VERTEX)
RS_PSD_TOOL = PSD.Solution.AddResponsePSDTool()
CLRSEL = ExtAPI.SelectionManager.ClearSelection()
RESPONSE_PSD_PROBE3 = RS_PSD_TOOL.Children[0]
RESPONSE_PSD_PROBE3.Name="Response PSD 3"
RESPONSE_PSD_PROBE3.Reference=ResultRelativityType.Relative
RESPONSE_PSD_PROBE3.ResultType = ProbeResultType.DeformationProbe
RESPONSE_PSD_PROBE3.ResultSelection=ProbeDisplayFilter.XAxis
SOLUTION_MODAL.Activate()
FREQUENCY = MODAL.GetResultsData()
MODAL_FREQ_1ST = FREQUENCY.ListTimeFreq[0]
MODAL_FREQ_2ND = FREQUENCY.ListTimeFreq[1]
MODAL_FREQ_3RD = FREQUENCY.ListTimeFreq[2]
DIRECTIONAL_DEFORMATION_PSD.Activate()
MAX_X_AXIS_DEF_PSD = DIRECTIONAL_DEFORMATION_PSD.Maximum.Value
DIRECTIONAL_VELOCITY_PSD.Activate()
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 339
End-to-End Analysis Examples
MIN_X_AXIS_VEL_PSD = DIRECTIONAL_VELOCITY_PSD.Minimum.Value
MAX_X_AXIS_VEL_PSD = DIRECTIONAL_VELOCITY_PSD.Maximum.Value
DIRECTIONAL_ACCELERATION_PSD.Activate()
MIN_X_AXIS_ACC_PSD = DIRECTIONAL_ACCELERATION_PSD.Minimum.Value
MAX_X_AXIS_ACC_PSD = DIRECTIONAL_ACCELERATION_PSD.Maximum.Value
NORMAL_ELASTIC_STRAIN_PSD.Activate()
MAX_X_AXIS_STRAIN_PSD = NORMAL_ELASTIC_STRAIN_PSD.Maximum.Value
NORMAL_STRESS_PSD.Activate()
MAX_X_AXIS_STRESS_PSD = NORMAL_STRESS_PSD.Maximum.Value
RESPONSE_PSD_PROBE.Activate()
RMS_VALUE_RES_PSD = RESPONSE_PSD_PROBE.RMSValue.Value
EXP_FREQ_RES_PSD = RESPONSE_PSD_PROBE.ExpectedFrequency.Value
RESPONSE_PSD_PROBE2.Activate()
RMS_VALUE_RES_PSD2 = RESPONSE_PSD_PROBE2.RMSValue.Value
EXP_FREQ_RES_PSD2 = RESPONSE_PSD_PROBE2.ExpectedFrequency.Value
RESPONSE_PSD_PROBE3.Activate()
RMS_VALUE_RES_PSD3 = RESPONSE_PSD_PROBE3.RMSValue.Value
EXP_FREQ_RES_PSD3 = RESPONSE_PSD_PROBE3.ExpectedFrequency.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
This example begins in the Mechanical application. It requires you to download the following files.
• External_Model.bfd
• External_Model.py
Procedure
1. Open Workbench and insert an External Model system, from the Component Systems group in
the Toolbox, into the Project Schematic.
3. From the External Model tab, select the option of the Location column and select Browse.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
340 of ANSYS, Inc. and its subsidiaries and affiliates.
Static Structural Analysis using External Model
4. Navigate to the proper folder location and select the sample file, External_Model.bfd.
6. Drag and drop a Static Structural system onto the Setup cell of the External Model system so
that it is linked as shown below.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 341
End-to-End Analysis Examples
9. Select the Automation tab and select the Scripting option to open the Mechanical Scripting pane.
10. Select the Open Script option ( ) from the Editor (p. 4) toolbar. Navigate to
the proper folder location and select External_Model.py.
11. Select the Run Script option ( ) from the Editor (p. 4) toolbar.
Scripts Illustrated
In this example, the python file automatically performs the following actions:
# Scenario 1 Set up the Tree Object Items: Define the geometry, coordinate system, connections, mesh, static system,
GEOMETRY= Model.Geometry
COORDINATE_SYSTEM = Model.CoordinateSystems
CONNECTIONS = Model.Connections
MESH = Model.Mesh
STATIC_STRUCTURAL = ExtAPI.DataModel.AnalysisByName("Static Structural")
ANALYSIS_SETTINGS = STATIC_STRUCTURAL.AnalysisSettings
SOLUTION= STATIC_STRUCTURAL.Solution
# Scenario 2 Set up Unit System: Set up the Unit Systems to Metric (m, kg, N, s, V, A)
ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS
# Scenario 3 Shell Thicknesses Imported from External Model: working with Get and Set methods for getting and settin
# Scenario 4 Point Masses Imported from External Model: working with Get and Set methods for getting and setting dif
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
342 of ANSYS, Inc. and its subsidiaries and affiliates.
Static Structural Analysis using External Model
POINT_MASSES_OBJECT1_INERTIAXZ = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("InertiaXZ")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("InertiaXZ", "0")
POINT_MASSES_OBJECT1_INERTIAXZ = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("InertiaXZ")
POINT_MASSES_OBJECT1_INERTIAYZ = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("InertiaYZ")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("InertiaYZ", "0")
POINT_MASSES_OBJECT1_INERTIAYZ = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("InertiaYZ")
POINT_MASSES_OBJECT1_OFFSETX = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("OffsetX")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("OffsetX", "10")
POINT_MASSES_OBJECT1_OFFSETX = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("OffsetX")
POINT_MASSES_OBJECT1_OFFSETY = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("OffsetY")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("OffsetY", "8")
POINT_MASSES_OBJECT1_OFFSETY = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("OffsetY")
POINT_MASSES_OBJECT1_OFFSETZ = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("OffsetZ")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("OffsetZ", "5")
POINT_MASSES_OBJECT1_OFFSETZ = POINT_MASSES_WORKSHEET[0].GetPropertyValueAsString("OffsetZ")
POINT_MASSES_WORKSHEET[1].SetPropertyValue("InertiaXY", "0")
POINT_MASSES_WORKSHEET[1].SetPropertyValue("InertiaXZ", "0")
POINT_MASSES_WORKSHEET[1].SetPropertyValue("InertiaYZ", "0")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("OffsetX", "0")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("OffsetY", "0")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("OffsetZ", "0")
POINT_MASSES_WORKSHEET[0].SetPropertyValue("Mass", "1e3")
# Scenario 5 Rigid Remote Connectors Imported from External Model: working with Get and Set methods for getting and
# Scenario 6 Flexible Remote Connectors Imported from External Model: working with Get and Set methods for getting a
# Scenario 7 Spring Connectors Imported from External Model: working with Get and Set methods for getting and settin
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 343
End-to-End Analysis Examples
SPRING_CONNECTORS_OBJECT4_LOCATION= SPRING_CONNECTORS_WORKSHEET[3].GetPropertyValueAsString("Location")
SPRING_CONNECTORS_OBJECT4_LOCATION_COORDINATE_SYSTEM = SPRING_CONNECTORS_WORKSHEET[3].GetPropertyValueAsString("Loca
SPRING_CONNECTORS_WORKSHEET[3].SetPropertyValue("GroundedNode", 2)
SPRING_CONNECTORS_OBJECT4_GROUNDEDNODE = SPRING_CONNECTORS_WORKSHEET[3].GetPropertyValueAsString("GroundedNode")
SPRING_CONNECTORS_WORKSHEET[3].SetPropertyValue("GroundedNode", 0)
SPRING_CONNECTORS_OBJECT4_GROUNDEDNODE = SPRING_CONNECTORS_WORKSHEET[3].GetPropertyValueAsString("GroundedNode")
SPRING_CONNECTORS_WORKSHEET.Suppressed = True
SPRING_CONNECTORS_WORKSHEET.Suppressed = False
# Scenario 8 Define Analysis Settings: Set Number of Steps is equal to 4 under details view of Analysis Settings.
ANALYSIS_SETTINGS.Activate()
ANALYSIS_SETTINGS.NumberOfSteps=4
SOLUTION.Activate()
TOTAL_DEFORMATION = SOLUTION.AddTotalDeformation()
# Scenario 10 Uncheck Point Masses, Rigid and Flexible connectors: Unchecking Point Mass, Rigid and Flexible connect
POINT_MASSES_WORKSHEET.Activate()
POINT_MASSES_WORKSHEET[0].Active = False
POINT_MASSES_WORKSHEET[1].Active = False
FLEXIBLE_REMOTE_CONNECTORS_WORKSHEET.Activate()
FLEXIBLE_REMOTE_CONNECTORS_WORKSHEET[0].Active = False
RIGID_REMOTE_CONNECTORS_WORKSHEET.Activate()
RIGID_REMOTE_CONNECTORS_WORKSHEET[0].Active = False
# Scenario 11 Solve and Review the Results: Solve the system and set the results variables. Note the Scripting windo
SOLUTION.Activate()
SOLUTION.Solve(True)
MAXIMUM_TOTAL_DEFORMATION = TOTAL_DEFORMATION.Maximum.Value
MINIMUM_TOTAL_DEFORMATION =TOTAL_DEFORMATION.Minimum.Value
Summary
This example demonstrates how scripting in Mechanical can be used to automate your actions.
Release 2023 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
344 of ANSYS, Inc. and its subsidiaries and affiliates.