Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. // [[Rcpp::export]]
  2. NumericVector KF_fast(NumericMatrix y, NumericMatrix Z,NumericMatrix Ht, NumericMatrix Qtt,int m, int p, int t, NumericVector B0, NumericMatrix V0) {
  3.   static Rcpp::Function asVector("as.vector");
  4.  
  5.   //Define everything calculated down there
  6.   arma::vec  bp = Rcpp::as<arma::vec>(B0);
  7.   arma::mat Vp = Rcpp::as<arma::mat>(V0);
  8.   arma::mat Qt =Rcpp::as<arma::mat>(Qtt);
  9.   arma::mat bt(t,m);
  10.   arma::mat Vt(pow(m,2),t);
  11.   arma::mat R(p,m);
  12.   arma::mat H(t*m,p);
  13.   arma::mat cfe(p,1);
  14.   arma::mat yt(p,1);
  15.   arma::mat f(p,p);
  16.   arma::mat inv_f(p,p);
  17.   arma::mat btt(m,1);
  18.   arma::mat Vtt(m,m);
  19.  
  20.   arma::cube test(m,m,t);
  21.  
  22.   double log_lik = 0;
  23.   for (int i=1;i<(t+1);++i){
  24.     arma::mat Qt =diag(Qtt(i-1,_));
  25.     //int i=t;
  26.     R= Ht(Range((i-1)*p,(i*p)-1),_);
  27.     H = Z(Range((i-1)*p,(i*p)-1),_);
  28.     yt=y(_,i-1);
  29.     cfe= yt-H*bp;
  30.     f = H*Vp*trans(H)+R;
  31.     inv_f =  inv(f);
  32.     btt = bp+Vp*trans(H)*inv_f*cfe; // bp=btt-1
  33.     //btt = bp+Vp*inv_f*cfe;
  34.     Vtt = Vp-Vp*trans(H)*inv_f*H*Vp;
  35.     //Vtt = Vp-Vp*trans(H)*inv_f*H*Vp;
  36.     //log_lik=log_lik+
  37.     if ((i-1)<t){
  38.       bp=btt;
  39.       Vp=Vtt+Qt;
  40.     }
  41.     bt.row(i-1) = trans(btt);
  42.     test.slice(i-1)=Vtt;
  43.   }
  44.   //draw S(T|T) ~ N(S(T|T),P(T|T))
  45.   arma::mat bdraw(t,m);
  46.  
  47.   arma::mat Y = arma::randn(m, 1);
  48.   arma::mat bmean(m,1);
  49.   arma::mat bvar(m,m);
  50.  
  51.   bdraw.row(t-1)=trans(btt+ trans(arma::chol(Vtt))*Y);
  52.   //backward recurssions
  53.   arma::mat bf(1,m);
  54.   for (int i=1;i<t;++i){
  55.     arma::mat Qt =diag(Qtt(t-i,_));
  56.     bf=trans(bdraw.row(t-i));
  57.     btt=trans(bt.row(t-i-1));
  58.     Vtt=test.slice(t-i-1);
  59.     f=Vtt+Qt;
  60.     inv_f=inv(f);
  61.    
  62.     cfe=bf-btt;
  63.     bmean=btt+Vtt*inv_f*cfe;
  64.     //bmean=btt+inv_f*cfe;
  65.     bvar=Vtt-Vtt*inv_f*Vtt;
  66.     //bvar=Vtt-inv_f*Vtt;
  67.     arma::mat Y = arma::randn(m, 1);
  68.     bdraw.row(t-i-1)=trans(bmean+trans(arma::chol(bvar))*Y);
  69.   }
  70.   bdraw=trans(bdraw);
  71.  
  72.   return wrap(bdraw);
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement