3

I have two numpy array that describes a spatial curve, that are intersected on one point and I want to find the nearest value in both array for that intersection point, I have this code that works fine but its to slow for large amount of points.

from scipy import spatial
def nearest(arr0, arr1):
    ptos = []
    j = 0
    for i in arr0:
        distance, index = spatial.KDTree(arr1).query(i)
        ptos.append([distance, index, j])
        j += 1
    ptos.sort()
    return (arr1[ptos[0][1]].tolist(), ptos[0][1], ptos[0][2])

the result will be (<point coordinates>,<position in arr1>,<position in arr0>)

4
  • this Commented Mar 15, 2016 at 20:03
  • @cxw, how could I use it in my case? Commented Mar 15, 2016 at 20:05
  • How many dimensions do the arrays span? Commented Mar 15, 2016 at 20:20
  • @Alex the array are the coordinates x,y,z of a spatial line so nx3 the numbers of point are not fixed, but for now may work for a line in a x,y plane so nx2 may work too Commented Mar 15, 2016 at 20:30

1 Answer 1

3

Your code is doing a lot of things you don't need. First you're rebuilding the KDtree on every loop and that's a waste. Also query takes an array of points, so no need to write your own loop. Ptos is an odd data structure, and you don't need it (and don't need to sort it). Try something like this.

from scipy import spatial

def nearest(arr0, arr1):
    tree = spatial.KDTree(arr1)
    distance, arr1_index = tree.query(arr0)
    best_arr0 = distance.argmin()
    best_arr1 = arr1_index[best_arr0]
    two_closest_points = (arr0[best_arr0], arr1[best_arr1])
    return two_closest_points, best_arr1, best_arr0

If that still isn't fast enough, you'll need to describe your problem in more detail and figure out if another search algorithm will work better for your problem.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much, the entire run processes go down from 3 min to 20 seconds, you saved me a lot of time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.