daily pastebin goal
37%
SHARE
TWEET

Untitled

a guest Jan 16th, 2018 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #find the nearest point from a given point to a large list of points
  2.  
  3. import numpy as np
  4.  
  5. def distance(pt_1, pt_2):
  6.     pt_1 = np.array((pt_1[0], pt_1[1]))
  7.     pt_2 = np.array((pt_2[0], pt_2[1]))
  8.     return np.linalg.norm(pt_1-pt_2)
  9.  
  10. def closest_node(node, nodes):
  11.     pt = []
  12.     dist = 9999999
  13.     for n in nodes:
  14.         if distance(node, n) <= dist:
  15.             dist = distance(node, n)
  16.             pt = n
  17.     return pt
  18.  
  19. a = []
  20. for x in range(50000):
  21.     a.append((np.random.randint(0,1000),np.random.randint(0,1000)))
  22.  
  23. some_pt = (1, 2)
  24.  
  25. closest_node(some_pt, a)
  26.    
  27. def closest_node(node, nodes):
  28.     nodes = np.asarray(nodes)
  29.     dist_2 = np.sum((nodes - node)**2, axis=1)
  30.     return np.argmin(dist_2)
  31.    
  32. def closest_node(node, nodes):
  33.     nodes = np.asarray(nodes)
  34.     deltas = nodes - node
  35.     dist_2 = np.einsum('ij,ij->i', deltas, deltas)
  36.     return np.argmin(dist_2)
  37.    
  38. from numpy import random
  39. from scipy.spatial import distance
  40.  
  41. a = random.randint(1000, size=(50000, 2))
  42.  
  43. some_pt = (1, 2)
  44.  
  45. a[distance.cdist([some_pt], a).argmin()]
  46.    
  47. a = []
  48. for x in range(50000):
  49.     a.append((np.random.randint(0,1000),np.random.randint(0,1000)))
  50.    
  51. a = np.random.randint(1000, size=(50000, 2))
  52.    
  53. from scipy.spatial.distance import cdist
  54.  
  55. def closest_node(node, nodes):
  56.     return nodes[cdist([node], nodes).argmin()]
  57.    
  58. Original:
  59. 1 loop, best of 3: 1.01 sec per loop
  60.  
  61. Jaime v1:
  62. 100 loops, best of 3: 3.32 msec per loop
  63.  
  64. Jaime v2:
  65. 1000 loops, best of 3: 1.62 msec per loop
  66.  
  67. Mine:
  68. 100 loops, best of 3: 2.07 msec per loop
RAW Paste Data
Top