Stan  2.5.0
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
autocorrelation.hpp
Go to the documentation of this file.
1 #ifndef STAN__PROB__AUTOCORRELATION_HPP
2 #define STAN__PROB__AUTOCORRELATION_HPP
3 
4 #include <stan/math/matrix.hpp>
6 
7 #include <vector>
8 #include <complex>
9 #include <unsupported/Eigen/FFT>
10 
11 
12 namespace stan {
13 
14  namespace prob {
15 
16  namespace {
21  size_t fft_next_good_size(size_t N) {
22  if (N <= 2) return 2;
23  while (true) {
24  size_t m = N;
25  while((m % 2) == 0) m /= 2;
26  while((m % 3) == 0) m /= 3;
27  while((m % 5) == 0) m /= 5;
28  if (m <= 1)
29  return N;
30  N++;
31  }
32  }
33  }
34 
55  template <typename T>
56  void autocorrelation(const std::vector<T>& y,
57  std::vector<T>& ac,
58  Eigen::FFT<T>& fft) {
59 
60  using std::vector;
61  using std::complex;
62 
63  size_t N = y.size();
64  size_t M = fft_next_good_size(N);
65  size_t Mt2 = 2 * M;
66 
67 
68  vector<complex<T> > freqvec;
69 
70  // centered_signal = y-mean(y) followed by N zeroes
71  vector<T> centered_signal(y);
72  centered_signal.insert(centered_signal.end(),Mt2-N,0.0);
73  T mean = stan::math::mean(y);
74  for (size_t i = 0; i < N; i++)
75  centered_signal[i] -= mean;
76 
77  fft.fwd(freqvec,centered_signal);
78  for (size_t i = 0; i < Mt2; ++i)
79  freqvec[i] = complex<T>(norm(freqvec[i]), 0.0);
80 
81  fft.inv(ac,freqvec);
82  ac.resize(N);
83 
84  /*
85  vector<T> mask_correction_factors;
86  vector<T> mask;
87  mask.insert(mask.end(),N,1.0);
88  mask.insert(mask.end(),N,0.0);
89 
90  freqvec.resize(0);
91  fft.fwd(freqvec,mask);
92  for (size_t i = 0; i < Nt2; ++i)
93  freqvec[i] = complex<T>(norm(freqvec[i]), 0.0);
94 
95  fft.inv(mask_correction_factors, freqvec);
96 
97  for (size_t i = 0; i < N; ++i) {
98  ac[i] /= mask_correction_factors[i];
99  }
100  */
101  for (size_t i = 0; i < N; ++i) {
102  ac[i] /= (N - i);
103  }
104  T var = ac[0];
105  for (size_t i = 0; i < N; ++i)
106  ac[i] /= var;
107  }
108 
125  template <typename T>
126  void autocorrelation(const std::vector<T>& y,
127  std::vector<T>& ac) {
128  Eigen::FFT<T> fft;
129  return autocorrelation(y,ac,fft);
130  }
131 
132 
133  }
134 }
135 
136 #endif
boost::math::tools::promote_args< T >::type mean(const std::vector< T > &v)
Returns the sample mean (i.e., average) of the coefficients in the specified standard vector...
Definition: mean.hpp:23
void autocorrelation(const std::vector< T > &y, std::vector< T > &ac, Eigen::FFT< T > &fft)
Write autocorrelation estimates for every lag for the specified input sequence into the specified res...

     [ Stan Home Page ] © 2011–2014, Stan Development Team.