Belle II Software  release-08-01-10
VariablesToEventBasedTreeModule.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/VariablesToEventBasedTree/VariablesToEventBasedTreeModule.h>
10 
11 // analysis
12 #include <analysis/dataobjects/ParticleList.h>
13 #include <analysis/dataobjects/StringWrapper.h>
14 #include <analysis/VariableManager/Manager.h>
15 #include <analysis/VariableManager/Utility.h>
16 
17 // framework
18 #include <framework/logging/Logger.h>
19 #include <framework/pcore/ProcHandler.h>
20 #include <framework/utilities/MakeROOTCompatible.h>
21 #include <framework/utilities/RootFileCreationManager.h>
22 #include <framework/core/ModuleParam.templateDetails.h>
23 #include <framework/core/Environment.h>
24 
25 #include <cmath>
26 
27 using namespace std;
28 using namespace Belle2;
29 
30 // Register module in the framework
31 REG_MODULE(VariablesToEventBasedTree);
32 
33 
34 VariablesToEventBasedTreeModule::VariablesToEventBasedTreeModule() :
35  Module(), m_tree("", DataStore::c_Persistent)
36 {
37  //Set module properties
38  setDescription("Calculate variables specified by the user for a given ParticleList and save them into a TTree. The Tree is event-based, meaning that the variables of each candidate for each event are saved in an array of a branch of the Tree.");
40 
41  vector<string> emptylist;
42  addParam("particleList", m_particleList,
43  "Name of particle list with reconstructed particles. An empty ParticleList is not supported. Use the VariablesToNtupleModule for this use-case",
44  std::string(""));
45  addParam("variables", m_variables,
46  "List of variables (or collections) to save for each candidate. Variables are taken from Variable::Manager, and are identical to those available to e.g. ParticleSelector.",
47  emptylist);
48 
49  addParam("event_variables", m_event_variables,
50  "List of variables (or collections) to save for each event. Variables are taken from Variable::Manager, and are identical to those available to e.g. ParticleSelector. Only event-based variables are allowed here.",
51  emptylist);
52 
53  addParam("fileName", m_fileName, "Name of ROOT file for output. Can be overridden using the -o argument of basf2.",
54  string("VariablesToEventBasedTree.root"));
55  addParam("treeName", m_treeName, "Name of the NTuple in the saved file.", string("tree"));
56  addParam("maxCandidates", m_maxCandidates, "The maximum number of candidates in the ParticleList per entry of the Tree.", 100u);
57 
58  std::tuple<std::string, std::map<int, unsigned int>> default_sampling{"", {}};
59  addParam("sampling", m_sampling,
60  "Tuple of variable name and a map of integer values and inverse sampling rate. E.g. (signal, {1: 0, 0:10}) selects all signal events and every 10th background event. Variable must be event-based.",
61  default_sampling);
62 
63  addParam("fileNameSuffix", m_fileNameSuffix, "The suffix of the output ROOT file to be appended before ``.root``.",
64  string(""));
65 }
66 
68 {
69  m_eventMetaData.isRequired();
71 
72  // override the output file name with what's been provided with the -o option
73  const std::string& outputFileArgument = Environment::Instance().getOutputFileOverride();
74  if (!outputFileArgument.empty())
75  m_fileName = outputFileArgument;
76 
77  if (!m_fileNameSuffix.empty())
78  m_fileName = m_fileName.insert(m_fileName.rfind(".root"), m_fileNameSuffix);
79 
80  // See if there is already a file in which case add a new tree to it ...
81  // otherwise create a new file (all handled by framework)
83  if (!m_file) {
84  B2ERROR("Could not create file \"" << m_fileName <<
85  "\". Please set a valid root output file name (\"fileName\" module parameter).");
86  return;
87  }
88 
89  m_file->cd();
90 
91  // check if TTree with that name already exists
92  if (m_file->Get(m_treeName.c_str())) {
93  B2FATAL("Tree with the name " << m_treeName << " already exists in the file " << m_fileName);
94  return;
95  }
96 
98  // remove duplicates from list of variables but keep the previous order
99  unordered_set<string> seen;
100  auto newEnd = remove_if(m_variables.begin(), m_variables.end(), [&seen](const string & varStr) {
101  if (seen.find(varStr) != std::end(seen)) return true;
102  seen.insert(varStr);
103  return false;
104  });
105  m_variables.erase(newEnd, m_variables.end());
106 
108  // remove duplicates from list of variables but keep the previous order
109  unordered_set<string> seenEventVariables;
110  auto eventVariablesEnd = remove_if(m_event_variables.begin(),
111  m_event_variables.end(), [&seenEventVariables](const string & varStr) {
112  if (seenEventVariables.find(varStr) != std::end(seenEventVariables)) return true;
113  seenEventVariables.insert(varStr);
114  return false;
115  });
116  m_event_variables.erase(eventVariablesEnd, m_event_variables.end());
117 
118  m_tree.registerInDataStore(m_fileName + m_treeName, DataStore::c_DontWriteOut);
119  m_tree.construct(m_treeName.c_str(), "");
120 
121  m_valuesDouble.resize(m_variables.size());
122  m_valuesInt.resize(m_variables.size());
124  m_event_valuesInt.resize(m_event_variables.size());
125 
126  m_tree->get().Branch("__event__", &m_event, "__event__/i");
127  m_tree->get().Branch("__run__", &m_run, "__run__/I");
128  m_tree->get().Branch("__experiment__", &m_experiment, "__experiment__/I");
129  m_tree->get().Branch("__production__", &m_production, "__production__/I");
130  m_tree->get().Branch("__ncandidates__", &m_ncandidates, "__ncandidates__/I");
131  m_tree->get().Branch("__weight__", &m_weight, "__weight__/F");
132 
133  if (m_stringWrapper.isOptional("MCDecayString"))
134  m_tree->get().Branch("__MCDecayString__", &m_MCDecayString);
135 
136  for (unsigned int i = 0; i < m_event_variables.size(); ++i) {
137  auto varStr = m_event_variables[i];
138 
139  if (Variable::isCounterVariable(varStr)) {
140  B2WARNING("The counter '" << varStr
141  << "' is handled automatically by VariablesToEventBasedTree, you don't need to add it.");
142  continue;
143  }
144 
145  //also collection function pointers
147  if (!var) {
148  B2ERROR("Variable '" << varStr << "' is not available in Variable::Manager!");
149  } else {
150  if (var->variabletype == Variable::Manager::VariableDataType::c_double) {
151  m_tree->get().Branch(MakeROOTCompatible::makeROOTCompatible(varStr).c_str(), &m_event_valuesDouble[i],
152  (MakeROOTCompatible::makeROOTCompatible(varStr) + "/D").c_str());
153  } else if (var->variabletype == Variable::Manager::VariableDataType::c_int) {
154  m_tree->get().Branch(MakeROOTCompatible::makeROOTCompatible(varStr).c_str(), &m_event_valuesInt[i],
155  (MakeROOTCompatible::makeROOTCompatible(varStr) + "/I").c_str());
156  } else if (var->variabletype == Variable::Manager::VariableDataType::c_bool) {
157  m_tree->get().Branch(MakeROOTCompatible::makeROOTCompatible(varStr).c_str(), &m_event_valuesInt[i],
158  (MakeROOTCompatible::makeROOTCompatible(varStr) + "/O").c_str());
159  }
160  m_event_functions.push_back(var->function);
161  }
162  }
163 
164  for (unsigned int i = 0; i < m_variables.size(); ++i) {
165  auto varStr = m_variables[i];
166  m_valuesDouble[i].resize(m_maxCandidates);
167  m_valuesInt[i].resize(m_maxCandidates);
168 
169  //also collection function pointers
171  if (!var) {
172  B2ERROR("Variable '" << varStr << "' is not available in Variable::Manager!");
173  } else {
174  if (var->variabletype == Variable::Manager::VariableDataType::c_double) {
175  m_tree->get().Branch(MakeROOTCompatible::makeROOTCompatible(varStr).c_str(), &m_valuesDouble[i][0],
176  (MakeROOTCompatible::makeROOTCompatible(varStr) + "[__ncandidates__]/D").c_str());
177  } else if (var->variabletype == Variable::Manager::VariableDataType::c_int) {
178  m_tree->get().Branch(MakeROOTCompatible::makeROOTCompatible(varStr).c_str(), &m_valuesInt[i][0],
179  (MakeROOTCompatible::makeROOTCompatible(varStr) + "[__ncandidates__]/I").c_str());
180  } else if (var->variabletype == Variable::Manager::VariableDataType::c_bool) {
181  m_tree->get().Branch(MakeROOTCompatible::makeROOTCompatible(varStr).c_str(), &m_valuesInt[i][0],
182  (MakeROOTCompatible::makeROOTCompatible(varStr) + "[__ncandidates__]/O").c_str());
183  }
184  m_functions.push_back(var->function);
185  }
186  }
187 
188  m_sampling_name = std::get<0>(m_sampling);
189  m_sampling_rates = std::get<1>(m_sampling);
190 
191  if (m_sampling_name != "") {
193  if (m_sampling_variable == nullptr) {
194  B2FATAL("Couldn't find sample variable " << m_sampling_name << " via the Variable::Manager. Check the name!");
195  }
196  for (const auto& pair : m_sampling_rates)
197  m_sampling_counts[pair.first] = 0;
198  } else {
199  m_sampling_variable = nullptr;
200  }
201 
202 }
203 
204 
206 {
207 
208  if (m_sampling_variable == nullptr)
209  return 1.0;
210 
211  long target = 0;
212  if (m_sampling_variable->variabletype == Variable::Manager::VariableDataType::c_double) {
213  target = std::lround(std::get<double>(m_sampling_variable->function(nullptr)));
214  } else if (m_sampling_variable->variabletype == Variable::Manager::VariableDataType::c_int) {
215  target = std::lround(std::get<int>(m_sampling_variable->function(nullptr)));
216  } else if (m_sampling_variable->variabletype == Variable::Manager::VariableDataType::c_bool) {
217  target = std::lround(std::get<bool>(m_sampling_variable->function(nullptr)));
218  }
219 
220  if (m_sampling_rates.find(target) != m_sampling_rates.end() and m_sampling_rates[target] > 0) {
221  m_sampling_counts[target]++;
222  if (m_sampling_counts[target] % m_sampling_rates[target] != 0)
223  return 0;
224  else {
225  m_sampling_counts[target] = 0;
226  return m_sampling_rates[target];
227  }
228  }
229 
230  return 1.0;
231 }
232 
234 {
235  // get counter numbers
236  m_event = m_eventMetaData->getEvent();
237  m_run = m_eventMetaData->getRun();
238  m_experiment = m_eventMetaData->getExperiment();
239  m_production = m_eventMetaData->getProduction();
240 
241  if (m_stringWrapper.isValid())
242  m_MCDecayString = m_stringWrapper->getString();
243  else
244  m_MCDecayString = "";
245 
247  m_ncandidates = particlelist->getListSize();
249  if (m_weight > 0) {
250  for (unsigned int iVar = 0; iVar < m_event_functions.size(); iVar++) {
251  if (std::holds_alternative<double>(m_event_functions[iVar](nullptr))) {
252  m_event_valuesDouble[iVar] = std::get<double>(m_event_functions[iVar](nullptr));
253  } else if (std::holds_alternative<int>(m_event_functions[iVar](nullptr))) {
254  m_event_valuesInt[iVar] = std::get<int>(m_event_functions[iVar](nullptr));
255  } else if (std::holds_alternative<bool>(m_event_functions[iVar](nullptr))) {
256  m_event_valuesInt[iVar] = std::get<bool>(m_event_functions[iVar](nullptr));
257  }
258  }
259  for (unsigned int iPart = 0; iPart < m_ncandidates; iPart++) {
260 
261  if (iPart >= m_maxCandidates) {
262  B2WARNING("Maximum number of candidates exceeded in VariablesToEventBasedTree module. I will skip additional candidates");
264  break;
265  }
266 
267  const Particle* particle = particlelist->getParticle(iPart);
268  for (unsigned int iVar = 0; iVar < m_functions.size(); iVar++) {
269  if (std::holds_alternative<double>(m_functions[iVar](particle))) {
270  m_valuesDouble[iVar][iPart] = std::get<double>(m_functions[iVar](particle));
271  } else if (std::holds_alternative<int>(m_functions[iVar](particle))) {
272  m_valuesInt[iVar][iPart] = std::get<int>(m_functions[iVar](particle));
273  } else if (std::holds_alternative<bool>(m_functions[iVar](particle))) {
274  m_valuesInt[iVar][iPart] = std::get<bool>(m_functions[iVar](particle));
275  }
276  }
277  }
278  m_tree->get().Fill();
279  }
280 }
281 
283 {
285  B2INFO("Writing TTree " << m_treeName);
286  TDirectory::TContext directoryGuard(m_file.get());
287  m_tree->write(m_file.get());
288 
289  const bool writeError = m_file->TestBit(TFile::kWriteError);
290  if (writeError) {
291  B2FATAL("A write error occurred while saving '" << m_fileName << "', please check if enough disk space is available.");
292  }
293  }
294 }
In the store you can park objects that have to be accessed by various modules.
Definition: DataStore.h:51
@ c_DontWriteOut
Object/array should be NOT saved by output modules.
Definition: DataStore.h:71
const std::string & getOutputFileOverride() const
Return overriden output file name, or "" if none was set.
Definition: Environment.h:115
static Environment & Instance()
Static method to get a reference to the Environment instance.
Definition: Environment.cc:28
static std::string makeROOTCompatible(std::string str)
Remove special characters that ROOT dislikes in branch names, e.g.
Base class for Modules.
Definition: Module.h:72
void setDescription(const std::string &description)
Sets the description of the module.
Definition: Module.cc:214
void setPropertyFlags(unsigned int propertyFlags)
Sets the flags for the module properties.
Definition: Module.cc:208
@ c_ParallelProcessingCertified
This module can be run in parallel processing mode safely (All I/O must be done through the data stor...
Definition: Module.h:80
@ c_TerminateInAllProcesses
When using parallel processing, call this module's terminate() function in all processes().
Definition: Module.h:83
Class to store reconstructed particles.
Definition: Particle.h:75
static bool isOutputProcess()
Return true if the process is an output process.
Definition: ProcHandler.cc:232
static bool parallelProcessingUsed()
Returns true if multiple processes have been spawned, false in single-core mode.
Definition: ProcHandler.cc:226
bool isRequired(const std::string &name="")
Ensure this array/object has been registered previously.
Type-safe access to single objects in the data store.
Definition: StoreObjPtr.h:96
std::vector< std::string > resolveCollections(const std::vector< std::string > &variables)
Resolve Collection Returns variable names corresponding to the given collection or if it is not a col...
Definition: Manager.cc:179
const Var * getVariable(std::string name)
Get the variable belonging to the given key.
Definition: Manager.cc:57
static Manager & Instance()
get singleton instance.
Definition: Manager.cc:25
std::vector< std::string > m_variables
List of variables to save.
unsigned int m_maxCandidates
maximum number of candidates which is written out
std::vector< std::string > m_event_variables
List of event variables to save.
virtual void initialize() override
Initialises the module.
std::map< int, unsigned int > m_sampling_rates
Inverse sampling rates.
std::vector< int > m_event_valuesInt
Values of type int corresponding to given event variables.
virtual void event() override
Method called for each event.
unsigned int m_ncandidates
number of candidates in this event
virtual void terminate() override
Write TTree to file, and close file if necessary.
StoreObjPtr< EventMetaData > m_eventMetaData
event metadata (get event number etc)
std::map< int, unsigned long int > m_sampling_counts
Current number of samples with this value.
std::string m_fileName
Name of ROOT file for output.
std::tuple< std::string, std::map< int, unsigned int > > m_sampling
Tuple of variable name and a map of integer values and inverse sampling rate.
std::vector< std::vector< double > > m_valuesDouble
Values of type double corresponding to given variables.
float getInverseSamplingRateWeight()
Calculate inverse sampling rate weight.
int m_production
production ID (to distinguish MC samples)
StoreObjPtr< StringWrapper > m_stringWrapper
string wrapper storing the MCDecayString
std::vector< Variable::Manager::FunctionPtr > m_functions
List of function pointers corresponding to given variables.
std::string m_particleList
Name of particle list with reconstructed particles.
StoreObjPtr< RootMergeable< TTree > > m_tree
The ROOT TNtuple for output.
std::shared_ptr< TFile > m_file
ROOT file for output.
std::string m_sampling_name
Variable name of sampling variable.
std::vector< std::vector< int > > m_valuesInt
Values of type int corresponding to given variables.
std::vector< double > m_event_valuesDouble
Values of type double corresponding to given event variables.
const Variable::Manager::Var * m_sampling_variable
Variable Pointer to target variable.
std::vector< Variable::Manager::FunctionPtr > m_event_functions
List of function pointers corresponding to given event variables.
std::string m_fileNameSuffix
Suffix to be appended to the output file name.
std::string m_MCDecayString
MC decay string to be filled.
void addParam(const std::string &name, T &paramVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
Definition: Module.h:560
std::shared_ptr< TFile > getFile(std::string, bool ignoreErrors=false)
Get a file with a specific name, if is does not exist it will be created.
static RootFileCreationManager & getInstance()
Interface for the FileManager.
#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.
VariableDataType variabletype
data type of variable
Definition: Manager.h:133
A variable returning a floating-point value for a given Particle.
Definition: Manager.h:146
FunctionPtr function
Pointer to function.
Definition: Manager.h:147