Пример #1
0
 def __init__(self, inputFiles = '', maxEvents=0):
   """Initialize the AnalysisEvent like a standard Event, plus additional features."""
   # initialization of base functionalities
   TChain.__init__(self,"Delphes","Delphes")
   if isinstance(inputFiles,Iterable) and not isinstance(inputFiles,StringTypes):
     for thefile in inputFiles:
       if path.isfile(thefile): 
         self.AddFile(thefile)
       else:
         print "Warning: ",thefile," do not exist."
   elif  isinstance(inputFiles,StringTypes):
     thefile = inputFiles
     if path.isfile(thefile): 
       self.AddFile(thefile)
     else:
       print "Warning: ",thefile," do not exist."
   else:
     print "Warning: invalid inputFiles"
   self.BuildIndex("Event[0].Number")
   self.SetBranchStatus("*",0)
   self._eventCounts        = 0
   self._maxEvents          = maxEvents
   # additional features:
   # 1. instrumentation for event weight
   self._weightCache = {}
   self._weightEngines = {}
   # 2. a list of event products used in the analysis
   self._collections = {} 
   self._branches = dict((b,False) for b in map(lambda b:b.GetName(),self.GetListOfBranches()))
   # 3. a list of "producers" of analysis high-level quantities
   self._producers = {}
   # 4. volatile dictionary. User can add any quantity to the event and it will be 
   #    properly erased in the iteration step. 
   self.__dict__["vardict"] = {}
Пример #2
0
 def __getattr__(self, attr):
   """Overloaded getter to handle properly:
        - volatile analysis objects
        - event collections
        - data producers"""
   if attr in self.__dict__["vardict"]:
     return self.vardict[attr]
   if attr in self._collections:
     return self.vardict.setdefault(attr, TChain.__getattr__(self,self._collections[attr]))
   if attr in self._producers:
     return self.vardict.setdefault(attr, self._producers[attr][0](self, **self._producers[attr][1]))
   return TChain.__getattr__(self,attr)
Пример #3
0
 def getCollection(self,name):
   """Retrieve the event product or return the cached collection.
      Note that the prefered way to get the collection is instead to access the "event.name" attribute."""
   if not name in self._collections:
     raise AttributeError("%r object has no attribute %r" % (type(self).__name__,name))
   if not name in self.vardict:
     self.vardict[name] = TChain.__getattr__(self,self._collections[name])
   return getattr(self,name)
Пример #4
0
def getN(fileDir):
    # import ssUtil
    from multiLepSearch.ssUtil import getCut

    # Initialize nDict
    nDict = {}
    can = ROOT.TCanvas(
    )  # for Draw(). Not necessary, but gets rid of some out of place INFO message

    fileList = [
        d for d in listdir(fileDir)
        if isfile("%s/%s" % (fileDir, d)) and d.endswith(".root")
    ]
    nFiles = len(fileList)
    n = 0
    sw = ROOT.TStopwatch()
    sw.Start()  # Stopwatch
    print "Loading from", fileDir
    for line in tqdm(fileList):
        n += 1
        if testRun and n > 1: break
        # print "Folder %d of %d: %s" % (n, nFiles, line)
        tqdm.write("File %d of %d: %s" % (n, nFiles, line))

        # Skip specified directories
        if any(substr in line for substr in skipDirs):
            continue

        # Get sampleID for MC, set sampleID of data to 0
        if "data" not in line:
            match = re.search(".[0-9]{6}.", line)  # Find dataset ID
            if not match:
                # print "Cannot infer datasetID from filename %s , skipped" % line
                tqdm.write(
                    "Cannot infer datasetID from filename %s , skipped" % line)
                continue

            sampleID = int(match.group()[1:-1])
            weight = "(ElSF * MuSF * BtagSF * weight * pwt)"
        else:
            if "data15" in line: continue  # Reject 2015 data
            sampleID = 0  # data
            weight = "(fLwt+qFwt)"

        tc = TChain("evt2l")
        tc.Add("%s/%s" % (fileDir, line))

        # Add = tc.Add
        # for f in listdir("%s/%s" % (fileDir, line)):
        # 	if re.search("root\.*[0-9]*$", f) is not None:
        # 		Add("%s/%s/%s" % (fileDir,line,f))

        # The next two lines are some attempt to speed up the for loop
        Draw = tc.Draw
        GetHist = gDirectory.Get

        nSample = {}

        for chan in channels:  #  If tqdm not available, comment out the next line and comment in the next line
            # for chan in tqdm(channels):
            Draw("%s>>hist" % weight, "(%s)*(%s)" % (getCut(chan), weight))
            h = GetHist("hist")
            if h is None or not isinstance(h, ROOT.TH1):
                nSample[chan] = 0
            else:
                nSample[chan] = h.GetSumOfWeights()
                h.Delete()

        if nDict.get(
                sampleID, None
        ) is None:  # Save the dictionary if it doesn't exist for the given sampleID
            nDict[sampleID] = nSample
        else:
            for chan in channels:  # Sum the entries in the dictionary if it already exists
                nDict[sampleID][chan] += nSample[chan]

    sw.Stop()
    sw.Print()  # Print stopwatch
    return nDict
