import numpy as np import matlab.engine # Start MATLAB engine eng = matlab.engine.start_matlab() eng.addpath('C:/Users/tomoh/Dropbox/SPECTRUM', nargout=0) # Generate some data # Generate some data with two overlapping peaks and random noise x = np.linspace(0, 100, 1000) peak1 = 1.5 * np.exp(-((x - 45) ** 2) / (2 * 4 ** 2)) # First peak, higher and narrower, centered at x=45 peak2 = np.exp(-((x - 50) ** 2) / (2 * 6 ** 2)) # Second peak, lower and wider, centered at x=50 noise = np.random.normal(0, 0.02, len(x)) # Random noise with SNR ~50 y = peak1 + peak2 + noise data_matrix = np.array([x, y]) data_matrix_matlab = matlab.double(data_matrix.tolist()) # Define input arguments for peakfit and convert to MATLAB types center = matlab.double([0]) # Center of region to be fit; zero means to fit the entire signal window = matlab.double([0]) # Width of region to be fit; zero means to fit the entire signal NumPeaks = matlab.double([2])# 2 peaks in the model peakshape = matlab.double([1])# 1=Gaussian, 2=Lorentzian, etc. # Call the MATLAB function and ensure the figure stays open try: FitResults, GOF = eng.peakfit(data_matrix_matlab, center, window, NumPeaks, peakshape, nargout=2) # Generate the figure # Display FitResults in table format print("\nFit Results:") print(f"{'Peak #':<8}{'Position':<12}{'Height':<12}{'Width':<12}{'Area':<12}") print("-" * 56) for row in FitResults: print(f"{int(row[0]):<8}{row[1]:<12.4g}{row[2]:<12.4g}{row[3]:<12.4g}{row[4]:<12.4g}") # Display goodness of fit in formatted output print("\nGoodness of Fit:") print(f"{'% Fitting Error':<18}{'R-squared':<12}") print("-" * 30) print(f"{GOF[0][0]:<18.4g}{GOF[0][1]:<12.4g}") print("The MATLAB figure is displayed. Close it to continue.") input("Press Enter after closing the figure...") except Exception as e: print(f"Error: {e}") # Quit MATLAB engine eng.quit()