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

pari
Member Posts: 9
**
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:
0
Best 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 :
- I simply save the x-y data of the Transmission loss in a text file in the user_files folder,
- I plot it using matplotlib and save the plot as a png file.
- Using this approach I also have the possibility of customizing my plot a little bit (for example adding peaks etc.)
- import os
- def GetUserFileFolder(analysis):
- '''
- Return UserDir: path of the folder
- '''
- try:
- WorkDir = analysis.WorkingDir
- UserDir = os.path.dirname(WorkDir)
- for i in range(3):
- UserDir = os.path.dirname(UserDir)
- UserDir = os.path.join(UserDir, 'user_files')
- if not os.path.exists(UserDir):
- os.makedirs(UserDir)
- return UserDir
- except:
- ExtAPI.Log.WriteMessage("Error : Exception in GetUserFileFolder()")
- return None
- def after_post(this, solution):# Do not edit this line
- import wbjn
- import context_menu
- import os
- import matplotlib.pyplot as plt
- import time
- import numpy as np
- from scipy.signal import find_peaks
- userFilePath = GetUserFileFolder(solution.Parent)
- tl_path = os.path.join(userFilePath, "tLoss_curve.txt")
- tl_curve = [x for x in solution.Children if x.Name == "Transmission Loss"][0]
- tl_curve.ExportToTextFile(tl_path)
- time.sleep(1)
- # Load the data from the CSV file
- data = np.genfromtxt(tl_path, skip_header=1)
- # Extract the frequency and transmission loss data from the CSV file
- freq = data[:,0]
- loss = data[:,1]
- # Detect the peaks in the transmission loss data
- peaks, _ = find_peaks(loss)
- # Plot only the peaks with their corresponding frequency and transmission loss values
- plt.plot(freq, loss, color='red')
- plt.plot(freq[peaks], loss[peaks], "o", markerfacecolor='red', markeredgecolor='black')
- for i in peaks:
- plt.text(freq[i], loss[i], f"({freq[i]:.0f}Hz, {loss[i]:.0f}dB)", fontsize=8)
- plt.xlabel('Frequency (Hz)')
- plt.ylabel('Transmission Loss (dB)')
- plt.title('Transmission Loss vs Frequency')
- # increase figure width
- fig = plt.gcf()
- plt.grid(True)
- fig.set_size_inches(15, 6) # 8 inches wide, 4 inches tall
- # save plot as png image
- plt.savefig(os.path.join(userFilePath, "tLoss_curve.png"))
- plt.show()
The default Ansys Result curve looks like this:
And my python code generates this image:
0
Answers
-
This is probably longer than it needs to be, but you can see what is going on line by line:
- #This will export the Worksheet View.
- #You must have the view you want to export active, as this is a screen level screen capture.
- #Path to your image:
- ImgPath=r'C:\Users\mthompso\MyData\DeleteThis\test2.png'
- #routine
- import chart
- import os
- import clr
- clr.AddReference("System.Windows.Forms")
- clr.AddReference("System.Drawing")
- clr.AddReference("Ans.UI")
- clr.AddReference("Ans.Utilities")
- VersionInfo = Ansys.Utilities.ApplicationConfiguration.DefaultConfiguration.VersionInfo
- clr.AddReference("Ansys.Common.Interop."+VersionInfo.VersionString)
- import Ansys
- import time
- from System.Drawing import Bitmap, Graphics, Point, Size
- from System.Windows.Forms import (
- Application, Button, Form, FormWindowState,
- PictureBox, Screen )
- from module_base import *
- #Non-blocking sleep
- def Wait(ms):
- helper = Ansys.Common.Interop.WBControls.WBTestHelper()
- helper.Wait(ms)
- def ScreenCapture(FilePath,X1,Y1,w,h):
- #bmp = Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height) # For Full Screen
- bmp = Bitmap((w), (h))
- g = Graphics.FromImage(bmp)
- g.CopyFromScreen(X1,Y1 ,0,0, Size((w),(h)))
- # g.CopyFromScreen(0,0,0,0, bmp.Size) # For Full Screen
- bmp.Save(FilePath)
- g.Dispose()
- figures = chart.Figures(0,0)
- Dummy_Control=figures.view
- figurePanel = ExtAPI.UserInterface.AttachControlToPanel(Dummy_Control, MechanicalPanelEnum.Worksheet)
- figurePanel.Hide()
- wp=figurePanel.Control.Width
- hp=figurePanel.Control.Height
- figurePanel.Close()
- figurePanel = None
- WorksheetPane=ExtAPI.UserInterface.GetPane(MechanicalPanelEnum.Worksheet)
- X1Loc=WorksheetPane.CommandContainer.WindowRect.Left
- Y1Loc=WorksheetPane.CommandContainer.WindowRect.Top
- FileName="Worksheet.png"
- Wait(100)
- ScreenCapture(ImgPath,X1Loc,Y1Loc,wp,hp)
0