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
Below is a compact, self-contained script that
- generates synthetic data consisting of several Gaussian peaks plus noise,
- fits the data with a user-chosen number of Gaussians using non-linear least squares,
- plots the raw data, the individual fitted peaks and the total model.
You can also feed it your own x, y vectors – just replace the synthetic-data block.
#!/usr/bin/env python3 """ fit_n_gaussians.py Fit an arbitrary number of Gaussian peaks to 1-D data and display the result. """ import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit # ------------------------------------------------------------------ # 1. Synthetic data (replace with your own x, y if desired) # ------------------------------------------------------------------ def make_fake_data(): x = np.linspace(0, 100, 500) true_peaks = [ (30, 1.0, 5), # (center, amplitude, sigma) (50, 0.7, 7), (75, 0.9, 4) ] y = np.zeros_like(x) for c, a, s in true_peaks: y += a * np.exp(-0.5 * ((x - c) / s) ** 2) rng = np.random.default_rng(42) y += 0.05 * rng.normal(size=y.size) # noise return x, y x, y = make_fake_data() # ------------------------------------------------------------------ # 2. Model: sum of n Gaussians # ------------------------------------------------------------------ def gaussian(x, c, a, s): """Single Gaussian: center, amplitude, sigma.""" return a * np.exp(-0.5 * ((x - c) / s) ** 2) def multi_gaussian(x, *params): """ Sum of n Gaussians. params = [c1, a1, s1, c2, a2, s2, ...] """ n = len(params) // 3 out = 0.0 for i in range(n): out += gaussian(x, *params[3*i:3*i+3]) return out # ------------------------------------------------------------------ # 3. Fit # ------------------------------------------------------------------ n_peaks = 3 # <-- change this initial = [] for k in range(n_peaks): # crude initial guesses: evenly spaced centers, equal amps, equal widths initial += [x.min() + (x.max()-x.min())*(k+0.5)/n_peaks, y.max()/n_peaks, (x.max()-x.min())/n_peaks/2] popt, pcov = curve_fit(multi_gaussian, x, y, p0=initial) # ------------------------------------------------------------------ # 4. Plot # ------------------------------------------------------------------ plt.figure(figsize=(8, 5)) plt.scatter(x, y, s=8, color='k', label='data') # total model x_fine = np.linspace(x.min(), x.max(), 1000) plt.plot(x_fine, multi_gaussian(x_fine, *popt), 'r-', lw=2, label='total fit') # individual peaks for i in range(n_peaks): c, a, s = popt[3*i:3*i+3] plt.plot(x_fine, gaussian(x_fine, c, a, s), '--', label=f'peak {i+1}') plt.xlabel('x') plt.ylabel('y') plt.legend() plt.title(f'Fit with {n_peaks} Gaussian peaks') plt.tight_layout() plt.show()How to use with real data
Replace the synthetic-data block with something like:
x = np.loadtxt('spectrum.txt')[:, 0] y = np.loadtxt('spectrum.txt')[:, 1]and adjust
n_peaksto the number of peaks you expect.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.