python - numpy how find local minimum in neighborhood on 1darray -
i've got list of sorted samples. they're sorted sample time, each sample taken 1 second after previous one. i'd find minimum value in neighborhood of specified size.
for example, given neighborhood size of 2 , following sample size:
samples = [ 5, 12.3, 12.3, 7, 2, 6, 9, 10, 5, 9, 17, 2 ]
i'd expect following output: [5, 2, 5, 2] best way achieve in numpy / scipy
edited: explained reasoning behind min values:
- 5 - 2 number window next [12.3 12.3]. 5 smaller
- 2 - left [12.3, 7] right [6 9]. 2 min
- 5 - left [9 10] right [9 17]. 5 min
notice 9 isn't min there's 2 window left , right smaller value (2)
use scipy's argrelextrema
:
>>> import numpy np >>> scipy.signal import argrelextrema >>> data = np.array([ 5, 12.3, 12.3, 7, 2, 6, 9, 10, 5, 9, 17, 2 ]) >>> radius = 2 # number of elements left , right compare >>> argrelextrema(data, np.less, order=radius) (array([4, 8]),)
which suggest numbers @ position 4 , 8 (2
, 5
) smallest ones in within 2 size neighbourhood. numbers @ boundaries (5
, 2
) not detected since argrelextrema
supports clip
or wrap
boundary conditions. question, guess interested in them too. detect them, easy add reflect boundary conditions first:
>>> new_data = np.pad(data, radius, mode='reflect') >>> new_data array([ 12.3, 12.3, 5. , 12.3, 12.3, 7. , 2. , 6. , 9. , 10. , 5. , 9. , 17. , 2. , 17. , 9. ])
with data corresponding boundary conditions, can apply previus extrema detector:
>>> arg_minimas = argrelextrema(new_data, np.less, order=radius)[0] - radius >>> arg_minimas array([ 0, 4, 8, 11])
which returns positions local extrema (minimum in case since np.less
) happens in sliding window of radius=2
.
note -radius
fix +radius
index after wrapping array reflect
boundary conditions np.pad
.
edit: if insterested in values , not in positions, straight forward:
>>> data[arg_minimas] array([ 5., 2., 5., 2.])
Comments
Post a Comment