GGS(GenericGEANT4Simulation)Software  2.99.0
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Macros
Data Structures | Public Member Functions
GGSTRootReader Class Reference

Class to manage ROOT output readers. More...

#include <GGSTRootReader.h>

Inheritance diagram for GGSTRootReader:
Inheritance graph
[legend]

Public Member Functions

 GGSTRootReader ()
 Constructor.
 
 ~GGSTRootReader ()
 Destructor.
 
GGSTFilesHandlerOpen (const std::string &fileName, GGSTFilesHandler *filesHandler=nullptr, bool force=false)
 Open ROOT files. More...
 
GGSTFilesHandlerOpen (const char *fileName, GGSTFilesHandler *filesHandler=nullptr, bool force=false)
 Open ROOT files. More...
 
bool OpenFile (const char *fileName)
 Opens a ROOT file. More...
 
template<class T >
T * GetReader (GGSTFilesHandler *filesHandler=nullptr, const TString &treeName="")
 Get a chain reader. More...
 
void GetEntry (Long64_t entry)
 Reads an event. More...
 
Long64_t GetEntries ()
 The total number of events. More...
 
Long64_t GetReadEntry ()
 Returns the current entry (event). More...
 
const GGSTSimInfoGetSimInfo (const GGSTFilesHandler *filesHandler=nullptr)
 Returns the simulation informations. More...
 
const GGSTGeoParamsGetGeoParams (const GGSTFilesHandler *filesHandler=nullptr)
 Returns the geometry parameters. More...
 
const GGSTParametersGetGenParams (const GGSTFilesHandler *filesHandler=nullptr)
 Returns the generator parameters. More...
 
const TGeoManager * GetROOTGeometry (GGSTFilesHandler *filesHandler=nullptr)
 Returns the simulation geometry in TGeo format. More...
 
bool HasROOTGeometry (GGSTFilesHandler *filesHandler=nullptr)
 Checks if the data files contains the detector geometry in TGeo format. More...
 

Detailed Description

Class to manage ROOT output readers.

GGS actions which write output on a ROOT file generally write each one on its own tree. So for each of these trees there should be a reader class to read back the data. GGSTRootReader simplifies the handling of multiple tree reader classes, by providing facilities for opening ROOT files and reading entries for all the trees. The main method of this class is the GetReader method. See its documentation for further details.

Definition at line 38 of file GGSTRootReader.h.

Member Function Documentation

Long64_t GGSTRootReader::GetEntries ( )

The total number of events.

This method returns the number of events in the event chain. Since all the chains are enforced to contain the same number of event when they are created, there is no ambiguity on the returned value even in presence of multiple chains. If no reader has already been retrieved by GetReader when this method is called then there is still no chain. This is because chains are created when calling GetReader to connect each reader to its chain and branches. In this case a "blind" number of entries is returned: the files belonging to the files handler created by the first call to Open are scanned and when the first TTree object is found a chain is created and the number of its entries is used as the return value. This value might be incorrect in some corner cases, e.g. if two handlers containing a different number of events are opened and the second one is the one which will be effectively used for the analysis.

Returns
The number of entries.

Definition at line 295 of file GGSTRootReader.cpp.

295  {
296  static const std::string routineName("GGSTRootReader::GetEntries");
297 
298  if (_readers.size() > 0)
299  return _readers[0]->chain->GetEntries();
300  else {
301  GGSCOUT(WARNING) << "GetEntries may return a wrong number of entries when called before GetReader." << GGSENDL;
302  return _GetEntriesBlind();
303  }
304 }
#define GGSENDL
Definition: GGSSmartLog.h:131
void GGSTRootReader::GetEntry ( Long64_t  entry)

Reads an event.

This method reads the event specified by entry. It calls GetEntry for every chain associated with the already instantiated readers (

See Also
GetReader), so that every reader makes reference to the current event.
Parameters
entryThe event to be read.

Definition at line 287 of file GGSTRootReader.cpp.

287  {
288 
289  for (unsigned int i = 0; i < _readers.size(); i++) {
290  _readers[i]->reader->GetEntry(entry);
291  }
292  _currentEv = entry;
293 }
const GGSTParameters * GGSTRootReader::GetGenParams ( const GGSTFilesHandler filesHandler = nullptr)

Returns the generator parameters.

