Mechanical APDL and Sending Commands to Integrated Applications

As discussed in Scripting and Data-Integrated Applications, Ansys Workbench can interact with the native scripting language of many of its integrated applications. This example demonstrates scripting interaction with Mechanical APDL and the use of the SendCommand method to pass APDL commands to the editor. After you extract the ScriptingGuideExamples.zip file, you will find the files for this example in the Sending_Commands directory.

The case under consideration is a simple stress analysis of a bar that is defined in a Mechanical APDL input file. The bar dimensions and output displacement have been parameterized within Mechanical APDL. In this example, you wish to write a script that automates this analysis for a number of different bar lengths and write an Ansys .cdb file for each case for future processing.

To automate this process, you will write an Ansys Workbench script that performs the following operations:

  1. Creates a system for Mechanical APDL analysis and loads the specified Ansys input file.

  2. Publishes some of the parameters from the input file to Ansys Workbench.

  3. Loops through a list of desired bar lengths and, for each value, does the following:

    1. Sets the length parameter value.

    2. Updates the project to compute displacement for the new length.

    3. Sends APDL commands to Mechanical APDL to write the .cdb file to a desired location.

Sample Data File

The sample data file to be used in this example follows:

! set parameters
xlen=3
ylen=4
zlen=7

! define model
/prep7
block,,xlen,,ylen,,zlen  
et,1,185
mp,ex,1,1e6
mp,prxy,1,0.3
vmesh,all
nsel,s,loc,z,0
d,all,all
nsel,s,loc,y,ylen
sf,all,pres,125
alls
fini

! obtain the solution
/solution
solve
fini


! retrieve results
/post1
! get the max stress at the fixed end
nsel,s,loc,x,xlen
nsel,r,loc,y,ylen
nsel,r,loc,z,0
*GET,out_my_node_stress,NODE,1,NXTH
*GET,out_seqv,NODE,out_my_node_stress,S,EQV
! get the max displacement at the free end
nsel,s,loc,x,xlen
nsel,r,loc,y,ylen
nsel,r,loc,z,zlen
*GET,out_my_node_def,NODE,1,NXTH
*GET,out_uy,NODE,out_my_node_def,U,Y
alls
fini

Workbench Script

The script for this example follows. Each line is numbered for reference in the discussion that follows.

1 	# Import the 'os' module, which provides a portable way of using 
2 	# operating system dependent functionality
3 	import os
4 
5 	workDir = "ScriptingGuideExamples/Sending_Commands/"
6 
7 	# Specify the Mechanical APDL Input file to be processed
8 	inputFile = AbsUserPathName(workDir + "bar.dat")
9 
10	# Provide a list of bar length (Z) values to solve and write CDB files for.
11	
12	zValues = [3,5,12,15]
13
14	# Open a log file to record script progress
15	logFile = open(AbsUserPathName(workDir + "my_bar_script.log"),"w")
16
17	# Start a new project and create the Mechanical APDL system
18	Reset()
19	template1 = GetTemplate(TemplateName="Mechanical APDL")
20	system1 = template1.CreateSystem()
21
22	# Read the input file into the Mechanical APDL Setup
23	setup1 = system1.GetContainer(ComponentName="Setup")
24	mapdlInputFile1 = setup1.AddInputFile(FilePath=inputFile)
25
26
27	# Create Workbench parameters from two of the Mechanical APDL parameters
28	# in the input file
29	mapdlInputFile1.PublishMapdlParameter(Name="ZLEN")
30	parameter1 = Parameters.GetParameter(Name="P1")
31
32	mapdlInputFile1.PublishMapdlParameter(
33	    Name="OUT_UY",
34	    IsDirectOutput=True)
35	parameter2 = Parameters.GetParameter(Name="P2")
36
37	# Save the initial project definition.
38	Save(
39	    FilePath=AbsUserPathName(workDir + "myBar.wbpj"),
40	    Overwrite=True)
41	    
42	# Loop through all provided bar lengths
43	for zVal in zValues:
44	    
45	    # Set the Z (length) parameter expression
46	    parameter1.Expression = str(zVal)
47	    logFile.write("Updating for z = %s\n" % zVal)
48	    
49	    # Update the project for the new parameter value, and report 
50	    # success or failure to the log file.
51	    try:
52	        Update()
53	    except:
54	        logFile.write("  Update failed.\n")
55	    else:
56	        logFile.write("  Update succeeded. UY = %s\n" % parameter2.Value)
57	    
58	    # Generate the name of the CDB file to save
59	    cdbName = os.path.join(GetUserFilesDirectory(), "my_bar_" + str(zVal) + ".cdb")
60	    cdbName = cdbName.replace("\\","/")
61	    
62	    # Delete the cdb file if it already exists, to prevent 
63	    # Mechanical APDL from promting us about overwrite.
64	    if os.path.exists(cdbName):
65	        os.remove(cdbName)
66	    
67	    # Generate the APDL command to save the CDB file and send it.
68          apdlCmd = "cdwr,db,%s" % cdbName
69          setup1.Edit(
70              Interactive=False,
71              LoadInputFiles=True)
72
73	    setup1.SendCommand(Command=apdlCmd)
74	    logFile.write("  CDB written to %s\n" % cdbName)
75          setup1.Exit()
76
77	# Save the final project state.
78	Save()   
79	logFile.close()

