1 /*=========================================================================
2  *
3  *  Copyright Insight Software Consortium
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *         http://www.apache.org/licenses/LICENSE-2.0.txt
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *=========================================================================*/
18 #ifndef itkKdTree_h
19 #define itkKdTree_h
20 
21 #include <queue>
22 #include <vector>
23 
24 #include "itkPoint.h"
25 #include "itkSize.h"
26 #include "itkObject.h"
27 #include "itkArray.h"
28 
29 #include "itkSubsample.h"
30 
31 #include "itkEuclideanDistanceMetric.h"
32 
33 namespace itk
34 {
35 namespace Statistics
36 {
37 /** \class KdTreeNode
38  *  \brief This class defines the interface of its derived classes.
39  *
40  * The methods defined in this class are a superset of the methods
41  * defined in its subclases. Therefore, the subclasses implements only
42  * part of the methods. The template argument, TSample, can be any
43  * subclass of the Sample class.
44  *
45  * There are two categories for the subclasses, terminal and nonterminal
46  * nodes. The terminal nodes stores the instance identifiers beloging to
47  * them, while the nonterminal nodes don't. Therefore, the
48  * AddInstanceIdentifier and the GetInstanceIdentifier have meaning only
49  * with the terminal ones. The terminal nodes don't have any child (left
50  * or right). For terminal nodes, the GetParameters method is void.
51  *
52  * <b>Recent API changes:</b>
53  * The static const macro to get the length of a measurement vector,
54  * \c MeasurementVectorSize  has been removed to allow the length of a measurement
55  * vector to be specified at run time. The \c type alias for \c CentroidType has
56  * been changed from Array to FixedArray.
57  *
58  * \sa KdTreeNonterminalNode, KdTreeWeightedCentroidNonterminalNode,
59  * KdTreeTerminalNode
60  * \ingroup ITKStatistics
61  */
62 template<typename TSample>
63 
64 struct ITK_TEMPLATE_EXPORT KdTreeNode
65   {
66   /** type alias for itself */
67   using Self = KdTreeNode<TSample>;
68 
69   /** Measurement type, not the measurement vector type */
70   using MeasurementType = typename TSample::MeasurementType;
71 
72   /** Centroid type */
73   using CentroidType = Array<double>;
74 
75   /** Instance identifier type (index value type for the measurement
76    * vector in a sample */
77   using InstanceIdentifier = typename TSample::InstanceIdentifier;
78 
79   /** Returns true if the node is a terminal node, that is a node that
80    * doesn't have any child. */
81   virtual bool IsTerminal() const = 0;
82 
83   /** Fills the partitionDimension (the dimension that was chosen to
84    * split the measurement vectors belong to this node to the left and the
85    * right child among k dimensions) and the partitionValue (the
86    * measurement value on the partitionDimension divides the left and the
87    * right child */
88   virtual void GetParameters( unsigned int &, MeasurementType & ) const = 0;
89 
90   /** Returns the pointer to the left child of this node */
91   virtual Self * Left() = 0;
92 
93   /** Returns the const pointer to the left child of this node */
94   virtual const Self * Left() const = 0;
95 
96   /** Returns the pointer to the right child of this node */
97   virtual Self * Right() = 0;
98 
99   /** Returns the const pointer to the right child of this node */
100   virtual const Self * Right() const = 0;
101 
102   /**
103    * Returs the number of measurement vectors under this node including
104    * its children
105    */
106   virtual unsigned int Size() const = 0;
107 
108   /** Returns the vector sum of the all measurement vectors under this node */
109   virtual void GetWeightedCentroid( CentroidType & ) = 0;
110 
111   /** Returns the centroid. weighted centroid divided by the size */
112   virtual void GetCentroid( CentroidType & ) = 0;
113 
114   /** Retuns the instance identifier of the index-th measurement vector */
115   virtual InstanceIdentifier GetInstanceIdentifier( InstanceIdentifier ) const = 0;
116 
117   /** Add an instance to this node */
118   virtual void AddInstanceIdentifier( InstanceIdentifier ) = 0;
119 
120   /** Destructor */
121   virtual ~KdTreeNode() = default;  // needed to subclasses will actually be deleted
122 }; // end of class
123 
124 /** \class KdTreeNonterminalNode
125  *  \brief This is a subclass of the KdTreeNode.
126  *
127  * KdTreeNonterminalNode doesn't store the information related with the
128  * centroids. Therefore, the GetWeightedCentroid and the GetCentroid
129  * methods are void. This class should have the left and the right
130  * children. If we have a sample and want to generate a KdTree without
131  * the centroid related information, we can use the KdTreeGenerator.
132  *
133  * \sa KdTreeNode, KdTreeWeightedCentroidNonterminalNode, KdTreeGenerator
134  * \ingroup ITKStatistics
135  */
136 template<typename TSample>
137 
138 struct ITK_TEMPLATE_EXPORT KdTreeNonterminalNode:public KdTreeNode<TSample>
139   {
140   using Superclass = KdTreeNode<TSample>;
141   using MeasurementType = typename Superclass::MeasurementType;
142   using CentroidType = typename Superclass::CentroidType;
143   using InstanceIdentifier = typename Superclass::InstanceIdentifier;
144 
145   KdTreeNonterminalNode( unsigned int, MeasurementType, Superclass *,
146     Superclass * );
147 
148   ~KdTreeNonterminalNode() override = default;
149 
IsTerminalKdTreeNonterminalNode150   bool IsTerminal() const override
151   {
152     return false;
153   }
154 
155   void GetParameters( unsigned int &, MeasurementType & ) const override;
156 
157   /** Returns the pointer to the left child of this node */
LeftKdTreeNonterminalNode158   Superclass * Left() override
159   {
160     return m_Left;
161   }
162 
163   /** Returns the pointer to the right child of this node */
RightKdTreeNonterminalNode164   Superclass * Right() override
165   {
166     return m_Right;
167   }
168 
169   /** Returns the const pointer to the left child of this node */
LeftKdTreeNonterminalNode170   const Superclass * Left() const override
171   {
172     return m_Left;
173   }
174 
175   /** Returns the const pointer to the right child of this node */
RightKdTreeNonterminalNode176   const Superclass * Right() const override
177   {
178     return m_Right;
179   }
180 
181   /**
182    * Returs the number of measurement vectors under this node including
183    * its children
184    */
SizeKdTreeNonterminalNode185   unsigned int Size() const override
186   {
187     return 0;
188   }
189 
190   /**
191    * Returns the vector sum of the all measurement vectors under this node.
192    * Do nothing for this class.
193    */
GetWeightedCentroidKdTreeNonterminalNode194   void GetWeightedCentroid( CentroidType & ) override {}
195 
196   /**
197    * Returns the centroid. weighted centroid divided by the size. Do nothing for
198    * this class.
199    */
GetCentroidKdTreeNonterminalNode200   void GetCentroid( CentroidType & ) override {}
201 
202   /**
203    * Returns the identifier of the only MeasurementVector associated with
204    * this node in the tree. This MeasurementVector will be used later during
205    * the distance computation when querying the tree.
206    */
GetInstanceIdentifierKdTreeNonterminalNode207   InstanceIdentifier GetInstanceIdentifier( InstanceIdentifier ) const override
208   {
209     return this->m_InstanceIdentifier;
210   }
211 
212   /**
213    * Set the identifier of the node.
214    */
AddInstanceIdentifierKdTreeNonterminalNode215   void AddInstanceIdentifier( InstanceIdentifier valueId ) override
216   {
217     this->m_InstanceIdentifier = valueId;
218   }
219 
220 private:
221 
222   unsigned int           m_PartitionDimension;
223   MeasurementType        m_PartitionValue;
224   InstanceIdentifier     m_InstanceIdentifier;
225   Superclass            *m_Left;
226   Superclass            *m_Right;
227 };  // end of class
228 
229 /** \class KdTreeWeightedCentroidNonterminalNode
230  *  \brief This is a subclass of the KdTreeNode.
231  *
232  * KdTreeNonterminalNode does have the information related with the
233  * centroids. Therefore, the GetWeightedCentroid and the GetCentroid
234  * methods returns meaningful values. This class should have the left
235  * and right children. If we have a sample and want to generate a KdTree
236  * with the centroid related information, we can use the
237  * WeightedCentroidKdTreeGenerator. The centroid, the weighted
238  * centroid, and the size (the number of measurement vectors) can be
239  * used to accelate the k-means estimation.
240  *
241  * \sa KdTreeNode, KdTreeNonterminalNode, WeightedCentroidKdTreeGenerator
242  * \ingroup ITKStatistics
243  */
244 template<typename TSample>
245 struct ITK_TEMPLATE_EXPORT KdTreeWeightedCentroidNonterminalNode:public KdTreeNode<TSample>
246   {
247   using Superclass = KdTreeNode<TSample>;
248   using MeasurementType = typename Superclass::MeasurementType;
249   using CentroidType = typename Superclass::CentroidType;
250   using InstanceIdentifier = typename Superclass::InstanceIdentifier;
251   using MeasurementVectorSizeType = typename TSample::MeasurementVectorSizeType;
252 
253   KdTreeWeightedCentroidNonterminalNode( unsigned int, MeasurementType,
254     Superclass *, Superclass *, CentroidType &, unsigned int );
255 
256   ~KdTreeWeightedCentroidNonterminalNode() override = default;
257 
258   /** Not a terminal node. */
IsTerminalKdTreeWeightedCentroidNonterminalNode259   bool IsTerminal() const override
260   {
261     return false;
262   }
263 
264   /** Return the parameters of the node. */
265   void GetParameters( unsigned int &, MeasurementType & ) const override;
266 
267   /** Return the length of a measurement vector */
GetMeasurementVectorSizeKdTreeWeightedCentroidNonterminalNode268   MeasurementVectorSizeType GetMeasurementVectorSize() const
269   {
270     return m_MeasurementVectorSize;
271   }
272 
273   /** Return the left tree pointer. */
LeftKdTreeWeightedCentroidNonterminalNode274   Superclass * Left() override
275   {
276     return m_Left;
277   }
278 
279   /** Return the right tree pointer. */
RightKdTreeWeightedCentroidNonterminalNode280   Superclass * Right() override
281   {
282     return m_Right;
283   }
284 
285   /** Return the left tree const pointer. */
LeftKdTreeWeightedCentroidNonterminalNode286   const Superclass * Left() const override
287   {
288     return m_Left;
289   }
290 
291   /** Return the right tree const pointer. */
RightKdTreeWeightedCentroidNonterminalNode292   const Superclass * Right() const override
293   {
294     return m_Right;
295   }
296 
297   /** Return the size of the node. */
SizeKdTreeWeightedCentroidNonterminalNode298   unsigned int Size() const override
299   {
300     return m_Size;
301   }
302 
303   /**
304    * Returns the vector sum of the all measurement vectors under this node.
305    */
GetWeightedCentroidKdTreeWeightedCentroidNonterminalNode306   void GetWeightedCentroid(CentroidType & centroid) override
307   {
308     centroid = m_WeightedCentroid;
309   }
310 
311   /**
312    * Returns the centroid. weighted centroid divided by the size.
313    */
GetCentroidKdTreeWeightedCentroidNonterminalNode314   void GetCentroid(CentroidType & centroid) override
315   {
316     centroid = m_Centroid;
317   }
318 
319   /**
320    * Returns the identifier of the only MeasurementVector associated with
321    * this node in the tree. This MeasurementVector will be used later during
322    * the distance computation when querying the tree.
323    */
GetInstanceIdentifierKdTreeWeightedCentroidNonterminalNode324   InstanceIdentifier GetInstanceIdentifier(InstanceIdentifier) const override
325   {
326     return this->m_InstanceIdentifier;
327   }
328 
329   /**
330    * Set the identifier of the node.
331    */
AddInstanceIdentifierKdTreeWeightedCentroidNonterminalNode332   void AddInstanceIdentifier(InstanceIdentifier valueId) override
333   {
334     this->m_InstanceIdentifier = valueId;
335   }
336 
337 private:
338   MeasurementVectorSizeType     m_MeasurementVectorSize;
339   unsigned int                  m_PartitionDimension;
340   MeasurementType               m_PartitionValue;
341   CentroidType                  m_WeightedCentroid;
342   CentroidType                  m_Centroid;
343   InstanceIdentifier            m_InstanceIdentifier;
344   unsigned int                  m_Size;
345   Superclass                   *m_Left;
346   Superclass                   *m_Right;
347 };  // end of class
348 
349 /** \class KdTreeTerminalNode
350  *  \brief This class is the node that doesn't have any child node. The
351  *  IsTerminal method returns true for this class. This class stores the
352  *  instance identifiers belonging to this node, while the nonterminal
353  *  nodes do not store them. The AddInstanceIdentifier and
354  *  GetInstanceIdentifier are storing and retrieving the instance
355  *  identifiers belonging to this node.
356  *
357  * \sa KdTreeNode, KdTreeNonterminalNode,
358  * KdTreeWeightedCentroidNonterminalNode
359  * \ingroup ITKStatistics
360  */
361 template<typename TSample>
362 struct ITK_TEMPLATE_EXPORT KdTreeTerminalNode:public KdTreeNode<TSample>
363   {
364   using Superclass = KdTreeNode<TSample>;
365   using MeasurementType = typename Superclass::MeasurementType;
366   using CentroidType = typename Superclass::CentroidType;
367   using InstanceIdentifier = typename Superclass::InstanceIdentifier;
368 
369   KdTreeTerminalNode() = default;
370 
~KdTreeTerminalNodeKdTreeTerminalNode371   ~KdTreeTerminalNode() override
372   {
373     this->m_InstanceIdentifiers.clear();
374   }
375 
376   /** A terminal node. */
IsTerminalKdTreeTerminalNode377   bool IsTerminal() const override
378   {
379     return true;
380   }
381 
382   /** Return the parameters of the node. */
GetParametersKdTreeTerminalNode383   void GetParameters( unsigned int &, MeasurementType & ) const override {}
384 
385   /** Return the left tree pointer. Null for terminal nodes. */
LeftKdTreeTerminalNode386   Superclass * Left() override
387   {
388     return nullptr;
389   }
390 
391   /** Return the right tree pointer. Null for terminal nodes. */
RightKdTreeTerminalNode392   Superclass * Right() override
393   {
394     return nullptr;
395   }
396 
397   /** Return the left tree const pointer. Null for terminal nodes. */
LeftKdTreeTerminalNode398   const Superclass * Left() const override
399   {
400     return nullptr;
401   }
402 
403   /** Return the right tree const pointer. Null for terminal nodes. */
RightKdTreeTerminalNode404   const Superclass * Right() const override
405   {
406     return nullptr;
407   }
408 
409   /** Return the size of the node. */
SizeKdTreeTerminalNode410   unsigned int Size() const override
411   {
412     return static_cast< unsigned int >( m_InstanceIdentifiers.size() );
413   }
414 
415   /**
416    * Returns the vector sum of the all measurement vectors under this node.
417    * Do nothing for this case.
418    */
GetWeightedCentroidKdTreeTerminalNode419   void GetWeightedCentroid( CentroidType & ) override {}
420 
421   /**
422    * Returns the centroid. weighted centroid divided by the size.  Do nothing
423    * for this case.
424    */
GetCentroidKdTreeTerminalNode425   void GetCentroid( CentroidType & ) override {}
426 
427   /**
428    * Returns the identifier of the only MeasurementVector associated with
429    * this node in the tree. This MeasurementVector will be used later during
430    * the distance computation when querying the tree.
431    */
GetInstanceIdentifierKdTreeTerminalNode432   InstanceIdentifier GetInstanceIdentifier( InstanceIdentifier index ) const override
433   {
434     return m_InstanceIdentifiers[index];
435   }
436 
437   /**
438    * Set the identifier of the node.
439    */
AddInstanceIdentifierKdTreeTerminalNode440   void AddInstanceIdentifier( InstanceIdentifier id ) override
441   {
442     m_InstanceIdentifiers.push_back( id );
443   }
444 
445 private:
446   std::vector< InstanceIdentifier > m_InstanceIdentifiers;
447 };  // end of class
448 
449 /** \class KdTree
450  *  \brief This class provides methods for k-nearest neighbor search and
451  *  related data structures for a k-d tree.
452  *
453  * An object of this class stores instance identifiers in a k-d tree
454  * that is a binary tree with childrens split along a dimension among
455  * k-dimensions. The dimension of the split (or partition) is determined
456  * for each nonterminal node that has two children. The split process is
457  * terminated when the node has no children (when the number of
458  * measurement vectors is less than or equal to the size set by the
459  * SetBucketSize. That is The split process is a recursive process in
460  * nature and in implementation. This implementation doesn't support
461  * dynamic insert and delete operations for the tree. Instead, we can
462  * use the KdTreeGenerator or WeightedCentroidKdTreeGenerator to
463  * generate a static KdTree object.
464  *
465  * To search k-nearest neighbor, call the Search method with the query
466  * point in a k-d space and the number of nearest neighbors. The
467  * GetSearchResult method returns a pointer to a NearestNeighbors object
468  * with k-nearest neighbors.
469  *
470  * <b>Recent API changes:</b>
471  * The static const macro to get the length of a measurement vector,
472  * 'MeasurementVectorSize'  has been removed to allow the length of a measurement
473  * vector to be specified at run time. Please use the function
474  * GetMeasurementVectorSize() instead.
475 
476  * \sa KdTreeNode, KdTreeNonterminalNode,
477  * KdTreeWeightedCentroidNonterminalNode, KdTreeTerminalNode,
478  * KdTreeGenerator, WeightedCentroidKdTreeNode
479  * \ingroup ITKStatistics
480  */
481 
482 template<typename TSample>
483 class ITK_TEMPLATE_EXPORT KdTree:public Object
484 {
485 public:
486   ITK_DISALLOW_COPY_AND_ASSIGN(KdTree);
487 
488   /** Standard class type aliases */
489   using Self = KdTree;
490   using Superclass = Object;
491   using Pointer = SmartPointer< Self >;
492   using ConstPointer = SmartPointer< const Self >;
493 
494   /** Run-time type information (and related methods) */
495   itkTypeMacro(KdTree, Object);
496 
497   /** Method for creation through the object factory. */
498   itkNewMacro(Self);
499 
500   /** type alias alias for the source data container */
501   using SampleType = TSample;
502   using MeasurementVectorType = typename TSample::MeasurementVectorType;
503   using MeasurementType = typename TSample::MeasurementType;
504   using InstanceIdentifier = typename TSample::InstanceIdentifier;
505   using AbsoluteFrequencyType = typename TSample::AbsoluteFrequencyType;
506 
507   using MeasurementVectorSizeType = unsigned int;
508 
509   /** Get Macro to get the length of a measurement vector in the KdTree.
510    * The length is obtained from the input sample. */
511   itkGetConstMacro( MeasurementVectorSize, MeasurementVectorSizeType );
512 
513   /** DistanceMetric type for the distance calculation and comparison */
514   using DistanceMetricType = EuclideanDistanceMetric< MeasurementVectorType >;
515 
516   /** Node type of the KdTree */
517   using KdTreeNodeType = KdTreeNode<TSample>;
518 
519   /** Neighbor type. The first element of the std::pair is the instance
520    * identifier and the second one is the distance between the measurement
521    * vector identified by the first element and the query point. */
522   using NeighborType = std::pair< InstanceIdentifier, double >;
523 
524   using InstanceIdentifierVectorType = std::vector< InstanceIdentifier >;
525 
526   /** \class NearestNeighbors
527    * \brief data structure for storing k-nearest neighbor search result
528    * (k number of Neighbors)
529    *
530    * This class stores the instance identifiers and the distance values
531    * of k-nearest neighbors. We can also query the farthest neighbor's
532    * distance from the query point using the GetLargestDistance
533    * method.
534    * \ingroup ITKStatistics
535    */
536   class NearestNeighbors
537   {
538   public:
539     /** Constructor */
NearestNeighbors(std::vector<double> & cache_vector)540     NearestNeighbors( std::vector<double> & cache_vector) : m_FarthestNeighborIndex(0), m_Distances(cache_vector)  {}
541 
542     /** Destructor */
543     ~NearestNeighbors() = default;
544 
545     /** Initialize the internal instance identifier and distance holders
546      * with the size, k */
resize(unsigned int k)547     void resize( unsigned int k )
548     {
549       m_Identifiers.clear();
550       m_Identifiers.resize( k, NumericTraits< IdentifierType >::max() );
551       m_Distances.clear();
552       m_Distances.resize( k, NumericTraits<double>::max() );
553       m_FarthestNeighborIndex = 0;
554     }
555 
556     /** Returns the distance of the farthest neighbor from the query point */
GetLargestDistance()557     double GetLargestDistance()
558     {
559       return m_Distances[m_FarthestNeighborIndex];
560     }
561 
562     /** Replaces the farthest neighbor's instance identifier and
563      * distance value with the id and the distance */
ReplaceFarthestNeighbor(InstanceIdentifier id,double distance)564     void ReplaceFarthestNeighbor( InstanceIdentifier id, double distance )
565     {
566       m_Identifiers[m_FarthestNeighborIndex] = id;
567       m_Distances[m_FarthestNeighborIndex] = distance;
568       double farthestDistance = NumericTraits<double>::min();
569       const auto size = static_cast< unsigned int >( m_Distances.size() );
570       for ( unsigned int i = 0; i < size; i++ )
571         {
572         if ( m_Distances[i] > farthestDistance )
573           {
574           farthestDistance = m_Distances[i];
575           m_FarthestNeighborIndex = i;
576           }
577         }
578     }
579 
580     /** Returns the vector of k-neighbors' instance identifiers */
GetNeighbors()581     const InstanceIdentifierVectorType & GetNeighbors() const
582     {
583       return m_Identifiers;
584     }
585 
586     /** Returns the instance identifier of the index-th neighbor among
587      * k-neighbors */
GetNeighbor(unsigned int index)588     InstanceIdentifier GetNeighbor(unsigned int index) const
589     {
590       return m_Identifiers[index];
591     }
592 
593   private:
594     NearestNeighbors() = delete;
595     /** The index of the farthest neighbor among k-neighbors */
596     unsigned int m_FarthestNeighborIndex;
597 
598     /** Storage for the instance identifiers of k-neighbors */
599     InstanceIdentifierVectorType m_Identifiers;
600 
601     /** External storage for the distance values of k-neighbors
602      * from the query point. This is a reference to external
603      * vector to avoid unnecessary memory copying. */
604     std::vector<double> & m_Distances;
605   };
606 
607   /** Sets the number of measurement vectors that can be stored in a
608    * terminal node */
609   void SetBucketSize( unsigned int );
610 
611   /** Sets the input sample that provides the measurement vectors to the k-d
612    * tree */
613   void SetSample( const TSample * );
614 
615   /** Returns the pointer to the input sample */
GetSample()616   const TSample * GetSample() const
617   {
618     return m_Sample;
619   }
620 
Size()621   SizeValueType Size() const
622   {
623     return m_Sample->Size();
624   }
625 
626   /** Returns the pointer to the empty terminal node. A KdTree object
627    * has a single empty terminal node in memory. when the split process
628    * has to create an empty terminal node, the single instance is reused
629    * for this case */
GetEmptyTerminalNode()630   KdTreeNodeType * GetEmptyTerminalNode()
631   {
632     return m_EmptyTerminalNode;
633   }
634 
635   /** Sets the root node of the KdTree that is a result of
636    * KdTreeGenerator or WeightedCentroidKdTreeGenerator. */
SetRoot(KdTreeNodeType * root)637   void SetRoot(KdTreeNodeType *root)
638   {
639     if ( this->m_Root )
640       {
641       this->DeleteNode( this->m_Root );
642       }
643     this->m_Root = root;
644   }
645 
646   /** Returns the pointer to the root node. */
GetRoot()647   KdTreeNodeType * GetRoot()
648   {
649     return m_Root;
650   }
651 
652   /** Returns the measurement vector identified by the instance
653    * identifier that is an identifier defiend for the input sample */
GetMeasurementVector(InstanceIdentifier id)654   const MeasurementVectorType & GetMeasurementVector( InstanceIdentifier id )
655     const
656   {
657     return m_Sample->GetMeasurementVector( id );
658   }
659 
660   /** Returns the frequency of the measurement vector identified by
661    * the instance identifier */
GetFrequency(InstanceIdentifier id)662   AbsoluteFrequencyType GetFrequency(InstanceIdentifier id ) const
663   {
664     return m_Sample->GetFrequency( id );
665   }
666 
667   /** Get the pointer to the distance metric. */
GetDistanceMetric()668   DistanceMetricType * GetDistanceMetric()
669   {
670     return m_DistanceMetric.GetPointer();
671   }
672 
673   /** Searches the k-nearest neighbors */
674   void Search( const MeasurementVectorType &, unsigned int,
675               InstanceIdentifierVectorType & ) const;
676 
677   /** Searches the k-nearest neighbors and returns
678    *  the distance vector along with the distance measures.
679    */
680   void Search( const MeasurementVectorType &, unsigned int,
681     InstanceIdentifierVectorType &, std::vector<double> & ) const;
682 
683   /** Searches the neighbors fallen into a hypersphere */
684   void Search( const MeasurementVectorType &, double,
685     InstanceIdentifierVectorType & ) const;
686 
687   /** Returns true if the intermediate k-nearest neighbors exist within
688    * the the bounding box defined by the lowerBound and the
689    * upperBound. Otherwise returns false. Returns false if the ball
690    * defined by the distance between the query point and the farthest
691    * neighbor touch the surface of the bounding box. */
692   bool BallWithinBounds( const MeasurementVectorType &,
693     MeasurementVectorType &, MeasurementVectorType &, double ) const;
694 
695   /** Returns true if the ball defined by the distance between the query
696    * point and the farthest neighbor overlaps with the bounding box
697    * defined by the lower and the upper bounds. */
698   bool BoundsOverlapBall( const MeasurementVectorType &,
699     MeasurementVectorType &, MeasurementVectorType &, double) const;
700 
701   /** Deletes the node recursively */
702   void DeleteNode( KdTreeNodeType * );
703 
704   /** Prints out the tree information */
705   void PrintTree( std::ostream & ) const;
706 
707   /** Prints out the tree information */
708   void PrintTree( KdTreeNodeType *, unsigned int, unsigned int,
709     std::ostream & os = std::cout ) const;
710 
711   /** Draw out the tree information to a ostream using
712    * the format of the Graphviz dot tool. */
713   void PlotTree( std::ostream & os ) const;
714 
715   /** Prints out the tree information */
716   void PlotTree( KdTreeNodeType *node, std::ostream & os = std::cout ) const;
717 
718   using Iterator = typename TSample::Iterator;
719   using ConstIterator = typename TSample::ConstIterator;
720 
721 protected:
722   /** Constructor */
723   KdTree();
724 
725   /** Destructor: deletes the root node and the empty terminal node. */
726   ~KdTree() override;
727 
728   void PrintSelf( std::ostream & os, Indent indent ) const override;
729 
730   /** search loop */
731   int NearestNeighborSearchLoop( const KdTreeNodeType *,
732     const MeasurementVectorType &, MeasurementVectorType &,
733     MeasurementVectorType &, NearestNeighbors & ) const;
734 
735   /** search loop */
736   int SearchLoop( const KdTreeNodeType *, const MeasurementVectorType &,
737     double, MeasurementVectorType &, MeasurementVectorType &,
738     InstanceIdentifierVectorType & ) const;
739 
740 private:
741   /** Pointer to the input sample */
742   const TSample *m_Sample;
743 
744   /** Number of measurement vectors can be stored in a terminal node. */
745   int m_BucketSize;
746 
747   /** Pointer to the root node */
748   KdTreeNodeType *m_Root;
749 
750   /** Pointer to the empty terminal node */
751   KdTreeNodeType *m_EmptyTerminalNode;
752 
753   /** Distance metric smart pointer */
754   typename DistanceMetricType::Pointer m_DistanceMetric;
755 
756   /** Measurement vector size */
757   MeasurementVectorSizeType m_MeasurementVectorSize;
758 };  // end of class
759 } // end of namespace Statistics
760 } // end of namespace itk
761 
762 #ifndef ITK_MANUAL_INSTANTIATION
763 #include "itkKdTree.hxx"
764 #endif
765 
766 #endif
767