Python Forum

Full Version: Fitting Gaussian curve to data file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey,

I'm trying to build a code to fit Gaussians (1, 2 & 3) to some data to determine peak position, and though the code in itself seems to be working, the Gaussian fits all return straight lines. I've tried multiple different guessing parameters, but the result is always a straight line for all 3. If someone has an idea what the problem could be, please help! The code looks like this:

import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize

data = np.genfromtxt('file')

def gaussian(x, height, center, width, offset):
    return height*np.exp(-(x - center)**2/(2*width**2)) + offset

def two_gaussians(x, h1, c1, w1, h2, c2, w2, offset):
    return three_gaussians(x, h1, c1, w1, h2, c2, w2, 0,0,1, offset)

def three_gaussians(x, h1, c1, w1, h2, c2, w2, h3, c3, w3, offset):
    return (gaussian(x, h1, c1, w1, offset=0) +
        gaussian(x, h2, c2, w2, offset=0) +
        gaussian(x, h3, c3, w3, offset=0) + offset)

errfunc2 = lambda p, x, y: (two_gaussians(x, *p) - y)**2
errfunc3 = lambda p, x, y: (three_gaussians(x, *p) - y)**2

guess2 = [514, 900, 20, 552, 925, 20, 275]
guess3 = [514, 900, 20, 552, 925, 20, 531, 950, 20, 275]  
optim2, success = optimize.leastsq(errfunc2, guess2[:], args=(data[:,0], data[:,1]))
optim3, success = optimize.leastsq(errfunc3, guess3[:], args=(data[:,0], data[:,1]))

plt.plot(data[:,0], data[:,1], lw=1, c='b', label='sync1')
plt.plot(data[:,0], data[:,2], lw=1, c='r', label='sync2')
plt.plot(data[:,0], gaussian(data[:,1], 552, 925, 20, 275),
    lw=1, c='m', ls='--', label='Gaussian')
plt.plot(data[:,0], two_gaussians(data[:,1], *optim2),
    lw=1, c='y', ls='--', label='2 Gaussians')
plt.plot(data[:,0], three_gaussians(data[:,1], *optim3),
    lw=1, c='g', ls='--', label='3 Gaussians')
#plt.xlim([200, 2000])
#plt.ylim([0, 700])
plt.legend(loc='best')
The plot this code now gives is in attachments. Could the problem be in the error functions? Switching initial guess gives a small peak if I optimize column 2 and plot the first one, but it's still nowhere near the shape of the data since the amplitude is around 2 and two_gaussian is negative. I've fitted multi-gaussians to data before, and it should be a relatively simple prodecure, but the results are definitely not good.