amchugh89
amchugh89

Reputation: 1296

Numpy - Find 3-d distance to a testpoint for all gridpoints on 3-d grid

I tried np.hypot() and np.linalg.norm() but both of them have some issues (at least how I am using thm).

I am pretty sure np.hypot can only calculate 2-d distance. If I have a test point P (1,1,1) and a grid point G (3,3,3), then the returned value a grid point G will be something like : ((3-1)^2+(3-1)^2)^(0.5) = 2.82

I can do a straight up call to np.hypot, without having to loop thru gridpoints (looping I guess is slow, and therefore bad), and I get these distance-to-testpoint values returned at all grid points of my 3-d meshgrid, but the z dependency is not calculated (that is d at (1,2,0) = d at (1,2,3):

#crystal_lattice structure
x,y,z = np.linspace(-2,2,5),np.linspace(-2,2,5),np.linspace(-2,2,5)

xx,yy,zz = np.meshgrid(x,y,z)

#testpoint
point = np.array([1,1,1])

d = np.hypot(xx-1,yy-1,zz-1)

With np.linalg.norm, I do not know how to get returned values calculated elementwise at all the points on my grid, the parameters passed in seem to be a point A (gridpoint) and a point B (testpoint), but then I cannot think of any way to calculate for all gridpoints other than looping like follows:

for i in x:
    for j in y:
        for k in z:
            #not mapped back to a gridpoint, do not know what to do
            d = np.linalg.norm(np.array([i,j,k])-point)

Does anyone know how I can find a real 3-d distance to a testpoint for all my gridpoints on a 3d grid?

Upvotes: 0

Views: 364

Answers (2)

anishtain4
anishtain4

Reputation: 2402

Here's an easy function to calculate mutual distance of n-dimensional vectors:

def _distance2(v):
    nrm=np.sum(v**2,axis=0,keepdims=True)
    return nrm+nrm.T-2* v.T @ v

Rows are the points and columns are dimensions, so in your case you can just flatten the data. You can also use the general idea to manipulate it to whatever form your data is at.

Upvotes: 1

BenBoulderite
BenBoulderite

Reputation: 336

How about simply:

d = np.sqrt((point[0]-xx)**2 + (point[1]-yy)**2 + (point[2]-zz)**2)

Upvotes: 1

Related Questions