Пример #5
0
class WeightReader:
    ''' Get uncertainties from 9 scale weights, 33 PDF weights and 100 NNPDF30 weights

     ### For PDF + alpha_S (33 weights)
     See https://arxiv.org/pdf/1510.03865.pdf
     Eq 20 and 27 for PDF and alpha_s
     PDF4LHC15_nlo_nf4_30_pdfas, 1+30+2 weights, see Table 6
 '''
    def SetPath(self, p):
        self.path = p

    def SetOutPath(self, p):
        self.outpath = p

    def SetSampleName(self, n):
        self.sampleName = n

    def SetPDFhistoName(self, n):
        self.PDFhistoName = n

    def SetScaleHistoName(self, n):
        self.scaleHistoName = n

    def SetPShistoName(self, n):
        self.PShistoName = n

    def SetNormScaleHistoName(self, n):
        self.normScaleHitstoName = n

    def SetNormPDFhistoName(self, n):
        self.normPDFhistoName = n

    def SetMotherFileName(self, f):
        self.motherfname = f

    def SetPathToTrees(self, p):
        self.pathToTrees = p

    def SetSampleName(self, n):
        self.sampleName = n

    def SetLumi(self, l):
        self.lumi = l

    def SetLevel(self, l):
        self.level = l

    def SetChan(self, c):
        self.chan = c

    def SetHistoPrefix(self, p):
        self.histoprefix = p

    def SetNgenEvents(self, n):
        self.nGenEvents = n

    def SetYield(self, y):
        self.yieldnom = y

    def GetYield(self):
        return self.yieldnom

    def GetNgenEvents(self):
        return self.nGenEvents

    def GetLumi(self):
        return self.lumi

    def GetSampleName(self):
        return self.sampleName

    def GetLevel(self):
        return self.level

    def GetChan(self):
        return self.chan

    def LoadTreeSumOfWeights(self, path, fname):
        ''' Load the trees with the sum of weights and returns the corresponding TChain '''
        self.treesow = TChain('Runs', 'Runs')
        files = GetFiles(path, fname)
        for f in files:
            self.treesow.Add(f)
        print ' >> Loaded %i mother files!' % len(files)

    def GetSumPDFhistoFromSumWTree(self):
        if not hasattr(self, 'treesow'):
            print 'WARNING: tree with sum of weights has not been loaded!!'
            return
        self.treesow.GetEntry(1)
        nPDFweights = self.treesow.nLHEPdfSumw
        h = TH1F('SumOfWeightsPDF', '', nPDFweights, 0.5, nPDFweights + 0.5)
        count = 0
        sow = 0
        for event in self.treesow:
            count += event.genEventCount
            sow += event.genEventSumw
            for i in range(nPDFweights):
                h.Fill(i + 1, event.LHEPdfSumw[i])
        h.SetDirectory(0)
        #for i in range(h.GetNbinsX()): print '[%i] %1.2f'%(i, h.GetBinContent(i+1))
        self.count = count
        self.sow = sow
        return h

    def GetSumScaleHistoFromSumWTree(self):
        if not hasattr(self, 'treesow'):
            print 'WARNING: tree with sum of weights has not been loaded!!'
            return
        self.treesow.GetEntry(1)
        nScaleWeights = self.treesow.nLHEScaleSumw
        h = TH1F('SumOfWeightsScale', '', nScaleWeights, 0.5,
                 nScaleWeights + 0.5)
        print 'GetEntries: ', self.treesow.GetEntries()
        for event in self.treesow:
            for i in range(nScaleWeights):
                h.Fill(i + 1, event.LHEScaleSumw[i])
        h.SetDirectory(0)
        #for i in range(h.GetNbinsX()): print '[%i] %1.2f'%(i, h.GetBinContent(i+1))
        return h

    def loadHistos(self):
        ''' Load the PDF and Scale histos and norm histos '''
        t = TopHistoReader(self.path)
        t.SetHistoNamePrefix(self.histoprefix)
        t.SetIsData(1)
        n = self.GetSampleName()
        t.SetProcess(n)
        t.SetChan(self.GetChan())
        t.SetLevel(self.GetLevel())
        #if self.GetNgenEvents() <= 0 : self.SetNgenEvents(t.GetNGenEvents())
        self.SetYield(t.GetYield() * self.GetLumi())
        self.hpdf = t.GetHisto(n, self.PDFhistoName)
        self.hscale = t.GetHisto(n, self.scaleHistoName)
        #self.hPS       = t.GetHisto(n,self.PShistoName)
        if self.pathToTrees != '' and self.motherfname != '':
            self.LoadTreeSumOfWeights(self.pathToTrees, self.motherfname)
        self.hsumpdf = t.GetNamedHisto(
            self.normPDFhistoName
        ) if self.normPDFhistoName != '' else self.GetSumPDFhistoFromSumWTree(
        )
        self.hsumscale = t.GetNamedHisto(
            self.normScaleHitstoName
        ) if self.normScaleHitstoName != '' else self.GetSumScaleHistoFromSumWTree(
        )
        self.SetNgenEvents(self.count)
        self.nPDFweights = self.hsumpdf.GetNbinsX()
        self.nScaleWeighs = self.hsumscale.GetNbinsX()
        print '>> Count        : ', self.count
        print '>> SumOfWeights : ', self.sow

    def GetPDFyield(self, i):
        ''' Return value of bin i for PDF weights '''
        return self.hpdf.GetBinContent(i) * self.GetLumi() / self.GetPDFnorm(
            i)  #(self.GetNgenEvents())

    def GetPDFnom(self):
        ''' Nominal PDF set '''
        return self.GetPDFyield(1)

    def GetPDFnorm(self, i):
        ''' Get sum of PDF weights for a given set i '''
        return self.hsumpdf.GetBinContent(i)

    def GetScaleNorm(self, i):
        ''' Get sum of Scale weights for a given set i '''
        return self.hsumscale.GetBinContent(i)

    def GetScaleYield(self, i):
        ''' Return value of bin i for scale weights '''
        return self.hscale.GetBinContent(
            i) * self.GetLumi() / self.GetScaleNorm(i)  #(self.GetNgenEvents())

    def GetPSyield(self, i):
        ''' Return value of bin i for PS weights '''
        y = self.hPS.GetBinContent(i)
        return y * self.GetLumi()

    def GetScaleNom(self):
        ''' Nominal scale weights '''
        return self.GetScaleYield(5)

    def GetRelUncScale(self, i):
        ''' Returns the relative unc for a given scale set '''
        return abs(self.GetScaleYield(i) -
                   self.GetScaleNom()) / self.GetScaleNom()

    def GetRelUncPDF(self, i):
        ''' Returns the relative unc for a given PDF set i '''
        return abs(self.GetPDFyield(i) - self.GetPDFnom()) / self.GetPDFnom()

    def GetMaxRelUncScale(self):
        ''' Returns the max scale unc (avoiding unphysical variations) '''
        var = []
        for i in range(1, 10):
            if i == 3 or i == 7: continue
            var.append(self.GetRelUncScale(i))
        return max(var)

    def GetPDFunc(self):
        ''' 
     For 33 weights
     Eq [20] in:  https://arxiv.org/pdf/1510.03865.pdf
     Weights 2, to 31, using 1 as nominal
 
     For 100 weights:
   '''
        val = 0
        delta = sum([
            self.GetRelUncPDF(i) * self.GetRelUncPDF(i) for i in range(2, 32)
        ])
        if self.nPDFweights == 33:
            val = sqrt(delta)
        elif self.nPDFweights == 100:
            rms = sqrt(delta / 100)
            #val = sqrt(rms*rms + ((v110-v111)*0.75/2)*((v110-v111)*0.75/2));
            val = rms
        return val

    def GetAlphaSunc(self):
        '''
    if 33 weights:
    Eq [27] in:  https://arxiv.org/pdf/1510.03865.pdf
    Weights 32 and 33

    if 100 weights: no PDF weights...
   '''
        if self.nPDFweights == 33:
            alphaDo = self.GetPDFyield(32)
            alphaUp = self.GetPDFyield(33)
            return abs(alphaUp - alphaDo) / 2 / self.GetPDFnom()
        elif self.nPDFweights == 100:
            print 'WARNING: no LHE weights for alpha_s!!'
            return 0

    def GetPDFandAlphaSunc(self):
        ''' Quadratic sum of both '''
        pdfunc = self.GetPDFunc()
        alphas = self.GetAlphaSunc()
        return sqrt(pdfunc * pdfunc + alphas * alphas)

    def GetPSrelUnc(self, i):
        var = self.GetPSyield(i)
        nom = self.GetYield()
        return (var - nom) / nom

    def PrintPSunc(self, name='PSuncertainties'):
        ''' Prints a table with the ISR and FSR info '''
        t = OutText(self.outpath, name)
        #[0] is ISR=0.5 FSR=1; [1] is ISR=1 FSR=0.5; [2] is ISR=2 FSR=1; [3] is ISR=1 FSR=2
        s = lambda i, isr, fsr, lab: '[%i] ISR=%1.1f, FSR=%1.1f  (%s): %1.4f (%1.3f %s)' % (
            i, fsr, isr, lab, self.GetPSyield(i), self.GetPSrelUnc(
                i) * 100, '%')
        l1 = s(1, 0.5, 1.0, 'ISR down')
        t.SetSeparatorLength(len(l1))
        t.line(' PS uncertainties')
        t.line(' Yield: %1.2f' % self.GetYield())
        t.bar()
        t.line(l1)
        t.line(s(2, 1.0, 0.5, 'FSR down'))
        t.line(s(3, 2.0, 1.0, 'ISR up  '))
        t.line(s(4, 1.0, 2.0, 'FSR up  '))
        t.bar()
        t.write()

    def PrintMEscale(self, name='ScaleMEvariations'):
        ''' Prints a table with the info of scale systematics '''
        t = OutText(self.outpath, name)
        s = lambda i, muF, muR: ' [%d] muF = %1.2f, muR = %1.2f  | %1.2f (%1.2f %s)' % (
            i, muF, muR, self.GetScaleYield(i), self.GetRelUncScale(
                i) * 100, '%')
        nom = s(1, 0.5, 0.5)
        t.SetSeparatorLength(len(nom))
        t.line(" Scale ME uncertainties on tt acceptance")
        t.bar()
        t.line(nom)
        t.line(s(2, 0.5, 1.0))
        t.line(s(3, 0.5, 2.0) + ' (unphysical)')
        t.line(s(4, 1.0, 0.5))
        t.line(s(5, 1.0, 1.0) + ' (nominal)')
        t.line(s(6, 1.0, 2.0))
        t.line(s(7, 2.0, 0.5) + ' (unphysical)')
        t.line(s(8, 2.0, 1.0))
        t.line(s(9, 2.0, 2.0))
        t.sep()
        t.line(' Maximum variation: %1.2f %s ' %
               (self.GetMaxRelUncScale() * 100, '%'))
        t.bar()
        t.write()

    def PrintPDFyields(self, name='PDFvariations'):
        ''' Prints a table with the info of PDF systematics '''
        t = OutText(self.outpath, name)
        s = lambda i: ' ' + t.fix('[%d]' % i, 4, 'l', False
                                  ) + ' %1.2f (%1.2f %s)' % (self.GetPDFyield(
                                      i), self.GetRelUncPDF(i) * 100, '%')
        c0 = s(1) + ' (nominal) '
        t.SetSeparatorLength(len(c0))
        t.line('### PDF and alpha_s uncertianties')
        t.line()
        if self.nPDFweights == 33:
            t.line(
                ' Using PDF4LHC15_nlo_nf4_30_pdfas, 1+30+2 weights, see Table 6 in '
            )
            t.line(' > https://arxiv.org/pdf/1510.03865.pdf')
        elif self.nPDFweights == 100:
            t.line('### NNPDF variations: 100 (2 alpha_s variations missing)')
            #cout << " >>>> NNPDF systematic uncertainty" << endl;
            #cout << " Evaluated by taking the RMS under the 100 weights" << endl;
            #cout << " Alpha_s variations are added in quadrature after rescaling by 0.75" << endl;
            #cout << " The formula is: sqrt(RMS^2 + ((alphas var 1 - alphas var 2)*0.75/2)^2 )" << endl;
        t.bar()
        t.line(c0)
        for i in range(2, self.nPDFweights + 1):
            t.line(s(i))
        t.sep()
        pdfunc = self.GetPDFunc()
        alphas = self.GetAlphaSunc()
        totunc = self.GetPDFandAlphaSunc()
        if self.nPDFweights == 33:
            t.line(' See reference: ')
            t.line(' > https://arxiv.org/pdf/1510.03865.pdf')
            t.line(' Eq [20] for PDF unc:  %1.2f (%1.2f %s)' %
                   (pdfunc * self.GetPDFnom(), pdfunc * 100, '%'))
            t.line(' Eq [27] for alpha_S:  %1.2f (%1.2f %s)' %
                   (alphas * self.GetPDFnom(), alphas * 100, '%'))
            t.sep()
        t.line(' Total PDF + alpha_S uncertainty: ')
        t.line('  ## %1.2f (%1.2f %s)' %
               (totunc * self.GetPDFnom(), totunc * 100, '%'))
        t.bar()
        t.write()

    def __init__(self,
                 path='',
                 outpath='./temp/',
                 chan='ElMu',
                 level='2jets',
                 sampleName='TT',
                 PDFname='PDFweights',
                 ScaleName='ScaleWeights',
                 PSname='PSweights',
                 PDFsumName='',
                 ScaleSumName='',
                 lumi=308.54,
                 nGenEvents=-1,
                 pathToTrees='',
                 motherfname='',
                 histoprefix='H'):
        self.SetPath(path)
        self.SetOutPath(outpath)
        self.SetChan(chan)
        self.SetLevel(level)
        self.SetSampleName(sampleName)
        self.SetPDFhistoName(PDFname)
        self.SetScaleHistoName(ScaleName)
        self.SetPShistoName(PSname)
        self.SetNormPDFhistoName(PDFsumName)
        self.SetNormScaleHistoName(ScaleSumName)
        self.SetPathToTrees(pathToTrees)
        self.SetMotherFileName(motherfname)
        self.SetLumi(lumi)
        self.SetNgenEvents(nGenEvents)
        self.SetHistoPrefix(histoprefix)
        self.loadHistos()
Пример #6
0
# List of filenames
filelistname = sys.argv[1]

# Output filename
outfilename = sys.argv[2]
#outfilename = "csv/topreco_augmented1.csv"
#outfilename = "csv/topreco.csv"
outfile = open(outfilename, "wt")
csvwriter = csv.writer(outfile)
print("INFO: output file:", outfilename)

###############################
# BUILDING OUTPUTFILE

# Not entirely sure how TCHAIN works, but I am guessing the truth/nominal input determines which file it loads in?
tree = TChain("Delphes", "Delphes")
f = open(filelistname, 'r')
for fname in f.readlines():
    fname = fname.strip()
    tree.AddFile(fname)

n_entries = tree.GetEntries()
print("INFO: entries found:", n_entries)

###############################
# LOOPING THROUGH EVENTS

# Cap on number of reconstructed events.
if n_evt_max > 0: n_entries = min([n_evt_max, n_entries])
n_jets_per_event = 5
print("INFO: looping over %i reco-level events" % n_entries)
Пример #7
0
#outputdir='bbMETSamples/'
if outputdir != '.': os.system('mkdir -p ' + outputdir)

if options.outputfile is None or options.outputfile == rootfile:
    if not isfarmout:
        outputfilename = "/Output_" + rootfile
    else:
        outputfilename = "/Output_" + rootfile.split('.')[0] + ".root"
else:
    outputfilename = "/" + options.outputfile

#if isfarmout:
outfilename = outputdir + outputfilename
print "Input:", options.inputfile, "; Output:", outfilename

skimmedTree = TChain("outTree")


def WhichSample(filename):
    samplename = 'all'
    if filename.find('WJets') > -1:
        samplename = 'WJETS'
    elif filename.find('ZJets') > -1 or filename.find('DYJets') > -1:
        samplename = 'ZJETS'
    elif filename.find('TT') > -1:
        samplename = 'TT'
    else:
        samplename = 'all'