Parameters
filesHandlerThe handler to the file(s) containing the desired info object. If nullptr then the handler returned by the first invocation of Open will be automatically used.
Returns
pointer to the geometry parameters object.
nullptr if an invalid filesHandler is used as argument, if no file(s) has still been opened or if the geometry parameters are not available.

Definition at line 330 of file GGSTRootReader.cpp.

330  {
331 
332  if (filesHandler == nullptr) {
333  if (_filesHandlers.size() > 0)
334  filesHandler = _filesHandlers[0];
335  else
336  return nullptr;
337  }
338 
339  return &(filesHandler->_genParams);
340 }
const GGSTGeoParams * GGSTRootReader::GetGeoParams ( const GGSTFilesHandler filesHandler = nullptr)

Returns the geometry parameters.

Parameters
filesHandlerThe handler to the file(s) containing the desired info object. If nullptr then the handler returned by the first invocation of Open will be automatically used.
Returns
pointer to the geometry parameters object.
nullptr if an invalid filesHandler is used as argument, if no file(s) has still been opened or if the geometry parameters are not available.

Definition at line 318 of file GGSTRootReader.cpp.

318  {
319 
320  if (filesHandler == nullptr) {
321  if (_filesHandlers.size() > 0)
322  filesHandler = _filesHandlers[0];
323  else
324  return nullptr;
325  }
326 
327  return &(filesHandler->_geoParams);
328 }
Long64_t GGSTRootReader::GetReadEntry ( )
inline

Returns the current entry (event).

Returns
The current entry.

Definition at line 161 of file GGSTRootReader.h.

161 { return _currentEv; }
template<class T >
T * GGSTRootReader::GetReader ( GGSTFilesHandler filesHandler = nullptr,
const TString &  treeName = "" 
)

Get a chain reader.

The template argument T is the class name of a reader class, which must inherit from GGSTChainReader. The method will return a pointer to a reader of class T for the specified tree, eventually chaining all the files handled by the GGSTFilesHandler passed as first argument. The reader will be automatically set to current entry.

If a nullptr value is passed for GGSTFilesHandler then the first handler (i.e. the file(s) opened with the first call to Open) will be used. If an empty std::string is passed for treeName, then the default tree name will be used.

Parameters
filesHandlerHandler to the Root files to be read by the reader.
treeNameThe name of the tree to be read by the reader T.
Returns
Pointer to the reader (or nullptr if tree could not be found in files handled by the handler).

Definition at line 245 of file GGSTRootReader.h.

245  {
246 
247  static const char *routineName = "GGSTRootReader::GetReader";
248 
249  // Set filesHandler to first handler if no handler is provided
250  if (filesHandler == nullptr) {
251  if (_filesHandlers.size() > 0)
252  filesHandler = _filesHandlers[0];
253  }
254 
255  // Set default tree name if no name is provided
256  TString tName(treeName);
257  if (tName == "") {
258  tName = "GGSEventsTree";
259  }
260 
261  // Search the tree in stored trees (i.e., already requested by a reader)
262  for (unsigned int iReader = 0; iReader < _readers.size(); iReader++) {
263  if (_readers[iReader]->filesHandler == filesHandler && _readers[iReader]->chain->GetName() == tName) {
264  // Check if found reader is of the desired type
265  T *retVal = dynamic_cast<T *>(_readers[iReader]->reader);
266  if (retVal) {
267  return retVal;
268  }
269  }
270  }
271 
272  // Search for chain
273  TChain *chain = _FindChain(tName, filesHandler);
274  if (chain) {
275  T *reader = new T;
276  // Read first entry if no entry has been read yet.
277  // This is necessary in order to make branches available so that readers can check for branch match in their
278  // SetChain methods.
279  if (chain->GetReadEntry() < 0)
280  chain->GetEntry(0);
281  if (reader->SetChain(chain)) {
282  // Reset the read entry to -1, to avoid missing to read the first event with some readers.
283  chain->GetEntry(-1);
284  for (unsigned int iReader = 0; iReader < _readers.size(); iReader++) {
285  if (chain->GetEntries() != _readers[iReader]->chain->GetEntries()) {
286  GGSCOUT(WARNING) << routineName << "Event number for the requested reader (" << chain->GetEntries()
287  << ") and for reader no. " << iReader << " (" << _readers[iReader]->chain->GetEntries()
288  << ") do not match. The reader has not been created." << std::endl;
289  delete reader;
290  return nullptr;
291  }
292  }
293  if (_currentEv != -1)
294  reader->GetEntry(_currentEv);
295  _readers.push_back(new ReadersInfo());
296  _readers.back()->reader = reader;
297  _readers.back()->chain = chain;
298  _readers.back()->filesHandler = filesHandler;
299  return reader;
300  } else {
301  GGSCOUT(WARNING) << "Tree " << tName
302  << " cannot be read by the requested reader. The reader has not been created." << std::endl;
303  chain->GetEntry(-1);
304  delete reader;
305  return nullptr;
306  }
307  } else {
308  GGSCOUT(WARNING) << "Can't find tree " << tName << ". The reader has not been created." << GGSENDL;
309  return nullptr;
310  }
311 }
#define GGSENDL
Definition: GGSSmartLog.h:131
const TGeoManager * GGSTRootReader::GetROOTGeometry ( GGSTFilesHandler filesHandler = nullptr)

