Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Calculate the Gradient of a 3D grid

I have a cube of particles which I've projected onto a 2D grid, Projecting the particles onto the grid by a clouds in cells and weighting them by a scalar.

I would then like the gradient of the scalar at every grid point. In 2D I am doing this using np.gradient and I get two arrays with the gradient in the x and y directions:

gradx, grady = np.gradient(grid)

Does anyone have any idea how I can generalize this to 3 Dimensions? The Clouds in Cells in 3D is fine but I am then left with a grid with the shape (700, 700, 700).

As far as I can see np.gradient can't deal with this?

Thanks, Daniel

like image 962
Danwise Avatar asked Oct 30 '12 14:10

Danwise


People also ask

How do you find the gradient in Python?

The gradient of a function simply means the rate of change of a function. We will use numdifftools to find Gradient of a function. Examples: Input : x^4+x+1 Output :Gradient of x^4+x+1 at x=1 is 4.99 Input :(1-x)^2+(y-x^2)^2 Output :Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is [-4.

How do you find the gradient in numpy?

The gradient is computed using central differences in the interior and first differences at the boundaries. Are you sure h = 1? Because it means it is f(x + 0.5) - f(x - 0.5), so if we take x = 2 it becomes f(2.5) - f(1.5), if f is a 1-d array you can't have non-integer x.

What is gradient Python?

gradient is the function or any Python callable object that takes a vector and returns the gradient of the function you're trying to minimize. start is the point where the algorithm starts its search, given as a sequence (tuple, list, NumPy array, and so on) or scalar (in the case of a one-dimensional problem).


1 Answers

The Numpy documentation indicates that gradient works for any dimensions:

numpy.gradient(f, *varargs)

Return the gradient of an N-dimensional array.

The gradient is computed using central differences in the interior and first differences at the boundaries. The returned gradient hence has the same shape as the input array.

Parameters :

f: array_like. An N-dimensional array containing samples of a scalar function.

*varargs: 0, 1, or N scalars specifying the sample distances in each direction, that is: dx, dy, dz, ... The default distance is 1.

Returns :

g: ndarray. N arrays of the same shape as f giving the derivative of f with respect to each dimension.

Seems like you should be able to extend your 2-dimensional code to 3D like you would expect.

like image 155
japreiss Avatar answered Oct 08 '22 16:10

japreiss