PDFGaussian.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * @file PDFGaussian.cpp
  3. * @brief Normal Distribution / Gaussian PDF
  4. * @author Erik Rodner
  5. * @date 01/29/2008
  6. */
  7. #ifdef NOVISUAL
  8. #include <vislearning/nice_nonvis.h>
  9. #else
  10. #include <vislearning/nice.h>
  11. #endif
  12. #include <iostream>
  13. #include <sys/time.h>
  14. #include "vislearning/math/pdf/PDFGaussian.h"
  15. #include "vislearning/math/algebra/CholeskyRobustAuto.h"
  16. #include "core/vector/Algorithms.h"
  17. #include "core/basics/numerictools.h"
  18. using namespace OBJREC;
  19. using namespace std;
  20. using namespace NICE;
  21. PDFGaussian::PDFGaussian(int dimension) : mean(dimension)
  22. {
  23. constant = dimension * log(2 * M_PI);
  24. covariance.resize ( dimension, dimension );
  25. covariance.setIdentity();
  26. mean.resize ( dimension );
  27. mean.set(0.0);
  28. covCholesky = covariance;
  29. ldet = 0.0;
  30. }
  31. PDFGaussian::PDFGaussian(const NICE::Matrix & _covariance, const NICE::Vector & _mean)
  32. {
  33. covariance = _covariance;
  34. CholeskyRobustAuto cr ( true, regEPS, - std::numeric_limits<double>::max(), true );
  35. ldet = cr.robustChol ( covariance, covCholesky );
  36. mean = _mean;
  37. constant = mean.size() * log(2 * M_PI);
  38. constant = 0.0;
  39. ldet=0.0;
  40. }
  41. PDFGaussian::~PDFGaussian()
  42. {
  43. }
  44. double PDFGaussian::getNLogDensity(const NICE::Vector & x) const
  45. {
  46. // (x-mean)
  47. Vector diff ( x-mean );
  48. // covInvX = covariance^-1 (x-mean)
  49. Vector covInvX;
  50. choleskySolve ( covCholesky, diff, covInvX );
  51. double result = constant + ldet + diff.scalarProduct( covInvX );
  52. return result;
  53. }
  54. int PDFGaussian::getDimension() const
  55. {
  56. return mean.size();
  57. }
  58. NICE::Vector PDFGaussian::getMean()
  59. {
  60. return mean;
  61. }
  62. NICE::Matrix PDFGaussian::getCovariance()
  63. {
  64. if (covariance.rows() == 0 || covariance.cols() == 0)
  65. fthrow(Exception, "No covariance initialized, use other constructor !!");
  66. return covariance;
  67. }
  68. void PDFGaussian::sample(VVector & samples, int count) const
  69. {
  70. for (int i = 0 ; i < count ; i++)
  71. {
  72. NICE::Vector x(mean.size());
  73. NICE::Vector tmp(mean.size());
  74. tmp = NICE::VectorT<double>::GaussRandom(mean.size(), 0.0, 1.0);
  75. // cholesky decomposed covariance matrix * gauss vector
  76. x = mean + covCholesky * tmp;
  77. samples.push_back(x);
  78. }
  79. }