title: Why are KD-trees so damn slow for nearest neighbor search in point sets?
body: <p>I am using CGAL's (the latest) KD-tree implementation for searching nearest neighbors in point sets. And also Wikipedia and other resources seem to suggest that KD-trees are the way to go. But somehow they are too slow and Wiki also suggests their worst-case time of O(n), which is far from ideal.</p>
  
  <p>[BEGIN-EDIT] 
  <strong>I am now using "nanoflann", which is about 100-1000 times faster than the equivalent in CGAL for K-neighbor search. And I am using "Intel Embree" for raycasting, which is about 100-200 times faster than CGAL's AABB trees.</strong>
  [END-EDIT]</p>
  
  <p>My task looks like this:</p>
  
  <p>I have a HUGE point set, say like up to a few 100 mio. points!! and their distribution is on surfaces of triangulated geometry (yes, a photon tracer). So one could say that their distribution is 2D in 3D space, because it is sparse in 3D but dense when looking at the surfaces... This could be the problem right? Because to me this seems to trigger the worst-case performance of a KD-tree which probably could deal much better with 3D dense point sets...</p>
  
  <p>CGAl is quite good at what it does, so I have a bit doubt that their implementation just sucks. Their AABB tree I am using for raytracing burns a straight billion raytraces in a few mintues in the ground... That is remarkable I guess. But their KD-tree on the other hand can't even deal with a mio. points and 250k samples (point queries) in any reasonable time...</p>
  
  <p>I came up with two solutions which kick the crap out of KD-trees:</p>
  
  <p>1) Use texture maps to store the photons in a linked list on the geometry. This is always an O(1) operation, since you have to do the raycast anyway...</p>
  
  <p>2) Use view dependent sliced hashsets. That is the farther away you get, the more coarse the hashsets get. So basically you can think of a 1024x1024x1024 raster in NDC coordinates, but with hashsets, to save memory in sparse areas. This basically has O(1) complexity and can be parallelized efficiently, both for inserts (micro-sharding) and queries (lock-free). </p>
  
  <p>The former solution has the disadvantage that it is close to impossible to average over neighboring photon lists, which is important in darker regions to avoid noise.
  The latter solution doesn't have this problem and should be on par feature wise with KD-trees, just that it has O(1) worst case performance, lol.</p>
  
  <p>So what do you think? Bad KD-tree implementation? If not, is there something "better" than a KD-tree for bounded nearest neighbor queries? I mean I have nothing against my second solution above, but a "proven" data-structure that delivers similar performance would be nicer!</p>
  
  <p>Thanks!</p>
  
  <p>Here is the code (not compilable though) that I used:</p>
  
  <pre><code>#include "stdafx.h"
  #include "PhotonMap.h"
  
  #pragma warning (push)
      #pragma warning (disable: 4512 4244 4061)
      #pragma warning (disable: 4706 4702 4512 4310 4267 4244 4917 4820 4710 4514 4365 4350 4640 4571 4127 4242 4350 4668 4626)
      #pragma warning (disable: 4625 4265 4371)
  
      #include &lt;CGAL/Simple_cartesian.h&gt;
      #include &lt;CGAL/Orthogonal_incremental_neighbor_search.h&gt;
      #include &lt;CGAL/basic.h&gt;
      #include &lt;CGAL/Search_traits.h&gt;
      #include &lt;CGAL/point_generators_3.h&gt;
  
  #pragma warning (pop)
  
  struct PhotonicPoint
  {
      float vec[3];
      const Photon* photon;
  
      PhotonicPoint(const Photon&amp; photon) : photon(&amp;photon) 
      { 
          vec[0] = photon.hitPoint.getX();
          vec[1] = photon.hitPoint.getY();
          vec[2] = photon.hitPoint.getZ();
      }
  
      PhotonicPoint(Vector3 pos) : photon(nullptr) 
      { 
          vec[0] = pos.getX();
          vec[1] = pos.getY();
          vec[2] = pos.getZ();
      }
  
      PhotonicPoint() : photon(nullptr) { vec[0] = vec[1] = vec[2] = 0; }
  
      float x() const { return vec[0]; }
      float y() const { return vec[1]; }
      float z() const { return vec[2]; }
      float&amp; x() { return vec[0]; }
      float&amp; y() { return vec[1]; }
      float&amp; z() { return vec[2]; }
  
      bool operator==(const PhotonicPoint&amp; p) const
      {
          return (x() == p.x()) &amp;&amp; (y() == p.y()) &amp;&amp; (z() == p.z()) ;
      }
  
      bool operator!=(const PhotonicPoint&amp; p) const 
      { 
          return ! (*this == p); 
      }
  }; 
  
  namespace CGAL 
  {
      template &lt;&gt;
      struct Kernel_traits&lt;PhotonicPoint&gt; 
      {
          struct Kernel 
          {
              typedef float FT;
              typedef float RT;
          };
      };
  }
  
  struct Construct_coord_iterator
  {
      typedef const float* result_type;
  
      const float* operator()(const PhotonicPoint&amp; p) const
      { 
          return static_cast&lt;const float*&gt;(p.vec); 
      }
  
      const float* operator()(const PhotonicPoint&amp; p, int) const
      { 
          return static_cast&lt;const float*&gt;(p.vec+3); 
      }
  };
  
  typedef CGAL::Search_traits&lt;float, PhotonicPoint, const float*, Construct_coord_iterator&gt; Traits;
  typedef CGAL::Orthogonal_incremental_neighbor_search&lt;Traits&gt; NN_incremental_search;
  typedef NN_incremental_search::iterator NN_iterator;
  typedef NN_incremental_search::Tree Tree;
  
  
  struct PhotonMap_Impl
  {
      Tree tree;
  
      PhotonMap_Impl(const PhotonAllocator&amp; allocator) : tree()
      {
          int counter = 0, maxCount = allocator.GetAllocationCounter();
          for(auto&amp; list : allocator.GetPhotonLists())
          {
              int listLength = std::min((int)list.size(), maxCount - counter);
              counter += listLength; 
              tree.insert(std::begin(list), std::begin(list) + listLength);
          }
  
          tree.build();
      }
  };
  
  PhotonMap::PhotonMap(const PhotonAllocator&amp; allocator)
  {
      impl = std::make_shared&lt;PhotonMap_Impl&gt;(allocator);
  }
  
  void PhotonMap::Sample(Vector3 where, float radius, int minCount, std::vector&lt;const Photon*&gt;&amp; outPhotons)
  {
      NN_incremental_search search(impl-&gt;tree, PhotonicPoint(where));
      int count = 0;
  
      for(auto&amp; p : search)
      {
          if((p.second &gt; radius) &amp;&amp; (count &gt; minCount) || (count &gt; 50))
              break;
  
          count++;
          outPhotons.push_back(p.first.photon);
      }
  
  }
  </code></pre>