How to find FWHM in a dataset with multiple peaks?

2019-02-21 06:57发布

问题:

I'm using a Python script which finds the indexes of the peaks (or valleys in my case) along a 1D profile, in a specific range of values. My aim is to measure the FWHM for each valley of interest. This is an example of 1D profile

This is the script:

def detect_peaks (x, mnph=None, mxph=None, mpd=1, threshold=0, edge='rising',
             kpsh=False, valley=False, show=False, ax=None):
#from __future__ import division, print_function
import numpy as np
x = np.atleast_1d(x).astype('float64')
if x.size < 3:
    return np.array([], dtype=int)
if valley:
    x = -x
# find indices of all peaks
dx = x[1:] - x[:-1]
# handle NaN's
indnan = np.where(np.isnan(x))[0]
if indnan.size:
    x[indnan] = np.inf
    dx[np.where(np.isnan(dx))[0]] = np.inf
ine, ire, ife = np.array([[], [], []], dtype=int)
if not edge:
    ine = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) > 0))[0]
else:
    if edge.lower() in ['rising', 'both']:
        ire = np.where((np.hstack((dx, 0)) <= 0) & (np.hstack((0, dx)) > 0))[0]
    if edge.lower() in ['falling', 'both']:
        ife = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) >= 0))[0]
ind = np.unique(np.hstack((ine, ire, ife)))
# handle NaN's
if ind.size and indnan.size:
    # NaN's and values close to NaN's cannot be peaks
    ind = ind[np.in1d(ind, np.unique(np.hstack((indnan, indnan-1, indnan+1))), invert=True)]
# first and last values of x cannot be peaks
if ind.size and ind[0] == 0:
    ind = ind[1:]
if ind.size and ind[-1] == x.size-1:
    ind = ind[:-1]
"""ABOUT mnph and mxph => It works just on valleys, for peaks: REMOVE the minus ("-") below in the code"""
# remove valleys < minimum peak height
if ind.size and mnph is not None:
    ind = ind[-x[ind] >= mnph]
# remove valleys > maximum peak height
if ind.size and mxph is not None:
    ind = ind[-x[ind] <= mxph]
return ind

How can I perform this operation?

回答1:

You can do this using a Gaussian Mixture Model. I don't think there is a function in SciPy, but there is one in scikit-learn

Here is a tutorial on this.