Documente Academic
Documente Profesional
Documente Cultură
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: 2008 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 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. iii
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
iv of ANSYS, Inc. and its subsidiaries and affiliates.
Introduction to Scripting
Scripting refers to the use of a programming language to interact with and modify a software product.
To customize ANSYS products, you write scripts using ANSYS ACT and its powerful API (Application
Programming Interface). This particular document is intended for ACT novices who want to leverage
the ACT Console to write small and simple scripts for automating ANSYS Mechanical.
The next chapter, Script Examples (p. 9), supplies many sample scripts for completing tasks in Mech-
anical.
What is ACT?
ACT is the unified and consistent tool for the customization and expansion of ANSYS products. By
leveraging its Python-based API, you can tailor ANSYS Mechanical and other ANSYS products to meet
your application-specific and multi-physics simulation needs.
Because ACT allows you to create customization apps, you can modify existing capabilities and even
add new modules, giving you the power to make ANSYS products look and act just like you want.
For instance, you can use ACT to add functionality and operations of your own to the native function-
ality already available in Mechanical.
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 1
Introduction to Scripting
Within the ACT Console, you use the command line to write your scripts and then store the blocks of
code that you use repeatedly as snippets. You can move the ACT Console to other locations and dock
it, just as you do with native Mechanical windows.
This stands for Extension API and is the gateway into the ACT API. Once you type the period (.), you are
in the API. The ACT Console provides "smart" autocompletion, which means it takes syntax elements
such as brackets or quotations marks into account. As you type in the command line, a scrollable list
of suggestions is displayed above the command line. Each suggestion has an icon with a letter and
color-coding.
• A letter in a square icon describes the type of a member, such as P for property or M for method.
• A letter in a circle icon describes the nature of the return type for a selected member, such as C for class
or E for enumeration.
See Using Autocompletion in the ANSYS ACT Developer's Guide for more information about member
types and return types.
After typing ExtAPI., DataModel is one of the many member types shown in the list of suggestions.
This property accesses the Mechanical tree. When you place the mouse cursor over any suggestion in
the list, the tooltip provides information about it. Clicking a suggestion inserts it in the command line,
where you then type any string that might be required followed by a period to see the next set of
available suggestions.
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
2 of ANSYS, Inc. and its subsidiaries and affiliates.
Command Line Usage
In the command line, pressing Ctrl + ↑ gives you access to the previous command shown in the com-
mand history.
A step-by-step example follows for building a command that returns the volume for a specific part
body:
• ExtAPI.DataModel.GeoData.Assemblies[0].Parts[0].Bodies[0].Volume. – Provides
access to the volume for this body.
Pressing Enter after constructing this command returns the volume of the first body in the GeoData
hierarchy.
The next example shows how autocompletion helps you to construct the following command:
ExtAPI.DataModel.Project.Geometry.ElementControl = ElementControl.Manual
As you select the ElementControl property during command construction, the suggestion tooltip
indicates that you must get or set the enumeration return type to ElementControl. Once you do
this, the suggestion tooltip prompts you to select either Manual or Program Controlled.
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 3
Introduction to Scripting
While simple, these two examples demonstrate how you use the ACT Console to access information.
If you understand these examples, you are well on your way to writing scripts for the Mechanical interface.
Additionally, you can refer to Script Examples (p. 9) to see scripts for performing many different types
of tasks in Mechanical.
Snippets
Snippets are existing lines of code that can quickly and easily be inserted in the command line, saving
you from repetitive typing. As you use the ACT Console, you can insert any of the snippets that ANSYS
supplies for ACT-specific commands. Additionally, you can begin building your own library of snippets
to either supplement or replace the supplied snippets with your own custom snippets.
The ExtAPI snippet inserts ExtAPI. in the command line, providing you with immediate access to
the API. From the autocomplete options in the tooltip, you can then begin selecting additional attributes
to build your command.
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
4 of ANSYS, Inc. and its subsidiaries and affiliates.
Snippets
The Snippet Template snippet 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.
The Helpers folder provides snippets for frequently used commands. Descriptions follow of all snippets
in this folder:
• Project. Inserts ExtAPI.DataModel.Project, providing access to the project, which is the top
level of the hierarchy in the Mechanical tree. If you wanted to explore the model tree and interact with
first-level objects, you would use the tooltip to select the Model attribute and then the attribute for
the first-level object. The next two snippets in this folder provide object access, as do the following
command line entries:
• solution = ExtAPI.DataModel.Tree.GetObjectsByName("pressure")
• Quantity. Inserts Quantity("1 [mm]", providing a command method in which you can declare
values. Three examples follow:
– pres = ExtAPI.DataModel.Project.Model.Analyses[0].AddPressure()
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 5
Introduction to Scripting
Lastly, the Examples folder provides snippets that you can use as templates. For example, the Add
Pressure Template snippet shows how to create a pressure on the first face of the first body of the
first part.
To see all snippets, including those predefined for standard Python commands, you can press Ctrl +
space when nothing is entered in the command line and then scroll through the autocompletion sug-
gestions, which includes both variables and snippets. Although you can remove snippets for ACT-spe-
cific commands by deleting them from the Snippets panel, you cannot delete the snippets predefined
for standard Python commands. For more information, see Using Snippets.
• In ExtAPI.DataModel, DataModel refers to the Mechanical tree. Virtually any operation that involves
information in the tree begins with ExtAPI.DataModel. As demonstrated by bookmarks supplied in the
Helpers folder, you can find objects in the tree by searching for object names and types or by accessing a
list of all selected objects.
• It is important to understand a key but subtle distinction between two ways of dealing with the mesh:
– ExtAPI.DataModel.Project.Model.Mesh accesses the mesh tree object and thus its methods
and controls
• It is important to understand a key but subtle distinction between two ways of dealing with the geometry:
• When accessing GeoData, you must use the tree hierarchy. For example, ExtAPI.DataMod-
el.GeoData.Assemblies[0].Parts[0].Bodies[0].Volume accesses the volume for the body
of the first part in the first assembly. While attribute names such as Assemblies[0], Parts[0], and
Bodies[0] are plural, only the specified assembly, part, and body are accessed.
• All bodies have parts as their parents, even if they are not multibody parts. This is important to understand
in both GeoData and when traversing the Geometry object of the DataModel. Although a part might
be hidden from the Mechanical interface, the part is always there.
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
6 of ANSYS, Inc. and its subsidiaries and affiliates.
Key Usage Concepts
• You can use the ACT Console to both get and set properties on an object. For example, assume that you
want to get the variable definition types for the X, Y, and Z components of a displacement that has previously
been defined as d. You would execute the following commands in the ACT Console, one at a time:
– d.XComponent.Output.DefinitionType
– d.YComponent.Output.DefinitionType
– d.ZComponent.Output.DefinitionType
Now assume that you want to change the variable definition type for the Y component from Free
to Discrete and then verify the change and output value in the ACT Console. You would execute
the following commands:
– d.YComponent.Output.DefinitionType =VariableDefinitionType.Discrete
– d.YComponent.Output.DefinitionType
– d.YComponent.Output
For more information on accessing the properties of an object, including those for traversing the
geometry, mesh, simulation, and results, see the following topics in the APIs for ANSYS Mechanical
section of the ANSYS ACT Developer’s Guide:
– Tree Object
– Model Object
– TraverseExtension
• It is far better to create objects and access them rather than recalling the API over and over with the use of
ExtAPI in your commands. For example, using the following three commands is superior to calling ExtAPI
in the second and third commands:
– mesh = ExtAPI.DataModel.MeshDataByName("Global")
– mesh.ElementCount
– mesh.NodeCount
• Looping is a fundamental concept in any scripting language. Within a Geometry object, you can use loops
to add, modify, or export property data. The following script loops over all contacts and change their formu-
lation to MPC:
contact_region_list = ExtAPI.DataModel.Project.Model.GetChildren(DataModelObjectCategory.ContactRegion, True)
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 7
Introduction to Scripting
• Lastly, if you cannot find what you want, check the InternalObject attribute. 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 Mechanical tasks using scripts, see Script Ex-
amples (p. 9)
Additional Resources
To help you use scripts in Mechanical, many ACT resources are available.
• The ACT Resources page on the ANSYS Customer Portal provides links for viewing or downloading ACT
templates, documentation, examples, and training. To access this page from the ANSYS Customer
Portal, select Downloads > ACT Resources.
• The ANSYS App Store provides an array of free and paid apps developed by ANSYS and our trusted
partners to further expand the capabilities of our solutions.
• Additionally, you can refer to the installed Python scripts that Mechanical uses. These scripts are in your
ANSYS installation directory at .../aisol/DesignSpace/DSPages/Python. The most useful
ones are toolbar.py and selection.py, which are used by the Selection Utility toolbar. For more
information, see Selection Utilities in the ANSYS Mechanical User’s Guide
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
8 of ANSYS, Inc. and its subsidiaries and affiliates.
Script Examples
This chapter 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:
Script Examples for Selection
Script Examples for Interacting with Tree Objects
Script Examples for Interacting with the Mechanical Session
From the ANSYS Customer Portal, you can search solutions for additional script examples. After selecting
Knowledge Resources > Solutions, make the following filter selections in the left column:
To further limit the solution shown, you can use the search box at the top of the page.
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 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 9
Script Examples
Code:
myIds = ExtAPI.SelectionManager.CurrentSelection.Ids
geoBody = ExtAPI.DataModel.GeoData.GeoEntityById(myIds[0])
treeBody = ExtAPI.DataModel.Project.Model.Geometry.GetBody(geoBody)
Code:
treeBody = ExtAPI.DataModel.Project.Model.Geometry.Children[0].Children[0]
geoBody = treeBody.GetGeoBody()
Code:
# Macro to demonstrate how to query mesh information for the active selection
meshData = ExtAPI.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 = ExtAPI.DataModel.Tree.FirstActiveObject
myres.ClearGeneratedData()
myres.Location = mysel
myres.EvaluateAllResults()
Code:
clr.AddReference("Ans.UI.Toolkit")
from Ansys.UI.Toolkit import *
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
10 of ANSYS, Inc. and its subsidiaries and affiliates.
Script Examples for Interacting with Tree Objects
sel = ExtAPI.SelectionManager.CurrentSelection.Ids
sum = 0
Delete an Object
Goal: Delete a selected object from the Mechanical tree.
Code:
ObjToDelete.Delete()
Code:
ExtAPI.DataModel.Tree.Refresh()
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 11
Script Examples
Code:
contact_region_list = ExtAPI.DataModel.Project.Model.GetChildren(DataModelObjectCategory.ContactRegion, True)
contact_region_list.Count()
Code:
geom = ExtAPI.DataModel.GeoData
for n in range(0,contacts.Count):
cont = contacts[n]
source_area = 0
sourcenum = cont.SourceLocation.Ids.Count
for x in range(0,sourcenum):
myface = geom.GeoEntityById(cont.SourceLocation.Ids[x])
source_area = source_area + myface.Area
target_area = 0
targetnum = cont.TargetLocation.Ids.Count
for x in range(0,targetnum):
myface = geom.GeoEntityById(cont.TargetLocation.Ids[x])
target_area = target_area + myface.Area
Code:
contacts = ExtAPI.DataModel.Project.Model.GetChildren(DataModelObjectCategory.ContactRegion,True)
changeCount = 0
for cont in contacts:
if (cont.ContactType == ContactType.Frictionless) :
cont.PinballRegion = ContactPinballType.Radius
cont.PinballRadius = Quantity("5[mm]")
changeCount = changeCount + 1
Code:
load = ExtAPI.DataModel.Project.Model.Analyses[0].AddPressure()
ns = ExtAPI.DataModel.Project.Model.NamedSelections.Children[0]
load.Location = ns
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
12 of ANSYS, Inc. and its subsidiaries and affiliates.
Script Examples for Interacting with Tree Objects
Code:
ns = ExtAPI.DataModel.Project.Models[0].NamedSelections.Children[0] # selected a named selection containing bodie
bodyIds = ns.Location.Ids
Code:
pressureLoad=ExtAPI.DataModel.Project.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 = ExtAPI.DataModel.Tree.FirstActiveObject
for n in range(0,nDiv+1):
angle = Quantity(str(n*angleInc) + ' [degree]')
BaseResult.Duplicate()
newResult = ExtAPI.DataModel.Tree.FirstActiveObject
newResult.SweepingPhase = angle
newResult.Name = 'Sweep At ' + str(n*angleInc)
Code:
result = ExtAPI.DataModel.Project.Model.Analyses[0].Solution.Children[1]
result.ExportToSTLFile("E:\\test.stl")
Code:
# get a list of all the results in the project
results =ExtAPI.DataModel.Tree.GetObjectsByType(DataModelObjectCategory.Result)
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 13
Script Examples
# export the result to avz file using the result name for the filename
mvm = ExtAPI.Graphics.ModelViewManager
avzFilename = "D:\\Images\\" + result.Name + ".avz"
mvm.Capture3DImage(avzFilename)
Code:
# create a solution combination object combining 2 environments
sc = ExtAPI.DataModel.Project.Model.AddSolutionCombination()
ws = sc.Worksheet
ws.AddRow()
ws.SetCoefficient(0,1.234)
ws.SetEnvironmentId(0, envs[0].ObjectId)
ws.SetTime(0,1)
if envs.Count < 2:
print "There are not 2 or more environments"
else:
ws.AddRow()
ws.SetCoefficient(1,2)
ws.SetEnvironmentId(1, envs[1].ObjectId)
Code:
#The following example creates a pressure on the first face of the first body for the first part.
model = ExtAPI.DataModel.Project.Model
pressure = model.Analyses[0].AddPressure()
part1 = model.Geometry.Children[0]
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]")]
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
14 of ANSYS, Inc. and its subsidiaries and affiliates.
Script Examples for Interacting with the Mechanical Session
Code:
From time import clock, time
for x in range(0, 5):
ExtAPI.DataModel.Project.Model.ClearGeneratedData()
t1 = time()
ExtAPI.DataModel.Project.Model.Mesh.GenerateMesh()
t2 = time()
print "Stats for mesh %d, elapsed time=%d" % (x+1, t2-t1)
print ExtAPI.DataModel.Project.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 = ExtAPI.DataModel.Project.Model.Analyses[0].AnalysisSettings
OrigStep = aset.CurrentStepNumber
aset.CurrentStepNumber = aset.NumberOfSteps
FinalTime = aset.StepEndTime
aset.CurrentStepNumber = OrigStep
sol = ExtAPI.DataModel.Project.Model.Analyses[0].Solution
for obj in sol.Children:
if hasattr(obj,"DisplayTime"):
if obj.DisplayTime > FinalTime:
obj.Suppressed = True
sol.EvaluateAllResults()
Check Version
Goal: Check the version in which your user is operating.
Code:
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
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 15
Script Examples
Code:
reader=ExtAPI.DataModel.AnalysisList[0].GetResultsData()
reader.CurrentResultSet=1
S=reader.GetResult("S")
S.GetElementValues(1)
reader.Dispose()
Code:
path = "C:\\"
n = 0
model = ExtAPI.DataModel.Project.Model
view_manager = ExtAPI.Graphics.ModelViewManager
Code:
ExtAPI.Application.ScriptByName("jscript").ExecuteCommand('WB.PreferenceMgr.Preference("PID_Show_Node_Numbers") =
Code:
ExtAPI.Application.ScriptByName("jscript").ExecuteCommand("DS.Script.msgGrid.Refresh();")
Release 18.2 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
16 of ANSYS, Inc. and its subsidiaries and affiliates.