# SCRIPTS FITTING lmfit_gaussianΒΆ

```# -*-Python-*-
# Created by bgrierson at 13 Dec 2016  08:55

from pylab import random

# A gaussian function a*exp(-(x-x0)**2/w**2) + b
def func(x, a, x0, w, b):
return a * np.exp(-((x - x0) ** 2) / w ** 2) + b

# The function to minimize (ydata - ymodel) / uncertainty
def funcm(params, xm, ym, em):
a = params['a'].value
x0 = params['x0'].value
w = params['w'].value
b = params['b'].value
y = func(xm, a, x0, w, b)
r = (ym - y) / em
return r

# Gaussian parameters
a = 2.0
x0 = 0.5
w = 0.1
b = 0.0

# Make the data and uncertainty
nx = 101
xdata = linspace(0, 1, nx)
ydata = func(xdata, a, x0, w, b) + 0.1 * random(nx)
yerr = np.repeat(0.1, len(xdata))

# Create the lmfit paramters with guesses near the true values
params = lmfit.Parameters()

# Do the fit
fitter = lmfit.Minimizer(funcm, params, fcn_args=(xdata, ydata, yerr))
out = fitter.minimize()
print(lmfit.fit_report(out))

# Get the fit result
yfit = func(xdata, out.params['a'].value, out.params['x0'].value, out.params['w'].value, out.params['b'].value)

# Compute the residual
resid = funcm(out.params, xdata, ydata, yerr)

# Plot the result
fig, ax = plt.subplots(nrows=2)
uerrorbar(xdata, uarray(ydata, yerr), ax=ax[0], markersize=3.0, label='Data')
ax[0].plot(xdata, yfit, label='Fit')
ax[0].text(0.05, 2.0, '\$\\chi_r^2={0:0.3f}\$'.format(out.redchi))
ax[0].legend(loc='best')
ax[1].plot(xdata, resid, marker='o', ls='None')
ax[1].axhline(0.0, ls='dashed', color='black')
ax[1].set_ylim([-np.max(np.abs(ax[1].get_ylim())), np.max(np.abs(ax[1].get_ylim()))])
```