#    print samplename
Пример #8
0
        if "GluGluToHH" in files[0] or "HHTo4B" in files[0]: config["isSignal"] = True

    #read weights from alpSamples 
    config["xsec_br"]  = samples[sname]["xsec_br"]
    config["matcheff"] = samples[sname]["matcheff"]
    config["kfactor"]  = samples[sname]["kfactor"]

    json_str = json.dumps(config)

    #define selectors list
    selector = ComposableSelector(alp.Event)(0, json_str)
    selector.addOperator(BaseOperator(alp.Event)())

    selector.addOperator(FolderOperator(alp.Event)("pair"))
    selector.addOperator(CounterOperator(alp.Event)(config["n_gen_events"], weights_v))
    selector.addOperator(JetPlotterOperator(alp.Event)(btagAlgo, weights_v))        
    selector.addOperator(DiJetPlotterOperator(alp.Event)(weights_v))
    selector.addOperator(EventWriterOperator(alp.Event)(json_str,weights_v))

    #create tChain and process each files
    tchain = TChain("pair/tree")    
    for File in files:                     
        tchain.Add(File)       
    nev = numEvents if (numEvents > 0 and numEvents < tchain.GetEntries()) else tchain.GetEntries()
    procOpt = "ofile=./"+sname+".root" if not oDir else "ofile="+oDir+"/"+sname+".root"
    print "max numEv {}".format(nev)
    tchain.Process(selector, procOpt, nev)
    ns+=1

print "### processed {} samples ###".format(ns)
Пример #9
0
def Count(chan, trigs):
    #deal with weights first
    sumWeights=TChain("sumWeights")
    sumWeights.Add("%stth*.root" % prepath) 
    weights=[]
    fCurrent_wt = 0
    sampleNEvt=0
    nWeightEntries=sumWeights.GetEntries()
    for a in range(nWeightEntries):
       sumWeights.GetEntry(a)
       totalEventsWeighted=getattr(sumWeights, 'totalEventsWeighted')
       if sumWeights.GetTreeNumber() != fCurrent_wt:
          fCurrent_wt = sumWeights.GetTreeNumber()
          weights.append(sampleNEvt)
          sampleNEvt=0
       sampleNEvt = sampleNEvt+totalEventsWeighted
       if a==nWeightEntries-1: weights.append(sampleNEvt) #last file
    chain=TChain("nominal")
    chain.Add("%stth*.root" % prepath)
    nentries=chain.GetEntries()

    chain.SetBranchStatus("*",0) 
    chain.SetBranchStatus("Mll01",1)
    chain.SetBranchStatus("total_charge",1)
    chain.SetBranchStatus("lep_Pt_0",1)
    chain.SetBranchStatus("lep_Pt_1",1)
    chain.SetBranchStatus("lep_Eta_0",1)
    chain.SetBranchStatus("lep_Eta_1",1)
    chain.SetBranchStatus("lep_ID_0",1)
    chain.SetBranchStatus("lep_ID_1",1)
    chain.SetBranchStatus("lep_truthPdgId_0",1)
    chain.SetBranchStatus("lep_truthPdgId_1",1)
    chain.SetBranchStatus("lep_truthOrigin_0",1)
    chain.SetBranchStatus("lep_truthOrigin_1",1)
    chain.SetBranchStatus("lep_truthType_0",1)
    chain.SetBranchStatus("lep_truthType_1",1)
    chain.SetBranchStatus("lep_isQMisID_0",1)
    chain.SetBranchStatus("lep_isQMisID_1",1)
    chain.SetBranchStatus("nJets_OR_T_MV2c10_70",1)
    chain.SetBranchStatus("nJets_OR_T",1)
    chain.SetBranchStatus("lep_isTightLH_0",1)
    chain.SetBranchStatus("lep_isTightLH_1",1)
    chain.SetBranchStatus("lep_isLooseLH_0",1)
    chain.SetBranchStatus("lep_isLooseLH_1",1)
    chain.SetBranchStatus("lep_isolationFixedCutTight_0",1)
    chain.SetBranchStatus("lep_isolationFixedCutLoose_0",1)
    chain.SetBranchStatus("lep_isolationFixedCutTight_1",1)
    chain.SetBranchStatus("lep_isolationFixedCutLoose_1",1)
    chain.SetBranchStatus("lep_isolationFixedCutTightTrackOnly_0",1)
    chain.SetBranchStatus("lep_isolationFixedCutTightTrackOnly_1",1)
    chain.SetBranchStatus("HLT*",1)
    chain.SetBranchStatus("*type",1)
    chain.SetBranchStatus("RunYear",1)
    chain.SetBranchStatus("passEventCleaning",1)
    chain.SetBranchStatus("lep_isTrigMatch_0",1)
    chain.SetBranchStatus("lep_isTrigMatch_1",1)
    chain.SetBranchStatus("lep_isTrigMatchDLT_0",1)
    chain.SetBranchStatus("lep_isTrigMatchDLT_1",1)
    chain.SetBranchStatus("mcWeightOrg",1)
    chain.SetBranchStatus("pileupEventWeight_090",1)
    chain.SetBranchStatus("lepSFObjTight",1)
    chain.SetBranchStatus("lepSFTrigTight",1)
    chain.SetBranchStatus("JVT_EventWeight",1)
    chain.SetBranchStatus("SherpaNJetWeight",1)
    chain.SetBranchStatus("MV2c10_70_EventWeight",1)
    chain.SetBranchStatus("lep_chargeIDBDT*",1)
    chain.SetBranchStatus("nTaus_OR_Pt25",1)
    chain.SetBranchStatus("tau_JetBDTSigTight_0",1)
    chain.SetBranchStatus("tau_JetBDTSigTight_1",1)
    chain.SetBranchStatus("tau_tagWeightBin_0",1)
    chain.SetBranchStatus("tau_tagWeightBin_1",1)
    chain.SetBranchStatus("tau_passMuonOLR_0",1)
    chain.SetBranchStatus("tau_passMuonOLR_1",1)
    chain.SetBranchStatus("tau_passEleBDT_0",1)
    chain.SetBranchStatus("tau_passEleBDT_1",1)
    chain.SetBranchStatus("tau_charge_0",1)
    chain.SetBranchStatus("tau_charge_1",1)
    chain.SetBranchStatus("lep_ID_2",1)
    chain.SetBranchStatus("Mll02",1)
    chain.SetBranchStatus("lep_promptLeptonVeto_TagWeight_0",1)
    chain.SetBranchStatus("lep_promptLeptonVeto_TagWeight_1",1)
    chain.SetBranchStatus("lep_ambiguityType_0",1)
    chain.SetBranchStatus("lep_ambiguityType_1",1)
    #cuts
    fCurrent=-1
    chain.LoadTree(0)
    cuts_sr=TTreeFormula("cuts_sr",chan,chain)
    cuts_trig=TTreeFormula("cuts_trig",trigs,chain)
    raw_evts, numevts=0,0
    for evt in range(nentries):
    #for event in chain:
       #if evt%10000==0 : print evt
       chain.GetEntry(evt)
       #get current file
       currentFileName=chain.GetCurrentFile().GetName()
       RunYear=getattr(chain, "RunYear")
       mcWeightOrg=getattr(chain, "mcWeightOrg")
       pileupEventWeight_090=getattr(chain, "pileupEventWeight_090")
       lepSFObjTight=getattr(chain, "lepSFObjTight")
       lepSFTrigTight=getattr(chain, "lepSFTrigTight")
       JVT_EventWeight=getattr(chain, "JVT_EventWeight")
       SherpaNJetWeight=getattr(chain, "SherpaNJetWeight")
       MV2c10_70_EventWeight=getattr(chain, "MV2c10_70_EventWeight")
       lumi=1.0
       if RunYear < 2016.5: lumi=36074.6
       if RunYear > 2016.5: lumi=43813.7
       if chain.GetTreeNumber() != fCurrent:
          fCurrent=chain.GetTreeNumber()
          cuts_sr.Notify()
          cuts_trig.Notify()
       if cuts_sr.EvalInstance() and cuts_trig.EvalInstance():
       #if cuts_trig.EvalInstance():
          if "341177" in currentFileName: weight=0.05343
          if "341270" in currentFileName: weight=0.22276
          if "341271" in currentFileName: weight=0.23082
          kfac, filEff=1,1
          #weight=weight*kfac*filEff*mcWeightOrg*pileupEventWeight_090*lepSFObjTight*lepSFTrigTight*JVT_EventWeight*SherpaNJetWeight*MV2c10_70_EventWeight*lumi/weights[fCurrent]
          weight=weight*kfac*filEff*mcWeightOrg*lepSFObjTight*lepSFTrigTight*JVT_EventWeight*SherpaNJetWeight*MV2c10_70_EventWeight*lumi/weights[fCurrent]
          #print xsec, kfac, filEff, event.mcWeightOrg,event.pileupEventWeight_090,event.lepSFObjTight,event.lepSFTrigTight,event.JVT_EventWeight,event.SherpaNJetWeight,event.MV2c10_70_EventWeight, lumi
	  raw_evts=raw_evts+1
          numevts=numevts+weight
    print "%s(%.2f)" %(raw_evts, numevts)
