kmeans_index.h 66.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
/***********************************************************************
 * Software License Agreement (BSD License)
 *
 * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
 * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
 *
 * THE BSD LICENSE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *************************************************************************/

#ifndef OPENCV_FLANN_KMEANS_INDEX_H_
#define OPENCV_FLANN_KMEANS_INDEX_H_

//! @cond IGNORED

#include <algorithm>
#include <map>
#include <limits>
#include <cmath>

#include "general.h"
#include "nn_index.h"
#include "dist.h"
#include "matrix.h"
#include "result_set.h"
#include "heap.h"
#include "allocator.h"
#include "random.h"
#include "saving.h"
#include "logger.h"

#define BITS_PER_CHAR 8
#define BITS_PER_BASE 2 // for DNA/RNA sequences
#define BASE_PER_CHAR (BITS_PER_CHAR/BITS_PER_BASE)
#define HISTOS_PER_BASE (1<<BITS_PER_BASE)


namespace cvflann
{

struct KMeansIndexParams : public IndexParams
{
    KMeansIndexParams(int branching = 32, int iterations = 11,
                      flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM,
                      float cb_index = 0.2, int trees = 1 )
    {
        (*this)["algorithm"] = FLANN_INDEX_KMEANS;
        // branching factor
        (*this)["branching"] = branching;
        // max iterations to perform in one kmeans clustering (kmeans tree)
        (*this)["iterations"] = iterations;
        // algorithm used for picking the initial cluster centers for kmeans tree
        (*this)["centers_init"] = centers_init;
        // cluster boundary index. Used when searching the kmeans tree
        (*this)["cb_index"] = cb_index;
        // number of kmeans trees to search in
        (*this)["trees"] = trees;
    }
};


/**
 * Hierarchical kmeans index
 *
 * Contains a tree constructed through a hierarchical kmeans clustering
 * and other information for indexing a set of points for nearest-neighbour matching.
 */
template <typename Distance>
class KMeansIndex : public NNIndex<Distance>
{
public:
    typedef typename Distance::ElementType ElementType;
    typedef typename Distance::ResultType DistanceType;
    typedef typename Distance::CentersType CentersType;

    typedef typename Distance::is_kdtree_distance is_kdtree_distance;
    typedef typename Distance::is_vector_space_distance is_vector_space_distance;



    typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&);

    /**
     * The function used for choosing the cluster centers.
     */
    centersAlgFunction chooseCenters;



    /**
     * Chooses the initial centers in the k-means clustering in a random manner.
     *
     * Params:
     *     k = number of centers
     *     vecs = the dataset of points
     *     indices = indices in the dataset
     *     indices_length = length of indices vector
     *
     */
    void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length)
    {
        UniqueRandom r(indices_length);

        int index;
        for (index=0; index<k; ++index) {
            bool duplicate = true;
            int rnd;
            while (duplicate) {
                duplicate = false;
                rnd = r.next();
                if (rnd<0) {
                    centers_length = index;
                    return;
                }

                centers[index] = indices[rnd];

                for (int j=0; j<index; ++j) {
                    DistanceType sq = distance_(dataset_[centers[index]], dataset_[centers[j]], dataset_.cols);
                    if (sq<1e-16) {
                        duplicate = true;
                    }
                }
            }
        }

        centers_length = index;
    }


    /**
     * Chooses the initial centers in the k-means using Gonzales' algorithm
     * so that the centers are spaced apart from each other.
     *
     * Params:
     *     k = number of centers
     *     vecs = the dataset of points
     *     indices = indices in the dataset
     * Returns:
     */
    void chooseCentersGonzales(int k, int* indices, int indices_length, int* centers, int& centers_length)
    {
        int n = indices_length;

        int rnd = rand_int(n);
        CV_DbgAssert(rnd >=0 && rnd < n);

        centers[0] = indices[rnd];

        int index;
        for (index=1; index<k; ++index) {

            int best_index = -1;
            DistanceType best_val = 0;
            for (int j=0; j<n; ++j) {
                DistanceType dist = distance_(dataset_[centers[0]],dataset_[indices[j]],dataset_.cols);
                for (int i=1; i<index; ++i) {
                    DistanceType tmp_dist = distance_(dataset_[centers[i]],dataset_[indices[j]],dataset_.cols);
                    if (tmp_dist<dist) {
                        dist = tmp_dist;
                    }
                }
                if (dist>best_val) {
                    best_val = dist;
                    best_index = j;
                }
            }
            if (best_index!=-1) {
                centers[index] = indices[best_index];
            }
            else {
                break;
            }
        }
        centers_length = index;
    }


    /**
     * Chooses the initial centers in the k-means using the algorithm
     * proposed in the KMeans++ paper:
     * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding
     *
     * Implementation of this function was converted from the one provided in Arthur's code.
     *
     * Params:
     *     k = number of centers
     *     vecs = the dataset of points
     *     indices = indices in the dataset
     * Returns:
     */
    void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length)
    {
        int n = indices_length;

        double currentPot = 0;
        DistanceType* closestDistSq = new DistanceType[n];

        // Choose one random center and set the closestDistSq values
        int index = rand_int(n);
        CV_DbgAssert(index >=0 && index < n);
        centers[0] = indices[index];

        for (int i = 0; i < n; i++) {
            closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
            closestDistSq[i] = ensureSquareDistance<Distance>( closestDistSq[i] );
            currentPot += closestDistSq[i];
        }


        const int numLocalTries = 1;

        // Choose each center
        int centerCount;
        for (centerCount = 1; centerCount < k; centerCount++) {

            // Repeat several trials
            double bestNewPot = -1;
            int bestNewIndex = -1;
            for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {

                // Choose our center - have to be slightly careful to return a valid answer even accounting
                // for possible rounding errors
                double randVal = rand_double(currentPot);
                for (index = 0; index < n-1; index++) {
                    if (randVal <= closestDistSq[index]) break;
                    else randVal -= closestDistSq[index];
                }

                // Compute the new potential
                double newPot = 0;
                for (int i = 0; i < n; i++) {
                    DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
                    newPot += std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
                }

                // Store the best result
                if ((bestNewPot < 0)||(newPot < bestNewPot)) {
                    bestNewPot = newPot;
                    bestNewIndex = index;
                }
            }

            // Add the appropriate center
            centers[centerCount] = indices[bestNewIndex];
            currentPot = bestNewPot;
            for (int i = 0; i < n; i++) {
                DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols);
                closestDistSq[i] = std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
            }
        }

        centers_length = centerCount;

        delete[] closestDistSq;
    }



