hops
Autocorrelation.hpp
Go to the documentation of this file.
1 #ifndef HOPS_AUTOCORRELATION_HPP
2 #define HOPS_AUTOCORRELATION_HPP
3 
4 #include <Eigen/Core>
5 #include <unsupported/Eigen/FFT>
6 #include <memory>
7 
8 namespace hops {
9  inline size_t nextGoodSizeFFT(size_t N) {
10  if (N <= 2) {
11  return 2;
12  }
13  while (true) {
14  size_t m = N;
15  while ((m % 2) == 0) {
16  m /= 2;
17  }
18  while ((m % 3) == 0) {
19  m /= 3;
20  }
21  while ((m % 5) == 0) {
22  m /= 5;
23  }
24  if (m <= 1) {
25  return N;
26  }
27  N++;
28  }
29  }
30 
31  template <typename StateType>
32  void computeAutocorrelations (const std::vector<StateType>& draws,
33  Eigen::VectorXd& autocorrelations,
34  unsigned long dimension) {
35  computeAutocorrelations(&draws, autocorrelations, dimension);
36  }
37 
38  template <typename StateType>
39  void computeAutocorrelations (const std::vector<StateType>* draws,
40  Eigen::VectorXd& autocorrelations,
41  unsigned long dimension) {
42  size_t N = draws->size();
43  Eigen::VectorXd X = Eigen::VectorXd::Zero(N);
44  for (size_t n = 0; n < N; ++n) {
45  X(n) = (*draws)[n](dimension);
46  }
47 
48  Eigen::FFT<typename StateType::Scalar> fft;
49  size_t M = nextGoodSizeFFT(N);
50  size_t Mt2 = 2 * M;
51 
52  // center and pad X
53  Eigen::VectorXd centeredX(Mt2);
54  centeredX.setZero();
55  centeredX.head(N) = X.array() - X.mean();
56 
57  // See https://en.wikipedia.org/wiki/Autocorrelation#Efficient_computation for a quick
58  // explanation on what follows
59  Eigen::VectorXcd frequency(Mt2);
60  fft.fwd(frequency, centeredX);
61 
62  frequency = frequency.cwiseAbs2();
63 
64  Eigen::VectorXcd autocorrelationsTmp(Mt2);
65  fft.inv(autocorrelationsTmp, frequency);
66 
67  // use "biased" estimate as recommended by Geyer (1992)
68  autocorrelations = autocorrelationsTmp.head(N).real().array() / (N * N * 2);
69  autocorrelations /= autocorrelations(0);
70  }
71 }
72 
73 #endif // HOPS_AUTOCORRELATION_HPP
hops::computeAutocorrelations
void computeAutocorrelations(const std::vector< StateType > &draws, Eigen::VectorXd &autocorrelations, unsigned long dimension)
Definition: Autocorrelation.hpp:32
hops
Definition: CsvReader.hpp:8
hops::nextGoodSizeFFT
size_t nextGoodSizeFFT(size_t N)
Definition: Autocorrelation.hpp:9