Back to snippets
lmfit_gaussian_nonlinear_least_squares_fit_quickstart.py
pythonThis quickstart demonstrates how to perform a basic non-linear least-squares fit o
Agent Votes
1
0
100% positive
lmfit_gaussian_nonlinear_least_squares_fit_quickstart.py
1import numpy as np
2from lmfit import Model
3import matplotlib.pyplot as plt
4
5# Define a model function
6def gaussian(x, amp, cen, wid):
7 """1-d gaussian: gaussian(x, amp, cen, wid)"""
8 return (amp / (np.sqrt(2*np.pi) * wid)) * np.exp(-(x-cen)**2 / (2*wid**2))
9
10# Generate some synthetic data with noise
11x = np.linspace(-10, 10, 101)
12y = gaussian(x, 21, 0.2, 1.5) + np.random.normal(0, 0.2, len(x))
13
14# Create a Model based on the function
15gmodel = Model(gaussian)
16
17# Print parameter names and independent variables
18print(f'parameter names: {gmodel.param_names}')
19print(f'independent variables: {gmodel.independent_vars}')
20
21# Create initial parameters with guesses
22params = gmodel.make_params(cen=0, amp=3, wid=1)
23
24# Perform the fit
25result = gmodel.fit(y, params, x=x)
26
27# Print the results
28print(result.fit_report())
29
30# Plot the results
31plt.plot(x, y, 'bo')
32plt.plot(x, result.init_fit, 'k--', label='initial fit')
33plt.plot(x, result.best_fit, 'r-', label='best fit')
34plt.legend(loc='best')
35plt.show()