Пример #10
0
def multiplicities_2D_vs_eta(sign,
                             var_list,
                             name,
                             cut="",
                             cut_gen=True,
                             treename="ntuple/tree"):
    cv = TCanvas("cv", "cv", 1000, 800)
    cv.SetGrid()
    leg = TLegend(0.62, 0.3 + 0.4, 0.95, 0.58 + 0.4)
    massimo = 0.
    minimo = 999.

    for b, s in enumerate(sign):
        for a, var in enumerate(var_list):
            first, second = var.split('.')
            cutstring = first + ".hasGenJ"
            if first == "Jets":
                label = "slimmedJets"
            elif first == "JetsNew1":
                label = "(abs(dz) < cosh(eta)*(0.02+0.01/pt)*5)"
                label = "abs(dz)<x"
            elif first == "JetsNew2":
                label = "fromPV()>0 || charge() ==0"
                label = "fromPV()>0"
            elif first == "JetsNew3":
                label = "(abs(dz) < cosh(eta)*(0.02+0.01/pt)*5) ||  (hasTrackDetails() && abs(dz)<pt*dzError )"
                label = "abs(dz)<x or abs(dz)<pt*dzError"
            elif first == "JetsNew4":
                label = "vertexRef().key()==0 ||( dzAssociatedPV() < cosh(eta)*(0.003+0.01/pt)*5) || charge==0"
                label = "dzAssociatedPV()"
            elif first == "JetsNew5":
                label = "fromPV()==PVUsedInFit || ( (fromPV()==PVTight || fromPV()==PVLoose && abs(dz()) < 0.3 )"
                label = "PUPPI-like"
            else:
                label = ""

            leg_label = second
            if cutstring == "":
                cutstring = cut
            else:
                if cut != "":
                    cutstring += " && " + first + "." + cut

            var_x = first + ".eta"
            print "Variable y: ", var
            print "Variable x: ", var_x
            print "Cut: ", cutstring
            print "*****"
            chain[s] = TChain(treename)
            for j, ss in enumerate(samples[s]['files']):
                chain[s].Add(NTUPLEDIR + ss + ".root")

            if (variable[var_x]['nbins'] > 0 and variable[var]['nbins'] > 0):
                print var_x, var
                hist[s][var] = TH2F(
                    s + var,
                    variable[var]['title'] + " vs " + variable[var_x]['title'],
                    variable[var_x]['nbins'], 0, variable[var_x]['max'],
                    variable[var]['nbins'], variable[var]['min'],
                    variable[var]['max'])
                hist[s][var].Sumw2()
                chain[s].Project(s + var, var + ":fabs(" + var_x + ")",
                                 cutstring)
                hist[s][var].SetOption("%s" %
                                       chain[s].GetTree().GetEntriesFast())
                hist[s][var].GetXaxis().SetTitle("jets |#eta|")
                hist[s][var].SetTitle("")
                hist[s][var].GetYaxis().SetTitle(variable[var]['title'])
                hist[s][var].GetZaxis().SetRangeUser(0.,
                                                     hist[s][var].GetMaximum())
                hist[s][var].SetMarkerColor(colors[a])

            cv.cd()
            hist_profX[s][var] = TProfile(hist[s][var].ProfileX(s + var +
                                                                "prof"))
            hist_profX[s][var].SetLineColor(colors[a])
            hist_profX[s][var].SetMinimum(0)
            hist_profX[s][var].SetFillColor(1)
            hist_profX[s][var].SetLineWidth(2)
            hist_profX[s][var].SetMarkerStyle(markers[a])
            hist_profX[s][var].SetMarkerColor(colors[a])
            hist_profX[s][var].GetXaxis().SetTitle("jets |#eta|")
            hist_profX[s][var].GetYaxis().SetTitle("particle multiplicities")
            hist_profX[s][var].SetTitle("")
            hist_profX[s][var].Draw("PL,sames")
            leg.AddEntry(hist_profX[s][var], leg_label, 'PL')

        leg.SetHeader("PF candidates: " + label)
        leg.Draw()
        drawCMS(-1, "Preliminary")
        cv.Update()
        cv.Print(PLOTDIR + sign[0] + "_" + first + "_vs_" +
                 var_x.replace('.', '_') + name + ".pdf")
        cv.Print(PLOTDIR + sign[0] + "_" + first + "_vs_" +
                 var_x.replace('.', '_') + name + ".png")
        if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
import ROOT, os
from ROOT import TChain, TCanvas, TH1
from Imports import *

Xic_MC_filedir = ximc2pwd+"18"
Xic_MC_filename = "MC_Lc2pKpiTuple_25103036.root"

Xic_MC_tree = TChain("tuple_Lc2pKpi/DecayTree")
excludedjobs = []
for job in range(25) :
    if not job in excludedjobs :
        #print ("- Adding subjob {0}".format(job))
        Xic_MC_tree.Add("{0}/{1}/output/{2}".format(Xic_MC_filedir,job,Xic_MC_filename))

c1 = ROOT.TCanvas("c1")

histogram1 = ROOT.TH1F("histogram1", "hist 1", 300, 2240, 2340)
histogram2 = ROOT.TH1F("histogram2", "hist 1", 300, 2240, 2340)
histogram1.SetLineColor(8)
histogram1.SetLineStyle(2)
histogram2.SetLineColor(46)
histogram2.SetLineStyle(2)

mass= ROOT.RooRealVar("mass","Mass",2420,2520,"MeV/c^{2}")
nbins = 300
varname = "lcplus_MM"

IDcuts = "abs(pplus1_ID)==211 && abs(kminus_ID)==321 && abs(pplus0_ID)==2212 && abs(lcplus_ID)==4122" #cuts to ensure right particles in the Monte Carlo

Xic_MC_name = Xic_MC_tree.GetName() + ""
Xic_MC_tree.Draw(varname+">>Xic_MC_masshist("+str(nbins)+","+str(2420)+","+str(2520)+")", IDcuts)
Пример #12
0
                    action='store',
                    dest='infile',
                    help='File name (multiple files using * are ok.')
args = parser.parse_args()
#print 'Input', args.infile
import os, sys, string, time
import ROOT
from ROOT import TTree, TObject, TFile, gDirectory, TH1D, TH2D, TH3D, TCanvas, gROOT, TGaxis, gStyle, TColor, TLegend, THStack, TChain
from array import array
from glob import glob
import subprocess
# Opening root file
fname = glob(args.infile)
print "Input file(s): ", fname
# Creating TChain
chainPOT = TChain("UBXSec/pottree")
for f in fname:
    chainPOT.Add(f)

# Printing the number of entries
entriesPOT = chainPOT.GetEntries()
print "Number of entries in the POT tree: ", entriesPOT
file = open("runsubrun_list.txt", "w")
# Getting POT number
NominalPOT = 6.0e20
TotalPOT = 0
for jentry in xrange(entriesPOT):
    entry = chainPOT.GetEntry(jentry)
    #print '{:e}'.format(float(chainPOT.pot))
    TotalPOT += chainPOT.pot
    #print "event:", chainPOT.run
Пример #13
0
class SampleSums:
    def GetFiles(self):
        self.files = GetFiles(self.path, self.sname)

    def LoadTree(self):
        self.tree = TChain(self.tname, self.tname)
        for f in self.files:
            self.tree.Add(f)

    def GetCountsFromSumWTree(self):
        if not hasattr(self, 'treesow'):
            #print 'WARNING: tree with sum of weights has not been loaded!!'
            self.LoadTree()
        count = 0
        sow = 0
        for event in self.tree:
            count += event.genEventCount
            sow += event.genEventSumw
        self.count = count
        self.sow = sow

    def GetSumPDFhistoFromSumWTree(self):
        if not hasattr(self, 'treesow'):
            #print 'WARNING: tree with sum of weights has not been loaded!!'
            self.LoadTree()
        self.treesow.GetEntry(1)
        nPDFweights = self.treesow.nLHEPdfSumw
        h = TH1F('SumOfWeightsPDF', '', nPDFweights, 0.5, nPDFweights + 0.5)
        count = 0
        sow = 0
        for event in self.treesow:
            count += event.genEventCount
            sow += event.genEventSumw
            for i in range(nPDFweights):
                h.Fill(i + 1, event.LHEPdfSumw[i])
        h.SetDirectory(0)
        #for i in range(h.GetNbinsX()): print '[%i] %1.2f'%(i, h.GetBinContent(i+1))
        self.count = count
        self.sow = sow
        return h

    def GetSumScaleHistoFromSumWTree(self):
        if not hasattr(self, 'treesow'):
            #print 'WARNING: tree with sum of weights has not been loaded!!'
            self.LoadTree()
            return
        self.treesow.GetEntry(1)
        nScaleWeights = self.treesow.nLHEScaleSumw
        h = TH1F('SumOfWeightsScale', '', nScaleWeights, 0.5,
                 nScaleWeights + 0.5)
        print 'GetEntries: ', self.treesow.GetEntries()
        for event in self.treesow:
            for i in range(nScaleWeights):
                h.Fill(i + 1, event.LHEScaleSumw[i])
        h.SetDirectory(0)
        #for i in range(h.GetNbinsX()): print '[%i] %1.2f'%(i, h.GetBinContent(i+1))
        return h

    def SetNormPDFhistoName(self, n):
        self.normPDFhistoName = n

    def SetNormScaleHistoName(self, n):
        self.normScaleHitstoName = n

    def SetCountHistoName(self, n='Count'):
        self.countName = n

    def SetSOWname(self, n='SumWeights'):
        self.SOWname = n

    def GetHsumPDF(self, hname=''):
        if hname != '': self.SetNormPDFhistoName(hname)
        self.hsumpdf = t.GetNamedHisto(
            self.normPDFhistoName
        ) if self.normPDFhistoName != '' else self.GetSumPDFhistoFromSumWTree(
        )
        return self.hsumpdf

    def GetHsumPDF(self, hname=''):
        if hname != '': self.SetNormPDFhistoName(hname)
        self.hsumscale = t.GetNamedHisto(
            self.normScaleHitstoName
        ) if self.normScaleHitstoName != '' else self.GetSumScaleHistoFromSumWTree(
        )
        return self.hsumscale

    def GetCount(self, hname):
        if hname != '': self.SetCountHistoName(hname)
        if self.t.IsHisto(self.files[0], self.countName):
            h = t.GetNamedHisto(self.countName)
            count = h.GetBinContent(1)
            self.count = count
        else:
            self.GetCountsFromSumWTree()
        return self.count

    def GetSOW(self, hname):
        if hname != '': self.SetSOWname(hname)
        if self.t.IsHisto(self.files[0], self.SOWname):
            h = t.GetNamedHisto(self.SOWname)
            sow = h.GetBinContent(1)
            self.sow = sow
        else:
            self.GetCountsFromSumWTree()
        return self.sow

    def __init__(self,
                 pathToTrees,
                 sname,
                 tname='Runs',
                 normPDFhistoName='',
                 normScaleHitstoName=''):
        self.path = pathToTrees
        self.sname = sname
        self.tname = tname
        self.GetFiles()
        self.t = TopHistoReader('')  #self.path)
        self.SetNormPDFhistoName(normPDFhistoName)
        self.SetNormScaleHistoName(normScaleHitstoName)
Пример #14
0
 def LoadTree(self):
     self.tree = TChain(self.tname, self.tname)
     for f in self.files:
         self.tree.Add(f)
Пример #15
0
        i + 1, len(runs), len(this_file_list), run)
    if not len(this_file_list):
        run_information[run] = [0 for i in range(35)]
        continue
    cut_flow = False
    for file in this_file_list:
        try:
            if not cut_flow:
                first_root_file = TFile.Open(prefix + file)
                assert first_root_file.IsOpen()
                if options.verbose: print "   - root file " + file + " is open"
                cut_flow = first_root_file.Get("cut_flow").Clone(
                    "compressed_cut_flow")
                if options.verbose:
                    print "    - cut flow[1]: %i" % cut_flow.GetBinContent(1)
                first_chain = TChain("qcd")
                first_chain.Add(prefix + file)
                n_entries = first_chain.GetEntries()

                if cut_flow.GetBinContent(1) == 0: zero_entry_runs.append(file)
            else:
                root_file = TFile.Open(prefix + file)
                assert root_file.IsOpen()
                if options.verbose: print "   - root file " + file + " is open"
                this_cut_flow = root_file.Get("cut_flow")
                if options.verbose:
                    print "    - cut flow[1]: %i" % this_cut_flow.GetBinContent(
                        1)
                cut_flow.Add(this_cut_flow)
                chain = TChain("qcd")
                chain.Add(prefix + file)
