Stan  1.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs 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  while (true) {
23  size_t m = N;
24  while((m % 2) == 0) m /= 2;
25  while((m % 3) == 0) m /= 3;
26  while((m % 5) == 0) m /= 5;
27  if (m <= 1)
28  return N;
29  N++;
30  }
31  }
32  }
33 
54  template <typename T>
55  void autocorrelation(const std::vector<T>& y,
56  std::vector<T>& ac,
57  Eigen::FFT<T>& fft) {
58 
59  using std::vector;
60  using std::complex;
61 
62  size_t N = y.size();
63  size_t M = fft_next_good_size(N);
64  size_t Mt2 = 2 * M;
65 
66 
67  vector<complex<T> > freqvec;
68 
69  // centered_signal = y-mean(y) followed by N zeroes
70  vector<T> centered_signal(y);
71  centered_signal.insert(centered_signal.end(),Mt2-N,0.0);
72  T mean = stan::math::mean(y);
73  for (size_t i = 0; i < N; i++)
74  centered_signal[i] -= mean;
75 
76  fft.fwd(freqvec,centered_signal);
77  for (size_t i = 0; i < Mt2; ++i)
78  freqvec[i] = complex<T>(norm(freqvec[i]), 0.0);
79 
80  fft.inv(ac,freqvec);
81  ac.resize(N);
82 
83  /*
84  vector<T> mask_correction_factors;
85  vector<T> mask;
86  mask.insert(mask.end(),N,1.0);
87  mask.insert(mask.end(),N,0.0);
88 
89  freqvec.resize(0);
90  fft.fwd(freqvec,mask);
91  for (size_t i = 0; i < Nt2; ++i)
92  freqvec[i] = complex<T>(norm(freqvec[i]), 0.0);
93 
94  fft.inv(mask_correction_factors, freqvec);
95 
96  for (size_t i = 0; i < N; ++i) {
97  ac[i] /= mask_correction_factors[i];
98  }
99  */
100  for (size_t i = 0; i < N; ++i) {
101  ac[i] /= (N - i);
102  }
103  T var = ac[0];
104  for (size_t i = 0; i < N; ++i)
105  ac[i] /= var;
106  }
107 
124  template <typename T>
125  void autocorrelation(const std::vector<T>& y,
126  std::vector<T>& ac) {
127  Eigen::FFT<T> fft;
128  return autocorrelation(y,ac,fft);
129  }
130 
131 
132  }
133 }
134 
135 #endif

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