Function to compute 3D gradient with unevenly spaced sample locations

时间:2016-04-21 22:44:09

标签: python numpy multidimensional-array data-manipulation gradients

I have experimental observations in a volume:

import numpy as np

# observations are not uniformly spaced 
x = np.random.normal(0, 1, 10)
y = np.random.normal(5, 2, 10)
z = np.random.normal(10, 3, 10)
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')

# fake temperatures at those coords
tt = xx*2 + yy*2 + zz*2

# sample distances
dx = np.diff(x)
dy = np.diff(y)
dz = np.diff(z)

grad = np.gradient(tt, [dx, dy, dz])  # returns error

This gives me the error:

ValueError: operands could not be broadcast together with shapes (10,10,10) (3,9) (10,10,10).

EDIT: according to @jay-kominek in the comments below:

np.gradient won't work for you, it simply doesn't handle unevenly sampled data.

I've updated the question. Is there any function which can can do my computation?

2 个答案:

答案 0 :(得分:3)

需要注意两点:首先,标量是单个值,而不是数组。其次,函数的签名是numpy.gradient(f, *varargs, **kwargs)。请注意varargs之前的*。这意味着如果varargs是一个列表,则会传递*varargs。或者您可以将varargs的元素作为单独的参数提供。

因此,np.gradient想要每个维度的距离都有一个值,例如:

np.gradient(tt, np.diff(x)[0], np.diff(y)[0], np.diff(z)[0])

或:

distances = [np.diff(x)[0], np.diff(y)[0], np.diff(z)[0]]
np.gradient(tt, *distances)

答案 1 :(得分:0)

要传递给np.gradient的所需dx ...不是差异网格,而是每个只有一个标量。所以grad = np.gradient(tt,0.1,0.1,0.1)似乎有效。