예제 #1
0
    def test_dynamiccast(self):
        tobj_class = TClass.GetClass("TObject")
        tobjstr_class = TClass.GetClass("TObjString")

        o = TObjString("a")

        # Upcast: TObject <- TObjString
        o_upcast = tobjstr_class.DynamicCast(tobj_class, o)
        self.assertEquals(type(o_upcast), TObject)

        # Downcast: TObject -> TObjString
        o_downcast = tobjstr_class.DynamicCast(tobj_class, o_upcast, False)
        self.assertEquals(type(o_downcast), TObjString)
def retrieve_CCDBObject_asJSON(ccdbreader,
                               path,
                               timestamp,
                               objtype_external=None):
    """
    Retrieves a CCDB object as a JSON/dictionary.
    No need to know the type of the object a-priori.
    """
    header = ccdbreader.fetch_header(path, timestamp)
    if not header:
        print(
            f"WARNING: Could not get header for path ${path} and timestamp {timestamp}"
        )
        return None
    objtype = header["ObjectType"]
    if objtype == None:
        objtype = objtype_external
    if objtype == None:
        return None

    print(objtype)
    ts, obj = ccdbreader.fetch(path, objtype, timestamp)
    print(obj)
    # convert object to json
    jsonTString = TBufferJSON.ConvertToJSON(obj, TClass.GetClass(objtype))
    return json.loads(jsonTString.Data())
def objectsInheritingFrom(baseClass, directory):
    ''' return all objects inheriting from the base class in the list of keys '''
    keys = directory.GetListOfKeys()
    for key in keys:
        classname = key.GetClassName()
        if TClass.GetClass(classname, False).InheritsFrom(baseClass):
            #directory.cd() # must change so root doesn't move the object
            #yield directory.Get("%s/%s;1" % (directory.GetPath(), key.GetName()) )
            yield key.ReadObj()
예제 #4
0
 def __str__(self):
   """Event text dump."""
   dictjoin = lambda d,j=' => ',s='\n': s.join([j.join((str(k),str(v))) for k,v in d.iteritems()])
   mystring = "=================================================================\n"
   # general information
   if self._branches["Event"]:
     mystring += str(self.Event.At(0))
   else:
     mystring += "Event %d\n" % self.GetReadEvent()
   mystring += "-----------------------------------------------------------------\n"
   # weights
   if len(self._weightCache)==0: 
     mystring += "No weight computed so far. Default weight is %f.\n" % self.weight()
   else:
     mystring += "Weights:\n"
     mystring += dictjoin(self._weightCache)
   mystring += "\n-----------------------------------------------------------------\n"
   # list the collections
   mystring += "Collections:\n"
   for colname in self._collections.keys():
     collection = self.getCollection(colname)
     if collection.GetEntries()>0:
       if collection.At(0).IsA()==TClass.GetClass("HepMCEvent"):
         pass
       else:
         mystring += "*** %s has %d element(s)\n" % (colname,collection.GetEntries())
         mystring += reduce(lambda a,b: a+b,map(str,collection))
   mystring += "\n-----------------------------------------------------------------\n"
   # list the registered producers
   mystring += "Producers:\n"
   mystring += dictjoin(self._producers)
   mystring += "\n-----------------------------------------------------------------\n"
   # list the content of vardict, excluding collections
   mystring += "Content of the cache:\n"
   for k, v in self.vardict.iteritems():
     if k in self._collections.keys() : continue
     if isinstance(v,Iterable) and not isinstance(v,StringTypes):
       try:
         thisstring = "%s => vector of %d objects(s)\n" % (k,len(v))
       except:
         mystring += "%s => %s\n"%(k,str(v))
       else:
         try:
           for it,vec in enumerate(v):
             thisstring += "%s[%d] = %s\n"%(k,it,str(vec))
         except: 
           mystring += "%s => %s\n"%(k,str(v))
         else:
           mystring += thisstring
     else:
       mystring += "%s => %s\n"%(k,str(v))
   return mystring
