Sunteți pe pagina 1din 20

Scripting in Mechanical (Quick Start Guide)

ANSYS, Inc. Release 18.2


Southpointe August 2017
2600 ANSYS Drive
Canonsburg, PA 15317 ANSYS, Inc. and
ansysinfo@ansys.com ANSYS Europe,
Ltd. are UL
http://www.ansys.com registered ISO
(T) 724-746-3304 9001: 2008
(F) 724-514-9494 companies.
Copyright and Trademark Information

© 2017 ANSYS, Inc. Unauthorized use, distribution or duplication is prohibited.

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.

U.S. Government Rights

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.

Published in the U.S.A.


Table of Contents
Introduction to Scripting ............................................................................................................................ 1
What is ACT? .......................................................................................................................................... 1
What is the ACT Console? ........................................................................................................................ 1
Command Line Usage ............................................................................................................................. 2
Snippets ................................................................................................................................................. 4
Key Usage Concepts ............................................................................................................................... 6
Additional Resources .............................................................................................................................. 8
Script Examples .......................................................................................................................................... 9
Script Examples for Selection .................................................................................................................. 9
Select Geometry or Mesh in a Graphics Window ................................................................................ 9
Get Tree Object of a Body Corresponding to a Selected Body ........................................................... 10
Get GeoData Body Corresponding to a Tree Object of a Body ........................................................... 10
Query Mesh Information for Active Selection ................................................................................... 10
Use an Existing Graphics Selection on a Result Object ...................................................................... 10
Calculate Sum of Volume, Area, and Length of Scoped Entities ......................................................... 10
Script Examples for Interacting with Tree Objects .................................................................................. 11
Delete an Object ............................................................................................................................. 11
Refresh the Tree .............................................................................................................................. 11
Count the Number of Contacts ....................................................................................................... 11
Verify Contact Size .......................................................................................................................... 12
Set Pinball to 5mm for all Frictionless Contacts ................................................................................ 12
Use a Named Selection as Scoping of a Load or Support .................................................................. 12
Suppress Bodies Contained in a Given Named Selection .................................................................. 12
Change Tabular Data Values of a Standard Load or Support ............................................................. 13
Duplicate an Harmonic Result Object .............................................................................................. 13
Export a Result Object to an STL File ................................................................................................ 13
Export Result Images to Files ........................................................................................................... 13
Work with Solution Combinations ................................................................................................... 14
Create a Pressure Load .................................................................................................................... 14
Script Examples for Interacting with the Mechanical Session .................................................................. 14
Remesh a Model Multiple Times and Track Metrics ........................................................................... 15
Scan Results, Suppress Any with Invalid Display Times, and Evaluate ................................................. 15
Check Version ................................................................................................................................. 15
Check Operating Environment ........................................................................................................ 15
Retrieve Stress Results .................................................................................................................... 15
Search for Keyword and Export ....................................................................................................... 16
Modify Export Setting ..................................................................................................................... 16
Refresh the Messages Box ............................................................................................................... 16

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.

This chapter provides introductory information about ACT:


What is ACT?
What is the ACT Console?
Command Line Usage
Snippets
Key Usage Concepts
Additional Resources

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.

• Add pre-processing features such as loads and boundary conditions

• Add post-processing features such as custom results

• Add the ability to connect to third-party solvers or launch external processes

What is the ACT Console?


The Act Console exposes the ACT API so that you can develop and debug scripts. In Mechanical, you
click the toolbar button for opening the ACT Console.

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.

Command Line Usage


In the command line, you typically begin a command by typing:
ExtAPI.

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. – Provides access to the API.

• ExtAPI.DataModel. – Provides access to the Mechanical tree.

• ExtAPI.DataModel.GeoData. – Provides access to the geometry attached to Mechanical for this


session.

• ExtAPI.DataModel.GeoData.Assemblies[0]. – Provides access to the first assembly. Python


starts counting at 0 rather than 1.

