Write a Python program that fits data with a number of Gaussian peaks and displays this.
- User
Write a Python program that fits data with a number of Gaussian peaks and displays this.
Assistant
Gaussian Peak Fitting Program
This program uses the
scipylibrary to fit data with a specified number of Gaussian peaks and displays the result.Code
import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt # Define the Gaussian function def gaussian(x, *params): """ Gaussian function with multiple peaks. Parameters: x (array): Input array *params (float): Parameters for the Gaussian function. Each peak is defined by 3 parameters: amplitude, center, and width. """ result = np.zeros_like(x) for i in range(0, len(params), 3): amplitude = params[i] center = params[i + 1] width = params[i + 2] result += amplitude * np.exp(-((x - center) / width) ** 2) return result # Define the main function def main(): # Generate sample data x = np.linspace(-10, 10, 1000) y = 2 * np.exp(-((x - 2) / 1) ** 2) + 1 * np.exp(-((x - 5) / 2) ** 2) + 0.5 * np.exp(-((x - 8) / 3) ** 2) + np.random.normal(0, 0.1, len(x)) # Initial guess for the parameters initial_guess = [2, 2, 1, 1, 5, 2, 0.5, 8, 3] # Fit the data params, _ = curve_fit(gaussian, x, y, p0=initial_guess) # Print the fitted parameters print("Fitted Parameters:") for i in range(0, len(params), 3): print(f"Peak {i//3+1}: amplitude = {params[i]:.2f}, center = {params[i+1]:.2f}, width = {params[i+2]:.2f}") # Plot the data and the fitted curve plt.plot(x, y, label="Data") plt.plot(x, gaussian(x, *params), label="Fitted Curve") plt.legend() plt.show() if __name__ == "__main__": main()Explanation
- The
gaussianfunction defines a Gaussian function with multiple peaks. Each peak is defined by three parameters: amplitude, center, and width. - In the
mainfunction, we generate sample data with three Gaussian peaks and some random noise. - We make an initial guess for the parameters of the Gaussian function.
- We use the
curve_fitfunction fromscipyto fit the data with the Gaussian function. - We print the fitted parameters.
- We plot the data and the fitted curve.
Example Use Case
To use this program, simply run it. You can modify the
initial_guessvariable to change the initial guess for the parameters. You can also modify thexandyvariables to use your own data.Note: This program assumes that the number of peaks is known in advance. If the number of peaks is unknown, you may need to use a more sophisticated method, such as the
find_peaksfunction fromscipy.signal.- The
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.