Skip to main content

Abstract:

ANSYS Mechanical provides a Python scripting environment which allows one to automate control of features and the collection of results from within the ANSYS Mechanical environment. ANSYS provides extensive documentation for all of its products, but some features remain undocumented.

One such feature relates to the extraction of tabular results data.

This post explores how to extract tabular results data using Python and export this to a CSV file.

Details:

For many result types, there exists a Python method to export results to a file, however, not all result types support this feature, and if they do, one might desire to express more control about what data is collected and how it is used.

The Python scripting feature illustrated below accesses the Tabular Data Pane using an “Unknown Control”.

Even though I want to focus on this ability to export tabular data, the most simple example must also include additional features to make this example meaningful. I will explain all these features with just enough detail so that we can focus on this unknown control used for the tabular data.

My example examines a stress linearization result applied to a simple cantilever beam which was subject to a bending load and solved as a static structural analysis. This result appears as follows:

Interface

The Model tree shows the “Linearized Equivalent Stress” result. The Canvas displays the 3D model, the legend and the stress classification line. The Graph displays the linearized stress results which are tabulated within the “Tabular Data” pane.

For clarity purposes, I could right-click on “Linearized Equivalent Stress” and choose to “Export Text File”.

Export

This method, however, doesn’t teach us anything about Python scripting in ANSYS Mechanical and it doesn’t lend itself to automation.

We could also request this result is exported to a text file using Python in ANSYS Mechanical. We do this by accessing the “Automation” ribbon and left clicking on “Scripting”. Two new panes will appear on the right side of the ANSYS Mechanical interface: “Editor” at the top, and “Shell” at the bottom. I can type the following three commands for the model shown above and export the same text file:

sol=Model.Analyses[0].Solution

linres=sol.Children[3]

linres.ExportToTextFile("D:\LinearizedStress.txt")

 

Okay, this is a step in the right direction. Three lines seems really simple. The reality is that I can’t just write these three lines for any model and expect to successfully export this text file. Usually, there is some searching by executing commands in the “Shell” until I find what I want, then I can transpose that into a script up in the “Editor” for repeated automations. Since these details aren’t the focus for this discussion, I will move on.

Let’s assume I have been scripting for a while, and during this time, I have accessed different ANSYS resources to type to export that Tabular Data. If you knew what to search for, it is unlikely that it will be found within the online help. There are two resources I did find, and here they are:

https://forum.ansys.com/forums/topic/tabular-data-extraction/

https://www.linkedin.com/pulse/script-tip-friday-connecting-mechanical-excel-structural-analysis/

Each of these examples offers a different perspective on the same thing. Below, I will give a third perspective, which hopefully will be more direct based on my original premise of generating a CSV file based on this tabular data.

Here is my basic script, which can be entered directly into the ANSYS Mechanical Scripting Editor:

import csv

 

def writeCSV(filename, data):

   # Function to write python list to a csv file

   with open(filename, 'wb') as csvfile:

       spamwriter = csv.writer(csvfile, delimiter=',',

                               quotechar='|', quoting=csv.QUOTE_MINIMAL)

       for row in data:

           spamwriter.writerow(row)

 

ResultsOfInterest = []

ResultsOfInterest.append('Linearized Equivalent Stress')

 

 

import wbjn

cmd = 'returnValue(GetUserFilesDirectory())'

user_dir = wbjn.ExecuteCommand(ExtAPI, cmd)

 

AnalysisNumber=0

 

solution=Model.Analyses[AnalysisNumber].Solution

for j, item in enumerate(solution.Children):

   if item.GetType() == Ansys.ACT.Automation.Mechanical.Results.LinearizedStressResults.LinearizedEquivalentStress:

       if item.Name in ResultsOfInterest:

         item.Activate()

          

           data=[]

           del data[:]

           Pane=ExtAPI.UserInterface.GetPane(MechanicalPanelEnum.TabularData)

           Con = Pane.ControlUnknown

           for R in range(1,Con.RowsCount+1):

              data.append([])

               for C in range(2,Con.ColumnsCount+1):

                   data[-1].append(Con.cell(R,C).Text)

 

           writeCSV(user_dir + "/" + Model.Analyses[AnalysisNumber].Name + " - " + item.Name + ".csv", data)

  