Returns the simulation geometry in TGeo format.

Parameters
filesHandlerThe handler to the file(s) containing the desired info object. If nullptr then the handler returned by the first invocation of Open will be automatically used.
Returns
pointer to the geometry manager.
nullptr if an invalid filesHandler is used as argument, if no file(s) has still been opened or if the geometry manager is not available.

Definition at line 342 of file GGSTRootReader.cpp.

342  {
343  if (filesHandler == nullptr) {
344  if (_filesHandlers.size() > 0)
345  filesHandler = _filesHandlers[0];
346  else
347  return nullptr;
348  }
349  if (!(filesHandler->_geoManager)) {
350  if (filesHandler->_chains.size() != 0) {
351  auto readEntry = filesHandler->_chains[0]->GetReadEntry();
352  filesHandler->_chains[0]->GetEntry(0);
353  if (GGSSmartLog::verboseLevel < GGSSmartLog::DEBUG) {
354  GGSSmartLog::MuteOutput();
355  }
356  filesHandler->_geoManager = (TGeoManager *)(filesHandler->_chains[0]->GetCurrentFile()->Get("GGSGeometry"));
357  GGSSmartLog::UnmuteOutput();
358  filesHandler->_chains[0]->GetEntry(readEntry);
359  } else if (filesHandler->_files.size() != 0) {
360  TFile *tGeoFile = TFile::Open(filesHandler->_files[0].c_str());
361  filesHandler->_geoManager = (TGeoManager *)(tGeoFile->Get("GGSGeometry"));
362  tGeoFile->Close();
363  delete tGeoFile;
364  }
365  }
366 
367  return filesHandler->_geoManager;
368 }
const GGSTSimInfo * GGSTRootReader::GetSimInfo ( const GGSTFilesHandler filesHandler = nullptr)

Returns the simulation informations.

Since this class can manage many handlers, the user can specify from which of them the simulation informations must be read. If no handler is specified, then the one obtained with the first call to Open will be used. All the files belonging to the same handler are forced to have the same GGSTSimInfo object, except for the initial seeds.

Parameters
filesHandlerThe handler to the file(s) containing the desired info object. If nullptr then the handler returned by the first invocation of Open will be automatically used.
Returns
Pointer to simulation informations object.
nullptr if an invalid filesHandler is used as argument or if no file(s) has still been opened.

Definition at line 306 of file GGSTRootReader.cpp.

306  {
307 
308  if (filesHandler == nullptr) {
309  if (_filesHandlers.size() > 0)
310  filesHandler = _filesHandlers[0];
311  else
312  return nullptr;
313  }
314 
315  return &(filesHandler->_simInfo);
316 }
bool GGSTRootReader::HasROOTGeometry ( GGSTFilesHandler filesHandler = nullptr)

Checks if the data files contains the detector geometry in TGeo format.

This method checks if the TGeo geometry is available in the Root file without actually reading it. This is more efficient than checking the return value of GetROOTGeometry (which will read out the geometry from the file) when one just wants to know if the geometry is available without having to actually use it.

Parameters
filesHandlerThe handler to the file(s) containing the desired info object. If nullptr then the handler returned by the first invocation of Open will be automatically used.
Returns
true if the file contains the TGeo geometry.

Definition at line 370 of file GGSTRootReader.cpp.

