Belle II Software  release-05-01-25
Median.cc
1 /**************************************************************************
2  * BASF2 (Belle Analysis Framework 2) *
3  * Copyright(C) 2017 - Belle II Collaboration *
4  * *
5  * Author: The Belle II Collaboration *
6  * Contributors: Oliver Frost *
7  * *
8  * This software is provided "as is" without any warranty. *
9  **************************************************************************/
10 #include <tracking/trackFindingCDC/numerics/Median.h>
11 
12 #include <tracking/trackFindingCDC/numerics/WeightComperator.h>
13 #include <tracking/trackFindingCDC/utilities/Algorithms.h>
14 
15 #include <cmath>
16 
17 using namespace Belle2;
18 
19 double TrackFindingCDC::median(std::vector<double> values)
20 {
21  auto notfinite = [](double v) { return not std::isfinite(v); };
22  erase_remove_if(values, notfinite);
23 
24  int n = values.size();
25 
26  if (n == 0) return NAN;
27 
28  std::nth_element(values.begin(), values.begin() + n / 2, values.end());
29  if (n % 2 == 0) {
30  // For an even number of values the median is the average of the two central values.
31  double upper = values[n / 2];
32  double lower = *std::max_element(values.begin(), values.begin() + n / 2);
33  return (lower + upper) / 2;
34  } else {
35  return values[n / 2];
36  }
37 }
38 
39 double TrackFindingCDC::weightedMedian(std::vector<WithWeight<double> > weightedValues)
40 {
41  auto notfinite = [](const WithWeight<double>& weightedValue) {
42  return not std::isfinite(weightedValue) or not std::isfinite(weightedValue.getWeight());
43  };
44  erase_remove_if(weightedValues, notfinite);
45 
46  if (weightedValues.empty()) return NAN;
47 
48  std::sort(weightedValues.begin(), weightedValues.end());
49 
51  Weight totalWeight = 0;
52  for (WithWeight<double>& weightedValue : weightedValues) {
53  totalWeight += weightedValue.getWeight();
54  weightedValue.setWeight(totalWeight);
55  }
56 
57  auto it = std::partition_point(weightedValues.begin(),
58  weightedValues.end(),
59  GetWeight() < totalWeight / 2.0);
60  return it == weightedValues.end() ? weightedValues.back() : *it;
61 }
Belle2
Abstract base class for different kinds of events.
Definition: MillepedeAlgorithm.h:19