ACT APIs For Mechanical Guide
ACT APIs For Mechanical Guide
ACT APIs For 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: 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 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. iii
ACT APIs for Mechanical Guide
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
iv of ANSYS, Inc. and its subsidiaries and affiliates.
ACT API Introduction
The ACT API (Application Programming Interface) provides access to the native functionality of ANSYS
Mechanical. Using APIs, you can access all objects in the Mechanical tree (Project, Model, and Ana-
lysis). With APIs, you can write scripts to not only manipulate existing objects and their properties
but also create new ones.
Note
When you create an object, Mechanical initializes its property values in the Details window
to the same default values used when you add an object via standard mouse-click operations.
Some properties, such as scoping or the mass of a point mass, can be invalid until you enter
a value.
Other ANSYS guides provides related information in which you might be interested:
• For an introduction to writing scripts for Mechanical, see the Scripting in Mechanical Quick Start Guide.
• For descriptions of all ACT API objects, methods, and properties, see the ANSYS ACT API Reference Guide.
• For information on how to use ACT to create apps (extensions) that customize and automate ANSYS
products, see the ANSYS ACT Developer's Guide.
• For ACT usage, customization, and automation information specific to Mechanical, see the ANSYS ACT
Customization Guide for Mechanical.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 1
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
2 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Access
Using the ACT API, you can programmatically navigate the Mechanical tree to access objects. The root
node of the tree is ExtAPI.DataModel.Project.
Each tree node has children that you can access by calling the property Children. This returns all
child nodes in the project.
You can also call nested objects, such as Model, Geometry, Mesh, or Solution, to access all instances
of a given object or tree level.
Mesh = ExtAPI.DataModel.Project.Model.Mesh
Connection = ExtAPI.DataModel.Project.Model.Children[3]
Property Types
Each object in the tree has its own set of properties. Descriptions and examples of supported property
types follow:
Example:
my_object.ElementSize = Quantity("0.1 [m]")
Numerical Value (float and integer): A property, such as Relevance or Rate, expecting a numerical
value. No unit is specified for this number.
Example:
my_object.TetraGrowthRate = 2
Example:
my_object.WriteICEMCFDFiles = True
Geometry Scoping: A property whose value is one or more geometric entities. In this case, you must:
1. Create selection information and specify the IDs of the entities that you want to manipulate.
Example:
my_selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
my_selection.Ids= [28,25]
My_object.Location = my_selection
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 3
Object Access
Tree Objects
The API Ansys.ACT.Automation.Mechanical.Tree provides access to data contained within
the Mechanical tree.
To access the object Tree, you use ExtAPI.DataModel.Tree. The following table provides a
sampling of the APIs available for querying the tree for contained objects. Some usage examples appear
after the table. For a comprehensive list of API members, see the ANSYS ACT API Reference Guide.
Member Description
ActiveObjects Lists all selected objects. Read-only.
AllObjects Lists all of the objects available in the tree.
Read-only.
GetObjectsByName Lists all objects that match the specified name.
GetObjectsByType Lists all objects that match the specified type.
In the ACT Console, you enter commands to query the tree for contained objects.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
4 of ANSYS, Inc. and its subsidiaries and affiliates.
Tree Objects
Note
Refreshing the tree can cause performance issues when executing a script that adds many
objects, such as in a loop. To prevent a refresh until the loop completes, use the object
Transaction() as shown in this sample code:
with Transaction():
for i in range(5):
ExtAPI.DataModel.Project.AddComment()
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 5
Object Access
Model Objects
In the Mechanical tree, you can access and manipulate model objects. The following topics describe
the objects Geometry, Mesh, Connections, and Analysis:
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 to define new child objects. For example,
you can add a point mass to the Geometry object by calling the method AddPointMass.
point_mass = geometry.AddPointMass()
Child Geometry objects often require a valid location assignment. You can satisfy this requirement by
creating a new selection and setting the property Location:
my_selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
my_selection.Ids = [22]
point_mass.Location = my_selection
Each child object exposes a variety of important properties. For the point mass created above, a subset
of accessible properties includes:
point_mass.Mass = Quantity("12 [kg]")
point_mass.MassMomentOfInertiaX = Quantity("1.1 [kg m m]")
point_mass.MassMomentOfInertiaY = Quantity("1.2 [kg m m]")
point_mass.MassMomentOfInertiaZ = Quantity("1.3 [kg m m]")
point_mass.Behavior = LoadBehavior.Coupled
point_mass.PinballRegion = Quantity("0.2 [m]")
Combining the three previous actions, the geometry now contains a fully described point mass.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
6 of ANSYS, Inc. and its subsidiaries and affiliates.
Model Objects
You can export the Geometry object to an STL (STereoLithography) file, which is the most commonly
used file format in 3D printing. The following commands get the project model object and geometry
object and then export the geometry object to an STL file.
mymodel = ExtAPI.DataModel.Project.Model
geo = mymodel.Geometry
geo.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 create new meshing 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()
Child Mesh objects often require a valid location assignment. You can satisfy this requirement by cre-
ating a new selection and setting the property Location:
my_selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
my_selection.Ids = [16]
mesh_method.Location = my_selection
Each child object exposes a variety of important properties. For the meshing control created above, a
subset of accessible properties includes:
mesh_method.Method = MethodType.AllTriAllTet
mesh_method.Algorithm = MeshMethodAlgorithm.PatchIndependent
mesh_method.MaximumElementSize = Quantity("0.05 [m]")
mesh_method.FeatureAngle = Quantity("12.000000000000002 [degree]")
mesh_method.MeshBasedDefeaturing = True
mesh_method.DefeaturingTolerance = Quantity("0.0001 [m]")
mesh_method.MinimumSizeLimit = Quantity("0.001 [m]")
mesh_method.NumberOfCellsAcrossGap = 1
mesh_method.CurvatureNormalAngle = Quantity("36 [degree]")
mesh_method.SmoothTransition = True
mesh_method.TetraGrowthRate = 1
The Connections object exposes several convenient methods for adding connections. For example,
you can set a frictionless contact region and add a beam:
contact_region = connection.Children[0].Children[0]
contact_region.ContactType = ContactType.Frictionless
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 7
Object Access
beam = connection.AddBeam()
Child Connections objects often require a valid location assignment. You can satisfy this requirement
by creating a new selection and setting the appropriate property. For a beam, you set the properties
ReferenceLocation and MobileLocation:
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
Each child object exposes a variety of important properties. For the frictionless contact and beam created
above, a subset of accessible properties includes:
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 = ExtAPI.DataModel.Project.Model.Analyses[0]
analysis_settings = analysis1.AnalysisSettings
The Analysis object exposes several convenient methods for manipulating a specific analysis. For
example, you can add a pre-condition, loads, and a fixed support:
bolt = analysis1.AddBoltPretension()
pressure = analysis1.AddPressure()
force = analysis1.AddForce()
support = analysis1.AddFixedSupport()
Child Analysis objects often require a valid location assignment. You can satisfy this requirement by
creating a selection object and setting the locations. For example, the sample code below sets the
properties Location for the loads and boundary conditions created on the analysis:
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
Each child object exposes a variety of important properties. For the loads and boundary conditions
created above, a subset of accessible properties includes:
bolt.SetDefineBy(1, BoltLoadDefineBy.Load) # Change definition for step #1.
bolt.Preload.Output.SetDiscreteValue(0, Quantity("15 [N]")) # Change preload value for step #1.
pressure.Magnitude.Output.Formula = '10*time' # To use a formula
pressure.Magnitude.Output.DiscreteValues=[Quantity('6 [Pa]')] # To use a direct value
force.Magnitude.Output.DiscreteValues=[Quantity('11.3 [N]'), Quantity('12.85 [N]')]
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
8 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Traversal
Object Traversal
You can query the Mechanical tree to determine the connectivity of entities. 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.
You can traverse geometry data using the IronPython function traversegeometry(). In the sample
code that follows, an object of type IGeoData is obtained from the object Analysis using the
property GeoData. The object GeoData is then used to query for a list of IGeoAssembly objects
by calling the property Assembly. For each of the IGeoAssembly objects in the returned list, the
property Parts is called and a list of IGeoPart objects is returned. This pattern is repeated through
the hierarchy of the geometry down to the vertices of each edge.
def traversegeometry(analysis):
now = datetime.datetime.now()
outFile = SetUserOutput(analysis, "SolutionDetails.log")
f = open(outFile,'a')
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
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 9
Object Access
# +++ 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:
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 = "+yco
except:
continue
f.close()
return
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
10 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Traversal
traversemesh()
You can traverse mesh data using the IronPython function traversemesh(). In the sample code that
follows, an object of type IMeshData is obtained from the object IAnalysis using the property
MeshData. The mesh object is then used to query for a list of element IDs with the property Elements.
For each of the element IDs in the returned list, the method Element is called and the corresponding
object IElement is returned. This pattern is repeated for all of the nodes for each element. Finally,
the coordinates of the nodes are queried. Comments are included in the content of the function tra-
versemesh() to clarify script functionality.
def traversemesh(analysis):
now = datetime.datetime.now()
outFile = SetUserOutput(analysis, "SolutionDetails.log")
f = open(outFile,'a')
f.write("*.*.*.*.*.*.*.*\n")
f.write(str(now)+"\n")
# --- IMesh Interface
# +++ Properties and Methods
# +++ MeshRegion
# +++ Node
# +++ Element
# +++ Nodes
# +++ Elements
# +++ NumNodes
# +++ NumElements
mesh = analysis.MeshData
elementids = mesh.ElementIds
# --- IElement Interface
# +++ Properties and Methods
# +++ Id
# +++ Type
# +++ Nodes
for elementid in elementids:
element = mesh.ElementById(elementid)
nodeids = element.NodeIds
# --- INode Interface
# +++ Properties and Methods
# +++ Id
# +++ X
# +++ Y
# +++ Z
# +++ Elements
for nodeid in nodeids:
node = mesh.NodeById(nodeid)
nodex = node.X
nodey = node.Y
nodez = node.Z
try:
f.write(" Element: "+elementid.ToString()+" Node: "+nodeid.ToString()+", X = "+nodex.ToStrin
except:
continue
f.close()
return
elementcounter()
You can also traverse mesh data using the IronPython function elementcounter() can also be used
to access the mesh data. In the sample code that follows, only the elements of user-selected geometry
entities are considered. First, the script obtains the objects IGeoData and IMeshData. The property
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 11
Object Access
CurrentSelection.Ids then queries the IDs of the selected geometry entities using the object
ISelectionMgr.
If no IDs are returned, a message box displays the message Nothing Selected. Otherwise, the
methods GeoEntityById and MeshRegionById obtain the objects IGeoEntity and IMeshRegion
corresponding to each selected entity.
These two objects are used inside the try-except block to query for the type of entity selected and the
number of elements in each entity's mesh. The property Type of the interface IGeoEntity and the
property NumElements of the interface IMeshRegion are used here. The results are displayed in a
message box.
def elementcounter(analysis):
geometry = analysis.GeoData
mesh = analysis.MeshData
selectedids = ExtAPI.SelectionManager.CurrentSelection.Ids
if selectedids.Count == 0:
MessageBox.Show("Nothing Selected!")
else:
for selectedid in selectedids:
entity = geometry.GeoEntityById(selectedid)
meshregion = mesh.MeshRegionById(selectedid)
try:
numelem = meshregion.ElementCount
MessageBox.Show("Entity of type: "+entity.Type.ToString()+
" contains "+numelem.ToString()+
" elements.")
except:
MessageBox.Show("The mesh is empty!")
return
return
Traversing Results
The API for solution allows you to query solution details and even compute new results. In the sample
code that follows, the IronPython function minmaxresults() computes the minimum and maximum
component values of the nodal displacement and the SXX stress component.
The function minmaxresults() begins by instantiating a result reader using the method analys-
is.ResultsData. 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 minmaxresults() 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 maximum values.
Note
The second loop over the nodes is filtered to the primary nodes of the elements because
stress results are available only on these primary nodes.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
12 of ANSYS, Inc. and its subsidiaries and affiliates.
Object Traversal
f.write("*.*.*.*.*.*.*.*\n")
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:
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 13
Object Access
maxsxx = SXX
minsxx = SXX
num += 1
#
# Write the results to the output
#
f.write("Max U,X:Y:Z = "+maxdispx.ToString()+" : "+maxdispy.ToString()+" : "+maxdispz.ToString()+"\n")
f.write("Min U,X:Y:Z = "+mindispx.ToString()+" : "+mindispy.ToString()+" : "+mindispz.ToString()+"\n")
f.write("Max SXX = "+maxsxx.ToString()+"\n")
f.write("Min SXX = "+minsxx.ToString()+"\n")
f.close()
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
14 of ANSYS, Inc. and its subsidiaries and affiliates.
Boundary Conditions
ACT provides an API that enables you to manipulate boundary condition fields and add new loads.
Manipulating boundary conditions fields consists of managing the various time-dependent, space-de-
pendent, or frequency-dependent values of boundary conditions during a simulation. A field has one
or more inputs and a single output.
Mathematically speaking:
output = F(input1, input2, ...)
As with other types of ACT functionality available in Mechanical, the API-based actions for editing
boundary condition fields mirror the actions that can be performed manually in the Mechanical interface.
With the API, you can:
• Set input loading data definitions, which includes setting discrete input and output values
For example, assume time is an input variable representing the various time values in seconds and
magnitude is an output variable representing the magnitude of a force over time.
• Discrete. The variable contains a discontinuous set of values. By default, most variables are initially
defined as discrete.
• Formula. The variable is a continuous function depending on inputs, such as. time*10.
• Free. Determines the selection’s freedom to move along the specified plane. This variable definition
type (mode) is available only for certain boundary conditions such as displacements. It is not available
for force or pressure.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 15
Boundary Conditions
When you use the API to define boundary condition fields, ACT 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, ACT defines the input as
Constant (ramped).
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
16 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Variable Definition Types
Note
You can also change the variable definition type to Discrete or Free by using the property
Variable.DiscreteValues as described in Setting Discrete Values for Variables (p. 20).
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 in the ACT Console, one at a time.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 17
Boundary Conditions
d.XComponent.Output.DefinitionType
d.YComponent.Output.DefinitionType
d.ZComponent.Output.DefinitionType
In the following figure, each of the variable’s components has a variable definition type of Free.
Note
Even though the query d.XComponent.Output would produce the same output in the
console when the component is Free, be aware that it returns an instance of the Variable
class. This object is then converted into a string by the console. Appending .Definition-
Type to the query consistently returns the actual enum value, whatever the mode.
• 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. You can verify in the console
that the output values are 0 and 0.
• You can verify in the console that the variable definition type is set to Discrete.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
18 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Variable Definition Types
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 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 19
Boundary Conditions
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
20 of ANSYS, Inc. and its subsidiaries and affiliates.
Setting Discrete Values for Variables
Note
With a three-step analysis, you would see four values by default: the start time and three
end times (one end time for each step).
• The output cell for row t=1 has a yellow background. This is because a value has not been set for the
output variable.
• You’ve specified a list with a single value, indicating that the other rows should be removed.
• Although a single row is specified, two rows are still showing in the TabularData window. The value
=0 is actually a repeat of the value in the row above 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 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 21
Boundary Conditions
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
22 of ANSYS, Inc. and its subsidiaries and affiliates.
Adding a Load
Adding a Load
You can access the Analysis object for an analysis to add a load. This topic describes a static struc-
tural analysis in which external and internal pressures on a pipe are added and then a force is applied
to a section of the pipe.
support = static_structural.AddFixedSupport()
support_scoping = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
support_scoping.Ids = [104]
support.Location = support_scoping
To add the external and internal pressures exerted on the pipe and then apply a force to a section of
the pipe:
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 23
Boundary Conditions
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]')]
Script execution results in the creation of the property Magnitude for the applied force, with time as
an input variable and a single output variable.
Although tabular data is used to define the property Magnitude, you can also use a constant value or
a time-dependent or space-dependent formula. An example follows of how to use a constant value to
define the property.
force.Magnitude.Output.DiscreteValues=[Quantity('10 [N]')]
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
24 of ANSYS, Inc. and its subsidiaries and affiliates.
Extracting Min-Max Tabular Data for a Boundary Condition
Note
If you use a constant ramped from t=0s to define the force, the first value cannot be "0".
You can also opt to define the property Magnitude with global coordinates instead of a vector:
force.DefineBy = LoadDefineBy.Components
force.ZComponent.Output.DiscreteValues = [Quantity('0 [N]'),Quantity('-9 [N]')]
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 25
Boundary Conditions
First, get the project model object, analysis object, force object, and tabular data object:
mymodel = ExtAPI.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:
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 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
26 of ANSYS, Inc. and its subsidiaries and affiliates.
Worksheets
You can use the API to automate the creation of worksheets in Mechanical. You can also use the API
to populate worksheets. To accomplish the following tasks, you enter commands in the ACT Console
and execute these commands in Mechanical.
Creating and Populating Named Selection Worksheets
Adding Rows to Existing Mesh Order Worksheets
Accessing Layered Section Worksheets
Accessing Bushing Joint Worksheets
ACT supports all available actions for named selection worksheets, as described in Specifying Named
Selections Using Worksheet Criteria in the ANSYS Mechanical User’s Guide. This example focuses on the
Add Row action to add new geometric entities to a named selection.
This sample code creates the named selection object, renames it Pipe, and creates the worksheet for
your named selection.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 27
Worksheets
The command AddRow adds worksheet rows according to the standard behavior of the Add option in
Mechanical named selection worksheets. It adds the information defined in the current row to inform-
ation in the previous row, provided that the Entity Type is the same for both rows.
This example uses set methods to define a Body with a Size value greater than 3.8e-5.
The method Generate generates the body. After executing this method, the pipe body is selected in
the Graphics view. In the Details view, the property Total Selection is set to 1 Body.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
28 of ANSYS, Inc. and its subsidiaries and affiliates.
Adding Rows to Existing Mesh Order Worksheets
pipews.AddRow()
pipews.SetEntityType(1,NamedSelectionWorksheetEntityType.Body)
pipews.SetCriterion(1,NamedSelectionWorksheetCriterion.Size)
pipews.SetOperator(1,NamedSelectionWorksheetOperator.LessThan)
pipews.SetValue(1,8e-6)
pipews.Generate()
In this row, set methods define a Body with a Distance value less than 3.8e-6. When there are no locally
defined coordinate systems, you do not need to set the Coordinate System value. It is set to Global
Coordinate System by default.
After executing the method Generate, 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 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 29
Worksheets
ACT supports most of the functionality available for mesh worksheets, which is described in Using the
Mesh Worksheet to Create a Selective Meshing History in the ANSYS Meshing User’s Guide. The following
exceptions apply:
• The named selections must have Entity Type set to Body. Other entity types are not supported.
• The Start Recording and Stop Recording buttons are not supported.
This section assumes that you have already defined two or more named selections in Mechanical. In
your sample static structural analysis, you’ve defined three named selections, as shown in the following
figure.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
30 of ANSYS, Inc. and its subsidiaries and affiliates.
Adding Rows to Existing Mesh Order Worksheets
To add the first row to your worksheet, you execute these commands:
mws.AddRow()
mws.SetNamedSelection(0,ns1)
mws.SetActiveState(0,True)
• The command SetNamedSelection sets Named Selection to your named selection object ns1.
• The command SetActiveState sets Active State at the row index. This enables the row, as indicated
by the check mark in the left column.
The following figure shows the mesh worksheet after the execution of these commands.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 31
Worksheets
Next, you add rows for your other two named selections, ns2 and ns3. For ns3, you use the command
SetNamedSelectionID to set the named selection.
mws.AddRow()
mws.SetNamedSelection(1,ns2)
mws.SetActiveState(1,True)
mws.AddRow()
mws.SetNamedSelectionId(2,ns3.Id)
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 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
32 of ANSYS, Inc. and its subsidiaries and affiliates.
Adding Rows to Existing Mesh Order Worksheets
Delete a Row
To delete a single row, execute the following command:
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 33
Worksheets
1. In the Project tree, expand the node Geometry node and select the node Layered Section.
3. To the right of the Worksheet selection for this property, click the right arrow and select Worksheet.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
34 of ANSYS, Inc. and its subsidiaries and affiliates.
Accessing Bushing Joint Worksheets
To get and display the thickness property for a different layer index, such as layer index 3:
lsws.GetThickness(3)
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 35
Worksheets
1. In the Project tree, expand the node Connections and then the node Joints.
3. To the right of the Worksheet selection for this property, click the right arrow and select Worksheet.
The worksheet for the bushing joint displays in the Worksheet tab. The size of the matrices for stiffness
and damping coefficients are fixed, which means that rows and columns cannot be added or deleted.
Another aspect of these square matrices (6x6) is that they are both symmetric about their main diagonals.
To ensure that these matrices are always symmetric, you cannot enter values into their upper right
corners.
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 because that cell lies above the main diagonal. As indicated
by the error message, the valid range of indices is equal to 2 and less than or equal to 5.
The following figure shows some of the many methods available for getting coefficients for damping
and stiffness.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
36 of ANSYS, Inc. and its subsidiaries and affiliates.
Graphical Views
The API ModelViewManager allows you to set, create, delete, apply, rename, rotate, save, import,
and export graphical views, providing an alternative to the Manage Views window in Mechanical.
Note
The API ModelViewManager does not export graphical views exactly as they appear in
Mechanical. For example, the exported views exhibit inconsistencies in the zoom and model
orientation. If you want to compare views to see changes in results, export them to PNG files
using the command ExtAPI.Graphics.ExportScreenToImage instead. This command
exports the current view as it appears in Mechanical to a PNG file:
ExtAPI.Graphics.ExportScreenToImage(filePath)
Where filePath is the fully qualified path for the PNG file to create.
Currently, only the PNG file format is supported. The file path must be surrounded by escape
characters. An example follows:
ExtAPI.Graphics.ExportScreenToImage("C:\\Users\\Desktop\\image1.png")
The exported view retains the same orientation, zoom factor, and other graphics rendering
properties as the view in Mechanical.
In situations where exported graphical views do not have to match exactly what is shown in Mechanical,
you can use the API ModelViewManager.
Action Command
Set to ISO view_manager.SetISO-
view View()
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 37
Graphical Views
Action Command
Set to Fit view_manager.Set-
view FitView()
Set to Front view_manager.Set-
view FrontView()
Set to Back view_manager.SetBack-
view View()
Set to Right view_manager.Set-
view RightView()
Set to Left view_manager.Se-
view tLeftView()
Set to Top view_man-
view ager.SetTopView()
Set to view_manager.SetBottom-
Bottom view View()
Creating a View
You can create a graphical view from current graphics using either a default name or a specified name.
The name assigned to the new view is View followed by the next sequential number.
To create a view using a specified name, where viewName is the name to assign to the new view:
view_manager.CreateView(string viewName)
For example, assume that you want to set the top view and then create a view named Top View:
view_manager.SetTopView()
view_manager.CreateView("Top View")
Applying a View
You can apply a graphical view by specifying its name or index.
To apply a view by specifying its name, where viewLabel is the name of the view to apply:
view_manager.ApplyModelView(string viewLabel)
To apply a view by specifying its index, where viewIndex is the index of the listed view to apply:
view_manager.ApplyModelView(int viewIndex)
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
38 of ANSYS, Inc. and its subsidiaries and affiliates.
Rotating a View
Renaming a View
To rename a saved graphical view, where viewLabel is the current name of the view to rename and
newLabel is the new name to assign to the view:
view_manager.RenameView(string viewLabel, string newLabel)
For example, assume that a view is currently named View 7 and you want to rename it to ISO View:
view_manager.RenameView("View 7","ISO View")
Deleting a View
You can delete a view by specifying its name or index.
To delete a view by specifying its name, where viewLabel is the name of the view to delete:
DeleteView(string viewLabel)
To delete a view by specifying its index, where viewIndex is the index of the listed view to delete:
DeleteView(int viewIndex)
Rotating a View
To rotate the active view, where angle is the amount of rotation:
view_manager.RotateView(double angle)
Note
For the parameter angle, you enter a positive value to rotate the view clockwise or a neg-
ative value to rotate the view counter-clockwise.
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 39
Graphical Views
Saving a View
You can save a graphical view of the entire model as an image file by specifying its name or index. For
all methods, the mode is a string representing the graphics format of the file to which to save the image.
The values that can be entered for mode are "PNG", "JPG", "TIF", "BMP", and "EPS".
Note
For commands that use the parameter folder, an empty string ("") for this parameter defaults
to the project user files. This is a null operation if the specified folder does not exist.
To save a view specified by name as an image to the project user files, where viewLabel is the name
of the view to save and mode is the graphics format for the image file:
view_manager.CaptureModelView(string viewLabel, string mode)
For example, to save a view named Bottom View to a TIF file to the project user files:
view_manager.CaptureModelView("Bottom View", "TIF")
To save a view specified by name as an image to a specified folder, where viewLabel is the name of
the view to save, mode is the graphics format for the image file, and folder is the name of the folder
in which to save the file:
view_manager.CaptureModelView(string viewLabel, string mode, string folder)
For example, to save a view named Right View to a JPG file to D:\My_Projects\Views:
view_manager.CaptureModelView("Right View", "JPG", "D:\My_Projects\Views")
To save a view specified by index as an image to a specified folder, where index is the index of the
view to save, mode is the graphics format for the image file, and folder is the name of the folder in
which to save the file:
view_manager.CaptureModelView(index, string mode, string folder)
For example, to save a view with index 0 to a PNG file to the project user files:
view_manager.CaptureModelView(0, "PNG")
Saving an Object
To save an object as an image to a file having the same name as the object, where obj is the object
to save, mode is the graphics format for the image file, and folder is the name of the folder in which
to save the file:
view_manager.CaptureObjectImage(Ansys.ACT.Automation.Mechanical.DataModelObject obj, string mode, string folder)
For example, to save an object named plate to a BMP file to the project user files:
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
40 of ANSYS, Inc. and its subsidiaries and affiliates.
Importing a Saved View List
Note
An empty string ("") for the parameter folder defaults to the project user files. This is
a null operation if the specified folder does not exist.
Exporting an Object
To export the active object to a 3D AVZ file, where avzffilepath is a fully qualified AVZ filepath:
view_manager.Capture3DImage(string avzfilepath)
For example, to export the active object to a file named my_plane.avz to D:\My_Projects\Views:
view_manager.Capture3DImage("D:\My_Projects\Views\my_plane.avz")
For example, to import a saved view list named allviews.xml that is located in D:\My_Pro-
jects\Views:
view_manager.ImportModelViews("D:\My_Projects\Views\allviews.xml")
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 41
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
42 of ANSYS, Inc. and its subsidiaries and affiliates.
Results
In Mechanical, the Solution object contains child objects for analysis results. To access the Solution
object:
solution = ExtAPI.DataModel.Project.Model.Analyses[0].Solution
You can use the ACT API to add custom results to the Solution object. For example, you can add
the result Total Deformation to a static structural analysis and then solve for the minimum and max-
imum total deformation:
total_deformation = solution.AddTotalDeformation()
analysis = ExtAPI.DataModel.Project.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 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 43
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
44 of ANSYS, Inc. and its subsidiaries and affiliates.
Other APIs
The following sections describe other ACT APIs of particular interest:
Mechanical Interface and Toolbar Manipulation
Command Snippets
The API UserInterface allows you to hide or gray-out ACT-based features and customize existing
toolbars. It cannot be used to create new items such as toolbars. The API UserInterface provides
access only to existing UI elements.
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
The API CommandSnippet provides for defining a MAPDL script that you want to invoke during the
preprocessing, solution-solving, or postprocessing phase of your analysis. Use the function AddCom-
mandSnippet() to insert a new child command snippet in the project tree:
sol = ExtAPI.DataModel.Project.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 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
of ANSYS, Inc. and its subsidiaries and affiliates. 45
Release 19.0 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential information
46 of ANSYS, Inc. and its subsidiaries and affiliates.