print("Script has completed!")

print("")

print("Open File: " + chr(34) + user_dir + chr(92) + Model.Analyses[AnalysisNumber].Name + " - " + item.Name + ".csv" + chr(34))

 

Now let’s break down what is here for clarification purposes. This Python Script contains the following four elements:

  1. Can filter for a specific ANSYS Result Name
  2. Requires that one set the ANSYS Analysis number for this particular model
  3. Can filter for a specific "Result Type" before the script will collect the correct results
  4. Will read the "Tabular Data" of results from ANSYS and print that to a CSV file

Using Pictures (with some coloring for clarity), let’s examine what comprises each element.

Filter for a Specific ANSYS Result Name:

ResultsOfInterest

Highlighted above in pink is were a list is defined, but this list only contains one item named, “Linearized Equivalent Stress”. I can list as many specific results as I choose. If I had multiple results which were similar, but was only interested in a result having this specific name, then this method will allow me to filter based on result object name.

Set the ANSYS Analysis Number:

SetAnalysisNumber

The same code, just a different line highlighted in pink. ANSYS begins indexing of items at number “zero”. Therefore, in my model, the first and only analysis I have is the Static Structural analysis. Since this is the “first” analysis, I enter “0” to represent that analysis number… Done!

Set the "Result Type":

ResultType

The short answer here is this is not going to be a value that you will know. You will need to use the scripting “Shell” to interrogate result items in the Model Tree and query on “Name” and “GetType()” for the result item of interest. I will explore how to do this in a different presentation, but will suggest for a linearized equivalent stress result, the type is:

“Ansys.ACT.Automation.Mechanical.Results.LinearizedStressResults.LinearizedEquivalentStress”

Without filtering on the kind of result, I may try to extract a specific kind of result data that doesn’t exist. This is one more level of control in selectivity.

Read the "Tabular Data":

ReadTabularData

Finally, this is why we are here!

In this highlighted section, “data” collects and holds everything we will extract from the Tabular Data, then it is used to generate the CSV file.

We define “Pane” (by-the-way… “Pane” is what I choose to call this object, you could name it based on your own preference) as a programming object that is equivalent to:

ExtAPI.UserInterface.GetPane(MechanicalPanelEnum.TabularData)

This part is fine. It is the next line that would remain mysterious. We define a control named “Con” equivalent to:

Pane.ControlUnknown

Now I can perform actions using my new object, “Con”, to extract data from the Tabular Data, but keep in mind that typing a dot “.” after “Con” will not give you an accurate or complete list of the available functions. Here are some of the functions I have used (there may be more):

Con.RowsCount (Returns an integer)
Con.ColumnsCount (Returns an integer)
Con.cell(R,C).Text (where R and C are integers)
Con.Cell(1,C).CheckStateChecked (Boolean returns True of False)

 

This is what our exported CSV looks like if opened in Excel:

Excel

This process can be repeated for any tabular result type within ANSYS Mechanical.

Pat Tessaro, P.E.
Post by Pat Tessaro, P.E.
March 17, 2023
Pat Tessaro graduated with a BS in Mechanical Engineering from the University of Pittsburgh in 2000 and earned his Professional Engineer license in 2007. He comes to Ozen Engineering with 21 years of experience providing finite element analysis and automation solutions in the realm of linear statics, dynamics, vibrations, non-linear, fatigue, heat transfer and computational fluid flow, as well as working as an FEA analyst and engineer on various civil and process piping projects. When Pat isn’t working on very unusual projects at home, he is enjoying those most important relationships with his Parents, family and friends.