Belle II Software  release-06-00-14
BestCandidateSelectionModule.cc
1 /**************************************************************************
2  * basf2 (Belle II Analysis Software Framework) *
3  * Author: The Belle II Collaboration *
4  * *
5  * See git log for contributors and copyright holders. *
6  * This file is licensed under LGPL-3.0, see LICENSE.md. *
7  **************************************************************************/
8 
9 #include <analysis/modules/BestCandidateSelection/BestCandidateSelectionModule.h>
10 
11 #include <analysis/utility/ValueIndexPairSorting.h>
12 
13 #include <analysis/VariableManager/Utility.h>
14 
15 #include <framework/logging/Logger.h>
16 #include <framework/utilities/MakeROOTCompatible.h>
17 
18 using namespace std;
19 using namespace Belle2;
20 
21 
22 REG_MODULE(BestCandidateSelection)
23 
24 
26  m_variable(nullptr)
27 {
28  //the "undefined order" bit is not strictly true in the current implementation, but details (with anti-particle lists) are tricky
29  setDescription(R"DOC(Sort particles by the value of a given ``variable``
30 in the input list and optionally remove particles after the nth position.
31 
32 Per default particles are sorted in descending order but it can be switched to
33 an ascending order by setting ``selectLowest=True``. The convenience functions
34 `modularAnalysis.rankByHighest` and `modularAnalysis.rankByLowest` set this
35 parameter automatically based on their names.
36 
37 Particles will receive an extra-info field containing their rank as an integer
38 starting at 1 (best). The name of this extra-info field defaults to
39 ``${variable}_rank`` but can be chosen freely using the ``outputVariable``
40 parameter.
41 
42 The ranking also takes antiparticles into account, so there will only be one
43 B+- candidate with ``rank=1``. The remaining list is sorted from best to worst
44 candidate (each charge, e.g. B+/B-, separately). The sorting is guaranteed
45 to be stable between particle and anti particle list: particles with the same
46 value for ``variable`` will keep their relative order. That is, a particle "A"
47 which was before another particle "B" in the same list and has the same value
48 for ``variable`` will also stay before "B" after sorting.
49 
50 If ``allowMultiRank=False`` (the default) candidates with same value of
51 ``variable`` will have different ranks. If ``allowMultiRank=True`` they will
52 share the same rank.
53 
54 IF ``numBest>0`` only candidates with this rank or better will remain in the
55 output list. If ``allowMultiRank=True`` that means that there can be more than
56 ``numBest`` candidates in the output list if they share ranks.
57 )DOC");
58 
59  setPropertyFlags(c_ParallelProcessingCertified);
60 
61  addParam("particleList", m_inputListName, "Name of the ParticleList to rank for best candidate");
62  addParam("variable", m_variableName, "Variable which defines the candidate ranking (see ``selectLowest`` for ordering)");
63  addParam("selectLowest", m_selectLowest, "If true, candidate with lower values of ``variable`` are better, otherwise higher is better", false);
64  addParam("allowMultiRank", m_allowMultiRank, "If true, candidates with identical values get identical rank", false);
65  addParam("numBest", m_numBest, "Keep only particles with this rank or better. If ``allowMultiRank=False`` this is "
66  "identical to the maximum amount of candidates left in the list. Otherwise there may be more candidates if "
67  "some share the same rank (0: keep all)", 0);
68  addParam("cut", m_cutParameter, "Only candidates passing the cut will be ranked. The others will have rank -1.", std::string(""));
69  addParam("outputVariable", m_outputVariableName,
70  "Name for created variable, which contains the rank for the particle. If not provided, the standard name ``${variable}_rank`` is used.");
71 
72 }
73 
74 BestCandidateSelectionModule::~BestCandidateSelectionModule() = default;
75 
76 void BestCandidateSelectionModule::initialize()
77 {
78  m_particles.isRequired();
79  m_inputList.isRequired(m_inputListName);
80 
81  m_variable = Variable::Manager::Instance().getVariable(m_variableName);
82  if (!m_variable) {
83  B2ERROR("Variable '" << m_variableName << "' is not available in Variable::Manager!");
84  }
85  if (m_numBest < 0) {
86  B2ERROR("value of numBest must be >= 0!");
87  }
88  m_cut = Variable::Cut::compile(m_cutParameter);
89 
90  // parse the name that the rank will be stored under
91  if (m_outputVariableName.empty()) {
92  std::string root_compatible_VariableName = makeROOTCompatible(m_variableName);
93  m_outputVariableName = root_compatible_VariableName + "_rank";
94  }
95 }
96 
97 void BestCandidateSelectionModule::event()
98 {
99  // input list
100  if (!m_inputList) {
101  B2WARNING("Input list " << m_inputList.getName() << " was not created?");
102  return;
103  }
104 
105  // create list of particle index and the corresponding value of variable
106  typedef std::pair<double, unsigned int> ValueIndexPair;
107  std::vector<ValueIndexPair> valueToIndex;
108  const unsigned int numParticles = m_inputList->getListSize();
109  valueToIndex.reserve(numParticles);
110  for (const Particle& p : *m_inputList) {
111  double value = m_variable->function(&p);
112  valueToIndex.emplace_back(value, p.getArrayIndex());
113  }
114 
115  // use stable sort to make sure we keep the relative order of elements with
116  // same value as it was before
117  if (m_selectLowest) {
118  std::stable_sort(valueToIndex.begin(), valueToIndex.end(), ValueIndexPairSorting::lowerPair<ValueIndexPair>);
119  } else {
120  std::stable_sort(valueToIndex.begin(), valueToIndex.end(), ValueIndexPairSorting::higherPair<ValueIndexPair>);
121  }
122 
123  // assign ranks and (optionally) remove everything but best candidates
124  m_inputList->clear();
125  int rank{1};
126  double previous_val{0};
127  bool first_candidate{true};
128  for (const auto& candidate : valueToIndex) {
129  Particle* p = m_particles[candidate.second];
130  if (!m_cut->check(p)) {
131  p->addExtraInfo(m_outputVariableName, -1);
132  m_inputList->addParticle(p);
133  continue;
134  }
135  if (first_candidate) {
136  first_candidate = false;
137  } else {
138  if (!m_allowMultiRank || (candidate.first != previous_val)) ++rank;
139  }
140 
141  if (!p->hasExtraInfo(m_outputVariableName))
142  p->addExtraInfo(m_outputVariableName, rank);
143  m_inputList->addParticle(p);
144 
145  previous_val = candidate.first;
146 
147  if (m_numBest != 0 and rank >= m_numBest)
148  break;
149  }
150 }
Ranks particles by the values of a variable.
Class to store reconstructed particles.
Definition: Particle.h:74
std::string makeROOTCompatible(std::string str)
Remove special characters that ROOT dislikes in branch names, e.g.
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Definition: Module.h:650
Abstract base class for different kinds of events.