Home  · Classes  · Annotated Classes  · Modules  · Members  · Namespaces  · Related Pages
StatisticFunctions.h
Go to the documentation of this file.
1 // --------------------------------------------------------------------------
2 // OpenMS -- Open-Source Mass Spectrometry
3 // --------------------------------------------------------------------------
4 // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
5 // ETH Zurich, and Freie Universitaet Berlin 2002-2016.
6 //
7 // This software is released under a three-clause BSD license:
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 // notice, this list of conditions and the following disclaimer in the
12 // documentation and/or other materials provided with the distribution.
13 // * Neither the name of any author or any participating institution
14 // may be used to endorse or promote products derived from this software
15 // without specific prior written permission.
16 // For a full list of authors, refer to the file AUTHORS.
17 // --------------------------------------------------------------------------
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
22 // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25 // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27 // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28 // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // --------------------------------------------------------------------------
31 // $Maintainer: Clemens Groepl $
32 // $Authors: Clemens Groepl, Johannes Junker, Mathias Walzer, Chris Bielow $
33 // --------------------------------------------------------------------------
34 #ifndef OPENMS_MATH_STATISTICS_STATISTICFUNCTIONS_H
35 #define OPENMS_MATH_STATISTICS_STATISTICFUNCTIONS_H
36 
37 #include <vector>
39 #include <OpenMS/CONCEPT/Types.h>
40 
41 #include <boost/accumulators/accumulators.hpp>
42 #include <boost/accumulators/statistics/covariance.hpp>
43 #include <boost/accumulators/statistics/mean.hpp>
44 #include <boost/accumulators/statistics/stats.hpp>
45 #include <boost/accumulators/statistics/variance.hpp>
46 #include <boost/accumulators/statistics/variates/covariate.hpp>
47 #include <boost/function/function_base.hpp>
48 #include <boost/lambda/casts.hpp>
49 #include <boost/lambda/lambda.hpp>
50 
51 #include <iterator>
52 #include <algorithm>
53 
54 
55 
56 using std::iterator_traits;
57 
58 namespace OpenMS
59 {
60 
61  namespace Math
62  {
70  template <typename IteratorType>
71  static void checkIteratorsNotNULL(
72  IteratorType begin, IteratorType end)
73  {
74  if (begin == end)
75  {
76  throw Exception::InvalidRange(__FILE__, __LINE__, __PRETTY_FUNCTION__);
77  }
78  }
86  template <typename IteratorType>
87  static void checkIteratorsEqual(
88  IteratorType begin, IteratorType end)
89  {
90  if (begin != end)
91  {
92  throw Exception::InvalidRange(__FILE__, __LINE__, __PRETTY_FUNCTION__);
93  }
94  }
102  template <typename IteratorType1, typename IteratorType2>
104  IteratorType1 begin_b, IteratorType1 end_b,
105  IteratorType2 begin_a, IteratorType2 end_a)
106  {
107  if(begin_b != end_b && begin_a == end_a)
108  {
109  throw Exception::InvalidRange(__FILE__, __LINE__, __PRETTY_FUNCTION__);
110  }
111  }
117  template <typename IteratorType>
118  static double sum(IteratorType begin, IteratorType end)
119  {
120  return std::accumulate(begin, end, 0.0);
121  }
122 
130  template <typename IteratorType>
131  static double mean(IteratorType begin, IteratorType end)
132  {
133  checkIteratorsNotNULL(begin, end);
134  return sum(begin, end) / std::distance(begin, end);
135  }
136 
148  template <typename IteratorType>
149  static double median(IteratorType begin, IteratorType end, bool sorted = false)
150  {
151  checkIteratorsNotNULL(begin, end);
152  if (!sorted)
153  {
154  std::sort(begin, end);
155  }
156 
157  Size size = std::distance(begin, end);
158  if (size % 2 == 0) // even size => average two middle values
159  {
160  IteratorType it1 = begin;
161  std::advance(it1, size / 2 - 1);
162  IteratorType it2 = it1;
163  std::advance(it2, 1);
164  return (*it1 + *it2) / 2.0;
165  }
166  else
167  {
168  IteratorType it = begin;
169  std::advance(it, (size - 1) / 2);
170  return *it;
171  }
172  }
173 
174 
194  template <typename IteratorType>
195  double MAD(IteratorType begin, IteratorType end, double median_of_numbers)
196  {
197  std::vector<double> diffs;
198  diffs.reserve(std::distance(begin, end));
199  for (IteratorType it = begin; it != end; ++it)
200  {
201  diffs.push_back(fabs(*it - median_of_numbers));
202  }
203  return median(diffs.begin(), diffs.end(), false);
204  }
205 
219  template <typename IteratorType>
220  static double quantile1st(
221  IteratorType begin, IteratorType end, bool sorted = false)
222  {
223  checkIteratorsNotNULL(begin, end);
224 
225  if (!sorted)
226  {
227  std::sort(begin, end);
228  }
229 
230  Size size = std::distance(begin, end);
231  if (size % 2 == 0)
232  {
233  return median(begin, begin + (size/2)-1, true); //-1 to exclude median values
234  }
235  return median(begin, begin + (size/2), true);
236  }
237 
251  template <typename IteratorType>
252  static double quantile3rd(
253  IteratorType begin, IteratorType end, bool sorted = false)
254  {
255  checkIteratorsNotNULL(begin, end);
256  if (!sorted)
257  {
258  std::sort(begin, end);
259  }
260 
261  Size size = std::distance(begin, end);
262  return median(begin + (size/2)+1, end, true); //+1 to exclude median values
263  }
264 
274  template <typename IteratorType>
275  static double variance(
276  IteratorType begin, IteratorType end,
277  double mean = std::numeric_limits<double>::max())
278  {
279  checkIteratorsNotNULL(begin, end);
280  double sum = 0.0;
281  if (mean == std::numeric_limits<double>::max())
282  {
283  mean = Math::mean(begin, end);
284  }
285  for (IteratorType iter=begin; iter!=end; ++iter)
286  {
287  double diff = *iter - mean;
288  sum += diff * diff;
289  }
290  return sum / (std::distance(begin, end)-1);
291  }
292 
302  template <typename IteratorType>
303  static double sd(
304  IteratorType begin, IteratorType end,
305  double mean = std::numeric_limits<double>::max())
306  {
307  checkIteratorsNotNULL(begin, end);
308  return std::sqrt( variance(begin, end, mean) );
309  }
310 
318  template <typename IteratorType>
319  static double absdev(
320  IteratorType begin, IteratorType end,
321  double mean = std::numeric_limits<double>::max())
322  {
323  checkIteratorsNotNULL(begin, end);
324  double sum = 0.0;
325  if (mean == std::numeric_limits<double>::max())
326  {
327  mean = Math::mean(begin, end);
328  }
329  for (IteratorType iter=begin; iter!=end; ++iter)
330  {
331  sum += *iter - mean;
332  }
333  return sum / std::distance(begin, end);
334  }
335 
345  template <typename IteratorType1, typename IteratorType2>
346  static double covariance(
347  IteratorType1 begin_a, IteratorType1 end_a,
348  IteratorType2 begin_b, IteratorType2 end_b)
349  {
350  //no data or different lengths
351  checkIteratorsNotNULL(begin_a, end_a);
352 
353  double sum = 0.0;
354  double mean_a = Math::mean(begin_a, end_a);
355  double mean_b = Math::mean(begin_b, end_b);
356  IteratorType1 iter_a = begin_a;
357  IteratorType2 iter_b = begin_b;
358  for (; iter_a != end_a; ++iter_a, ++iter_b)
359  {
360  /* assure both ranges have the same number of elements */
361  checkIteratorsAreValid(begin_b, end_b, begin_a, end_a);
362  sum += (*iter_a - mean_a) * (*iter_b - mean_b);
363  }
364  /* assure both ranges have the same number of elements */
365  checkIteratorsEqual(iter_b, end_b);
366  Size n = std::distance(begin_a, end_a);
367  return sum / (n-1);
368  }
369 
370 
371 
372 
382  template <typename IteratorType1, typename IteratorType2>
383  static double meanSquareError(
384  IteratorType1 begin_a, IteratorType1 end_a,
385  IteratorType2 begin_b, IteratorType2 end_b)
386  {
387  //no data or different lengths
388  checkIteratorsNotNULL(begin_a, end_a);
389 
390  SignedSize dist = std::distance(begin_a, end_a);
391  double error = 0;
392  IteratorType1 iter_a = begin_a;
393  IteratorType2 iter_b = begin_b;
394  for (; iter_a != end_a; ++iter_a, ++iter_b)
395  {
396  /* assure both ranges have the same number of elements */
397  checkIteratorsAreValid(iter_b, end_b, iter_a, end_a);
398 
399  double tmp(*iter_a - *iter_b);
400  error += tmp * tmp;
401  }
402  /* assure both ranges have the same number of elements */
403  checkIteratorsEqual(iter_b, end_b);
404 
405  return error / dist;
406  }
407 
417  template <typename IteratorType1, typename IteratorType2>
418  static double classificationRate(
419  IteratorType1 begin_a, IteratorType1 end_a,
420  IteratorType2 begin_b, IteratorType2 end_b)
421  {
422  //no data or different lengths
423  checkIteratorsNotNULL(begin_a, end_a);
424 
425  SignedSize dist = std::distance(begin_a, end_a);
426  SignedSize correct = dist;
427  IteratorType1 iter_a = begin_a;
428  IteratorType2 iter_b = begin_b;
429  for (; iter_a != end_a; ++iter_a, ++iter_b)
430  {
431  /* assure both ranges have the same number of elements */
432  checkIteratorsAreValid(iter_b, end_b, iter_a, end_a);
433  if ((*iter_a < 0 && *iter_b >= 0) || (*iter_a >= 0 && *iter_b < 0))
434  {
435  --correct;
436  }
437 
438  }
439  /* assure both ranges have the same number of elements */
440  checkIteratorsEqual(iter_b, end_b);
441 
442  return double(correct) / dist;
443  }
444 
457  template <typename IteratorType1, typename IteratorType2>
459  IteratorType1 begin_a, IteratorType1 end_a,
460  IteratorType2 begin_b, IteratorType2 end_b)
461  {
462  //no data or different lengths
463  checkIteratorsNotNULL(begin_a, end_b);
464 
465  double tp = 0;
466  double fp = 0;
467  double tn = 0;
468  double fn = 0;
469  IteratorType1 iter_a = begin_a;
470  IteratorType2 iter_b = begin_b;
471  for (; iter_a != end_a; ++iter_a, ++iter_b)
472  {
473  /* assure both ranges have the same number of elements */
474  checkIteratorsAreValid(iter_b, end_b, iter_a, end_a);
475 
476  if (*iter_a < 0 && *iter_b >= 0)
477  {
478  ++fn;
479  }
480  else if (*iter_a < 0 && *iter_b < 0)
481  {
482  ++tn;
483  }
484  else if (*iter_a >= 0 && *iter_b >= 0)
485  {
486  ++tp;
487  }
488  else if (*iter_a >= 0 && *iter_b < 0)
489  {
490  ++fp;
491  }
492  }
493  /* assure both ranges have the same number of elements */
494  checkIteratorsEqual(iter_b, end_b);
495 
496  return (tp * tn - fp * fn) / sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn));
497  }
498 
510  template <typename IteratorType1, typename IteratorType2>
512  IteratorType1 begin_a, IteratorType1 end_a,
513  IteratorType2 begin_b, IteratorType2 end_b)
514  {
515  //no data or different lengths
516  checkIteratorsNotNULL(begin_a, end_a);
517 
518  //calculate average
519  SignedSize dist = std::distance(begin_a, end_a);
520  double avg_a = std::accumulate(begin_a, end_a, 0.0) / dist;
521  double avg_b = std::accumulate(begin_b, end_b, 0.0) / dist;
522 
523  double numerator = 0;
524  double denominator_a = 0;
525  double denominator_b = 0;
526  IteratorType1 iter_a = begin_a;
527  IteratorType2 iter_b = begin_b;
528  for (; iter_a != end_a; ++iter_a, ++iter_b)
529  {
530  /* assure both ranges have the same number of elements */
531  checkIteratorsAreValid(iter_b, end_b, iter_a, end_a);
532  double temp_a = *iter_a - avg_a;
533  double temp_b = *iter_b - avg_b;
534  numerator += (temp_a * temp_b);
535  denominator_a += (temp_a * temp_a);
536  denominator_b += (temp_b * temp_b);
537  }
538  /* assure both ranges have the same number of elements */
539  checkIteratorsEqual(iter_b, end_b);
540  return numerator / sqrt(denominator_a * denominator_b);
541  }
542 
544  template <typename Value>
545  static void computeRank(std::vector<Value> & w)
546  {
547  Size i = 0; // main index
548  Size z = 0; // "secondary" index
549  Value rank = 0;
550  Size n = (w.size() - 1);
551  //store original indices for later
552  std::vector<std::pair<Size, Value> > w_idx;
553  for (Size j = 0; j < w.size(); ++j)
554  {
555  w_idx.push_back(std::make_pair(j, w[j]));
556  }
557  //sort
558  std::sort(w_idx.begin(), w_idx.end(),
559  boost::lambda::ret<bool>((&boost::lambda::_1->*& std::pair<Size, Value>::second) <
560  (&boost::lambda::_2->*& std::pair<Size, Value>::second)));
561  //replace pairs <orig_index, value> in w_idx by pairs <orig_index, rank>
562  while (i < n)
563  {
564  // test for equality with tolerance:
565  if (fabs(w_idx[i + 1].second - w_idx[i].second) > 0.0000001 * fabs(w_idx[i + 1].second)) // no tie
566  {
567  w_idx[i].second = Value(i + 1);
568  ++i;
569  }
570  else // tie, replace by mean rank
571  {
572  // count number of ties
573  for (z = i + 1; (z <= n) && fabs(w_idx[z].second - w_idx[i].second) <= 0.0000001 * fabs(w_idx[z].second); ++z)
574  {
575  }
576  // compute mean rank of tie
577  rank = 0.5 * (i + z + 1);
578  // replace intensities by rank
579  for (Size v = i; v <= z - 1; ++v)
580  {
581  w_idx[v].second = rank;
582  }
583  i = z;
584  }
585  }
586  if (i == n)
587  w_idx[n].second = Value(n + 1);
588  //restore original order and replace elements of w with their ranks
589  for (Size j = 0; j < w.size(); ++j)
590  {
591  w[w_idx[j].first] = w_idx[j].second;
592  }
593  }
594 
606  template <typename IteratorType1, typename IteratorType2>
608  IteratorType1 begin_a, IteratorType1 end_a,
609  IteratorType2 begin_b, IteratorType2 end_b)
610  {
611  //no data or different lengths
612  checkIteratorsNotNULL(begin_a, end_a);
613 
614  // store and sort intensities of model and data
615  SignedSize dist = std::distance(begin_a, end_a);
616  std::vector<double> ranks_data;
617  ranks_data.reserve(dist);
618  std::vector<double> ranks_model;
619  ranks_model.reserve(dist);
620  IteratorType1 iter_a = begin_a;
621  IteratorType2 iter_b = begin_b;
622  for (; iter_a != end_a; ++iter_a, ++iter_b)
623  {
624  /* assure both ranges have the same number of elements */
625  checkIteratorsAreValid(iter_b, end_b, iter_a, end_a);
626 
627  ranks_model.push_back(*iter_a);
628  ranks_data.push_back(*iter_b);
629  }
630  /* assure both ranges have the same number of elements */
631  checkIteratorsEqual(iter_b, end_b);
632 
633  // replace entries by their ranks
634  computeRank(ranks_data);
635  computeRank(ranks_model);
636 
637  double mu = double(ranks_data.size() + 1) / 2.; // mean of ranks
638  // Was the following, but I think the above is more correct ... (Clemens)
639  // double mu = (ranks_data.size() + 1) / 2;
640 
641  double sum_model_data = 0;
642  double sqsum_data = 0;
643  double sqsum_model = 0;
644 
645  for (Int i = 0; i < dist; ++i)
646  {
647  sum_model_data += (ranks_data[i] - mu) * (ranks_model[i] - mu);
648  sqsum_data += (ranks_data[i] - mu) * (ranks_data[i] - mu);
649  sqsum_model += (ranks_model[i] - mu) * (ranks_model[i] - mu);
650  }
651 
652  // check for division by zero
653  if (!sqsum_data || !sqsum_model)
654  {
655  return 0;
656  }
657 
658  return sum_model_data / (sqrt(sqsum_data) * sqrt(sqsum_model));
659  }
660 
662  template<typename T>
664  {
666  :mean(0), variance(0), min(0), lowerq(0), median(0), upperq(0), max(0)
667  {
668  }
669 
670  // Ctor with data
672  {
673  count = data.size();
674  // Sanity check: avoid core dump if no data points present.
675  if (data.empty())
676  {
677  mean = variance = min = lowerq = median = upperq = max = 0.0;
678  }
679  else
680  {
681  sort(data.begin(), data.end());
682  mean = Math::mean(data.begin(), data.end());
683  variance = Math::variance(data.begin(), data.end(), mean);
684  min = data.front();
685  lowerq = Math::quantile1st(data.begin(), data.end(), true);
686  median = Math::median(data.begin(), data.end(), true);
687  upperq = Math::quantile3rd(data.begin(), data.end(), true);
688  max = data.back();
689  }
690  }
691 
693  typename T::value_type min, max;
694  size_t count;
695  };
696 
697  } // namespace Math
698 } // namespace OpenMS
699 
700 #endif // OPENMS_MATH_STATISTICS_STATISTICFUNCTIONS_H
SummaryStatistics()
Definition: StatisticFunctions.h:665
double variance
Definition: StatisticFunctions.h:692
static double meanSquareError(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b)
Calculates the mean square error for the values in [begin_a, end_a) and [begin_b, end_b) ...
Definition: StatisticFunctions.h:383
T::value_type max
Definition: StatisticFunctions.h:693
double MAD(IteratorType begin, IteratorType end, double median_of_numbers)
median absolute deviation (MAD)
Definition: StatisticFunctions.h:195
double lowerq
Definition: StatisticFunctions.h:692
static double variance(IteratorType begin, IteratorType end, double mean=std::numeric_limits< double >::max())
Calculates the variance of a range of values.
Definition: StatisticFunctions.h:275
static double sum(IteratorType begin, IteratorType end)
Calculates the sum of a range of values.
Definition: StatisticFunctions.h:118
static void checkIteratorsAreValid(IteratorType1 begin_b, IteratorType1 end_b, IteratorType2 begin_a, IteratorType2 end_a)
Helper function checking if an iterator and a co-iterator both have a next element.
Definition: StatisticFunctions.h:103
static double quantile1st(IteratorType begin, IteratorType end, bool sorted=false)
Calculates the first quantile of a range of values.
Definition: StatisticFunctions.h:220
static void computeRank(std::vector< Value > &w)
Replaces the elements in vector w by their ranks.
Definition: StatisticFunctions.h:545
static double covariance(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b)
Calculates the covariance of two ranges of values.
Definition: StatisticFunctions.h:346
ptrdiff_t SignedSize
Signed Size type e.g. used as pointer difference.
Definition: Types.h:135
static void checkIteratorsEqual(IteratorType begin, IteratorType end)
Helper function checking if two iterators are equal.
Definition: StatisticFunctions.h:87
Main OpenMS namespace.
Definition: FeatureDeconvolution.h:47
static double mean(IteratorType begin, IteratorType end)
Calculates the mean of a range of values.
Definition: StatisticFunctions.h:131
static double sd(IteratorType begin, IteratorType end, double mean=std::numeric_limits< double >::max())
Calculates the standard deviation of a range of values.
Definition: StatisticFunctions.h:303
static double matthewsCorrelationCoefficient(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b)
Calculates the Matthews correlation coefficient for the values in [begin_a, end_a) and [begin_b...
Definition: StatisticFunctions.h:458
static double absdev(IteratorType begin, IteratorType end, double mean=std::numeric_limits< double >::max())
Calculates the absolute deviation of a range of values.
Definition: StatisticFunctions.h:319
static double pearsonCorrelationCoefficient(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b)
Calculates the Pearson correlation coefficient for the values in [begin_a, end_a) and [begin_b...
Definition: StatisticFunctions.h:511
Helper class to gather (and dump) some statistics from a e.g. vector.
Definition: StatisticFunctions.h:663
static void checkIteratorsNotNULL(IteratorType begin, IteratorType end)
Helper function checking if two iterators are not equal.
Definition: StatisticFunctions.h:71
double upperq
Definition: StatisticFunctions.h:692
static double quantile3rd(IteratorType begin, IteratorType end, bool sorted=false)
Calculates the third quantile of a range of values.
Definition: StatisticFunctions.h:252
double median
Definition: StatisticFunctions.h:692
static double median(IteratorType begin, IteratorType end, bool sorted=false)
Calculates the median of a range of values.
Definition: StatisticFunctions.h:149
SummaryStatistics(T &data)
Definition: StatisticFunctions.h:671
Invalid range exception.
Definition: Exception.h:286
static double rankCorrelationCoefficient(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b)
calculates the rank correlation coefficient for the values in [begin_a, end_a) and [begin_b...
Definition: StatisticFunctions.h:607
size_t count
Definition: StatisticFunctions.h:694
T::value_type min
Definition: StatisticFunctions.h:693
static double classificationRate(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b)
Calculates the classification rate for the values in [begin_a, end_a) and [begin_b, end_b)
Definition: StatisticFunctions.h:418
double mean
Definition: StatisticFunctions.h:692
int Int
Signed integer type.
Definition: Types.h:103

OpenMS / TOPP release 2.0.0 Documentation generated on Tue Jan 31 2017 06:39:54 using doxygen 1.8.8