CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
FWFileEntry.cc
Go to the documentation of this file.
1 #include <boost/regex.hpp>
2 
3 #include "TFile.h"
4 #include "TTreeCache.h"
5 #include "TEveTreeTools.h"
6 #include "TError.h"
7 #include "TMath.h"
8 
14 
17 
18 #define private public
20 #undef private
21 
26 
27 FWFileEntry::FWFileEntry(const std::string& name, bool checkVersion) :
28  m_name(name), m_file(0), m_eventTree(0), m_event(0),
29  m_needUpdate(true), m_globalEventList(0)
30 {
31  openFile(checkVersion);
32 }
33 
35 {
36  for(std::list<Filter*>::iterator i = m_filterEntries.begin(); i != m_filterEntries.end(); ++i)
37  delete (*i)->m_eventList;
38 
39  delete m_globalEventList;
40 }
41 
42 void FWFileEntry::openFile(bool checkVersion)
43 {
44  gErrorIgnoreLevel = 3000; // suppress warnings about missing dictionaries
45  TFile *newFile = TFile::Open(m_name.c_str());
46  if (newFile == 0 || newFile->IsZombie() || !newFile->Get("Events")) {
47  // std::cout << "Invalid file. Ignored." << std::endl;
48  // return false;
49  throw std::runtime_error("Invalid file. Ignored.");
50  }
51  gErrorIgnoreLevel = -1;
52  m_file = newFile;
53 
54 
55  // check CMSSW relese version for compatibility
56  if (checkVersion) {
57  typedef std::vector<edm::ProcessHistory> provList;
58 
59  TTree *metaData = dynamic_cast<TTree*>(m_file->Get("MetaData"));
60  TBranch *b = metaData->GetBranch("ProcessHistory");
61  provList *x = 0;
62  b->SetAddress(&x);
63  b->GetEntry(0);
64 
65  const edm::ProcessConfiguration* dd = 0;
66  int latestVersion =0;
67  int currentVersionArr[] = {0, 0, 0};
68  for (auto const& processHistory : *x)
69  {
70  for (auto const& processConfiguration : processHistory)
71  {
72  // std::cout << processConfiguration.releaseVersion() << " " << processConfiguration.processName() << std::endl;
73  TString dcv = processConfiguration.releaseVersion();
74  fireworks::getDecomposedVersion(dcv, currentVersionArr);
75  int nvv = currentVersionArr[0]*100 + currentVersionArr[1]*10 + currentVersionArr[2];
76  if (nvv > latestVersion) {
77  latestVersion = nvv;
79  }
80  }
81  }
82 
83  if (latestVersion) {
84  fwLog(fwlog::kInfo) << "Checking process history. " << m_name.c_str() << " latest process \"" << dd->processName() << "\", version " << dd->releaseVersion() << std::endl;
85 
86  b->SetAddress(0);
87  TString v = dd->releaseVersion();
89  {
91  TString msg = Form("incompatible data: Process version does not mactch major data formats version. File produced with %s. Data formats version \"CMSSW_%d_%d_%d\".\n",
92  dd->releaseVersion().c_str(), di[0], di[1], di[2]);
93  msg += "Use --no-version-check option if you still want to view the file.\n";
94  throw std::runtime_error(msg.Data());
95  }
96  }
97  else {
98  TString msg = "No process history available\n";
99  msg += "Use --no-version-check option if you still want to view the file.\n";
100  throw std::runtime_error(msg.Data());
101  }
102  }
103 
104  // load event
106 
107  if (m_event->size() == 0)
108  throw std::runtime_error("fwlite::Event size == 0");
109 
110 
111  m_eventTree = dynamic_cast<TTree*>(m_file->Get("Events"));
112 
113  if (m_eventTree == 0)
114  {
115  throw std::runtime_error("Cannot find TTree 'Events' in the data file");
116  }
117 
118  // This now set in DataHelper
119  //TTreeCache::SetLearnEntries(2);
120  //m_eventTree->SetCacheSize(10*1024*1024);
121  //TTreeCache *tc = (TTreeCache*) m_file->GetCacheRead();
122  //tc->AddBranch(m_event->auxBranch_,kTRUE);
123  //tc->StartLearningPhase();
124 }
125 
127 {
128  if (m_file) {
129  printf("Reading %lld bytes in %d transactions.\n",
130  m_file->GetBytesRead(), m_file->GetReadCalls());
131  delete m_file->GetCacheRead(m_eventTree);
132 
133  m_file->Close();
134  delete m_file;
135  }
136  if (m_event) delete m_event;
137 }
138 
139 //______________________________________________________________________________
140 
141 bool FWFileEntry::isEventSelected(int tree_entry)
142 {
143  int idx = m_globalEventList->GetIndex(tree_entry);
144  return idx >= 0;
145 }
146 
148 {
149  return m_globalEventList->GetN() > 0;
150 }
151 
153 {
154  if (m_globalEventList->GetN() > 0)
155  {
156  return m_globalEventList->GetEntry(0);
157  }
158  else
159  {
160  return -1;
161  }
162 }
163 
165 {
166  if (m_globalEventList->GetN() > 0)
167  return m_globalEventList->GetEntry(m_globalEventList->GetN() - 1);
168  else
169  return -1;
170 }
171 
173 {
174  // Find next selected event after the current one.
175  // This returns the index in the selected event list.
176  // If none exists -1 is returned.
177 
178  const Long64_t *list = m_globalEventList->GetList();
179  Long64_t val = tree_entry;
180  Long64_t idx = TMath::BinarySearch(m_globalEventList->GetN(), list, val);
181  ++idx;
182  if (idx >= m_globalEventList->GetN() || idx < 0)
183  return -1;
184  return list[idx];
185 }
186 
188 {
189  // Find first selected event before current one.
190  // This returns the index in the selected event list.
191  // If none exists -1 is returned.
192 
193  const Long64_t *list = m_globalEventList->GetList();
194  Long64_t val = tree_entry;
195  Long64_t idx = TMath::BinarySearch(m_globalEventList->GetN(), list, val);
196  if (list[idx] == val)
197  --idx;
198  if (idx >= 0)
199  return list[idx];
200  else
201  return -1;
202 }
203 
204 //______________________________________________________________________________
206 {
207  for (std::list<Filter*>::iterator it = m_filterEntries.begin(); it != m_filterEntries.end(); ++it)
208  {
209  if ((*it)->m_selector->m_enabled)
210  return true;
211  }
212 
213  return false;
214 }
215 
216 //______________________________________________________________________________
217 void FWFileEntry::updateFilters(const FWEventItemsManager* eiMng, bool globalOR)
218 {
219  if (!m_needUpdate)
220  return;
221 
222  if (m_globalEventList)
223  m_globalEventList->Reset();
224  else
226 
227  for (std::list<Filter*>::iterator it = m_filterEntries.begin(); it != m_filterEntries.end(); ++it)
228  {
229  if ((*it)->m_selector->m_enabled && (*it)->m_needsUpdate)
230  {
231  runFilter(*it, eiMng);
232  }
233  // Need to re-check if enabled after filtering as it can be set to false
234  // in runFilter().
235  if ((*it)->m_selector->m_enabled)
236  {
237  if ((*it)->hasSelectedEvents())
238  {
239  if (globalOR || m_globalEventList->GetN() == 0)
240  {
241  m_globalEventList->Add((*it)->m_eventList);
242  }
243  else
244  {
245  m_globalEventList->Intersect((*it)->m_eventList);
246  }
247  }
248  else if (!globalOR)
249  {
250  m_globalEventList->Reset();
251  break;
252  }
253  }
254  }
255 
256  fwLog(fwlog::kDebug) << "FWFileEntry::updateFilters in [" << m_file->GetName() << "] global selection [" << m_globalEventList->GetN() << "/" << m_eventTree->GetEntries() << "]" << std::endl;
257 
258  m_needUpdate = false;
259 }
260 
261 //_____________________________________________________________________________
263 {
264  if (!filter->m_selector->m_triggerProcess.empty())
265  {
267  return;
268  }
269 
270  // parse selection for known Fireworks expressions
271  std::string interpretedSelection = filter->m_selector->m_expression;
272 
274  end = eiMng->end(); i != end; ++i)
275  {
276  FWEventItem *item = *i;
277  if (item == 0)
278  continue;
279  // FIXME: hack to get full branch name filled
280  if (item->m_event == 0)
281  {
282  item->m_event = m_event;
283  item->getPrimaryData();
284  item->m_event = 0;
285  }
286 
287  boost::regex re(std::string("\\$") + (*i)->name());
288 
289  if (boost::regex_search(interpretedSelection, re))
290  {
291  const edm::TypeWithDict elementType(const_cast<TClass*>(item->type()));
292  const edm::TypeWithDict wrapperType = edm::TypeWithDict::byName(edm::wrappedClassName(elementType.name()));
293  std::string fullBranchName = m_event->getBranchNameFor(wrapperType.typeInfo(),
294  item->moduleLabel().c_str(),
295  item->productInstanceLabel().c_str(),
296  item->processName().c_str());
297 
298  interpretedSelection = boost::regex_replace(interpretedSelection, re,
299  fullBranchName + ".obj");
300 
301  // printf("selection after applying s/%s/%s/: %s\n",
302  // (std::string("\\$") + (*i)->name()).c_str(),
303  // ((*i)->m_fullBranchName + ".obj").c_str(),
304  // interpretedSelection.c_str());
305  }
306  }
307 
308 
309  std::size_t found = interpretedSelection.find('$');
310  if (found!=std::string::npos)
311  {
312  fwLog(fwlog::kError) << "FWFileEntry::RunFilter invalid expression " << interpretedSelection << std::endl;
313  filter->m_needsUpdate = false;
314  return;
315  }
316 
317  m_file->cd();
318  m_eventTree->SetEventList(0);
319 
320  // Since ROOT will leave any TBranches used in the filtering at the last event,
321  // we need to be able to reset them to what fwlite::Event expects them to be
322  // we do this by holding onto the old buffers and create temporary new ones.
323 
324  std::map<TBranch*, void*> prevAddrs;
325 
326  {
327  TObjArray* branches = m_eventTree->GetListOfBranches();
328  std::auto_ptr<TIterator> pIt( branches->MakeIterator());
329  while (TObject* branchObj = pIt->Next())
330  {
331  TBranch* b = dynamic_cast<TBranch*> (branchObj);
332  if (0!=b)
333  {
334  const char * name = b->GetName();
335  unsigned int length = strlen(name);
336  if (length > 1 && name[length-1] != '.')
337  {
338  // This is not a data branch so we should ignore it.
339  continue;
340  }
341  if (0 != b->GetAddress())
342  {
343  if (prevAddrs.find(b) != prevAddrs.end())
344  {
345  fwLog(fwlog::kWarning) << "FWFileEntry::runFilter branch is already in the map!\n";
346  }
347  prevAddrs.insert(std::make_pair(b, b->GetAddress()));
348 
349  // std::cout <<"Zeroing branch: "<< b->GetName() <<" "<< (void*) b->GetAddress() <<std::endl;
350  b->SetAddress(0);
351  }
352  }
353  }
354  }
355 
356  if (filter->m_eventList)
357  filter->m_eventList->Reset();
358  else
359  filter->m_eventList = new FWTEventList;
360 
361  TEveSelectorToEventList stoelist(filter->m_eventList, interpretedSelection.c_str());
362  Long64_t result = m_eventTree->Process(&stoelist);
363 
364  if (result < 0)
365  fwLog(fwlog::kWarning) << "FWFileEntry::runFilter in file [" << m_file->GetName() << "] filter [" << filter->m_selector->m_expression << "] is invalid." << std::endl;
366  else
367  fwLog(fwlog::kDebug) << "FWFileEntry::runFilter is file [" << m_file->GetName() << "], filter [" << filter->m_selector->m_expression << "] has [" << filter->m_eventList->GetN() << "] events selected" << std::endl;
368 
369  // Set back the old branch buffers.
370  {
371  for (auto i : prevAddrs)
372  {
373  // std::cout <<"Resetting branch: "<< i.first->GetName() <<" "<< i.second <<std::endl;
374  i.first->SetAddress(i.second);
375  }
376  }
377 
378  filter->m_needsUpdate = false;
379 }
380 
381 //______________________________________________________________________________
382 
383 bool
385 {
387 
388  boost::regex re_spaces("\\s+");
389  selection = boost::regex_replace(selection,re_spaces,"");
390  if (selection.find("&&") != std::string::npos &&
391  selection.find("||") != std::string::npos )
392  {
393  // Combination of && and || operators not supported.
394  return false;
395  }
396 
397  fwlite::Handle<edm::TriggerResults> hTriggerResults;
398  edm::TriggerNames const* triggerNames(0);
399  try
400  {
401  hTriggerResults.getByLabel(*m_event,"TriggerResults","", filterEntry->m_selector->m_triggerProcess.c_str());
402  triggerNames = &(m_event->triggerNames(*hTriggerResults));
403  }
404  catch(...)
405  {
406  fwLog(fwlog::kWarning) << " failed to get trigger results with process name "<< filterEntry->m_selector->m_triggerProcess << std::endl;
407  return false;
408  }
409 
410  // std::cout << "Number of trigger names: " << triggerNames->size() << std::endl;
411  // for (unsigned int i=0; i<triggerNames->size(); ++i)
412  // std::cout << " " << triggerNames->triggerName(i);
413  //std::cout << std::endl;
414 
415  bool junction_mode = true; // AND
416  if (selection.find("||")!=std::string::npos)
417  junction_mode = false; // OR
418 
419  boost::regex re("\\&\\&|\\|\\|");
420 
421  boost::sregex_token_iterator i(selection.begin(), selection.end(), re, -1);
422  boost::sregex_token_iterator j;
423 
424  // filters and how they enter in the logical expression
425  std::vector<std::pair<unsigned int,bool> > filters;
426 
427  while (i != j)
428  {
429  std::string filter = *i++;
430  bool flag = true;
431  if (filter[0] == '!')
432  {
433  flag = false;
434  filter.erase(filter.begin());
435  }
436  unsigned int index = triggerNames->triggerIndex(filter);
437  if (index == triggerNames->size())
438  {
439  // Trigger name not found.
440  return false;
441  }
442  filters.push_back(std::make_pair(index, flag));
443  }
444  if (filters.empty())
445  return false;
446 
447  if (filterEntry->m_eventList)
448  filterEntry->m_eventList->Reset();
449  else
450  filterEntry->m_eventList = new FWTEventList();
451  FWTEventList* list = filterEntry->m_eventList;
452 
453  // loop over events
454  edm::EventID currentEvent = m_event->id();
455  unsigned int iEvent = 0;
456 
457  for (m_event->toBegin(); !m_event->atEnd(); ++(*m_event))
458  {
459  hTriggerResults.getByLabel(*m_event,"TriggerResults","", filterEntry->m_selector->m_triggerProcess.c_str());
460  std::vector<std::pair<unsigned int,bool> >::const_iterator filter = filters.begin();
461  bool passed = hTriggerResults->accept(filter->first) == filter->second;
462  while (++filter != filters.end())
463  {
464  if (junction_mode)
465  passed &= hTriggerResults->accept(filter->first) == filter->second;
466  else
467  passed |= hTriggerResults->accept(filter->first) == filter->second;
468  }
469  if (passed)
470  list->Enter(iEvent);
471  ++iEvent;
472  }
473  m_event->to(currentEvent);
474 
475  filterEntry->m_needsUpdate = false;
476 
477  fwLog(fwlog::kDebug) << "FWFile::filterEventsWithCustomParser file [" << m_file->GetName() << "], filter [" << filterEntry->m_selector->m_expression << "], selected [" << list->GetN() << "]" << std::endl;
478 
479  return true;
480 }
void closeFile()
Definition: FWFileEntry.cc:126
int i
Definition: DBlmapReader.cc:9
FWEventSelector * m_selector
Definition: FWFileEntry.h:41
virtual void Enter(Long64_t entry)
Definition: FWTEventList.cc:55
virtual edm::TriggerNames const & triggerNames(edm::TriggerResults const &triggerResults) const
Definition: Event.cc:429
void openFile(bool)
Definition: FWFileEntry.cc:42
int lastSelectedEvent()
Definition: FWFileEntry.cc:164
bool hasSelectedEvents()
Definition: FWFileEntry.cc:147
bool accept() const
Has at least one path accepted the event?
selection
main part
Definition: corrVsCorr.py:98
FWTEventList * m_eventList
Definition: FWFileEntry.h:40
void getPrimaryData() const
Definition: FWEventItem.cc:443
processConfiguration
Definition: Schedule.cc:370
std::string m_triggerProcess
FWFileEntry(const std::string &name, bool checkVersion)
Definition: FWFileEntry.cc:27
void getDecomposedVersion(const TString &s, int *out)
Definition: fwPaths.cc:30
Strings::size_type size() const
Definition: TriggerNames.cc:39
const std::string & processName() const
Definition: FWEventItem.cc:529
virtual std::string const getBranchNameFor(std::type_info const &, char const *iModuleLabel, char const *iProductInstanceLabel, char const *iProcessName) const
Return the branch name in the TFile which contains the data.
Definition: Event.cc:305
Long64_t size() const
Returns number of events in the file.
Definition: Event.cc:269
bool isEventSelected(int event)
Definition: FWFileEntry.cc:141
static TypeWithDict byName(std::string const &name)
Definition: TypeWithDict.cc:60
std::string const & processName() const
void getByLabel(const P &iP, const char *iModuleLabel, const char *iProductInstanceLabel=0, const char *iProcessLabel=0)
Definition: Handle.h:94
Event const & toBegin()
Go to the very first Event.
Definition: Event.cc:242
int iEvent
Definition: GenABIO.cc:230
const std::string & productInstanceLabel() const
Definition: FWEventItem.cc:523
std::list< Filter * > m_filterEntries
Definition: FWFileEntry.h:100
int * supportedDataFormatsVersion()
Definition: fwPaths.cc:43
unsigned int triggerIndex(std::string const &name) const
Definition: TriggerNames.cc:32
std::string name() const
virtual void Add(const TEventList *list)
Definition: FWTEventList.cc:7
std::string m_expression
const TClass * type() const
Definition: FWEventItem.cc:506
tuple result
Definition: query.py:137
bool filterEventsWithCustomParser(Filter *filter)
Definition: FWFileEntry.cc:384
int j
Definition: DBlmapReader.cc:9
bool to(Long64_t iIndex)
Go to the event at index iIndex.
Definition: Event.cc:212
std::type_info const & typeInfo() const
#define end
Definition: vmac.h:37
std::list< Filter * > & filters()
Definition: FWFileEntry.h:64
TFile * m_file
Definition: FWFileEntry.h:94
virtual ~FWFileEntry()
Definition: FWFileEntry.cc:34
virtual bool atEnd() const
Definition: Event.cc:285
bool m_needUpdate
Definition: FWFileEntry.h:98
TTree * m_eventTree
Definition: FWFileEntry.h:95
fwlite::Event * m_event
Definition: FWFileEntry.h:96
const_iterator begin() const
NOTE: iterator is allowed to return a null object for items that have been removed.
int firstSelectedEvent()
Definition: FWFileEntry.cc:152
#define fwLog(_level_)
Definition: fwLog.h:50
tuple idx
DEBUGGING if hasattr(process,&quot;trackMonIterativeTracking2012&quot;): print &quot;trackMonIterativeTracking2012 D...
ReleaseVersion const & releaseVersion() const
std::string wrappedClassName(std::string const &iFullName)
void runFilter(Filter *fe, const FWEventItemsManager *eiMng)
Definition: FWFileEntry.cc:262
double b
Definition: hdecay.h:120
int nextSelectedEvent(int event)
Definition: FWFileEntry.cc:172
const edm::EventBase * m_event
Definition: FWEventItem.h:239
bool acceptDataFormatsVersion(TString &n)
Definition: fwPaths.cc:71
edm::EventID id() const
Definition: EventBase.h:60
void updateFilters(const FWEventItemsManager *eiMng, bool isOR)
Definition: FWFileEntry.cc:217
FWTEventList * m_globalEventList
Definition: FWFileEntry.h:101
bool hasActiveFilters()
Definition: FWFileEntry.cc:205
std::string m_name
Definition: FWFileEntry.h:93
int previousSelectedEvent(int event)
Definition: FWFileEntry.cc:187
std::vector< FWEventItem * >::const_iterator const_iterator
const std::string & moduleLabel() const
Definition: FWEventItem.cc:518
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run
const_iterator end() const