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 2020 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 2020 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. v
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
vi 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
This section provides introductory information about scripting in Mechanical:
Mechanical Scripting View
Autocompletion
Snippets
Keyboard Shortcuts
Scope Selection for ACT Extensions
Release 2020 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 information, see
Scope Selection for ACT Extensions (p. 20).
• 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 2020 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.
3. Save Script As: Saves the script that you are working on to disk.
6. Promote Script to Snippet: Opens the Snippet Editor (p. 14) with fields already filled out using the
information from the script in the Editor.
7. Open Snippet Editor: Opens the Snippet Editor with empty fields so that you can create your own
script.
8. Button Editor: Opens the Button Editor. For more information, see Creating User-Defined Buttons
in the Mechanical User's Guide.
9. Promote Script to Button: Opens the Button Editor with fields already filled out using the inform-
ation from the script in the Editor.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 5
Scripting Introduction
1. Script name: Initially, New Script: Description is shown. When you click New Script, the field be-
comes editable so that you can specify the name and a description for the new script. When you
save or open a script, this field will display the file name.
2. Button for showing and hiding the area in which you describe the script.
Content Area
The content area is where you write scripts. This area provides autocompletion (p. 8) and the following
shortcuts:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
6 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical Scripting View
Toolbar
The toolbar for the Shell provides these buttons, which have these callotus in the previous figure:
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. 13) 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. 8).
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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 7
Scripting Introduction
• 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. 14), and the input field in the Shell all provide autocom-
pletion.
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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
8 of ANSYS, Inc. and its subsidiaries and affiliates.
Autocompletion
Color Syntax
Green Accessibility
Purple Type
Orange Warning
Blue Argument
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)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 9
Scripting Introduction
The tooltip for an overloaded method is a list of all members from all overloaded methods.
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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
10 of ANSYS, Inc. and its subsidiaries and affiliates.
Snippets
Supplied Snippets
Descriptions follow of all supplied snippets:
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. Inserts project = DataModel.Project, providing access to the project, which is the
top level of the hierarchy in the Mechanical tree. To interact with first-level objects in the tree, you
would then type a period and use the list of suggestion to select the attribute Model and then the
attribute for the first-level object. For example, these command line entries provide access to the
first-level tree objects Connections and Named Selections:
– 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.
• Analysis. Inserts analysis = Model.Analyses[0], providing access to the first analysis of the
model. As indicated earlier, Python starts counting at 0 rather than 1.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 11
Scripting Introduction
• 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
12 of ANSYS, Inc. and its subsidiaries and affiliates.
Snippets
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.
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:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 13
Scripting Introduction
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
14 of ANSYS, Inc. and its subsidiaries and affiliates.
Snippets
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.
4. Content area: Where you write the snippet that is to be inserted when the snippet inserter is used.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 15
Scripting Introduction
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:
1. Edit snippet: Opens the snippet in the Snippet Editor so that you can view and make changes to
the snippet.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
16 of ANSYS, Inc. and its subsidiaries and affiliates.
Keyboard Shortcuts
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 17
Scripting Introduction
Selection Shortcuts
Key Action
Combination
Ctrl + A
Shift + ← Select all
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
18 of ANSYS, Inc. and its subsidiaries and affiliates.
Keyboard Shortcuts
Key Action
Combination
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 19
Scripting Introduction
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
The following image shows the state of the tabs when supplied extensions AqwaLoadMapping and
AdditiveWizard are loaded:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
20 of ANSYS, Inc. and its subsidiaries and affiliates.
Scope Selection for ACT Extensions
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 21
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
22 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 geometry:
• The underlying Geometry, much like the Tree, is hierarchical. For example, DataModel.GeoData.As-
semblies[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 under-
stand 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 geo-
metry, mesh, simulation, and results, see Mechanical APIs (p. 29).
• 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 DataModel.MeshBy-
Name(“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:
contact_region_list = DataModel.GetObjectsByType(DataModelObjectCategory.ContactRegion)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 23
Key Usage Concepts
• 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 valida-
tions 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 re-
dundant 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 additional 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. 129)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
24 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 25
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
26 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 in-
stallation 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 27
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
28 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
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 31
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
32 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical API Notes
The following topics provide migration notes for those of you who have existing scripts for Mechanical
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.
Property change for Interface Delamination and SMART Crack Growth objects
For Interface Delamination and SMART Crack Growth objects, the enum type for the property Auto-
maticTimeStepping has changed to AutomaticOrManual.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 33
Mechanical API Notes
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.
Results using external solvers cannot be scoped to ElemNodal locations. This is not currently sup-
ported.
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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
34 of ANSYS, Inc. and its subsidiaries and affiliates.
Mechanical API Known Issues and Limitations
The ACT postprocessing API returns the results on orientation nodes when dealing with beam bodies,
even though these results are irrelevant.
– FileOpen
– FolderOpen
– PropertyTable
These controls are implemented using the ANSYS UI Toolkit, which is currently not supported on
Linux when executed within Mechanical.
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 35
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
36 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 37
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
38 of ANSYS, Inc. and its subsidiaries and affiliates.
Tree
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 39
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
40 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()
Combining the three previous actions, the geometry now contains a fully defined point mass.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 41
Object Access
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
42 of ANSYS, Inc. and its subsidiaries and affiliates.
Model Objects
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()
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()
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 43
Object Access
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
Object Traversal
The following topics describe how to traverse the objects Geometry, Mesh, and Results:
Traversing the Geometry
Traversing the Mesh
Traversing Results
Note:
• The sample code in this section is taken from the supplied extension TraverseExtension.
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
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
44 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Traversal
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
# +++ 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:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 45
Object Access
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
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
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
46 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Traversal
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)
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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 47
Object Access
f.write(str(now)+"\n")
#
# Get the element ids
#
meshObj = analysis.MeshData
elementids = meshObj.ElementIds
nodeids = meshObj.NodeIds
#
# Get the results reader
#
reader = analysis.GetResultsData()
reader.CurrentResultSet = int(1)
#
# Get the displacement result object
displacement = reader.GetResult("U")
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
#
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
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
48 of ANSYS, Inc. and its subsidiaries and affiliates.
Property APIs for Native Tree Objects
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()
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
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 49
Object Access
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. 118).
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)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
50 of ANSYS, Inc. and its subsidiaries and affiliates.
Solver Data
RemoveParameter("PropertyName")
For a scripting example, see Parametrize a Property for a Tree Object (p. 118).
Solver Data
You can use SolverData APIs to get solver-related data specific to an object or global items applicable
to the solver. Currently, SolverData APIs are available only for the MAPDL solver.
The following sections describe ways of using SolverData APIs to get global items and object-specific
data.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 51
Object Access
You can use SolverData APIs to retrieve object data for the following objects:
• AM Support
• 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. 120).
Note:
SolverData APIs are not available for objects imported using External Model systems.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
52 of ANSYS, Inc. and its subsidiaries and affiliates.
Boundary Conditions
This section describes APIs that enable you to manipulate boundary condition fields.
Unlike many other tree objects, boundary conditions are defined using both the Details view and tab-
ular 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
• 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.
• Free. This variable definition type is available only for certain boundary conditions such as displacements.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 53
Boundary Conditions
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).
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. 57).
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
54 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Variable Definition Types
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
d.ZComponent.Output.DefinitionType
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 55
Boundary Conditions
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
56 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 57
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
58 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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 59
Boundary Conditions
Adding a Load
You use the object Analysis to add a load. This topic describes adding loads to a static structural ana-
lysis.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
60 of ANSYS, Inc. and its subsidiaries and affiliates.
Adding a Load
static_structural = Model.Analyses[0]
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 61
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]')]
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
62 of ANSYS, Inc. and its subsidiaries and affiliates.
Extracting Min-Max Tabular Data for 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])
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 63
Boundary Conditions
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
64 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
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
This sample code creates the named selection object, renames it yo Pipe, changes the property
Define By to Worksheet, and stores a variable of the NamedSelectionCriteria object that can be
used to manipulate the data in the worksheet.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 65
Worksheets
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
66 of ANSYS, Inc. and its subsidiaries and affiliates.
Named Selection Worksheet
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 67
Worksheets
• 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
68 of ANSYS, Inc. and its subsidiaries and affiliates.
Mesh Order Worksheet
• 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 69
Worksheets
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
70 of ANSYS, Inc. and its subsidiaries and affiliates.
Layered Section Worksheet
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 71
Worksheets
• 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.
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
72 of ANSYS, Inc. and its subsidiaries and affiliates.
Bushing Joint Worksheet
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 73
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
74 of ANSYS, Inc. and its subsidiaries and affiliates.
Graphics
This section describes APIs related to graphics:
Manipulating Graphics
Exporting Graphics
Exporting Result or Probe Animations
Creating Section Planes
Setting Model Lighting Properties
Manipulating Graphics
You can use the MechanicalCameraWrapper to manipulate the camera for precise control of model
visualization.
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
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 75
Graphics
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.
Example 1
This code rotates the model by 30 degrees about the direction normal to the current screen display:
camera.Rotate(30, CameraAxisType.ScreenZ)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
76 of ANSYS, Inc. and its subsidiaries and affiliates.
Manipulating Graphics
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.
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 orientation. The
scene, defined by SceneWidth and SceneHeight, is then scaled in or out, maintaining the aspect
ratio until the height equals the viewport height.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 77
Graphics
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.
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).
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
78 of ANSYS, Inc. and its subsidiaries and affiliates.
Manipulating Graphics
5. If you enlarge the viewport panel in either direction, the scene parameters still hold their shape.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 79
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.
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, TIF, BMP, or EPS file
age
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
80 of ANSYS, Inc. and its subsidiaries and affiliates.
Exporting Result or Probe Animations
setting3d = Ansys.Mechanical.Graphics.Graphics3DExportSettings()
Graphics.Export3D("c:\\temp\\binarySTL.stl", Graphics3DExportFormat.BinarySTL, setting3d)
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)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 81
Graphics
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
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
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
82 of ANSYS, Inc. and its subsidiaries and affiliates.
Creating Section Planes
Command Description
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:
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 83
Graphics
Example 2
This code modifies the direction of the section plane:
sectionPlane.Direction = Vector3D(0, 1, 0)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
84 of ANSYS, Inc. and its subsidiaries and affiliates.
Creating Section Planes
Example 3
This code gets the existing section plane and changes its name:
sectionPlane = Graphics.SectionPlanes[1]
sectionPlane.Name = "Plane2"
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 85
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:
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
The following image shows model lighting properties being set in the Details view for the model:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
86 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Model Lighting Properties
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
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 87
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
88 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
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 89
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).
• ElementalNodal: Results are calculated on the element but then interpolated onto the nodes (like
stresses)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
90 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
1. In the Outline view, select Solution, which activates the Worksheet tab.
3. Right-click a result in the table and select Create User Defined Result.
4. In the Outline view, right-click and select Evaluate All Results to generate contour results for the
new user-defined result.
5. To display the contour results in the tabular data interface, enter these commands:
result=Model.Analyses[0].Solution.Children[1]
result.PlotData
For a Nodal type, the results table has only node information:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 91
Results
For an Elemental type, the results table has only element information:
For an ElementalNodal type, you must select an ElementalNodal result from the worksheet and
evaluate with Unaveraged set for Display Option in the Details view of the result:
When you display contour results for an ElementalNodal type in the tabular data interface, the results
table has both node and element information:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
92 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
Similarly, you can generate contour results with different result styles. Here is the command and
output for an unaveraged tensor strain:
To access the independent and dependent variables, you enter the following commands:
tablename.Independents
tablename.Dependents
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 93
Results
To display a column's count and units for the dependants of the table, you enter this command:
tablename[columnName]
You can retrieve the unit and the count of the column values using this snippet:
value = tablename[columnName]
value.Unit
value.Count
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
94 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
After the contour results are evaluated, the following code accesses them in the tabular data interface:
# Total Deformation Scoped to Nodes
print(" Result 3 : Total Deformation Nodes")
result3 = Model.Analyses[0].Solution.Children[3]
result3.PlotData
The following format applies for results scoped to a geometry face, element face, or a vertex:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 95
Results
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
96 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
After the contour results are evaluated, the following code accesses them in the tabular data interface:
print(" Result 5 : Nodal")
result5 = Model.Analyses[0].Solution.Children[5]
result5.PlotData
The result is scoped to the X, Y, and Z coordinates of the path sampling points:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 97
Results
The following code accesses the evaluated contour results in the tabular data interface:
result = Model.Analyses[0].Solution.Children[3]
result.PlotData
When Position is set to onlyTop, onlyBottom, or onlyMiddle, the output has two values per
node:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
98 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Contour Results for an Evaluated Result
• 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.
• 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).
• When the result is scoped to more than one body, nodes shared by bodies might appear as multiple
entries in the table, with the same or different result values. It may not be possible to determine the
body for a given entry because no such information is presented in the table.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 99
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
100 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
Interacting with Legacy JScript
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")
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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 101
Other APIs
Object Tags
You can use APIs to access object tags and to add or remove them:
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
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
102 of ANSYS, Inc. and its subsidiaries and affiliates.
Interacting with Legacy JScript
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)
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)""")
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 103
Other APIs
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
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);
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
104 of ANSYS, Inc. and its subsidiaries and affiliates.
Interacting with Legacy JScript
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);
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.
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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 105
Other APIs
x = [1, 2, 3, 5]
script = """
var x = """ + str(x) + """;
x[3] = 10;
returnFromScript(x);
"""
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.
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
106 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
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 109
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
110 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()
Criterion2.Action = SelectionActionType.Add
Criterion2.EntityType = SelectionType.GeoFace
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 111
Script Examples for Selection
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
112 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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 113
Script Examples for Selection
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
114 of ANSYS, Inc. and its subsidiaries and affiliates.
Create a Selection Based on the Location of Nodes in Y
return \
TriangleArea( \
[element_face_nodes[0].X, element_face_nodes[0].Y, element_face_nodes[0].Z], \
[element_face_nodes[1].X, element_face_nodes[1].Y, element_face_nodes[1].Z], \
[element_face_nodes[2].X, element_face_nodes[2].Y, element_face_nodes[2].Z]) + \
TriangleArea( \
[element_face_nodes[0].X, element_face_nodes[0].Y, element_face_nodes[0].Z], \
[element_face_nodes[2].X, element_face_nodes[2].Y, element_face_nodes[2].Z], \
[element_face_nodes[3].X, element_face_nodes[3].Y, element_face_nodes[3].Z])
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)
Code:
# Get access to mesh
mesh = DataModel.MeshDataByName(ExtAPI.DataModel.MeshDataNames[0])
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 115
Script Examples for Selection
# 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 here to download the archived
ANSYS project.
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
116 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
Get All Visible Properties for a Tree Object
Parametrize a Property for a Tree Object
Count the Number of 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
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 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
Coordinate System Math
Delete an Object
Goal: Delete a selected object from the tree.
Code:
ObjToDelete.Delete()
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 117
Script Examples for Interacting with Tree Objects
Code:
Tree.Refresh()
Code:
force = Model.Analyses[0].AddForce()
for forceProperty in force.VisibleProperties:
print(forceProperty.Caption + " | " + forceProperty.StringValue)
Code:
hydrostaticPressure = Model.Analyses[0].AddHydrostaticPressure()
fluidDensity = hydrostaticPressure.CreateParameter("FluidDensity")
fluidDensity.ID
Code:
contacts = DataModel.GetObjectsByType(DataModelObjectCategory.ContactRegion)
numContacts = contacts.Count
print("There are %s contact regions" % (numContacts) )
Code:
geom=DataModel.GeoData
contacts = DataModel.GetObjectsByType(DataModelObjectCategory.ContactRegion)
with Transaction():
for cont in contacts:
source_area = 0
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
118 of ANSYS, Inc. and its subsidiaries and affiliates.
Suppress Bodies Contained in a Given Named Selection
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:
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"
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 119
Script Examples for Interacting with Tree Objects
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]')]
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
120 of ANSYS, Inc. and its subsidiaries and affiliates.
Export Result Images to Files
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")
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 121
Script Examples for Interacting with Tree Objects
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:
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)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
122 of ANSYS, Inc. and its subsidiaries and affiliates.
Work with Solution Combinations
u_result.CalculateTimeHistory = False
tag2.AddObject(u_result)
tag3.AddObject(u_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
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)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 123
Script Examples for Interacting with Tree Objects
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
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]")]
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 = []
facesMinus = []
for part in parts:
for body in part.Bodies:
distBody = GetSignedDistanceFromPointToPlane(body.Centroid, planeOrigin, planeNormal)
for face in body.Faces:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
124 of ANSYS, Inc. and its subsidiaries and affiliates.
Access Contour Results for an Evaluated Result
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()
masterSel = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
masterSel.Entities = facesColls[0]
slaveSel = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
slaveSel.Entities = facesColls[1]
nodeMergeObj.MasterLocation = masterSel
nodeMergeObj.SlaveLocation = slaveSel
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 125
Script Examples for Interacting with Tree Objects
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 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
126 of ANSYS, Inc. and its subsidiaries and affiliates.
Coordinate System Math
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]))
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)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 127
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
128 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
Scan Results, Suppress Any with Invalid Display Times, and Evaluate
Check Version
Check Operating Environment
Retrieve Stress Results
Search for Keyword and Export
Modify Export Setting
Pan the Camera
Functions to Draw
Export All Result Animations
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
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:
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 129
Script Examples for Interacting with the Mechanical Session
obj.Suppressed = True
sol.EvaluateAllResults()
Check Version
Goal: Check the version in which your user is operating.
Code:
import Ansys.Utilities
from Ansys.Utilities import ApplicationConfiguration
---
ansysVersion = ApplicationConfiguration.DefaultConfiguration.VersionInfo.VersionString
Code:
import Ansys.Utilities
from Ansys.Utilities import ApplicationConfiguration
---
isUnix = ApplicationConfiguration.DefaultConfiguration.IsUnix
Code:
reader = Model.Analyses[0].GetResultsData()
reader.CurrentResultSet=1
S=reader.GetResult("S")
S.GetElementValues(1)
reader.Dispose()
Code:
path = "C:\\"
n = 0
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
130 of ANSYS, Inc. and its subsidiaries and affiliates.
Functions to Draw
sol_obj.Activate()
Graphics.ExportImage(path + sol_obj.name + ".png")
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
#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]
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 131
Script Examples for Interacting with the Mechanical Session
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
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)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
132 of ANSYS, Inc. and its subsidiaries and affiliates.
Functions to Draw
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))
coll.Factory2D.CreateText(point, str(i + j + k))
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)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 133
Script Examples for Interacting with the Mechanical Session
Code:
#Set camera and view
cam = Graphics.Camera
cam.SetSpecificViewOrientation(ViewOrientationType.Right)
#Animation settings
Graphics.ResultAnimationOptions.NumberOfFrames = 10
Graphics.ResultAnimationOptions.Duration = Quantity(2, 's')
settings = Ansys.Mechanical.Graphics.AnimationExportSettings(width = 1000, height = 665)
Release 2020 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
134 of ANSYS, Inc. and its subsidiaries and affiliates.