|
#include <thrust/device_vector.h> |
|
#include <thrust/scan.h> |
|
#include <thrust/transform.h> |
|
#include <thrust/functional.h> |
|
#include <thrust/sequence.h> |
|
#include <thrust/random.h> |
|
#include <iostream> |
|
#include <iomanip> |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
template <typename T> |
|
struct minus_and_divide : public thrust::binary_function<T,T,T> |
|
{ |
|
T w; |
|
|
|
minus_and_divide(T w) : w(w) {} |
|
|
|
__host__ __device__ |
|
T operator()(const T& a, const T& b) const |
|
{ |
|
return (a - b) / w; |
|
} |
|
}; |
|
|
|
template <typename InputVector, typename OutputVector> |
|
void simple_moving_average(const InputVector& data, size_t w, OutputVector& output) |
|
{ |
|
typedef typename InputVector::value_type T; |
|
|
|
if (data.size() < w) |
|
return; |
|
|
|
|
|
thrust::device_vector<T> temp(data.size() + 1); |
|
|
|
|
|
thrust::exclusive_scan(data.begin(), data.end(), temp.begin()); |
|
temp[data.size()] = data.back() + temp[data.size() - 1]; |
|
|
|
|
|
thrust::transform(temp.begin() + w, temp.end(), temp.begin(), output.begin(), minus_and_divide<T>(T(w))); |
|
} |
|
|
|
int main(void) |
|
{ |
|
|
|
size_t n = 30; |
|
|
|
|
|
size_t w = 4; |
|
|
|
|
|
thrust::device_vector<float> data(n); |
|
thrust::default_random_engine rng; |
|
thrust::uniform_int_distribution<int> dist(0, 10); |
|
for (size_t i = 0; i < n; i++) |
|
data[i] = static_cast<float>(dist(rng)); |
|
|
|
|
|
thrust::device_vector<float> averages(data.size() - (w - 1)); |
|
|
|
|
|
simple_moving_average(data, w, averages); |
|
|
|
|
|
std::cout << "data series: [ "; |
|
for (size_t i = 0; i < data.size(); i++) |
|
std::cout << data[i] << " "; |
|
std::cout << "]" << std::endl; |
|
|
|
|
|
std::cout << "simple moving averages (window = " << w << ")" << std::endl; |
|
for (size_t i = 0; i < averages.size(); i++) |
|
std::cout << " [" << std::setw(2) << i << "," << std::setw(2) << (i + w) << ") = " << averages[i] << std::endl; |
|
|
|
return 0; |
|
} |
|
|
|
|