1
votes

I have an array of timesteps (in seconds) and an array of locations (in latitude). Both arrays are the same size with N=36. I am computing the np.gradient between the two arrays which returns nan values when any two sequential timesteps are the same value. But when I compute the gradient using a constant scalar as the vararg value, I get the correct data output. I need to find a way to create the correct gradient output with varying timesteps.

Using Python 3.4 and Numpy 1.14

I tried computing the gradient with my original timestep array, which returned nan values when the values are the same. Next, I tried computing the gradient with a single scalar value as the vararg input, which gave me the correct output. Then, I tried setting vararg as a numpy array with all the same timestep values, which returned all -inf values.

#Original Code:    
dt = np.array([10800,10800,9900,5400,6300]) #delta time in seconds
x = np.array([-85.18,-85.80,-86.3,-87,-87.0]) #delta x in decimal degrees
dx_dt = np.gradient(x,dt) 
#returns:
#[nan,nan, 4.8e-004,-3.1e-004,-2.19e-004]

#Test 1 - test with constant scalar
dx_dt = np.gradient(x,10800) 
#returns:
#[-5.5e-5,-5.1e-5,-5.5e-5,-4.1e-5,-5.1e-5]

#Test 2 - test with constant array
dt = np.array([10800,10800,10800,10800,10800)]
dx_dt = np.gradient(x,dt) 
#returns:
#[-inf,-inf,-inf,-inf,-inf]

I would expect the output of the np.gradient(x,10800) to be the same as the np.gradient(x,np.array([10800,10800,10800,10800,10800])), but it is not.

I need an output without nan or inf values for the next part of the code to work, simply setting the -inf or nans to 0 is not helpful.

1

1 Answers

1
votes

For numpy.gradient, when varargs is an array, the coordinates of the values along t must be given, not the deltas. See point 3 of the np.gradient documentation below.

varargs : list of scalar or array, optional

Spacing between f values. Default unitary spacing for all dimensions. Spacing can be specified using:

  1. 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.

To get your gradient, you can use np.cumsum to get the coordinates from the deltas:

dt = np.array([10800,10800,9900,5400,6300]) #delta time in seconds
t = np.cumsum(dt)
x = np.array([-85.18,-85.80,-86.3,-87,-87.0]) #delta x in decimal degrees
dx_dt = np.gradient(x,t) 

Which gives:

[-5.74074074e-05 -5.38061777e-05 -1.01703308e-04 -6.98005698e-05 0.00000000e+00]

And you can check that:

dx_dt = np.gradient(x,10800) 

and

dt = np.array([10800,10800,10800,10800,10800])
t = np.cumsum(dt)
dx_dt = np.gradient(x,t) 

give the same result:

[-5.74074074e-05 -5.18518519e-05 -5.55555556e-05 -3.24074074e-05 0.00000000e+00]