00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028 #ifndef CRejectionSamplingCapable_H
00029 #define CRejectionSamplingCapable_H
00030
00031 #include <mrpt/utils/utils_defs.h>
00032 #include <mrpt/bayes/CProbabilityParticle.h>
00033 #include <mrpt/random.h>
00034
00035 namespace mrpt
00036 {
00037 namespace bayes
00038 {
00044 template <class TStateSpace>
00045 class CRejectionSamplingCapable
00046 {
00047 public:
00048 typedef CProbabilityParticle<TStateSpace> TParticle;
00049
00052 virtual ~CRejectionSamplingCapable()
00053 {
00054 }
00055
00063 void rejectionSampling(
00064 size_t desiredSamples,
00065 std::vector<TParticle> &outSamples,
00066 size_t timeoutTrials = 1000)
00067 {
00068 MRPT_TRY_START;
00069
00070 TStateSpace x;
00071 typename std::vector<TParticle>::iterator it;
00072
00073
00074 if ( outSamples.size() != desiredSamples )
00075 {
00076
00077 for (it = outSamples.begin();it!=outSamples.end();it++)
00078 delete (it->d);
00079 outSamples.clear();
00080
00081
00082 outSamples.resize( desiredSamples );
00083 for (it = outSamples.begin();it!=outSamples.end();it++)
00084 it->d = new TStateSpace;
00085 }
00086
00087
00088 double acceptanceProb;
00089 for (it = outSamples.begin();it!=outSamples.end();it++)
00090 {
00091 size_t timeoutCount = 0;
00092 double bestLik = -1e250;
00093 TStateSpace bestVal;
00094 do
00095 {
00096 RS_drawFromProposal( *it->d );
00097 acceptanceProb = RS_observationLikelihood( *it->d );
00098 ASSERT_(acceptanceProb>=0 && acceptanceProb<=1);
00099 if (acceptanceProb>bestLik)
00100 {
00101 bestLik = acceptanceProb;
00102 bestVal = *it->d;
00103 }
00104 } while ( acceptanceProb < mrpt::random::RandomUni(0.0,0.999) &&
00105 (++timeoutCount)<timeoutTrials );
00106
00107
00108 if (timeoutCount>=timeoutTrials)
00109 {
00110 it->log_w = log(bestLik);
00111 *it->d = bestVal;
00112 }
00113 else
00114 {
00115 it->log_w = 0;
00116 }
00117 }
00118
00119 MRPT_TRY_END;
00120 }
00121
00122 protected:
00125 virtual void RS_drawFromProposal( TStateSpace &outSample ) = 0;
00126
00129 virtual double RS_observationLikelihood( const TStateSpace &x) = 0;
00130
00131 };
00132
00133 }
00134 }
00135
00136 #endif