making np.gradient support unevenly spaced data

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

making np.gradient support unevenly spaced data

alebarde@gmail.com
Hi all,

I have implemented a proposed enhancement for the np.gradient function that allows to compute the gradient on non uniform grids. (PR: https://github.com/numpy/numpy/pull/8446)
The proposed implementation has a behaviour/signature is similar to that of Matlab/Octave. As argument it can take:
1. A single scalar to specify a sample distance for all dimensions.
2. N scalars to specify a constant sample distance for each dimension.
   i.e. `dx`, `dy`, `dz`, ...
3. N arrays to specify the coordinates of the values along each
   dimension of F. The length of the array must match the size of
   the corresponding dimension
4. Any combination of N scalars/arrays with the meaning of 2. and 3.

e.g., you can do the following:
   
    >>> f = np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float)
    >>> dx = 2.
    >>> y = [1., 1.5, 3.5]
    >>> np.gradient(f, dx, y)
    [array([[ 1. ,  1. , -0.5], [ 1. ,  1. , -0.5]]),
     array([[ 2. ,  2. ,  2. ], [ 2. ,  1.7,  0.5]])]

It should not break any existing code since as of 1.12 only scalars or list of scalars are allowed.
A possible alternative API could be pass arrays of sampling steps instead of the coordinates.
On the one hand, this would have the advantage of having "differences" both in the scalar case and in the array case.
On the other hand, if you are dealing with non uniformly-spaced data (e.g, data is mapped on a grid or it is a time-series), in most cases you already have the coordinates/timestamps. Therefore, in the case of difference as argument, you would almost always have a call np.diff before np.gradient.

In the end, I would rather prefer the coordinates option since IMHO it is more handy, I don't think that would be too much "surprising" and it is what Matlab already does. Also, it could not easily lead to "silly" mistakes since the length have to match the size of the corresponding dimension.

What do you think?

Thanks

Alessandro

--
--------------------------------------------------------------------------
NOTICE:
Dlgs 196/2003 this e-mail and any attachments thereto may contain confidential information and are intended for the sole use of the recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any dissemination or copying of this message is strictly prohibited. If you have received this e-mail in error, please notify the sender either by telephone or by e-mail and delete the material from any computer. Thank you.
------------------------------
--------------------------------------------

_______________________________________________
NumPy-Discussion mailing list
[hidden email]
https://mail.scipy.org/mailman/listinfo/numpy-discussion
Loading...