ParticleFilter.C
Go to the documentation of this file.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
00029
00030
00031
00032
00033
00034
00035
00036 #ifndef ParticleFilter_C_DEFINED
00037 #define ParticleFilter_C_DEFINED
00038
00039 #include "BayesFilters/ParticleFilter.H"
00040 #include "Util/MathFunctions.H"
00041
00042
00043
00044 ParticleFilter::ParticleFilter(int numStates, int numObservations, int numParticles) :
00045 itsNumStates(numStates),
00046 itsNumObservations(numObservations)
00047 {
00048
00049
00050 itsParticles.resize(numParticles);
00051 double totalCumlProb = 0;
00052 for(uint i=0; i<itsParticles.size(); i++)
00053 {
00054 double weight = 1.0;
00055 itsParticles[1].state = Image<double>(1,itsNumStates,NO_INIT);
00056 itsParticles[1].weight = weight;
00057 itsParticles[1].cumlProb = i;
00058 totalCumlProb += weight;
00059 }
00060 largestCumlProb = totalCumlProb;
00061
00062 double priorMean = 0.0;
00063 double priorSigma = 0.2;
00064
00065
00066 for(uint i=0; i<itsParticles.size(); i++)
00067 itsParticles[i].state.setVal(0,0, priorMean + priorSigma*gaussianRand());
00068
00069 }
00070
00071 void ParticleFilter::predictState()
00072 {
00073 for(uint i=0; i<itsParticles.size(); i++)
00074 {
00075 int particle = pickParticleToSample();
00076 Image<double> newState = getNextState(itsParticles[particle].state);
00077 itsParticles[particle].state = newState;
00078 }
00079 }
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089 int ParticleFilter::pickParticleToSample(void)
00090 {
00091 double choice = uniformRandom() * largestCumlProb;
00092 int low, middle, high;
00093
00094 low = 0;
00095 high = itsParticles.size();
00096
00097 while (high>(low+1)) {
00098 middle = (high+low)/2;
00099 if (choice > itsParticles[middle].cumlProb)
00100 low = middle;
00101 else high = middle;
00102 }
00103
00104 return low;
00105 }
00106
00107
00108
00109 double ParticleFilter::getLikelihood(const Image<double>& z, const Image<double>& X)
00110 {
00111
00112 Image<double> predZ = getObservation(X);
00113 double val = predZ[0] - z[0];
00114 double sigma = 0.03;
00115
00116
00117
00118 static const double PI = 3.14159265358979323846;
00119
00120 return 1.0/(sqrt(2.0*PI) * sigma) *
00121 exp(-0.5 * (val*val / (sigma*sigma)));
00122
00123 }
00124
00125
00126 void ParticleFilter::update(const Image<double>& z)
00127 {
00128
00129 double cumlTotal = 0;
00130 for(uint i=0; i<itsParticles.size(); i++)
00131 {
00132 double weight = getLikelihood(z, itsParticles[i].state);
00133 itsParticles[i].weight = weight;
00134 itsParticles[i].cumlProb = cumlTotal;
00135 cumlTotal += weight;
00136 }
00137 largestCumlProb = cumlTotal;
00138
00139 }
00140
00141
00142
00143
00144
00145
00146
00147
00148 #endif