NNSearch_experimental.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import math
  2. from ctypes import cdll, c_uint, c_double, c_void_p
  3. import tensorflow as tf
  4. import tensorflow.keras.layers as L
  5. import numpy as np
  6. import numpy.ctypeslib as npct
  7. array_2d_uint = npct.ndpointer(dtype=np.uint, ndim=2, flags='CONTIGUOUS')
  8. array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS')
  9. array_2d_double = npct.ndpointer(dtype=np.double, ndim=2, flags='CONTIGUOUS')
  10. from sklearn.neighbors import NearestNeighbors
  11. from library.timing import timing
  12. from library.MaxHeap import MaxHeap
  13. nbhLib = cdll.LoadLibrary("./library/c/libNeighborhood.so")
  14. nbhLib.Neighborhood.rettype = None
  15. nbhLib.Neighborhood.argtypes = [c_uint, c_uint, c_uint, array_2d_double, array_2d_uint]
  16. #nbhLib.NeighborhoodHeuristic.rettype = None
  17. #nbhLib.NeighborhoodHeuristic.argtypes = [c_uint, c_uint, c_uint, array_2d_double, array_2d_uint]
  18. def scalarP(a, b):
  19. return sum(map(lambda c: c[0] * c[1], zip(a, b)))
  20. def norm2(v):
  21. return sum(map(lambda z: z*z, v))
  22. def dist(x,y):
  23. return norm2(x - y)
  24. def maxby(data, fn, startValue=0.0):
  25. m = startValue
  26. for v in data:
  27. m = max(m, fn(v))
  28. return m
  29. def distancesToPoint(p, points):
  30. w = np.array(np.repeat([p], len(points), axis=0))
  31. d = L.Subtract()([w, np.array(points)])
  32. t = L.Dot(axes=(1,1))([d,d])
  33. # As the concrete distance is not needed and sqrt(x) is strict monotone
  34. # we avoid here unneccessary calculating of expensive roots.
  35. return t.numpy()
  36. def calculateCenter(points):
  37. if points.shape[0] == 1:
  38. return points[0]
  39. return tf.keras.layers.Average()(np.array(points)).numpy()
  40. def centerPoints(points):
  41. points = np.array(points)
  42. center = L.Average()(list(points)).numpy()
  43. ctr = np.array(np.repeat([center], points.shape[0], axis=0))
  44. return L.Subtract()([ctr, points]).numpy()
  45. def maxNormPoints(points):
  46. points = np.array(points)
  47. a = L.Lambda(lambda x: np.abs(x))(points)
  48. a = L.Reshape((points.shape[1], 1))(a)
  49. m = L.GlobalMaxPooling1D()(a)
  50. m = L.Reshape((1,))
  51. return m.numpy()
  52. def twoNormSquaredPoints(points):
  53. points = np.array(points)
  54. return L.Dot(axes=(1,1))([points,points]).numpy()
  55. def twoNormPoints(points):
  56. points = np.array(points)
  57. nsq = L.Dot(axes=(1,1))([points,points])
  58. return L.Lambda(lambda x: np.sqrt(x))(points).numpy()
  59. def norms(points):
  60. points = np.array(points)
  61. a = L.Lambda(lambda x: np.abs(x))(points)
  62. a = L.Reshape((points.shape[1], 1))(a)
  63. m = L.GlobalMaxPooling1D()(a)
  64. m = L.Reshape((1,))(m)
  65. nsq = L.Dot(axes=(1,1))([points,points])
  66. return L.Concatenate()([m, nsq]).numpy()
  67. class NNSearch:
  68. def __init__(self, nebSize=5, timingDict=None):
  69. self.nebSize = nebSize
  70. self.neighbourhoods = []
  71. self.timingDict = timingDict
  72. def timerStart(self, name):
  73. if self.timingDict is not None:
  74. if name not in self.timingDict:
  75. self.timingDict[name] = timing(name)
  76. self.timingDict[name].start()
  77. def timerStop(self, name):
  78. if self.timingDict is not None:
  79. if name in self.timingDict:
  80. self.timingDict[name].stop()
  81. def neighbourhoodOfItem(self, i):
  82. return self.neighbourhoods[i]
  83. def fit(self, X, nebSize=None):
  84. self.timerStart("NN_fit_all")
  85. self.fit_chained(X, nebSize)
  86. #self.fit_bruteForce_np(X, nebSize)
  87. self.timerStop("NN_fit_all")
  88. def fit_optimized(self, X, nebSize=None):
  89. self.timerStart("NN_fit_all")
  90. if nebSize == None:
  91. nebSize = self.nebSize
  92. nPoints = len(X)
  93. nFeatures = len(X[0])
  94. if nFeatures > 15 or nebSize >= (nPoints // 2):
  95. print("Using brute force")
  96. self.fit_bruteForce_np(X, nebSize)
  97. else:
  98. print("Using chained")
  99. self.fit_chained(X, nebSize)
  100. self.timerStop("NN_fit_all")
  101. def fit_bruteForce(self, X, nebSize=None):
  102. if nebSize == None:
  103. nebSize = self.nebSize
  104. self.timerStart("NN_fit_bf_init")
  105. isGreaterThan = lambda x, y: x[1] > y[1]
  106. self.neighbourhoods = [MaxHeap(nebSize, isGreaterThan, (i, 0.0)) for i in range(len(X))]
  107. self.timerStop("NN_fit_bf_init")
  108. self.timerStart("NN_fit_bf_loop")
  109. for (i, x) in enumerate(X):
  110. nbh = self.neighbourhoods[i]
  111. for (j, y) in enumerate(X[i+1:]):
  112. j += i + 1
  113. self.timerStart("NN_fit_bf_dist")
  114. d = dist(x,y)
  115. self.timerStop("NN_fit_bf_dist")
  116. self.timerStart("NN_fit_bf_insert")
  117. nbh.insert((j,d))
  118. self.neighbourhoods[j].insert((i,d))
  119. self.timerStop("NN_fit_bf_insert")
  120. self.timerStart("NN_fit_bf_toList")
  121. self.neighbourhoods[i] = nbh.toArray(lambda v: v[0])
  122. self.timerStop("NN_fit_bf_toList")
  123. self.timerStop("NN_fit_bf_loop")
  124. def fit_bruteForce_np(self, X, nebSize=None):
  125. self.timerStart("NN_fit_bfnp_init")
  126. numOfPoints = len(X)
  127. nFeatures = len(X[0])
  128. tX = tf.convert_to_tensor(X)
  129. def distancesTo(x):
  130. w = np.repeat([x], numOfPoints, axis=0)
  131. d = tf.keras.layers.Subtract()([w,tX])
  132. t = tf.keras.layers.Dot(axes=(1,1))([d,d])
  133. return t.numpy()
  134. if nebSize == None:
  135. nebSize = self.nebSize
  136. isGreaterThan = lambda x, y: x[1] > y[1]
  137. self.neighbourhoods = [MaxHeap(nebSize, isGreaterThan, (i, 0.0)) for i in range(len(X))]
  138. self.timerStop("NN_fit_bfnp_init")
  139. self.timerStart("NN_fit_bfnp_loop")
  140. for (i, x) in enumerate(X):
  141. self.timerStart("NN_fit_bfnp_dist")
  142. distances = distancesTo(x)
  143. self.timerStop("NN_fit_bfnp_dist")
  144. nbh = self.neighbourhoods[i]
  145. for (j, y) in enumerate(X[i+1:]):
  146. j += i + 1
  147. d = distances[j]
  148. self.timerStart("NN_fit_bfnp_insert")
  149. nbh.insert((j,d))
  150. self.neighbourhoods[j].insert((i,d))
  151. self.timerStop("NN_fit_bfnp_insert")
  152. self.timerStart("NN_fit_bfnp_toList")
  153. self.neighbourhoods[i] = nbh.toArray(lambda v: v[0])
  154. self.timerStop("NN_fit_bfnp_toList")
  155. self.timerStop("NN_fit_bfnp_loop")
  156. def fit_chained(self, X, nebSize=None):
  157. self.timerStart("NN_fit_chained_init")
  158. if nebSize == None:
  159. nebSize = self.nebSize
  160. nPoints = len(X)
  161. nFeatures = len(X[0])
  162. neigh = NearestNeighbors(n_neighbors=nebSize)
  163. neigh.fit(X)
  164. self.timerStop("NN_fit_chained_init")
  165. self.timerStart("NN_fit_chained_toList")
  166. self.neighbourhoods = [
  167. (neigh.kneighbors([x], nebSize, return_distance=False))[0]
  168. for (i, x) in enumerate(X)
  169. ]
  170. self.timerStop("NN_fit_chained_toList")
  171. def fit_cLib(self, X, nebSize=None):
  172. self.timerStart("NN_fit_cLib_init")
  173. if nebSize == None:
  174. nebSize = self.nebSize
  175. nbh = np.array([np.zeros(nebSize, dtype=np.uint) for i in range(X.shape[0])])
  176. self.timerStop("NN_fit_cLib_init")
  177. self.timerStart("NN_fit_cLib_call")
  178. nbhLib.Neighborhood(nebSize, X.shape[0], X.shape[1], X, nbh)
  179. self.timerStop("NN_fit_cLib_call")
  180. self.timerStart("NN_fit_cLib_list")
  181. self.neighbourhoods = list(nbh)
  182. self.timerStop("NN_fit_cLib_list")
  183. # def fit_cLibHeuristic(self, X, nebSize=None):
  184. # self.timerStart("NN_fit_cLib_init")
  185. # if nebSize == None:
  186. # nebSize = self.nebSize
  187. #
  188. # nbh = np.array([np.zeros(nebSize, dtype=np.uint) for i in range(X.shape[0])])
  189. # self.timerStop("NN_fit_cLib_init")
  190. # self.timerStart("NN_fit_cLib_call")
  191. # nbhLib.NeighborhoodHeuristic(nebSize, X.shape[0], X.shape[1], X, nbh)
  192. # self.timerStop("NN_fit_cLib_call")
  193. # self.timerStart("NN_fit_cLib_list")
  194. # self.neighbourhoods = list(nbh)
  195. # self.timerStop("NN_fit_cLib_list")
  196. # ===============================================================
  197. # Heuristic search
  198. # ===============================================================
  199. def fit_heuristic(self, X, nebSize=None, debugLayer=0, withDouble=True):
  200. if nebSize == None:
  201. nebSize = self.nebSize
  202. self.timerStart("NN_fit_heuristic_init")
  203. nPoints = len(X)
  204. nFeatures = len(X[0])
  205. nHeuristic = max(1, int(math.log(nFeatures)))
  206. isGreaterThan = lambda x, y: x[1] > y[1]
  207. self.neighbourhoods = [MaxHeap(maxSize=nebSize, isGreaterThan=isGreaterThan, smalestValue=(i, 0.0)) for i in range(len(X))]
  208. self.timerStart("NN_fit_heuristic_lineStart")
  209. z = X[0]
  210. farest = 0
  211. bestDist = 0.0
  212. for (i, x) in enumerate(X):
  213. d = dist(x, z)
  214. if d > bestDist:
  215. farest = i
  216. bestDist = d
  217. lineStart = farest
  218. z = X[lineStart]
  219. self.timerStop("NN_fit_heuristic_lineStart")
  220. # print(f"lineStart: {lineStart}@{z} ... {bestDist}")
  221. self.timerStart("NN_fit_heuristic_lineEnd")
  222. bestDist = 0.0
  223. for (i, x) in enumerate(X):
  224. d = dist(x, z)
  225. if d > bestDist:
  226. farest = i
  227. bestDist = d
  228. lineEnd = farest
  229. self.timerStop("NN_fit_heuristic_lineEnd")
  230. self.timerStart("NN_fit_heuristic_line")
  231. # print(f"lineEnd: {lineEnd}@{X[lineEnd]} ... {bestDist}")
  232. u = (X[lineEnd] - z)
  233. uFactor = (1 / math.sqrt(norm2(u)))
  234. u = uFactor * u
  235. # print(f"u: {u} ... {norm2(u)}")
  236. def heuristic(i,x):
  237. p = z + (scalarP(u, x - z) * u)
  238. dz = math.sqrt(dist(z, p))
  239. dx = math.sqrt(dist(x, p))
  240. return (i, dz, dx)
  241. line = [heuristic(i, x) for (i,x) in enumerate(X) ]
  242. line.sort(key= lambda a: a[1])
  243. self.timerStop("NN_fit_heuristic_line")
  244. self.timerStop("NN_fit_heuristic_init")
  245. self.timerStart("NN_fit_heuristic_loop")
  246. s = 0
  247. ff = False
  248. ptsDone = set()
  249. for (i,(xi, di, dix)) in enumerate(line):
  250. self.timerStart("NN_fit_heuristic_loop_init")
  251. h = self.neighbourhoods[xi]
  252. z = X[xi]
  253. self.timerStop("NN_fit_heuristic_loop_init")
  254. ptsDone.add(xi)
  255. self.timerStart("NN_fit_heuristic_loop_distance")
  256. ll = [(xj, norm2([dj - di, djx - dix])) for (xj, dj, djx) in line[i:]]
  257. # ll = [(xj, dist(
  258. # np.array([di, dix] + list(X[xi][0:nHeuristic])),
  259. # np.array([dj, djx] + list(X[xj][0:nHeuristic]))))
  260. # for (xj, dj, djx) in line[1:]
  261. # ]
  262. ll.sort(key = lambda a: a[1])
  263. kk = distancesToPoint(z, [X[j] for (j, _) in ll])
  264. self.timerStop("NN_fit_heuristic_loop_distance")
  265. for (d, (xj, djx)) in zip(kk, ll):
  266. ign = h.size >= nebSize and djx > h.getMax()[1]
  267. if ign:
  268. break
  269. else:
  270. #d = dist(X[xj], z)
  271. self.timerStart("NN_fit_heuristic_insert")
  272. s += 1
  273. h.insert((xj, d))
  274. k = self.neighbourhoods[xj]
  275. if not isinstance(k, list):
  276. k.insert((xi, d))
  277. self.timerStop("NN_fit_heuristic_insert")
  278. # if xi == debugLayer:
  279. # d = dist(X[xj], z)
  280. # hint = ""
  281. # if djx > d:
  282. # hint += "!!"
  283. # if ign:
  284. # hint += "*"
  285. # print(f"xj:{xj} dx:{h.getMax()[1]:0.1f} djx:{djx:0.1f} d:{d:0.1f}" + hint)
  286. self.timerStart("NN_fit_heuristic_toArray")
  287. self.neighbourhoods[xi] = h.toArray()
  288. self.timerStop("NN_fit_heuristic_toArray")
  289. self.timerStop("NN_fit_heuristic_loop")
  290. print(f"calculated distances: {s} / {nPoints * (nPoints - 1)}")