コード例 #1
0
def make_ntup(file_name, tree_name, branches, outfile, n_events,
              new_tree_name):
    if new_tree_name == "":
        new_tree_name = tree_name

    print file_name

    # Get the event tree
    tree = TChain(tree_name)
    tree.Add(file_name)
    if not tree:
        print "Error: No tree named %s in %s" % (tree_name, file_name)
        sys.exit()

    # Check branches exist
    branches_avail = [x.GetName() for x in tree.GetListOfBranches()]
    for b in branches:
        if not b in branches_avail:
            print "Error branch '%s' not a branch in input tree" % (b)
            print "Branches available are: \n"
            print "\t".join(branches_avail)
            sys.exit()

    # output
    out_file = TFile(outfile, "RECREATE")
    nt = TNtuple(new_tree_name, "", ":".join(branches))

    if (n_events < 0):
        n_events = tree.GetEntries()

    # loop over events and fill the branches of new ntuple
    for index, entry in enumerate(tree):
        if index > n_events:
            break
        vals = array('f', [entry.__getattr__(b) for b in branches])
        nt.Fill(vals)

        if (index % 100000 == 0):
            print index, "/", n_events
    # Save
    out_file.cd()
    nt.Write()
    out_file.Close()

    print "Written %i entries of branch(es) '%s' \nto tree %s  \nin file %s" % (
        n_events, ":".join(branches), new_tree_name, outfile)
コード例 #2
0
ファイル: Optimisation.py プロジェクト: gitter-badger/zfit
def FillNTuple(tupname, data, names) : 
  """
    Create and fill ROOT NTuple with the data sample. 
      tupname : name of the NTuple
      data : data sample
      names : names of the NTuple variables
  """
  variables = ""
  for n in names : variables += "%s:" % n
  variables = variables[:-1]
  values = len(names)*[ 0. ]
  avalues = array.array('f', values)
  nt = TNtuple(tupname, "", variables)
  for d in data : 
    for i in range(len(names)) : avalues[i] = d[i]
    nt.Fill(avalues)
  nt.Write()
コード例 #3
0
def LeCroy2Root(directory, outputRootFile):
    masterFile = TFile(outputRootFile, "recreate")

    print("listing files...")
    filesPerChannel = listFilesPerChannel(directory)
    ## se rellena el ultimo canal en 0:
    print len(filesPerChannel)
    nMC = len(
        filesPerChannel[0])  # number of available measurement per channel

    for i in range(4 - len(filesPerChannel)):
        filesPerChannel.append([0] * nMC)

    #### Get time from CHANNEL n #######################
    TimeNch = 1
    ########################################

    nMC = len(
        filesPerChannel[0])  # number of available measurement per channel

    # formar la tupla con las columnas necesarias:
    # measuresLabels = "event:time:C1:C2:C3:C4"
    measuresLabels = "event:time:C1:C2:C3"

    tup = TNtuple("osc", "LeCroy Readings", measuresLabels)

    readingGroup = []

    print("loading data..." + str(nMC))

    # para cada frame
    for i in range(nMC):
        # obtener cada canal
        for j in range(len(filesPerChannel)):
            if (filesPerChannel[j][i] == 0):
                readingGroup.append([])
#               print "channel: " + str(j) + " empty"
            else:
                #               print "channel: " + str(j) + " ok"
                #               print directory+filesPerChannel[j][i]
                readingGroup.append(readTrc(directory + filesPerChannel[j][i]))

        largos = []
        for j in range(len(readingGroup)):
            if (not (len(readingGroup[j]) in largos)):
                if (len(readingGroup[j]) != 0):
                    largos.append(len(readingGroup[j][0]))
        n_data = max(largos)
        for j in range(len(readingGroup)):
            if (len(readingGroup[j]) == 0):
                x_data = [0] * n_data
                y_data = [0] * n_data
                d_data = [0] * n_data
                readingGroup[j] = [x_data, y_data, d_data]

        # luego, generar listas a cargar a la tupla
        event = i
        for [time, c1, c2,
             c3] in zip(readingGroup[TimeNch - 1][0], readingGroup[0][1],
                        readingGroup[1][1], readingGroup[2][1]):
            tup.Fill(event, time, c1, c2, c3)