public:

    flann_algorithm_t getType() const CV_OVERRIDE
    {
        return FLANN_INDEX_KMEANS;
    }

    template<class CentersContainerType>
    class KMeansDistanceComputer : public cv::ParallelLoopBody
    {
    public:
        KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
            const int _branching, const int* _indices, const CentersContainerType& _dcenters,
            const size_t _veclen, std::vector<int> &_new_centroids,
            std::vector<DistanceType> &_sq_dists)
            : distance(_distance)
            , dataset(_dataset)
            , branching(_branching)
            , indices(_indices)
            , dcenters(_dcenters)
            , veclen(_veclen)
            , new_centroids(_new_centroids)
            , sq_dists(_sq_dists)
        {
        }

        void operator()(const cv::Range& range) const CV_OVERRIDE
        {
            const int begin = range.start;
            const int end = range.end;

            for( int i = begin; i<end; ++i)
            {
                DistanceType sq_dist(distance(dataset[indices[i]], dcenters[0], veclen));
                int new_centroid(0);
                for (int j=1; j<branching; ++j) {
                    DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
                    if (sq_dist>new_sq_dist) {
                        new_centroid = j;
                        sq_dist = new_sq_dist;
                    }
                }
                sq_dists[i] = sq_dist;
                new_centroids[i] = new_centroid;
            }
        }

    private:
        Distance distance;
        const Matrix<ElementType>& dataset;
        const int branching;
        const int* indices;
        const CentersContainerType& dcenters;
        const size_t veclen;
        std::vector<int> &new_centroids;
        std::vector<DistanceType> &sq_dists;
        KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
    };

    /**
     * Index constructor
     *
     * Params:
     *          inputData = dataset with the input features
     *          params = parameters passed to the hierarchical k-means algorithm
     */
    KMeansIndex(const Matrix<ElementType>& inputData, const IndexParams& params = KMeansIndexParams(),
                Distance d = Distance())
        : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d)
    {
        memoryCounter_ = 0;

        size_ = dataset_.rows;
        veclen_ = dataset_.cols;

        branching_ = get_param(params,"branching",32);
        trees_ = get_param(params,"trees",1);
        iterations_ = get_param(params,"iterations",11);
        if (iterations_<0) {
            iterations_ = (std::numeric_limits<int>::max)();
        }
        centers_init_  = get_param(params,"centers_init",FLANN_CENTERS_RANDOM);

        if (centers_init_==FLANN_CENTERS_RANDOM) {
            chooseCenters = &KMeansIndex::chooseCentersRandom;
        }
        else if (centers_init_==FLANN_CENTERS_GONZALES) {
            chooseCenters = &KMeansIndex::chooseCentersGonzales;
        }
        else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
            chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
        }
        else {
            FLANN_THROW(cv::Error::StsBadArg, "Unknown algorithm for choosing initial centers.");
        }
        cb_index_ = 0.4f;

        root_ = new KMeansNodePtr[trees_];
        indices_ = new int*[trees_];

        for (int i=0; i<trees_; ++i) {
            root_[i] = NULL;
            indices_[i] = NULL;
        }
    }


    KMeansIndex(const KMeansIndex&);
    KMeansIndex& operator=(const KMeansIndex&);


    /**
     * Index destructor.
     *
     * Release the memory used by the index.
     */
    virtual ~KMeansIndex()
    {
        if (root_ != NULL) {
            free_centers();
            delete[] root_;
        }
        if (indices_!=NULL) {
            free_indices();
            delete[] indices_;
        }
    }

    /**
     *  Returns size of index.
     */
    size_t size() const CV_OVERRIDE
    {
        return size_;
    }

    /**
     * Returns the length of an index feature.
     */
    size_t veclen() const CV_OVERRIDE
    {
        return veclen_;
    }


    void set_cb_index( float index)
    {
        cb_index_ = index;
    }

    /**
     * Computes the inde memory usage
     * Returns: memory used by the index
     */
    int usedMemory() const CV_OVERRIDE
    {
        return pool_.usedMemory+pool_.wastedMemory+memoryCounter_;
    }

    /**
     * Builds the index
     */
    void buildIndex() CV_OVERRIDE
    {
        if (branching_<2) {
            FLANN_THROW(cv::Error::StsError, "Branching factor must be at least 2");
        }

        free_indices();

        for (int i=0; i<trees_; ++i) {
            indices_[i] = new int[size_];
            for (size_t j=0; j<size_; ++j) {
                indices_[i][j] = int(j);
            }
            root_[i] = pool_.allocate<KMeansNode>();
            std::memset(root_[i], 0, sizeof(KMeansNode));

            Distance* dummy = NULL;
            computeNodeStatistics(root_[i], indices_[i], (unsigned int)size_, dummy);

            computeClustering(root_[i], indices_[i], (int)size_, branching_,0);
        }
    }


    void saveIndex(FILE* stream) CV_OVERRIDE
    {
        save_value(stream, branching_);
        save_value(stream, iterations_);
        save_value(stream, memoryCounter_);
        save_value(stream, cb_index_);
        save_value(stream, trees_);
        for (int i=0; i<trees_; ++i) {
            save_value(stream, *indices_[i], (int)size_);
            save_tree(stream, root_[i], i);
        }
    }


    void loadIndex(FILE* stream) CV_OVERRIDE
    {
        if (indices_!=NULL) {
            free_indices();
            delete[] indices_;
        }
        if (root_!=NULL) {
            free_centers();
        }

        load_value(stream, branching_);
        load_value(stream, iterations_);
        load_value(stream, memoryCounter_);
        load_value(stream, cb_index_);
        load_value(stream, trees_);

        indices_ = new int*[trees_];
        for (int i=0; i<trees_; ++i) {
            indices_[i] = new int[size_];
            load_value(stream, *indices_[i], size_);
            load_tree(stream, root_[i], i);
        }

        index_params_["algorithm"] = getType();
        index_params_["branching"] = branching_;
        index_params_["trees"] = trees_;
        index_params_["iterations"] = iterations_;
        index_params_["centers_init"] = centers_init_;
        index_params_["cb_index"] = cb_index_;
    }


    /**
     * Find set of nearest neighbors to vec. Their indices are stored inside
     * the result object.
     *
     * Params:
     *     result = the result object in which the indices of the nearest-neighbors are stored
     *     vec = the vector for which to search the nearest neighbors
     *     searchParams = parameters that influence the search algorithm (checks, cb_index)
     */
    void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
    {

        const int maxChecks = get_param(searchParams,"checks",32);

        if (maxChecks==FLANN_CHECKS_UNLIMITED) {
            findExactNN(root_[0], result, vec);
        }
        else {
            // Priority queue storing intermediate branches in the best-bin-first search
            const cv::Ptr<Heap<BranchSt>>& heap = Heap<BranchSt>::getPooledInstance(cv::utils::getThreadID(), (int)size_);

            int checks = 0;
            for (int i=0; i<trees_; ++i) {
                findNN(root_[i], result, vec, checks, maxChecks, heap);
                if ((checks >= maxChecks) && result.full())
                    break;
            }

            BranchSt branch;
            while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
                KMeansNodePtr node = branch.node;
                findNN(node, result, vec, checks, maxChecks, heap);
            }
            CV_Assert(result.full());
        }
    }

    /**
     * Clustering function that takes a cut in the hierarchical k-means
     * tree and return the clusters centers of that clustering.
     * Params:
     *     numClusters = number of clusters to have in the clustering computed
     * Returns: number of cluster centers
     */
    int getClusterCenters(Matrix<CentersType>& centers)
    {
        int numClusters = centers.rows;
        if (numClusters<1) {
            FLANN_THROW(cv::Error::StsBadArg, "Number of clusters must be at least 1");
        }

        DistanceType variance;
        KMeansNodePtr* clusters = new KMeansNodePtr[numClusters];

        int clusterCount = getMinVarianceClusters(root_[0], clusters, numClusters, variance);

        Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount);

        for (int i=0; i<clusterCount; ++i) {
            CentersType* center = clusters[i]->pivot;
            for (size_t j=0; j<veclen_; ++j) {
                centers[i][j] = center[j];
            }
        }
        delete[] clusters;

        return clusterCount;
    }

    IndexParams getParameters() const CV_OVERRIDE
    {
        return index_params_;
    }