• ExtAPI.DataModel.GeoData.Assemblies[0].Parts[0].Bodies[0]. – Provides access


to the first part and its first 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:

– ExtAPI.DataModel.Project.Model.Connections accesses the Connections object.

– ExtAPI.DataModel.Project.Model.NamedSelections accesses the NamedSelections


object.

• Mesh. Inserts mesh = ExtAPI.DataModel.Project.Model.Mesh, providing access to the


Mesh object.

• Geometry. Inserts geometry = ExtAPI.DataModel.Project.Model.Geometry, providing


access to the Geometry object.

• Analysis. Inserts analysis = ExtAPI.DataModel.Project.Model.Analyses[0], providing


access to the first analysis of the model. As indicated earlier, Python starts counting at 0 rather than 1.

• ObjectsByName. Inserts solution = ExtAPI.DataModel.Tree.GetObjectsByName("Solu-


tion"), providing access to a list of all solutions. To apply this function with pressure, you
use:pressure = ExtAPI.DataModel.Tree.GetObjectsByName("pressure").

• solution = ExtAPI.DataModel.Tree.GetObjectsByName("pressure")

• PathToFirstActiveObject. Inserts path_to_object = ExtAPI.DataModel.Tree.Get-


PathToFirstActiveObject(), providing access to the full path that must be typed to go to the
first object that is selected in the tree.

• ObjectsByType. Inserts coordinate_system_list = ExtAPI.DataModel.Tree.GetOb-


jectsByType(DataModelObjectCategory.CoordinateSystem), where DataModelOb-
jectCategory is the enumeration containing all types. To apply this function with pressure, you use:
pressure_list = ExtAPI.DataModel.Tree.GetObjectsByType(DataModelObjectCategory.Pressure)

• Active Objects. Inserts active_objects = ExtAPI.DataModel.Tree.ActiveObjects,


providing a list of all selected objects in the tree.

• FirstActiveObject. Inserts first_active_object = ExtAPI.DataModel.Tree.FirstAct-


iveObject, providing access to the first of all selected objects.

• 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

– pres.Magnitude.Inputs[0].DiscreteValues = [Quantity('0 [sec]'), Quantity('1 [sec]'), Quantity('2 [sec]')]

– pres.Magnitude.Output.DiscreteValues = [Quantity('0 [Pa]'), Quantity('50 [Pa]'), Quantity('100 [Pa]')]

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.

Key Usage Concepts


ACT continues to evolve rapidly, expanding in both features and the ANSYS products that it supports.
Consequently, learning to use it can sometimes seem overwhelming. However, knowing these key
concepts makes using the ACT Console to script in Mechanical easier:

• 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.

• Entering mesh = ExtAPI.DataModel.MeshDataByName("Global") in the command line is an


easy way to access the mesh. Global is the main and only mesh. You can save this command as a snippet
to use it anytime that you want to access the mesh.

• 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

– ExtAPI.DataModel.MeshDataByName("Global") accesses FE information (node and element


locations, element connectivity, and so on).

• It is important to understand a key but subtle distinction between two ways of dealing with the geometry:

– ExtAPI.DataModel.GeoData accesses the underlying geometry attached to Mechanical.

– ExtAPI.DataModel.Project.Model.Geometry accesses the Geometry object in the Mechanical


tree.

• 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:

– Directly Accessing an Object

– 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)

For example, for contact_region in contact_region_list, you execute this command:


contact_region.ContactFormulation = Ansys.ACT.Automation.Mechanical.Enums.ContactFormulation.MPC

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

• ANSYS support is available anytime by emailing support@ansys.com.

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:

• For Product, select ACT Customization Suite.

• For Product Family, select Scripting.

To further limit the solution 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 a 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

Select Geometry or Mesh in a Graphics Window


Goal: Select a geometry or mesh in a graphics window.

Code for Geometry selection:


