General Mechanical

General Mechanical

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

Mechanical Scripting: Pressure Import componentwise

    • Dayana Behrens
      Subscriber

      Hi,

      I have a extern csv. file with x,y,z coodinates and x,y,z pressure. I want to import and map the data in Mechanical with a script (not with external data in Workbench, this works). 

      Thank you very much

    • Aniket
      Forum Moderator

      Hi, why you do not want to use external data? If you have a CSV file in a different format, you can easily automate modifications required to it so that it will be compatible with external data.

      -Aniket

      Forum Rules & Guidelines

    • Dayana Behrens
      Subscriber

      Hello, 

      I want to import multiple extern csv-s in Mechanical (about 100k). I saw a tutorial (code is below; source: https://www.linkedin.com/pulse/script-tip-friday-automate-imported-loads-set-up-/). It works, but i have x,y and z components of the pressure. He only imports one component (normal stress). The problem is not in Workbench or external data. It is in Mechanical when I need to define the table with the pressure (as normal stress or with the 3 components) (see picture, sorry it is in german). I have too many cvs-s to do it manually for every csv. I hope this is clear. 

      Thank you very much

      The full code:

      import glob
      import os
      import re
      
      
      template1 = GetTemplate(TemplateName="External Data")
      system1 = template1.CreateSystem()
      setup1 = system1.GetContainer(ComponentName="Setup")

      ####------------------------------------------------------------------------- #Inputs: Setting up External Data  DataPath = r"D:\AutomateExternalLoadImport_Generic\lotsofdata" DataExtension = "txt" DelimiterIs = "Tab"             #Tab --> "Tab", Space --> "Space" DelimiterStringIs = r"\t"       #Tab --> r"\t", Space --> r" " StartImportAtLine = 2 LengthUnit = "mm" PressureUnit = "MPa" #Inputs: Sys ID of the Mechanical System - When you click on Blue bar with name "Static Structural" of a static structural system, you should see the System ID property on the right in the Properties Window system_id = "SYS 2" #Inputs: Setting up the Imported Pressures namedSelectionUsed = "Pressure_Face"

      allfiles = glob.glob1(DataPath,"*." + DataExtension) allfiles.sort(key=lambda f: int(''.join(filter(str.isdigit, f)))) numfilestoload = len(allfiles) for i in range(numfilestoload):     filenum = i+1     completefilepath = os.path.join(DataPath,allfiles[i])     externalLoadFileData = setup1.AddDataFile(FilePath=completefilepath)          if i == 0:         externalLoadFileData.SetAsMaster(Master=True)         externalLoadFileDataProperty1 = externalLoadFileData.GetDataProperty()                  externalLoadFileData.SetStartImportAtLine(             FileDataProperty=externalLoadFileDataProperty1,             LineNumber=StartImportAtLine)                  externalLoadFileData.SetDelimiterType(             FileDataProperty=externalLoadFileDataProperty1,             Delimiter=DelimiterIs,             DelimiterString=DelimiterStringIs)                  externalLoadFileDataProperty1.SetLengthUnit(Unit=LengthUnit)                  externalLoadColumnData1 = externalLoadFileDataProperty1.GetColumnData(Name="ExternalLoadColumnData")         externalLoadFileDataProperty1.SetColumnDataType(             ColumnData=externalLoadColumnData1,             DataType="X Coordinate")         externalLoadColumnData2 = externalLoadFileDataProperty1.GetColumnData(Name="ExternalLoadColumnData 1")         externalLoadFileDataProperty1.SetColumnDataType(             ColumnData=externalLoadColumnData2,             DataType="Y Coordinate")         externalLoadColumnData3 = externalLoadFileDataProperty1.GetColumnData(Name="ExternalLoadColumnData 2")         externalLoadFileDataProperty1.SetColumnDataType(             ColumnData=externalLoadColumnData3,             DataType="Z Coordinate")         externalLoadColumnData4 = externalLoadFileDataProperty1.GetColumnData(Name="ExternalLoadColumnData 3")         externalLoadFileDataProperty1.SetColumnDataType(             ColumnData=externalLoadColumnData4,             DataType="Pressure")         externalLoadColumnData4.Unit = PressureUnit         externalLoadColumnData4.Identifier = allfiles[i]      #Setting up rest of the files timecounter = 1 columncounter = 3 numfiles = len(setup1.GetExternalLoadData().FilesData) for filecounter in range(numfiles-1):     DataFile = setup1.GetExternalLoadData().FilesData[filecounter+1]     DataProp = DataFile.GetDataProperty()          DataFile.SetStartImportAtLine(         FileDataProperty=DataProp,         LineNumber=StartImportAtLine)          DataFile.SetDelimiterType(         FileDataProperty=DataProp,         Delimiter=DelimiterIs,         DelimiterString=DelimiterStringIs)     if filecounter == 0:          columncounter = numfiles+5     else:         columncounter += 3     DataColumn = DataProp.GetColumnData(Name="ExternalLoadColumnData " + str(columncounter))     DataProp.SetColumnDataType(         ColumnData=DataColumn,         DataType="Pressure")     DataColumn.Unit = PressureUnit     timecounter += 1     DataColumn.Identifier = allfiles[filecounter+1] #Mechanical System system2 = GetSystem(Name=system_id)     #Connect External Data to Set up of Mechanical setupComponent2 = system2.GetComponent(Name="Setup") setup2 = system2.GetContainer(ComponentName="Setup") setupComponent1 = system1.GetComponent(Name="Setup") setupComponent1.TransferData(TargetComponent=setupComponent2) setupComponent1.Update(AllDependencies=True) setupComponent2.Refresh() setup2.Edit() systemName = system2.DisplayText mechScriptCmds=""" wbAnalysisName = '{3}' for item in ExtAPI.DataModel.AnalysisList:     if item.SystemCaption == wbAnalysisName:         analysis = item mycaption = analysis.SystemCaption ExtAPI.Log.WriteMessage(mycaption) with Transaction():     import glob     import os     DataPath = r'{0}'     DataExtension = '{1}'     allfiles = glob.glob1(DataPath,"*." + DataExtension)     allfiles.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))     numfilestoload = len(allfiles)     importedloadobjects = [child for child in analysis.Children if child.DataModelObjectCategory.ToString() == "ImportedLoadGroup"]     usedimportedloadobj = importedloadobjects[-1]     importedPres = usedimportedloadobj.AddImportedPressure()     namedsel_importedload = ExtAPI.DataModel.GetObjectsByName('{2}')[0]     importedPres.Location = namedsel_importedload     table = importedPres.GetTableByName("")     for i in range(numfilestoload-1):         table.Add(None)     for i in range(numfilestoload):         table[i][0] = "File"+str(i+1)+":"+str(allfiles[i])         table[i][1] = (i+1)*100     importedPres.ImportLoad() """.format(DataPath,DataExtension,namedSelectionUsed,systemName) model2 = system2.GetContainer(ComponentName="Model")  model2.SendCommand(Language="Python", Command=mechScriptCmds)

    • mjmiddle
      Ansys Employee

      You should be able to do most of if by studying and modifying the script you attached. You'll need to add two pressure data columns in the External Data, so that its just copying the code a couple times and changing a name.

      For the code sent to Mechanical, you'll need this to change the pressure from the default "Normal to" to "Components:

      DefineByProp = importedPres.PropertyByName('PROPID_DefineByType')
      DefineByProp = 0    # 0="Components", 2="Normal To"

      Then, you'll have another two columns of data, so use a couple more indices in the table:

          for i in range(numfilestoload):
              table[i][0] = "File"+str(i+1)+":"+str(allfiles[i])
              table[i][1] = "File"+str(i+2)+":"+str(allfiles[i+1])
              table[i][2] = "File"+str(i+3)+":"+str(allfiles[i+2])
              table[i][3] = (i+1)*100

      This method assumes you have a separate file for each X,Y,Z component of pressure.

       

    • Dayana Behrens
      Subscriber

       

      Hello,

      thank you for your support.

      The first part works, but I still cannot change the components of the pressure. When I try to add it to the code like that:

       

      mechScriptCmds="""
      wbAnalysisName = '{3}'
      for item in ExtAPI.DataModel.AnalysisList:
          if item.SystemCaption == wbAnalysisName:
              analysis = item
      mycaption = analysis.SystemCaption
      ExtAPI.Log.WriteMessage(mycaption)
      with Transaction():
          import glob
          import os
          DataPath = r'{0}'
          DataExtension = '{1}'
          allfiles = glob.glob1(DataPath,"*." + DataExtension)
          allfiles.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))
          numfilestoload = len(allfiles)
          importedloadobjects = [child for child in analysis.Children if child.DataModelObjectCategory.ToString() == "ImportedLoadGroup"]
          usedimportedloadobj = importedloadobjects[-1]
          importedPres = usedimportedloadobj.AddImportedPressure()
      DefineByProp = importedPres.PropertyByName('PROPID_DefineByType')
      DefineByProp = 0    # 0="Components", 2="Normal To"
        namedsel_importedload = ExtAPI.DataModel.GetObjectsByName('{2}')[0]     importedPres.Location = namedsel_importedload     table = importedPres.GetTableByName("")     for i in range(numfilestoload-1):         table.Add(None)     for i in range(numfilestoload):         table[i][0] = "File"+str(i+1)+":"+str(allfiles[i])
              table[i][1] = "File"+str(i+2)+":"+str(allfiles[i+1])
              table[i][2] = "File"+str(i+3)+":"+str(allfiles[i+2])
            table[i][3] = (i+1)*100
        importedPres.ImportLoad() """.format(DataPath,DataExtension,namedSelectionUsed,systemName) model2 = system2.GetContainer(ComponentName="Model")  model2.SendCommand(Language="Python", Command=mechScriptCmds)

       

      When I run it nothing happens. I have of course tried several writing variations, but it doesn’t work. The components are apparently not turned on and therefore no further columns are created.

      I also tried it like that, but it also doesnt work… I have seen this spelling several times, but never for imported pressure

       

      ImportedPres.DefineBy = LoadDefineBy.Components

       

      Best regards

      Dayana

       

       
    • mjmiddle
      Ansys Employee

      Sorry, I had a typo in my previous post. This is how you set to Components:

          DefineByProp = importedPres.PropertyByName('PROPID_DefineByType')
          DefineByProp.InternalValue = 0    # 0="Components", 2="Normal To"

      And you'll need to place the importedPres.ImportLoad() outside (and after) of the "with Transaction():" block of code.

       

    • Dayana Behrens
      Subscriber

      Hi,

      thank you very much. That works! 

      I probably need to contact the author of the code because I can't import the pressure... 
      Everything looks good. However, it doesn't work, not even manually. I get an error message every time I try to import the pressure, but it contains nothing. The yellow flash turns red. ????
      If I click on all components ( pressure_x, pressure_y and pressure_z) manually again and select them, it works. 
      It is not due to the components. It does not work with normal pressure either. 
      The project is a bit crazy by now... I can understand if you can't help me any further ????

      The last part of the code looks like that am:

      mechScriptCmds="""
      wbAnalysisName = '{3}'
      for item in ExtAPI.DataModel.AnalysisList:
          if item.SystemCaption == wbAnalysisName:
              analysis = item
      mycaption = analysis.SystemCaption
      ExtAPI.Log.WriteMessage(mycaption)
      with Transaction():
          import glob
          import os
          DataPath = r'{0}'
          DataExtension = '{1}'
          allfiles = glob.glob1(DataPath,"*." + DataExtension)
          allfiles.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))
          numfilestoload = len(allfiles)
          importedloadobjects = [child for child in analysis.Children if child.DataModelObjectCategory.ToString() == "ImportedLoadGroup"]
          usedimportedloadobj = importedloadobjects[-1]
          importedPres = usedimportedloadobj.AddImportedPressure()
          DefineByProp = importedPres.PropertyByName('PROPID_DefineByType')
          DefineByProp.InternalValue = 0    # 0="Components", 2="Normal To"
          namedsel_importedload = ExtAPI.DataModel.GetObjectsByName('{2}')[0]
          importedPres.Location = namedsel_importedload
          table = importedPres.GetTableByName("")
          for i in range(numfilestoload-1):
              table.Add(None)
          for i in range(numfilestoload):
              table[i][0] = "File"+str(i+1)+":"+str(allfiles[i])+"_x"
              table[i][1] = "File"+str(i+1)+":"+str(allfiles[i])+"_y"
              table[i][2] = "File"+str(i+1)+":"+str(allfiles[i])+"_z"
              table[i][3] = (i+1)
      importedPres.ImportLoad()
      """.format(DataPath,DataExtension,namedSelectionUsed,systemName)
      model2 = system2.GetContainer(ComponentName="Model") 
      model2.SendCommand(Language="Python", Command=mechScriptCmds)

       

    • mjmiddle
      Ansys Employee

       

      I noticed that when I tested the commands that set the pressure components the GUI does not update display until you click away from the pressure on another object, then back on the pressure. Run your code by entering it one line at a time as a means to debug. You can just use the first iteration of your “for” loop that sets the pressure xyz components. Just after you execute the lines that sets these components click on a different Outline object and back on the pressure load to see if it shows the components set.

       

    • Dayana Behrens
      Subscriber

      Hi, 

      thank you very very much for your help. 

      It looks the same for me. Nevertheless, the pressure cannot be imported, unless I manually click on the pressure in each row in the table and select it again from the drop down menu. ????

      It seems to me that Mechanical does not recognize the information in the fields. For example, when I click on the x-component, the y- and z-components turn yellow. This is what it looks like if you have not yet assigned any information to the component. Although the yellow flash indicates that there should be some input and that the fields are not empty. Perhaps it is simply bugged and cannot work like this. ????

    • mjmiddle
      Ansys Employee

      Maybe you are using an old version. I had tested in 2023 R2.

    • mjmiddle
      Ansys Employee

      I had seen in some older versions of Mechanical that it needs to graphically update the change to components before the script could enter the values. So try do the Mechanical commands outside the "with Transaction():" block.

      If that doesn't work place these commands at the beginning of the Mechanical commands:

      clr.AddReference("Ans.Common.WB1ManagedUtils")
      from Ansys.Common.WB1ManagedUtils import TestHelper

      Then just after the commands I gave you to set to component entry type, give the application a wait for 0.5 sec or maybe more to let the graphics update:

      TestHelper().Wait(ms)

      For "ms" test different values to see what works. Try 500 ms, or all the way to 3 seconds (3000).

      You can't use the regular python sleep command or most other wait methods, because it will pause entire application.

    • Dayana Behrens
      Subscriber

      Hi,

      thank you very much. 

      I solved the problem. It was releated to the german version of Ansys:

      table[i][0] = "File"+str(i+1)+":"+str(allfiles[i])+"_x"; It was using "Datei" (german for file) and not "File". After changing the language it worked. Suprisigly it worked for all other german commands...

      Anyway, I am just on step ahead of my workflow. I want to export an stl after the solution: For that I modified parts of your script with your online help:

      commands="""
      STATIC_STRUCTURAL=Model.Analyses[0]
      SOLUTION=STATIC_STRUCTURAL.Solution
      setting2d= Ansys.Mechanical.Graphics.GraphicsImageExportSettings()
      setting3d = Ansys.Mechanical.Graphics.Graphics3DExportSettings()
      TOTAL_DEFORMATION_RESULT=SOLUTION.AddTotalDeformation()
      CAMERA=Graphics.Camera

      SOLUTION.ClearGeneratedData()
      SOLUTION.Solve()

      TOTAL_DEFORMATION_RESULT.Activate()
      CAMERA.SetFit()
      FOLDER_PATH = 'C:\Users\dbehrens\Desktop'
      Graphics.ExportImage(FOLDER_PATH+'\\DEF7.png', GraphicsImageExportFormat.PNG, setting2d)
      TOTAL_DEFORMATION_RESULT.ExportToTextFile(FOLDER_PATH+'\\Txt1.txt')
      Graphics.Export3D(FOLDER_PATH+'\\test.stl', Graphics3DExportFormat.BinarySTL, setting3d)
      result = SOLUTION.Children[1]
      result.ExportToSTLFile("C:\Users\dbehrens\Desktop\test1.stl")
      """
      model3 = system2.GetContainer("Solution") 
      model3.SendCommand(Language="Python", Command=commands)

      Both options doesnt work in this script, but they work in the mechanical scripting window or in shell. Any ideas to fix that?

      Thank you so much ????

    • mjmiddle
      Ansys Employee

      We like to keep forum posts as close to one subject as possible. It makes for sensible lookup of a topic for other users of the forum, when posts have a soluton. Long run-on posts that change to many topics are confusing when people try to find solutions in previous posts. Since this is an unrelated question, please create a new post for this.

Viewing 12 reply threads
  • The topic ‘Mechanical Scripting: Pressure Import componentwise’ is closed to new replies.