Пример #16
0
def main():
    gStyle.SetOptStat(0)
    BIAS_DIR = global_paths.BIASDIR+args.btagging+"/"
    if args.year == 'run2c':
        BIAS_DIR += "combined_run2/"
        #BIAS_DIR += "combined_run2_signal{}/"
        ## individual plots stored in run2c_masspoints    
    
    ## extract pulls
    pulls = TGraphErrors()
    for m in range(1600,8001,100):
        #try:
            pull0=int(PULL0[m])
            #pull0=10.

            #tfile = TFile.Open(BIAS_DIR+"fitDiagnostics_M{mass}.root".format(mass=m), "READ")
            #tfile = TFile.Open(BIAS_DIR.format(pull0)+"fitDiagnostics_M{mass}.root".format(mass=m), "READ")
            #tree = tfile.Get("tree_fit_sb")
            tree = TChain("tree_fit_sb")
            for seed in ['123456', '234567', '345678', '456789', '567891', '678912', '789123', '891234', '912345', '123459']:
                tree.Add(BIAS_DIR+"fitDiagnostics_M{mass}_{seed}.root".format(mass=m, seed=seed))
 
            ## the method proposed in the documemtation
            #hist = TH1D("hist", "hist", 20, -5, 5)
            #tree.Project("hist", "(r-1)/(0.5*(rHiErr+rLoErr))")
            #fit_func = TF1("gaussfit","gaus" , -5., 5.)
            #hist.Fit(fit_func, "E")
            #pulls.SetPoint(pulls.GetN(), m, fit_func.GetParameter(1)) ## get mean of gaussian fit
            
            ## Alberto's method
            #hist = TH1D("s_pulls", ";%s/#sigma_{r};Number of toys" % ("(r - "+str(pull0)+")"), 25, -5, +5) #
            hist = TH1D("s_pulls", ";%s/#sigma_{r};Number of toys" % ("#Deltar"), 25, -5, +5) #
            for i in range(tree.GetEntries()):
                if hist.GetEntries() >= 1000: continue
                tree.GetEntry(i)
                #print "r = {} (+{}, -{})".format(tree.r, tree.rHiErr, tree.rLoErr)
                ##if tree.rLoErr < 0.: continue
                if abs(tree.r+1.) < 0.001: continue
                if abs(tree.r-1.) < 0.001: continue
                if abs(tree.r-0.) < 0.001: continue
                #if abs(tree.rLoErr)>8.: continue # trying to skip these values FIXME
                if tree.rHiErr==0. or tree.rLoErr==0.: continue
                #print "r = {} (+{}, -{})".format(tree.r, tree.rHiErr, tree.rLoErr)
                #pull = (tree.r-pull0)/(0.5*(abs(tree.rHiErr)+abs(tree.rLoErr))) ## documentation approach
                #pull = (tree.r-pull0)/abs(tree.rHiErr) if tree.r-pull0 < 0. else (tree.r-pull0)/abs(tree.rLoErr)  ## Alberto's sign convention
                pull = (tree.r-pull0)/abs(tree.rHiErr) if tree.r-pull0 > 0. else (tree.r-pull0)/abs(tree.rLoErr) ## my own approach
                #pull = (tree.r-pull0)/abs(tree.rHiErr) if tree.r < 0. else (tree.r-pull0)/abs(tree.rLoErr)  ## Alberto's sign convention but depending directly on the sign of r
                #pull = (tree.r-pull0)/abs(tree.rHiErr) if tree.r > 0. else (tree.r-pull0)/abs(tree.rLoErr) ## my own approach with an rErr dependence on r, not r-1
                hist.Fill(pull)

            ## individual plots for checking the fit quality
            c1 = TCanvas("c1", "Pulls", 600, 600)
            c1.cd()
            #c1.GetPad(0).SetTopMargin(0.06)
            #c1.GetPad(0).SetRightMargin(0.05)
            #c1.GetPad(0).SetBottomMargin(0.15)
            #c1.GetPad(0).SetTicks(1, 1)
            hist.GetXaxis().SetTitleSize(0.045)
            hist.GetYaxis().SetTitleSize(0.045)
            hist.GetYaxis().SetTitleOffset(1.1)
            hist.GetXaxis().SetTitleOffset(1.05)
            hist.GetXaxis().SetLimits(-5, 5.)
            hist.GetYaxis().SetLimits(0, 200.)
            hist.SetMinimum(0.)
            hist.SetMaximum(190.)
            c1.SetTopMargin(0.05)

            ##print "@ m= {}: \t mean = {}".format(m, hist.GetMean())
            #pulls.SetPoint(pulls.GetN(), m, hist.GetMean()) ## get actual mean of histogram
            fit_func = TF1("gaussfit","gaus" , -3., 3.)
            ###fit_func.SetParameter(1, hist.GetMean())
            #fit_func.SetParameter(1, 0.)
            ###fit_func.SetParLimits(1, -0.8, 0.8)
            #fit_func.SetParameter(2, 1.)
            ###fit_func.SetParameter(0, 45.)
            ###fit_func.SetParLimits(0, 30., 100.)
            hist.Fit(fit_func, "E")

            hist.Draw()

            drawCMS(-1, "Simulation Preliminary", year='run2')
            drawMass("m_{Z'} = "+str(m)+" GeV")
            c1.Print("plots/bias/run2c_masspoints/bias_fit_"+str(m)+"_"+args.year+".pdf")
            c1.Print("plots/bias/run2c_masspoints/bias_fit_"+str(m)+"_"+args.year+".png")

            n = pulls.GetN()
            pulls.SetPoint(n, m, fit_func.GetParameter(1)) ## get fitted gaussian mean
            pulls.SetPointError(n, 0., fit_func.GetParError(1)) ## set gaussian width as error

            hist.Delete()
            c1.Delete()
            #tfile.Close()
        #except:
        #    print "something went wrong in m =", m

    ## draw pulls
    c = TCanvas("canvas", "canvas", 800, 600)
    pulls.SetTitle(";m_{Z'} (GeV);mean #Deltar/#sigma_{r}")
    pulls.SetMarkerStyle(2)
    pulls.SetMarkerColor(2)
    pulls.SetLineColor(2)
    pulls.SetLineWidth(2)
    #pulls.GetYaxis().SetNdivisions(1020)
    pulls.SetMinimum(-0.5)
    pulls.SetMaximum(0.5)
    pulls.Draw("APL")
    zeroline = TGraph()
    zeroline.SetPoint(zeroline.GetN(), 1000, 0)
    zeroline.SetPoint(zeroline.GetN(), 8600, 0)
    zeroline.SetMarkerStyle(7)
    zeroline.SetMarkerSize(0)
    zeroline.SetLineStyle(15)
    zeroline.SetLineColor(1)
    zeroline.Draw("PL")
    c.SetGrid()
    pulls.GetXaxis().SetTitleSize(0.045)
    pulls.GetYaxis().SetTitleSize(0.045)
    pulls.GetYaxis().SetTitleOffset(1.1)
    pulls.GetXaxis().SetTitleOffset(1.05)
    pulls.GetXaxis().SetLimits(1350., 8150.)
    c.SetTopMargin(0.05)
    drawCMS(-1, "Simulation Preliminary", year='run2')
    c.Print("plots/bias/bias_study_"+args.year+".png")
    c.Print("plots/bias/bias_study_"+args.year+".pdf")
Пример #17
0
        cut = allVertCut
    if opt == '-m':
        cut = mollerCut
    if opt == '-w':
        cut = wabCut
    if opt == '-e':
        ebeam = float(arg)
    if opt == '-c':
        clusterT = float(arg)
    if opt == '-z':
        targetZ = float(arg)
    if opt == '-h':
        print_usage()
        sys.exit(0)

print remainder[0]
#treeFile = TFile(sys.argv[1],"RECREATE")
#tree = TTree("ntuple","data from text tuple "+sys.argv[2])
print remainder[1:]
chain = TChain("ntuple")
for i in remainder[1:]:
    chain.Add(i, 0)
