CMS 3D CMS Logo

EventContentAnalyzer.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: Modules
4 // Class: EventContentAnalyzer
5 //
12 //
13 // Original Author: Chris Jones
14 // Created: Mon Sep 19 11:47:28 CEST 2005
15 //
16 //
17 
18 // user include files
36 
37 // system include files
38 #include <algorithm>
39 #include <iomanip>
40 #include <iostream>
41 #include <map>
42 #include <sstream>
43 #include <string>
44 #include <vector>
45 
46 namespace edm {
48  namespace {
49  std::string formatClassName(std::string const& iName) { return std::string("(") + iName + ")"; }
50 
51  char const* kNameValueSep = "=";
53  template <typename T>
54  void doPrint(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
55  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep
56  << *reinterpret_cast<T*>(iObject.address()); // << "\n";
57  }
58 
59  template <>
60  void doPrint<char>(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
61  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep
62  << static_cast<int>(*reinterpret_cast<char*>(iObject.address())); // << "\n";
63  }
64 
65  template <>
66  void doPrint<unsigned char>(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
67  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep
68  << static_cast<unsigned int>(
69  *reinterpret_cast<unsigned char*>(iObject.address())); // << "\n";
70  }
71 
72  template <>
73  void doPrint<bool>(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
74  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep
75  << ((*reinterpret_cast<bool*>(iObject.address())) ? "true" : "false"); // << "\n";
76  }
77 
78  typedef void (*FunctionType)(std::string const&, ObjectWithDict const&, std::string const&);
79  typedef std::map<std::string, FunctionType> TypeToPrintMap;
80 
81  template <typename T>
82  void addToMap(TypeToPrintMap& iMap) {
83  iMap[typeid(T).name()] = doPrint<T>;
84  }
85 
86  bool printAsBuiltin(std::string const& iName, ObjectWithDict const& iObject, std::string const& iIndent) {
87  typedef void (*FunctionType)(std::string const&, ObjectWithDict const&, std::string const&);
88  typedef std::map<std::string, FunctionType> TypeToPrintMap;
89  static TypeToPrintMap s_map;
90  static bool isFirst = true;
91  if (isFirst) {
92  addToMap<bool>(s_map);
93  addToMap<char>(s_map);
94  addToMap<short>(s_map);
95  addToMap<int>(s_map);
96  addToMap<long>(s_map);
97  addToMap<unsigned char>(s_map);
98  addToMap<unsigned short>(s_map);
99  addToMap<unsigned int>(s_map);
100  addToMap<unsigned long>(s_map);
101  addToMap<float>(s_map);
102  addToMap<double>(s_map);
103  isFirst = false;
104  }
105  TypeToPrintMap::iterator itFound = s_map.find(iObject.typeOf().name());
106  if (itFound == s_map.end()) {
107  return false;
108  }
109  itFound->second(iName, iObject, iIndent);
110  return true;
111  }
112 
113  bool printAsContainer(std::string const& iName,
114  ObjectWithDict const& iObject,
115  std::string const& iIndent,
116  std::string const& iIndentDelta);
117 
118  void printObject(std::string const& iName,
119  ObjectWithDict const& iObject,
120  std::string const& iIndent,
121  std::string const& iIndentDelta) {
122  const std::string& printName = iName;
123  const ObjectWithDict& objectToPrint = iObject;
124  std::string indent(iIndent);
125  if (iObject.typeOf().isPointer()) {
126  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep << formatClassName(iObject.typeOf().name())
127  << std::hex << iObject.address() << std::dec; // << "\n";
128  TypeWithDict pointedType = iObject.typeOf().toType(); // for Pointers, I get the real type this way
129  if (TypeWithDict::byName("void") == pointedType || pointedType.isPointer() || iObject.address() == nullptr) {
130  return;
131  }
132  return;
133  /*
134  //have the code that follows print the contents of the data to which the pointer points
135  objectToPrint = ObjectWithDict(pointedType, iObject.address());
136  //try to convert it to its actual type (assuming the original type was a base class)
137  objectToPrint = ObjectWithDict(objectToPrint.castObject(objectToPrint.dynamicType()));
138  printName = std::string("*")+iName;
139  indent += iIndentDelta;
140  */
141  }
142  std::string typeName(objectToPrint.typeOf().name());
143  if (typeName.empty()) {
144  typeName = "<unknown>";
145  }
146 
147  if (printAsBuiltin(printName, objectToPrint, indent)) {
148  return;
149  }
150  if (printAsContainer(printName, objectToPrint, indent, iIndentDelta)) {
151  return;
152  }
153 
154  LogAbsolute("EventContent") << indent << printName << " " << formatClassName(typeName); // << "\n";
155  indent += iIndentDelta;
156  //print all the data members
157  TypeDataMembers dataMembers(objectToPrint.typeOf());
158  for (auto const& dataMember : dataMembers) {
159  MemberWithDict const member(dataMember);
160  //LogAbsolute("EventContent") << " debug " << member.name() << " " << member.typeName() << "\n";
161  try {
162  printObject(member.name(), member.get(objectToPrint), indent, iIndentDelta);
163  } catch (std::exception& iEx) {
164  LogAbsolute("EventContent") << indent << member.name() << " <exception caught(" << iEx.what() << ")>\n";
165  }
166  }
167  }
168 
169  bool printAsContainer(std::string const& iName,
170  ObjectWithDict const& iObject,
171  std::string const& iIndent,
172  std::string const& iIndentDelta) {
173  ObjectWithDict sizeObj;
174  try {
175  size_t temp; //used to hold the memory for the return value
176  FunctionWithDict sizeFunc = iObject.typeOf().functionMemberByName("size");
177  assert(sizeFunc.finalReturnType() == typeid(size_t));
178  sizeObj = ObjectWithDict(TypeWithDict(typeid(size_t)), &temp);
179  sizeFunc.invoke(iObject, &sizeObj);
180  //std::cout << "size of type '" << sizeObj.name() << "' " << sizeObj.typeName() << std::endl;
181  size_t size = *reinterpret_cast<size_t*>(sizeObj.address());
182  FunctionWithDict atMember;
183  try {
184  atMember = iObject.typeOf().functionMemberByName("at");
185  } catch (std::exception const& x) {
186  //std::cerr << "could not get 'at' member because " << x.what() << std::endl;
187  return false;
188  }
189  LogAbsolute("EventContent") << iIndent << iName << kNameValueSep << "[size=" << size << "]"; //"\n";
190  ObjectWithDict contained;
191  std::string indexIndent = iIndent + iIndentDelta;
192  TypeWithDict atReturnType(atMember.finalReturnType());
193  //std::cout << "return type " << atReturnType.name() << " size of " << atReturnType.SizeOf()
194  // << " pointer? " << atReturnType.isPointer() << " ref? " << atReturnType.isReference() << std::endl;
195 
196  //Return by reference must be treated differently since reflex will not properly create
197  // memory for a ref (which should just be a pointer to the object and not the object itself)
198  //So we will create memory on the stack which can be used to hold a reference
199  bool const isRef = atReturnType.isReference();
200  void* refMemoryBuffer = nullptr;
201  size_t index = 0;
202  //The argument to the 'at' function is the index. Since the argument list holds pointers to the arguments
203  // we only need to create it once and then when the value of index changes the pointer already
204  // gets the new value
205  std::vector<void*> args;
206  args.push_back(&index);
207  for (; index != size; ++index) {
208  std::ostringstream sizeS;
209  sizeS << "[" << index << "]";
210  if (isRef) {
211  ObjectWithDict refObject(atReturnType, &refMemoryBuffer);
212  atMember.invoke(iObject, &refObject, args);
213  //Although to hold the return value from a reference reflex requires you to pass it a
214  // void** when it tries to call methods on the reference it expects to be given a void*
215  contained = ObjectWithDict(atReturnType, refMemoryBuffer);
216  } else {
217  contained = atReturnType.construct();
218  atMember.invoke(iObject, &contained, args);
219  }
220  //LogAbsolute("EventContent") << "invoked 'at'" << std::endl;
221  try {
222  printObject(sizeS.str(), contained, indexIndent, iIndentDelta);
223  } catch (std::exception& iEx) {
224  LogAbsolute("EventContent") << indexIndent << iName << " <exception caught(" << iEx.what() << ")>\n";
225  }
226  if (!isRef) {
227  contained.destruct(true);
228  }
229  }
230  return true;
231  } catch (std::exception const& x) {
232  //std::cerr << "failed to invoke 'at' because " << x.what() << std::endl;
233  return false;
234  }
235  return false;
236  }
237 
238  void printObject(Event const& iEvent,
239  std::string const& iClassName,
240  std::string const& iModuleLabel,
241  std::string const& iInstanceLabel,
242  std::string const& iProcessName,
243  std::string const& iIndent,
244  std::string const& iIndentDelta) {
245  try {
246  GenericHandle handle(iClassName);
247  } catch (edm::Exception const&) {
248  LogAbsolute("EventContent") << iIndent << " \"" << iClassName << "\""
249  << " is an unknown type" << std::endl;
250  return;
251  }
252  GenericHandle handle(iClassName);
253  iEvent.getByLabel(InputTag(iModuleLabel, iInstanceLabel, iProcessName), handle);
254  std::string className = formatClassName(iClassName);
255  printObject(className, *handle, iIndent, iIndentDelta);
256  }
257  } // namespace
258 
260  public:
261  explicit EventContentAnalyzer(ParameterSet const&);
262  ~EventContentAnalyzer() override;
263 
264  void analyze(Event const&, EventSetup const&) override;
265  void endJob() override;
266 
267  static void fillDescriptions(ConfigurationDescriptions& descriptions);
268 
269  private:
270  // ----------member data ---------------------------
271  std::string indentation_;
272  std::string verboseIndentation_;
273  std::vector<std::string> moduleLabels_;
274  bool verbose_;
275  std::vector<std::string> getModuleLabels_;
276  bool getData_;
277  int evno_;
278  std::map<std::string, int> cumulates_;
281  };
282 
283  //
284  // constructors and destructor
285  //
287  : indentation_(iConfig.getUntrackedParameter("indentation", std::string("++"))),
288  verboseIndentation_(iConfig.getUntrackedParameter("verboseIndentation", std::string(" "))),
289  moduleLabels_(iConfig.getUntrackedParameter("verboseForModuleLabels", std::vector<std::string>())),
290  verbose_(iConfig.getUntrackedParameter("verbose", false) || !moduleLabels_.empty()),
291  getModuleLabels_(iConfig.getUntrackedParameter("getDataForModuleLabels", std::vector<std::string>())),
292  getData_(iConfig.getUntrackedParameter("getData", false) || !getModuleLabels_.empty()),
293  evno_(1),
294  listContent_(iConfig.getUntrackedParameter("listContent", true)),
295  listProvenance_(iConfig.getUntrackedParameter("listProvenance", false)) {
296  //now do what ever initialization is needed
299  if (getData_) {
301  if (getModuleLabels_.empty()) {
302  const std::string kPathStatus("edm::PathStatus");
303  const std::string kEndPathStatus("edm::EndPathStatus");
304  if (iBranch.className() != kPathStatus && iBranch.className() != kEndPathStatus) {
306  edm::InputTag{iBranch.moduleLabel(), iBranch.productInstanceName(), iBranch.processName()});
307  }
308  } else {
309  for (auto const& mod : this->getModuleLabels_) {
310  if (iBranch.moduleLabel() == mod) {
312  edm::InputTag{mod, iBranch.productInstanceName(), iBranch.processName()});
313  break;
314  }
315  }
316  }
317  });
318  }
319  }
320 
322  // do anything here that needs to be done at destruction time
323  // (e.g. close files, deallocate resources etc.)
324  }
325 
326  //
327  // member functions
328  //
329 
330  // ------------ method called to produce the data ------------
331  void EventContentAnalyzer::analyze(Event const& iEvent, EventSetup const&) {
332  typedef std::vector<StableProvenance const*> Provenances;
333  Provenances provenances;
334 
335  iEvent.getAllStableProvenance(provenances);
336 
337  if (listContent_) {
338  LogAbsolute("EventContent") << "\n"
339  << indentation_ << "Event " << std::setw(5) << evno_ << " contains "
340  << provenances.size() << " product" << (provenances.size() == 1 ? "" : "s")
341  << " with friendlyClassName, moduleLabel, productInstanceName and processName:"
342  << std::endl;
343  }
344 
345  std::string startIndent = indentation_ + verboseIndentation_;
346  for (auto const& provenance : provenances) {
347  std::string const& className = provenance->className();
348  const std::string kPathStatus("edm::PathStatus");
349  const std::string kEndPathStatus("edm::EndPathStatus");
350  if (className == kPathStatus || className == kEndPathStatus) {
351  continue;
352  }
353  std::string const& friendlyName = provenance->friendlyClassName();
354  //if(friendlyName.empty()) friendlyName = std::string("||");
355 
356  std::string const& modLabel = provenance->moduleLabel();
357  //if(modLabel.empty()) modLabel = std::string("||");
358 
359  std::string const& instanceName = provenance->productInstanceName();
360  //if(instanceName.empty()) instanceName = std::string("||");
361 
362  std::string const& processName = provenance->processName();
363 
364  bool doVerbose = verbose_ && (moduleLabels_.empty() || binary_search_all(moduleLabels_, modLabel));
365 
366  if (listContent_ || doVerbose) {
367  LogAbsolute("EventContent") << indentation_ << friendlyName << " \"" << modLabel << "\" \"" << instanceName
368  << "\" \"" << processName << "\""
369  << " (productId = " << provenance->productID() << ")" << std::endl;
370 
371  if (listProvenance_) {
372  auto const& prov = iEvent.getProvenance(provenance->branchID());
373  auto const* productProvenance = prov.productProvenance();
374  if (productProvenance) {
375  const bool isAlias = productProvenance->branchID() != provenance->branchID();
376  std::string aliasForModLabel;
377  LogAbsolute("EventContent") << prov;
378  if (isAlias) {
379  aliasForModLabel = iEvent.getProvenance(productProvenance->branchID()).moduleLabel();
380  LogAbsolute("EventContent") << "Is an alias for " << aliasForModLabel;
381  }
382  ProcessHistory const* processHistory = prov.processHistoryPtr();
383  if (processHistory) {
384  for (ProcessConfiguration const& pc : *processHistory) {
385  if (pc.processName() == prov.processName()) {
386  ParameterSetID const& psetID = pc.parameterSetID();
387  pset::Registry const* psetRegistry = pset::Registry::instance();
388  ParameterSet const* processPset = psetRegistry->getMapped(psetID);
389  if (processPset) {
390  if (processPset->existsAs<ParameterSet>(modLabel)) {
391  if (isAlias) {
392  LogAbsolute("EventContent") << "Alias PSet";
393  }
394  LogAbsolute("EventContent") << processPset->getParameterSet(modLabel);
395  }
396  if (isAlias and processPset->existsAs<ParameterSet>(aliasForModLabel)) {
397  LogAbsolute("EventContent") << processPset->getParameterSet(aliasForModLabel);
398  }
399  }
400  }
401  }
402  }
403  }
404  }
405  }
406  std::string key = friendlyName + std::string(" + \"") + modLabel + std::string("\" + \"") + instanceName +
407  "\" \"" + processName + "\"";
408  ++cumulates_[key];
409 
410  if (doVerbose) {
411  //indent one level before starting to print
412  printObject(iEvent, className, modLabel, instanceName, processName, startIndent, verboseIndentation_);
413  continue;
414  }
415  if (getData_) {
416  std::string class_and_label = friendlyName + "_" + modLabel;
417  if (getModuleLabels_.empty() || binary_search_all(getModuleLabels_, modLabel) ||
418  binary_search_all(getModuleLabels_, class_and_label)) {
419  try {
420  GenericHandle handle(className);
421  } catch (edm::Exception const&) {
422  LogAbsolute("EventContent") << startIndent << " \"" << className << "\""
423  << " is an unknown type" << std::endl;
424  return;
425  }
426  GenericHandle handle(className);
427  iEvent.getByLabel(InputTag(modLabel, instanceName, processName), handle);
428  }
429  }
430  }
431  //std::cout << "Mine" << std::endl;
432  ++evno_;
433  }
434 
435  // ------------ method called at end of job -------------------
437  typedef std::map<std::string, int> nameMap;
438 
439  LogAbsolute("EventContent") << "\nSummary for key being the concatenation of friendlyClassName, moduleLabel, "
440  "productInstanceName and processName"
441  << std::endl;
442  for (nameMap::const_iterator it = cumulates_.begin(), itEnd = cumulates_.end(); it != itEnd; ++it) {
443  LogAbsolute("EventContent") << std::setw(6) << it->second << " occurrences of key " << it->first << std::endl;
444  }
445 
446  // Test boost::lexical_cast We don't need this right now so comment it out.
447  // int k = 137;
448  // std::string ktext = boost::lexical_cast<std::string>(k);
449  // std::cout << "\nInteger " << k << " expressed as a string is |" << ktext << "|" << std::endl;
450  }
451 
453  descriptions.setComment(
454  "This plugin will print a list of all products in the event "
455  "provenance. It also has options to print and/or get each product.");
456 
458 
460 
461  std::string defaultString("++");
462  np = desc.addOptionalUntracked<std::string>("indentation", defaultString);
463  np->setComment("This string is printed at the beginning of every line printed during event processing.");
464 
465  np = desc.addOptionalUntracked<bool>("verbose", false);
466  np->setComment("If true, the contents of products are printed.");
467 
468  defaultString = " ";
469  np = desc.addOptionalUntracked<std::string>("verboseIndentation", defaultString);
470  np->setComment(
471  "This string is used to further indent lines when printing the contents of products in verbose mode.");
472 
473  std::vector<std::string> defaultVString;
474 
475  np = desc.addOptionalUntracked<std::vector<std::string> >("verboseForModuleLabels", defaultVString);
476  np->setComment("If this vector is not empty, then only products with module labels on this list are printed.");
477 
478  np = desc.addOptionalUntracked<bool>("getData", false);
479  np->setComment("If true the products will be retrieved using getByLabel.");
480 
481  np = desc.addOptionalUntracked<std::vector<std::string> >("getDataForModuleLabels", defaultVString);
482  np->setComment(
483  "If this vector is not empty, then only products with module labels on this list are retrieved by getByLabel.");
484 
485  np = desc.addOptionalUntracked<bool>("listContent", true);
486  np->setComment("If true then print a list of all the event content.");
487 
488  np = desc.addOptionalUntracked<bool>("listProvenance", false);
489  np->setComment("If true, and if listContent or verbose is true, print provenance information for each product");
490 
491  descriptions.add("printContent", desc);
492  }
493 } // namespace edm
494 
size
Write out results.
std::vector< std::string > getModuleLabels_
void setComment(std::string const &value)
BranchID const & branchID() const
bool existsAs(std::string const &parameterName, bool trackiness=true) const
checks if a parameter exists as a given type
Definition: ParameterSet.h:161
std::string const & processName() const
std::map< std::string, int > cumulates_
ProductProvenance const * productProvenance() const
Definition: Provenance.cc:35
example_stream void analyze(const edm::Event &, const edm::EventSetup &) override
static TypeWithDict byName(std::string const &name)
Definition: TypeWithDict.cc:74
EDGetTokenT< ProductType > consumes(edm::InputTag const &tag)
int iEvent
Definition: GenABIO.cc:224
void analyze(Event const &, EventSetup const &) override
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
std::string const & className() const
int np
Definition: AMPTWrapper.h:33
std::string friendlyName(std::string const &iFullName)
std::string const & moduleLabel() const
std::string const & productInstanceName() const
TypeID unwrappedTypeID() const
bool getMapped(key_type const &k, value_type &result) const
Definition: Registry.cc:17
static void fillDescriptions(ConfigurationDescriptions &descriptions)
bool getByLabel(InputTag const &tag, Handle< PROD > &result) const
Definition: Event.h:480
isFirst
Definition: cuy.py:419
void setComment(std::string const &value)
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
void sort_all(RandomAccessSequence &s)
wrappers for std::sort
Definition: Algorithms.h:92
ParameterSet const & getParameterSet(std::string const &) const
std::vector< std::string > moduleLabels_
void add(std::string const &label, ParameterSetDescription const &psetDescription)
void callWhenNewProductsRegistered(std::function< void(BranchDescription const &)> const &func)
Definition: EDAnalyzer.cc:96
HLT enums.
bool binary_search_all(ForwardSequence const &s, Datum const &d)
wrappers for std::binary_search
Definition: Algorithms.h:58
ParameterDescriptionBase * addOptionalUntracked(U const &iLabel, T const &value)
bool isPointer() const
Provenance getProvenance(BranchID const &theID) const
Definition: Event.cc:105
long double T
T mod(const T &a, const T &b)
Definition: ecalDccMap.h:4
static const bool doPrint
EventContentAnalyzer(ParameterSet const &)
static Registry * instance()
Definition: Registry.cc:12
std::string className(const T &t)
Definition: ClassName.h:30
void getAllStableProvenance(std::vector< StableProvenance const * > &provenances) const
Definition: Event.cc:117