# Clear the current selection and select some previously determined Geo IDs
ExtAPI.SelectionManager.ClearSelection()
mySel = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities)
mySel.Ids = [17,19,22] #These are the IDs of any geometric entities
ExtAPI.SelectionManager.NewSelection(mySel)

Code for Mesh selection:

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

Get Tree Object of a Body Corresponding to a Selected Body


Goal: Get the tree object corresponding to a selected body in the Mechanical graphics window.

Code:
myIds = ExtAPI.SelectionManager.CurrentSelection.Ids
geoBody = ExtAPI.DataModel.GeoData.GeoEntityById(myIds[0])
treeBody = ExtAPI.DataModel.Project.Model.Geometry.GetBody(geoBody)

Get GeoData Body Corresponding to a Tree Object of a Body


Goal: Get the GeoData (graphics window) body corresponding to a tree object of a body in Mechanical.

Code:
treeBody = ExtAPI.DataModel.Project.Model.Geometry.Children[0].Children[0]
geoBody = treeBody.GetGeoBody()

Query Mesh Information for Active Selection


Goal: Query the mesh information for the active selection in Mechanical.

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

# check that current selection is nodes


if sel.SelectionType == SelectionTypeEnum.MeshNodes:
print "%s Nodes Selected" % (refIds.Count)
for meshId in refIds:
node = meshData.NodeById(meshId)
print "Node %s, X = %s, Y = %s, Z = %s" % (meshId, node.X, node.Y, node.Z)
else:
print "Selection is not made of nodes"

Use an Existing Graphics Selection on a Result Object


Goal: Take an existing graphics selection and use it on a result object.

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()

Calculate Sum of Volume, Area, and Length of Scoped Entities


Goal: Calculate the sum of the volume, area, and length of the scoped entities.

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

for geoid in sel:


geoEntity = ExtAPI.DataModel.GeoData.GeoEntityById(geoid)
if geoEntity.Type == GeoCellTypeEnum.GeoBody:
sum += geoEntity.Volume
type = "volume"
unit = ExtAPI.DataModel.Project.Model.Geometry.LengthX.Unit + "^3"
if geoEntity.Type == GeoCellTypeEnum.GeoFace:
sum += geoEntity.Area
type = "area"
unit = ExtAPI.DataModel.Project.Model.Geometry.LengthX.Unit + "^2"
if geoEntity.Type == GeoCellTypeEnum.GeoEdge:
sum += geoEntity.Length
type = "length"
unit = ExtAPI.DataModel.Project.Model.Geometry.LengthX.Unit

MessageBox.Show("Total selected "+type+" is: "+str(sum)+" "+unit)

Script Examples for Interacting with Tree Objects


The following scripts are for interacting with tree objects in Mechanical:
Delete an Object
Refresh the Tree
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
Change Tabular Data Values of a Standard Load or Support
Duplicate an Harmonic Result Object
Export a Result Object to an STL File
Export Result Images to Files
Work with Solution Combinations
Create a Pressure Load

Delete an Object
Goal: Delete a selected object from the Mechanical tree.

Code:
ObjToDelete.Delete()

Refresh the Tree


Goal: Refresh the Mechanical tree. This is needed for certain operations that visually appear only after
an update of the tree.

Code:
ExtAPI.DataModel.Tree.Refresh()

Count the Number of Contacts


Goal: Count the number of contacts in the model.

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()

Verify Contact Size


Goal: For a face-to-face contact, ensure that all "contact" sides are smaller than their "target" sides.

Code:
geom = ExtAPI.DataModel.GeoData

contacts = ExtAPI.DataModel.Project.Model.GetChildren(DataModelObjectCategory.ContactRegion, True)

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

if (target_area < source_area):


print "Flipping Source/Target For Contact Region = %s" % (cont.Name)
cont.FlipContactTarget()

print "Done with Macro"

Set Pinball to 5mm for all Frictionless Contacts


Goal: Change all frictionless contacts to have a pinball of 5mm.

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

print "Done with macro, changed %s contact regions" % (changeCount)

Use a Named Selection as Scoping of a Load or Support


