Best of Script Tip Friday 2022
Come back in 2023 to learn script tips from the Ansys experts!

Best of Script Tip Friday 2022

As the year 2022 comes to a close, it’s time to take a look back and reflect on all the amazing and beneficial tips that were submitted and shared through Script Tip Friday. If you’re new here and unfamiliar with what Script Tip Friday is, it is a weekly article post from our Ansys Structures LinkedIn page that provides tips, tricks and best practices for those who want to use scripting to automate and customize our software.

Script Tip Friday began from our Ansys experts sharing some of their best and favorite script tips, but quickly grew into customers, partners and even students sharing their scripts as well. We love hearing from our users, so remember: if you have a script tip that others can benefit from, please share with us!

Without further ado, let’s check out the top performing script tips, and a snippet from each of them, from this past year.


Coming in at #1 is Bolt Pretension, authored by Pierre THIEFFRY . Check out the full article here:

Yet not all items can be parameterized and there are times where you will want to create your very own parameters. Scripting in Mechanical allows you to do this easily. Since 22R1, the Python Code objects allow you to embed Python script in the simulation tree so that the script gets executed every time the model is updated. The object supports the definition of properties, some of which can be then parameterized. In the example below, you see a Python Code designed to update multiple bolt pretensions at once. The object in the tree has the famous white box and its “P” indicator and the script below shows you how this parameter is used. You first retrieve its value then update all Bolt Pretension items with this value. As simple as this!

No alt text provided for this image
No alt text provided for this image

Coming in at #2 is “Python Code” Object in Mechanical, authored by Rohith Gandhi Patchigolla . Check out the full article here:

What if you could easily export all your results in Mechanical as images using simple scripts when running several design variations from Workbench automatically?

?From the latest release i.e. 2022 R2, we can do that!

This is possible because of the new, highly powerful, “Python Code” object, which is native in Ansys Mechanical, using which one can use simple python scripts, to automate tasks (such as exporting images, results and many more…).

?So, how do I do it?

Step 1: Insert this “Python Code Object”

No alt text provided for this image

Step 2: Set a “Callback”, which is basically telling Mechanical, at which point you would like it to trigger the Python script

  • In this case, we use “After Post”, as we want to wait till Mechanical solves the model so that the contour plots are available

No alt text provided for this image

Coming in at #3 is argparse, How to Make Your Own CLI, authored by James Derrick . Check out the full article here:

How do I construct the parser?

First of all you create an instance of?argparse.ArgumentParser.

parser = ArgumentParser(description='Demo program')        

The description is purely for documentation purposes, and you can leave it out if you want, though why would you?! Writing docs is fun!

Next we add arguments to our parser. We tell the parser what it should expect to see on the command line and how to treat those inputs. For this tutorial though we're just keeping it as simple as possible and not worrying about the many things you can do.


parser.add_argument('--density', help='density provided as a float')        

this adds the "option"?--density?which is a point of entry for the "argument" associated with it.

Now we parse the args, which stores all the supplied arguments in the returned namespace object that I always call?args.


args = parser.parse_args()        

Coming in at #4 is From ODB++ to Modal Analysis, authored by Enrico Bedogni . Check out the full article here:

The whole workflow is managed by the workbench script that, during its execution, recalls two other scripts. This is amazing because one can script on single products and take care of the details (like SPCM and Mechanical) and then glue up all together to automate in just one script. Here just an overview on the scripting interface:

  1. Record Journal: it’s a step-by-step recorder of the python functions that you are calling while you are clicking in the workbench. It’s a very useful tool to get a quick start, then, when things get more complicated, it needs a bit of postprocess.
  2. Run script File: it’s a loader, you can re-call saved script and workbench automatically performs all the sequences of commands inside the script.
  3. Open Command Window: It’s a live console, you can try functions and see how they perform, live. I found it very useful to check and debug.??

No alt text provided for this image

Coming in at #5 is How to Sum Damage Results, authored by Vishnuram V . Check out the full article here:

