1#ifndef STAN_MATH_PRIM_FUN_AUTOCORRELATION_HPP
2#define STAN_MATH_PRIM_FUN_AUTOCORRELATION_HPP
6#include <unsupported/Eigen/FFT>
24 while ((m % 2) == 0) {
27 while ((m % 3) == 0) {
30 while ((m % 5) == 0) {
71 vector<complex<T> > freqvec;
74 vector<T> centered_signal(y);
75 centered_signal.insert(centered_signal.end(), Mt2 - N, 0.0);
77 for (
size_t i = 0; i < N; i++) {
78 centered_signal[i] -=
mean;
81 fft.fwd(freqvec, centered_signal);
82 for (
size_t i = 0; i < Mt2; ++i) {
83 freqvec[i] = complex<T>(
norm(freqvec[i]), 0.0);
89 for (
size_t i = 0; i < N; ++i) {
93 for (
size_t i = 0; i < N; ++i) {
118template <
typename T,
typename DerivedA,
typename DerivedB>
120 Eigen::MatrixBase<DerivedB>& ac, Eigen::FFT<T>&
fft) {
126 Eigen::Matrix<T, Eigen::Dynamic, 1> centered_signal(Mt2);
127 centered_signal.setZero();
128 centered_signal.head(N) = y.array() - y.mean();
130 Eigen::Matrix<std::complex<T>, Eigen::Dynamic, 1> freqvec(Mt2);
131 fft.SetFlag(
fft.HalfSpectrum);
132 fft.fwd(freqvec, centered_signal);
134 freqvec = freqvec.cwiseAbs2();
136 Eigen::Matrix<T, Eigen::Dynamic, 1> ac_tmp(Mt2);
137 fft.inv(ac_tmp, freqvec);
138 fft.ClearFlag(
fft.HalfSpectrum);
140 for (
size_t i = 0; i < N; ++i) {
141 ac_tmp(i) /= (N - i);
144 ac = ac_tmp.head(N).array() / ac_tmp(0);
169 const Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1> > y_map(&y[0], N);
170 Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1> > ac_map(&ac[0], N);
171 autocorrelation<T>(y_map, ac_map,
fft);
190template <
typename T,
typename DerivedA,
typename DerivedB>
192 Eigen::MatrixBase<DerivedB>& ac) {
size_t fft_next_good_size(size_t N)
Find the optimal next size for the FFT so that a minimum number of zeros are padded.
scalar_type_t< T > mean(const T &m)
Returns the sample mean (i.e., average) of the coefficients in the specified std vector,...
fvar< T > norm(const std::complex< fvar< T > > &z)
Return the squared magnitude of the complex argument.
Eigen::Matrix< scalar_type_t< V >, -1, 1 > fft(const V &x)
Return the discrete Fourier transform of the specified complex vector.
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...
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...