00001 #ifndef HMMLIB_H 00002 #define HMMLIB_H 00003 00004 #include <vector> 00005 #include <string> 00006 #include "Learn/WiimoteGR/TimeSlot.h" 00007 00008 using namespace std; 00009 00010 namespace WiimoteGR{ 00011 /* 00012 Hidden Markov Model, represents a gesture 00013 */ 00014 struct HMM{ 00015 string gestureName; 00016 //quantizer used to generate training sequence, corresponding to M,B 00017 string quantizerName; 00018 //represents the style of model(N,pi,A), 00019 // ex: "3 state circular", "3 state full connection", "5 state left to right", etc... 00020 string modelStyle; 00021 00022 bool trained; 00023 size_t N; // number of states 00024 size_t M; // number of observable symbols 00025 vector<double> A; // size = N*N, A[i*N+j] is the transition prob of going from state i at time t to state j at time t+1 00026 vector<double> B; // size = N*M, B[i*M+k] is the probability of observable symbol k in state i 00027 vector<double> pi; // size = N, pi[i] is the initial state distribution. 00028 00029 //constructor for Database::LoadHMM() 00030 HMM(const Quantizer& quantizer, const char* modelStyle, bool trained) 00031 :quantizerName(quantizer.name), modelStyle(modelStyle), trained(trained), M(quantizer.M) 00032 { /* nothing */ } 00033 00034 HMM(const char* gestureName, const Quantizer& quantizer, const char* modelStyle, bool trained, size_t N, 00035 double *const A_in, double *const B_in, double *const pi_in); 00036 00037 //for const HMM object 00038 const double& TranProb(size_t i, size_t j) const{ 00039 return A[i*N+j]; 00040 } 00041 const double& ObsProb(size_t j, size_t k) const{ 00042 return B[j*M+k]; 00043 } 00044 00045 //for nonconst HMM object 00046 double& TranProb(size_t i, size_t j){ 00047 return A[i*N+j]; 00048 } 00049 double& ObsProb(size_t j, size_t k){ 00050 return B[j*M+k]; 00051 } 00052 }; 00053 00054 struct TimeSlot; 00055 00056 class HMMLib{ 00057 public: 00058 void ShowHMM(HMM& hmm); 00059 const HMM& Recognize(const vector<HMM>& HMMVec, TimeSlot& seq); 00060 double SeqLogProb(const HMM& hmm, TimeSlot& seq, bool restart); 00061 int EstimateModel(HMM& hmm, TimeSlot& seq, size_t maxIteration = 10); 00062 int EstimateModelBySeqs(HMM& hmm, vector<TimeSlot>& seqs, size_t maxIteration = 10); 00063 private: 00064 bool CheckAndAllocateMemory(const HMM &hmm, vector<TimeSlot>& seqs); 00065 void Forward(const HMM& hmm, TimeSlot& seq, bool restart); 00066 void Backward(const HMM& hmm, TimeSlot& seq); 00067 void ComputeGamma(const HMM& hmm, TimeSlot& seq); 00068 void ComputeXi(const HMM& hmm, TimeSlot& seq); 00069 }; 00070 } 00071 #endif