General Mechanical

General Mechanical

Topics related to Mechanical Enterprise, Motion, Additive Print and more.

Python Code Object not working when updating Design Points

    • Akshay Panchwagh
      Subscriber

      Hello everyone!

       

      I am performing a parameter study in Transient Thermal in which I need to export the temperature results for all time steps to a CSV file. I have a Python script which works perfectly fine when I run it in the Mechanical Scripting editor. But when I try to update the Design Points from Workbench, the Python Code does not work.

       

      For reference, this is script I am using at the moment which runs perfectly fine in Mechanical Scripting editor:
          
          import csv
          import os
          import wbjn
          
        
          dpn=wbjn.ExecuteCommand(ExtAPI,"returnValue(a+Parameters.GetActiveDesignPoint().Name)",a="DP")
          
          cmd = "returnValue(GetUserFilesDirectory())"
          user_dir = wbjn.ExecuteCommand(ExtAPI, cmd)
          
          

          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('Directional Deformation')

       

       

          #import wbjn


          AnalysisNumber=0

       

          solution=Model.Analyses[AnalysisNumber].Solution

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

              if item.GetType() == Ansys.ACT.Automation.Mechanical.Results.DeformationResults.DirectionalDeformation:

                  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 + "/" + dpn+ "Deformation.csv", data)

       

      As I stated earlier, while updating the Design Points through Parameter Set in Workbench, the results do not get stored. Is there any solution for this?

       

      P.S.: I have already checked the option where one needs to connect the Python script under Workbench -> Tools -> Option -> Mechanical -> Connect/Run Python Code Objects when Mechanical is launched.

       

      EDIT: The above script is for a sample problem in which I am trying to obtain results before I actually implement it for my use-case. Under Ansys.ACT.Automation.Mechanical.Results, results of choice can be extracted. 

    • mrife
      Ansys Employee

      Hi Akshay

      Which version of Workbench are you using?  Mike

      • Akshay Panchwagh
        Subscriber

         

        Hello Mike,

        Thank you for following up. I am using 2022 R2 Enterprise. 

         

        Regards,

        Akshay

    • Akshay Panchwagh
      Subscriber

      Hello Mike,

      Thank you for following up. I am using 2022 R2 Enterprise. 

       

      Regards,

      Akshay

       

    • mrife
      Ansys Employee

      Akshay

      In the Details of the Python Code object make sure that the 'Target Callback' is set to 'After Post'.  I tested your above code on a simple model and it worked though I did change what was written to the file from result data to just the DP number.  Since I only wanted to verify that something was written at each DP.

      Mike

      • Akshay Panchwagh
        Subscriber

        Hi Mike,

        That is quite reassuring to know that the code worked. Even in my case the Target Callback is set to "After Post". I wonder what is going wrong. The above code was written between "def after_post(this, solution)" and "pass".

        Tomorrow I will look into it again and provide an update.

         

        P.S.: Did you update your Design Points through Workbench without opening Mechanical? I read somewhere today that apparantly some commands in this code need the Mechanical GUI running. Outside the Mechanical GUI they do not work. Hence I just wanted to clarify it.

         

        Regards,

        Akshay

    • mrife
      Ansys Employee

      Akshay

      Correct I did the DP from Workbench with Mechanical closed.  Mechanical does open as a background process as it needs to create the input file for each DP.  Then extract the result data for any result object once the DP completes solving.

      • Akshay Panchwagh
        Subscriber

        Hi Mike, Hi mjmiddle,

        It still does not work for me unfortunately. Only when I manually select a new Design Point under "Set as Current" in the Parameter Set and update the whole thing through Mechanical does it save the CSV files. I really don't know what is going wrong here. 

         

        Regards,

        Akshay

      • Akshay Panchwagh
        Subscriber

        Hello Mike, Hello mjmiddle,

         

        So there has been some progress. I did minor changes through which my script is now generating a CSV file for every Design Point I am updating through the Parameter Set. But the results are not getting stored in those files. When I manually run the script in Mechanical, only then are the results getting saved in the generated CSV files. 

        For your reference, here is the actual code that I am using:

         

        def after_post(this, solution):# Do not edit this line
            """
            Called after post processing.
            Keyword Arguments : 
                this -- the datamodel object instance of the python code object you are currently editing in the tree
                solution -- Solution
            """

            # User Dir

            import os
            import csv
            import wbjn
            
            userfilesdir = wbjn.ExecuteCommand(ExtAPI,"""returnValue(GetUserFilesDirectory())""")
            #DPValue as parameter

            DPValue = this.GetCustomPropertyByPath("Parameter/DPValue").Value
            dpn = "DP_"+str(int(DPValue))
            
            file_name = os.path.join(userfilesdir, dpn+"data.csv")
            file_handle = open(file_name, "wb")
            
            ResultsOfInterest = []
            
            for i in range(1,5):
                ResultsOfInterest.append(ExtAPI.DataModel.AnalysisList[0].Solution.Children[i].Name)
            
            
            
            solution=ExtAPI.DataModel.AnalysisList[0].Solution

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

                if item.GetType() == Ansys.ACT.Automation.Mechanical.Results.ThermalResults.TemperatureResult:
            
                    if item.Name in ResultsOfInterest:

                        item.Activate()

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

                        Con = Pane.ControlUnknown

                        for R in range(1,Con.RowsCount+1):
                            for C in range(2,Con.ColumnsCount+1):
                                cellText = Con.cell(R, C).Text
                                file_handle.write("%s;" % cellText)
                            file_handle.write("\n")

            file_handle.close()
            pass

        Do you have any suggesstions?

         

        Regards,

        Akshay

    • mjmiddle
      Ansys Employee

      The "Tools -> Options -> Mechanical -> Connect/Run Python Code Objects when Mechanical is launched" will not work unless you have opened Mechanical in the active design point and right clicked on the python code object to "Connect."

    • mjmiddle
      Ansys Employee

      Your code is reading the time history directly from the Mechanical GUI panel, and you can't do that when updating through design points, because it opens Mechanical in the background (without the GUI):

      Pane=ExtAPI.UserInterface.GetPane(MechanicalPanelEnum.TabularData)
      Con = Pane.ControlUnknown
      for R in range(1,Con.RowsCount+1):
          for C in range(2,Con.ColumnsCount+1):
              cellText = Con.cell(R, C).Text
              file_handle.write("%s;" % cellText)
          file_handle.write("\n")

      One way to resolve this would be to use the objects under the result object to obtain the max, min, avg:

      item.GetType() == Ansys.ACT.Automation.Mechanical.Results.ThermalResults.TemperatureResult
      item.Maximum
      item.Minimum
      item.Average

      You will need to get the result set time list or the number of result sets and either set the display time or set result object by result set number and evaluate for each result in a loop:

      reader = analysis.GetResultsData()
      rsets = reader.ResultSetCount
      item.By = Ansys.Mechanical.DataModel.Enums.SetDriverStyle.ResultSet
      for rset in range(1,rsets+1):
          item.SetNumber = rset
          item.EvaluateAllResults()
          # get max,min,avg and write to csv file

      or:

      rtimes = reader.ListTimeFreq
      for rtime in rtimes:
          item.DisplayTime = rtime
          item.EvaluateAllResults()
          # get max,min,avg and write to csv file

      • Akshay Panchwagh
        Subscriber

        Hello mjmiddle,

         

        you're right about the first part. After going through my code, I realised that the code is reading the history direcly from Mechanical, and for that it will always need Mechanical to be open and running. 

         

        Coming to the suggestions you provided, I did try applying it. But I am unable to produce useful results from it.

        If I use it with rset, i.e. the ResultSetCount, it gives an error: 'PythonCodeEventBased' object has no attribute 'By'. I believe this error arises when I use the line 'item.By'. 

        And when I use it with rtime, i.e. the ListTimeFreq, it gives an error saying: 'Expected Quantity, received float'. The line item.DisplayTime = rtime throws this error. 

         

        I tried finding some documentation about it but had no success.

         

        I have been able to extract the time step counts, or the actual time steps. But I am unable to connect them somehow with the intermediary result values. Even if I put it in a loop, and try to append the values to a list just to see what is happening, only the temperature values for the last time step are getting saved into the list. 

         

        I am unable to follow where exactly it is going wrong with these suggesstions you provided. Can you please elaborate a bit more, if you don't mind? 

         

         

        Regards,

        Akshay

    • mjmiddle
      Ansys Employee

      Have you gone over any training, such as the ACT training for Mechanical in the Ansys Learning Hub? It discusses the use of Quantity(). I can probably find some locations in the Ansys documentation also. What version are you using? The "By" will exist under native results. Are you getting results from an ACT generated result defined in the XML file of the extension?

      Is the "item" the result object? The forum post question has been answered. From here you have to do some reguar development activities that you would always need to do when creating something that works with results. Do some exploration and list what objects you have. Change an item in the Details and see how the object you want underneath changes. Get the result in the Outline:

      result1 = ExtAPI.DataModel.Project.Model.Analyses[0].Children[1]

      dir(result1)

       

      • Akshay Panchwagh
        Subscriber

        Have you gone over any training, such as the ACT training for Mechanical in the Ansys Learning Hub?

        - No I haven't. But thank you for the suggestion. I will check it out. It will help me with other activities as well. As an Enterprise user, do I have access to it? Or do I need some subscription? 

         

        What version are you using?

        - 2022R2 Enterprise edition

         

        Is the "item" the result object?

        - Yes it is. for j, item in enumerate(solution.Children): When I execute this for loop, the "j" is for the 4 solutions I am evaluating and the results get are stored in the variable "item"

         

         

        Thank you for answering everything until now. You are right. I should to build up on this. I am not well versed with ACT, or scripting in ANSYS using Python, for that matter. This is the first instance that I am using it. So that's why it is taking some time to figure everything out. In addition to that, if the code fails, it is kind of difficult to figure out what went wrong as in the Shell, only the error appears. It does not mention while line has encountered the error, making it a bit more challenging. Only if the Python Code Object is executed, then the source of error is atleast a bit easier to decipher. But I feel the ACT training you mentioned should be helpful in resolving any questions I have/might encounter in future. 

         

        Regards,

        Akshay

    • mjmiddle
      Ansys Employee

       

      The Ansys Learning Hub does take a yearly subscription. The ACT Training for Mechanical there is old. It is a nice place to get started but not absolutely necessary. It focuses on writing ACT extensions, but you learn a lot more about scripting in the training even if you just want to write simple scripts and not ACT extensions.

      I tried item.By=Ansys.Mechanical.DataModel.Enums.SetDriverStyle.ResultSet in a native temperature result in 2022 R2, and this worked for me so I don’t know what kind of object you have.

      There is a quick definition of the Quantity() here, but you will find it in lots of places in the Scripting in Mechanical Guide:

      https://ansyshelp.ansys.com/account/secured?returnurl=/Views/Secured/corp/v232/en/act_script/mech_apis_ObjectProps.html

      Speaking of that, some places to learn about scripting can be found in the Ansys help (https://ansyshelp.ansys.com) at:

      Mechanical Application > Scripting in Mechanical Guide

      Customization Suite > ACT Developer’s Guide

      Customization Suite > ACT Customization Guide for Mechanical

      At Ansys Customer Portal (https://support.ansys.com/Home/HomePage), go to “Downloads > ACT Resources”

      You should explore objects on your own by getting objects from the Outline and using dir(object). You can get the first result item after the “Solution Information” object with:

      result1 = ExtAPI.DataModel.Project.Model.Analyses[0].Children[1]

       

      • Akshay Panchwagh
        Subscriber

        I figured out the problem for the code line item.By=Ansys.Mechanical.DataModel.Enums.SetDriverStyle.ResultSet. In definition, it was set to "Time" and not "Result Set". I changed it now. Thank you for sharing the screen grab. I was able to figure out the issue thanks to it.

Viewing 8 reply threads
  • The topic ‘Python Code Object not working when updating Design Points’ is closed to new replies.