I have created code to fit the sum of "n" gaussians to my data. Now, I was trying to keep the width or sigma of all gaussians equal using Lmfit expressions, but it caused the kernel that contains the minimize function to die. Here is my code; I've split it into kernels using dashes and indicated which kernel keeps dying.
import scipy
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from numpy import exp, loadtxt, pi, sqrt
from lmfit import Model
from numpy import exp, linspace, pi, random, sign, sin
from lmfit import Parameters, fit_report, minimize
data = np.loadtxt("MyDataFile.csv", delimiter=',', skiprows=1)
x = data[:, 0]
y = data[:, 1]
n=3
--------------------------------------------
def gaussian (x, amp, cen, wid):
return (amp / (sqrt(2*pi) * wid)) * exp(-(x-cen)**2 / (2*wid**2))
def gaussiangenerator(params, i, x):
amp = params['amp_%d' % (i)]
cen = params['cen_%d' % (i)]
wid = params['wid_%d' % (i)]
return gaussian (x, amp, cen, wid)
def objective(params, x, data, n):
individual_fits=np.ones([n, len(x)])
for i in range(1, n+1):
individual_fits[i-1, :] = gaussiangenerator(params, i, x)
resid = data - np.sum(individual_fits, axis=0)
return resid.flatten()
------------------------------------------------------
fit_params = Parameters()
for i in range(1, n+1):
fit_params.add('amp_%d' % (i), value = 1, min = 0.5, max = 10, vary = True)
fit_params.add('cen_%d' % (i), value = 9, min = 0, max = 20, vary = True)
fit_params.add('wid_%d' % (i), value = 1, min = 0, max = 2, vary = True)
for iy in range(1, n+1):
fit_params['wid_%d' % (iy)].expr='wid_%d' % (1)
--------------------------------------------------------
out = minimize(objective, fit_params, args=(x, y, n)) #This is the Kernel that keeps dying when I run it.
----------------------------------------------------------
print(fit_report(out))