CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
NanoAODOutputModule.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: PhysicsTools/NanoAODOutput
4 // Class : NanoAODOutputModule
5 //
6 // Implementation:
7 // [Notes on implementation]
8 //
9 // Original Author: Christopher Jones
10 // Created: Mon, 07 Aug 2017 14:21:41 GMT
11 //
12 
13 // system include files
14 #include <algorithm>
15 #include <memory>
16 
17 #include "Compression.h"
18 #include "TFile.h"
19 #include "TObjString.h"
20 #include "TROOT.h"
21 #include "TTree.h"
22 #include <string>
23 
24 // user include files
45 
46 #include <iostream>
47 
48 #include "tbb/task_arena.h"
49 
51 public:
53  ~NanoAODOutputModule() override;
54 
55  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
56 
57 private:
58  void write(edm::EventForOutput const& e) override;
60  void writeRun(edm::RunForOutput const&) override;
61  bool isFileOpen() const override;
62  void openFile(edm::FileBlock const&) override;
63  void reallyCloseFile() override;
64 
71  bool m_fakeName; //crab workaround, remove after crab is fixed
75  std::unique_ptr<TFile> m_file;
77 
78  static constexpr int m_firstFlush{1000};
79 
81  public:
82  void branch(TTree& tree) {
83  tree.Branch("run", &m_run, "run/i");
84  tree.Branch("luminosityBlock", &m_luminosityBlock, "luminosityBlock/i");
85  tree.Branch("event", &m_event, "event/l");
86  }
87  void fill(const edm::EventID& id) {
88  m_run = id.run();
89  m_luminosityBlock = id.luminosityBlock();
90  m_event = id.event();
91  }
92 
93  private:
94  UInt_t m_run;
96  ULong64_t m_event;
98 
100  public:
101  void branch(TTree& tree) {
102  tree.Branch("run", &m_run, "run/i");
103  tree.Branch("luminosityBlock", &m_luminosityBlock, "luminosityBlock/i");
104  }
105  void fill(const edm::LuminosityBlockID& id) {
106  m_run = id.run();
107  m_luminosityBlock = id.value();
108  }
109 
110  private:
111  UInt_t m_run;
114 
116  public:
117  void branch(TTree& tree) { tree.Branch("run", &m_run, "run/i"); }
118  void fill(const edm::RunID& id) { m_run = id.run(); }
119 
120  private:
121  UInt_t m_run;
123 
124  std::vector<TableOutputBranches> m_tables;
125  std::vector<TriggerOutputBranches> m_triggers;
126  bool m_triggers_areSorted = false;
127  std::vector<EventStringOutputBranches> m_evstrings;
128 
129  std::vector<SummaryTableOutputBranches> m_runTables;
130  std::vector<SummaryTableOutputBranches> m_lumiTables;
131  std::vector<TableOutputBranches> m_runFlatTables;
132 
133  std::vector<std::pair<std::string, edm::EDGetToken>> m_nanoMetadata;
134 };
135 
136 //
137 // constants, enums and typedefs
138 //
139 
140 //
141 // static data member definitions
142 //
143 
144 //
145 // constructors and destructor
146 //
148  : edm::one::OutputModuleBase::OutputModuleBase(pset),
149  edm::one::OutputModule<>(pset),
150  m_fileName(pset.getUntrackedParameter<std::string>("fileName")),
151  m_logicalFileName(pset.getUntrackedParameter<std::string>("logicalFileName")),
152  m_compressionLevel(pset.getUntrackedParameter<int>("compressionLevel")),
153  m_compressionAlgorithm(pset.getUntrackedParameter<std::string>("compressionAlgorithm")),
154  m_writeProvenance(pset.getUntrackedParameter<bool>("saveProvenance", true)),
155  m_fakeName(pset.getUntrackedParameter<bool>("fakeNameForCrab", false)),
156  m_autoFlush(pset.getUntrackedParameter<int>("autoFlush", -10000000)),
157  m_processHistoryRegistry() {}
158 
160 
162  //Get data from 'e' and write it to the file
164  jr->eventWrittenToFile(m_jrToken, iEvent.id().run(), iEvent.id().event());
165 
166  if (m_autoFlush) {
167  int64_t events = m_tree->GetEntriesFast();
168  if (events == m_firstFlush) {
169  m_tree->FlushBaskets();
170  float maxMemory;
171  if (m_autoFlush > 0) {
172  // Estimate the memory we'll be using at the first full flush by
173  // linearly scaling the number of events.
174  float percentClusterDone = m_firstFlush / static_cast<float>(m_autoFlush);
175  maxMemory = static_cast<float>(m_tree->GetTotBytes()) / percentClusterDone;
176  } else if (m_tree->GetZipBytes() == 0) {
177  maxMemory = 100 * 1024 * 1024; // Degenerate case of no information in the tree; arbitrary value
178  } else {
179  // Estimate the memory we'll be using by scaling the current compression ratio.
180  float cxnRatio = m_tree->GetTotBytes() / static_cast<float>(m_tree->GetZipBytes());
181  maxMemory = -m_autoFlush * cxnRatio;
182  float percentBytesDone = -m_tree->GetZipBytes() / static_cast<float>(m_autoFlush);
183  m_autoFlush = m_firstFlush / percentBytesDone;
184  }
185  //std::cout << "OptimizeBaskets: total bytes " << m_tree->GetTotBytes() << std::endl;
186  //std::cout << "OptimizeBaskets: zip bytes " << m_tree->GetZipBytes() << std::endl;
187  //std::cout << "OptimizeBaskets: autoFlush " << m_autoFlush << std::endl;
188  //std::cout << "OptimizeBaskets: maxMemory " << static_cast<uint32_t>(maxMemory) << std::endl;
189  //m_tree->OptimizeBaskets(static_cast<uint32_t>(maxMemory), 1, "d");
190  m_tree->OptimizeBaskets(static_cast<uint32_t>(maxMemory), 1, "");
191  }
193  m_tree->FlushBaskets();
194  m_eventsSinceFlush = 0;
195  }
197  }
198 
199  m_commonBranches.fill(iEvent.id());
200  // fill all tables, starting from main tables and then doing extension tables
201  for (unsigned int extensions = 0; extensions <= 1; ++extensions) {
202  for (auto& t : m_tables)
203  t.fill(iEvent, *m_tree, extensions);
204  }
205  if (!m_triggers_areSorted) { // sort triggers/flags in inverse processHistory order, to save without any special label the most recent ones
206  std::vector<std::string> pnames;
207  for (auto& p : iEvent.processHistory())
208  pnames.push_back(p.processName());
209  std::sort(m_triggers.begin(), m_triggers.end(), [pnames](TriggerOutputBranches& a, TriggerOutputBranches& b) {
210  return ((std::find(pnames.begin(), pnames.end(), a.processName()) - pnames.begin()) >
211  (std::find(pnames.begin(), pnames.end(), b.processName()) - pnames.begin()));
212  });
213  m_triggers_areSorted = true;
214  }
215  // fill triggers
216  for (auto& t : m_triggers)
217  t.fill(iEvent, *m_tree);
218  // fill event branches
219  for (auto& t : m_evstrings)
220  t.fill(iEvent, *m_tree);
221  tbb::this_task_arena::isolate([&] { m_tree->Fill(); });
222 
224 }
225 
228  jr->reportLumiSection(m_jrToken, iLumi.id().run(), iLumi.id().value());
229 
230  m_commonLumiBranches.fill(iLumi.id());
231 
232  for (auto& t : m_lumiTables)
233  t.fill(iLumi, *m_lumiTree);
234 
235  tbb::this_task_arena::isolate([&] { m_lumiTree->Fill(); });
236 
238 }
239 
242  jr->reportRunNumber(m_jrToken, iRun.id().run());
243 
244  m_commonRunBranches.fill(iRun.id());
245 
246  for (auto& t : m_runTables)
247  t.fill(iRun, *m_runTree);
248 
249  for (unsigned int extensions = 0; extensions <= 1; ++extensions) {
250  for (auto& t : m_runFlatTables)
251  t.fill(iRun, *m_runTree, extensions);
252  }
253 
255  for (const auto& p : m_nanoMetadata) {
256  iRun.getByToken(p.second, hstring);
257  TObjString* tos = dynamic_cast<TObjString*>(m_file->Get(p.first.c_str()));
258  if (tos) {
259  if (hstring->str() != tos->GetString())
260  throw cms::Exception("LogicError", "Inconsistent nanoMetadata " + p.first + " (" + hstring->str() + ")");
261  } else {
262  auto ostr = std::make_unique<TObjString>(hstring->str().c_str());
263  m_file->WriteTObject(ostr.release(), p.first.c_str());
264  }
265  }
266 
267  tbb::this_task_arena::isolate([&] { m_runTree->Fill(); });
268 
270 }
271 
272 bool NanoAODOutputModule::isFileOpen() const { return nullptr != m_file.get(); }
273 
275  m_file = std::make_unique<TFile>(m_fileName.c_str(), "RECREATE", "", m_compressionLevel);
277  cms::Digest branchHash;
278  m_jrToken = jr->outputFileOpened(m_fileName,
280  std::string(),
281  m_fakeName ? "PoolOutputModule" : "NanoAODOutputModule",
282  description().moduleLabel(),
284  std::string(),
285  branchHash.digest().toString(),
286  std::vector<std::string>());
287 
288  if (m_compressionAlgorithm == std::string("ZLIB")) {
289  m_file->SetCompressionAlgorithm(ROOT::kZLIB);
290  } else if (m_compressionAlgorithm == std::string("LZMA")) {
291  m_file->SetCompressionAlgorithm(ROOT::kLZMA);
292  } else {
293  throw cms::Exception("Configuration")
294  << "NanoAODOutputModule configured with unknown compression algorithm '" << m_compressionAlgorithm << "'\n"
295  << "Allowed compression algorithms are ZLIB and LZMA\n";
296  }
297  /* Setup file structure here */
298  m_tables.clear();
299  m_triggers.clear();
300  m_triggers_areSorted = false;
301  m_evstrings.clear();
302  m_runTables.clear();
303  m_lumiTables.clear();
304  m_runFlatTables.clear();
305  const auto& keeps = keptProducts();
306  for (const auto& keep : keeps[edm::InEvent]) {
307  if (keep.first->className() == "nanoaod::FlatTable")
308  m_tables.emplace_back(keep.first, keep.second);
309  else if (keep.first->className() == "edm::TriggerResults") {
310  m_triggers.emplace_back(keep.first, keep.second);
311  } else if (keep.first->className() == "std::basic_string<char,std::char_traits<char> >" &&
312  keep.first->productInstanceName() == "genModel") { // friendlyClassName == "String"
313  m_evstrings.emplace_back(keep.first, keep.second, true); // update only at lumiBlock transitions
314  } else
315  throw cms::Exception("Configuration", "NanoAODOutputModule cannot handle class " + keep.first->className());
316  }
317 
318  for (const auto& keep : keeps[edm::InLumi]) {
319  if (keep.first->className() == "nanoaod::MergeableCounterTable")
320  m_lumiTables.push_back(SummaryTableOutputBranches(keep.first, keep.second));
321  else if (keep.first->className() == "nanoaod::UniqueString" && keep.first->moduleLabel() == "nanoMetadata")
322  m_nanoMetadata.emplace_back(keep.first->productInstanceName(), keep.second);
323  else
324  throw cms::Exception(
325  "Configuration",
326  "NanoAODOutputModule cannot handle class " + keep.first->className() + " in LuminosityBlock branch");
327  }
328 
329  for (const auto& keep : keeps[edm::InRun]) {
330  if (keep.first->className() == "nanoaod::MergeableCounterTable")
331  m_runTables.push_back(SummaryTableOutputBranches(keep.first, keep.second));
332  else if (keep.first->className() == "nanoaod::UniqueString" && keep.first->moduleLabel() == "nanoMetadata")
333  m_nanoMetadata.emplace_back(keep.first->productInstanceName(), keep.second);
334  else if (keep.first->className() == "nanoaod::FlatTable")
335  m_runFlatTables.emplace_back(keep.first, keep.second);
336  else
337  throw cms::Exception("Configuration",
338  "NanoAODOutputModule cannot handle class " + keep.first->className() + " in Run branch");
339  }
340 
341  // create the trees
342  m_tree = std::make_unique<TTree>("Events", "Events");
343  m_tree->SetAutoSave(0);
344  m_tree->SetAutoFlush(0);
346 
347  m_lumiTree = std::make_unique<TTree>("LuminosityBlocks", "LuminosityBlocks");
348  m_lumiTree->SetAutoSave(0);
350 
351  m_runTree = std::make_unique<TTree>("Runs", "Runs");
352  m_runTree->SetAutoSave(0);
354 
355  if (m_writeProvenance) {
356  m_metaDataTree = std::make_unique<TTree>(edm::poolNames::metaDataTreeName().c_str(), "Job metadata");
357  m_metaDataTree->SetAutoSave(0);
358  m_parameterSetsTree = std::make_unique<TTree>(edm::poolNames::parameterSetsTreeName().c_str(), "Parameter sets");
359  m_parameterSetsTree->SetAutoSave(0);
360  }
361 }
363  if (m_writeProvenance) {
364  int basketSize = 16384; // fixme configurable?
367  if (m_metaDataTree->GetNbranches() != 0) {
368  m_metaDataTree->SetEntries(-1);
369  }
370  if (m_parameterSetsTree->GetNbranches() != 0) {
371  m_parameterSetsTree->SetEntries(-1);
372  }
373  }
374  m_file->Write();
375  m_file->Close();
376  m_file.reset();
377  m_tree.release(); // apparently root has ownership
378  m_lumiTree.release(); //
379  m_runTree.release(); //
380  m_metaDataTree.release(); //
381  m_parameterSetsTree.release(); //
384 }
385 
388 
389  desc.addUntracked<std::string>("fileName");
390  desc.addUntracked<std::string>("logicalFileName", "");
391 
392  desc.addUntracked<int>("compressionLevel", 9)->setComment("ROOT compression level of output file.");
393  desc.addUntracked<std::string>("compressionAlgorithm", "ZLIB")
394  ->setComment("Algorithm used to compress data in the ROOT output file, allowed values are ZLIB and LZMA");
395  desc.addUntracked<bool>("saveProvenance", true)
396  ->setComment("Save process provenance information, e.g. for edmProvDump");
397  desc.addUntracked<bool>("fakeNameForCrab", false)
398  ->setComment(
399  "Change the OutputModule name in the fwk job report to fake PoolOutputModule. This is needed to run on cran "
400  "(and publish) till crab is fixed");
401  desc.addUntracked<int>("autoFlush", -10000000)->setComment("Autoflush parameter for ROOT file");
402 
403  //replace with whatever you want to get from the EDM by default
404  const std::vector<std::string> keep = {"drop *",
405  "keep nanoaodFlatTable_*Table_*_*",
406  "keep edmTriggerResults_*_*_*",
407  "keep String_*_genModel_*",
408  "keep nanoaodMergeableCounterTable_*Table_*_*",
409  "keep nanoaodUniqueString_nanoMetadata_*_*"};
411 
412  //Used by Workflow management for their own meta data
414  dataSet.setAllowAnything();
415  desc.addUntracked<edm::ParameterSetDescription>("dataset", dataSet)
416  ->setComment("PSet is only used by Data Operations and not by this module.");
417 
419  branchSet.setAllowAnything();
420  desc.add<edm::ParameterSetDescription>("branches", branchSet);
421 
422  descriptions.addDefault(desc);
423 }
424 
RunNumber_t run() const
Definition: EventID.h:38
std::unique_ptr< TTree > m_runTree
EventNumber_t event() const
Definition: EventID.h:40
std::vector< TableOutputBranches > m_runFlatTables
std::unique_ptr< TTree > m_lumiTree
EventID const & id() const
std::vector< SummaryTableOutputBranches > m_lumiTables
ParameterDescriptionBase * addUntracked(U const &iLabel, T const &value)
RunNumber_t run() const
Definition: RunID.h:36
std::unique_ptr< TTree > m_tree
void setAllowAnything()
allow any parameter label/value pairs
RunID const & id() const
Definition: RunForOutput.h:55
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
void fillParameterSetBranch(TTree *parameterSetsTree, int basketSize)
bool registerProcessHistory(ProcessHistory const &processHistory)
void fillProcessHistoryBranch(TTree *metaDataTree, int basketSize, ProcessHistoryRegistry const &processHistoryRegistry)
NanoAODOutputModule(edm::ParameterSet const &pset)
bool isFileOpen() const override
void fill(const edm::LuminosityBlockID &id)
void reportRunNumber(JobReport::Token token, unsigned int run)
Definition: JobReport.cc:469
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
std::string const & parameterSetsTreeName()
Definition: BranchType.cc:216
std::unique_ptr< TTree > m_parameterSetsTree
void writeRun(edm::RunForOutput const &) override
class NanoAODOutputModule::CommonLumiBranches m_commonLumiBranches
std::unique_ptr< TTree > m_metaDataTree
const int keep
std::unique_ptr< TFile > m_file
int iEvent
Definition: GenABIO.cc:224
void addDefault(ParameterSetDescription const &psetDescription)
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
virtual ProcessHistory const & processHistory() const
MD5Result digest()
Definition: Digest.cc:171
std::vector< EventStringOutputBranches > m_evstrings
ModuleDescription const & description() const
std::vector< SummaryTableOutputBranches > m_runTables
std::vector< TableOutputBranches > m_tables
static constexpr int m_firstFlush
std::vector< TriggerOutputBranches > m_triggers
RunNumber_t run() const
uint64_t value() const
std::vector< std::pair< std::string, edm::EDGetToken > > m_nanoMetadata
std::string const & metaDataTreeName()
Definition: BranchType.cc:159
ParameterDescriptionBase * add(U const &iLabel, T const &value)
std::size_t Token
Definition: JobReport.h:106
void openFile(edm::FileBlock const &) override
std::string createGlobalIdentifier(bool binary=false)
void reallyCloseFile() override
void eventWrittenToFile(Token fileToken, RunNumber_t run, EventNumber_t event)
Definition: JobReport.cc:428
std::string toString() const
Definition: Digest.cc:95
double b
Definition: hdecay.h:118
BasicHandle getByToken(EDGetToken token, TypeID const &typeID) const
tuple events
Definition: patZpeak.py:20
double a
Definition: hdecay.h:119
void outputFileClosed(Token fileToken)
Definition: JobReport.cc:433
void write(edm::EventForOutput const &e) override
class NanoAODOutputModule::CommonRunBranches m_commonRunBranches
SelectedProductsForBranchType const & keptProducts() const
edm::JobReport::Token m_jrToken
class NanoAODOutputModule::CommonEventBranches m_commonBranches
edm::ProcessHistoryRegistry m_processHistoryRegistry
LuminosityBlockID const & id() const
static void fillDescription(ParameterSetDescription &desc, std::vector< std::string > const &iDefaultOutputCommands=ProductSelectorRules::defaultSelectionStrings())
std::string m_compressionAlgorithm
void reportLumiSection(JobReport::Token token, unsigned int run, unsigned int lumiSectId, unsigned long nEvents=0)
Definition: JobReport.cc:458
void writeLuminosityBlock(edm::LuminosityBlockForOutput const &) override