In this article, I tackle the task of summing damage results by creating your own field using DPF. You can use the similar method to sum or manipulate contour results from multiple result objects.

This particle example shows how to sum the damage results from 2 damage result objects and plot them using python results.

(Thanks to Sascha and Pierre. This script is adapted from their scripts.)

In this example we create our own scalar field and populate the data and id and use the created scalar fields to plot.

The algorithm is like below:

No alt text provided for this image

Your sample code will look like below: I am getting damage result objects by name "damage". Please change that line according to your case.


def post_started(sender, analysis):# Do not edit this line
    define_dpf_workflow(analysis)

def define_dpf_workflow(analysis):
    analysis = ExtAPI.DataModel.AnalysisByName(ExtAPI.DataModel.AnalysisNames[0])
    import mech_dpf
    import Ans.DataProcessing as dpf
    
    ####################################
    # Get IDs of damage object to combine
    damageresults = ExtAPI.DataModel.GetObjectsByName("damage")

    # build set with all nodes
    all_scoped_nodes = []                           # Create List of nodes
    for damageobj in damageresults:
        all_scoped_nodes.extend(damageobj.PlotData.Values[1]) # add nodes from each UDR
    all_scoped_nodes_set = set(all_scoped_nodes)    # create set - eliminate multiple entries
    all_scoped_nodes = list(all_scoped_nodes_set)   # create list from set        
    
    ####################################
    ### Create new results
    
    #analysis=ExtAPI.DataModel.AnalysisByName('Static Structural')
    dataSource = dpf.DataSources(analysis.ResultFileName)
    
    # Read mesh in results file
    mesh_op = dpf.operators.mesh.mesh_provider() # operator instanciation
    mesh_op.inputs.data_sources.Connect(dataSource)
    mesh = mesh_op.outputs.mesh.GetData()
    

    field_list = []
    # go through all values of each damage results and feed them into created field
    for damageobj in damageresults:
        # Create Field of necessary size
        numnodes = len(all_scoped_nodes)                                  # number of nodes
        field = dpf.FieldsFactory.CreateScalarField(numnodes)    # create field with size
        field.MeshedRegionSupport = mesh                         # attach mesh
        field.ScopingIds = all_scoped_nodes                      # give list of nodes
        field.Data = [0. for i in range(0,len(all_scoped_nodes))]# fill field with zeros
        node_scope_udr = damageobj.PlotData.Values[1]
        val_udr = damageobj.PlotData.Values[len(damageobj.PlotData.Values)-1]
    
        for ii in range(0,len(node_scope_udr)):
            index=field.ScopingIds.IndexOf(node_scope_udr[ii])         # get index of node in created field
            field.UpdateEntityDataByEntityIndex(index,[val_udr[ii]])  
        field_list.append(field)
                

################################
    sum_field_list = field_list[0]
    for i in range(0,len(field_list)-1,1):
       sum_field_list = dpf.operators.math.add(fieldA=sum_field_list,fieldB=field_list[i+1])
    # Create field operator for plotting
    combined_plot = dpf.operators.utility.forward_field() # operator instanciation
    combined_plot.inputs.field.Connect(sum_field_list)
    
    ####################################
    ### create plotting workflow
    
    dpf_workflow = dpf.Workflow()
    dpf_workflow.Add(combined_plot)
    
    dpf_workflow.SetOutputContour(combined_plot)
    
    dpf_workflow.Record('wf_id', True)
    this.WorkflowId = dpf_workflow.GetRecordedId()        

There were plenty of other fantastic script tips published this year that weren’t highlighted in this Best of Script Tip Friday 2022 article, that can be found here: Script Tip Friday.

Thank you to all of our subscribers for not only subscribing, but liking, commenting, sharing, and even submitting script tips throughout this past year! We look forward to bringing you even more valuable script tips in 2023.


Do you have a Script Tip worth sharing? Let us know in the comments and we will reach out to learn more and feature you on our next Script Tip Friday.

要查看或添加评论,请登录

Ansys Structures的更多文章

社区洞察

其他会员也浏览了