private:
    /**
     * Structure representing a node in the hierarchical k-means tree.
     */
    struct KMeansNode
    {
        /**
         * The cluster center.
         */
        CentersType* pivot;
        /**
         * The cluster radius.
         */
        DistanceType radius;
        /**
         * The cluster mean radius.
         */
        DistanceType mean_radius;
        /**
         * The cluster variance.
         */
        DistanceType variance;
        /**
         * The cluster size (number of points in the cluster)
         */
        int size;
        /**
         * Child nodes (only for non-terminal nodes)
         */
        KMeansNode** childs;
        /**
         * Node points (only for terminal nodes)
         */
        int* indices;
        /**
         * Level
         */
        int level;
    };
    typedef KMeansNode* KMeansNodePtr;

    /**
     * Alias definition for a nicer syntax.
     */
    typedef BranchStruct<KMeansNodePtr, DistanceType> BranchSt;




    void save_tree(FILE* stream, KMeansNodePtr node, int num)
    {
        save_value(stream, *node);
        save_value(stream, *(node->pivot), (int)veclen_);
        if (node->childs==NULL) {
            int indices_offset = (int)(node->indices - indices_[num]);
            save_value(stream, indices_offset);
        }
        else {
            for(int i=0; i<branching_; ++i) {
                save_tree(stream, node->childs[i], num);
            }
        }
    }


    void load_tree(FILE* stream, KMeansNodePtr& node, int num)
    {
        node = pool_.allocate<KMeansNode>();
        load_value(stream, *node);
        node->pivot = new CentersType[veclen_];
        load_value(stream, *(node->pivot), (int)veclen_);
        if (node->childs==NULL) {
            int indices_offset;
            load_value(stream, indices_offset);
            node->indices = indices_[num] + indices_offset;
        }
        else {
            node->childs = pool_.allocate<KMeansNodePtr>(branching_);
            for(int i=0; i<branching_; ++i) {
                load_tree(stream, node->childs[i], num);
            }
        }
    }


    /**
     * Helper function
     */
    void free_centers(KMeansNodePtr node)
    {
        delete[] node->pivot;
        if (node->childs!=NULL) {
            for (int k=0; k<branching_; ++k) {
                free_centers(node->childs[k]);
            }
        }
    }

    void free_centers()
    {
       if (root_ != NULL) {
           for(int i=0; i<trees_; ++i) {
               if (root_[i] != NULL) {
                   free_centers(root_[i]);
               }
           }
       }
    }

    /**
     * Release the inner elements of indices[]
     */
    void free_indices()
    {
        if (indices_!=NULL) {
            for(int i=0; i<trees_; ++i) {
                if (indices_[i]!=NULL) {
                    delete[] indices_[i];
                    indices_[i] = NULL;
                }
            }
        }
    }

    /**
     * Computes the statistics of a node (mean, radius, variance).
     *
     * Params:
     *     node = the node to use
     *     indices = array of indices of the points belonging to the node
     *     indices_length = number of indices in the array
     */
    void computeNodeStatistics(KMeansNodePtr node, int* indices, unsigned int indices_length)
    {
        DistanceType variance = 0;
        CentersType* mean = new CentersType[veclen_];
        memoryCounter_ += int(veclen_*sizeof(CentersType));

        memset(mean,0,veclen_*sizeof(CentersType));

        for (unsigned int i=0; i<indices_length; ++i) {
            ElementType* vec = dataset_[indices[i]];
            for (size_t j=0; j<veclen_; ++j) {
                mean[j] += vec[j];
            }
            variance += distance_(vec, ZeroIterator<ElementType>(), veclen_);
        }
        float length = static_cast<float>(indices_length);
        for (size_t j=0; j<veclen_; ++j) {
            mean[j] = cvflann::round<CentersType>( mean[j] / static_cast<double>(indices_length) );
        }
        variance /= static_cast<DistanceType>( length );
        variance -= distance_(mean, ZeroIterator<ElementType>(), veclen_);

        DistanceType radius = 0;
        for (unsigned int i=0; i<indices_length; ++i) {
            DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
            if (tmp>radius) {
                radius = tmp;
            }
        }

        node->variance = variance;
        node->radius = radius;
        node->pivot = mean;
    }


    void computeBitfieldNodeStatistics(KMeansNodePtr node, int* indices,
                                       unsigned int indices_length)
    {
        const unsigned int accumulator_veclen = static_cast<unsigned int>(
                                                veclen_*sizeof(CentersType)*BITS_PER_CHAR);

        unsigned long long variance = 0ull;
        CentersType* mean = new CentersType[veclen_];
        memoryCounter_ += int(veclen_*sizeof(CentersType));
        unsigned int* mean_accumulator = new unsigned int[accumulator_veclen];

        memset(mean_accumulator, 0, sizeof(unsigned int)*accumulator_veclen);

        for (unsigned int i=0; i<indices_length; ++i) {
            variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(
                        distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_)));
            unsigned char* vec = (unsigned char*)dataset_[indices[i]];
            for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
                mean_accumulator[k]   += (vec[l])    & 0x01;
                mean_accumulator[k+1] += (vec[l]>>1) & 0x01;
                mean_accumulator[k+2] += (vec[l]>>2) & 0x01;
                mean_accumulator[k+3] += (vec[l]>>3) & 0x01;
                mean_accumulator[k+4] += (vec[l]>>4) & 0x01;
                mean_accumulator[k+5] += (vec[l]>>5) & 0x01;
                mean_accumulator[k+6] += (vec[l]>>6) & 0x01;
                mean_accumulator[k+7] += (vec[l]>>7) & 0x01;
            }
        }
        double cnt = static_cast<double>(indices_length);
        unsigned char* char_mean = (unsigned char*)mean;
        for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
            char_mean[l] = static_cast<unsigned char>(
                              (((int)(0.5 + (double)(mean_accumulator[k])   / cnt)))
                            | (((int)(0.5 + (double)(mean_accumulator[k+1]) / cnt))<<1)
                            | (((int)(0.5 + (double)(mean_accumulator[k+2]) / cnt))<<2)
                            | (((int)(0.5 + (double)(mean_accumulator[k+3]) / cnt))<<3)
                            | (((int)(0.5 + (double)(mean_accumulator[k+4]) / cnt))<<4)
                            | (((int)(0.5 + (double)(mean_accumulator[k+5]) / cnt))<<5)
                            | (((int)(0.5 + (double)(mean_accumulator[k+6]) / cnt))<<6)
                            | (((int)(0.5 + (double)(mean_accumulator[k+7]) / cnt))<<7));
        }
        variance = static_cast<unsigned long long>(
                    0.5 + static_cast<double>(variance) / static_cast<double>(indices_length));
        variance -= static_cast<unsigned long long>(
                    ensureSquareDistance<Distance>(
                        distance_(mean, ZeroIterator<ElementType>(), veclen_)));

        DistanceType radius = 0;
        for (unsigned int i=0; i<indices_length; ++i) {
            DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
            if (tmp>radius) {
                radius = tmp;
            }
        }

        node->variance = static_cast<DistanceType>(variance);
        node->radius = radius;
        node->pivot = mean;

        delete[] mean_accumulator;
    }


    void computeDnaNodeStatistics(KMeansNodePtr node, int* indices,
                                       unsigned int indices_length)
    {
        const unsigned int histos_veclen = static_cast<unsigned int>(
                    veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR));

        unsigned long long variance = 0ull;
        unsigned int* histograms = new unsigned int[histos_veclen];
        memset(histograms, 0, sizeof(unsigned int)*histos_veclen);

        for (unsigned int i=0; i<indices_length; ++i) {
            variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(
                        distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_)));

            unsigned char* vec = (unsigned char*)dataset_[indices[i]];
            for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
                histograms[k +     ((vec[l])    & 0x03)]++;
                histograms[k + 4 + ((vec[l]>>2) & 0x03)]++;
                histograms[k + 8 + ((vec[l]>>4) & 0x03)]++;
                histograms[k +12 + ((vec[l]>>6) & 0x03)]++;
            }
        }

        CentersType* mean = new CentersType[veclen_];
        memoryCounter_ += int(veclen_*sizeof(CentersType));
        unsigned char* char_mean = (unsigned char*)mean;
        unsigned int* h = histograms;
        for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
            char_mean[l] = (h[k] > h[k+1] ? h[k+2] > h[k+3] ? h[k]   > h[k+2] ? 0x00 : 0x10
                                                            : h[k]   > h[k+3] ? 0x00 : 0x11
                                          : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10
                                                            : h[k+1] > h[k+3] ? 0x01 : 0x11)
                         | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00   : 0x1000
                                                            : h[k+4] > h[k+7] ? 0x00   : 0x1100
                                          : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000
                                                            : h[k+5] > h[k+7] ? 0x0100 : 0x1100)
                         | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00   : 0x100000
                                                            : h[k+8] >h[k+11] ? 0x00   : 0x110000
                                          : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000
                                                            : h[k+9] >h[k+11] ? 0x010000 : 0x110000)
                         | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00   : 0x10000000
                                                              : h[k+12] >h[k+15] ? 0x00   : 0x11000000
                                            : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000
                                                              : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000);
        }
        variance = static_cast<unsigned long long>(
                    0.5 + static_cast<double>(variance) / static_cast<double>(indices_length));
        variance -= static_cast<unsigned long long>(
                    ensureSquareDistance<Distance>(
                        distance_(mean, ZeroIterator<ElementType>(), veclen_)));

        DistanceType radius = 0;
        for (unsigned int i=0; i<indices_length; ++i) {
            DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
            if (tmp>radius) {
                radius = tmp;
            }
        }

        node->variance = static_cast<DistanceType>(variance);
        node->radius = radius;
        node->pivot = mean;

        delete[] histograms;
    }


    template<typename DistType>
    void computeNodeStatistics(KMeansNodePtr node, int* indices,
                               unsigned int indices_length,
                               const DistType* identifier)
    {
        (void)identifier;
        computeNodeStatistics(node, indices, indices_length);
    }

    void computeNodeStatistics(KMeansNodePtr node, int* indices,
                               unsigned int indices_length,
                               const cvflann::HammingLUT* identifier)
    {
        (void)identifier;
        computeBitfieldNodeStatistics(node, indices, indices_length);
    }

    void computeNodeStatistics(KMeansNodePtr node, int* indices,
                               unsigned int indices_length,
                               const cvflann::Hamming<unsigned char>* identifier)
    {
        (void)identifier;
        computeBitfieldNodeStatistics(node, indices, indices_length);
    }

    void computeNodeStatistics(KMeansNodePtr node, int* indices,
                               unsigned int indices_length,
                               const cvflann::Hamming2<unsigned char>* identifier)
    {
        (void)identifier;
        computeBitfieldNodeStatistics(node, indices, indices_length);
    }

    void computeNodeStatistics(KMeansNodePtr node, int* indices,
                               unsigned int indices_length,
                               const cvflann::DNAmmingLUT* identifier)
    {
        (void)identifier;
        computeDnaNodeStatistics(node, indices, indices_length);
    }

    void computeNodeStatistics(KMeansNodePtr node, int* indices,
                               unsigned int indices_length,
                               const cvflann::DNAmming2<unsigned char>* identifier)
    {
        (void)identifier;
        computeDnaNodeStatistics(node, indices, indices_length);
    }


    void refineClustering(int* indices, int indices_length, int branching, CentersType** centers,
                          std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
    {
        cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
        Matrix<double> dcenters(dcenters_buf.data(), branching, veclen_);

        bool converged = false;
        int iteration = 0;
        while (!converged && iteration<iterations_) {
            converged = true;
            iteration++;

            // compute the new cluster centers
            for (int i=0; i<branching; ++i) {
                memset(dcenters[i],0,sizeof(double)*veclen_);
                radiuses[i] = 0;
            }
            for (int i=0; i<indices_length; ++i) {
                ElementType* vec = dataset_[indices[i]];
                double* center = dcenters[belongs_to[i]];
                for (size_t k=0; k<veclen_; ++k) {
                    center[k] += vec[k];
                }
            }
            for (int i=0; i<branching; ++i) {
                int cnt = count[i];
                for (size_t k=0; k<veclen_; ++k) {
                    dcenters[i][k] /= cnt;
                }
            }

            std::vector<int> new_centroids(indices_length);
            std::vector<DistanceType> sq_dists(indices_length);

            // reassign points to clusters
            KMeansDistanceComputer<Matrix<double> > invoker(
                        distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists);
            parallel_for_(cv::Range(0, (int)indices_length), invoker);

            for (int i=0; i < (int)indices_length; ++i) {
                DistanceType sq_dist(sq_dists[i]);
                int new_centroid(new_centroids[i]);
                if (sq_dist > radiuses[new_centroid]) {
                    radiuses[new_centroid] = sq_dist;
                }
                if (new_centroid != belongs_to[i]) {
                    count[belongs_to[i]]--;
                    count[new_centroid]++;
                    belongs_to[i] = new_centroid;
                    converged = false;
                }
            }

            for (int i=0; i<branching; ++i) {
                // if one cluster converges to an empty cluster,
                // move an element into that cluster
                if (count[i]==0) {
                    int j = (i+1)%branching;
                    while (count[j]<=1) {
                        j = (j+1)%branching;
                    }

                    for (int k=0; k<indices_length; ++k) {
                        if (belongs_to[k]==j) {
                            // for cluster j, we move the furthest element from the center to the empty cluster i
                            if ( distance_(dataset_[indices[k]], dcenters[j], veclen_) == radiuses[j] ) {
                                belongs_to[k] = i;
                                count[j]--;
                                count[i]++;
                                break;
                            }
                        }
                    }
                    converged = false;
                }
            }
        }

       for (int i=0; i<branching; ++i) {
           centers[i] = new CentersType[veclen_];
           memoryCounter_ += (int)(veclen_*sizeof(CentersType));
           for (size_t k=0; k<veclen_; ++k) {
               centers[i][k] = (CentersType)dcenters[i][k];
           }
       }
    }


    void refineBitfieldClustering(int* indices, int indices_length, int branching, CentersType** centers,
                                  std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
    {
        for (int i=0; i<branching; ++i) {
            centers[i] = new CentersType[veclen_];
            memoryCounter_ += (int)(veclen_*sizeof(CentersType));
        }

        const unsigned int accumulator_veclen = static_cast<unsigned int>(
                                                veclen_*sizeof(ElementType)*BITS_PER_CHAR);
        cv::AutoBuffer<unsigned int> dcenters_buf(branching*accumulator_veclen);
        Matrix<unsigned int> dcenters(dcenters_buf.data(), branching, accumulator_veclen);

        bool converged = false;
        int iteration = 0;
        while (!converged && iteration<iterations_) {
            converged = true;
            iteration++;

            // compute the new cluster centers
            for (int i=0; i<branching; ++i) {
                memset(dcenters[i],0,sizeof(unsigned int)*accumulator_veclen);
                radiuses[i] = 0;
            }
            for (int i=0; i<indices_length; ++i) {
                unsigned char* vec = (unsigned char*)dataset_[indices[i]];
                unsigned int* dcenter = dcenters[belongs_to[i]];
                for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
                    dcenter[k]   += (vec[l])    & 0x01;
                    dcenter[k+1] += (vec[l]>>1) & 0x01;
                    dcenter[k+2] += (vec[l]>>2) & 0x01;
                    dcenter[k+3] += (vec[l]>>3) & 0x01;
                    dcenter[k+4] += (vec[l]>>4) & 0x01;
                    dcenter[k+5] += (vec[l]>>5) & 0x01;
                    dcenter[k+6] += (vec[l]>>6) & 0x01;
                    dcenter[k+7] += (vec[l]>>7) & 0x01;
                }
            }
            for (int i=0; i<branching; ++i) {
                double cnt = static_cast<double>(count[i]);
                unsigned int* dcenter = dcenters[i];
                unsigned char* charCenter = (unsigned char*)centers[i];
                for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
                    charCenter[l] = static_cast<unsigned char>(
                                      (((int)(0.5 + (double)(dcenter[k])   / cnt)))
                                    | (((int)(0.5 + (double)(dcenter[k+1]) / cnt))<<1)
                                    | (((int)(0.5 + (double)(dcenter[k+2]) / cnt))<<2)
                                    | (((int)(0.5 + (double)(dcenter[k+3]) / cnt))<<3)
                                    | (((int)(0.5 + (double)(dcenter[k+4]) / cnt))<<4)
                                    | (((int)(0.5 + (double)(dcenter[k+5]) / cnt))<<5)
                                    | (((int)(0.5 + (double)(dcenter[k+6]) / cnt))<<6)
                                    | (((int)(0.5 + (double)(dcenter[k+7]) / cnt))<<7));
                }
            }

            std::vector<int> new_centroids(indices_length);
            std::vector<DistanceType> dists(indices_length);

            // reassign points to clusters
            KMeansDistanceComputer<ElementType**> invoker(
                        distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists);
            parallel_for_(cv::Range(0, (int)indices_length), invoker);

            for (int i=0; i < indices_length; ++i) {
                DistanceType dist(dists[i]);
                int new_centroid(new_centroids[i]);
                if (dist > radiuses[new_centroid]) {
                    radiuses[new_centroid] = dist;
                }
                if (new_centroid != belongs_to[i]) {
                    count[belongs_to[i]]--;
                    count[new_centroid]++;
                    belongs_to[i] = new_centroid;
                    converged = false;
                }
            }

            for (int i=0; i<branching; ++i) {
                // if one cluster converges to an empty cluster,
                // move an element into that cluster
                if (count[i]==0) {
                    int j = (i+1)%branching;
                    while (count[j]<=1) {
                        j = (j+1)%branching;
                    }

                    for (int k=0; k<indices_length; ++k) {
                        if (belongs_to[k]==j) {
                            // for cluster j, we move the furthest element from the center to the empty cluster i
                            if ( distance_(dataset_[indices[k]], centers[j], veclen_) == radiuses[j] ) {
                                belongs_to[k] = i;
                                count[j]--;
                                count[i]++;
                                break;
                            }
                        }
                    }
                    converged = false;
                }
            }
        }
    }


    void refineDnaClustering(int* indices, int indices_length, int branching, CentersType** centers,
                                  std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
    {
        for (int i=0; i<branching; ++i) {
            centers[i] = new CentersType[veclen_];
            memoryCounter_ += (int)(veclen_*sizeof(CentersType));
        }

        const unsigned int histos_veclen = static_cast<unsigned int>(
                    veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR));
        cv::AutoBuffer<unsigned int> histos_buf(branching*histos_veclen);
        Matrix<unsigned int> histos(histos_buf.data(), branching, histos_veclen);

        bool converged = false;
        int iteration = 0;
        while (!converged && iteration<iterations_) {
            converged = true;
            iteration++;

            // compute the new cluster centers
            for (int i=0; i<branching; ++i) {
                memset(histos[i],0,sizeof(unsigned int)*histos_veclen);
                radiuses[i] = 0;
            }
            for (int i=0; i<indices_length; ++i) {
                unsigned char* vec = (unsigned char*)dataset_[indices[i]];
                unsigned int* h = histos[belongs_to[i]];
                for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
                    h[k +     ((vec[l])    & 0x03)]++;
                    h[k + 4 + ((vec[l]>>2) & 0x03)]++;
                    h[k + 8 + ((vec[l]>>4) & 0x03)]++;
                    h[k +12 + ((vec[l]>>6) & 0x03)]++;
                }
            }
            for (int i=0; i<branching; ++i) {
                unsigned int* h = histos[i];
                unsigned char* charCenter = (unsigned char*)centers[i];
                for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
                    charCenter[l]= (h[k] > h[k+1] ? h[k+2] > h[k+3] ? h[k]   > h[k+2] ? 0x00 : 0x10
                                                                    : h[k]   > h[k+3] ? 0x00 : 0x11
                                                  : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10
                                                                    : h[k+1] > h[k+3] ? 0x01 : 0x11)
                                 | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00   : 0x1000
                                                                    : h[k+4] > h[k+7] ? 0x00   : 0x1100
                                                  : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000
                                                                    : h[k+5] > h[k+7] ? 0x0100 : 0x1100)
                                 | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00   : 0x100000
                                                                    : h[k+8] >h[k+11] ? 0x00   : 0x110000
                                                  : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000
                                                                    : h[k+9] >h[k+11] ? 0x010000 : 0x110000)
                                 | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00   : 0x10000000
                                                                      : h[k+12] >h[k+15] ? 0x00   : 0x11000000
                                                    : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000
                                                                      : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000);
                }
            }

            std::vector<int> new_centroids(indices_length);
            std::vector<DistanceType> dists(indices_length);

            // reassign points to clusters
            KMeansDistanceComputer<ElementType**> invoker(
                        distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists);
            parallel_for_(cv::Range(0, (int)indices_length), invoker);

            for (int i=0; i < indices_length; ++i) {
                DistanceType dist(dists[i]);
                int new_centroid(new_centroids[i]);
                if (dist > radiuses[new_centroid]) {
                    radiuses[new_centroid] = dist;
                }
                if (new_centroid != belongs_to[i]) {
                    count[belongs_to[i]]--;
                    count[new_centroid]++;
                    belongs_to[i] = new_centroid;
                    converged = false;
                }
            }

            for (int i=0; i<branching; ++i) {
                // if one cluster converges to an empty cluster,
                // move an element into that cluster
                if (count[i]==0) {
                    int j = (i+1)%branching;
                    while (count[j]<=1) {
                        j = (j+1)%branching;
                    }

                    for (int k=0; k<indices_length; ++k) {
                        if (belongs_to[k]==j) {
                            // for cluster j, we move the furthest element from the center to the empty cluster i
                            if ( distance_(dataset_[indices[k]], centers[j], veclen_) == radiuses[j] ) {
                                belongs_to[k] = i;
                                count[j]--;
                                count[i]++;
                                break;
                            }
                        }
                    }
                    converged = false;
                }
            }
        }
    }


    void computeSubClustering(KMeansNodePtr node, int* indices, int indices_length,
                              int branching, int level, CentersType** centers,
                              std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
    {
        // compute kmeans clustering for each of the resulting clusters
        node->childs = pool_.allocate<KMeansNodePtr>(branching);
        int start = 0;
        int end = start;
        for (int c=0; c<branching; ++c) {
            int s = count[c];

            DistanceType variance = 0;
            DistanceType mean_radius =0;
            for (int i=0; i<indices_length; ++i) {
                if (belongs_to[i]==c) {
                    DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
                    variance += d;
                    mean_radius += static_cast<DistanceType>( sqrt(d) );
                    std::swap(indices[i],indices[end]);
                    std::swap(belongs_to[i],belongs_to[end]);
                    end++;
                }
            }
            variance /= s;
            mean_radius /= s;
            variance -= distance_(centers[c], ZeroIterator<ElementType>(), veclen_);

            node->childs[c] = pool_.allocate<KMeansNode>();
            std::memset(node->childs[c], 0, sizeof(KMeansNode));
            node->childs[c]->radius = radiuses[c];
            node->childs[c]->pivot = centers[c];
            node->childs[c]->variance = variance;
            node->childs[c]->mean_radius = mean_radius;
            computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
            start=end;
        }
    }


    void computeAnyBitfieldSubClustering(KMeansNodePtr node, int* indices, int indices_length,
                              int branching, int level, CentersType** centers,
                              std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
    {
        // compute kmeans clustering for each of the resulting clusters
        node->childs = pool_.allocate<KMeansNodePtr>(branching);
        int start = 0;
        int end = start;
        for (int c=0; c<branching; ++c) {
            int s = count[c];

            unsigned long long variance = 0ull;
            DistanceType mean_radius =0;
            for (int i=0; i<indices_length; ++i) {
                if (belongs_to[i]==c) {
                    DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
                    variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(d) );
                    mean_radius += ensureSimpleDistance<Distance>(d);
                    std::swap(indices[i],indices[end]);
                    std::swap(belongs_to[i],belongs_to[end]);
                    end++;
                }
            }
            mean_radius = static_cast<DistanceType>(
                        0.5f + static_cast<float>(mean_radius) / static_cast<float>(s));
            variance = static_cast<unsigned long long>(
                        0.5 + static_cast<double>(variance) / static_cast<double>(s));
            variance -= static_cast<unsigned long long>(
                        ensureSquareDistance<Distance>(
                            distance_(centers[c], ZeroIterator<ElementType>(), veclen_)));

            node->childs[c] = pool_.allocate<KMeansNode>();
            std::memset(node->childs[c], 0, sizeof(KMeansNode));
            node->childs[c]->radius = radiuses[c];
            node->childs[c]->pivot = centers[c];
            node->childs[c]->variance = static_cast<DistanceType>(variance);
            node->childs[c]->mean_radius = mean_radius;
            computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
            start=end;
        }
    }


    template<typename DistType>
    void refineAndSplitClustering(
            KMeansNodePtr node, int* indices, int indices_length, int branching,
            int level, CentersType** centers, std::vector<DistanceType>& radiuses,
            int* belongs_to, int* count, const DistType* identifier)
    {
        (void)identifier;
        refineClustering(indices, indices_length, branching, centers, radiuses, belongs_to, count);

        computeSubClustering(node, indices, indices_length, branching,
                             level, centers, radiuses, belongs_to, count);
    }


    /**
     * The methods responsible with doing the recursive hierarchical clustering on
     * binary vectors.
     * As some might have heard that KMeans on binary data doesn't make sense,
     * it's worth a little explanation why it actually fairly works. As
     * with the Hierarchical Clustering algortihm, we seed several centers for the
     * current node by picking some of its points. Then in a first pass each point
     * of the node is then related to its closest center. Now let's have a look at
     * the 5 central dimensions of the 9 following points:
     *
     * xxxxxx11100xxxxx (1)
     * xxxxxx11010xxxxx (2)
     * xxxxxx11001xxxxx (3)
     * xxxxxx10110xxxxx (4)
     * xxxxxx10101xxxxx (5)
     * xxxxxx10011xxxxx (6)
     * xxxxxx01110xxxxx (7)
     * xxxxxx01101xxxxx (8)
     * xxxxxx01011xxxxx (9)
     * sum   _____
     * of 1: 66555
     *
     * Even if the barycenter notion doesn't apply, we can set a center
     * xxxxxx11111xxxxx that will better fit the five dimensions we are focusing
     * on for these points.
     *
     * Note that convergence isn't ensured anymore. In practice, using Gonzales
     * as seeding algorithm should be fine for getting convergence ("iterations"
     * value can be set to -1). But with KMeans++ seeding you should definitely
     * set a maximum number of iterations (but make it higher than the "iterations"
     * default value of 11).
     *
     * Params:
     *     node = the node to cluster
     *     indices = indices of the points belonging to the current node
     *     indices_length = number of points in the current node
     *     branching = the branching factor to use in the clustering
     *     level = 0 for the root node, it increases with the subdivision levels
     *     centers = clusters centers to compute
     *     radiuses = radiuses of clusters
     *     belongs_to = LookUp Table returning, for a given indice id, the center id it belongs to
     *     count = array storing the number of indices for a given center id
     *     identifier = dummy pointer on an instance of Distance (use to branch correctly among templates)
     */
    void refineAndSplitClustering(
            KMeansNodePtr node, int* indices, int indices_length, int branching,
            int level, CentersType** centers, std::vector<DistanceType>& radiuses,
            int* belongs_to, int* count, const cvflann::HammingLUT* identifier)
    {
        (void)identifier;
        refineBitfieldClustering(
                    indices, indices_length, branching, centers, radiuses, belongs_to, count);

        computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
                                        level, centers, radiuses, belongs_to, count);
    }


    void refineAndSplitClustering(
            KMeansNodePtr node, int* indices, int indices_length, int branching,
            int level, CentersType** centers, std::vector<DistanceType>& radiuses,
            int* belongs_to, int* count, const cvflann::Hamming<unsigned char>* identifier)
    {
        (void)identifier;
        refineBitfieldClustering(
                    indices, indices_length, branching, centers, radiuses, belongs_to, count);

        computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
                                        level, centers, radiuses, belongs_to, count);
    }


    void refineAndSplitClustering(
            KMeansNodePtr node, int* indices, int indices_length, int branching,
            int level, CentersType** centers, std::vector<DistanceType>& radiuses,
            int* belongs_to, int* count, const cvflann::Hamming2<unsigned char>* identifier)
    {
        (void)identifier;
        refineBitfieldClustering(
                    indices, indices_length, branching, centers, radiuses, belongs_to, count);

        computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
                                        level, centers, radiuses, belongs_to, count);
    }


    void refineAndSplitClustering(
            KMeansNodePtr node, int* indices, int indices_length, int branching,
            int level, CentersType** centers, std::vector<DistanceType>& radiuses,
            int* belongs_to, int* count, const cvflann::DNAmmingLUT* identifier)
    {
        (void)identifier;
        refineDnaClustering(
                    indices, indices_length, branching, centers, radiuses, belongs_to, count);

        computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
                                        level, centers, radiuses, belongs_to, count);
    }


    void refineAndSplitClustering(
            KMeansNodePtr node, int* indices, int indices_length, int branching,
            int level, CentersType** centers, std::vector<DistanceType>& radiuses,
            int* belongs_to, int* count, const cvflann::DNAmming2<unsigned char>* identifier)
    {
        (void)identifier;
        refineDnaClustering(
                    indices, indices_length, branching, centers, radiuses, belongs_to, count);

        computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
                                        level, centers, radiuses, belongs_to, count);
    }


    /**
     * The method responsible with actually doing the recursive hierarchical
     * clustering
     *
     * Params:
     *     node = the node to cluster
     *     indices = indices of the points belonging to the current node
     *     branching = the branching factor to use in the clustering
     *
     * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
     */
    void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
    {
        node->size = indices_length;
        node->level = level;

        if (indices_length < branching) {
            node->indices = indices;
            std::sort(node->indices,node->indices+indices_length);
            node->childs = NULL;
            return;
        }

        cv::AutoBuffer<int> centers_idx_buf(branching);
        int* centers_idx = centers_idx_buf.data();
        int centers_length;
        (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);

        if (centers_length<branching) {
            node->indices = indices;
            std::sort(node->indices,node->indices+indices_length);
            node->childs = NULL;
            return;
        }


        std::vector<DistanceType> radiuses(branching);
        cv::AutoBuffer<int> count_buf(branching);
        int* count = count_buf.data();
        for (int i=0; i<branching; ++i) {
            radiuses[i] = 0;
            count[i] = 0;
        }

        //	assign points to clusters
        cv::AutoBuffer<int> belongs_to_buf(indices_length);
        int* belongs_to = belongs_to_buf.data();
        for (int i=0; i<indices_length; ++i) {
            DistanceType sq_dist = distance_(dataset_[indices[i]], dataset_[centers_idx[0]], veclen_);
            belongs_to[i] = 0;
            for (int j=1; j<branching; ++j) {
                DistanceType new_sq_dist = distance_(dataset_[indices[i]], dataset_[centers_idx[j]], veclen_);
                if (sq_dist>new_sq_dist) {
                    belongs_to[i] = j;
                    sq_dist = new_sq_dist;
                }
            }
            if (sq_dist>radiuses[belongs_to[i]]) {
                radiuses[belongs_to[i]] = sq_dist;
            }
            count[belongs_to[i]]++;
        }

        CentersType** centers = new CentersType*[branching];

        Distance* dummy = NULL;
        refineAndSplitClustering(node, indices, indices_length, branching, level,
                                 centers, radiuses, belongs_to, count, dummy);

        delete[] centers;
    }


    /**
     * Performs one descent in the hierarchical k-means tree. The branches not
     * visited are stored in a priority queue.
     *
     * Params:
     *      node = node to explore
     *      result = container for the k-nearest neighbors found
     *      vec = query points
     *      checks = how many points in the dataset have been checked so far
     *      maxChecks = maximum dataset points to checks
     */


    void findNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
                const cv::Ptr<Heap<BranchSt>>& heap)
    {
        // Ignore those clusters that are too far away
        {
            DistanceType bsq = distance_(vec, node->pivot, veclen_);
            DistanceType rsq = node->radius;
            DistanceType wsq = result.worstDist();

            if (isSquareDistance<Distance>())
            {
                DistanceType val = bsq-rsq-wsq;
                if ((val>0) && (val*val > 4*rsq*wsq))
                    return;
            }
            else
            {
                if (bsq-rsq > wsq)
                    return;
            }
        }

        if (node->childs==NULL) {
            if ((checks>=maxChecks) && result.full()) {
                return;
            }
            checks += node->size;
            for (int i=0; i<node->size; ++i) {
                int index = node->indices[i];
                DistanceType dist = distance_(dataset_[index], vec, veclen_);
                result.addPoint(dist, index);
            }
        }
        else {
            DistanceType* domain_distances = new DistanceType[branching_];
            int closest_center = exploreNodeBranches(node, vec, domain_distances, heap);
            delete[] domain_distances;
            findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap);
        }
    }

    /**
     * Helper function that computes the nearest childs of a node to a given query point.
     * Params:
     *     node = the node
     *     q = the query point
     *     distances = array with the distances to each child node.
     * Returns:
     */
    int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, const cv::Ptr<Heap<BranchSt>>& heap)
    {

        int best_index = 0;
        domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_);
        for (int i=1; i<branching_; ++i) {
            domain_distances[i] = distance_(q, node->childs[i]->pivot, veclen_);
            if (domain_distances[i]<domain_distances[best_index]) {
                best_index = i;
            }
        }

        //		float* best_center = node->childs[best_index]->pivot;
        for (int i=0; i<branching_; ++i) {
            if (i != best_index) {
                domain_distances[i] -= cvflann::round<DistanceType>(
                                        cb_index_*node->childs[i]->variance );

                //				float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q);
                //				if (domain_distances[i]<dist_to_border) {
                //					domain_distances[i] = dist_to_border;
                //				}
                heap->insert(BranchSt(node->childs[i],domain_distances[i]));
            }
        }

        return best_index;
    }


    /**
     * Function the performs exact nearest neighbor search by traversing the entire tree.
     */
    void findExactNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec)
    {
        // Ignore those clusters that are too far away
        {
            DistanceType bsq = distance_(vec, node->pivot, veclen_);
            DistanceType rsq = node->radius;
            DistanceType wsq = result.worstDist();

            if (isSquareDistance<Distance>())
            {
                DistanceType val = bsq-rsq-wsq;
                if ((val>0) && (val*val > 4*rsq*wsq))
                    return;
            }
            else
            {
                if (bsq-rsq > wsq)
                    return;
            }
        }


        if (node->childs==NULL) {
            for (int i=0; i<node->size; ++i) {
                int index = node->indices[i];
                DistanceType dist = distance_(dataset_[index], vec, veclen_);
                result.addPoint(dist, index);
            }
        }
        else {
            int* sort_indices = new int[branching_];

            getCenterOrdering(node, vec, sort_indices);

            for (int i=0; i<branching_; ++i) {
                findExactNN(node->childs[sort_indices[i]],result,vec);
            }

            delete[] sort_indices;
        }
    }


    /**
     * Helper function.
     *
     * I computes the order in which to traverse the child nodes of a particular node.
     */
    void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices)
    {
        DistanceType* domain_distances = new DistanceType[branching_];
        for (int i=0; i<branching_; ++i) {
            DistanceType dist = distance_(q, node->childs[i]->pivot, veclen_);

            int j=0;
            while (domain_distances[j]<dist && j<i)
                j++;
            for (int k=i; k>j; --k) {
                domain_distances[k] = domain_distances[k-1];
                sort_indices[k] = sort_indices[k-1];
            }
            domain_distances[j] = dist;
            sort_indices[j] = i;
        }
        delete[] domain_distances;
    }

    /**
     * Method that computes the squared distance from the query point q
     * from inside region with center c to the border between this
     * region and the region with center p
     */
    DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q)
    {
        DistanceType sum = 0;
        DistanceType sum2 = 0;

        for (int i=0; i<veclen_; ++i) {
            DistanceType t = c[i]-p[i];
            sum += t*(q[i]-(c[i]+p[i])/2);
            sum2 += t*t;
        }

        return sum*sum/sum2;
    }


    /**
     * Helper function the descends in the hierarchical k-means tree by splitting those clusters that minimize
     * the overall variance of the clustering.
     * Params:
     *     root = root node
     *     clusters = array with clusters centers (return value)
     *     varianceValue = variance of the clustering (return value)
     * Returns:
     */
    int getMinVarianceClusters(KMeansNodePtr root, KMeansNodePtr* clusters, int clusters_length, DistanceType& varianceValue)
    {
        int clusterCount = 1;
        clusters[0] = root;

        DistanceType meanVariance = root->variance*root->size;

        while (clusterCount<clusters_length) {
            DistanceType minVariance = (std::numeric_limits<DistanceType>::max)();
            int splitIndex = -1;

            for (int i=0; i<clusterCount; ++i) {
                if (clusters[i]->childs != NULL) {

                    DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size;

                    for (int j=0; j<branching_; ++j) {
                        variance += clusters[i]->childs[j]->variance*clusters[i]->childs[j]->size;
                    }
                    if (variance<minVariance) {
                        minVariance = variance;
                        splitIndex = i;
                    }
                }
            }

            if (splitIndex==-1) break;
            if ( (branching_+clusterCount-1) > clusters_length) break;

            meanVariance = minVariance;

            // split node
            KMeansNodePtr toSplit = clusters[splitIndex];
            clusters[splitIndex] = toSplit->childs[0];
            for (int i=1; i<branching_; ++i) {
                clusters[clusterCount++] = toSplit->childs[i];
            }
        }

        varianceValue = meanVariance/root->size;
        return clusterCount;
    }

