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 
4 
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  edm::one::OutputModuleBase::OutputModuleBase(pset),
33  one::OutputModule<WatchInputFiles>(pset),
34  rootServiceChecker_(),
35  auxItems_(),
36  selectedOutputItemList_(),
37  fileName_(pset.getUntrackedParameter<std::string>("fileName")),
38  logicalFileName_(pset.getUntrackedParameter<std::string>("logicalFileName")),
39  catalog_(pset.getUntrackedParameter<std::string>("catalog")),
40  maxFileSize_(pset.getUntrackedParameter<int>("maxSize")),
41  compressionLevel_(pset.getUntrackedParameter<int>("compressionLevel")),
42  compressionAlgorithm_(pset.getUntrackedParameter<std::string>("compressionAlgorithm")),
43  basketSize_(pset.getUntrackedParameter<int>("basketSize")),
44  eventAutoFlushSize_(pset.getUntrackedParameter<int>("eventAutoFlushCompressedSize")),
45  splitLevel_(std::min<int>(pset.getUntrackedParameter<int>("splitLevel") + 1, 99)),
46  basketOrder_(pset.getUntrackedParameter<std::string>("sortBaskets")),
47  treeMaxVirtualSize_(pset.getUntrackedParameter<int>("treeMaxVirtualSize")),
48  whyNotFastClonable_(pset.getUntrackedParameter<bool>("fastCloning") ? FileBlock::CanFastClone : FileBlock::DisabledInConfigFile),
49  dropMetaData_(DropNone),
50  moduleLabel_(pset.getParameter<std::string>("@module_label")),
51  initializedFromInput_(false),
52  outputFileCount_(0),
53  inputFileCount_(0),
54  childIndex_(0U),
55  numberOfDigitsInIndex_(0U),
56  branchParents_(),
57  branchChildren_(),
58  overrideInputFileSplitLevels_(pset.getUntrackedParameter<bool>("overrideInputFileSplitLevels")),
59  rootOutputFile_(),
60  statusFileName_() {
61 
62  if (pset.getUntrackedParameter<bool>("writeStatusFile")) {
63  std::ostringstream statusfilename;
64  statusfilename << moduleLabel_ << '_' << getpid();
65  statusFileName_ = statusfilename.str();
66  }
67 
69  if(dropMetaData.empty()) dropMetaData_ = DropNone;
70  else if(dropMetaData == std::string("NONE")) dropMetaData_ = DropNone;
71  else if(dropMetaData == std::string("DROPPED")) dropMetaData_ = DropDroppedPrior;
72  else if(dropMetaData == std::string("PRIOR")) dropMetaData_ = DropPrior;
73  else if(dropMetaData == std::string("ALL")) dropMetaData_ = DropAll;
74  else {
75  throw edm::Exception(errors::Configuration, "Illegal dropMetaData parameter value: ")
76  << dropMetaData << ".\n"
77  << "Legal values are 'NONE', 'DROPPED', 'PRIOR', and 'ALL'.\n";
78  }
79 
80  if (!wantAllEvents()) {
82  }
83 
84  // We don't use this next parameter, but we read it anyway because it is part
85  // of the configuration of this module. An external parser creates the
86  // configuration by reading this source code.
87  pset.getUntrackedParameterSet("dataset");
88  }
89 
91  }
92 
94  return rootOutputFile_->fileName();
95  }
96 
98  basketSize_(BranchDescription::invalidBasketSize) {}
99 
101  branchDescription_(0),
102  product_(0),
103  splitLevel_(BranchDescription::invalidSplitLevel),
104  basketSize_(BranchDescription::invalidBasketSize) {}
105 
107  branchDescription_(bd),
108  product_(0),
109  splitLevel_(splitLevel),
110  basketSize_(basketSize) {}
111 
112 
113  PoolOutputModule::OutputItem::Sorter::Sorter(TTree* tree) : treeMap_(new std::map<std::string, int>) {
114  // Fill a map mapping branch names to an index specifying the order in the tree.
115  if(tree != nullptr) {
116  TObjArray* branches = tree->GetListOfBranches();
117  for(int i = 0; i < branches->GetEntries(); ++i) {
118  TBranchElement* br = (TBranchElement*)branches->At(i);
119  treeMap_->insert(std::make_pair(std::string(br->GetName()), i));
120  }
121  }
122  }
123 
124  bool
126  // Provides a comparison for sorting branches according to the index values in treeMap_.
127  // Branches not found are always put at the end (i.e. not found > found).
128  if(treeMap_->empty()) return lh < rh;
129  std::string const& lstring = lh.branchDescription_->branchName();
130  std::string const& rstring = rh.branchDescription_->branchName();
131  std::map<std::string, int>::const_iterator lit = treeMap_->find(lstring);
132  std::map<std::string, int>::const_iterator rit = treeMap_->find(rstring);
133  bool lfound = (lit != treeMap_->end());
134  bool rfound = (rit != treeMap_->end());
135  if(lfound && rfound) {
136  return lit->second < rit->second;
137  } else if(lfound) {
138  return true;
139  } else if(rfound) {
140  return false;
141  }
142  return lh < rh;
143  }
144 
146 
147  SelectedProducts const& keptVector = keptProducts()[branchType];
149  AuxItem& auxItem = auxItems_[branchType];
150 
151  // Fill AuxItem
152  if (theInputTree != nullptr && !overrideInputFileSplitLevels_) {
153  TBranch* auxBranch = theInputTree->GetBranch(BranchTypeToAuxiliaryBranchName(branchType).c_str());
154  if (auxBranch) {
155  auxItem.basketSize_ = auxBranch->GetBasketSize();
156  } else {
157  auxItem.basketSize_ = basketSize_;
158  }
159  } else {
160  auxItem.basketSize_ = basketSize_;
161  }
162 
163  // Fill outputItemList with an entry for each branch.
164  for(SelectedProducts::const_iterator it = keptVector.begin(), itEnd = keptVector.end(); it != itEnd; ++it) {
167 
168  BranchDescription const& prod = **it;
169  TBranch* theBranch = ((!prod.produced() && theInputTree != nullptr && !overrideInputFileSplitLevels_) ? theInputTree->GetBranch(prod.branchName().c_str()) : 0);
170 
171  if(theBranch != nullptr) {
172  splitLevel = theBranch->GetSplitLevel();
173  basketSize = theBranch->GetBasketSize();
174  } else {
175  splitLevel = (prod.splitLevel() == BranchDescription::invalidSplitLevel ? splitLevel_ : prod.splitLevel());
176  basketSize = (prod.basketSize() == BranchDescription::invalidBasketSize ? basketSize_ : prod.basketSize());
177  }
178  outputItemList.emplace_back(&prod, splitLevel, basketSize);
179  }
180 
181  // Sort outputItemList to allow fast copying.
182  // The branches in outputItemList must be in the same order as in the input tree, with all new branches at the end.
183  sort_all(outputItemList, OutputItem::Sorter(theInputTree));
184  }
185 
187  if(isFileOpen()) {
188  rootOutputFile_->beginInputFile(fb, remainingEvents());
189  }
190  }
191 
193  if(!isFileOpen()) {
194  reallyOpenFile();
195  beginInputFile(fb);
196  }
197  }
198 
200  if(!initializedFromInput_) {
201  for(int i = InEvent; i < NumBranchTypes; ++i) {
202  BranchType branchType = static_cast<BranchType>(i);
203  TTree* theInputTree = (branchType == InEvent ? fb.tree() :
204  (branchType == InLumi ? fb.lumiTree() :
205  fb.runTree()));
206  fillSelectedItemList(branchType, theInputTree);
207  }
208  initializedFromInput_ = true;
209  }
210  ++inputFileCount_;
211  beginInputFile(fb);
212  }
213 
215  if(rootOutputFile_) rootOutputFile_->respondToCloseInputFile(fb);
216  }
217 
218  void PoolOutputModule::postForkReacquireResources(unsigned int iChildIndex, unsigned int iNumberOfChildren) {
219  childIndex_ = iChildIndex;
220  while (iNumberOfChildren != 0) {
222  iNumberOfChildren /= 10;
223  }
224  if (numberOfDigitsInIndex_ == 0) {
225  numberOfDigitsInIndex_ = 3; // Protect against zero iNumberOfChildren
226  }
227  }
228 
230  }
231 
234  rootOutputFile_->writeOne(e, mcc);
235  if (!statusFileName_.empty()) {
236  std::ofstream statusFile(statusFileName_.c_str());
237  statusFile << e.id() << " time: " << std::setprecision(3) << TimeOfDay() << '\n';
238  statusFile.close();
239  }
240  }
241 
243  rootOutputFile_->writeLuminosityBlock(lb, mcc);
244  }
245 
247  rootOutputFile_->writeRun(r, mcc);
248  }
249 
252  branchParents_.clear();
254  startEndFile();
265  finishEndFile();
266 
268  }
269 
270 
271  // At some later date, we may move functionality from finishEndFile() to here.
273 
274  void PoolOutputModule::writeFileFormatVersion() { rootOutputFile_->writeFileFormatVersion(); }
275  void PoolOutputModule::writeFileIdentifier() { rootOutputFile_->writeFileIdentifier(); }
276  void PoolOutputModule::writeIndexIntoFile() { rootOutputFile_->writeIndexIntoFile(); }
277  void PoolOutputModule::writeProcessHistoryRegistry() { rootOutputFile_->writeProcessHistoryRegistry(); }
278  void PoolOutputModule::writeParameterSetRegistry() { rootOutputFile_->writeParameterSetRegistry(); }
279  void PoolOutputModule::writeProductDescriptionRegistry() { rootOutputFile_->writeProductDescriptionRegistry(); }
280  void PoolOutputModule::writeParentageRegistry() { rootOutputFile_->writeParentageRegistry(); }
281  void PoolOutputModule::writeBranchIDListRegistry() { rootOutputFile_->writeBranchIDListRegistry(); }
282  void PoolOutputModule::writeThinnedAssociationsHelper() { rootOutputFile_->writeThinnedAssociationsHelper(); }
283  void PoolOutputModule::writeProductDependencies() { rootOutputFile_->writeProductDependencies(); }
284  void PoolOutputModule::finishEndFile() { rootOutputFile_->finishEndFile(); rootOutputFile_ = nullptr; } // propagate_const<T> has no reset() function
286  bool PoolOutputModule::isFileOpen() const { return rootOutputFile_.get() != nullptr; }
287  bool PoolOutputModule::shouldWeCloseFile() const { return rootOutputFile_->shouldWeCloseFile(); }
288 
289  std::pair<std::string, std::string>
291  if(inputFileCount_ == 0) {
293  << "Attempt to open output file before input file. "
294  << "Please report this to the core framework developers.\n";
295  }
296  std::string suffix(".root");
297  std::string::size_type offset = fileName().rfind(suffix);
298  bool ext = (offset == fileName().size() - suffix.size());
299  if(!ext) suffix.clear();
300  std::string fileBase(ext ? fileName().substr(0, offset) : fileName());
301  std::ostringstream ofilename;
302  std::ostringstream lfilename;
303  ofilename << fileBase;
304  lfilename << logicalFileName();
306  ofilename << '_' << std::setw(numberOfDigitsInIndex_) << std::setfill('0') << childIndex_;
307  if(!logicalFileName().empty()) {
308  lfilename << '_' << std::setw(numberOfDigitsInIndex_) << std::setfill('0') << childIndex_;
309  }
310  }
311  if(outputFileCount_) {
312  ofilename << std::setw(3) << std::setfill('0') << outputFileCount_;
313  if(!logicalFileName().empty()) {
314  lfilename << std::setw(3) << std::setfill('0') << outputFileCount_;
315  }
316  }
317  ofilename << suffix;
319 
320  return std::make_pair(ofilename.str(), lfilename.str());
321  }
322 
325  rootOutputFile_ = std::make_unique<RootOutputFile>(this, names.first, names.second); // propagate_const<T> has no reset() function
326  }
327 
328  void
330  for(EventPrincipal::const_iterator i = ep.begin(), iEnd = ep.end(); i != iEnd; ++i) {
331  if((*i) && (*i)->productProvenancePtr() != nullptr) {
332  BranchID const& bid = (*i)->branchDescription().branchID();
333  BranchParents::iterator it = branchParents_.find(bid);
334  if(it == branchParents_.end()) {
335  it = branchParents_.insert(std::make_pair(bid, std::set<ParentageID>())).first;
336  }
337  it->second.insert((*i)->productProvenancePtr()->parentageID());
339  }
340  }
341  }
342 
343  void
345  for(BranchParents::const_iterator i = branchParents_.begin(), iEnd = branchParents_.end();
346  i != iEnd; ++i) {
347  BranchID const& child = i->first;
348  std::set<ParentageID> const& eIds = i->second;
349  for(std::set<ParentageID>::const_iterator it = eIds.begin(), itEnd = eIds.end();
350  it != itEnd; ++it) {
351  Parentage entryDesc;
352  ParentageRegistry::instance()->getMapped(*it, entryDesc);
353  std::vector<BranchID> const& parents = entryDesc.parents();
354  for(std::vector<BranchID>::const_iterator j = parents.begin(), jEnd = parents.end();
355  j != jEnd; ++j) {
356  branchChildren_.insertChild(*j, child);
357  }
358  }
359  }
360  }
361 
362  void
364  std::string defaultString;
365 
366  desc.setComment("Writes runs, lumis, and events into EDM/ROOT files.");
367  desc.addUntracked<std::string>("fileName")
368  ->setComment("Name of output file.");
369  desc.addUntracked<std::string>("logicalFileName", defaultString)
370  ->setComment("Passed to job report. Otherwise unused by module.");
371  desc.addUntracked<std::string>("catalog", defaultString)
372  ->setComment("Passed to job report. Otherwise unused by module.");
373  desc.addUntracked<int>("maxSize", 0x7f000000)
374  ->setComment("Maximum output file size, in kB.\n"
375  "If over maximum, new output file will be started at next input file transition.");
376  desc.addUntracked<int>("compressionLevel", 7)
377  ->setComment("ROOT compression level of output file.");
378  desc.addUntracked<std::string>("compressionAlgorithm", "ZLIB")
379  ->setComment("Algorithm used to compress data in the ROOT output file, allowed values are ZLIB and LZMA");
380  desc.addUntracked<int>("basketSize", 16384)
381  ->setComment("Default ROOT basket size in output file.");
382  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.");
383  desc.addUntracked<int>("splitLevel", 99)
384  ->setComment("Default ROOT branch split level in output file.");
385  desc.addUntracked<std::string>("sortBaskets", std::string("sortbasketsbyoffset"))
386  ->setComment("Legal values: 'sortbasketsbyoffset', 'sortbasketsbybranch', 'sortbasketsbyentry'.\n"
387  "Used by ROOT when fast copying. Affects performance.");
388  desc.addUntracked<int>("treeMaxVirtualSize", -1)
389  ->setComment("Size of ROOT TTree TBasket cache. Affects performance.");
390  desc.addUntracked<bool>("fastCloning", true)
391  ->setComment("True: Allow fast copying, if possible.\n"
392  "False: Disable fast copying.");
393  desc.addUntracked<bool>("overrideInputFileSplitLevels", false)
394  ->setComment("False: Use branch split levels and basket sizes from input file, if possible.\n"
395  "True: Always use specified or default split levels and basket sizes.");
396  desc.addUntracked<bool>("writeStatusFile", false)
397  ->setComment("Write a status file. Intended for use by workflow management.");
398  desc.addUntracked<std::string>("dropMetaData", defaultString)
399  ->setComment("Determines handling of per product per event metadata. Options are:\n"
400  "'NONE': Keep all of it.\n"
401  "'DROPPED': Keep it for products produced in current process and all kept products. Drop it for dropped products produced in prior processes.\n"
402  "'PRIOR': Keep it for products produced in current process. Drop it for products produced in prior processes.\n"
403  "'ALL': Drop all of it.");
404  ParameterSetDescription dataSet;
405  dataSet.setAllowAnything();
406  desc.addUntracked<ParameterSetDescription>("dataset", dataSet)
407  ->setComment("PSet is only used by Data Operations and not by this module.");
408 
410  }
411 
412  void
416  descriptions.add("edmOutput", desc);
417  }
418 }
virtual void openFile(FileBlock const &fb) override
virtual std::pair< std::string, std::string > physicalAndLogicalNameForNewFile()
T getUntrackedParameter(std::string const &, T const &) const
int i
Definition: DBlmapReader.cc:9
std::string const & branchName() const
std::string const & BranchTypeToAuxiliaryBranchName(BranchType const &branchType)
Definition: BranchType.cc:115
virtual void writeRun(RunPrincipal const &r, ModuleCallingContext const *) override
BranchDescription const * branchDescription_
int const & basketSize() const
TPRegexp parents
Definition: eve_filter.cc:21
ParameterDescriptionBase * addUntracked(U const &iLabel, T const &value)
static const HistoName names[]
edm::propagate_const< std::unique_ptr< RootOutputFile > > rootOutputFile_
static int const invalidSplitLevel
const_iterator end() const
Definition: Principal.h:169
void setAllowAnything()
allow any parameter label/value pairs
static int const invalidBasketSize
DropMetaData const & dropMetaData() const
BranchChildren branchChildren_
EventID const & id() const
std::vector< OutputItem > OutputItemList
std::string const & fileName() const
void insertEmpty(BranchID parent)
void insertChild(BranchID parent, BranchID child)
std::string const moduleLabel_
ParameterSet getUntrackedParameterSet(std::string const &name, ParameterSet const &defaultValue) const
bool int lh
Definition: SIMDVec.h:21
uint16_t size_type
virtual void doExtrasAfterCloseFile()
std::string const & logicalFileName() const
BranchType
Definition: BranchType.h:11
void fillSelectedItemList(BranchType branchtype, TTree *theInputTree)
std::vector< BranchID > const & parents() const
Definition: Parentage.h:44
PoolOutputModule(ParameterSet const &ps)
void setComment(std::string const &value)
bool operator()(OutputItem const &lh, OutputItem const &rh) const
std::string const & currentFileName() const
bool getMapped(key_type const &k, value_type &result) const
OutputItemListArray selectedOutputItemList_
int j
Definition: DBlmapReader.cc:9
void updateBranchParents(EventPrincipal const &ep)
SelectedProductsForBranchType const & keptProducts() const
int const & splitLevel() const
EventID const & min(EventID const &lh, EventID const &rh)
Definition: EventID.h:137
virtual void reallyOpenFile() override
BranchParents branchParents_
unsigned int numberOfDigitsInIndex_
void sort_all(RandomAccessSequence &s)
wrappers for std::sort
Definition: Algorithms.h:120
TTree * lumiTree() const
Definition: FileBlock.h:99
virtual bool shouldWeCloseFile() const override
allow inheriting classes to override but still be able to call this method in the overridden version ...
virtual void respondToCloseInputFile(FileBlock const &fb) override
virtual bool isFileOpen() const override
virtual void write(EventPrincipal const &e, ModuleCallingContext const *) override
const_iterator begin() const
Definition: Principal.h:168
virtual void beginJob() override
virtual void reallyCloseFile() override
void add(std::string const &label, ParameterSetDescription const &psetDescription)
virtual void writeLuminosityBlock(LuminosityBlockPrincipal const &lb, ModuleCallingContext const *) override
static void fillDescription(ParameterSetDescription &desc)
virtual void postForkReacquireResources(unsigned int iChildIndex, unsigned int iNumberOfChildren) override
std::shared_ptr< std::map< std::string, int > > treeMap_
boost::filter_iterator< FilledProductPtr, ProductHolderCollection::const_iterator > const_iterator
Definition: Principal.h:58
std::vector< BranchDescription const * > SelectedProducts
void beginInputFile(FileBlock const &fb)
volatile std::atomic< bool > shutdown_flag false
virtual void respondToOpenInputFile(FileBlock const &fb) override
static void fillDescriptions(ConfigurationDescriptions &descriptions)
static void fillDescription(ParameterSetDescription &desc)
moduleLabel_(iConfig.getParameter< string >("@module_label"))
static ParentageRegistry * instance()
TTree * runTree() const
Definition: FileBlock.h:101
TTree * tree() const
Definition: FileBlock.h:97