How to export results like "Transmission Loss" from the Harmonic Acoustics module?

Member Posts: 9
First Anniversary Photogenic Name Dropper First Comment
**
edited June 2023 in Structures

Hello,

I want to programmatically export this result as an image (.png or .jpg). Is there a way to do it?

I am able to export the curve as points, but not the image itself. When I use the "Image" button in Ansys, it creates an image of the model itself, instead of the Transmission Loss Curve.

Thank you!

Tagged:

Best Answer

  • Member Posts: 9
    First Anniversary Photogenic Name Dropper First Comment
    **
    Answer ✓

    Hello Mike, thank you for the snippet. I havent tried that out, but in the meantime I tried to come up with a workaround using the Python After-post Command snippet :

    1. I simply save the x-y data of the Transmission loss in a text file in the user_files folder,
    2. I plot it using matplotlib and save the plot as a png file.
    3. Using this approach I also have the possibility of customizing my plot a little bit (for example adding peaks etc.)
    1. import os
    2.  
    3. def GetUserFileFolder(analysis):
    4.   '''
    5.     Return UserDir: path of the folder
    6.   '''
    7.   try:
    8.     WorkDir = analysis.WorkingDir
    9.     UserDir = os.path.dirname(WorkDir)
    10.     for i in range(3):
    11.       UserDir = os.path.dirname(UserDir)
    12.     UserDir = os.path.join(UserDir, 'user_files')
    13.     if not os.path.exists(UserDir):
    14.       os.makedirs(UserDir)
    15.     return UserDir
    16.   except:
    17.     ExtAPI.Log.WriteMessage("Error : Exception in GetUserFileFolder()")
    18.     return None
    19.  
    20. def after_post(this, solution):# Do not edit this line
    21.   import wbjn
    22.   import context_menu
    23.   import os
    24.   import matplotlib.pyplot as plt
    25.   import time
    26.   import numpy as np
    27.   from scipy.signal import find_peaks
    28.    
    29.   userFilePath = GetUserFileFolder(solution.Parent)
    30.   tl_path = os.path.join(userFilePath, "tLoss_curve.txt")
    31.   tl_curve = [x for x in solution.Children if x.Name == "Transmission Loss"][0]
    32.    
    33.   tl_curve.ExportToTextFile(tl_path)
    34.    
    35.   time.sleep(1)
    36.    
    37.   # Load the data from the CSV file
    38.   data = np.genfromtxt(tl_path, skip_header=1)
    39.    
    40.   # Extract the frequency and transmission loss data from the CSV file
    41.   freq = data[:,0]
    42.   loss = data[:,1]
    43.    
    44.   # Detect the peaks in the transmission loss data
    45.   peaks, _ = find_peaks(loss)
    46.    
    47.   # Plot only the peaks with their corresponding frequency and transmission loss values
    48.   plt.plot(freq, loss, color='red')
    49.   plt.plot(freq[peaks], loss[peaks], "o", markerfacecolor='red', markeredgecolor='black')
    50.    
    51.   for i in peaks:
    52.     plt.text(freq[i], loss[i], f"({freq[i]:.0f}Hz, {loss[i]:.0f}dB)", fontsize=8)
    53.    
    54.   plt.xlabel('Frequency (Hz)')
    55.   plt.ylabel('Transmission Loss (dB)')
    56.   plt.title('Transmission Loss vs Frequency')
    57.   # increase figure width
    58.   fig = plt.gcf()
    59.   plt.grid(True)
    60.   fig.set_size_inches(15, 6) # 8 inches wide, 4 inches tall
    61.    
    62.   # save plot as png image
    63.   plt.savefig(os.path.join(userFilePath, "tLoss_curve.png"))
    64.   plt.show()

    The default Ansys Result curve looks like this:

    And my python code generates this image:


Answers

  • Member, Employee Posts: 385
    25 Answers 100 Comments Second Anniversary 25 Likes
    ✭✭✭✭

    This is probably longer than it needs to be, but you can see what is going on line by line:

    1. #This will export the Worksheet View.
    2. #You must have the view you want to export active, as this is a screen level screen capture.
    3. #Path to your image:
    4. ImgPath=r'C:\Users\mthompso\MyData\DeleteThis\test2.png'
    5.  
    6.  
    7. #routine
    8. import chart
    9. import os
    10. import clr
    11. clr.AddReference("System.Windows.Forms")
    12. clr.AddReference("System.Drawing")
    13. clr.AddReference("Ans.UI")
    14. clr.AddReference("Ans.Utilities")
    15. VersionInfo = Ansys.Utilities.ApplicationConfiguration.DefaultConfiguration.VersionInfo
    16. clr.AddReference("Ansys.Common.Interop."+VersionInfo.VersionString)
    17. import Ansys
    18. import time
    19. from System.Drawing import Bitmap, Graphics, Point, Size
    20. from System.Windows.Forms import (
    21.     Application, Button, Form, FormWindowState,
    22.     PictureBox, Screen )
    23. from module_base import *
    24.  
    25.  
    26. #Non-blocking sleep
    27. def Wait(ms):
    28.     helper = Ansys.Common.Interop.WBControls.WBTestHelper()
    29.     helper.Wait(ms)
    30. def ScreenCapture(FilePath,X1,Y1,w,h):
    31.     #bmp = Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height) # For Full Screen
    32.     bmp = Bitmap((w), (h))
    33.     g = Graphics.FromImage(bmp)
    34.     g.CopyFromScreen(X1,Y1 ,0,0, Size((w),(h)))
    35.     # g.CopyFromScreen(0,0,0,0, bmp.Size) # For Full Screen
    36.    
    37.     bmp.Save(FilePath)
    38.     g.Dispose()
    39.  
    40.  
    41. figures = chart.Figures(0,0)
    42. Dummy_Control=figures.view
    43. figurePanel = ExtAPI.UserInterface.AttachControlToPanel(Dummy_Control, MechanicalPanelEnum.Worksheet)
    44. figurePanel.Hide()
    45. wp=figurePanel.Control.Width
    46. hp=figurePanel.Control.Height
    47. figurePanel.Close()
    48. figurePanel = None
    49. WorksheetPane=ExtAPI.UserInterface.GetPane(MechanicalPanelEnum.Worksheet)
    50. X1Loc=WorksheetPane.CommandContainer.WindowRect.Left
    51. Y1Loc=WorksheetPane.CommandContainer.WindowRect.Top
    52. FileName="Worksheet.png"
    53. Wait(100)
    54. ScreenCapture(ImgPath,X1Loc,Y1Loc,wp,hp)

Welcome!

It looks like you're new here. Sign in or register to get started.