algorithmoptimizationnearest-neighboroctree

Algorithm for Octree for nearest neighbor search


Problem Statement: To find the nearest GRID ID of each of the particles using Octree.

Fig[1]: enter image description here

Fig[2]: enter image description here

I have a system of particles(~6k, movable) for which I need to check which grid point (rigid; in picture) is nearest to. Somebody have suggested me to go for Octree as it is fast(est) for 3D Grids.

Is this the correct Algorithm for recursive Octree to get the nearest grid point of the grid?

  1. Get a input as point P Start coordinate C (first time it [0,0,0])
  2. Start Size = [Sx, Sy, Sz]
  3. Get all 8 mid point Mi = {M1,..,M8} get minimum distance of Mi and P
  4. Say M get start position of M as Cn set size Sn = [Sx/8, Sy/8, Sz/8]

  5. if distance of M and P is less than 2 * (Grid Space G):

    5.1. Iterate all the grid points from Cn to Sn

    5.2. Print least as result

  6. else

    6.1. set Start coordinate as Cn

    6.2. set Size as Sn

    6.3. Goto 1

Problem: The last iteration eat all speed if the particle is out or nearly on the border as it checks all A x B x C.

Please suggest if you have a better way to solve this problem.


Solution

  • There is no need to use an octree here. Octree is useful for the reverse problem (given a grid point, find the nearest particule) but completely useless here.

    Assuming the size of a grid cell is (a, b, c), then the nearest grid point from (x, y, z) is (a*floor(x/a+0.5), b*floor(y/b+0.5), c*floor(z/c+0.5)).