openfabmap.cpp 26.7 KB
Newer Older
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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
// This file originates from the openFABMAP project:
// [http://code.google.com/p/openfabmap/]
//
// For published work which uses all or part of OpenFABMAP, please cite:
// [http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=6224843]
//
// Original Algorithm by Mark Cummins and Paul Newman:
// [http://ijr.sagepub.com/content/27/6/647.short]
// [http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=5613942]
// [http://ijr.sagepub.com/content/30/9/1100.abstract]
//
//                           License Agreement
//
// Copyright (C) 2012 Arren Glover [aj.glover@qut.edu.au] and
//                    Will Maddern [w.maddern@qut.edu.au], all rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "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 Intel Corporation or contributors 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.
//
//M*/

#include "precomp.hpp"
#include "opencv2/contrib/openfabmap.hpp"


/*
    Calculate the sum of two log likelihoods
*/
namespace cv {

namespace of2 {

static double logsumexp(double a, double b) {
64
    return a > b ? std::log(1 + std::exp(b - a)) + a : std::log(1 + std::exp(a - b)) + b;
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
FabMap::FabMap(const Mat& _clTree, double _PzGe,
        double _PzGNe, int _flags, int _numSamples) :
    clTree(_clTree), PzGe(_PzGe), PzGNe(_PzGNe), flags(
            _flags), numSamples(_numSamples) {

    CV_Assert(flags & MEAN_FIELD || flags & SAMPLED);
    CV_Assert(flags & NAIVE_BAYES || flags & CHOW_LIU);
    if (flags & NAIVE_BAYES) {
        PzGL = &FabMap::PzqGL;
    } else {
        PzGL = &FabMap::PzqGzpqL;
    }

    //check for a valid Chow-Liu tree
    CV_Assert(clTree.type() == CV_64FC1);
    cv::checkRange(clTree.row(0), false, NULL, 0, clTree.cols);
    cv::checkRange(clTree.row(1), false, NULL, DBL_MIN, 1);
    cv::checkRange(clTree.row(2), false, NULL, DBL_MIN, 1);
    cv::checkRange(clTree.row(3), false, NULL, DBL_MIN, 1);

    // TODO: Add default values for member variables
    Pnew = 0.9;
    sFactor = 0.99;
    mBias = 0.5;
}

FabMap::~FabMap() {
}

const std::vector<cv::Mat>& FabMap::getTrainingImgDescriptors() const {
    return trainingImgDescriptors;
}

const std::vector<cv::Mat>& FabMap::getTestImgDescriptors() const {
    return testImgDescriptors;
}

void FabMap::addTraining(const Mat& queryImgDescriptor) {
    CV_Assert(!queryImgDescriptor.empty());
106
    std::vector<Mat> queryImgDescriptors;
107 108 109 110 111 112
    for (int i = 0; i < queryImgDescriptor.rows; i++) {
        queryImgDescriptors.push_back(queryImgDescriptor.row(i));
    }
    addTraining(queryImgDescriptors);
}

113
void FabMap::addTraining(const std::vector<Mat>& queryImgDescriptors) {
114 115 116 117 118 119 120 121 122 123 124
    for (size_t i = 0; i < queryImgDescriptors.size(); i++) {
        CV_Assert(!queryImgDescriptors[i].empty());
        CV_Assert(queryImgDescriptors[i].rows == 1);
        CV_Assert(queryImgDescriptors[i].cols == clTree.cols);
        CV_Assert(queryImgDescriptors[i].type() == CV_32F);
        trainingImgDescriptors.push_back(queryImgDescriptors[i]);
    }
}

void FabMap::add(const cv::Mat& queryImgDescriptor) {
    CV_Assert(!queryImgDescriptor.empty());
125
    std::vector<Mat> queryImgDescriptors;
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    for (int i = 0; i < queryImgDescriptor.rows; i++) {
        queryImgDescriptors.push_back(queryImgDescriptor.row(i));
    }
    add(queryImgDescriptors);
}

void FabMap::add(const std::vector<cv::Mat>& queryImgDescriptors) {
    for (size_t i = 0; i < queryImgDescriptors.size(); i++) {
        CV_Assert(!queryImgDescriptors[i].empty());
        CV_Assert(queryImgDescriptors[i].rows == 1);
        CV_Assert(queryImgDescriptors[i].cols == clTree.cols);
        CV_Assert(queryImgDescriptors[i].type() == CV_32F);
        testImgDescriptors.push_back(queryImgDescriptors[i]);
    }
}

void FabMap::compare(const Mat& queryImgDescriptor,
143
            std::vector<IMatch>& matches, bool addQuery,
144 145
            const Mat& mask) {
    CV_Assert(!queryImgDescriptor.empty());
146
    std::vector<Mat> queryImgDescriptors;
147 148 149 150 151 152 153
    for (int i = 0; i < queryImgDescriptor.rows; i++) {
        queryImgDescriptors.push_back(queryImgDescriptor.row(i));
    }
    compare(queryImgDescriptors,matches,addQuery,mask);
}

void FabMap::compare(const Mat& queryImgDescriptor,
154
            const Mat& testImgDescriptor, std::vector<IMatch>& matches,
155 156
            const Mat& mask) {
    CV_Assert(!queryImgDescriptor.empty());
157
    std::vector<Mat> queryImgDescriptors;
158 159 160 161 162
    for (int i = 0; i < queryImgDescriptor.rows; i++) {
        queryImgDescriptors.push_back(queryImgDescriptor.row(i));
    }

    CV_Assert(!testImgDescriptor.empty());
163
    std::vector<Mat> _testImgDescriptors;
164 165 166 167 168 169 170 171
    for (int i = 0; i < testImgDescriptor.rows; i++) {
        _testImgDescriptors.push_back(testImgDescriptor.row(i));
    }
    compare(queryImgDescriptors,_testImgDescriptors,matches,mask);

}

void FabMap::compare(const Mat& queryImgDescriptor,
172 173
        const std::vector<Mat>& _testImgDescriptors,
        std::vector<IMatch>& matches, const Mat& mask) {
174
    CV_Assert(!queryImgDescriptor.empty());
175
    std::vector<Mat> queryImgDescriptors;
176 177 178 179 180 181
    for (int i = 0; i < queryImgDescriptor.rows; i++) {
        queryImgDescriptors.push_back(queryImgDescriptor.row(i));
    }
    compare(queryImgDescriptors,_testImgDescriptors,matches,mask);
}

182 183
void FabMap::compare(const std::vector<Mat>& queryImgDescriptors,
                     std::vector<IMatch>& matches, bool addQuery, const Mat& /*mask*/) {
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

    // TODO: add first query if empty (is this necessary)

    for (size_t i = 0; i < queryImgDescriptors.size(); i++) {
        CV_Assert(!queryImgDescriptors[i].empty());
        CV_Assert(queryImgDescriptors[i].rows == 1);
        CV_Assert(queryImgDescriptors[i].cols == clTree.cols);
        CV_Assert(queryImgDescriptors[i].type() == CV_32F);

        // TODO: add mask

        compareImgDescriptor(queryImgDescriptors[i],
                             (int)i, testImgDescriptors, matches);
        if (addQuery)
            add(queryImgDescriptors[i]);
    }
}

202 203 204
void FabMap::compare(const std::vector<Mat>& queryImgDescriptors,
        const std::vector<Mat>& _testImgDescriptors,
        std::vector<IMatch>& matches, const Mat& /*mask*/) {
205 206 207 208 209 210 211

    CV_Assert(!(flags & MOTION_MODEL));
    for (size_t i = 0; i < _testImgDescriptors.size(); i++) {
        CV_Assert(!_testImgDescriptors[i].empty());
        CV_Assert(_testImgDescriptors[i].rows == 1);
        CV_Assert(_testImgDescriptors[i].cols == clTree.cols);
        CV_Assert(_testImgDescriptors[i].type() == CV_32F);
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    }

    for (size_t i = 0; i < queryImgDescriptors.size(); i++) {
        CV_Assert(!queryImgDescriptors[i].empty());
        CV_Assert(queryImgDescriptors[i].rows == 1);
        CV_Assert(queryImgDescriptors[i].cols == clTree.cols);
        CV_Assert(queryImgDescriptors[i].type() == CV_32F);

        // TODO: add mask

        compareImgDescriptor(queryImgDescriptors[i],
                (int)i, _testImgDescriptors, matches);
    }
}

void FabMap::compareImgDescriptor(const Mat& queryImgDescriptor,
228 229
        int queryIndex, const std::vector<Mat>& _testImgDescriptors,
        std::vector<IMatch>& matches) {
230

231
    std::vector<IMatch> queryMatches;
232 233 234 235 236 237 238 239 240 241 242
    queryMatches.push_back(IMatch(queryIndex,-1,
        getNewPlaceLikelihood(queryImgDescriptor),0));
    getLikelihoods(queryImgDescriptor,_testImgDescriptors,queryMatches);
    normaliseDistribution(queryMatches);
    for (size_t j = 1; j < queryMatches.size(); j++) {
        queryMatches[j].queryIdx = queryIndex;
    }
    matches.insert(matches.end(), queryMatches.begin(), queryMatches.end());
}

void FabMap::getLikelihoods(const Mat& /*queryImgDescriptor*/,
243
        const std::vector<Mat>& /*testImgDescriptors*/, std::vector<IMatch>& /*matches*/) {
244 245 246 247 248 249 250 251 252 253 254

}

double FabMap::getNewPlaceLikelihood(const Mat& queryImgDescriptor) {
    if (flags & MEAN_FIELD) {
        double logP = 0;
        bool zq, zpq;
        if(flags & NAIVE_BAYES) {
            for (int q = 0; q < clTree.cols; q++) {
                zq = queryImgDescriptor.at<float>(0,q) > 0;

255
                logP += std::log(Pzq(q, false) * PzqGeq(zq, false) +
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
                        Pzq(q, true) * PzqGeq(zq, true));
            }
        } else {
            for (int q = 0; q < clTree.cols; q++) {
                zq = queryImgDescriptor.at<float>(0,q) > 0;
                zpq = queryImgDescriptor.at<float>(0,pq(q)) > 0;

                double alpha, beta, p;
                alpha = Pzq(q, zq) * PzqGeq(!zq, false) * PzqGzpq(q, !zq, zpq);
                beta = Pzq(q, !zq) * PzqGeq(zq, false) * PzqGzpq(q, zq, zpq);
                p = Pzq(q, false) * beta / (alpha + beta);

                alpha = Pzq(q, zq) * PzqGeq(!zq, true) * PzqGzpq(q, !zq, zpq);
                beta = Pzq(q, !zq) * PzqGeq(zq, true) * PzqGzpq(q, zq, zpq);
                p += Pzq(q, true) * beta / (alpha + beta);

272
                logP += std::log(p);
273 274 275 276 277 278 279 280 281
            }
        }
        return logP;
    }

    if (flags & SAMPLED) {
        CV_Assert(!trainingImgDescriptors.empty());
        CV_Assert(numSamples > 0);

282
        std::vector<Mat> sampledImgDescriptors;
283 284 285 286 287 288 289 290 291

        // TODO: this method can result in the same sample being added
        // multiple times. Is this desired?

        for (int i = 0; i < numSamples; i++) {
            int index = rand() % trainingImgDescriptors.size();
            sampledImgDescriptors.push_back(trainingImgDescriptors[index]);
        }

292
        std::vector<IMatch> matches;
293 294 295 296 297 298 299 300
        getLikelihoods(queryImgDescriptor,sampledImgDescriptors,matches);

        double averageLogLikelihood = -DBL_MAX + matches.front().likelihood + 1;
        for (int i = 0; i < numSamples; i++) {
            averageLogLikelihood =
                logsumexp(matches[i].likelihood, averageLogLikelihood);
        }

301
        return averageLogLikelihood - std::log((double)numSamples);
302 303 304 305
    }
    return 0;
}

306
void FabMap::normaliseDistribution(std::vector<IMatch>& matches) {
307 308 309 310
    CV_Assert(!matches.empty());

    if (flags & MOTION_MODEL) {

311
        matches[0].match = matches[0].likelihood + std::log(Pnew);
312 313 314

        if (priorMatches.size() > 2) {
            matches[1].match = matches[1].likelihood;
315
            matches[1].match += std::log(
316 317 318 319 320
                (2 * (1-mBias) * priorMatches[1].match +
                priorMatches[1].match +
                2 * mBias * priorMatches[2].match) / 3);
            for (size_t i = 2; i < priorMatches.size()-1; i++) {
                matches[i].match = matches[i].likelihood;
321
                matches[i].match += std::log(
322 323 324 325 326 327
                    (2 * (1-mBias) * priorMatches[i-1].match +
                    priorMatches[i].match +
                    2 * mBias * priorMatches[i+1].match)/3);
            }
            matches[priorMatches.size()-1].match =
                matches[priorMatches.size()-1].likelihood;
328
            matches[priorMatches.size()-1].match += std::log(
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
                (2 * (1-mBias) * priorMatches[priorMatches.size()-2].match +
                priorMatches[priorMatches.size()-1].match +
                2 * mBias * priorMatches[priorMatches.size()-1].match)/3);

            for(size_t i = priorMatches.size(); i < matches.size(); i++) {
                matches[i].match = matches[i].likelihood;
            }
        } else {
            for(size_t i = 1; i < matches.size(); i++) {
                matches[i].match = matches[i].likelihood;
            }
        }

        double logsum = -DBL_MAX + matches.front().match + 1;

        //calculate the normalising constant
        for (size_t i = 0; i < matches.size(); i++) {
            logsum = logsumexp(logsum, matches[i].match);
        }

        //normalise
        for (size_t i = 0; i < matches.size(); i++) {
351
            matches[i].match = std::exp(matches[i].match - logsum);
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
        }

        //smooth final probabilities
        for (size_t i = 0; i < matches.size(); i++) {
            matches[i].match = sFactor*matches[i].match +
            (1 - sFactor)/matches.size();
        }

        //update our location priors
        priorMatches = matches;

    } else {

        double logsum = -DBL_MAX + matches.front().likelihood + 1;

        for (size_t i = 0; i < matches.size(); i++) {
            logsum = logsumexp(logsum, matches[i].likelihood);
        }
        for (size_t i = 0; i < matches.size(); i++) {
371
            matches[i].match = std::exp(matches[i].likelihood - logsum);
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
        }
        for (size_t i = 0; i < matches.size(); i++) {
            matches[i].match = sFactor*matches[i].match +
            (1 - sFactor)/matches.size();
        }
    }
}

int FabMap::pq(int q) {
    return (int)clTree.at<double>(0,q);
}

double FabMap::Pzq(int q, bool zq) {
    return (zq) ? clTree.at<double>(1,q) : 1 - clTree.at<double>(1,q);
}

double FabMap::PzqGzpq(int q, bool zq, bool zpq) {
    if (zpq) {
        return (zq) ? clTree.at<double>(2,q) : 1 - clTree.at<double>(2,q);
    } else {
        return (zq) ? clTree.at<double>(3,q) : 1 - clTree.at<double>(3,q);
    }
}

double FabMap::PzqGeq(bool zq, bool eq) {
    if (eq) {
        return (zq) ? PzGe : 1 - PzGe;
    } else {
        return (zq) ? PzGNe : 1 - PzGNe;
    }
}

double FabMap::PeqGL(int q, bool Lzq, bool eq) {
    double alpha, beta;
    alpha = PzqGeq(Lzq, true) * Pzq(q, true);
    beta = PzqGeq(Lzq, false) * Pzq(q, false);

    if (eq) {
        return alpha / (alpha + beta);
    } else {
        return 1 - (alpha / (alpha + beta));
    }
}

double FabMap::PzqGL(int q, bool zq, bool /*zpq*/, bool Lzq) {
    return PeqGL(q, Lzq, false) * PzqGeq(zq, false) +
        PeqGL(q, Lzq, true) * PzqGeq(zq, true);
}


double FabMap::PzqGzpqL(int q, bool zq, bool zpq, bool Lzq) {
    double p;
    double alpha, beta;

    alpha = Pzq(q,  zq) * PzqGeq(!zq, false) * PzqGzpq(q, !zq, zpq);
    beta  = Pzq(q, !zq) * PzqGeq( zq, false) * PzqGzpq(q,  zq, zpq);
    p = PeqGL(q, Lzq, false) * beta / (alpha + beta);

    alpha = Pzq(q,  zq) * PzqGeq(!zq, true) * PzqGzpq(q, !zq, zpq);
    beta  = Pzq(q, !zq) * PzqGeq( zq, true) * PzqGzpq(q,  zq, zpq);
    p += PeqGL(q, Lzq, true) * beta / (alpha + beta);

    return p;
}


FabMap1::FabMap1(const Mat& _clTree, double _PzGe, double _PzGNe, int _flags,
        int _numSamples) : FabMap(_clTree, _PzGe, _PzGNe, _flags,
                _numSamples) {
}

FabMap1::~FabMap1() {
}

void FabMap1::getLikelihoods(const Mat& queryImgDescriptor,
447
        const std::vector<Mat>& testImageDescriptors, std::vector<IMatch>& matches) {
448

449
    for (size_t i = 0; i < testImageDescriptors.size(); i++) {
450 451 452 453 454 455
        bool zq, zpq, Lzq;
        double logP = 0;
        for (int q = 0; q < clTree.cols; q++) {

            zq = queryImgDescriptor.at<float>(0,q) > 0;
            zpq = queryImgDescriptor.at<float>(0,pq(q)) > 0;
456
            Lzq = testImageDescriptors[i].at<float>(0,q) > 0;
457

458
            logP += std::log((this->*PzGL)(q, zq, zpq, Lzq));
459 460 461 462 463 464 465 466 467 468 469

        }
        matches.push_back(IMatch(0,(int)i,logP,0));
    }
}

FabMapLUT::FabMapLUT(const Mat& _clTree, double _PzGe, double _PzGNe,
        int _flags, int _numSamples, int _precision) :
FabMap(_clTree, _PzGe, _PzGNe, _flags, _numSamples), precision(_precision) {

    int nWords = clTree.cols;
470
    double precFactor = (double)std::pow(10.0, precision);
471 472 473 474 475 476 477 478 479 480

    table = new int[nWords][8];

    for (int q = 0; q < nWords; q++) {
        for (unsigned char i = 0; i < 8; i++) {

            bool Lzq = (bool) ((i >> 2) & 0x01);
            bool zq = (bool) ((i >> 1) & 0x01);
            bool zpq = (bool) (i & 1);

481
            table[q][i] = -(int)(std::log((this->*PzGL)(q, zq, zpq, Lzq))
482 483 484 485 486 487 488 489 490 491
                    * precFactor);
        }
    }
}

FabMapLUT::~FabMapLUT() {
    delete[] table;
}

void FabMapLUT::getLikelihoods(const Mat& queryImgDescriptor,
492
        const std::vector<Mat>& testImageDescriptors, std::vector<IMatch>& matches) {
493

494
    double precFactor = (double)std::pow(10.0, -precision);
495

496
    for (size_t i = 0; i < testImageDescriptors.size(); i++) {
497 498 499 500
        unsigned long long int logP = 0;
        for (int q = 0; q < clTree.cols; q++) {
            logP += table[q][(queryImgDescriptor.at<float>(0,pq(q)) > 0) +
            ((queryImgDescriptor.at<float>(0, q) > 0) << 1) +
501
            ((testImageDescriptors[i].at<float>(0,q) > 0) << 2)];
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
        }
        matches.push_back(IMatch(0,(int)i,-precFactor*(double)logP,0));
    }
}

FabMapFBO::FabMapFBO(const Mat& _clTree, double _PzGe, double _PzGNe,
        int _flags, int _numSamples, double _rejectionThreshold,
        double _PsGd, int _bisectionStart, int _bisectionIts) :
FabMap(_clTree, _PzGe, _PzGNe, _flags, _numSamples), PsGd(_PsGd),
    rejectionThreshold(_rejectionThreshold), bisectionStart(_bisectionStart),
        bisectionIts(_bisectionIts) {
}


FabMapFBO::~FabMapFBO() {
}

void FabMapFBO::getLikelihoods(const Mat& queryImgDescriptor,
520
        const std::vector<Mat>& testImageDescriptors, std::vector<IMatch>& matches) {
521 522 523 524

    std::multiset<WordStats> wordData;
    setWordStatistics(queryImgDescriptor, wordData);

525 526
    std::vector<int> matchIndices;
    std::vector<IMatch> queryMatches;
527

528
    for (size_t i = 0; i < testImageDescriptors.size(); i++) {
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        queryMatches.push_back(IMatch(0,(int)i,0,0));
        matchIndices.push_back((int)i);
    }

    double currBest  = -DBL_MAX;
    double bailedOut = DBL_MAX;

    for (std::multiset<WordStats>::iterator wordIter = wordData.begin();
            wordIter != wordData.end(); wordIter++) {
        bool zq = queryImgDescriptor.at<float>(0,wordIter->q) > 0;
        bool zpq = queryImgDescriptor.at<float>(0,pq(wordIter->q)) > 0;

        currBest = -DBL_MAX;

        for (size_t i = 0; i < matchIndices.size(); i++) {
            bool Lzq =
545
                testImageDescriptors[matchIndices[i]].at<float>(0,wordIter->q) > 0;
546
            queryMatches[matchIndices[i]].likelihood +=
547
                std::log((this->*PzGL)(wordIter->q,zq,zpq,Lzq));
548 549 550 551 552 553 554 555
            currBest =
                std::max(queryMatches[matchIndices[i]].likelihood, currBest);
        }

        if (matchIndices.size() == 1)
            continue;

        double delta = std::max(limitbisection(wordIter->V, wordIter->M),
556
            -std::log(rejectionThreshold));
557

558
        std::vector<int>::iterator matchIter = matchIndices.begin();
559 560 561 562 563 564 565 566 567 568 569 570
        while (matchIter != matchIndices.end()) {
            if (currBest - queryMatches[*matchIter].likelihood > delta) {
                queryMatches[*matchIter].likelihood = bailedOut;
                matchIter = matchIndices.erase(matchIter);
            } else {
                matchIter++;
            }
        }
    }

    for (size_t i = 0; i < queryMatches.size(); i++) {
        if (queryMatches[i].likelihood == bailedOut) {
571
            queryMatches[i].likelihood = currBest + std::log(rejectionThreshold);
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
        }
    }
    matches.insert(matches.end(), queryMatches.begin(), queryMatches.end());

}

void FabMapFBO::setWordStatistics(const Mat& queryImgDescriptor,
        std::multiset<WordStats>& wordData) {
    //words are sorted according to information = -ln(P(zq|zpq))
    //in non-log format this is lowest probability first
    for (int q = 0; q < clTree.cols; q++) {
        wordData.insert(WordStats(q,PzqGzpq(q,
                queryImgDescriptor.at<float>(0,q) > 0,
                queryImgDescriptor.at<float>(0,pq(q)) > 0)));
    }

    double d = 0, V = 0, M = 0;
    bool zq, zpq;

    for (std::multiset<WordStats>::reverse_iterator wordIter =
            wordData.rbegin();
            wordIter != wordData.rend(); wordIter++) {

        zq = queryImgDescriptor.at<float>(0,wordIter->q) > 0;
        zpq = queryImgDescriptor.at<float>(0,pq(wordIter->q)) > 0;

598 599
        d = std::log((this->*PzGL)(wordIter->q, zq, zpq, true)) -
            std::log((this->*PzGL)(wordIter->q, zq, zpq, false));
600

601 602
        V += std::pow(d, 2.0) * 2 *
            (Pzq(wordIter->q, true) - std::pow(Pzq(wordIter->q, true), 2.0));
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
        M = std::max(M, fabs(d));

        wordIter->V = V;
        wordIter->M = M;
    }
}

double FabMapFBO::limitbisection(double v, double m) {
    double midpoint, left_val, mid_val;
    double left = 0, right = bisectionStart;

    left_val = bennettInequality(v, m, left) - PsGd;

    for(int i = 0; i < bisectionIts; i++) {

        midpoint = (left + right)*0.5;
        mid_val = bennettInequality(v, m, midpoint)- PsGd;

        if(left_val * mid_val > 0) {
            left = midpoint;
            left_val = mid_val;
        } else {
            right = midpoint;
        }
    }

    return (right + left) * 0.5;
}

double FabMapFBO::bennettInequality(double v, double m, double delta) {
    double DMonV = delta * m / v;
634 635
    double f_delta = std::log(DMonV + std::sqrt(std::pow(DMonV, 2.0) + 1));
    return std::exp((v / std::pow(m, 2.0))*(cosh(f_delta) - 1 - DMonV * f_delta));
636 637 638 639 640 641 642 643 644 645 646 647 648 649
}

bool FabMapFBO::compInfo(const WordStats& first, const WordStats& second) {
    return first.info < second.info;
}

FabMap2::FabMap2(const Mat& _clTree, double _PzGe, double _PzGNe,
        int _flags) :
FabMap(_clTree, _PzGe, _PzGNe, _flags) {
    CV_Assert(flags & SAMPLED);

    children.resize(clTree.cols);

    for (int q = 0; q < clTree.cols; q++) {
650
        d1.push_back(std::log((this->*PzGL)(q, false, false, true) /
651
                (this->*PzGL)(q, false, false, false)));
652
        d2.push_back(std::log((this->*PzGL)(q, false, true, true) /
653
                (this->*PzGL)(q, false, true, false)) - d1[q]);
654
        d3.push_back(std::log((this->*PzGL)(q, true, false, true) /
655
                (this->*PzGL)(q, true, false, false))- d1[q]);
656
        d4.push_back(std::log((this->*PzGL)(q, true, true, true) /
657 658 659 660 661 662 663 664 665 666
                (this->*PzGL)(q, true, true, false))- d1[q]);
        children[pq(q)].push_back(q);
    }

}

FabMap2::~FabMap2() {
}


667
void FabMap2::addTraining(const std::vector<Mat>& queryImgDescriptors) {
668 669 670 671 672 673 674 675 676 677 678
    for (size_t i = 0; i < queryImgDescriptors.size(); i++) {
        CV_Assert(!queryImgDescriptors[i].empty());
        CV_Assert(queryImgDescriptors[i].rows == 1);
        CV_Assert(queryImgDescriptors[i].cols == clTree.cols);
        CV_Assert(queryImgDescriptors[i].type() == CV_32F);
        trainingImgDescriptors.push_back(queryImgDescriptors[i]);
        addToIndex(queryImgDescriptors[i], trainingDefaults, trainingInvertedMap);
    }
}


679
void FabMap2::add(const std::vector<Mat>& queryImgDescriptors) {
680 681 682 683 684 685 686 687 688 689 690
    for (size_t i = 0; i < queryImgDescriptors.size(); i++) {
        CV_Assert(!queryImgDescriptors[i].empty());
        CV_Assert(queryImgDescriptors[i].rows == 1);
        CV_Assert(queryImgDescriptors[i].cols == clTree.cols);
        CV_Assert(queryImgDescriptors[i].type() == CV_32F);
        testImgDescriptors.push_back(queryImgDescriptors[i]);
        addToIndex(queryImgDescriptors[i], testDefaults, testInvertedMap);
    }
}

void FabMap2::getLikelihoods(const Mat& queryImgDescriptor,
691
        const std::vector<Mat>& testImageDescriptors, std::vector<IMatch>& matches) {
692

693
    if (&testImageDescriptors == &testImgDescriptors) {
694 695 696 697
        getIndexLikelihoods(queryImgDescriptor, testDefaults, testInvertedMap,
            matches);
    } else {
        CV_Assert(!(flags & MOTION_MODEL));
698 699
        std::vector<double> defaults;
        std::map<int, std::vector<int> > invertedMap;
700 701
        for (size_t i = 0; i < testImageDescriptors.size(); i++) {
            addToIndex(testImageDescriptors[i],defaults,invertedMap);
702 703 704 705 706 707 708 709 710
        }
        getIndexLikelihoods(queryImgDescriptor, defaults, invertedMap, matches);
    }
}

double FabMap2::getNewPlaceLikelihood(const Mat& queryImgDescriptor) {

    CV_Assert(!trainingImgDescriptors.empty());

711
    std::vector<IMatch> matches;
712 713 714 715 716 717 718 719 720
    getIndexLikelihoods(queryImgDescriptor, trainingDefaults,
            trainingInvertedMap, matches);

    double averageLogLikelihood = -DBL_MAX + matches.front().likelihood + 1;
    for (size_t i = 0; i < matches.size(); i++) {
        averageLogLikelihood =
            logsumexp(matches[i].likelihood, averageLogLikelihood);
    }

721
    return averageLogLikelihood - std::log((double)trainingDefaults.size());
722 723 724 725

}

void FabMap2::addToIndex(const Mat& queryImgDescriptor,
726 727
        std::vector<double>& defaults,
        std::map<int, std::vector<int> >& invertedMap) {
728 729 730 731 732 733 734 735 736 737 738
    defaults.push_back(0);
    for (int q = 0; q < clTree.cols; q++) {
        if (queryImgDescriptor.at<float>(0,q) > 0) {
            defaults.back() += d1[q];
            invertedMap[q].push_back((int)defaults.size()-1);
        }
    }
}

void FabMap2::getIndexLikelihoods(const Mat& queryImgDescriptor,
        std::vector<double>& defaults,
739
        std::map<int, std::vector<int> >& invertedMap,
740 741
        std::vector<IMatch>& matches) {

742
    std::vector<int>::iterator LwithI, child;
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

    std::vector<double> likelihoods = defaults;

    for (int q = 0; q < clTree.cols; q++) {
        if (queryImgDescriptor.at<float>(0,q) > 0) {
            for (LwithI = invertedMap[q].begin();
                LwithI != invertedMap[q].end(); LwithI++) {

                if (queryImgDescriptor.at<float>(0,pq(q)) > 0) {
                    likelihoods[*LwithI] += d4[q];
                } else {
                    likelihoods[*LwithI] += d3[q];
                }
            }
            for (child = children[q].begin(); child != children[q].end();
                child++) {

                if (queryImgDescriptor.at<float>(0,*child) == 0) {
                    for (LwithI = invertedMap[*child].begin();
                        LwithI != invertedMap[*child].end(); LwithI++) {

                        likelihoods[*LwithI] += d2[*child];
                    }
                }
            }
        }
    }

    for (size_t i = 0; i < likelihoods.size(); i++) {
        matches.push_back(IMatch(0,(int)i,likelihoods[i],0));
    }
}

}

}