Search code examples
pythonnumpyscipymaxima

Python: Find maxima and discontinuities in a numpy array


I have a question related to finding maxima or more preciseley discontinuities in a numpy array? My exemplary data looks for example like this

a = np.array([3,4,5,8,7,6,5,4,1])

In general, I am interested in every maximum/jump in the data. For array a, I want to detect the 8 since it is a maximum (growing numbers on the left side and decreasing numbers on the right) and the value of 4, since the data drops after this value. Until now, I have used scipy.signal.argrelextrema with np.greater to detect maxima, but I am not able to detect these jumps/discontinuities. For the data I am looking at, only a jump towards smaller values can occur not the opposite. Is there an easy pythonic way to detect these jumps?


Solution

  • Let's try this:

    threshold = 1
    a = np.array([3, 4, 5, 8, 7, 6, 5, 4, 1])
    discontinuities_idx = np.where(abs(np.diff(a))>threshold)[0] + 1
    

    np.diff(a) gives the difference between every component of a:

    >>> array([ 1,  1,  3, -1, -1, -1, -1, -3])
    

    From then np.where(abs(np.diff(a))>threshold)[0] is applied to find where detected discontinuities are (above user specified threshold in terms of absolute difference). Finally, you may add +1 to compensate for n=1 difference idx if needed (see np.diff kwargs) depending on which side of the discontinuities you need to be.

    >>> discontinuities_idx
    >>> array([3, 8])
    >>> a[discontinuities_idx]
    >>> array([8, 1])