#        for [time,c1,c2,c3,c4] in zip(readingGroup[TimeNch-1][0], readingGroup[0][1], readingGroup[1][1], readingGroup[2][1], readingGroup[3][1]):	tup.Fill(event,time,c1,c2,c3,c4)

#        for [time,c1] in zip(readingGroup[0][0], readingGroup[0][1]):
#            tup.Fill(event,time,c1)

#        for [time,c2,c3] in zip(readingGroup[0][0], readingGroup[0][1], ):
#            tup.Fill(event,time,c2,c3)

        readingGroup = []
        if (int((float(i * 100) / nMC) * 100) % 100 == 0):
            sys.stdout.write(str(float(i * 100) / nMC) + "%" + "\r")
            sys.stdout.flush()

    tup.Write("", tup.kOverwrite)
    masterFile.Close()
    sys.stdout.write("\n")
コード例 #4
0
                        varNames[0]]['step'][iPt] / 2
                    maxVar1 = cutVars[varNames[1]]['max'][iPt] + cutVars[
                        varNames[1]]['step'][iPt] / 2
                    hFrame = cEstimVsCut[counter].cd(iPad + 1).DrawFrame(
                        minVar0, minVar1, maxVar0, maxVar1,
                        f';{varNames[0]};{varNames[1]};{estNames[est]}')
                    if 'Eff' in est:
                        cEstimVsCut[counter].cd(iPad + 1).SetLogz()
                        hFrame.GetZaxis().SetMoreLogLabels()
                    hFrame.GetXaxis().SetNdivisions(505)
                    hFrame.GetYaxis().SetNdivisions(505)
                    hFrame.GetXaxis().SetDecimals()
                    hFrame.GetYaxis().SetDecimals()
                    hEstimVsCut[iPt][est].DrawCopy('colzsame')
                    outDirPlotsPt[iPt].cd(
                        f'{ParCutsName}{ParCutMin}-{ParCutMax}')
                    hEstimVsCut[iPt][est].Write()
            cEstimVsCut[counter].Update()
            cEstimVsCut[counter].Modified()
            outDirPlotsPt[iPt].cd(f'{ParCutsName}{ParCutMin}-{ParCutMax}')
            cEstimVsCut[counter].Write()

            cEstimVsCut[counter].Print(f'scan_pT{ptMin}_{ptMax}.pdf', 'pdf')
        counter += 1
outFile.cd()
tSignif.Write()
outFile.Close()

if not args.batch:
    input('Press enter to exit')