private:
    /** The branching factor used in the hierarchical k-means clustering */
    int branching_;

    /** Number of kmeans trees (default is one) */
    int trees_;

    /** Maximum number of iterations to use when performing k-means clustering */
    int iterations_;

    /** Algorithm for choosing the cluster centers */
    flann_centers_init_t centers_init_;

    /**
     * Cluster border index. This is used in the tree search phase when determining
     * the closest cluster to explore next. A zero value takes into account only
     * the cluster centres, a value greater then zero also take into account the size
     * of the cluster.
     */
    float cb_index_;

    /**
     * The dataset used by this index
     */
    const Matrix<ElementType> dataset_;

    /** Index parameters */
    IndexParams index_params_;

    /**
     * Number of features in the dataset.
     */
    size_t size_;

    /**
     * Length of each feature.
     */
    size_t veclen_;

    /**
     * The root node in the tree.
     */
    KMeansNodePtr* root_;

    /**
     *  Array of indices to vectors in the dataset.
     */
    int** indices_;

    /**
     * The distance
     */
    Distance distance_;

    /**
     * Pooled memory allocator.
     */
    PooledAllocator pool_;

    /**
     * Memory occupied by the index.
     */
    int memoryCounter_;
};

}

//! @endcond

#endif //OPENCV_FLANN_KMEANS_INDEX_H_