1 #ifndef _theplu_yat_statistics_percentiler_
2 #define _theplu_yat_statistics_percentiler_
26 #include "yat/utility/concept_check.h"
27 #include "yat/utility/DataWeight.h"
28 #include "yat/utility/iterator_traits.h"
29 #include "yat/utility/yat_assert.h"
30 #include "yat/utility/WeightIterator.h"
32 #include <boost/concept_check.hpp>
43 namespace statistics {
96 template<
typename RandomAccessIterator>
98 RandomAccessIterator last)
const
100 BOOST_CONCEPT_ASSERT((boost::RandomAccessIterator<RandomAccessIterator>));
103 return std::numeric_limits<double>::quiet_NaN();
106 typedef typename weighted_iterator_traits<RandomAccessIterator>::type tag;
107 return calculate(first, last, sorted_, tag());
114 template<
typename RandomAccessIterator>
115 double calculate(RandomAccessIterator first, RandomAccessIterator last,
119 template<
typename RandomAccessIterator>
120 double calculate(RandomAccessIterator first, RandomAccessIterator last,
133 template<
typename RandomAccessIterator>
135 Percentiler::calculate(RandomAccessIterator first,
136 RandomAccessIterator last,
140 size_t n = last - first;
145 double j = n * perc_ / 100.0;
151 return *std::max_element(first, last);
156 return *std::min_element(first, last);
159 size_t i =
static_cast<size_t>(j);
161 size_t k = (i==j) ? i-1 : i;
166 return (first[i]+first[k])/2;
169 std::vector<double> vec(first, last);
171 std::nth_element(vec.begin(), vec.begin()+i, vec.end());
183 return (vec[i] + *std::max_element(vec.begin(), vec.begin()+i))/2;
188 template<
typename RandomAccessIterator>
189 double Percentiler::calculate(RandomAccessIterator first,
190 RandomAccessIterator last,
192 utility::weighted_iterator_tag tag)
const
195 utility::iterator_traits<RandomAccessIterator> trait;
196 std::vector<double> accum_w;
197 accum_w.reserve(last-first);
198 std::partial_sum(weight_iterator(first),
199 weight_iterator(last),
200 std::back_inserter(accum_w));
202 double w_bound=perc_/100.0*accum_w.back();
203 std::vector<double>::const_iterator upper(accum_w.begin());
205 while (upper!=accum_w.end() && *upper <= w_bound+margin)
207 while (upper!=accum_w.begin() &&
208 (upper==accum_w.end() ||
209 trait.weight(first+(upper-accum_w.begin()))==0.0))
211 std::vector<double>::const_iterator lower(upper);
212 while ( *(lower-1)>=w_bound-margin && lower>accum_w.begin())
215 return (trait.data(first+(upper-accum_w.begin()))+
216 trait.data(first+(lower-accum_w.begin())))/2;
219 std::vector<utility::DataWeight> v_copy(first, last);
220 std::sort(v_copy.begin(), v_copy.end());
221 return calculate(v_copy.begin(), v_copy.end(),
true, tag);
Concept check for Data Iterator.
Definition: concept_check.h:226
Definition: iterator_traits.h:47
Definition: iterator_traits.h:55
Definition: iterator_traits.h:105
Percentiler(double perc=50, bool sorted=false)
Functor to calculate percentile of a range.
Definition: Percentiler.h:50
double operator()(RandomAccessIterator first, RandomAccessIterator last) const
Definition: Percentiler.h:97