CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
PoolOutputModule.cc
Go to the documentation of this file.
2 
5 
20 
21 #include "TTree.h"
22 #include "TBranchElement.h"
23 #include "TObjArray.h"
24 #include "RVersion.h"
25 
26 #include <fstream>
27 #include <iomanip>
28 #include <sstream>
29 
30 namespace edm {
32  OutputModule(pset),
33  rootServiceChecker_(),
34  auxItems_(),
35  selectedOutputItemList_(),
36  fileName_(pset.getUntrackedParameter<std::string>("fileName")),
37  logicalFileName_(pset.getUntrackedParameter<std::string>("logicalFileName")),
38  catalog_(pset.getUntrackedParameter<std::string>("catalog")),
39  maxFileSize_(pset.getUntrackedParameter<int>("maxSize")),
40  compressionLevel_(pset.getUntrackedParameter<int>("compressionLevel")),
41 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,30,0)
42  compressionAlgorithm_(pset.getUntrackedParameter<std::string>("compressionAlgorithm")),
43 #else
44  compressionAlgorithm_("ZLIB"),
45 #endif
46  basketSize_(pset.getUntrackedParameter<int>("basketSize")),
47  eventAutoFlushSize_(pset.getUntrackedParameter<int>("eventAutoFlushCompressedSize")),
48  splitLevel_(std::min<int>(pset.getUntrackedParameter<int>("splitLevel") + 1, 99)),
49  basketOrder_(pset.getUntrackedParameter<std::string>("sortBaskets")),
50  treeMaxVirtualSize_(pset.getUntrackedParameter<int>("treeMaxVirtualSize")),
51  whyNotFastClonable_(pset.getUntrackedParameter<bool>("fastCloning") ? FileBlock::CanFastClone : FileBlock::DisabledInConfigFile),
52  dropMetaData_(DropNone),
53  moduleLabel_(pset.getParameter<std::string>("@module_label")),
54  initializedFromInput_(false),
55  outputFileCount_(0),
56  inputFileCount_(0),
57  childIndex_(0U),
58  numberOfDigitsInIndex_(0U),
59  overrideInputFileSplitLevels_(pset.getUntrackedParameter<bool>("overrideInputFileSplitLevels")),
60  rootOutputFile_(),
61  statusFileName_() {
62 
63  if (pset.getUntrackedParameter<bool>("writeStatusFile")) {
64  std::ostringstream statusfilename;
65  statusfilename << moduleLabel_ << '_' << getpid();
66  statusFileName_ = statusfilename.str();
67  }
68 
70  if(dropMetaData.empty()) dropMetaData_ = DropNone;
71  else if(dropMetaData == std::string("NONE")) dropMetaData_ = DropNone;
72  else if(dropMetaData == std::string("DROPPED")) dropMetaData_ = DropDroppedPrior;
73  else if(dropMetaData == std::string("PRIOR")) dropMetaData_ = DropPrior;
74  else if(dropMetaData == std::string("ALL")) dropMetaData_ = DropAll;
75  else {
76  throw edm::Exception(errors::Configuration, "Illegal dropMetaData parameter value: ")
77  << dropMetaData << ".\n"
78  << "Legal values are 'NONE', 'DROPPED', 'PRIOR', and 'ALL'.\n";
79  }
80 
81  if (!wantAllEvents()) {
83  }
84 
85  // We don't use this next parameter, but we read it anyway because it is part
86  // of the configuration of this module. An external parser creates the
87  // configuration by reading this source code.
88  pset.getUntrackedParameterSet("dataset");
89  }
90 
92  for(int i = InEvent; i < NumBranchTypes; ++i) {
93  BranchType branchType = static_cast<BranchType>(i);
94  Selections const& keptVector = keptProducts()[branchType];
95  for(Selections::const_iterator it = keptVector.begin(), itEnd = keptVector.end(); it != itEnd; ++it) {
96  BranchDescription const& prod = **it;
97  checkDictionaries(prod.fullClassName(), true);
99  }
100  }
101  }
102 
104  return rootOutputFile_->fileName();
105  }
106 
108  basketSize_(BranchDescription::invalidBasketSize) {}
109 
111  branchDescription_(0),
112  product_(0),
113  splitLevel_(BranchDescription::invalidSplitLevel),
114  basketSize_(BranchDescription::invalidBasketSize) {}
115 
117  branchDescription_(bd),
118  product_(0),
119  splitLevel_(splitLevel),
120  basketSize_(basketSize) {}
121 
122 
123  PoolOutputModule::OutputItem::Sorter::Sorter(TTree* tree) : treeMap_(new std::map<std::string, int>) {
124  // Fill a map mapping branch names to an index specifying the order in the tree.
125  if(tree != 0) {
126  TObjArray* branches = tree->GetListOfBranches();
127  for(int i = 0; i < branches->GetEntries(); ++i) {
128  TBranchElement* br = (TBranchElement*)branches->At(i);
129  treeMap_->insert(std::make_pair(std::string(br->GetName()), i));
130  }
131  }
132  }
133 
134  bool
136  // Provides a comparison for sorting branches according to the index values in treeMap_.
137  // Branches not found are always put at the end (i.e. not found > found).
138  if(treeMap_->empty()) return lh < rh;
139  std::string const& lstring = lh.branchDescription_->branchName();
140  std::string const& rstring = rh.branchDescription_->branchName();
141  std::map<std::string, int>::const_iterator lit = treeMap_->find(lstring);
142  std::map<std::string, int>::const_iterator rit = treeMap_->find(rstring);
143  bool lfound = (lit != treeMap_->end());
144  bool rfound = (rit != treeMap_->end());
145  if(lfound && rfound) {
146  return lit->second < rit->second;
147  } else if(lfound) {
148  return true;
149  } else if(rfound) {
150  return false;
151  }
152  return lh < rh;
153  }
154 
156 
157  Selections const& keptVector = keptProducts()[branchType];
159  AuxItem& auxItem = auxItems_[branchType];
160 
161  // Fill AuxItem
162  if (theInputTree != 0 && !overrideInputFileSplitLevels_) {
163  TBranch* auxBranch = theInputTree->GetBranch(BranchTypeToAuxiliaryBranchName(branchType).c_str());
164  if (auxBranch) {
165  auxItem.basketSize_ = auxBranch->GetBasketSize();
166  } else {
167  auxItem.basketSize_ = basketSize_;
168  }
169  } else {
170  auxItem.basketSize_ = basketSize_;
171  }
172 
173  // Fill outputItemList with an entry for each branch.
174  for(Selections::const_iterator it = keptVector.begin(), itEnd = keptVector.end(); it != itEnd; ++it) {
177 
178  BranchDescription const& prod = **it;
179  TBranch* theBranch = ((!prod.produced() && theInputTree != 0 && !overrideInputFileSplitLevels_) ? theInputTree->GetBranch(prod.branchName().c_str()) : 0);
180 
181  if(theBranch != 0) {
182  splitLevel = theBranch->GetSplitLevel();
183  basketSize = theBranch->GetBasketSize();
184  } else {
185  splitLevel = (prod.splitLevel() == BranchDescription::invalidSplitLevel ? splitLevel_ : prod.splitLevel());
186  basketSize = (prod.basketSize() == BranchDescription::invalidBasketSize ? basketSize_ : prod.basketSize());
187  }
188  outputItemList.emplace_back(&prod, splitLevel, basketSize);
189  }
190 
191  // Sort outputItemList to allow fast copying.
192  // The branches in outputItemList must be in the same order as in the input tree, with all new branches at the end.
193  sort_all(outputItemList, OutputItem::Sorter(theInputTree));
194  }
195 
197  if(isFileOpen()) {
198  rootOutputFile_->beginInputFile(fb, remainingEvents());
199  }
200  }
201 
203  if(!isFileOpen()) {
204  doOpenFile();
205  beginInputFile(fb);
206  }
207  }
208 
210  if(!initializedFromInput_) {
211  for(int i = InEvent; i < NumBranchTypes; ++i) {
212  BranchType branchType = static_cast<BranchType>(i);
213  TTree* theInputTree = (branchType == InEvent ? fb.tree() :
214  (branchType == InLumi ? fb.lumiTree() :
215  fb.runTree()));
216  fillSelectedItemList(branchType, theInputTree);
217  }
218  initializedFromInput_ = true;
219  }
220  ++inputFileCount_;
221  beginInputFile(fb);
222  }
223 
225  if(rootOutputFile_) rootOutputFile_->respondToCloseInputFile(fb);
226  }
227 
228  void PoolOutputModule::postForkReacquireResources(unsigned int iChildIndex, unsigned int iNumberOfChildren) {
229  childIndex_ = iChildIndex;
230  while (iNumberOfChildren != 0) {
232  iNumberOfChildren /= 10;
233  }
234  if (numberOfDigitsInIndex_ == 0) {
235  numberOfDigitsInIndex_ = 3; // Protect against zero iNumberOfChildren
236  }
237  }
238 
240  }
241 
243  rootOutputFile_->writeOne(e);
244  if (!statusFileName_.empty()) {
245  std::ofstream statusFile(statusFileName_.c_str());
246  statusFile << e.id() << " time: " << std::setprecision(3) << TimeOfDay() << '\n';
247  statusFile.close();
248  }
249  }
250 
252  rootOutputFile_->writeLuminosityBlock(lb);
253  Service<JobReport> reportSvc;
254  reportSvc->reportLumiSection(lb.id().run(), lb.id().luminosityBlock());
255  }
256 
258  rootOutputFile_->writeRun(r);
259  Service<JobReport> reportSvc;
260  reportSvc->reportRunNumber(r.run());
261  }
262 
263  // At some later date, we may move functionality from finishEndFile() to here.
265 
266 
267  void PoolOutputModule::writeFileFormatVersion() { rootOutputFile_->writeFileFormatVersion(); }
268  void PoolOutputModule::writeFileIdentifier() { rootOutputFile_->writeFileIdentifier(); }
269  void PoolOutputModule::writeIndexIntoFile() { rootOutputFile_->writeIndexIntoFile(); }
270  void PoolOutputModule::writeProcessConfigurationRegistry() { rootOutputFile_->writeProcessConfigurationRegistry(); }
271  void PoolOutputModule::writeProcessHistoryRegistry() { rootOutputFile_->writeProcessHistoryRegistry(); }
272  void PoolOutputModule::writeParameterSetRegistry() { rootOutputFile_->writeParameterSetRegistry(); }
273  void PoolOutputModule::writeProductDescriptionRegistry() { rootOutputFile_->writeProductDescriptionRegistry(); }
274  void PoolOutputModule::writeParentageRegistry() { rootOutputFile_->writeParentageRegistry(); }
275  void PoolOutputModule::writeBranchIDListRegistry() { rootOutputFile_->writeBranchIDListRegistry(); }
276  void PoolOutputModule::writeProductDependencies() { rootOutputFile_->writeProductDependencies(); }
278  bool PoolOutputModule::isFileOpen() const { return rootOutputFile_.get() != 0; }
279  bool PoolOutputModule::shouldWeCloseFile() const { return rootOutputFile_->shouldWeCloseFile(); }
280 
282  if(inputFileCount_ == 0) {
284  << "Attempt to open output file before input file. "
285  << "Please report this to the core framework developers.\n";
286  }
287  std::string suffix(".root");
288  std::string::size_type offset = fileName().rfind(suffix);
289  bool ext = (offset == fileName().size() - suffix.size());
290  if(!ext) suffix.clear();
291  std::string fileBase(ext ? fileName().substr(0, offset) : fileName());
292  std::ostringstream ofilename;
293  std::ostringstream lfilename;
294  ofilename << fileBase;
295  lfilename << logicalFileName();
297  ofilename << '_' << std::setw(numberOfDigitsInIndex_) << std::setfill('0') << childIndex_;
298  if(!logicalFileName().empty()) {
299  lfilename << '_' << std::setw(numberOfDigitsInIndex_) << std::setfill('0') << childIndex_;
300  }
301  }
302  if(outputFileCount_) {
303  ofilename << std::setw(3) << std::setfill('0') << outputFileCount_;
304  if(!logicalFileName().empty()) {
305  lfilename << std::setw(3) << std::setfill('0') << outputFileCount_;
306  }
307  }
308  ofilename << suffix;
309  rootOutputFile_.reset(new RootOutputFile(this, ofilename.str(), lfilename.str()));
311  }
312 
313  void
315  std::string defaultString;
317  desc.setComment("Writes runs, lumis, and events into EDM/ROOT files.");
318  desc.addUntracked<std::string>("fileName")
319  ->setComment("Name of output file.");
320  desc.addUntracked<std::string>("logicalFileName", defaultString)
321  ->setComment("Passed to job report. Otherwise unused by module.");
322  desc.addUntracked<std::string>("catalog", defaultString)
323  ->setComment("Passed to job report. Otherwise unused by module.");
324  desc.addUntracked<int>("maxSize", 0x7f000000)
325  ->setComment("Maximum output file size, in kB.\n"
326  "If over maximum, new output file will be started at next input file transition.");
327  desc.addUntracked<int>("compressionLevel", 7)
328  ->setComment("ROOT compression level of output file.");
329 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,30,0)
330  desc.addUntracked<std::string>("compressionAlgorithm", "ZLIB")
331  ->setComment("Algorithm used to compress data in the ROOT output file, allowed values are ZLIB and LZMA");
332 #endif
333  desc.addUntracked<int>("basketSize", 16384)
334  ->setComment("Default ROOT basket size in output file.");
335  desc.addUntracked<int>("eventAutoFlushCompressedSize",-1)->setComment("Set ROOT auto flush stored data size (in bytes) for event TTree. The value sets how large the compressed buffer is allowed to get. The uncompressed buffer can be quite a bit larger than this depending on the average compression ratio. The value of -1 just uses ROOT's default value. The value of 0 turns off this feature.");
336  desc.addUntracked<int>("splitLevel", 99)
337  ->setComment("Default ROOT branch split level in output file.");
338  desc.addUntracked<std::string>("sortBaskets", std::string("sortbasketsbyoffset"))
339  ->setComment("Legal values: 'sortbasketsbyoffset', 'sortbasketsbybranch', 'sortbasketsbyentry'.\n"
340  "Used by ROOT when fast copying. Affects performance.");
341  desc.addUntracked<int>("treeMaxVirtualSize", -1)
342  ->setComment("Size of ROOT TTree TBasket cache. Affects performance.");
343  desc.addUntracked<bool>("fastCloning", true)
344  ->setComment("True: Allow fast copying, if possible.\n"
345  "False: Disable fast copying.");
346  desc.addUntracked<bool>("overrideInputFileSplitLevels", false)
347  ->setComment("False: Use branch split levels and basket sizes from input file, if possible.\n"
348  "True: Always use specified or default split levels and basket sizes.");
349  desc.addUntracked<bool>("writeStatusFile", false)
350  ->setComment("Write a status file. Intended for use by workflow management.");
351  desc.addUntracked<std::string>("dropMetaData", defaultString)
352  ->setComment("Determines handling of per product per event metadata. Options are:\n"
353  "'NONE': Keep all of it.\n"
354  "'DROPPED': Keep it for products produced in current process and all kept products. Drop it for dropped products produced in prior processes.\n"
355  "'PRIOR': Keep it for products produced in current process. Drop it for products produced in prior processes.\n"
356  "'ALL': Drop all of it.");
357  ParameterSetDescription dataSet;
358  dataSet.setAllowAnything();
359  desc.addUntracked<ParameterSetDescription>("dataset", dataSet)
360  ->setComment("PSet is only used by Data Operations and not by this module.");
361 
363 
364  descriptions.add("edmOutput", desc);
365  }
366 }
virtual void writeParentageRegistry()
T getUntrackedParameter(std::string const &, T const &) const
int i
Definition: DBlmapReader.cc:9
std::string const & BranchTypeToAuxiliaryBranchName(BranchType const &branchType)
Definition: BranchType.cc:114
BranchDescription const * branchDescription_
int const & basketSize() const
SelectionsArray const & keptProducts() const
Definition: OutputModule.h:61
ParameterDescriptionBase * addUntracked(U const &iLabel, T const &value)
static int const invalidSplitLevel
std::string & branchName() const
void setAllowAnything()
allow any parameter label/value pairs
static int const invalidBasketSize
DropMetaData const & dropMetaData() const
virtual bool isFileOpen() const
int remainingEvents() const
Definition: OutputModule.h:55
bool & produced() const
EventID const & id() const
std::vector< OutputItem > OutputItemList
std::string const & fileName() const
std::string const moduleLabel_
virtual void write(EventPrincipal const &e)
RunNumber_t run() const
Definition: RunPrincipal.h:46
bool int lh
Definition: SIMDVec.h:19
virtual bool shouldWeCloseFile() const
allow inheriting classes to override but still be able to call this method in the overridden version ...
uint16_t size_type
std::string const & logicalFileName() const
virtual void writeParameterSetRegistry()
BranchType
Definition: BranchType.h:11
dictionary map
Definition: Association.py:205
void fillSelectedItemList(BranchType branchtype, TTree *theInputTree)
bool wantAllEvents() const
Definition: OutputModule.h:71
PoolOutputModule(ParameterSet const &ps)
virtual void respondToOpenInputFile(FileBlock const &fb)
void setComment(std::string const &value)
virtual void respondToCloseInputFile(FileBlock const &fb)
bool operator()(OutputItem const &lh, OutputItem const &rh) const
std::string const & currentFileName() const
virtual void writeFileFormatVersion()
virtual void writeLuminosityBlock(LuminosityBlockPrincipal const &lb)
OutputItemListArray selectedOutputItemList_
iterator end()
Definition: Selections.h:367
ParameterSet const & getUntrackedParameterSet(std::string const &name, ParameterSet const &defaultValue) const
void checkDictionaries(std::string const &name, bool noComponents=false)
RunNumber_t run() const
virtual void writeProcessConfigurationRegistry()
int const & splitLevel() const
iterator begin()
Definition: Selections.h:366
EventID const & min(EventID const &lh, EventID const &rh)
Definition: EventID.h:132
virtual void writeProductDependencies()
std::unique_ptr< RootOutputFile > rootOutputFile_
unsigned int offset(bool)
virtual void writeIndexIntoFile()
unsigned int numberOfDigitsInIndex_
std::string const & fullClassName() const
void sort_all(RandomAccessSequence &s)
wrappers for std::sort
Definition: Algorithms.h:120
virtual void writeBranchIDListRegistry()
TTree * lumiTree() const
Definition: FileBlock.h:103
virtual void writeProcessHistoryRegistry()
std::string wrappedClassName(std::string const &iFullName)
virtual void openFile(FileBlock const &fb)
LuminosityBlockNumber_t luminosityBlock() const
void add(std::string const &label, ParameterSetDescription const &psetDescription)
virtual void postForkReacquireResources(unsigned int iChildIndex, unsigned int iNumberOfChildren)
static void fillDescription(ParameterSetDescription &desc)
virtual void writeFileIdentifier()
virtual void finishEndFile()
if(dp >Float(M_PI)) dp-
void beginInputFile(FileBlock const &fb)
virtual void startEndFile()
virtual void writeProductDescriptionRegistry()
boost::shared_ptr< std::map< std::string, int > > treeMap_
static void fillDescriptions(ConfigurationDescriptions &descriptions)
TTree * runTree() const
Definition: FileBlock.h:105
TTree * tree() const
Definition: FileBlock.h:101
virtual void writeRun(RunPrincipal const &r)