GGS(GenericGEANT4Simulation)Software  2.7.0
 All Data Structures Namespaces Files Functions Variables Typedefs Macros
Data Structures | Public Member Functions | Static Public Member Functions | Friends
GGSRootFileService Class Reference

Singleton for a centralized ROOT files management. More...

#include <GGSRootFileService.h>

Public Member Functions

 ~GGSRootFileService ()
 Destructor.
 
TFile * GetFileForThisRun (const path &baseName, const G4Run *run)
 Opens a file for a given run and returns a pointer to it. More...
 
void CloseFileForThisRun (const path &baseName)
 Closes the ROOT output file. More...
 
TTree * GetDefaultTree (TFile *file)
 Gets the default tree for this file. More...
 
void SetSuffix (const std::string &suffix)
 Sets the suffix for file names. More...
 
void SetDefaultFileBase (const path &newFileBase)
 Sets the default file name. More...
 
int StoreVolume (TFile *filePtr, const std::string &detector, const G4VPhysicalVolume *volume, const G4ThreeVector &position, int id)
 Set persistence for the specified volume. More...
 
void SetSimInfo (const GGSTSimInfo &simInfo)
 Set the simulation info object to be saved on output files. More...
 

Static Public Member Functions

static GGSRootFileServiceGetInstance ()
 Get reference to GGSRootFileService unique instance. More...
 

Friends

class GGSUserActionsManager
 
std::size_t hash_value (const VolumeKey &key)
 

Detailed Description

Singleton for a centralized ROOT files management.

The aim of this class is to provide a centralized management for ROOT output files. For each run, the singleton will provide pointers to output file to the action which may require them with the GetFileForThisRun method. The purpose of this is to allow multiple actions to write on the same ROOT file, avoiding the proliferation of output files when many actions are in use. Typically, the singleton will create a file the first time that file is requested; if subsequently other actions require the same file, the singleton will not open it again, but it will simply return a pointer to the already opened file. Consistently, file closure requests issued by calling CloseFileForThisRun will be ignored until no more actions require that file. Users wishing to use this service in their actions are demanded to call GetFileForThisRun in BeginOfRunAction to get the file and to close it with CloseFileForThisRun in EndOfRunAction. The service also provides a standard TTree called GGSEventsTree to let actions save their event data in different branches of the same tree rather than in different trees. This helps I/O performance. See GetDefaultTree.

Definition at line 46 of file GGSRootFileService.h.

Member Function Documentation

void GGSRootFileService::CloseFileForThisRun ( const path &  baseName)

Closes the ROOT output file.

The closure request is handled this way: if a file has been requested N times, it will be closed when this method is called for the N-th time. This will avoid to close the file when other actions may still need it.

WARNING: when a ROOT file is closed, all the TTree objects associated to it will be automatically deleted. User must NOT delete its trees before calling this method. Eg.:

outRootFile->cd(); outTree->Write(); GGSRootFileService::GetInstance().CloseFileForThisRun(outBase); //delete outTree; // Uncommenting this will generate a segfault

Parameters
baseNameThe file base name.

Definition at line 120 of file GGSRootFileService.cpp.

120  {
121 
122  path absBaseName;
123 
124  // Set default if no base name has been provided
125  if (baseName.string() == "") {
126  absBaseName = _defaultOutBase;
127  } else
128  absBaseName = baseName;
129  absBaseName = _GetAbsolutePath(absBaseName);
130 
131  for (FileInfoContainer::iterator iter = _files.begin(); iter != _files.end(); iter++)
132  if (iter->absBaseName == absBaseName) {
133  if (iter->nRequests > 1) {
134  iter->nRequests--;
135  return;
136  } else {
137  iter->filePtr->cd();
138  if (iter->defaultEventsTree)
139  iter->defaultEventsTree->Write();
140  if (iter->detectorsArray)
141  iter->detectorsArray->Write(
142  "GGSHitDetInfo",
143  TObject::kSingleKey); // Automatically set iter->detectorsArray ownership to iter->filePtr
144  iter->filePtr->Close();
145  delete iter->filePtr;
146  delete iter->detectorsMap;
147  iter = _files.erase(iter);
148  }
149  }
150 }
TTree * GGSRootFileService::GetDefaultTree ( TFile *  file)

Gets the default tree for this file.