Log File

The log file generated by this script should look like this:

Change all the forward slashes (\) with backslashes (/)
Updating for z = 3
  Update succeeded. UY = -0.00083352729
  CDB written to C:\Users\neUser\Demo\ScriptExample4\myBar_files\user_files\my_bar_3.cdb
Updating for z = 5
  Update succeeded. UY = -0.00304172391
  CDB written to C:\Users\neUser\Demo\ScriptExample4\myBar_files\user_files\my_bar_5.cdb
Updating for z = 0
  Update failed.
  CDB written to C:\Users\neUser\Demo\ScriptExample4\myBar_files\user_files\my_bar_0.cdb
Updating for z = 12
  Update succeeded. UY = -0.0504979576
  CDB written to C:\Users\neUser\Demo\ScriptExample4\myBar_files\user_files\my_bar_12.cdb
Updating for z = 15
  Update succeeded. UY = -0.121175623
  CDB written to C:\Users\neUser\Demo\ScriptExample4\myBar_files\user_files\my_bar_15.cdb

Discussion

This example demonstrates interaction with Mechanical APDL to operate on an existing Ansys input file and send APDL commands. The following discussion refers to the specified line numbers of the example script to illustrate some of these concepts and constructs. Discussion points from earlier examples will not be repeated here.

Lines 1-15

The initial lines of the script import useful modules, define controlling variables and create a log file to record script progress.

Lines 17-20

Here the script starts a new project and creates a new Mechanical APDL system.

Lines 22-24

The AddInputFile method on the Mechanical APDL Setup container reads and processes the specified input file.

Lines 27-35

The input file contains a number of values that can be parameterized. Here the script promotes two of them to be parameters that are controlled and displayed at the Ansys Workbench level. The script accesses the ZLEN parameter as an input to set the bar length and the OUT_UY parameter as an output to track maximum Y displacement.

Lines 40

The script saves the project to a permanent location. Until the project is saved, all files and project directories are based on a temporary location. By saving the project, the script can more accurately report the directory that holds the .cdb files. The script will still function if the project is not first saved, but it will report the temporary location for the project files.

Lines 42-47

The script starts the loop for the desired bar length values and sets the Z parameter appropriately. The Expression for a parameter is a string as it can support complex functions. The Python str() function is used to convert the Z value to a string.

Lines 49-56

The script calls the project Update() command to recalculate the project based on the new length parameter value and uses Python exception handling to report the success or failure of the update. The value of output displacement is reported on successful update.

Lines 58-60

The project user_files directory is used to store the .cdb files for each case. Here the script generates the desired .cdb file path based on the GetUserFilesDirectory() query and uses os.path.join to combine that with the desired file name.

Mechanical APDL typically uses forward slashes in file paths by convention, so line 62 of the script converts any backslashes to forward slashes.

Line 62-65

Mechanical APDL interactively prompts you to overwrite a .cdb file if one already exists, so the script ensures that no .cdb file of the desired name is present.

Lines 67-75

The generated APDL command string writes the .cdb file to the desired file path and uses the SendCommand method to execute it. While this example just passes a single line command, the command string can contain multiple commands separated by newlines.

Lines 77-79

The script saves the final project state and closes the log file.