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 
19 
20 #include "TTree.h"
21 #include "TBranchElement.h"
22 #include "TObjArray.h"
23 #include "RVersion.h"
24 
25 #include <fstream>
26 #include <iomanip>
27 #include <sstream>
28 
29 namespace edm {
31  OutputModule(pset),
32  rootServiceChecker_(),
33  auxItems_(),
34  selectedOutputItemList_(),
35  fileName_(pset.getUntrackedParameter<std::string>("fileName")),
36  logicalFileName_(pset.getUntrackedParameter<std::string>("logicalFileName")),
37  catalog_(pset.getUntrackedParameter<std::string>("catalog")),
38  maxFileSize_(pset.getUntrackedParameter<int>("maxSize")),
39  compressionLevel_(pset.getUntrackedParameter<int>("compressionLevel")),
40 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,30,0)
41  compressionAlgorithm_(pset.getUntrackedParameter<std::string>("compressionAlgorithm")),
42 #else
43  compressionAlgorithm_("ZLIB"),
44 #endif
45  basketSize_(pset.getUntrackedParameter<int>("basketSize")),
46  eventAutoFlushSize_(pset.getUntrackedParameter<int>("eventAutoFlushCompressedSize")),
47  splitLevel_(std::min<int>(pset.getUntrackedParameter<int>("splitLevel") + 1, 99)),
48  basketOrder_(pset.getUntrackedParameter<std::string>("sortBaskets")),
49  treeMaxVirtualSize_(pset.getUntrackedParameter<int>("treeMaxVirtualSize")),
50  whyNotFastClonable_(pset.getUntrackedParameter<bool>("fastCloning") ? FileBlock::CanFastClone : FileBlock::DisabledInConfigFile),
51  dropMetaData_(DropNone),
52  moduleLabel_(pset.getParameter<std::string>("@module_label")),
53  initializedFromInput_(false),
54  outputFileCount_(0),
55  inputFileCount_(0),
56  childIndex_(0U),
57  numberOfDigitsInIndex_(0U),
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 
68  std::string dropMetaData(pset.getUntrackedParameter<std::string>("dropMetaData"));
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  for(int i = InEvent; i < NumBranchTypes; ++i) {
92  BranchType branchType = static_cast<BranchType>(i);
93  Selections const& keptVector = keptProducts()[branchType];
94  for(Selections::const_iterator it = keptVector.begin(), itEnd = keptVector.end(); it != itEnd; ++it) {
95  BranchDescription const& prod = **it;
96  checkDictionaries(prod.fullClassName(), true);
98  }
99  }
100  }
101 
102  std::string const& PoolOutputModule::currentFileName() const {
103  return rootOutputFile_->fileName();
104  }
105 
107  basketSize_(BranchDescription::invalidBasketSize) {}
108 
110  branchDescription_(0),
111  product_(0),
112  splitLevel_(BranchDescription::invalidSplitLevel),
113  basketSize_(BranchDescription::invalidBasketSize) {}
114 
116  branchDescription_(bd),
117  product_(0),
118  splitLevel_(splitLevel),
119  basketSize_(basketSize) {}
120 
121 
122  PoolOutputModule::OutputItem::Sorter::Sorter(TTree* tree) : treeMap_(new std::map<std::string, int>) {
123  // Fill a map mapping branch names to an index specifying the order in the tree.
124  if(tree != 0) {
125  TObjArray* branches = tree->GetListOfBranches();
126  for(int i = 0; i < branches->GetEntries(); ++i) {
127  TBranchElement* br = (TBranchElement*)branches->At(i);
128  treeMap_->insert(std::make_pair(std::string(br->GetName()), i));
129  }
130  }
131  }
132 
133  bool
135  // Provides a comparison for sorting branches according to the index values in treeMap_.
136  // Branches not found are always put at the end (i.e. not found > found).
137  if(treeMap_->empty()) return lh < rh;
138  std::string const& lstring = lh.branchDescription_->branchName();
139  std::string const& rstring = rh.branchDescription_->branchName();
140  std::map<std::string, int>::const_iterator lit = treeMap_->find(lstring);
141  std::map<std::string, int>::const_iterator rit = treeMap_->find(rstring);
142  bool lfound = (lit != treeMap_->end());
143  bool rfound = (rit != treeMap_->end());
144  if(lfound && rfound) {
145  return lit->second < rit->second;
146  } else if(lfound) {
147  return true;
148  } else if(rfound) {
149  return false;
150  }
151  return lh < rh;
152  }
153 
155 
156  Selections const& keptVector = keptProducts()[branchType];
158  AuxItem& auxItem = auxItems_[branchType];
159 
160  // Fill AuxItem
161  if (theInputTree != 0 && !overrideInputFileSplitLevels_) {
162  TBranch* auxBranch = theInputTree->GetBranch(BranchTypeToAuxiliaryBranchName(branchType).c_str());
163  if (auxBranch) {
164  auxItem.basketSize_ = auxBranch->GetBasketSize();
165  } else {
166  auxItem.basketSize_ = basketSize_;
167  }
168  } else {
169  auxItem.basketSize_ = basketSize_;
170  }
171 
172  // Fill outputItemList with an entry for each branch.
173  for(Selections::const_iterator it = keptVector.begin(), itEnd = keptVector.end(); it != itEnd; ++it) {
176 
177  BranchDescription const& prod = **it;
178  TBranch* theBranch = ((!prod.produced() && theInputTree != 0 && !overrideInputFileSplitLevels_) ? theInputTree->GetBranch(prod.branchName().c_str()) : 0);
179 
180  if(theBranch != 0) {
181  splitLevel = theBranch->GetSplitLevel();
182  basketSize = theBranch->GetBasketSize();
183  } else {
184  splitLevel = (prod.splitLevel() == BranchDescription::invalidSplitLevel ? splitLevel_ : prod.splitLevel());
185  basketSize = (prod.basketSize() == BranchDescription::invalidBasketSize ? basketSize_ : prod.basketSize());
186  }
187  outputItemList.emplace_back(&prod, splitLevel, basketSize);
188  }
189 
190  // Sort outputItemList to allow fast copying.
191  // The branches in outputItemList must be in the same order as in the input tree, with all new branches at the end.
192  sort_all(outputItemList, OutputItem::Sorter(theInputTree));
193  }
194 
196  if(isFileOpen()) {
197  rootOutputFile_->beginInputFile(fb, remainingEvents());
198  }
199  }
200 
202  if(!isFileOpen()) {
203  doOpenFile();
204  beginInputFile(fb);
205  }
206  }
207 
209  if(!initializedFromInput_) {
210  for(int i = InEvent; i < NumBranchTypes; ++i) {
211  BranchType branchType = static_cast<BranchType>(i);
212  TTree* theInputTree = (branchType == InEvent ? fb.tree() :
213  (branchType == InLumi ? fb.lumiTree() :
214  fb.runTree()));
215  fillSelectedItemList(branchType, theInputTree);
216  }
217  initializedFromInput_ = true;
218  }
219  ++inputFileCount_;
220  beginInputFile(fb);
221  }
222 
224  if(rootOutputFile_) rootOutputFile_->respondToCloseInputFile(fb);
225  }
226 
227  void PoolOutputModule::postForkReacquireResources(unsigned int iChildIndex, unsigned int iNumberOfChildren) {
228  childIndex_ = iChildIndex;
229  while (iNumberOfChildren != 0) {
231  iNumberOfChildren /= 10;
232  }
233  if (numberOfDigitsInIndex_ == 0) {
234  numberOfDigitsInIndex_ = 3; // Protect against zero iNumberOfChildren
235  }
236  }
237 
239  }
240 
242  rootOutputFile_->writeOne(e);
243  if (!statusFileName_.empty()) {
244  std::ofstream statusFile(statusFileName_.c_str());
245  statusFile << e.id() << " time: " << std::setprecision(3) << TimeOfDay() << '\n';
246  statusFile.close();
247  }
248  }
249 
251  rootOutputFile_->writeLuminosityBlock(lb);
252  Service<JobReport> reportSvc;
253  reportSvc->reportLumiSection(lb.id().run(), lb.id().luminosityBlock());
254  }
255 
257  rootOutputFile_->writeRun(r);
258  Service<JobReport> reportSvc;
259  reportSvc->reportRunNumber(r.run());
260  }
261 
262  // At some later date, we may move functionality from finishEndFile() to here.
264 
265 
266  void PoolOutputModule::writeFileFormatVersion() { rootOutputFile_->writeFileFormatVersion(); }
267  void PoolOutputModule::writeFileIdentifier() { rootOutputFile_->writeFileIdentifier(); }
268  void PoolOutputModule::writeIndexIntoFile() { rootOutputFile_->writeIndexIntoFile(); }
269  void PoolOutputModule::writeProcessConfigurationRegistry() { rootOutputFile_->writeProcessConfigurationRegistry(); }
270  void PoolOutputModule::writeProcessHistoryRegistry() { rootOutputFile_->writeProcessHistoryRegistry(); }
271  void PoolOutputModule::writeParameterSetRegistry() { rootOutputFile_->writeParameterSetRegistry(); }
272  void PoolOutputModule::writeProductDescriptionRegistry() { rootOutputFile_->writeProductDescriptionRegistry(); }
273  void PoolOutputModule::writeParentageRegistry() { rootOutputFile_->writeParentageRegistry(); }
274  void PoolOutputModule::writeBranchIDListRegistry() { rootOutputFile_->writeBranchIDListRegistry(); }
275  void PoolOutputModule::writeProductDependencies() { rootOutputFile_->writeProductDependencies(); }
277  bool PoolOutputModule::isFileOpen() const { return rootOutputFile_.get() != 0; }
278  bool PoolOutputModule::shouldWeCloseFile() const { return rootOutputFile_->shouldWeCloseFile(); }
279 
281  if(inputFileCount_ == 0) {
283  << "Attempt to open output file before input file. "
284  << "Please report this to the core framework developers.\n";
285  }
286  std::string suffix(".root");
287  std::string::size_type offset = fileName().rfind(suffix);
288  bool ext = (offset == fileName().size() - suffix.size());
289  if(!ext) suffix.clear();
290  std::string fileBase(ext ? fileName().substr(0, offset) : fileName());
291  std::ostringstream ofilename;
292  std::ostringstream lfilename;
293  ofilename << fileBase;
294  lfilename << logicalFileName();
296  ofilename << '_' << std::setw(numberOfDigitsInIndex_) << std::setfill('0') << childIndex_;
297  if(!logicalFileName().empty()) {
298  lfilename << '_' << std::setw(numberOfDigitsInIndex_) << std::setfill('0') << childIndex_;
299  }
300  }
301  if(outputFileCount_) {
302  ofilename << std::setw(3) << std::setfill('0') << outputFileCount_;
303  if(!logicalFileName().empty()) {
304  lfilename << std::setw(3) << std::setfill('0') << outputFileCount_;
305  }
306  }
307  ofilename << suffix;
308  rootOutputFile_.reset(new RootOutputFile(this, ofilename.str(), lfilename.str()));
310  }
311 
312  void
314  std::string defaultString;
316  desc.setComment("Writes runs, lumis, and events into EDM/ROOT files.");
317  desc.addUntracked<std::string>("fileName")
318  ->setComment("Name of output file.");
319  desc.addUntracked<std::string>("logicalFileName", defaultString)
320  ->setComment("Passed to job report. Otherwise unused by module.");
321  desc.addUntracked<std::string>("catalog", defaultString)
322  ->setComment("Passed to job report. Otherwise unused by module.");
323  desc.addUntracked<int>("maxSize", 0x7f000000)
324  ->setComment("Maximum output file size, in kB.\n"
325  "If over maximum, new output file will be started at next input file transition.");
326  desc.addUntracked<int>("compressionLevel", 7)
327  ->setComment("ROOT compression level of output file.");
328 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,30,0)
329  desc.addUntracked<std::string>("compressionAlgorithm", "ZLIB")
330  ->setComment("Algorithm used to compress data in the ROOT output file, allowed values are ZLIB and LZMA");
331 #endif
332  desc.addUntracked<int>("basketSize", 16384)
333  ->setComment("Default ROOT basket size in output file.");
334  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.");
335  desc.addUntracked<int>("splitLevel", 99)
336  ->setComment("Default ROOT branch split level in output file.");
337  desc.addUntracked<std::string>("sortBaskets", std::string("sortbasketsbyoffset"))
338  ->setComment("Legal values: 'sortbasketsbyoffset', 'sortbasketsbybranch', 'sortbasketsbyentry'.\n"
339  "Used by ROOT when fast copying. Affects performance.");
340  desc.addUntracked<int>("treeMaxVirtualSize", -1)
341  ->setComment("Size of ROOT TTree TBasket cache. Affects performance.");
342  desc.addUntracked<bool>("fastCloning", true)
343  ->setComment("True: Allow fast copying, if possible.\n"
344  "False: Disable fast copying.");
345  desc.addUntracked<bool>("overrideInputFileSplitLevels", false)
346  ->setComment("False: Use branch split levels and basket sizes from input file, if possible.\n"
347  "True: Always use specified or default split levels and basket sizes.");
348  desc.addUntracked<bool>("writeStatusFile", false)
349  ->setComment("Write a status file. Intended for use by workflow management.");
350  desc.addUntracked<std::string>("dropMetaData", defaultString)
351  ->setComment("Determines handling of per product per event metadata. Options are:\n"
352  "'NONE': Keep all of it.\n"
353  "'DROPPED': Keep it for products produced in current process and all kept products. Drop it for dropped products produced in prior processes.\n"
354  "'PRIOR': Keep it for products produced in current process. Drop it for products produced in prior processes.\n"
355  "'ALL': Drop all of it.");
356  ParameterSetDescription dataSet;
357  dataSet.setAllowAnything();
358  desc.addUntracked<ParameterSetDescription>("dataset", dataSet)
359  ->setComment("PSet is only used by Data Operations and not by this module.");
360 
362 
363  descriptions.add("edmOutput", desc);
364  }
365 }
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:56
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:50
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: SSEVec.h:55
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
void fillSelectedItemList(BranchType branchtype, TTree *theInputTree)
bool wantAllEvents() const
Definition: OutputModule.h:68
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
tuple br
Definition: scaleCards.py:54
void checkDictionaries(std::string const &name, bool noComponents=false)
Definition: ReflexTools.cc:199
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:98
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()
perl if(1 lt scalar(@::datatypes))
Definition: edlooper.cc:31
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:100
TTree * tree() const
Definition: FileBlock.h:96
virtual void writeRun(RunPrincipal const &r)