예제 #5
0
def get_toy_dataset(varargset, PDF=None):
    """Return a toy dataset for the given PDF."""

    from rplot.fixes import ROOT
    from ROOT import TClass, RooAbsPdf, RooFit
    objclass = TClass.GetClass(PDF.ClassName())
    if objclass.InheritsFrom(RooAbsPdf.Class()):
        dataset = PDF.generate(varargset, 10000, RooFit.Name('toydataset'),
                               RooFit.Verbose(True))
        print 'Toy generation completed with %s' % PDF.GetName()
        return dataset
    else:
        raise TypeError('PDF should inherit from RooAbsPdf.')
예제 #6
0
 def getObjectContent(self, object):
     """ get string value of a method """
     if not callable(object):
         return object
     else:
         typ = ""
         if not object.__doc__ or str(object.__doc__) == "":
             return "ERROR: Empty __doc__ string"
         docs = str(object.__doc__).split("\n")
         for doc in docs:
             parameters = []
             for p in doc[doc.find("(") + 1:doc.find(")")].split(","):
                 if p != "" and not "=" in p:
                     parameters += [p]
             if len(parameters) != 0:
                 continue
             typestring = doc[:doc.find("(")]
             split_typestring = typestring.split(" ")
             templates = 0
             end_typestring = 0
             for i in reversed(range(len(split_typestring))):
                 templates += split_typestring[i].count("<")
                 templates -= split_typestring[i].count(">")
                 if templates == 0:
                     end_typestring = i
                     break
             typ = " ".join(split_typestring[:end_typestring])
         hidden_types = ["iterator", "Iterator"]
         root_types = ["ROOT::"]
         if typ == "" or "void" in typ or True in [
                 t in typ for t in hidden_types
         ]:
             return None
         from ROOT import TClass
         if True in [t in typ
                     for t in root_types] and TClass.GetClass(typ) == None:
             return "ERROR: Cannot display object of type " + typ
         try:
             object = object()
             value = object
         except Exception as message:
             value = "ERROR: " + str(message)
         if "Buffer" in str(type(value)):
             return "ERROR: Cannot display object of type " + typ
         else:
             return value
    def test2UsageOfTQClassInstance(self):
        """Calls on a TQClass instance"""

        self.assertEqual(TClass.GetClass("TQClass").GetName(), "TQClass")
예제 #8
0
def is_type(key, rtype):
    """Is key the ROOT type `rtype''?"""
    from ROOT import TClass
    return TClass.GetClass(key.GetClassName()).InheritsFrom(rtype.Class())
예제 #9
0
 gSystem.Load("$CMSSW_BASE/lib/$SCRAM_ARCH/libMMozerpowhegweight.so")
 res = gSystem.Load(
     "$CMSSW_BASE/lib/$SCRAM_ARCH/libHiggsAnalysisCombinedLimit.so")
 gROOT.GetInterpreter().AddIncludePath(cmssw_base + '/src')
 gSystem.AddIncludePath('-I"' + cmssw_base + '/src"')
 if not RooFitInclude():
     workingdir = os.getcwd()
     print 'changing to', cmssw_base, 'directory'
     os.chdir(cmssw_base)
     RooFitInclude()
     print 'returning to working directory', workingdir
     os.chdir(workingdir)
 gROOT.ProcessLine('.L EffTableReader.cc+')
 gROOT.ProcessLine('.L EffTableLoader.cc+')
 gROOT.ProcessLine('.L CPWeighter.cc+')
 if not TClass.GetClass('RooPowerLaw'):
     # print 'importing RooFit PDF classes'
     gROOT.ProcessLine('.L RooPowerLaw.cc+')
 if not TClass.GetClass('RooPowerExpPdf'):
     gROOT.ProcessLine('.L RooPowerExpPdf.cxx+')
 if not TClass.GetClass('RooErfExpPdf'):
     gROOT.ProcessLine('.L RooErfExpPdf.cxx+')
 if not TClass.GetClass('RooErfPdf'):
     gROOT.ProcessLine('.L RooErfPdf.cxx+')
 if not TClass.GetClass('RooTH1DPdf'):
     gROOT.ProcessLine('.L RooTH1DPdf.cxx+')
 if not TClass.GetClass('RooChebyshevPdf'):
     gROOT.ProcessLine('.L RooChebyshevPDF.cc+')
 if not TClass.GetClass('alphaFunction'):
     gROOT.ProcessLine('.L alphaFunction.cxx+')
 if not TClass.GetClass('RooATGCFunction'):