This method returns the default events tree for the specified file. This is intended to allow user actions to write their output as branches of the same tree instead of using a tree for each action. In this way the best performance of the I/O system of ROOT can be exploited (see https://twiki.cern.ch/twiki/bin/view/LHCb/PersistencyMigration#POOL). The Fill() and Write() operations for the default tree are managed by GGSRootFileService. The only operation that can be done with the tree is the creation of a branch. Explicitly calling Fill() or Write() for the default tree in user actions will result in a wrong number of events and in multiple keys for the tree in the output file. Fill() will be automatically called at the end of each event after calling EndOfEventAction() for every user action.

Different default trees can be requested for different files.

Parameters
fileThe file on which the default tree will be saved. This file pointer must have been previously retrieved by calling GetFileForThisRun; DON'T use a file created in any other way.
Returns
a pointer to the default tree, NULL if file has not been created by GetFileForThisRun.

Definition at line 153 of file GGSRootFileService.cpp.

153  {
154 
155  for (FileInfoContainer::iterator iter = _files.begin(); iter != _files.end(); iter++) {
156  if (file == iter->filePtr) {
157  if (iter->defaultEventsTree == NULL) {
158  iter->filePtr->cd();
159  iter->defaultEventsTree = new TTree("GGSEventsTree", "GGS events tree. Info: ");
160  }
161  return iter->defaultEventsTree;
162  }
163  }
164  return NULL;
165 }
TFile * GGSRootFileService::GetFileForThisRun ( const path &  baseName,
const G4Run *  run 
)

Opens a file for a given run and returns a pointer to it.

This method will open a file for a given run and return a pointer to it; if the file is already opened, it will simply return the pointer without attempting to open it again. The created file will be named baseName.root for run 0 (eventually baseName_suffix.root if a suffix is specified calling SetSuffix); for subsequent runs, it will be named baseName_RunID.root (or baseName_RunID_suffix.root).

Parameters
baseNameThe file base name (.root extension, run ID and suffix will be (eventually) automatically appended). If no name is provided, the default one ("GGSRootOutput") will be used (it can also be set with SetDefaultFileBase).
runThe current run.
Returns
Pointer to the (eventually opened) output ROOT file.

Definition at line 52 of file GGSRootFileService.cpp.

52  {
53 
54  path absBaseName;
55 
56  // Set default if no base name has been provided
57  if (baseName.string() == "") {
58  absBaseName = _defaultOutBase;
59  } else
60  absBaseName = baseName;
61 
62  // Retrieve absolute path
63  absBaseName = _GetAbsolutePath(absBaseName);
64 
65  // check if the file is already opened
66  for (FileInfoContainer::iterator iter = _files.begin(); iter != _files.end(); iter++)
67  if (absBaseName == iter->absBaseName) {
68  iter->nRequests++;
69  return iter->filePtr;
70  }
71 
72  // Create new file info struct
73  FileInfo fInfo;
74  fInfo.nRequests = 1;
75  fInfo.absBaseName = absBaseName;
76 
77  // Strip extension and append suffix and extension
78  TString absFileName = _AppendSuffixAndExt(absBaseName, run);
79 
80  // Open file and store it
81  fInfo.filePtr = new TFile(absFileName, "RECREATE");
82  _files.push_back(fInfo);
83 
84  // Write simulation informations
85  _simInfo.Write();
86 
87  // Write geometry informations
89  GGSTGeoParams geoParams;
90  geoParams.SetIntGeoParams(geoCons->GetIntParameters());
91  geoParams.SetBoolGeoParams(geoCons->GetBoolParameters());
92  geoParams.SetRealGeoParams(geoCons->GetRealParameters());
93  geoParams.SetStringGeoParams(geoCons->GetStringParameters());
94  geoParams.SetVectIntGeoParams(geoCons->GetVectIntParameters());
95  geoParams.SetVectBoolGeoParams(geoCons->GetVectBoolParameters());
96  geoParams.SetVectRealGeoParams(geoCons->GetVectRealParameters());
97  geoParams.SetVectStringGeoParams(geoCons->GetVectStringParameters());
98  geoParams.Write("GGSGeoParams");
99 
100  // Write generator informations
101  // These are written only for GGS generators that export a parameter object containing the "generator" name setting.
102  auto *genAction =
103  dynamic_cast<const GGSGeneratorAction *>(GGSRunManager::GetRunManager()->GetUserPrimaryGeneratorAction());
104  if (genAction) {
105  GGSTParameters generatorParams(genAction->GetParameters());
106  try {
107  generatorParams.GetParam<std::string>("generator"); // Throws if "generator" parameter is not present
108  generatorParams.Write("GGSGenParams");
109  } catch (...) {
110  }
111  }
112  // Set storage of detector to null values to force proper initialization in StoreVolume
113  _currVolStorageFile = NULL;
114  _currDetVolName = "";
115 
116  return fInfo.filePtr;
117 }
const std::map< std::string, std::vector< bool > > & GetVectBoolParameters()
Getter method for vector-of-booleans geometry parameters.
void SetVectBoolGeoParams(const std::map< std::string, std::vector< bool >> &vectBoolGeoParams)
Sets the vector-of-booleans geometry parameters.
const std::map< std::string, int > & GetIntParameters()
Getter method for integer geometry parameters.
const std::map< std::string, double > & GetRealParameters()
Getter method for real geometry parameters.
Base class for GGS generator actions.
Abstract class needed to load GGS geometry.
static GGSGeoPluginManager & GetInstance()
Get the singleton instance.
T GetParam(const std::string &name) const
Gets a parameter.
void SetStringGeoParams(const std::map< std::string, std::string > &stringGeoParams)
Sets the string geometry parameters.
const std::map< std::string, std::vector< std::string > > & GetVectStringParameters()
Getter method for vector-of-strings geometry parameters.
void SetRealGeoParams(const std::map< std::string, double > &realGeoParams)
Sets the real geometry parameters.
const std::map< std::string, std::vector< int > > & GetVectIntParameters()
Getter method for vector-of-integers geometry parameters.
const std::map< std::string, std::string > & GetStringParameters()
Getter method for string geometry parameters.
const std::map< std::string, std::vector< double > > & GetVectRealParameters()
Getter method for vector-of-reals geometry parameters.
void SetVectRealGeoParams(const std::map< std::string, std::vector< double >> &vectRealGeoParams)
Sets the vector-of-reals geometry parameters.
void SetVectStringGeoParams(const std::map< std::string, std::vector< std::string >> &vectStringGeoParams)
Sets the vector-of-strings geometry parameters.
const std::map< std::string, bool > & GetBoolParameters()
Getter method for boolean geometry parameters.
static GGSRunManager * GetRunManager()
Static getter function the run manager.
Class for storing the geometry parameters on Root output file.
Definition: GGSTGeoParams.h:18
void SetVectIntGeoParams(const std::map< std::string, std::vector< int >> &vectIntGeoParams)
Sets the vector-of-integers geometry parameters.
GGSVGeometryConstruction * GetGeoConstruction()
Returns the geometry construction object.
void SetBoolGeoParams(const std::map< std::string, bool > &boolGeoParams)
Sets the boolean geometry parameters.
Class for writing parameters into the output Root file.
void SetIntGeoParams(const std::map< std::string, int > &intGeoParams)
Sets the integer geometry parameters.
GGSRootFileService & GGSRootFileService::GetInstance ( )
static

Get reference to GGSRootFileService unique instance.

Returns
reference to the root file service.

Definition at line 30 of file GGSRootFileService.cpp.

30  {
31  static GGSRootFileService instance;
32  return instance;
33 }
Singleton for a centralized ROOT files management.
void GGSRootFileService::SetDefaultFileBase ( const path &  newFileBase)
inline

Sets the default file name.

The default file name is used when a file is requested by calling GetFileForThisRun but no file name is provided.

Parameters
newFileBaseThe new default file base name (optionally with path).

Definition at line 123 of file GGSRootFileService.h.

123 { _defaultOutBase = newFileBase; }
void GGSRootFileService::SetSimInfo ( const GGSTSimInfo simInfo)
inline

Set the simulation info object to be saved on output files.

Parameters
simInfoThe object containing informations about the simulation.

Definition at line 148 of file GGSRootFileService.h.

148 { _simInfo = simInfo; }
void GGSRootFileService::SetSuffix ( const std::string &  suffix)
inline

Sets the suffix for file names.

The suffix will be appended after just before the .root extension.

Parameters
suffixThe suffix.

Definition at line 115 of file GGSRootFileService.h.

115 { _suffix = suffix; }
int GGSRootFileService::StoreVolume ( TFile *  filePtr,
const std::string &  detector,
const G4VPhysicalVolume *  volume,
const G4ThreeVector &  position,
int  id 
)

Set persistence for the specified volume.

The specified volume (volume name, position and id) will be saved as a GGSTHitVolInfo object inside the GGSTHitDetInfo object corresponding to the specified detector. The GGSTHitDetInfo is saved as an element of a TClonesArray called GGSHitDetArray inside the specified file.

The (volume name, id) pair must be unique for each volume to be stored.

Parameters
filePtrThe file where to save the informations about detectors and volumes.
detectorThe name of the detector.
volumeThe pointer to the physical volume.
positionThe position of the volume (in internal G4 units; will be saved in [cm]).
idThe ID of the volume (see GGSTHitVolInfo).
Returns
The position of the volume in the store.
See Also
GGSTHitVolInfo

Definition at line 213 of file GGSRootFileService.cpp.

214  {
215  static const std::string routineName("GGSRootFileService::StoreVolume");
216 
217  std::string detVolName = detector.substr(0, detector.find_first_of('.'));
218 
219  // 1. Retrieve file info structure
220  bool fileChanged = false;
221  if (filePtr != _currVolStorageFile) {
222  fileChanged = true;
223  _currVolStorageFile = filePtr;
224  for (_currVolStorageFileInfo = _files.begin(); _currVolStorageFileInfo != _files.end(); _currVolStorageFileInfo++) {
225  if (_currVolStorageFileInfo->filePtr == filePtr)
226  break;
227  }
228  if (_currVolStorageFileInfo == _files.end()) {
229  COUT(WARNING) << "The requested file is not managed by GGSRootFileService. Volume informations will not be saved."
230  << ENDL;
231  return -1;
232  }
233  }
234 
235  // 2. Find the detector in the index
236  static HitDetMap::iterator currDetector;
237  static GGSTHitDetInfo *currPersDetector = NULL;
238  if (fileChanged || _currDetVolName != detVolName) {
239  if (_currVolStorageFileInfo->detectorsMap == NULL)
240  _currVolStorageFileInfo->detectorsMap = new HitDetMap;
241  _currDetVolName = detVolName;
242  int currPersDetectorIndex = 0;
243  for (currDetector = _currVolStorageFileInfo->detectorsMap->begin();
244  currDetector != _currVolStorageFileInfo->detectorsMap->end(); currDetector++, currPersDetectorIndex++) {
245  if (currDetector->first == _currDetVolName)
246  break;
247  }
248  if (currDetector == _currVolStorageFileInfo->detectorsMap->end()) {
249  // 2.1 Detector not found. Create it both in index and persistence array
250  _currVolStorageFileInfo->detectorsMap->push_back(std::pair<std::string, HitVolMap>(_currDetVolName, HitVolMap()));
251  currDetector = _currVolStorageFileInfo->detectorsMap->end(); // Past-the-end iterator
252  currDetector--; // Set the iterator to the last element
253  if (_currVolStorageFileInfo->detectorsArray == NULL) {
254  _currVolStorageFileInfo->detectorsArray = new TClonesArray("GGSTHitDetInfo");
255  }
256  currPersDetectorIndex = _currVolStorageFileInfo->detectorsArray->GetEntries(); // Redundant
257  currPersDetector = new ((*(_currVolStorageFileInfo->detectorsArray))[currPersDetectorIndex]) GGSTHitDetInfo;
258  currPersDetector->detectorName = _currDetVolName.data();
259  } else {
260  // 2.2 Detector found. Set the current persistent detector
261  currPersDetector = (GGSTHitDetInfo *)(_currVolStorageFileInfo->detectorsArray->At(currPersDetectorIndex));
262  }
263  }
264 
265  // 3. Insert the volume in the index and in the persistency structure
266 
267  // Append volume ID to volume name to avoid placing all the replicated volumes at the same place in the index
268  static std::stringstream ss;
269  ss.str("");
270  ss << id;
271  std::string volAndId = volume->GetName() + ss.str();
272 
273  std::pair<VolumeKey, G4int> insertValue(VolumeKey(volAndId, volume, position),
274  currPersDetector->volumes.GetEntries());
275  std::pair<HitVolMap::iterator, bool> insertResult;
276  insertResult = currDetector->second.insert(insertValue); // TODO: using emplace instead of insert would improve speed?
277  if (insertResult.second) {
278  // 3.1 No hash collision: this is a new volume. Add it also to the volumes array in detector object...
279  GGSTHitVolInfo *volInfo = new ((currPersDetector->volumes)[currPersDetector->volumes.GetEntries()]) GGSTHitVolInfo;
280  volInfo->volumeName = volume->GetName().data();
281  for (int i = 0; i < 3; i++) {
282  volInfo->volumePos[i] = position[i] / cm;
283  }
284  volInfo->id = id;
285  // ... then return its position in the array
286  return currPersDetector->volumes.GetEntries() - 1;
287  } else {
288  // 3.2 A hash collision has happened: the volume is already present. So take its position from the index
289  return insertResult.first->second;
290  }
291 }
Float_t volumePos[3]
Position of the touchable in world volume coordinates [cm].
Int_t id
ID of the volume.
Class to store detector informations.
#define ENDL
Definition: GGSSmartLog.h:105
#define COUT(level)
Smart log macro. It writes on stdout only if the specified verbosity level is lesser than the maximum...
Definition: GGSSmartLog.h:76
TClonesArray volumes
Array of GGSTHitVolInfo objects.
TString volumeName
Name of the physical volume.
GGSTHitVolInfo.h GGSTHitVolInfo class declaration.
TString detectorName
Name of detector associated to integrated hits.

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