1 /***********************************************************************
2  * Software License Agreement (BSD License)
3  *
4  * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
5  * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
6  *
7  * THE BSD LICENSE
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *************************************************************************/
30 
31 #ifndef OPENCV_FLANN_KMEANS_INDEX_H_
32 #define OPENCV_FLANN_KMEANS_INDEX_H_
33 
34 #include <algorithm>
35 #include <map>
36 #include <cassert>
37 #include <limits>
38 #include <cmath>
39 
40 #include "general.h"
41 #include "nn_index.h"
42 #include "dist.h"
43 #include "matrix.h"
44 #include "result_set.h"
45 #include "heap.h"
46 #include "allocator.h"
47 #include "random.h"
48 #include "saving.h"
49 #include "logger.h"
50 
51 
52 namespace cvflann
53 {
54 
55 struct KMeansIndexParams : public IndexParams
56 {
57     KMeansIndexParams(int branching = 32, int iterations = 11,
58                       flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 )
59     {
60         (*this)["algorithm"] = FLANN_INDEX_KMEANS;
61         // branching factor
62         (*this)["branching"] = branching;
63         // max iterations to perform in one kmeans clustering (kmeans tree)
64         (*this)["iterations"] = iterations;
65         // algorithm used for picking the initial cluster centers for kmeans tree
66         (*this)["centers_init"] = centers_init;
67         // cluster boundary index. Used when searching the kmeans tree
68         (*this)["cb_index"] = cb_index;
69     }
70 };
71 
72 
73 /**
74  * Hierarchical kmeans index
75  *
76  * Contains a tree constructed through a hierarchical kmeans clustering
77  * and other information for indexing a set of points for nearest-neighbour matching.
78  */
79 template <typename Distance>
80 class KMeansIndex : public NNIndex<Distance>
81 {
82 public:
83     typedef typename Distance::ElementType ElementType;
84     typedef typename Distance::ResultType DistanceType;
85 
86 
87 
88     typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&);
89 
90     /**
91      * The function used for choosing the cluster centers.
92      */
93     centersAlgFunction chooseCenters;
94 
95 
96 
97     /**
98      * Chooses the initial centers in the k-means clustering in a random manner.
99      *
100      * Params:
101      *     k = number of centers
102      *     vecs = the dataset of points
103      *     indices = indices in the dataset
104      *     indices_length = length of indices vector
105      *
106      */
chooseCentersRandom(int k,int * indices,int indices_length,int * centers,int & centers_length)107     void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length)
108     {
109         UniqueRandom r(indices_length);
110 
111         int index;
112         for (index=0; index<k; ++index) {
113             bool duplicate = true;
114             int rnd;
115             while (duplicate) {
116                 duplicate = false;
117                 rnd = r.next();
118                 if (rnd<0) {
119                     centers_length = index;
120                     return;
121                 }
122 
123                 centers[index] = indices[rnd];
124 
125                 for (int j=0; j<index; ++j) {
126                     DistanceType sq = distance_(dataset_[centers[index]], dataset_[centers[j]], dataset_.cols);
127                     if (sq<1e-16) {
128                         duplicate = true;
129                     }
130                 }
131             }
132         }
133 
134         centers_length = index;
135     }
136 
137 
138     /**
139      * Chooses the initial centers in the k-means using Gonzales' algorithm
140      * so that the centers are spaced apart from each other.
141      *
142      * Params:
143      *     k = number of centers
144      *     vecs = the dataset of points
145      *     indices = indices in the dataset
146      * Returns:
147      */
chooseCentersGonzales(int k,int * indices,int indices_length,int * centers,int & centers_length)148     void chooseCentersGonzales(int k, int* indices, int indices_length, int* centers, int& centers_length)
149     {
150         int n = indices_length;
151 
152         int rnd = rand_int(n);
153         assert(rnd >=0 && rnd < n);
154 
155         centers[0] = indices[rnd];
156 
157         int index;
158         for (index=1; index<k; ++index) {
159 
160             int best_index = -1;
161             DistanceType best_val = 0;
162             for (int j=0; j<n; ++j) {
163                 DistanceType dist = distance_(dataset_[centers[0]],dataset_[indices[j]],dataset_.cols);
164                 for (int i=1; i<index; ++i) {
165                     DistanceType tmp_dist = distance_(dataset_[centers[i]],dataset_[indices[j]],dataset_.cols);
166                     if (tmp_dist<dist) {
167                         dist = tmp_dist;
168                     }
169                 }
170                 if (dist>best_val) {
171                     best_val = dist;
172                     best_index = j;
173                 }
174             }
175             if (best_index!=-1) {
176                 centers[index] = indices[best_index];
177             }
178             else {
179                 break;
180             }
181         }
182         centers_length = index;
183     }
184 
185 
186     /**
187      * Chooses the initial centers in the k-means using the algorithm
188      * proposed in the KMeans++ paper:
189      * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding
190      *
191      * Implementation of this function was converted from the one provided in Arthur's code.
192      *
193      * Params:
194      *     k = number of centers
195      *     vecs = the dataset of points
196      *     indices = indices in the dataset
197      * Returns:
198      */
chooseCentersKMeanspp(int k,int * indices,int indices_length,int * centers,int & centers_length)199     void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length)
200     {
201         int n = indices_length;
202 
203         double currentPot = 0;
204         DistanceType* closestDistSq = new DistanceType[n];
205 
206         // Choose one random center and set the closestDistSq values
207         int index = rand_int(n);
208         assert(index >=0 && index < n);
209         centers[0] = indices[index];
210 
211         for (int i = 0; i < n; i++) {
212             closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
213             closestDistSq[i] = ensureSquareDistance<Distance>( closestDistSq[i] );
214             currentPot += closestDistSq[i];
215         }
216 
217 
218         const int numLocalTries = 1;
219 
220         // Choose each center
221         int centerCount;
222         for (centerCount = 1; centerCount < k; centerCount++) {
223 
224             // Repeat several trials
225             double bestNewPot = -1;
226             int bestNewIndex = -1;
227             for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {
228 
229                 // Choose our center - have to be slightly careful to return a valid answer even accounting
230                 // for possible rounding errors
231                 double randVal = rand_double(currentPot);
232                 for (index = 0; index < n-1; index++) {
233                     if (randVal <= closestDistSq[index]) break;
234                     else randVal -= closestDistSq[index];
235                 }
236 
237                 // Compute the new potential
238                 double newPot = 0;
239                 for (int i = 0; i < n; i++) {
240                     DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
241                     newPot += std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
242                 }
243 
244                 // Store the best result
245                 if ((bestNewPot < 0)||(newPot < bestNewPot)) {
246                     bestNewPot = newPot;
247                     bestNewIndex = index;
248                 }
249             }
250 
251             // Add the appropriate center
252             centers[centerCount] = indices[bestNewIndex];
253             currentPot = bestNewPot;
254             for (int i = 0; i < n; i++) {
255                 DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols);
256                 closestDistSq[i] = std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
257             }
258         }
259 
260         centers_length = centerCount;
261 
262         delete[] closestDistSq;
263     }
264 
265 
266 
267 public:
268 
getType()269     flann_algorithm_t getType() const CV_OVERRIDE
270     {
271         return FLANN_INDEX_KMEANS;
272     }
273 
274     class KMeansDistanceComputer : public cv::ParallelLoopBody
275     {
276     public:
KMeansDistanceComputer(Distance _distance,const Matrix<ElementType> & _dataset,const int _branching,const int * _indices,const Matrix<double> & _dcenters,const size_t _veclen,int * _count,int * _belongs_to,std::vector<DistanceType> & _radiuses,bool & _converged,cv::Mutex & _mtx)277         KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
278             const int _branching, const int* _indices, const Matrix<double>& _dcenters, const size_t _veclen,
279             int* _count, int* _belongs_to, std::vector<DistanceType>& _radiuses, bool& _converged, cv::Mutex& _mtx)
280             : distance(_distance)
281             , dataset(_dataset)
282             , branching(_branching)
283             , indices(_indices)
284             , dcenters(_dcenters)
285             , veclen(_veclen)
286             , count(_count)
287             , belongs_to(_belongs_to)
288             , radiuses(_radiuses)
289             , converged(_converged)
290             , mtx(_mtx)
291         {
292         }
293 
operator()294         void operator()(const cv::Range& range) const CV_OVERRIDE
295         {
296             const int begin = range.start;
297             const int end = range.end;
298 
299             for( int i = begin; i<end; ++i)
300             {
301                 DistanceType sq_dist = distance(dataset[indices[i]], dcenters[0], veclen);
302                 int new_centroid = 0;
303                 for (int j=1; j<branching; ++j) {
304                     DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
305                     if (sq_dist>new_sq_dist) {
306                         new_centroid = j;
307                         sq_dist = new_sq_dist;
308                     }
309                 }
310                 if (sq_dist > radiuses[new_centroid]) {
311                     radiuses[new_centroid] = sq_dist;
312                 }
313                 if (new_centroid != belongs_to[i]) {
314                     count[belongs_to[i]]--;
315                     count[new_centroid]++;
316                     belongs_to[i] = new_centroid;
317                     mtx.lock();
318                     converged = false;
319                     mtx.unlock();
320                 }
321             }
322         }
323 
324     private:
325         Distance distance;
326         const Matrix<ElementType>& dataset;
327         const int branching;
328         const int* indices;
329         const Matrix<double>& dcenters;
330         const size_t veclen;
331         int* count;
332         int* belongs_to;
333         std::vector<DistanceType>& radiuses;
334         bool& converged;
335         cv::Mutex& mtx;
336         KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
337     };
338 
339     /**
340      * Index constructor
341      *
342      * Params:
343      *          inputData = dataset with the input features
344      *          params = parameters passed to the hierarchical k-means algorithm
345      */
346     KMeansIndex(const Matrix<ElementType>& inputData, const IndexParams& params = KMeansIndexParams(),
347                 Distance d = Distance())
dataset_(inputData)348         : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d)
349     {
350         memoryCounter_ = 0;
351 
352         size_ = dataset_.rows;
353         veclen_ = dataset_.cols;
354 
355         branching_ = get_param(params,"branching",32);
356         iterations_ = get_param(params,"iterations",11);
357         if (iterations_<0) {
358             iterations_ = (std::numeric_limits<int>::max)();
359         }
360         centers_init_  = get_param(params,"centers_init",FLANN_CENTERS_RANDOM);
361 
362         if (centers_init_==FLANN_CENTERS_RANDOM) {
363             chooseCenters = &KMeansIndex::chooseCentersRandom;
364         }
365         else if (centers_init_==FLANN_CENTERS_GONZALES) {
366             chooseCenters = &KMeansIndex::chooseCentersGonzales;
367         }
368         else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
369             chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
370         }
371         else {
372             throw FLANNException("Unknown algorithm for choosing initial centers.");
373         }
374         cb_index_ = 0.4f;
375 
376     }
377 
378 
379     KMeansIndex(const KMeansIndex&);
380     KMeansIndex& operator=(const KMeansIndex&);
381 
382 
383     /**
384      * Index destructor.
385      *
386      * Release the memory used by the index.
387      */
~KMeansIndex()388     virtual ~KMeansIndex()
389     {
390         if (root_ != NULL) {
391             free_centers(root_);
392         }
393         if (indices_!=NULL) {
394             delete[] indices_;
395         }
396     }
397 
398     /**
399      *  Returns size of index.
400      */
size()401     size_t size() const CV_OVERRIDE
402     {
403         return size_;
404     }
405 
406     /**
407      * Returns the length of an index feature.
408      */
veclen()409     size_t veclen() const CV_OVERRIDE
410     {
411         return veclen_;
412     }
413 
414 
set_cb_index(float index)415     void set_cb_index( float index)
416     {
417         cb_index_ = index;
418     }
419 
420     /**
421      * Computes the inde memory usage
422      * Returns: memory used by the index
423      */
usedMemory()424     int usedMemory() const CV_OVERRIDE
425     {
426         return pool_.usedMemory+pool_.wastedMemory+memoryCounter_;
427     }
428 
429     /**
430      * Builds the index
431      */
buildIndex()432     void buildIndex() CV_OVERRIDE
433     {
434         if (branching_<2) {
435             throw FLANNException("Branching factor must be at least 2");
436         }
437 
438         indices_ = new int[size_];
439         for (size_t i=0; i<size_; ++i) {
440             indices_[i] = int(i);
441         }
442 
443         root_ = pool_.allocate<KMeansNode>();
444         std::memset(root_, 0, sizeof(KMeansNode));
445 
446         computeNodeStatistics(root_, indices_, (int)size_);
447         computeClustering(root_, indices_, (int)size_, branching_,0);
448     }
449 
450 
saveIndex(FILE * stream)451     void saveIndex(FILE* stream) CV_OVERRIDE
452     {
453         save_value(stream, branching_);
454         save_value(stream, iterations_);
455         save_value(stream, memoryCounter_);
456         save_value(stream, cb_index_);
457         save_value(stream, *indices_, (int)size_);
458 
459         save_tree(stream, root_);
460     }
461 
462 
loadIndex(FILE * stream)463     void loadIndex(FILE* stream) CV_OVERRIDE
464     {
465         load_value(stream, branching_);
466         load_value(stream, iterations_);
467         load_value(stream, memoryCounter_);
468         load_value(stream, cb_index_);
469         if (indices_!=NULL) {
470             delete[] indices_;
471         }
472         indices_ = new int[size_];
473         load_value(stream, *indices_, size_);
474 
475         if (root_!=NULL) {
476             free_centers(root_);
477         }
478         load_tree(stream, root_);
479 
480         index_params_["algorithm"] = getType();
481         index_params_["branching"] = branching_;
482         index_params_["iterations"] = iterations_;
483         index_params_["centers_init"] = centers_init_;
484         index_params_["cb_index"] = cb_index_;
485 
486     }
487 
488 
489     /**
490      * Find set of nearest neighbors to vec. Their indices are stored inside
491      * the result object.
492      *
493      * Params:
494      *     result = the result object in which the indices of the nearest-neighbors are stored
495      *     vec = the vector for which to search the nearest neighbors
496      *     searchParams = parameters that influence the search algorithm (checks, cb_index)
497      */
findNeighbors(ResultSet<DistanceType> & result,const ElementType * vec,const SearchParams & searchParams)498     void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
499     {
500 
501         int maxChecks = get_param(searchParams,"checks",32);
502 
503         if (maxChecks==FLANN_CHECKS_UNLIMITED) {
504             findExactNN(root_, result, vec);
505         }
506         else {
507             // Priority queue storing intermediate branches in the best-bin-first search
508             Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
509 
510             int checks = 0;
511             findNN(root_, result, vec, checks, maxChecks, heap);
512 
513             BranchSt branch;
514             while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
515                 KMeansNodePtr node = branch.node;
516                 findNN(node, result, vec, checks, maxChecks, heap);
517             }
518             assert(result.full());
519 
520             delete heap;
521         }
522 
523     }
524 
525     /**
526      * Clustering function that takes a cut in the hierarchical k-means
527      * tree and return the clusters centers of that clustering.
528      * Params:
529      *     numClusters = number of clusters to have in the clustering computed
530      * Returns: number of cluster centers
531      */
getClusterCenters(Matrix<DistanceType> & centers)532     int getClusterCenters(Matrix<DistanceType>& centers)
533     {
534         int numClusters = centers.rows;
535         if (numClusters<1) {
536             throw FLANNException("Number of clusters must be at least 1");
537         }
538 
539         DistanceType variance;
540         KMeansNodePtr* clusters = new KMeansNodePtr[numClusters];
541 
542         int clusterCount = getMinVarianceClusters(root_, clusters, numClusters, variance);
543 
544         Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount);
545 
546         for (int i=0; i<clusterCount; ++i) {
547             DistanceType* center = clusters[i]->pivot;
548             for (size_t j=0; j<veclen_; ++j) {
549                 centers[i][j] = center[j];
550             }
551         }
552         delete[] clusters;
553 
554         return clusterCount;
555     }
556 
getParameters()557     IndexParams getParameters() const CV_OVERRIDE
558     {
559         return index_params_;
560     }
561 
562 
563 private:
564     /**
565      * Struture representing a node in the hierarchical k-means tree.
566      */
567     struct KMeansNode
568     {
569         /**
570          * The cluster center.
571          */
572         DistanceType* pivot;
573         /**
574          * The cluster radius.
575          */
576         DistanceType radius;
577         /**
578          * The cluster mean radius.
579          */
580         DistanceType mean_radius;
581         /**
582          * The cluster variance.
583          */
584         DistanceType variance;
585         /**
586          * The cluster size (number of points in the cluster)
587          */
588         int size;
589         /**
590          * Child nodes (only for non-terminal nodes)
591          */
592         KMeansNode** childs;
593         /**
594          * Node points (only for terminal nodes)
595          */
596         int* indices;
597         /**
598          * Level
599          */
600         int level;
601     };
602     typedef KMeansNode* KMeansNodePtr;
603 
604     /**
605      * Alias definition for a nicer syntax.
606      */
607     typedef BranchStruct<KMeansNodePtr, DistanceType> BranchSt;
608 
609 
610 
611 
save_tree(FILE * stream,KMeansNodePtr node)612     void save_tree(FILE* stream, KMeansNodePtr node)
613     {
614         save_value(stream, *node);
615         save_value(stream, *(node->pivot), (int)veclen_);
616         if (node->childs==NULL) {
617             int indices_offset = (int)(node->indices - indices_);
618             save_value(stream, indices_offset);
619         }
620         else {
621             for(int i=0; i<branching_; ++i) {
622                 save_tree(stream, node->childs[i]);
623             }
624         }
625     }
626 
627 
load_tree(FILE * stream,KMeansNodePtr & node)628     void load_tree(FILE* stream, KMeansNodePtr& node)
629     {
630         node = pool_.allocate<KMeansNode>();
631         load_value(stream, *node);
632         node->pivot = new DistanceType[veclen_];
633         load_value(stream, *(node->pivot), (int)veclen_);
634         if (node->childs==NULL) {
635             int indices_offset;
636             load_value(stream, indices_offset);
637             node->indices = indices_ + indices_offset;
638         }
639         else {
640             node->childs = pool_.allocate<KMeansNodePtr>(branching_);
641             for(int i=0; i<branching_; ++i) {
642                 load_tree(stream, node->childs[i]);
643             }
644         }
645     }
646 
647 
648     /**
649      * Helper function
650      */
free_centers(KMeansNodePtr node)651     void free_centers(KMeansNodePtr node)
652     {
653         delete[] node->pivot;
654         if (node->childs!=NULL) {
655             for (int k=0; k<branching_; ++k) {
656                 free_centers(node->childs[k]);
657             }
658         }
659     }
660 
661     /**
662      * Computes the statistics of a node (mean, radius, variance).
663      *
664      * Params:
665      *     node = the node to use
666      *     indices = the indices of the points belonging to the node
667      */
computeNodeStatistics(KMeansNodePtr node,int * indices,int indices_length)668     void computeNodeStatistics(KMeansNodePtr node, int* indices, int indices_length)
669     {
670 
671         DistanceType radius = 0;
672         DistanceType variance = 0;
673         DistanceType* mean = new DistanceType[veclen_];
674         memoryCounter_ += int(veclen_*sizeof(DistanceType));
675 
676         memset(mean,0,veclen_*sizeof(DistanceType));
677 
678         for (size_t i=0; i<size_; ++i) {
679             ElementType* vec = dataset_[indices[i]];
680             for (size_t j=0; j<veclen_; ++j) {
681                 mean[j] += vec[j];
682             }
683             variance += distance_(vec, ZeroIterator<ElementType>(), veclen_);
684         }
685         for (size_t j=0; j<veclen_; ++j) {
686             mean[j] /= size_;
687         }
688         variance /= size_;
689         variance -= distance_(mean, ZeroIterator<ElementType>(), veclen_);
690 
691         DistanceType tmp = 0;
692         for (int i=0; i<indices_length; ++i) {
693             tmp = distance_(mean, dataset_[indices[i]], veclen_);
694             if (tmp>radius) {
695                 radius = tmp;
696             }
697         }
698 
699         node->variance = variance;
700         node->radius = radius;
701         node->pivot = mean;
702     }
703 
704 
705     /**
706      * The method responsible with actually doing the recursive hierarchical
707      * clustering
708      *
709      * Params:
710      *     node = the node to cluster
711      *     indices = indices of the points belonging to the current node
712      *     branching = the branching factor to use in the clustering
713      *
714      * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
715      */
computeClustering(KMeansNodePtr node,int * indices,int indices_length,int branching,int level)716     void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
717     {
718         node->size = indices_length;
719         node->level = level;
720 
721         if (indices_length < branching) {
722             node->indices = indices;
723             std::sort(node->indices,node->indices+indices_length);
724             node->childs = NULL;
725             return;
726         }
727 
728         cv::AutoBuffer<int> centers_idx_buf(branching);
729         int* centers_idx = (int*)centers_idx_buf;
730         int centers_length;
731         (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
732 
733         if (centers_length<branching) {
734             node->indices = indices;
735             std::sort(node->indices,node->indices+indices_length);
736             node->childs = NULL;
737             return;
738         }
739 
740 
741         cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
742         Matrix<double> dcenters((double*)dcenters_buf,branching,veclen_);
743         for (int i=0; i<centers_length; ++i) {
744             ElementType* vec = dataset_[centers_idx[i]];
745             for (size_t k=0; k<veclen_; ++k) {
746                 dcenters[i][k] = double(vec[k]);
747             }
748         }
749 
750         std::vector<DistanceType> radiuses(branching);
751         cv::AutoBuffer<int> count_buf(branching);
752         int* count = (int*)count_buf;
753         for (int i=0; i<branching; ++i) {
754             radiuses[i] = 0;
755             count[i] = 0;
756         }
757 
758         //	assign points to clusters
759         cv::AutoBuffer<int> belongs_to_buf(indices_length);
760         int* belongs_to = (int*)belongs_to_buf;
761         for (int i=0; i<indices_length; ++i) {
762 
763             DistanceType sq_dist = distance_(dataset_[indices[i]], dcenters[0], veclen_);
764             belongs_to[i] = 0;
765             for (int j=1; j<branching; ++j) {
766                 DistanceType new_sq_dist = distance_(dataset_[indices[i]], dcenters[j], veclen_);
767                 if (sq_dist>new_sq_dist) {
768                     belongs_to[i] = j;
769                     sq_dist = new_sq_dist;
770                 }
771             }
772             if (sq_dist>radiuses[belongs_to[i]]) {
773                 radiuses[belongs_to[i]] = sq_dist;
774             }
775             count[belongs_to[i]]++;
776         }
777 
778         bool converged = false;
779         int iteration = 0;
780         while (!converged && iteration<iterations_) {
781             converged = true;
782             iteration++;
783 
784             // compute the new cluster centers
785             for (int i=0; i<branching; ++i) {
786                 memset(dcenters[i],0,sizeof(double)*veclen_);
787                 radiuses[i] = 0;
788             }
789             for (int i=0; i<indices_length; ++i) {
790                 ElementType* vec = dataset_[indices[i]];
791                 double* center = dcenters[belongs_to[i]];
792                 for (size_t k=0; k<veclen_; ++k) {
793                     center[k] += vec[k];
794                 }
795             }
796             for (int i=0; i<branching; ++i) {
797                 int cnt = count[i];
798                 for (size_t k=0; k<veclen_; ++k) {
799                     dcenters[i][k] /= cnt;
800                 }
801             }
802 
803             // reassign points to clusters
804             cv::Mutex mtx;
805             KMeansDistanceComputer invoker(distance_, dataset_, branching, indices, dcenters, veclen_, count, belongs_to, radiuses, converged, mtx);
806             parallel_for_(cv::Range(0, (int)indices_length), invoker);
807 
808             for (int i=0; i<branching; ++i) {
809                 // if one cluster converges to an empty cluster,
810                 // move an element into that cluster
811                 if (count[i]==0) {
812                     int j = (i+1)%branching;
813                     while (count[j]<=1) {
814                         j = (j+1)%branching;
815                     }
816 
817                     for (int k=0; k<indices_length; ++k) {
818                         if (belongs_to[k]==j) {
819                             // for cluster j, we move the furthest element from the center to the empty cluster i
820                             if ( distance_(dataset_[indices[k]], dcenters[j], veclen_) == radiuses[j] ) {
821                                 belongs_to[k] = i;
822                                 count[j]--;
823                                 count[i]++;
824                                 break;
825                             }
826                         }
827                     }
828                     converged = false;
829                 }
830             }
831 
832         }
833 
834         DistanceType** centers = new DistanceType*[branching];
835 
836         for (int i=0; i<branching; ++i) {
837             centers[i] = new DistanceType[veclen_];
838             memoryCounter_ += (int)(veclen_*sizeof(DistanceType));
839             for (size_t k=0; k<veclen_; ++k) {
840                 centers[i][k] = (DistanceType)dcenters[i][k];
841             }
842         }
843 
844 
845         // compute kmeans clustering for each of the resulting clusters
846         node->childs = pool_.allocate<KMeansNodePtr>(branching);
847         int start = 0;
848         int end = start;
849         for (int c=0; c<branching; ++c) {
850             int s = count[c];
851 
852             DistanceType variance = 0;
853             DistanceType mean_radius =0;
854             for (int i=0; i<indices_length; ++i) {
855                 if (belongs_to[i]==c) {
856                     DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
857                     variance += d;
858                     mean_radius += sqrt(d);
859                     std::swap(indices[i],indices[end]);
860                     std::swap(belongs_to[i],belongs_to[end]);
861                     end++;
862                 }
863             }
864             variance /= s;
865             mean_radius /= s;
866             variance -= distance_(centers[c], ZeroIterator<ElementType>(), veclen_);
867 
868             node->childs[c] = pool_.allocate<KMeansNode>();
869             std::memset(node->childs[c], 0, sizeof(KMeansNode));
870             node->childs[c]->radius = radiuses[c];
871             node->childs[c]->pivot = centers[c];
872             node->childs[c]->variance = variance;
873             node->childs[c]->mean_radius = mean_radius;
874             computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
875             start=end;
876         }
877 
878         delete[] centers;
879     }
880 
881 
882 
883     /**
884      * Performs one descent in the hierarchical k-means tree. The branches not
885      * visited are stored in a priority queue.
886      *
887      * Params:
888      *      node = node to explore
889      *      result = container for the k-nearest neighbors found
890      *      vec = query points
891      *      checks = how many points in the dataset have been checked so far
892      *      maxChecks = maximum dataset points to checks
893      */
894 
895 
findNN(KMeansNodePtr node,ResultSet<DistanceType> & result,const ElementType * vec,int & checks,int maxChecks,Heap<BranchSt> * heap)896     void findNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
897                 Heap<BranchSt>* heap)
898     {
899         // Ignore those clusters that are too far away
900         {
901             DistanceType bsq = distance_(vec, node->pivot, veclen_);
902             DistanceType rsq = node->radius;
903             DistanceType wsq = result.worstDist();
904 
905             DistanceType val = bsq-rsq-wsq;
906             DistanceType val2 = val*val-4*rsq*wsq;
907 
908             //if (val>0) {
909             if ((val>0)&&(val2>0)) {
910                 return;
911             }
912         }
913 
914         if (node->childs==NULL) {
915             if (checks>=maxChecks) {
916                 if (result.full()) return;
917             }
918             checks += node->size;
919             for (int i=0; i<node->size; ++i) {
920                 int index = node->indices[i];
921                 DistanceType dist = distance_(dataset_[index], vec, veclen_);
922                 result.addPoint(dist, index);
923             }
924         }
925         else {
926             DistanceType* domain_distances = new DistanceType[branching_];
927             int closest_center = exploreNodeBranches(node, vec, domain_distances, heap);
928             delete[] domain_distances;
929             findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap);
930         }
931     }
932 
933     /**
934      * Helper function that computes the nearest childs of a node to a given query point.
935      * Params:
936      *     node = the node
937      *     q = the query point
938      *     distances = array with the distances to each child node.
939      * Returns:
940      */
exploreNodeBranches(KMeansNodePtr node,const ElementType * q,DistanceType * domain_distances,Heap<BranchSt> * heap)941     int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, Heap<BranchSt>* heap)
942     {
943 
944         int best_index = 0;
945         domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_);
946         for (int i=1; i<branching_; ++i) {
947             domain_distances[i] = distance_(q, node->childs[i]->pivot, veclen_);
948             if (domain_distances[i]<domain_distances[best_index]) {
949                 best_index = i;
950             }
951         }
952 
953         //		float* best_center = node->childs[best_index]->pivot;
954         for (int i=0; i<branching_; ++i) {
955             if (i != best_index) {
956                 domain_distances[i] -= cb_index_*node->childs[i]->variance;
957 
958                 //				float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q);
959                 //				if (domain_distances[i]<dist_to_border) {
960                 //					domain_distances[i] = dist_to_border;
961                 //				}
962                 heap->insert(BranchSt(node->childs[i],domain_distances[i]));
963             }
964         }
965 
966         return best_index;
967     }
968 
969 
970     /**
971      * Function the performs exact nearest neighbor search by traversing the entire tree.
972      */
findExactNN(KMeansNodePtr node,ResultSet<DistanceType> & result,const ElementType * vec)973     void findExactNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec)
974     {
975         // Ignore those clusters that are too far away
976         {
977             DistanceType bsq = distance_(vec, node->pivot, veclen_);
978             DistanceType rsq = node->radius;
979             DistanceType wsq = result.worstDist();
980 
981             DistanceType val = bsq-rsq-wsq;
982             DistanceType val2 = val*val-4*rsq*wsq;
983 
984             //                  if (val>0) {
985             if ((val>0)&&(val2>0)) {
986                 return;
987             }
988         }
989 
990 
991         if (node->childs==NULL) {
992             for (int i=0; i<node->size; ++i) {
993                 int index = node->indices[i];
994                 DistanceType dist = distance_(dataset_[index], vec, veclen_);
995                 result.addPoint(dist, index);
996             }
997         }
998         else {
999             int* sort_indices = new int[branching_];
1000 
1001             getCenterOrdering(node, vec, sort_indices);
1002 
1003             for (int i=0; i<branching_; ++i) {
1004                 findExactNN(node->childs[sort_indices[i]],result,vec);
1005             }
1006 
1007             delete[] sort_indices;
1008         }
1009     }
1010 
1011 
1012     /**
1013      * Helper function.
1014      *
1015      * I computes the order in which to traverse the child nodes of a particular node.
1016      */
getCenterOrdering(KMeansNodePtr node,const ElementType * q,int * sort_indices)1017     void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices)
1018     {
1019         DistanceType* domain_distances = new DistanceType[branching_];
1020         for (int i=0; i<branching_; ++i) {
1021             DistanceType dist = distance_(q, node->childs[i]->pivot, veclen_);
1022 
1023             int j=0;
1024             while (domain_distances[j]<dist && j<i) j++;
1025             for (int k=i; k>j; --k) {
1026                 domain_distances[k] = domain_distances[k-1];
1027                 sort_indices[k] = sort_indices[k-1];
1028             }
1029             domain_distances[j] = dist;
1030             sort_indices[j] = i;
1031         }
1032         delete[] domain_distances;
1033     }
1034 
1035     /**
1036      * Method that computes the squared distance from the query point q
1037      * from inside region with center c to the border between this
1038      * region and the region with center p
1039      */
getDistanceToBorder(DistanceType * p,DistanceType * c,DistanceType * q)1040     DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q)
1041     {
1042         DistanceType sum = 0;
1043         DistanceType sum2 = 0;
1044 
1045         for (int i=0; i<veclen_; ++i) {
1046             DistanceType t = c[i]-p[i];
1047             sum += t*(q[i]-(c[i]+p[i])/2);
1048             sum2 += t*t;
1049         }
1050 
1051         return sum*sum/sum2;
1052     }
1053 
1054 
1055     /**
1056      * Helper function the descends in the hierarchical k-means tree by splitting those clusters that minimize
1057      * the overall variance of the clustering.
1058      * Params:
1059      *     root = root node
1060      *     clusters = array with clusters centers (return value)
1061      *     varianceValue = variance of the clustering (return value)
1062      * Returns:
1063      */
getMinVarianceClusters(KMeansNodePtr root,KMeansNodePtr * clusters,int clusters_length,DistanceType & varianceValue)1064     int getMinVarianceClusters(KMeansNodePtr root, KMeansNodePtr* clusters, int clusters_length, DistanceType& varianceValue)
1065     {
1066         int clusterCount = 1;
1067         clusters[0] = root;
1068 
1069         DistanceType meanVariance = root->variance*root->size;
1070 
1071         while (clusterCount<clusters_length) {
1072             DistanceType minVariance = (std::numeric_limits<DistanceType>::max)();
1073             int splitIndex = -1;
1074 
1075             for (int i=0; i<clusterCount; ++i) {
1076                 if (clusters[i]->childs != NULL) {
1077 
1078                     DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size;
1079 
1080                     for (int j=0; j<branching_; ++j) {
1081                         variance += clusters[i]->childs[j]->variance*clusters[i]->childs[j]->size;
1082                     }
1083                     if (variance<minVariance) {
1084                         minVariance = variance;
1085                         splitIndex = i;
1086                     }
1087                 }
1088             }
1089 
1090             if (splitIndex==-1) break;
1091             if ( (branching_+clusterCount-1) > clusters_length) break;
1092 
1093             meanVariance = minVariance;
1094 
1095             // split node
1096             KMeansNodePtr toSplit = clusters[splitIndex];
1097             clusters[splitIndex] = toSplit->childs[0];
1098             for (int i=1; i<branching_; ++i) {
1099                 clusters[clusterCount++] = toSplit->childs[i];
1100             }
1101         }
1102 
1103         varianceValue = meanVariance/root->size;
1104         return clusterCount;
1105     }
1106 
1107 private:
1108     /** The branching factor used in the hierarchical k-means clustering */
1109     int branching_;
1110 
1111     /** Maximum number of iterations to use when performing k-means clustering */
1112     int iterations_;
1113 
1114     /** Algorithm for choosing the cluster centers */
1115     flann_centers_init_t centers_init_;
1116 
1117     /**
1118      * Cluster border index. This is used in the tree search phase when determining
1119      * the closest cluster to explore next. A zero value takes into account only
1120      * the cluster centres, a value greater then zero also take into account the size
1121      * of the cluster.
1122      */
1123     float cb_index_;
1124 
1125     /**
1126      * The dataset used by this index
1127      */
1128     const Matrix<ElementType> dataset_;
1129 
1130     /** Index parameters */
1131     IndexParams index_params_;
1132 
1133     /**
1134      * Number of features in the dataset.
1135      */
1136     size_t size_;
1137 
1138     /**
1139      * Length of each feature.
1140      */
1141     size_t veclen_;
1142 
1143     /**
1144      * The root node in the tree.
1145      */
1146     KMeansNodePtr root_;
1147 
1148     /**
1149      *  Array of indices to vectors in the dataset.
1150      */
1151     int* indices_;
1152 
1153     /**
1154      * The distance
1155      */
1156     Distance distance_;
1157 
1158     /**
1159      * Pooled memory allocator.
1160      */
1161     PooledAllocator pool_;
1162 
1163     /**
1164      * Memory occupied by the index.
1165      */
1166     int memoryCounter_;
1167 };
1168 
1169 }
1170 
1171 #endif //OPENCV_FLANN_KMEANS_INDEX_H_
1172