rolling_variance.hpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // rolling_variance.hpp
  3. // Copyright (C) 2005 Eric Niebler
  4. // Copyright (C) 2014 Pieter Bastiaan Ober (Integricom).
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. #ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_VARIANCE_HPP_EAN_15_11_2011
  9. #define BOOST_ACCUMULATORS_STATISTICS_ROLLING_VARIANCE_HPP_EAN_15_11_2011
  10. #include <boost/accumulators/accumulators.hpp>
  11. #include <boost/accumulators/statistics/stats.hpp>
  12. #include <boost/mpl/placeholders.hpp>
  13. #include <boost/accumulators/framework/accumulator_base.hpp>
  14. #include <boost/accumulators/framework/extractor.hpp>
  15. #include <boost/accumulators/numeric/functional.hpp>
  16. #include <boost/accumulators/framework/parameters/sample.hpp>
  17. #include <boost/accumulators/framework/depends_on.hpp>
  18. #include <boost/accumulators/statistics_fwd.hpp>
  19. #include <boost/accumulators/statistics/rolling_mean.hpp>
  20. #include <boost/accumulators/statistics/rolling_moment.hpp>
  21. #include <boost/type_traits/is_arithmetic.hpp>
  22. #include <boost/utility/enable_if.hpp>
  23. namespace boost { namespace accumulators
  24. {
  25. namespace impl
  26. {
  27. //! Immediate (lazy) calculation of the rolling variance.
  28. /*!
  29. Calculation of sample variance \f$\sigma_n^2\f$ is done as follows, see also
  30. http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.
  31. For a rolling window of size \f$N\f$, when \f$n <= N\f$, the variance is computed according to the formula
  32. \f[
  33. \sigma_n^2 = \frac{1}{n-1} \sum_{i = 1}^n (x_i - \mu_n)^2.
  34. \f]
  35. When \f$n > N\f$, the sample variance over the window becomes:
  36. \f[
  37. \sigma_n^2 = \frac{1}{N-1} \sum_{i = n-N+1}^n (x_i - \mu_n)^2.
  38. \f]
  39. */
  40. ///////////////////////////////////////////////////////////////////////////////
  41. // lazy_rolling_variance_impl
  42. //
  43. template<typename Sample>
  44. struct lazy_rolling_variance_impl
  45. : accumulator_base
  46. {
  47. // for boost::result_of
  48. typedef typename numeric::functional::fdiv<Sample, std::size_t,void,void>::result_type result_type;
  49. lazy_rolling_variance_impl(dont_care) {}
  50. template<typename Args>
  51. result_type result(Args const &args) const
  52. {
  53. result_type mean = rolling_mean(args);
  54. size_t nr_samples = rolling_count(args);
  55. if (nr_samples < 2) return result_type();
  56. return nr_samples*(rolling_moment<2>(args) - mean*mean)/(nr_samples-1);
  57. }
  58. };
  59. //! Iterative calculation of the rolling variance.
  60. /*!
  61. Iterative calculation of sample variance \f$\sigma_n^2\f$ is done as follows, see also
  62. http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.
  63. For a rolling window of size \f$N\f$, for the first \f$N\f$ samples, the variance is computed according to the formula
  64. \f[
  65. \sigma_n^2 = \frac{1}{n-1} \sum_{i = 1}^n (x_i - \mu_n)^2 = \frac{1}{n-1}M_{2,n},
  66. \f]
  67. where the sum of squares \f$M_{2,n}\f$ can be recursively computed as:
  68. \f[
  69. M_{2,n} = \sum_{i = 1}^n (x_i - \mu_n)^2 = M_{2,n-1} + (x_n - \mu_n)(x_n - \mu_{n-1}),
  70. \f]
  71. and the estimate of the sample mean as:
  72. \f[
  73. \mu_n = \frac{1}{n} \sum_{i = 1}^n x_i = \mu_{n-1} + \frac{1}{n}(x_n - \mu_{n-1}).
  74. \f]
  75. For further samples, when the rolling window is fully filled with data, one has to take into account that the oldest
  76. sample \f$x_{n-N}\f$ is dropped from the window. The sample variance over the window now becomes:
  77. \f[
  78. \sigma_n^2 = \frac{1}{N-1} \sum_{i = n-N+1}^n (x_i - \mu_n)^2 = \frac{1}{n-1}M_{2,n},
  79. \f]
  80. where the sum of squares \f$M_{2,n}\f$ now equals:
  81. \f[
  82. M_{2,n} = \sum_{i = n-N+1}^n (x_i - \mu_n)^2 = M_{2,n-1} + (x_n - \mu_n)(x_n - \mu_{n-1}) - (x_{n-N} - \mu_n)(x_{n-N} - \mu_{n-1}),
  83. \f]
  84. and the estimated mean is:
  85. \f[
  86. \mu_n = \frac{1}{N} \sum_{i = n-N+1}^n x_i = \mu_{n-1} + \frac{1}{n}(x_n - x_{n-N}).
  87. \f]
  88. Note that the sample variance is not defined for \f$n <= 1\f$.
  89. */
  90. ///////////////////////////////////////////////////////////////////////////////
  91. // immediate_rolling_variance_impl
  92. //
  93. template<typename Sample>
  94. struct immediate_rolling_variance_impl
  95. : accumulator_base
  96. {
  97. // for boost::result_of
  98. typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
  99. template<typename Args>
  100. immediate_rolling_variance_impl(Args const &args)
  101. : previous_mean_(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))
  102. , sum_of_squares_(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))
  103. {
  104. }
  105. template<typename Args>
  106. void operator()(Args const &args)
  107. {
  108. Sample added_sample = args[sample];
  109. result_type mean = immediate_rolling_mean(args);
  110. sum_of_squares_ += (added_sample-mean)*(added_sample-previous_mean_);
  111. if(is_rolling_window_plus1_full(args))
  112. {
  113. Sample removed_sample = rolling_window_plus1(args).front();
  114. sum_of_squares_ -= (removed_sample-mean)*(removed_sample-previous_mean_);
  115. prevent_underflow(sum_of_squares_);
  116. }
  117. previous_mean_ = mean;
  118. }
  119. template<typename Args>
  120. result_type result(Args const &args) const
  121. {
  122. size_t nr_samples = rolling_count(args);
  123. if (nr_samples < 2) return result_type();
  124. return numeric::fdiv(sum_of_squares_,(nr_samples-1));
  125. }
  126. private:
  127. result_type previous_mean_;
  128. result_type sum_of_squares_;
  129. template<typename T>
  130. void prevent_underflow(T &non_negative_number,typename boost::enable_if<boost::is_arithmetic<T>,T>::type* = 0)
  131. {
  132. if (non_negative_number < T(0)) non_negative_number = T(0);
  133. }
  134. template<typename T>
  135. void prevent_underflow(T &non_arithmetic_quantity,typename boost::disable_if<boost::is_arithmetic<T>,T>::type* = 0)
  136. {
  137. }
  138. };
  139. } // namespace impl
  140. ///////////////////////////////////////////////////////////////////////////////
  141. // tag:: lazy_rolling_variance
  142. // tag:: immediate_rolling_variance
  143. // tag:: rolling_variance
  144. //
  145. namespace tag
  146. {
  147. struct lazy_rolling_variance
  148. : depends_on< rolling_count, rolling_mean, rolling_moment<2> >
  149. {
  150. /// INTERNAL ONLY
  151. ///
  152. typedef accumulators::impl::lazy_rolling_variance_impl< mpl::_1 > impl;
  153. #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
  154. /// tag::rolling_window::window_size named parameter
  155. static boost::parameter::keyword<tag::rolling_window_size> const window_size;
  156. #endif
  157. };
  158. struct immediate_rolling_variance
  159. : depends_on< rolling_window_plus1, rolling_count, immediate_rolling_mean>
  160. {
  161. /// INTERNAL ONLY
  162. ///
  163. typedef accumulators::impl::immediate_rolling_variance_impl< mpl::_1> impl;
  164. #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
  165. /// tag::rolling_window::window_size named parameter
  166. static boost::parameter::keyword<tag::rolling_window_size> const window_size;
  167. #endif
  168. };
  169. // make immediate_rolling_variance the default implementation
  170. struct rolling_variance : immediate_rolling_variance {};
  171. } // namespace tag
  172. ///////////////////////////////////////////////////////////////////////////////
  173. // extract::lazy_rolling_variance
  174. // extract::immediate_rolling_variance
  175. // extract::rolling_variance
  176. //
  177. namespace extract
  178. {
  179. extractor<tag::lazy_rolling_variance> const lazy_rolling_variance = {};
  180. extractor<tag::immediate_rolling_variance> const immediate_rolling_variance = {};
  181. extractor<tag::rolling_variance> const rolling_variance = {};
  182. BOOST_ACCUMULATORS_IGNORE_GLOBAL(lazy_rolling_variance)
  183. BOOST_ACCUMULATORS_IGNORE_GLOBAL(immediate_rolling_variance)
  184. BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_variance)
  185. }
  186. using extract::lazy_rolling_variance;
  187. using extract::immediate_rolling_variance;
  188. using extract::rolling_variance;
  189. // rolling_variance(lazy) -> lazy_rolling_variance
  190. template<>
  191. struct as_feature<tag::rolling_variance(lazy)>
  192. {
  193. typedef tag::lazy_rolling_variance type;
  194. };
  195. // rolling_variance(immediate) -> immediate_rolling_variance
  196. template<>
  197. struct as_feature<tag::rolling_variance(immediate)>
  198. {
  199. typedef tag::immediate_rolling_variance type;
  200. };
  201. // for the purposes of feature-based dependency resolution,
  202. // lazy_rolling_variance provides the same feature as rolling_variance
  203. template<>
  204. struct feature_of<tag::lazy_rolling_variance>
  205. : feature_of<tag::rolling_variance>
  206. {
  207. };
  208. // for the purposes of feature-based dependency resolution,
  209. // immediate_rolling_variance provides the same feature as rolling_variance
  210. template<>
  211. struct feature_of<tag::immediate_rolling_variance>
  212. : feature_of<tag::rolling_variance>
  213. {
  214. };
  215. }} // namespace boost::accumulators
  216. #endif