コード例 #5
0
class SimpleJetNTupler(Analyzer):
    '''dump very few quantities into a TNtuple for jet resolution studies.'''

    ### def __init__(self,cfg_ana, cfg_comp, looperName):
    ###     loadLibs()
    ###     super (SimpleJetNTupler, self).__init__(cfg_ana, cfg_comp, looperName)

    def declareHandles(self):
        super(SimpleJetNTupler, self).declareHandles()
        self.handles['jets'] = AutoHandle(*self.cfg_ana.jetCollection)
        if self.cfg_ana.useGenLeptons:
            self.mchandles['genParticlesPruned'] = AutoHandle(
                'genParticlesPruned', 'std::vector<reco::GenParticle>')
        else:
            self.mchandles['genParticles'] = AutoHandle(
                'prunedGen', 'std::vector<reco::GenParticle>')

        self.mchandles['genJets'] = AutoHandle(*self.cfg_ana.genJetsCollection)
        self.handles['vertices'] = AutoHandle('offlinePrimaryVertices',
                                              'std::vector<reco::Vertex>')

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def beginLoop(self):
        super(SimpleJetNTupler, self).beginLoop()
        self.file = TFile('/'.join([self.looperName, 'testJetsNT.root']),
                          'recreate')
        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor
            self.isPFLooseFunc = PFJetIDSelectionFunctor(
                0, PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind nor PFJetIDSelectionFunctor(Jet)PFJetIDSelectionFunctor.getBitsTemplates
            from ROOT import pat
            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF", "NHF", "CEF", "NEF", "NCH", "nConstituents":
                self.isPFLooseFunc.bits.push_back(i)
            ## /Workaround
            self.isPFLoose = lambda x: self.isPFLooseFunc(
                x, self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x: True

        self.myntuple = TNtuple(
            self.cfg_ana.ntupleName, self.cfg_ana.ntupleName,
            'genPt:recoPt:genEta:recoEta:genPhi:recoPhi:nvtx')

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def process(self, iEvent, event):
        #read all the handles defined beforehand
        self.readCollections(iEvent)

        jetEtaCut = 4.5

        # get the vertexes
        event.vertices = self.handles['vertices'].product()
        #        self.h_nvtx.Fill (len (event.vertices))

        # get the jets in the jets variable
        jets = self.handles['jets'].product()
        # filter jets with some selections
        event.jets = [
            jet for jet in jets
            if (abs(jet.eta()) < jetEtaCut and jet.pt() > self.cfg_ana.ptCut
                and self.isPFLoose(jet))
        ]

        # get status 2 leptons
        if 'genParticlesPruned' in self.mchandles:
            event.genLeptons = [
                lep for lep in self.mchandles['genParticlesPruned'].product()
                if lep.status() == 2 and (abs(lep.pdgId()) == 11 or abs(
                    lep.pdgId()) == 13 or abs(lep.pdgId()) == 15)
            ]
        else:
            event.genLeptons = [
                lep for lep in self.mchandles['genParticles'].product()
                if lep.status() == 3 and (abs(lep.pdgId()) == 11 or abs(
                    lep.pdgId()) == 13 or abs(lep.pdgId()) == 15)
            ]
# @ Pasquale: why level 3 and not level 2?
#        event.selGenLeptons = [GenParticle (lep) for lep in event.genLeptons if (lep.pt ()>self.cfg_ana.ptCut and abs (lep.eta ()) < jetEtaCut)]

# get genJets
        event.genJets = map(GenJet, self.mchandles['genJets'].product())
        # filter genjets as for reco jets
        event.selGenJets = [
            GenJet(jet) for jet in event.genJets
            if (jet.pt() > self.cfg_ana.genPtCut)
        ]

        #FIXME why are there cases in which there's 4 or 6 leptons?
        if len(event.genLeptons) != 2:
            return
        # in case I want to filter out taus
        # 11, 13, 15 : e, u, T
#        event.genOneLepton = [GenParticle (part) for part in event.genLeptons if abs (part.pdgId ()) == 15]
# remove leptons from jets if closer than 0.2
        event.cleanJets = cleanObjectCollection(event.jets, event.genLeptons,
                                                0.2)
        event.matchingCleanJets = matchObjectCollection2(
            event.cleanJets, event.selGenJets, 0.25)
        # assign to each jet its gen match (easy life :))
        for jet in event.cleanJets:
            jet.gen = event.matchingCleanJets[jet]

        event.matchedCleanJets = [
            jet for jet in event.matchingCleanJets if jet.gen != None
        ]
        for jet in event.matchedCleanJets:
            self.myntuple.Fill(jet.gen.pt(), jet.pt(), jet.gen.eta(),
                               jet.eta(), jet.gen.phi(), jet.phi(),
                               len(event.vertices))

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def write(self):
        from ROOT import gROOT
        gROOT.SetBatch(True)
        self.file.cd()
        self.myntuple.Write()
        self.file.Close()
コード例 #6
0
Nbin = (len(lineList))  # get number of bins
Line_string = str(lineList[0])
bin_init, _, _ = Line_string.split()
bin_init = float(bin_init)  # get initial bin
Line_string = str(lineList[len(lineList) - 1])
_, bin_final, _ = Line_string.split()
bin_final = float(bin_final)  # get final bin
f.seek(0)  # reset python read line

hist = TH1D("h1f", "h1f", Nbin, bin_init, bin_final)
ntuple = TNtuple("ntuple", "ntuple", "low_bin:high_bin:bin_contents")
total_e = 0
for i in range(1, Nbin + 1):
    Line_string = str(f.readline())
    ss, ff, bin_c = Line_string.split()
    ss = float(ss)
    ff = float(ff)
    bin_c = float(bin_c)
    hist.SetBinContent(i, bin_c)
    total_e = total_e + bin_c
    ntuple.Fill(ss, ff, bin_c)
#gStyle.SetOptStat()
hist.Draw()
gPad.Update()
can.Update()

wf = TFile("root_ntuple_from_txt.root", "RECREATE")
hist.Write()
ntuple.Write()
wf.Close()