9#include <analysis/modules/VariablesToEventBasedTree/VariablesToEventBasedTreeModule.h>
12#include <analysis/dataobjects/ParticleList.h>
13#include <analysis/dataobjects/StringWrapper.h>
14#include <analysis/VariableManager/Manager.h>
15#include <analysis/VariableManager/Utility.h>
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>
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.");
41 vector<string> emptylist;
43 "Name of particle list with reconstructed particles. An empty ParticleList is not supported. Use the VariablesToNtupleModule for this use-case",
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.",
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.",
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);
58 std::tuple<std::string, std::map<int, unsigned int>> default_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.",
66 "Ignore override of file name via command line argument -o. Useful if you have multiple output modules in one path.",
false);
69 "If true, the branch __eventType__ is added. The eventType information is available from MC16 on.",
true);
80 if (!outputFileArgument.empty())
91 B2ERROR(
"Could not create file \"" <<
m_fileName <<
92 "\". Please set a valid root output file name (\"fileName\" module parameter).");
106 unordered_set<string> seen;
108 if (seen.find(varStr) != std::end(seen)) return true;
116 unordered_set<string> seenEventVariables;
119 if (seenEventVariables.find(varStr) != std::end(seenEventVariables)) return true;
120 seenEventVariables.insert(varStr);
134 m_tree->get().Branch(
"__run__", &
m_run,
"__run__/I");
146 B2INFO(
"EventExtraInfo is not registered. __eventType__ will be empty. The eventType is available from MC16 on.");
153 if (Variable::isCounterVariable(varStr)) {
154 B2WARNING(
"The counter '" << varStr
155 <<
"' is handled automatically by VariablesToEventBasedTree, you don't need to add it.");
162 B2ERROR(
"Variable '" << varStr <<
"' is not available in Variable::Manager!");
164 if (var->variabletype == Variable::Manager::VariableDataType::c_double) {
167 }
else if (var->variabletype == Variable::Manager::VariableDataType::c_int) {
170 }
else if (var->variabletype == Variable::Manager::VariableDataType::c_bool) {
178 for (
unsigned int i = 0; i <
m_variables.size(); ++i) {
186 B2ERROR(
"Variable '" << varStr <<
"' is not available in Variable::Manager!");
188 if (var->variabletype == Variable::Manager::VariableDataType::c_double) {
191 }
else if (var->variabletype == Variable::Manager::VariableDataType::c_int) {
194 }
else if (var->variabletype == Variable::Manager::VariableDataType::c_bool) {
208 B2FATAL(
"Couldn't find sample variable " <<
m_sampling_name <<
" via the Variable::Manager. Check the name!");
278 for (
unsigned int iPart = 0; iPart <
m_ncandidates; iPart++) {
281 B2WARNING(
"Maximum number of candidates exceeded in VariablesToEventBasedTree module. I will skip additional candidates");
286 const Particle* particle = particlelist->getParticle(iPart);
287 for (
unsigned int iVar = 0; iVar <
m_functions.size(); iVar++) {
288 if (std::holds_alternative<double>(
m_functions[iVar](particle))) {
290 }
else if (std::holds_alternative<int>(
m_functions[iVar](particle))) {
292 }
else if (std::holds_alternative<bool>(
m_functions[iVar](particle))) {
305 TDirectory::TContext directoryGuard(
m_file.get());
308 const bool writeError =
m_file->TestBit(TFile::kWriteError);
311 B2FATAL(
"A write error occurred while saving '" <<
m_fileName <<
"', please check if enough disk space is available.");
In the store you can park objects that have to be accessed by various modules.
@ c_DontWriteOut
Object/array should be NOT saved by output modules.
const std::string & getOutputFileOverride() const
Return overriden output file name, or "" if none was set.
static Environment & Instance()
Static method to get a reference to the Environment instance.
static std::string makeROOTCompatible(std::string str)
Remove special characters that ROOT dislikes in branch names, e.g.
void setDescription(const std::string &description)
Sets the description of the module.
void setPropertyFlags(unsigned int propertyFlags)
Sets the flags for the module properties.
@ c_ParallelProcessingCertified
This module can be run in parallel processing mode safely (All I/O must be done through the data stor...
@ c_TerminateInAllProcesses
When using parallel processing, call this module's terminate() function in all processes().
Class to store reconstructed particles.
static bool isOutputProcess()
Return true if the process is an output process.
static bool parallelProcessingUsed()
Returns true if multiple processes have been spawned, false in single-core mode.
bool isRequired(const std::string &name="")
Ensure this array/object has been registered previously.
Type-safe access to single objects in the data store.
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...
const Var * getVariable(std::string name)
Get the variable belonging to the given key.
static Manager & Instance()
get singleton instance.
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.
VariablesToEventBasedTreeModule()
Constructor.
int m_production
production ID (to distinguish MC samples)
StoreObjPtr< StringWrapper > m_stringWrapper
string wrapper storing the MCDecayString
int m_experiment
experiment number
bool m_storeEventType
If true, the branch eventType is added.
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.
bool m_ignoreCommandLineOverride
if true, ignore override of filename
std::string m_eventType
EventType to be filled.
StoreObjPtr< RootMergeable< TTree > > m_tree
The ROOT TNtuple for output.
std::shared_ptr< TFile > m_file
ROOT file for output.
float m_weight
weight of this event
std::string m_sampling_name
Variable name of sampling variable.
StoreObjPtr< EventExtraInfo > m_eventExtraInfo
pointer to EventExtraInfo
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.
std::string m_treeName
Name of the TTree.
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 ¶mVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
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.
Abstract base class for different kinds of events.
VariableDataType variabletype
data type of variable
A variable returning a floating-point value for a given Particle.
FunctionPtr function
Pointer to function.