CMS 3D CMS Logo

EdmDataAccessor.py
Go to the documentation of this file.
1 from builtins import range
2 import logging
3 import os.path
4 
5 from PyQt4.QtGui import QColor
6 
7 from Vispa.Share.BasicDataAccessor import BasicDataAccessor
8 from Vispa.Share.RelativeDataAccessor import RelativeDataAccessor
9 from Vispa.Share.ParticleDataAccessor import ParticleDataAccessor
10 from Vispa.Plugins.EventBrowser.EventFileAccessor import EventFileAccessor
11 from Vispa.Main.Exceptions import exception_traceback
12 from Vispa.Plugins.EdmBrowser.ParticleDataList import defaultParticleDataList
13 
14 def eq(self,other):
15  return id(self)==id(other)
16 def ne(self,other):
17  return id(self)!=id(other)
18 # PhysicsTools.PythonAnalysis.cmstools
19 def all(container):
20  # loop over ROOT::TTree and similar
21  if hasattr(container,'GetEntries'):
22  try:
23  entries = container.GetEntries()
24  for entry in range(entries):
25  yield entry
26  except:
27  raise cmserror("Looping of %s failed" %container)
28  # loop over std::vectors and similar
29  elif hasattr(container, 'size'):
30  # convert std::map to std::vector<std::pair>
31  if hasattr(container, 'ids'):
32  container = container.ids()
33  try:
34  entries = container.size()
35  for entry in range(entries):
36  yield container[entry]
37  except:
38  pass
39  # loop over c buffer
40  #elif hasattr(container,'begin') and hasattr(container,'end'):
41  # begin=container.begin()
42  # end=container.end()
43  # while (begin!=end):
44  # yield begin.__deref__()
45  # begin.__preinc__()
46 
48  def __init__(self,branchtuple):
49  self.branchtuple=branchtuple
50 
52 
53  def __init__(self):
54  logging.debug(__name__ + ": __init__")
55 
56  self._dataObjects = []
57  self._edmLabel={}
58  self._edmParent={}
59  self._edmChildren={}
63 
64  self._eventIndex = 0
65  self._numEvents = 0
66 
67  self._filename=""
68  self._branches=[]
70  self._events=None
71  self._readOnDemand=True
72  self._underscore=False
73  self._filterBranches=True
74  self.maxLevels=2
75  self.maxDaughters=1000
76 
77  def isRead(self,object,levels=1):
78  if not id(object) in self._edmChildrenObjects.keys():
79  return False
80  if levels>1 and id(object) in self._edmChildren.keys():
81  for child in self._edmChildren[id(object)]:
82  if not self.isRead(child, levels-1):
83  return False
84  return True
85 
86  def children(self,object):
87  """ Get children of an object """
88  if id(object) in self._edmChildren.keys() and self.isRead(object):
89  return self._edmChildren[id(object)]
90  else:
91  return ()
92 
93  def isContainer(self,object):
94  """ Get children of an object """
95  if id(object) in self._edmChildren.keys() and self.isRead(object):
96  return len(self._edmChildren[id(object)])>0
97  else:
98  return True
99 
100  def motherRelations(self,object):
101  """ Get motherRelations of an object """
102  if id(object) in self._edmMotherRelations.keys():
103  return self._edmMotherRelations[id(object)]
104  else:
105  return ()
106 
107  def daughterRelations(self,object):
108  """ Get daughterRelations of an object """
109  if id(object) in self._edmDaughterRelations.keys():
110  return self._edmDaughterRelations[id(object)]
111  else:
112  return ()
113 
114  def label(self,object):
115  return self.getShortLabel(object)
116 
117  def getShortLabel(self,object):
118  if id(object) in self._edmLabel.keys():
119  splitlabel=self._edmLabel[id(object)].strip(".").split(".")
120  return splitlabel[len(splitlabel)-1]
121  else:
122  return ""
123 
124  def getShortLabelWithType(self,object):
125  return self.getShortLabel(object)+" <"+self.getShortType(object)+">"
126 
127  def getObjectLabel(self,object):
128  splitlabel=self._edmLabel[id(object)].strip(".").split(".")
129  return ".".join(splitlabel[1:-1])
130 
131  def getType(self,object):
132  typ=str(object.__class__)
133  if "\'" in typ:
134  typ=typ.split("\'")[1]
135  if "." in typ:
136  typ=typ.split(".")[len(typ.split("."))-1]
137  return typ.strip(" ")
138 
139  def getShortType(self,object):
140  typ=self.getType(object).split("<")[0].strip(" ")
141  return typ
142 
143  def getBranch(self,object):
144  entry=object
145  while id(entry) in self._edmParent.keys() and self._edmParent[id(entry)]!=None:
146  entry=self._edmParent[id(entry)]
147  return entry
148 
149  def getDepth(self,object):
150  entry=object
151  i=0
152  while id(entry) in self._edmParent.keys() and self._edmParent[id(entry)]!=None:
153  entry=self._edmParent[id(entry)]
154  i+=1
155  return i
156 
157  def getObjectProperties(self,object):
158  """ get all method properties of an object """
159  objects=[]
160  for attr in dir(object):
161  prop=getattr(object,attr)
162  if not attr.startswith("__") and (self._underscore or attr.strip("_")==attr):
163  objects+=[(attr,prop)]
164  return objects
165 
166  def getObjectRef(self,object):
167  """ get object and resolve references """
168  typshort=self.getShortType(object)
169  ref_types=["edm::Ref","edm::RefProd","edm::RefToBase","edm::RefToBaseProd","edm::Ptr"]
170  value=object
171  ref=False
172  if typshort in ref_types:
173  try:
174  if hasattr(object, "isNull") and object.isNull():
175  value="ERROR: "+self.getType(object)+" object is null"
176  elif hasattr(object, "isAvailable") and not object.isAvailable():
177  value="ERROR: "+self.getType(object)+" object is not available"
178  else:
179  value=object.get()
180  if isinstance(value, type(None)):
181  value="ERROR: Could not get "+self.getType(object)
182  else:
183  ref=True
184  except Exception as message:
185  value="ERROR: "+str(message)
186  return value,ref
187 
188  def getObjectContent(self,object):
189  """ get string value of a method """
190  if not callable(object):
191  return object
192  else:
193  typ=""
194  if not object.__doc__ or str(object.__doc__)=="":
195  return "ERROR: Empty __doc__ string"
196  docs=str(object.__doc__).split("\n")
197  for doc in docs:
198  parameters=[]
199  for p in doc[doc.find("(")+1:doc.find(")")].split(","):
200  if p!="" and not "=" in p:
201  parameters+=[p]
202  if len(parameters)!=0:
203  continue
204  typestring=doc[:doc.find("(")]
205  split_typestring=typestring.split(" ")
206  templates=0
207  end_typestring=0
208  for i in reversed(list(range(len(split_typestring)))):
209  templates+=split_typestring[i].count("<")
210  templates-=split_typestring[i].count(">")
211  if templates==0:
212  end_typestring=i
213  break
214  typ=" ".join(split_typestring[:end_typestring])
215  hidden_types=["iterator","Iterator"]
216  root_types=["ROOT::"]
217  if typ=="" or "void" in typ or True in [t in typ for t in hidden_types]:
218  return None
219  from ROOT import TClass
220  if True in [t in typ for t in root_types] and TClass.GetClass(typ)==None:
221  return "ERROR: Cannot display object of type "+typ
222  try:
223  object=object()
224  value=object
225  except Exception as message:
226  value="ERROR: "+str(message)
227  if "Buffer" in str(type(value)):
228  return "ERROR: Cannot display object of type "+typ
229  else:
230  return value
231 
232  def isVectorObject(self,object):
233  typ=self.getShortType(object)
234  return typ=="list" or typ[-6:].lower()=="vector" or typ[-3:].lower()=="map" or typ[-10:].lower()=="collection" or hasattr(object,"size")
235 
236  def compareObjects(self,a,b):
237  same=False
238  if hasattr(a,"px") and hasattr(a,"py") and hasattr(a,"pz") and hasattr(a,"energy") and \
239  hasattr(b,"px") and hasattr(b,"py") and hasattr(b,"pz") and hasattr(b,"energy"):
240  same=a.px()==b.px() and a.py()==b.py() and a.pz()==b.pz() and a.energy()==b.energy()
241  return same
242 
243  def getDaughterObjects(self,object):
244  """ get list of daughter objects from properties """
245  objects=[]
246  # subobjects
247  objectdict={}
248  hidden_attr=["front","back","IsA","clone","masterClone","masterClonePtr","mother","motherRef","motherPtr","daughter","daughterRef","daughterPtr","is_back_safe"]
249  broken_attr=[]#["jtaRef"]
250  for attr1,property1 in self.getObjectProperties(object):
251  if attr1 in hidden_attr:
252  pass
253  elif attr1 in broken_attr:
254  objectdict[attr1]=("ERROR: Cannot read property",False)
255  else:
256  (value,ref)=self.getObjectRef(self.getObjectContent(property1))
257  if not isinstance(value,type(None)) and (not self.isVectorObject(object) or self._propertyType(value)!=None):
258  objectdict[attr1]=(value,ref)
259  for name in sorted(objectdict.keys()):
260  objects+=[(name,objectdict[name][0],objectdict[name][1],self._propertyType(objectdict[name][0]))]
261  # entries in vector
262  if self.isVectorObject(object):
263  n=0
264  for o in all(object):
265  (value,ref)=self.getObjectRef(o)
266  typ=self._propertyType(value)
267  if typ!=None:
268  name="["+str(n)+"]"
269  elif "GenParticle" in str(value):
270  name=defaultParticleDataList.getNameFromId(value.pdgId())
271  else:
272  name=self.getType(value)+" ["+str(n)+"]"
273  objects+=[(name,value,ref,typ)]
274  n+=1
275  # read candidate relations
276  for name,mother,ref,propertyType in objects:
277  if hasattr(mother,"numberOfDaughters") and hasattr(mother,"daughter"):
278  try:
279  for n in range(mother.numberOfDaughters()):
280  daughter=mother.daughter(n)
281  found=False
282  for na,da,re,st in objects:
283  if self.compareObjects(daughter,da):
284  daughter=da
285  found=True
286  if not id(mother) in self._edmDaughterRelations.keys():
287  self._edmDaughterRelations[id(mother)]=[]
288  self._edmDaughterRelations[id(mother)]+=[daughter]
289  if not id(daughter) in self._edmMotherRelations.keys():
290  self._edmMotherRelations[id(daughter)]=[]
291  self._edmMotherRelations[id(daughter)]+=[mother]
292  except Exception as message:
293  logging.error("Cannot read candidate relations: "+str(message))
294  return objects
295 
296  def _propertyType(self,value):
297  if type(value) in (bool,):
298  return "Boolean"
299  elif type(value) in (int, long):
300  return "Integer"
301  elif type(value) in (float,):
302  return "Double"
303  elif type(value) in (complex,str,unicode):
304  return "String"
305  else:
306  return None
307 
308  def properties(self,object):
309  """ Make list of all properties """
310  logging.debug(__name__ + ": properties: "+self.label(object))
311  properties=[]
312 
313  objectproperties={}
314  objectproperties_sorted=[]
315  if id(object) in self._edmChildrenObjects.keys():
316  for name,value,ref,propertyType in self._edmChildrenObjects[id(object)]:
317  if propertyType!=None:
318  objectproperties[name]=(value,propertyType)
319  objectproperties_sorted+=[name]
320 
321  properties+=[("Category","Object info","")]
322  shortlabel=self.getShortLabel(object)
323  properties+=[("String","label",shortlabel)]
324  properties+=[("String","type",self.getType(object))]
325  objectlabel=self.getObjectLabel(object)
326  if objectlabel!="":
327  properties+=[("String","object",objectlabel)]
328  branchlabel=self.label(self.getBranch(object))
329  if shortlabel.strip(".")!=branchlabel.strip("."):
330  properties+=[("String","branch",branchlabel)]
331  else:
332  properties+=[("Category","Branch info","")]
333  properties+=[("String","Type",branchlabel.split("_")[0])]
334  properties+=[("String","Label",branchlabel.split("_")[1])]
335  properties+=[("String","Product",branchlabel.split("_")[2])]
336  properties+=[("String","Process",branchlabel.split("_")[3])]
337 
338  for property in ["pdgId","charge","status"]:
339  if property in objectproperties.keys():
340  properties+=[(objectproperties[property][1],property,objectproperties[property][0])]
341  del objectproperties[property]
342 
343  if "px" in objectproperties.keys():
344  properties+=[("Category","Vector","")]
345  for property in ["energy","px","py","pz","mass","pt","eta","phi","p","theta","y","rapidity","et","mt","mtSqr","massSqr"]:
346  if property in objectproperties.keys():
347  properties+=[(objectproperties[property][1],property,objectproperties[property][0])]
348  del objectproperties[property]
349 
350  if "x" in objectproperties.keys():
351  properties+=[("Category","Vector","")]
352  for property in ["x","y","z"]:
353  if property in objectproperties.keys():
354  properties+=[(objectproperties[property][1],property,objectproperties[property][0])]
355  del objectproperties[property]
356 
357  if False in [str(value[0]).startswith("ERROR") for value in objectproperties.values()]:
358  properties+=[("Category","Values","")]
359  for property in objectproperties_sorted:
360  if property in objectproperties.keys():
361  if not str(objectproperties[property][0]).startswith("ERROR"):
362  properties+=[(objectproperties[property][1],property,objectproperties[property][0])]
363  del objectproperties[property]
364 
365  if len(objectproperties)>0:
366  properties+=[("Category","Errors","")]
367  for property in objectproperties_sorted:
368  if property in objectproperties.keys():
369  properties+=[(objectproperties[property][1],property,objectproperties[property][0])]
370 
371  return tuple(properties)
372 
373  def readObjectsRecursive(self,mother,label,edmobject,levels=1):
374  """ read edm objects recursive """
375  logging.debug(__name__ + ": readObjectsRecursive (levels="+str(levels)+"): "+label)
376  # save object information
377  if not id(edmobject) in self._edmLabel.keys():
378  if not isinstance(edmobject,(int,float,long,complex,str,unicode,bool)):
379  # override comparison operator of object
380  try:
381  type(edmobject).__eq__=eq
382  type(edmobject).__ne__=ne
383  except:
384  pass
385  self._edmLabel[id(edmobject)]=label
386  self._edmParent[id(edmobject)]=mother
387  self._edmChildren[id(edmobject)]=[]
388  if not id(mother) in self._edmChildren.keys():
389  self._edmChildren[id(mother)]=[]
390  self._edmChildren[id(mother)]+=[edmobject]
391  if levels==0:
392  # do not read more daughters
393  return [edmobject],True
394  else:
395  # read daughters
396  return self.readDaughtersRecursive(edmobject,[edmobject],levels)
397 
398  def readDaughtersRecursive(self,edmobject,objects,levels=1):
399  """ read daughter objects of an edmobject """
400  logging.debug(__name__ + ": readDaughtersRecursive (levels="+str(levels)+"): "+str(edmobject))
401  # read children information
402  if not id(edmobject) in self._edmChildrenObjects.keys():
403  self._edmChildrenObjects[id(edmobject)]=self.getDaughterObjects(edmobject)
404  # analyze children information
405  ok=True
406  daughters=self._edmChildrenObjects[id(edmobject)]
407  i=0
408  for name,daughter,ref,propertyType in daughters:
409  # create children objects
410  if propertyType==None:
411  if ref:
412  label="* "+name
413  else:
414  label=name
415  if id(edmobject) in self._edmLabel.keys() and self._edmLabel[id(edmobject)]!="":
416  label=self._edmLabel[id(edmobject)]+"."+label
417  (res,ok)=self.readObjectsRecursive(edmobject,label,daughter,levels-1)
418  objects+=res
419  i+=1
420  if i>self.maxDaughters:
421  logging.warning("Did not read all daughter objects. Maximum is set to "+str(self.maxDaughters)+".")
422  return objects,False
423  return objects,ok
424 
425  def read(self,object,levels=1):
426  """ reads contents of a branch """
427  logging.debug(__name__ + ": read")
428  if isinstance(object,BranchDummy):
429  if hasattr(object,"product"):
430  return object.product
431  if not self._events:
432  return object
433  try:
434  self._events.getByLabel(object.branchtuple[2],object.branchtuple[3],object.branchtuple[4],object.branchtuple[1])
435  if object.branchtuple[1].isValid():
436  product=object.branchtuple[1].product()
437  if not isinstance(product,(int,float,long,complex,str,unicode,bool)):
438  # override comparison operator of object
439  try:
440  type(product).__eq__=eq
441  type(product).__ne__=ne
442  except:
443  pass
444  self._dataObjects.insert(self._dataObjects.index(object),product)
445  self._dataObjects.remove(object)
446  self._edmLabel[id(product)]=object.branchtuple[0]
447  object.product=product
448  object=product
449  else:
450  self._edmChildrenObjects[id(object)]=[("ERROR","ERROR: Branch is not valid.",False,True)]
451  logging.info("Branch is not valid: "+object.branchtuple[0]+".")
452  object.invalid=True
453  return object
454  except Exception as e:
455  self._edmChildrenObjects[id(object)]=[("ERROR","ERROR: Unable to read branch : "+str(e),False,True)]
456  object.unreadable=True
457  logging.warning("Unable to read branch "+object.branchtuple[0]+" : "+exception_traceback())
458  return object
459  if self.isRead(object,levels):
460  return object
461  if levels>0:
462  self.readDaughtersRecursive(object,[],levels)
463  return object
464 
465  def goto(self, index):
466  """ Goto event number index in file.
467  """
468  self._eventIndex=index-1
469  self._edmLabel={}
470  self._edmChildren={}
471  self._edmMotherRelations={}
472  self._edmDaughterRelations={}
473  self._edmChildrenObjects={}
474  if self._events:
475  self._events.to(self._eventIndex)
476  self._dataObjects=[]
477  i=0
478  for branchtuple in self._filteredBranches:
479  branch=BranchDummy(branchtuple)
480  self._dataObjects+=[branch]
481  self._edmLabel[id(branch)]=branchtuple[0]
482  if not self._readOnDemand:
483  self.read(branch,self.maxLevels)
484  i+=1
485  if self._filterBranches and self._events:
486  self.setFilterBranches(True)
487  return True
488 
489  def eventNumber(self):
490  return self._eventIndex+1
491 
492  def numberOfEvents(self):
493  return self._numEvents
494 
495  def topLevelObjects(self):
496  return self._dataObjects
497 
498  def open(self, filename=None):
499  """ Open edm file and show first event """
500  self._filename=filename
501  self._branches=[]
502  if os.path.splitext(filename)[1].lower()==".txt":
503  file = open(filename)
504  for line in file.readlines():
505  if "\"" in line:
506  linecontent=[l.strip(" \n").rstrip(".") for l in line.split("\"")]
507  self._branches+=[(linecontent[0]+"_"+linecontent[1]+"_"+linecontent[3]+"_"+linecontent[5],None,linecontent[1],linecontent[3],linecontent[5])]
508  else:
509  linecontent=line.strip("\n").split(" ")[0].split("_")
510  if len(linecontent)>3:
511  self._branches+=[(linecontent[0]+"_"+linecontent[1]+"_"+linecontent[2]+"_"+linecontent[3],None,linecontent[1],linecontent[2],linecontent[3])]
512  elif os.path.splitext(filename)[1].lower()==".root":
513  from DataFormats.FWLite import Events, Handle
514  self._events = Events(self._filename)
515  self._numEvents=self._events.size()
516  branches=self._events.object().getBranchDescriptions()
517  for branch in branches:
518  try:
519  branchname=branch.friendlyClassName()+"_"+branch.moduleLabel()+"_"+branch.productInstanceName()+"_"+branch.processName()
520  handle=Handle(branch.fullClassName())
521  self._branches+=[(branchname,handle,branch.moduleLabel(),branch.productInstanceName(),branch.processName())]
522  except Exception as e:
523  logging.warning("Cannot read branch "+branchname+":"+str(e))
524  self._branches.sort(lambda x, y: cmp(x[0], y[0]))
525  self._filteredBranches=self._branches[:]
526  return self.goto(1)
527 
528  def particleId(self, object):
529  charge=self.property(object,"pdgId")
530  if charge==None:
531  charge=0
532  return charge
533 
534  def isQuark(self, object):
535  particleId = self.particleId(object)
536  if not particleId:
537  return False
538  return defaultParticleDataList.isQuarkId(particleId)
539 
540  def isLepton(self, object):
541  particleId = self.particleId(object)
542  if not particleId:
543  return False
544  return defaultParticleDataList.isLeptonId(particleId)
545 
546  def isGluon(self, object):
547  particleId = self.particleId(object)
548  if not particleId:
549  return False
550  return defaultParticleDataList.isGluonId(particleId)
551 
552  def isBoson(self, object):
553  particleId = self.particleId(object)
554  if not particleId:
555  return False
556  return defaultParticleDataList.isBosonId(particleId)
557 
558  def isPhoton(self, object):
559  particleId = self.particleId(object)
560  if not particleId:
561  return False
562  if not hasattr(defaultParticleDataList,"isPhotonId"):
563  return False
564  return defaultParticleDataList.isPhotonId(particleId)
565 
566  def isHiggs(self, object):
567  particleId = self.particleId(object)
568  if not particleId:
569  return False
570  if not hasattr(defaultParticleDataList,"isHiggsId"):
571  return False
572  return defaultParticleDataList.isHiggsId(particleId)
573 
574  def lineStyle(self, object):
575  particleId = self.particleId(object)
576  if hasattr(defaultParticleDataList,"isPhotonId") and defaultParticleDataList.isPhotonId(particleId):
577  return self.LINE_STYLE_WAVE
578  elif defaultParticleDataList.isGluonId(particleId):
579  return self.LINE_STYLE_SPIRAL
580  elif defaultParticleDataList.isBosonId(particleId):
581  return self.LINE_STYLE_DASH
582  return self.LINE_STYLE_SOLID
583 
584  def color(self, object):
585  particleId = self.particleId(object)
586  if defaultParticleDataList.isLeptonId(particleId):
587  return QColor(244, 164, 96)
588  elif defaultParticleDataList.isQuarkId(particleId):
589  return QColor(0, 100, 0)
590  elif hasattr(defaultParticleDataList,"isHiggsId") and defaultParticleDataList.isHiggsId(particleId):
591  return QColor(247, 77, 251)
592  elif defaultParticleDataList.isBosonId(particleId):
593  return QColor(253, 74, 74)
594  return QColor(176, 179, 177)
595 
596  def charge(self, object):
597  charge=self.property(object,"charge")
598  if charge==None:
599  charge=0
600  return charge
601 
602  def linkMother(self, object, mother):
603  pass
604 
605  def linkDaughter(self, object, daughter):
606  pass
607 
609  return self._underscore
610 
611  def setUnderscoreProperties(self,check):
612  self._underscore=check
613 
614  def filterBranches(self):
615  return self._filterBranches
616 
617  def setFilterBranches(self,check):
618  if not self._events:
619  return True
620  self._filterBranches=check
621  if check:
622  for branch in self._dataObjects[:]:
623  result=self.read(branch,0)
624  if isinstance(result,BranchDummy):
625  self._dataObjects.remove(result)
626  if hasattr(result,"invalid"):
627  self._filteredBranches.remove(result.branchtuple)
628  return True
629  else:
630  self._filteredBranches=self._branches[:]
631  self.goto(self.eventNumber())
632  return False
633 
634  def filteredBranches(self):
635  return self._filteredBranches
636 
def readObjectsRecursive(self, mother, label, edmobject, levels=1)
def readDaughtersRecursive(self, edmobject, objects, levels=1)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
dbl *** dir
Definition: mlp_gen.cc:35
#define str(s)
double split
Definition: MVATrainer.cc:139
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