Say I have an array in NumPy containing evaluations of a continuous differentiable function, and I want to find the local minima. There is no noise, so every point whose value is lower than the values of all its neighbors meets my criterion for a local minimum.
I have the following list comprehension which works for a two-dimensional array, ignoring potential minima on the boundaries:
import numpy as N
def local_minima(array2d):
local_minima = [ index
for index in N.ndindex(array2d.shape)
if index[0] > 0
if index[1] > 0
if index[0] < array2d.shape[0] - 1
if index[1] < array2d.shape[1] - 1
if array2d[index] < array2d[index[0] - 1, index[1] - 1]
if array2d[index] < array2d[index[0] - 1, index[1]]
if array2d[index] < array2d[index[0] - 1, index[1] + 1]
if array2d[index] < array2d[index[0], index[1] - 1]
if array2d[index] < array2d[index[0], index[1] + 1]
if array2d[index] < array2d[index[0] + 1, index[1] - 1]
if array2d[index] < array2d[index[0] + 1, index[1]]
if array2d[index] < array2d[index[0] + 1, index[1] + 1]
]
return local_minima
However, this is quite slow. I would also like to get this to work for any number of dimensions. For example, is there an easy way to get all the neighbors of a point in an array of any dimensions? Or am I approaching this problem the wrong way altogether? Should I be using numpy.gradient()
instead?
Find min values along the axis in 2D numpy array | min in rows or columns: If we pass axis=0 in numpy. amin() then it returns an array containing min value for each column i.e. If we pass axis = 1 in numpy.
Function argrelmin() is used to calculate the relative minima of data. Similarly, argrelmax() is used to calculate the relative maxima of data. These functions return the indices of local minima/maxima in the data. The indices can be used to find the values of local minima/maxima.
Python provides different inbuilt function. min() is used for find out minimum value in an array, max() is used for find out maximum value in an array. index() is used for finding the index of the element.
Try this for 2D:
import numpy as N
def local_minima(array2d):
return ((array2d <= N.roll(array2d, 1, 0)) &
(array2d <= N.roll(array2d, -1, 0)) &
(array2d <= N.roll(array2d, 1, 1)) &
(array2d <= N.roll(array2d, -1, 1)))
This will return you an array2d-like array with True/False where local minima (four neighbors) are located.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With