370  {
371  if (filesHandler == nullptr) {
372  if (_filesHandlers.size() > 0)
373  filesHandler = _filesHandlers[0];
374  else
375  return false;
376  }
377  if (filesHandler->_geoManager) {
378  return true;
379  }
380 
381  TKey *geoKey = nullptr;
382  if (filesHandler->_chains.size() != 0) {
383  auto readEntry = filesHandler->_chains[0]->GetReadEntry();
384  filesHandler->_chains[0]->GetEntry(0);
385  if (GGSSmartLog::verboseLevel < GGSSmartLog::DEBUG) {
386  GGSSmartLog::MuteOutput();
387  }
388  geoKey = (filesHandler->_chains[0]->GetCurrentFile()->GetKey("GGSGeometry"));
389  GGSSmartLog::UnmuteOutput();
390  filesHandler->_chains[0]->GetEntry(readEntry);
391  } else if (filesHandler->_files.size() != 0) {
392  TFile *tGeoFile = TFile::Open(filesHandler->_files[0].c_str());
393  geoKey = tGeoFile->GetKey("GGSGeometry");
394  tGeoFile->Close();
395  delete tGeoFile;
396  }
397 
398  return geoKey;
399 }
GGSTFilesHandler * GGSTRootReader::Open ( const std::string &  fileName,
GGSTFilesHandler filesHandler = nullptr,
bool  force = false 
)

Open ROOT files.

The argument of this method can either be the name of a single file or multiple files, in turn specified using wildcards (*, ? and []) or the name of a txt file containing the full paths to the desired files (one per row). The reader will handle the files and return a pointer to a GGSTFilesHandler object handling all the files that have been opened.

When opening with wildcards the files will be sorted in alphabetical order, while when using the txt file the order will not be modified.

If the file(s) do not exist or in case of an error, a nullptr value will be returned. When opening multiple files a consistency check is done in order to assure that all the files have been produced in the same way. The check is based on the content of the GGSTSimInfo stored in each file, and currently it only checks that the content of each member of the GGSTSimInfo objects exactly match those of the GGSTSimInfo object contained in the first file. This means that two file produced with two datacards with different names will be considered as inconsistent, even if the content of the datacards was actually the same. Files which are inconsistent with respecto to the first one will be ignored. The consistency check can be turned off using the #force argument.

The pointer to the handler can eventually be passed to GetReader to specify which files the desired reader should use (see GetReader).

After a handler has been created by calling Open, more files can be added to it by passing it as the second argument to subsequent calls of Open. In this case the returned address will be equal to that of the argument. If an error occurs the method will return nullptr and the handler will not be modified (i.e. no files will be appended).

The reader retains the ownership of the handler objects it creates and will adopt eventual handlers instantiated explicitly by the user and passed to Open as the second argument (e.g. the user must not delete the handler in these cases)

Parameters
fileNamePath to Root file (eventually with wildcards) or to a txt file containing the list of desired Root files.
filesHandlerThe files handler to which the newly opened file will be appended. If nullptr a new handler will be created.
forceif true, no consistency check between different files will be done.
Returns
A pointer to a GGSTFilesHandler object handling the opened files (nullptr if the files do not exist or if an error has occurred).

Definition at line 34 of file GGSTRootReader.cpp.