print chain.GetEntries()
outFile = TFile(remainder[0], "RECREATE")
events = chain.CopyTree(cut.format(ebeam, clusterT, targetZ))
print events.GetEntries()
#outFile = TFile(remainder[0],"RECREATE")
#events.Write()
events.Write("ntuple", TTree.kOverwrite)
gDirectory.ls()
Пример #18
0
    '''
    p1 = pair[0].p
    p2 = pair[1].p
    ppair = p1 + p2
    return ppair.M()


class Particle:
    def __init__(self, p, q):
        self.p = p
        self.q = q


if __name__ == '__main__':

    data = TChain("mini")
    data.Add("http://opendata.atlas.cern/release/samples/Data/DataMuons.root")

    num_events = data.GetEntries()
    print("Number of events = " + str(num_events))

    h_mpair = TH1F("mpair", "Invariant Mass of Leptons ; mass /Gev; freq", 50,
                   0, 200)

    num_events_to_process = 10000
    for i_event in range(num_events_to_process):
        data.GetEntry(i_event)
        n_leptons = data.lep_n
        if n_leptons >= 2:
            #print("num of Leptons "+str(n_leptons))
            leptons = leptons_from_event(data)
Пример #19
0
class DataReader(Path):
    """Create RooDataSet from a TChain"""
    def __init__(self, cfg):
        """Init"""
        super(DataReader, self).__init__(cfg)
        self.argset = cfg['argset']
        self.reset()
        return

    def reset(self):
        super(DataReader, self).reset()
        self.ch = None
        self.friend = None
        self.dataset = {}

    def __str__(self):
        list_of_files = self.ch.GetListOfFiles()
        next_file = TIter(list_of_files)
        print("Input file list is given below.")
        for f in range(list_of_files.GetEntries()):
            print("\t{0}".format(next_file().GetTitle()))
        print("End of the input file list.")
        return ""

    @classmethod
    def templateConfig(cls):
        cfg = {
            'name': "DataReader",
            'ifile': [],
            'ifriend': [],
            'ifriendIndex': ["Run", "Event"],
            'argset': [],
            'dataset': [],
            'preloadFile': None,
        }
        return cfg

    def createDataSet(self, dname, dcut):
        """Create named dataset"""
        if dname in self.dataset.keys():
            return self.dataset[dname]
        data = RooDataSet(dname, "", self.ch, self.argset, dcut)
        self.dataset[dname] = data
        return data

    def createDataSets(self, cfg):
        """Create named dataset"""
        for name, cut in cfg:
            if self.cfg['preloadFile'] and os.path.exists(
                    self.cfg['preloadFile']):
                file_preload = ROOT.TFile(self.cfg['preloadFile'])
                data = file_preload.Get(name)
                if not data == None:
                    self.dataset[name] = data
                file_preload.Close()
            self.createDataSet(name, cut)
        return self.dataset

    def _runPath(self):
        self.ch = TChain("events")
        for f in self.cfg['ifile']:
            self.ch.Add(f)
        if len(self.cfg['ifriend']) > 0:
            self.friend = TChain("tree")
            for f in self.cfg['ifriend']:
                self.friend.Add(f)
            self.friend.BuildIndex(*self.cfg['ifriendIndex'])
            self.ch.AddFriend(self.friend)
        self.createDataSets(self.cfg['dataset'])
        pass

    def _addSource(self):
        """Add dataset and arguments to source pool"""
        if self.cfg['preloadFile'] and not os.path.exists(
                self.cfg['preloadFile']):
            file_preload = ROOT.TFile(self.cfg['preloadFile'], 'RECREATE')
            for dname, d in self.dataset.items():
                d.Write()
            file_preload.Close()

        if not 'source' in self.cfg.keys():
            self.cfg['source'] = {}
        self.cfg['source']['{0}.tree'.format(self.name)] = self.ch
        self.cfg['source']['{0}.argset'.format(self.name)] = self.argset
        if len(self.cfg['ifriend']) > 0:
            self.cfg['source']['{0}.friend'.format(self.name)] = self.friend
        for dname, d in self.dataset.items():
            self.cfg['source'][dname] = d
            self.logger.logINFO("{0} events in {1}.".format(
                d.sumEntries(), dname))
        super(DataReader, self)._addSource()
Пример #20
0
def compare(fnames, varsets, **kwargs):

    # SETTING
    tname = kwargs.get('tree', 'Events')
    entries = kwargs.get('entries', [])  # entries of files
    outdir = kwargs.get('outdir', "compare")
    tag = kwargs.get('tag', "")
    cut = kwargs.get('cut', "")
    norm = kwargs.get('norm', False)
    ensuredir(outdir)
    if norm:
        tag += "_norm"  # normalize each histogram
    tree = TChain(tname)

    # GET FILES & TREES
    for fname in fnames:
        tree.Add(fname)

    # PLOT
    for varset in varsets:
        fname = "%s/%s%s.png" % (outdir, '-'.join(v.filename
                                                  for v in varset), tag)
        rrange = 0.5
        header = "Compare"  # legend header
        text = ""  # corner text
        ratio = True  #and False
        logy = True and False
        grid = True  #and False
        staterr = True  #and False # add uncertainty band to first histogram
        lstyle = 1  # solid lines
        xvar = varset[0]
        LOG.header(fname)

        # GET HISOGRAMS
        hists = []
        for i, variable in enumerate(varset):
            hname = "%s_%d" % (variable.filename, i)
            htitle = variable.name
            #hist   = variable.gethist(hname,htitle)
            #dcmd   = variable.drawcmd(hname)
            hist = variable.draw(
                tree, cut, name=hname,
                title=htitle)  # create and fill hist from tree
            evts = hist.GetEntries()
            hist.SetTitle(htitle)  #"%s (%d)"%(htitle,evts)
            hists.append(hist)
            print ">>>   %r: entries=%d, integral=%s, mean=%#.6g, s.d.=%#.6g" % (
                htitle, evts, hist.Integral(), hist.GetMean(),
                hist.GetStdDev())

        # DRAW PLOT
        plot = Plot(xvar, hists, norm=norm)
        plot.draw(ratio=True,
                  logy=logy,
                  ratiorange=rrange,
                  lstyle=lstyle,
                  grid=grid,
                  staterr=staterr)
        plot.drawlegend(header=header, latex=False)
        plot.drawtext(text)
        plot.saveas(fname)
        plot.close()
        print
Пример #21
0
    def _load_root(self, files, *, start=None, stop=None, **_):
        import sys
        sys.argv.append('-b')
        from ROOT import TChain
        from root_numpy import tree2array

        tree = TChain('T')
        for file_ in files:
            if exists(file_):
                tree.Add(file_)

        p0 = self._db.d1p * 1000

        if self.run < 20000:
            arm = 'L'
            pr1_cut = 'L.prl1.e>{}'.format(self._db.pr1_cut * p0)
            sum_cut = '(L.prl1.e+L.prl2.e)>{}'.format(self._db.sum_cut * p0)
        else:
            arm = 'R'
            pr1_cut = 'R.ps.e>{}'.format(self._db.pr1_cut * p0)
            sum_cut = '(R.ps.e+R.sh.e)>{}'.format(self._db.sum_cut * p0)
        cut = '&&'.join([
            'D{}.evtypebits!=0'.format(arm),
            '{}.tr.n==1'.format(arm),
            '{}.cer.asum_c>{}'.format(arm, self._db.cer_cut),
            pr1_cut,
            sum_cut,
            '{}rb.bpmavail>0.5'.format(arm),
        ])

        hel_vars = ['hel.{}.{}'.format(arm, x) for x in ['hel_act', 'error']]
        bpm_vars = [
            '{}rb.tgt_0_{}'.format(arm, x) for x in ['x', 'y', 'theta', 'phi']
        ]
        sr_vars = [
            '{}rb.Raster.rawcurSL.{}'.format(arm, x) for x in ['x', 'y']
        ]
        gold_vars = [
            '{}.gold.{}'.format(arm, x) for x in ['th', 'y', 'ph', 'dp']
        ]
        rec_vars = [
            '{}.rec.{}'.format(arm, x) for x in ['x', 'th', 'y', 'ph', 'dp']
        ]

        all_vars = tree2array(
            tree,
            hel_vars + bpm_vars + sr_vars + gold_vars + rec_vars,
            cut,
            start=start,
            stop=stop,
        )

        self.hel = np.rec.fromarrays(
            [all_vars[x] for x in hel_vars],
            names='val,err',
        )
        self.bpm = np.rec.fromarrays(
            [all_vars[x] for x in bpm_vars],
            names='x,y,t,p',
        )
        self.sr = np.rec.fromarrays(
            [all_vars[x] for x in sr_vars],
            names='x,y',
        )
        self.gold = np.rec.fromarrays(
            [all_vars[x] for x in gold_vars],
            names='t,y,p',
        )
        self.rec = np.rec.fromarrays(
            [all_vars[x] for x in rec_vars],
            names='x,t,y,p,d',
        )
Пример #22
0
def compare_variables(sign,
                      var_list,
                      cut_gen,
                      name,
                      cut="",
                      treename="ntuple/tree"):
    cv = TCanvas("cv", "cv", 1000, 800)
    cv.SetGrid()
    leg = TLegend(0.62, 0.7, 0.95, 0.98)
    leg.SetHeader("Cut on PF candidates")
    massimo = 0.
    minimo = 999.
    for b, s in enumerate(sign):
        for a, var in enumerate(var_list):
            if cut_gen:
                first, second = var.split('.')
                cutstring = first + ".hasGenJ"
                if first == "Jets":
                    label = "slimmedJets"
                elif first == "JetsNew1":
                    label = "(abs(dz) < cosh(eta)*(0.02+0.01/pt)*5)"
                    label = "abs(dz)<x"
                elif first == "JetsNew2":
                    label = "fromPV()>0 || charge() ==0"
                    label = "fromPV()>0"
                elif first == "JetsNew3":
                    label = "(abs(dz) < cosh(eta)*(0.02+0.01/pt)*5) ||  (hasTrackDetails() && abs(dz)<pt*dzError )"
                    label = "abs(dz)<x or abs(dz)<pt*dzError"
                elif first == "JetsNew4":
                    label = "vertexRef().key()==0 ||( dzAssociatedPV() < cosh(eta)*(0.003+0.01/pt)*5) || charge==0"
                    label = "dzAssociatedPV()"
                elif first == "JetsNew5":
                    label = "fromPV()==PVUsedInFit || ( (fromPV()==PVTight || fromPV()==PVLoose && abs(dz()) < 0.3 )"
                    label = "PUPPI-like"
                else:
                    label = ""
            else:
                first, second = var.split('n')
                if second == "Jets":
                    label = "slimmedJets"
                elif second == "JetsNew1":
                    label = "(abs(dz) < cosh(eta)*(0.02+0.01/pt)*5)"
                    label = "abs(dz)<x"
                elif second == "JetsNew2":
                    label = "fromPV()>0 || charge() ==0"
                    label = "fromPV()>0"
                elif second == "JetsNew3":
                    label = "(abs(dz) < cosh(eta)*(0.02+0.01/pt)*5) ||  (hasTrackDetails() && abs(dz)<pt*dzError )"
                    label = "abs(dz)<x or abs(dz)<pt*dzError"
                elif second == "JetsNew4":
                    label = "vertexRef().key()==0 ||( dzAssociatedPV() < cosh(eta)*(0.003+0.01/pt)*5) || charge==0"
                    label = "dzAssociatedPV()"
                elif second == "JetsNew5":
                    label = "fromPV()==PVUsedInFit || ( (fromPV()==PVTight || fromPV()==PVLoose && abs(dz()) < 0.3 )"
                    label = "PUPPI-like"
                else:
                    label = ""

                first = ""
                first = second
                cutstring = first + ".hasGenJ"

            if cutstring == "":
                cutstring = cut
            else:
                if cut != "":
                    cutstring += " && " + first + "." + cut

            print "Variable: ", var
            print "Cut: ", cutstring
            print "*****"
            chain[s] = TChain(treename)
            for j, ss in enumerate(samples[s]['files']):
                chain[s].Add(NTUPLEDIR + ss + ".root")
            if variable[var]['nbins'] > 0:
                hist[s][var] = TH1F(s + var, ";" + variable[var]['title'],
                                    variable[var]['nbins'],
                                    variable[var]['min'], variable[var]['max'])
            hist[s][var].Sumw2()
            chain[s].Project(s + var, var, cutstring)

            hist[s][var].SetOption("%s" % chain[s].GetTree().GetEntriesFast())
            hist[s][var].Scale(
                samples[s]['weight'] if hist[s][var].Integral() >= 0 else 0)
            hist[s][var].SetLineColor(colors[a])
            hist[s][var].SetFillColor(colors[a])
            hist[s][var].SetLineWidth(2)
            hist[s][var].SetMarkerStyle(markers[a])
            hist[s][var].SetMarkerColor(colors[a])
            hist[s][var].SetTitle("")
            #hist[s][var].SetFillStyle(0)
            hist[s][var].SetLineStyle(
                lines[b]
            )  #original: lines[b] to have different styles for different backgrounds
            addOverflow(hist[s][var], False)
            massimo = max(massimo, hist[s][var].GetMaximum())
            minimo = min(minimo, hist[s][var].GetMinimum())
            cv.cd()
            hist[s][var].Draw("SAMES, PL")  # if (a>0 and b>0) else "HISTO")
            leg.AddEntry(hist[s][var], label, 'PL')
            uncert[s][var] = hist[s][var].Clone(s + "_err")
            uncert[s][var].SetMarkerStyle(0)
            uncert[s][var].SetFillColor(colors[a])
            uncert[s][var].SetFillStyle(3001)
            uncert[s][var].Draw("SAME,E2")

        if variable[var]['log']:

            cv.SetLogy()

    for b, s in enumerate(sign):
        for a, var in enumerate(var_list):
            hist[s][var].SetMaximum(massimo * 1.5)
            if variable[var]['log'] == False:
                hist[s][var].SetMinimum(minimo * 0.5)
    #leg.SetHeader(samples[sample]['leg_name'])
    #massimo = 0
    leg.Draw()
    drawCMS(-1, "Preliminary")
    cv.Update()
    cv.Print(PLOTDIR + sign[0] + "_" + var_list[0].replace('.', '_') + name +
             ".pdf")
    cv.Print(PLOTDIR + sign[0] + "_" + var_list[0].replace('.', '_') + name +
             ".png")
    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Пример #23
0
npx_sum = {1: 0, 2: 0}
npx_sum_correct = {1: 0, 2: 0}

filler.set_next_index(current_index)
roi_chain = None

fout = open(CSVNAME, 'w')
fout.write(
    'entry,label_shower_npx,reco_shower_npx,correct_shower_npx,label_track_npx,reco_track_npx,correct_track_npx,total_npx,correct_npx'
)
if '1e1p' in FLAVOUR:
    fout.write(
        ',eminus_energy,eminus_mom,eminus_dirx,eminus_diry,eminus_dirz,proton_energy,proton_mom,proton_dirx,proton_diry,proton_dirz,open_angle'
    )
    from ROOT import TChain
    roi_chain = TChain("partroi_segment_tree")
    for fname in filler.pd().io().file_list():
        roi_chain.AddFile(fname)
fout.write('\n')


def target_event(roi_v):
    primary_eminus = None
    primary_proton = None
    for roi_index in xrange(roi_v.size()):
        roi = roi_v[roi_index]
        if roi.PdgCode() == 11 and roi.TrackID() == roi.ParentTrackID():
            if not primary_eminus is None: return False
            primary_eminus = roi_index
        elif roi.PdgCode() == 2212 and roi.TrackID() == roi.ParentTrackID():
            if not primary_eminus is None: return False
Пример #24
0
def resolution_vs_eta(sign,
                      var,
                      cut_gen,
                      name,
                      min_eta,
                      max_eta,
                      cut="",
                      treename="ntuple/tree",
                      drawDebugFit=False,
                      col_index=-1):
    massimo = 0.
    minimo = 999.
    if col_index == -1:
        col = 0
    else:
        col = col_index
    if cut_gen:
        first, second = var.split('.')
        cutstring = first + ".hasGenJ"
        if first == "Jets":
            label = "slimmedJets"
        elif first == "JetsNew1":
            label = "(abs(dz) < cosh(eta)*(0.02+0.01/pt)*5)"
            label = "abs(dz)<x"
        elif first == "JetsNew2":
            label = "fromPV()>0 || charge() ==0"
            label = "fromPV()>0"
        elif first == "JetsNew3":
            label = "(abs(dz) < cosh(eta)*(0.02+0.01/pt)*5) ||  (hasTrackDetails() && abs(dz)<pt*dzError )"
            label = "abs(dz)<x or abs(dz)<pt*dzError"
        elif first == "JetsNew4":
            label = "vertexRef().key()==0 ||( dzAssociatedPV() < cosh(eta)*(0.003+0.01/pt)*5) || charge==0"
            label = "dzAssociatedPV()"
        elif first == "JetsNew5":
            label = "fromPV()==PVUsedInFit || ( (fromPV()==PVTight || fromPV()==PVLoose && abs(dz()) < 0.3 )"
            label = "PUPPI-like"
        else:
            label = ""
    else:
        first, second = var.split('n')
        label = "aaa"
        first = ""
        first = second
        cutstring = first + ".hasGenJ"

    if cutstring == "":
        cutstring = cut + ""
    else:
        if cut != "":
            cutstring += " && " + first + "." + cut + " && abs(" + first + ".eta)<" + str(
                max_eta) + " && abs(" + first + ".eta)>=" + str(min_eta)

    print "Variable: ", var
    print "Cut: ", cutstring
    print "*****"
    chain[sign] = TChain(treename)
    for j, ss in enumerate(samples[sign]['files']):
        chain[sign].Add(NTUPLEDIR + ss + ".root")
    if variable[var]['nbins'] > 0:
        hist[sign][var] = TH1F(sign + var, ";" + variable[var]['title'],
                               variable[var]['nbins'], variable[var]['min'],
                               variable[var]['max'])
    hist[sign][var].Sumw2()
    chain[sign].Project(sign + var, var, cutstring)

    hist[sign][var].SetOption("%s" % chain[sign].GetTree().GetEntriesFast())
    hist[sign][var].Scale(
        samples[sign]['weight'] if hist[sign][var].Integral() >= 0 else 0)
    hist[sign][var].SetLineColor(colors[col])
    hist[sign][var].SetFillColor(colors[col])
    hist[sign][var].SetLineWidth(2)
    hist[sign][var].SetMarkerStyle(markers[1])
    hist[sign][var].SetMarkerColor(colors[col])
    hist[sign][var].SetTitle("")
    hist[sign][var].SetLineStyle(
        lines[0]
    )  #original: lines[0] to have different styles for different backgrounds
    addOverflow(hist[sign][var], False)
    massimo = max(massimo, hist[sign][var].GetMaximum())
    minimo = min(minimo, hist[sign][var].GetMinimum())
    if drawDebugFit:
        cv = TCanvas("cv", "cv", 1000, 800)
        cv.SetGrid()
        leg = TLegend(0.62, 0.7, 0.95, 0.98)
        leg.SetHeader("|#eta|:[" + str(min_eta) + "," + str(max_eta) + "]")
        cv.cd()
        hist[sign][var].Draw("SAMES, PL")  # if (a>0 and b>0) else "HISTO")
        uncert[sign][var] = hist[sign][var].Clone(sign + "_err")
        uncert[sign][var].SetMarkerStyle(markers[col])
        uncert[sign][var].SetFillColor(colors[col])
        uncert[sign][var].SetFillStyle(3001)
        uncert[sign][var].Draw("SAME,E2")
        leg.AddEntry(hist[sign][var], label, 'PL')
    fit0[sign][var] = TF1("f0" + sign + var, "gaus", variable[var]['min'],
                          variable[var]['max'])
    fit0[sign][var].SetParameter(1, hist[sign][var].GetMean())
    fit0[sign][var].SetParameter(2, hist[sign][var].GetRMS())
    hist[sign][var].Fit(
        "f0" + sign + var, "PWMS", "",
        hist[sign][var].GetMean() - 4 * hist[sign][var].GetRMS(),
        hist[sign][var].GetMean() + 4 * hist[sign][var].GetRMS())
    RMS_resolution = hist[sign][var].GetRMS()
    fit1[sign][var] = TF1("f1" + sign + var, "gaus", variable[var]['min'],
                          variable[var]['max'])
    fit1[sign][var].SetParameter(1, fit0[sign][var].GetParameter(1))
    fit1[sign][var].SetParameter(2, fit0[sign][var].GetParameter(2))
    hist[sign][var].Fit(
        "f1" + sign + var, "PWMS", "", fit0[sign][var].GetParameter(1) -
        1.5 * fit0[sign][var].GetParameter(2),
        fit0[sign][var].GetParameter(1) +
        1.5 * fit0[sign][var].GetParameter(2))

    if drawDebugFit:
        fit0[sign][var].SetLineColor(colors[col])
        fit0[sign][var].SetLineWidth(2)
        fit0[sign][var].SetLineStyle(2)
        fit0[sign][var].Draw("L,sames")
        fit1[sign][var].SetLineColor(colors[col])
        fit1[sign][var].SetLineWidth(2)
        fit1[sign][var].SetLineStyle(1)
        fit1[sign][var].Draw("L,sames")
    mean_resolution = fit1[sign][var].GetParameter(1)
    mean_uncertainty = fit1[sign][var].GetParError(1)
    sigma_resolution = fit1[sign][var].GetParameter(2)
    sigma_uncertainty = fit1[sign][var].GetParError(2)

    if variable[var]['log'] and drawDebugFit:
        cv.SetLogy()

    hist[sign][var].SetMaximum(massimo * 1.5)
    if variable[var]['log'] == False:
        hist[sign][var].SetMinimum(minimo * 0.5)

    if drawDebugFit:
        leg.Draw()
        drawCMS(-1, "Preliminary")
        cv.Update()
        cv.Print(PLOTDIR + sign + "_" + var.replace('.', '_') + name +
                 "_eta_" + str(min_eta).replace('.', 'p') + "_" +
                 str(max_eta).replace('.', 'p') + ".pdf")
        cv.Print(PLOTDIR + sign + "_" + var.replace('.', '_') + name +
                 "_eta_" + str(min_eta).replace('.', 'p') + "_" +
                 str(max_eta).replace('.', 'p') + ".png")
        if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
    return mean_resolution, mean_uncertainty, sigma_resolution, sigma_uncertainty, RMS_resolution
Пример #25
0
    print("To generate a kay, go here : https://atlasdqm.cern.ch/dqauth/")
    print("You can also define by hand the data project tag wit hthe option -t")
    sys.exit()
  passfile = open("atlasdqmpass.txt")
  passwd = passfile.read().strip(); passfile.close()
  passurl = 'https://%[email protected]'%passwd
  s = xmlrpclib.ServerProxy(passurl)
  run_spec = {'stream': 'physics_CosmicCalo', 'proc_ver': 1,'source': 'tier0', 'low_run': runNumber, 'high_run':runNumber}
  run_info= s.get_run_information(run_spec)
  if '%d'%runNumber not in run_info.keys() or len(run_info['%d'%runNumber])<2:
    print("Unable to retrieve the data project tag via atlasdqm... Please double check your atlasdqmpass.txt or define it by hand with -t option")
    sys.exit()
  tag = run_info['%d'%runNumber][1]

amiTag = args.amiTag

listOfFiles = pathExtract.returnEosTagPath(runNumber,stream,amiTag,tag)

tree = TChain("POOLCollectionTree")

file = {}
for fileNames in listOfFiles:
  print("Adding %s"%(fileNames))
  tree.AddFile("root://eosatlas/%s"%(fileNames))

entries = tree.GetEntries()
if entries != 0:
  print("The chained tree contains %d entries"%(entries))
else:
  print("Empty chain...")
Пример #26
0
def merge_root_file(target, source_list):
    """
    Merge next file from the source list with the target file.
    Function called recursively for each element of the list.

    :param TFile target: the result ROOT file
    :param TList source_list: list of input files to merge
    """
    logger = get_logger()
    raw_path = target.GetPath()
    path = raw_path[raw_path.find(":") + 1:]

    first_source = source_list.First()
    first_source.cd(path)
    current_source_dir = gDirectory
    # gain time, do not add the objects in the list in memory
    status = TH1.AddDirectoryStatus()
    TH1.AddDirectory(False)

    # loop over all keys in this directory
    #global_chain = TChain()
    next_key = TIter(current_source_dir.GetListOfKeys())
    #key = TKey()
    #TKey old_key = None
    key = next_key()
    while key:
        # keep only the highest cycle number for each key
        #if old_key and not old_key.GetName() == key.GetName():
        #    continue
        # read object from first source file
        first_source.cd(path)
        obj = key.ReadObj()

        if obj.IsA().InheritsFrom(TH1.Class()):
            # descendant of TH1 -> merge it
            logger.info("Merging histogram %s", obj.GetName())
            h1 = TH1(obj)

            # loop over all source files and add the content of the
            # correspondant histogram to the one pointed to by "h1"
            next_source = source_list.After(first_source)
            while next_source:
                # make sure we are at the correct directory level by cd'ing to path
                next_source.cd(path)
                key2 = gDirectory.GetListOfKeys().FindObject(h1.GetName())
                if key2:
                    h2 = TH1(key2.ReadObj())
                    h1.Add(h2)
                    #del h2
                next_source = source_list.After(next_source)

        elif obj.IsA().InheritsFrom(TTree.Class()):
            logger.info("Merging tree %s", obj.GetName())
            # loop over all source files and create a chain of Trees "global_chain"
            obj_name = obj.GetName()
            global_chain = TChain(obj_name)
            global_chain.Add(first_source.GetName())
            next_source = source_list.After(first_source)
            while next_source:
                global_chain.Add(next_source.GetName())
                next_source = source_list.After(next_source)

        elif obj.IsA().InheritsFrom(TDirectory.Class()):
            logger.info("Found subdirectory %s", obj.GetName())
            # create a new subdir of same name and title in the target file
            target.cd()
            new_dir = target.mkdir(obj.GetName(), obj.GetTitle())
            # newdir is now the starting point of another round of merging
            # newdir still knows its depth within the target file via
            # GetPath(), so we can still figure out where we are in the recursion
            merge_root_file(new_dir, source_list)

        else:
            logger.info("Unknown object type, name: %s, title: %s",
                        obj.GetName(), obj.GetTitle())

        # now write the merged histogram (which is "in" obj) to the target file
        # note that this will just store obj in the current directory level,
        # which is not persistent until the complete directory itself is stored
        # by "target.Write()" below
        if obj is not None:
            target.cd()
            # if the object is a tree, it is stored in global_chain...
            if obj.IsA().InheritsFrom(TTree.Class()):
                global_chain.Merge(target.GetFile(), 0, "keep")
            else:
                obj.Write(key.GetName())

        # move to the next element
        key = next_key()

    # save modifications to target file
    target.SaveSelf(True)
    TH1.AddDirectory(status)
    target.Write()
import ROOT, os
from ROOT import TChain, TCanvas, TH1
from Imports import *

subjobs = 101
filedir = pwd + "4_reduced"
filename = "charm_29r2_g.root"
excludedjobs = []

tree = TChain("tuple_Lc2pKpi/DecayTree")

for job in range(1, subjobs):
    if not job in excludedjobs:
        tree.Add("{0}/{1}/output/{2}".format(filedir, job, filename))

c1 = ROOT.TCanvas("c1")

histogram1 = ROOT.TH1F("histogram1", "hist 1", 300, 2240, 2340)
histogram2 = ROOT.TH1F("histogram2", "hist 1", 300, 2240, 2340)
histogram1.SetLineColor(8)
histogram1.SetLineStyle(2)
histogram2.SetLineColor(46)
histogram2.SetLineStyle(2)
masshist_Lc = ROOT.TH1F("masshist_Lc", "Histogram of L_{c} mass", 300, 2240,
                        2340)
masshist_Lc.GetXaxis().SetTitle("M(L_{c}^{+}) [MeV/c^{2}]")
masshist_Lc.GetYaxis().SetTitle("Number of events")

mass = ROOT.RooRealVar("mass", "Mass", 2240, 2340, "MeV/c^{2}")
nbins = 300
varname = "lcplus_MM"
Пример #28
0
def drawMuonWithDict(inBoxPoints,thisev):
  antipoints=[]
  antipoints.append(geo.getNewPos(thisev['StartPointx_tpcFV'], thisev['StartPointy_tpcFV'], thisev['StartPointz_tpcFV'],thisev['theta'],thisev['phi'],700))
  antipoints.append((thisev['StartPointx_tpcFV'], thisev['StartPointy_tpcFV'], thisev['StartPointz_tpcFV']))
  #print antipoints
  geo.drawValidPoints(antipoints)


def drawShowers(ne):
  global anatree
  nepoints=((anatree.StartPointx[ne], anatree.StartPointy[ne], anatree.StartPointz[ne]),(anatree.EndPointx[ne], anatree.EndPointy[ne], anatree.EndPointz[ne]))
  #print nepoints
  geo.drawValidPoints(nepoints,2)


anatree=TChain('analysistree/anatree')
anatree.Add(file)
entries=anatree.GetEntries()
anatree.SetBranchStatus("*",0)
for b in ("StartPointx", "StartPointy", "StartPointz","EndPointx", "EndPointy", "EndPointz", "StartPointx_tpcAV", "StartPointy_tpcAV", "StartPointz_tpcAV","pdg","TrackId","Mother","processname"):
  anatree.SetBranchStatus(b,1)

#tree to store nue-like bgs in
nueliketree=flatttree("nuelikes",["jentry/I","ngeant/I","pdg/I", "Mother/I", "TrackId/I", "iscomp/I", "isconv/I","Eng/F", "Mother_ngeant/I", "Mother_pdg/I", "Mother_Eng/F", "Primary_ngeant/I", "Primary_pdg/I", "Primary_Eng/F","muon_inTPCActive/I","muon_inMTG/I","StartPointx_tpcAV/F", "StartPointy_tpcAV/F", "StartPointz_tpcAV/F"])

print "Total anatree entries: ", entries
anatree.GetEntry(anatree.GetEntries()-1)
print "Total muonslist entries: ", len(muonslist)


#draw boxes
Пример #29
0
parser.add_argument('-r',
                    '--reco-tree',
                    default='reco',
                    type=str,
                    help="Reco tree name")
parser.add_argument('-t',
                    '--truth-tree',
                    default='parton',
                    choices=['particle', 'parton'],
                    help="Truth tree name")

args = parser.parse_args()

print("Read trees from", args.inputfiles)

tree_reco = TChain(args.reco_tree)
for infile in args.inputfiles:
    tree_reco.Add(infile)

tree_truth = TChain(args.truth_tree)
for infile in args.inputfiles:
    tree_truth.Add(infile)

# make them friends!
tree_reco.AddFriend(tree_truth)

branches_reco = {}
branches_truth = {}
cuts = "isMatched"

if args.truth_tree == 'parton':
Пример #30
0
signalHistList = []

if len(files) == 2:
    colors = [632, 600]
else:
    colors = [636, 635, 634, 633, 632, 807, 802, 801, 800, 798]

if addBackground:
    colors.append(600)

for f, fileDict in enumerate(files):
    filename = fileDict['file']
    massPoint = fileDict['massPoint']
    print('Now considering mass point... ' + massPoint)

    signalChain = TChain("Events")
    for actualFile in fnmatch.filter(os.listdir(signalDir),
                                     'nanoLatino*' + filename + '*'):
        signalChain.AddFile(signalDir + actualFile)

    histname = 'hist_' + str(f)
    signalHist = TH1F(histname, 'Mass points distribution', variable[1],
                      variable[2], variable[3])

    signalChain.Draw(variable[0] + ' >> ' + histname, cuts)
    signalHist.SetDirectory(0)
    if normalization:
        signalHist.Scale(1. /
                         signalHist.Integral())  #Normalize the histo to unity
    signalHist.SetStats(0)
    signalHist.SetLineColor(colors[f])
Пример #31
0
print 'NEW FOLDER: ' + newfolder
print 'OLD WEIGHT "' + oweight + '"  - NEW WEIGHT "' + nweight

print '\n{:>40}'.format(' Ntuple name          ') + '{:>16}'.format(
    'Difference') + '{:>17}'.format('Old yield'),
print '{:>17}'.format('New yield') + '{:>17}'.format(
    'Old entries') + '{:>17}'.format('New entries')
print '=' * 128
not_in_old = list()
not_in_new = list()
rows = list()
line = 1
histo = TH1D("histo", "", 10, 0, 10)
for ifile in sortedfiles:
    if ("TTJets_HT" not in ifile): continue
    ochain = TChain("tree")
    oldntuples = oldfolder + "/*" + ifile + '*root'
    no = ochain.Add(oldntuples)
    if no == 0:
        not_in_old.append(ifile)
        continue
    nchain = TChain("tree")
    newntuples = newfolder + "/*" + ifile + '*root'
    nn = nchain.Add(newntuples)
    if nn == 0:
        not_in_new.append(ifile)
        continue

    no = ochain.Draw("1>>histo", oweight, "goff")
    oldtot = histo.Integral()
    nn = nchain.Draw("1>>histo", nweight, "goff")
Пример #32
0
from ROOT import TFile, TTree, TChain, TH1F
import time

# specify the tree/tuple name of interest
c1 = TChain('tree44')
c2 = TChain('tree44')

# add root file to the chain
# after defining(by adding trees to it) the tchain behaves like a ttree object(Draw() can be used etc.)
c1.Add('f1.root')
c2.Add('f2.root')

# histogram with 100 bins x axis runs from -10 to 10
h1 = TH1F('h1', 'Title of the h1', 100, -10, 10)

# set uncertainty of the histogram
# this should be done right after the histogram has been defined
h1.Sumw2()

##########################
# test weighting of hist #
##########################
"""
# specify in the first entry what variable you want to plot(in our case: v0)
# by '>>' we tell the tchain to project the tree to the histogram 
# the last entry specifies the weight of the events from this variable
c1.Draw('v0 >> h1','0.2')

# pause the program to be able to see the plot
#time.sleep(3)
#c2.Draw('l3    >> h1','0.4')
Пример #33
0
    if not jobid in job_files:
        job_files[jobid]=[]
    job_files[jobid].append('%s/%s' % (TARGET_DIR,f))

bad_files={}
good_files={}
for jobid,files in job_files.iteritems():

    if not len(files) == len(flavors):
        print 'JobID %d missing files (%d/%d)' % (jobid,len(files),len(flavors))
        bad_files[jobid]=files
        continue

    good=True
    for f in files:
        ch=TChain("larlite_id_tree")
        ch.AddFile(f)
        if ch.GetEntries() > 0: continue
        good=False
        break

    if not good:
        print 'JobID %d has corrupted file(s)!' % jobid
        bad_files[jobid]=files
    else:
        good_files[jobid]=files

print 'Found',len(bad_files),'bad jobs'
print bad_files.keys()
print