Goal: Use a named selection as scoping of a load or support object in Mechanical.

Code:
load = ExtAPI.DataModel.Project.Model.Analyses[0].AddPressure()
ns = ExtAPI.DataModel.Project.Model.NamedSelections.Children[0]
load.Location = ns

Suppress Bodies Contained in a Given Named Selection


Goal: Retrieve and suppress the bodies contained in a named selection in Mechanical.

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

for bodyId in bodyIds:


geoBody = ExtAPI.DataModel.GeoData.GeoEntityById(bodyId)
body = ExtAPI.DataModel.Project.Model.Geometry.GetBody(geoBody)
body.Suppressed = True
print "Done with Macro"

Change Tabular Data Values of a Standard Load or Support


Goal: Change the tabular data values of a standard load or support in Mechanical.

Code:
pressureLoad=ExtAPI.DataModel.Project.Model.Analyses[0].AddPressure()
pressureLoad.Magnitude.Output.DiscreteValues = [Quantity('0 [MPa]'),Quantity('10 [MPa]')]

Duplicate an Harmonic Result Object


Goal: Given a selected harmonic result, duplicate it and sweep over the phase.

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)

Export a Result Object to an STL File


Goal: Export a result object to an STL file.

Code:
result = ExtAPI.DataModel.Project.Model.Analyses[0].Solution.Children[1]
result.ExportToSTLFile("E:\\test.stl")

Export Result Images to Files


Goal: Export all result in the tree to PNG (2D image) and AVZ (3D image) files.

Code:
# get a list of all the results in the project
results =ExtAPI.DataModel.Tree.GetObjectsByType(DataModelObjectCategory.Result)

#loop over the results


for n in range(0,results.Count):

# select and activate the result


result = results[n]
result.Activate()

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)

# export the result as a 2D PNG file


mvm.CaptureModelView(result.Name,"PNG","D:\\Images")

print "Done with Exporting Results"

Work with Solution Combinations


Goal: Create a solution combination object combining two environments.

Code:
# create a solution combination object combining 2 environments
sc = ExtAPI.DataModel.Project.Model.AddSolutionCombination()

# get the environments, an alternative would be via ExtAPI.DataModel.Project.Model.Analyses


envs = ExtAPI.DataModel.Tree.GetObjectsByType(DataModelObjectCategory.Analysis)

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)

Create a Pressure Load


Goal: Create a pressure on the first face of the first body for the first part.

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]")]

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

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

Refresh the Messages Box

Remesh a Model Multiple Times and Track Metrics


Goal: Remesh a model five times, tracking how long each remesh takes and the number of nodes that
are created.

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

Check Operating Environment


Goal: Check to see if your user is operating in a Unix environment.

Code:
import Ansys.Utilities
from Ansys.Utilities import ApplicationConfiguration
---
isUnix = ApplicationConfiguration.DefaultConfiguration.IsUnix

Retrieve Stress Results


Goal: Obtain stress results for an element.

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()

Search for Keyword and Export


Goal: Loop through all results that contain a keyword of For Image and export the image shown to
a directory.

You must specify the path in the first line.

Code:
path = "C:\\"
n = 0

model = ExtAPI.DataModel.Project.Model
view_manager = ExtAPI.Graphics.ModelViewManager

for analysis in ExtAPI.DataModel.Project.Model.Analyses:


sol = analysis.Solution
for sol_obj in sol.Children:
if sol_obj.Name.Contains("For_Image"):
n += 1
sol_obj.Activate()
view_manager.CaptureObjectImage(sol_obj, "PNG", path)

Modify Export Setting


Goal: Modify the export setting in Mechanical to include node numbers in exports.

Code:
ExtAPI.Application.ScriptByName("jscript").ExecuteCommand('WB.PreferenceMgr.Preference("PID_Show_Node_Numbers") =

Refresh the Messages Box


Goal: Refresh the Messages box in Mechanical.

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.

S-ar putea să vă placă și