# [SciPy-user] Finding local minima of greater than a given depth

Zane Selvans zane@ideotrope....
Thu Aug 14 18:37:11 CDT 2008

```Zachary Pincus <zachary.pincus <at> yale.edu> writes:

> Another way to find local minima in a noise-robust manner that I've
> often seen is to not look for a minimum "depth", but for a minimum
> distance between minima. This is easy to implement using
> scipy.ndimage's minimum filter, which sets each element of an array to
> the minimum value seen over a specified neighborhood of that element.
> Then you just check for array elements where the element is equal to
> the minimum in the neighborhood...
>
> I'd also suggest smoothing the data a bit with a gaussian to get rid
> or some of the noise. Scipy.ndimage also provides these filters.

Great!  This works well:

def local_minima(fits, window=15): #{{{
"""
Find the local minima within fits, and return them and their indices.

Returns a list of indices at which the minima were found, and a list of the
minima, sorted in order of increasing minimum.  The keyword argument window
determines how close two local minima are allowed to be to one another.  If
two local minima are found closer together than that, then the lowest of
them is taken as the real minimum.  window=1 will return all local minima.

"""
from scipy.ndimage.filters import minimum_filter as min_filter

minfits = min_filter(fits, size=window, mode="wrap")

minima = []
for i in range(len(fits)):
if fits[i] == minfits[i]:
minima.append(fits[i])

minima.sort()

good_indices = [ fits.index(fit) for fit in minima ]
good_fits = [ fit for fit in minima ]

return(good_indices, good_fits)

```