9#include <arich/modules/arichToNtuple/arichToNtupleModule.h>
11#include <arich/dataobjects/ARICHLikelihood.h>
12#include <arich/dataobjects/ARICHAeroHit.h>
13#include <arich/dataobjects/ARICHTrack.h>
14#include <arich/dataobjects/ARICHPhoton.h>
15#include <arich/dataobjects/ARICHHit.h>
16#include <mdst/dataobjects/Track.h>
17#include <tracking/dataobjects/ExtHit.h>
20#include <analysis/dataobjects/ParticleList.h>
21#include <analysis/VariableManager/Manager.h>
22#include <analysis/VariableManager/Utility.h>
25#include <framework/logging/Logger.h>
26#include <framework/pcore/ProcHandler.h>
27#include <framework/core/ModuleParam.templateDetails.h>
29#include <framework/datastore/DataStore.h>
30#include <framework/datastore/StoreArray.h>
33#include <framework/utilities/MakeROOTCompatible.h>
34#include <framework/utilities/RootFileCreationManager.h>
48 setDescription(
"Local arich extension of VariblesToNtuple module to append detailed arich information to reconstructed candidates in the analysis output Ntuple. The TNtuple is candidate-based, meaning that the variables of each candidate are saved separate rows.");
51 std::vector<std::string> emptylist;
53 "Name of particle list with reconstructed particles. If no list is provided the variables are saved once per event (only possible for event-type variables)",
56 "Decay string with selected particles to which arich info should be appened", std::string(
""));
58 "List of variables (or collections) to save. Variables are taken from Variable::Manager, and are identical to those available to e.g. ParticleSelector.",
61 "List of aliases for particles to which arich info will be appended (used for tree branch names)",
64 addParam(
"fileName",
m_fileName,
"Name of ROOT file for output.", std::string(
"arichToNtuple.root"));
65 addParam(
"treeName",
m_treeName,
"Name of the NTuple in the saved file.", std::string(
"ntuple"));
67 std::tuple<std::string, std::map<int, unsigned int>> default_sampling{
"", {}};
69 "Tuple of variable name and a map of integer values and inverse sampling rate. E.g. (signal, {1: 0, 0:10}) selects all signal candidates and every 10th background candidate.",
92 B2FATAL(
"Output root file name is not set. Please set a vaild root output file name (\"fileName\" module parameter).");
98 B2ERROR(
"Could not create file \"" <<
m_fileName <<
99 "\". Please set a vaild root output file name (\"fileName\" module parameter).");
103 TDirectory::TContext directoryGuard(
m_file.get());
108 <<
"\" already exists in the file \"" <<
m_fileName <<
"\"\n"
109 <<
"\nYou probably want to either set the output fileName or the treeName to something else:\n\n"
110 <<
" from modularAnalysis import arichToNtuple\n"
111 <<
" arichToNtuple('pi+:all', ['p'], treename='pions', filename='arichToNtuple.root')\n"
112 <<
" arichToNtuple('gamma:all', ['p'], treename='photons', filename='arichToNtuple.root') # two trees, same file\n"
114 <<
" from modularAnalysis import arichToNtuple\n"
115 <<
" arichToNtuple('pi+:all', ['p'], filename='pions.root')\n"
116 <<
" arichToNtuple('gamma:all', ['p'], filename='photons.root') # two files\n"
124 m_tree->get().SetCacheSize(100000);
128 m_tree->get().Branch(
"__run__", &
m_run,
"__run__/I");
135 if (Variable::isCounterVariable(variable)) {
136 B2WARNING(
"The counter '" << variable
137 <<
"' is handled automatically by arichToNtuple, you don't need to add it.");
144 size_t enumerate = 1;
153 B2ERROR(
"Variable '" << varStr <<
"' is not available in Variable::Manager!");
166 m_tree->get().SetBasketSize(
"*", 1600);
174 B2FATAL(
"Couldn't find sample variable " <<
m_sampling_name <<
" via the Variable::Manager. Check the name!");
218 for (
unsigned int iVar = 0; iVar <
m_variables.size(); iVar++) {
219 if (std::holds_alternative<double>(
m_functions[iVar](
nullptr))) {
221 }
else if (std::holds_alternative<int>(
m_functions[iVar](
nullptr))) {
223 }
else if (std::holds_alternative<bool>(
m_functions[iVar](
nullptr))) {
227 for (
auto& arich :
m_arich) arich->clear();
235 for (
unsigned int iPart = 0; iPart <
m_ncandidates; iPart++) {
237 const Particle* particle = particlelist->getParticle(iPart);
240 for (
unsigned int iVar = 0; iVar <
m_variables.size(); iVar++) {
241 if (std::holds_alternative<double>(
m_functions[iVar](particle))) {
243 }
else if (std::holds_alternative<int>(
m_functions[iVar](particle))) {
245 }
else if (std::holds_alternative<bool>(
m_functions[iVar](particle))) {
249 for (
auto& arich :
m_arich) arich->clear();
261 TDirectory::TContext directoryGuard(
m_file.get());
264 const bool writeError =
m_file->TestBit(TFile::kWriteError);
267 B2FATAL(
"A write error occured while saving '" <<
m_fileName <<
"', please check if enough disk space is available.");
277 m_tree->get().Branch((name +
"_detPhot").c_str(), &tree->detPhot,
"detPhot/I");
278 m_tree->get().Branch((name +
"_expPhot").c_str(), &tree->expPhot,
"e/F:mu:pi:K:p:d");
279 m_tree->get().Branch((name +
"_logL").c_str(), &tree->logL,
"e/F:mu:pi:K:p:d");
280 m_tree->get().Branch((name +
"_recHit").c_str(), &tree->recHit,
"PDG/I:x/F:y:z:p:theta:phi");
281 m_tree->get().Branch((name +
"_mcHit").c_str(), &tree->mcHit,
"PDG/I:x/F:y:z:p:theta:phi");
282 m_tree->get().Branch((name +
"_winHit").c_str(), &tree->winHit,
"x/F:y");
283 m_tree->get().Branch((name +
"_photons").c_str(),
"std::vector<Belle2::ARICHPhoton>", &tree->photons);
292 for (
auto p : selParticles) {
293 const Track* track = p->getTrack();
294 if (!track)
continue;
295 for (
const ExtHit& hit : track->getRelationsTo<
ExtHit>()) {
306 ROOT::Math::XYZVector recPos = atrk->
getPosition();
307 m_arich[iTree]->recHit.x = recPos.X();
308 m_arich[iTree]->recHit.y = recPos.Y();
309 m_arich[iTree]->recHit.z = recPos.Z();
312 m_arich[iTree]->recHit.p = recMom.R();
313 m_arich[iTree]->recHit.theta = recMom.Theta();
314 m_arich[iTree]->recHit.phi = recMom.Phi();
338 ROOT::Math::XYZVector truePos = aeroHit->
getPosition();
339 m_arich[iTree]->mcHit.x = truePos.X();
340 m_arich[iTree]->mcHit.y = truePos.Y();
341 m_arich[iTree]->mcHit.z = truePos.Z();
343 ROOT::Math::XYZVector trueMom = aeroHit->
getMomentum();
344 m_arich[iTree]->mcHit.p = trueMom.R();
345 m_arich[iTree]->mcHit.theta = trueMom.Theta();
346 m_arich[iTree]->mcHit.phi = trueMom.Phi();
Datastore class that holds information on track parameters at the entrance in aerogel.
int getPDG() const
Get particle PDG identity number.
ROOT::Math::XYZVector getMomentum() const
Get track momentum (at entrance in 1. aerogel plane)
ROOT::Math::XYZVector getPosition() const
Get track position (at entrance in 1. aerogel plane)
This is a class to store ARICH likelihoods in the datastore.
float getDetPhot() const
Return number of detected photons for a given particle.
float getLogL(const Const::ChargedStable &part) const
Return log likelihood for a given particle.
float getExpPhot(const Const::ChargedStable &part) const
Return number of expected photons for a given particle.
Datastore class that holds position and momentum information of tracks that hit ARICH.
bool hitsWindow() const
Returns true if track hits HAPD window.
ROOT::Math::XYZVector getDirection() const
returns track direction vector
const std::vector< ARICHPhoton > & getPhotons() const
Returns vector of ARICHPhoton's associated with track.
ROOT::Math::XYZVector getPosition() const
returns track position vector
ROOT::Math::XYVector windowHitPosition() const
Get HAPD window hit position.
double getMomentum() const
returns track momentum
static const ChargedStable muon
muon particle
static const ChargedStable pion
charged pion particle
static const ChargedStable proton
proton particle
static const ChargedStable kaon
charged kaon particle
static const ChargedStable electron
electron particle
static const ChargedStable deuteron
deuteron particle
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.
bool init(const std::string &str)
Initialise the DecayDescriptor from given string.
std::vector< const Particle * > getSelectionParticles(const Particle *particle)
Get a vector of pointers with selected daughters in the decay tree.
Store one Ext hit as a ROOT object.
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.
T * getRelated(const std::string &name="", const std::string &namedRelation="") const
Get the object to or from which this object has a relation.
bool isRequired(const std::string &name="")
Ensure this array/object has been registered previously.
Accessor to arrays stored in the data store.
Type-safe access to single objects in the data store.
Class that bundles various TrackFitResults.
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< ARICH::ARICHTree * > m_arich
Vector of arich branch addresses.
void addARICHBranches(const std::string &name)
Add arich branches to the output TTree.
std::vector< std::string > m_variables
List of variables to save.
virtual void initialize() override
Initialises the module.
std::map< int, unsigned int > m_sampling_rates
Inverse sampling rates.
virtual void event() override
Method called for each event.
void fillARICHTree(const Particle *particle)
Fill data to arich branches.
unsigned int m_ncandidates
total n candidates
virtual void terminate() override
Write TTree to file, and close file if necessary.
StoreObjPtr< EventMetaData > m_eventMetaData
the event information
std::vector< double > m_branchAddresses
Variable branch addresses.
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.
int m_experiment
experiment number
std::vector< std::string > m_arichVariables
List of aliases of particles to which arich info will be appended (used for tree branch naming)
std::vector< Variable::Manager::FunctionPtr > m_functions
List of function pointers corresponding to given variables.
std::string m_arichSelector
Decay string with selected particles to which arich info should be appendend.
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.
DecayDescriptor m_decaydescriptor
Decay descriptor for selected particles to append arich info.
std::string m_sampling_name
Variable name of sampling variable.
arichToNtupleModule()
Constructor.
float getInverseSamplingRateWeight(const Particle *particle)
Calculate inverse sampling rate weight.
std::string m_treeName
Name of the TTree.
const Variable::Manager::Var * m_sampling_variable
Variable Pointer to target variable.
int m_candidate
candidate counter
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.
Structure of a flat ntuple.
VariableDataType variabletype
data type of variable
A variable returning a floating-point value for a given Particle.
FunctionPtr function
Pointer to function.