34  {
35  static const std::string routineName("GGSTRootReader::Open");
36 
37  GGSTFilesHandler *handler = nullptr;
38  if (filesHandler == nullptr)
39  handler = new GGSTFilesHandler;
40  else {
41  handler = filesHandler;
42  }
43 
44  if (fileName.find('?') != std::string::npos || fileName.find('*') != std::string::npos) {
45  // ******* Name with wildcards *******
46 
47  // ++++ Convert fileName into a regular expression ++++
48  std::string regExpFiles(fileName);
49  // 1. escape all .
50  std::string::size_type pos = 0;
51  while ((pos = regExpFiles.find('.', pos)) != std::string::npos) {
52  regExpFiles.replace(pos, 1, "\\.");
53  pos += 2;
54  }
55  // 2. convert all * to .*
56  pos = 0;
57  while ((pos = regExpFiles.find('*', pos)) != std::string::npos) {
58  regExpFiles.replace(pos, 1, ".*");
59  pos += 2;
60  }
61  // 3. convert all ? to .
62  std::replace(regExpFiles.begin(), regExpFiles.end(), '?', '.');
63 
64  // ++++ Search files ++++
65  std::string basePathName(fileName);
66  // Extract path
67  size_t posOfLastSlash = basePathName.find_last_of('/');
68  if (posOfLastSlash != std::string::npos)
69  basePathName.erase(posOfLastSlash);
70  else
71  basePathName = std::filesystem::current_path().string();
72 
73  std::filesystem::path basePath(std::filesystem::absolute(basePathName));
74 
75  std::filesystem::directory_iterator endItr; // Default constructor yields past-the-end
76  std::filesystem::directory_iterator dirIter(basePath);
77  if (dirIter == endItr) {
78  if (filesHandler == nullptr) {
79  delete handler;
80  }
81  return nullptr;
82  }
83 
84  for (; dirIter != endItr; ++dirIter) {
85  // Skip if not a file
86  if (!std::filesystem::is_regular_file(dirIter->status()))
87  continue;
88  std::smatch what;
89  // Skip if no match
90  auto pathStr = dirIter->path().string();
91  if (!std::regex_match(pathStr, what, std::regex(regExpFiles)))
92  continue;
93  // Skip if not a Root file
94  if (pathStr.substr(pathStr.size() - 5) != ".root")
95  continue;
96  // File matches, store it
97  handler->_AddFile(pathStr, force);
98  }
99  if (handler->GetNFiles() == 0) {
100  GGSCOUT(WARNING) << fileName << ": no file found." << GGSENDL;
101  delete handler;
102  return nullptr;
103  }
104  handler->_SortFiles();
105 
106  } else if (fileName.substr(fileName.size() - 4) == ".txt") {
107  // ******* Text file with file names *******
108  if (std::filesystem::exists(fileName)) {
109  std::ifstream file(fileName.data(), std::ios::in);
110  std::string currFile;
111  while (file.good()) {
112  getline(file, currFile);
113  if (std::filesystem::exists(currFile) && currFile.substr(currFile.size() - 5) == ".root")
114  handler->_AddFile(currFile, force);
115  }
116  } else {
117  if (filesHandler == nullptr) {
118  delete handler;
119  }
120  return nullptr;
121  }
122  } else if (fileName.substr(fileName.size() - 5) == ".root") {
123  // ******* Single root file *******
124  if (!handler->_AddFile(fileName, force)) {
125  if (filesHandler == nullptr) {
126  delete handler;
127  }
128  return nullptr;
129  }
130  } else {
131  if (filesHandler == nullptr) {
132  delete handler;
133  }
134  return nullptr;
135  }
136 
137  if (find(_filesHandlers.begin(), _filesHandlers.end(), handler) == _filesHandlers.end())
138  _filesHandlers.push_back(handler);
139  return handler;
140 }
#define GGSENDL
Definition: GGSSmartLog.h:131
Class to handle group of Root files.
unsigned int GetNFiles()
The number of files handled by this object.
GGSTFilesHandler* GGSTRootReader::Open ( const char *  fileName,
GGSTFilesHandler filesHandler = nullptr,
bool  force = false 
)
inline

Open ROOT files.

Overload with const char *.

Parameters
fileNamePath to Root file (eventually with wildcards) or to a txt file containing the list of desired Root files.
filesHandlerThe files handler to which the newly opened file will be appended. If nullptr a new handler will be created.
forceif true, no consistency check between different files will be done.
Returns
A pointer to a GGSTFilesHandler object handling the opened files (nullptr if file(s) do(es) not exist or if an error has occurred).

Definition at line 101 of file GGSTRootReader.h.

101  {
102  return Open(std::string(fileName), filesHandler, force);
103  }
GGSTFilesHandler * Open(const std::string &fileName, GGSTFilesHandler *filesHandler=nullptr, bool force=false)
Open ROOT files.
bool GGSTRootReader::OpenFile ( const char *  fileName)
inline

Opens a ROOT file.

This method is kept for backward compatibility. It opens a single Root file. The usage of this method is discouraged and it will be deprecated in some future release. The suggested method is Open.

Parameters
fileNamePath to file.
Returns
true if file opening was successful, false otherwise.

Definition at line 113 of file GGSTRootReader.h.

113 { return Open(fileName); }
GGSTFilesHandler * Open(const std::string &fileName, GGSTFilesHandler *filesHandler=nullptr, bool force=false)
Open ROOT files.

The documentation for this class was generated from the following files: