When I compute the gradient of a masked array in numpy as
import numpy as np
import numpy.ma as ma
x = np.array([100, 2, 3, 5, 5, 5, 10, 100])
mx = ma.masked_array(x, mask=[1, 0, 0, 0, 0, 0, 0, 1])
the mask of the resulting array is different from the original mask:
np.gradient(mx)
masked_array(data = [-- -- 1.5 1.0 0.0 2.5 -- --],
mask = [ True True False False False False True True],
fill_value = 999999)
Why is the gradient not computed at the 'new' boundaries? How can I change that?
For masked entries in the middle it gets weirder:
x = np.array([100, 2, 3, 5, 5, 6, 6, 6, 6, 6, 7, 5, 10, 100])
mx = ma.masked_array(x, mask=[1, 0, 0, 0,0, 0,1,0,0,0, 0, 0, 0, 1])
np.gradient(mx)
masked_array(data = [-- -- 1.5 1.0 0.5 -- 0.0 -- 0.0 0.5 -0.5 1.5 ----],
mask = [ True True False False False True False True False False False False
True True],
fill_value = 1e+20)
I would expect np.gradient to just treat the masked cells as boundaries.
Update:
What I want to do: I need to compute the gradient on the array and not change the mask, nor the shape of the array (I want 2d in the end) Masked cells should not contribute to the gradient. Points next to a masked cell should be considered boundaries and a one-sided difference applied.
- - - - - - - - - - -
- - - - o o - - o - -
- - - o x x o o x o -
- - - o x o - - o - -
- - - - o - - - - - -
- - - - - - - - - - -
In this sketch x represent a masked cell and o are cells where a one-sided difference should be computed (cells at the edges of the area need to be one-sided too, but I don't paint them in here for clarity).