Last active
September 13, 2019 05:45
-
-
Save banesullivan/54c97246a700cb383ed2b1d9545d8305 to your computer and use it in GitHub Desktop.
[Compute Distances] Compute the element-wise distances between two arrays of points in 3D space. This rather simple but a snippet I find myself using all the time. #numpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
# The function for computing distances | |
compute = lambda a, b: np.sqrt(np.sum((b - a)**2, axis=1)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
# The function for computing distances | |
compute = lambda a, b: np.sqrt(np.sum((b - a)**2, axis=1)) | |
# Sanity check | |
check = compute(np.array([[0,0,0],]), np.array([[1,1,1],])) | |
assert np.allclose(check, np.sqrt(3)) | |
# Example usage | |
import pyvista as pv | |
from pyvista import examples | |
mesh = examples.download_st_helens().warp_by_scalar() | |
distances = compute(mesh.points, mesh.points[mesh.n_points//2]) | |
mesh['distances'] = distances | |
mesh.plot(scalars='distances') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Another implementation that is a bit more robust | |
""" | |
import numpy as np | |
def compute(a, b): | |
"""Comute distances between points in arrays""" | |
if not isinstance(a, np.ndarray): | |
a = np.array(a) | |
if not isinstance(b, np.ndarray): | |
b = np.array(b) | |
if a.ndim != 2: | |
a = a.reshape((1, -1)) | |
if b.ndim != 2: | |
b = b.reshape((1, -1)) | |
return np.sqrt(np.sum((b - a)**2, axis=1)) | |
# Sanity check | |
assert np.allclose(compute([0,0,0], [1,1,0]), np.sqrt(2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment