PDFGaussian.cpp 2.0 KB

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