Exemple #1
0
 def setUp(self):
     super(TestOps, self).setUp()
     h1 = TH1I("h1", "", 2, .5, 4.5)
     h1.Fill(1, 4)
     self.wrp1 = HistoWrapper(h1, lumi=2., history="wrp1")
     h2 = TH1I("h2", "", 2, .5, 4.5)
     h2.Fill(1, 3)
     h2.Fill(3, 6)
     self.wrp2 = HistoWrapper(h2, lumi=3., history="wrp2")
def malujWykresyOdchylen(ileKanalow):
    wykresKoncowyNar = TH1I("Odchylenia standardowe (zb. narastajace)",
                            "Wykres odchylen standardowych", ileKanalow - 1, 0,
                            ileKanalow - 2)
    wykresKoncowyOp = TH1I("Odchylenia standardowe (zb. opadajace)",
                           "Wykres odchylen standardowych", ileKanalow - 1, 0,
                           ileKanalow - 2)
    #wypełnianie wykresu zbiorczego odchyleń dla zbocz opadających
    wypelnijWykresZbiorczy(wykresKoncowyOp, ileKanalow, sigmy, 0)
    #wypełnianie wykresu zbiorczego odchyleń dla zbocz narastających
    wypelnijWykresZbiorczy(wykresKoncowyNar, ileKanalow, sigmy, 1)
    #malowanie wykresu zbiorczego odchyleń dla zbocz narastających
    malowanieWykresuZbiorczego(wykresKoncowyNar, "narastajace", czas)
    #malowanie wykresu zbiorczego odchyleń dla zbocz opadających
    malowanieWykresuZbiorczego(wykresKoncowyOp, "opadajace", czas)
Exemple #3
0
def leggi_hist(file_name):
    hist = TH1I(file_name, file_name, bins, 0, bins)
    with open(file_name) as file:
        for i, line in enumerate(file):
            line = float(line)
            hist.SetBinContent(i + 1, line)
    return hist
Exemple #4
0
def load_hist_from_file(file_name):
    histogram = TH1I(file_name, file_name, N_BINS, 0, N_BINS)
    with open(file_name) as file:
        for i, line in enumerate(file):
            line = line.split()[0]
            line = float(line)
            histogram.SetBinContent(i + 1, line)
    return histogram
Exemple #5
0
def stworzZmiennaWykresowa(katalog, kanal1, kanal2, jaka, pojemnik):
    nazwaKr = " op." if jaka == 0 else " nar."
    nazwaDl = "opadajace" if jaka == 0 else "narastajace"
    wykr = TH1I(("Wykres " + str(kanal1) + "-" + str(kanal2) + nazwaKr),
                ("Roznica miedzy kanalami " + str(kanal1) + " a " +
                 str(kanal2) + " (zbocze " + nazwaDl + ")"), 1055, -527, 527)
    wykr.SetDirectory(katalog)
    pojemnik.ustawWykres(jaka, kanal1, kanal2, wykr)
Exemple #6
0
    def beginLoop(self, setup):
        super(TreeProducer, self).beginLoop(setup)
        self.rootfile = TFile('/'.join([self.dirName, 'tree.root']),
                              'recreate')

        bins = array("f", self.cfg_ana.thresholds)
        self.histogram = TH1I(
            "numberOfEvents_VS_JetPt",
            "Number of events vs jet minimum transverse momentum",
            len(bins) - 1, bins)
def stworzZmiennaWykresowa(katalog, ktora, jaka, pojemnik):
    nazwaKr = " op." if jaka == 0 else " nar."
    nazwaDl = "opadajace" if jaka == 0 else "narastajace"
    pojemnik = pojemnik + [
        TH1I(("Wykres " + str(ktora + 1) + nazwaKr),
             ("Roznica miedzy kanalem " + str(ktora) + " a " + str(ktora + 1) +
              " (zbocze " + nazwaDl + ")"), 1023, -511, 511)
    ]
    pojemnik[2 * ktora + jaka].SetDirectory(katalog)
    return pojemnik
Exemple #8
0
 def draw_energy(self):
     #draw histogram with integrals (energy)
     #integr_output = TFile(self.name + "_integr.root", "recreate")
     #integr_output.cd()
     self.integral_canvas = TCanvas("integral_canvas" + self.name,
             "integral")
     self.integral_hist = TH1I("integral_hist" + self.name,
             "Integral " + self.name,
             150, 5000, 7000) 
     self.ntuple.Draw("integr>>integral_hist" + self.name)
     #self.integral_hist.Write()
     self.integral_hist.SaveAs(self.name + "_integr.root")
    def setUp(self):
        super(TestHistoToolsBase, self).setUp()

        test_fs = "fileservice/"
        settings.DIR_FILESERVICE = test_fs
        if (not os.path.exists(test_fs + "tt.root")) \
        or (not os.path.exists(test_fs + "ttgamma.root")) \
        or (not os.path.exists(test_fs + "ttgamma.root")):
            self.fail("Fileservice testfiles not present!")

        # create samples
        settings.samples["tt"] = sample.Sample(
            name = "tt",
            is_data = True,
            lumi = 3.,
            legend = "pseudo data",
            input_files = "none",
        )
        settings.samples["ttgamma"] = sample.Sample(
            name = "ttgamma",
            lumi = 4.,
            legend = "tt gamma",
            input_files = "none",
        )
        settings.samples["zjets"] = sample.Sample(
            name = "zjets",
            lumi = 0.1,
            legend = "z jets",
            input_files = "none",
        )
        settings.colors = {
            "tt gamma": kRed,
            "z jets": kBlue
        }
        settings.stacking_order = [
            "tt gamma",
            "z jets"
        ]
        settings.active_samples = settings.samples.keys()

        #create a test wrapper
        h1 = TH1I("h1", "H1", 2, .5, 4.5)
        h1.Fill(1)
        h1.Fill(3,2)
        hist = History("test_op") # create some fake history
        hist.add_args([History("fake_input_A"), History("fake_input_B")])
        hist.add_kws({"john":"cleese"})
        self.test_wrp = HistoWrapper(
            h1,
            name="Nam3",
            title="T1tl3",
            history=hist
        )
def Rebin(h, name, newbinwidth, xlow):
    import random
    from ROOT import TH1I, TRandom
    binwidth = h.GetBinWidth(1)
    nbins = h.GetNbinsX()
    xup = h.GetXaxis().GetBinUpEdge(nbins)
    L = xup - xlow
    if (L % newbinwidth == 0):
        newnbin = int(L / newbinwidth)
        h2 = TH1I(name, "", newnbin, xlow, xup)
    if (L % newbinwidth > 0):
        newnbin = int(L / newbinwidth) + 1
        newxup = xup + newbinwidth
        h2 = TH1I(name, "", newnbin, xlow, newxup)

    #seed = random.randint(0, 500)
    seed = 123
    ran = TRandom(seed)
    for i in range(1, nbins + 1):
        for j in range(1, int(h.GetBinContent(i)) + 1):
            h2.Fill(
                ran.Uniform(h.GetBinLowEdge(i),
                            h.GetXaxis().GetBinUpEdge(i)))
    return h2
Exemple #11
0
 def draw_event_size(self, fit=True, show=True):
     h = TH1I('h_es', 'Event Size', 100, 0, 100)
     self.Tree.Draw('@plane.size()>>h_es', '', 'goff')
     f = None
     if fit:
         set_root_output(False)
         set_statbox(only_fit=True, entries=1.5, w=.2)
         f = TF1('fit', '[0]*TMath::Poisson(x, [1])', 0, 100)
         f.SetParameters(1e7, 5)
         f.SetParNames('Constant', 'Event Rate #lambda')
         h.SetName('Fit Result')
         h.Fit(f, 'q')
     x_range = [h.FindFirstBinAbove(0) - 3, h.FindLastBinAbove(0) + 3]
     format_histo(h, x_tit='Number of Hits per Event', y_tit='Number of Entries', y_off=1.6, x_range=x_range)
     self.Drawer.draw_histo(h, show=show, lm=.14)
     return h if not fit else f.GetParameter(1)
def AddFWHM(h, name, modelpars, mflags=[True, True, True]):
    import random
    from ROOT import TH1I, TRandom
    #seed = random.randint(0, 500)
    seed = 123
    ran = TRandom(seed)
    nbins = h.GetNbinsX()
    hout = TH1I(name, '', nbins, h.GetBinLowEdge(1),
                h.GetXaxis().GetBinUpEdge(nbins))
    for i in range(1, nbins + 1):
        for j in range(1, int(h.GetBinContent(i)) + 1):
            hout.Fill(
                ran.Gaus(
                    h.GetBinCenter(i),
                    FWHM(h.GetBinCenter(i), modelpars, mflags=mflags) / 2.35))
    return hout
def main():
    parser = ArgumentParser(description='Calculate the average event rate '+ \
                            'of specific lumisections in specific files.')
    parser.add_argument('-b', action='store_true', help='enable batch mode')
    parser.add_argument('--dataset', required=True, choices=['PromptReco2015', \
                        'ReRecoOct2015', 'ReRecoDec2015', 'PromptReco2016', \
                        '2015ReRecoJan2017', '2016ReRecoJan2017'], \
                        help='specify data-taking period and reconstruction')
    parser.add_argument('-dir', nargs=2, type=int, help='Specify a range in '+ \
                        'directories')
    parser.add_argument('-ls', nargs=2, type=int, help='Specify a range '+ \
                        'in lumisections')
    parser.add_argument('-files', nargs=2, type=int, help='Specify a range '+ \
                        'in file numbers')
    parser.add_argument('-run', nargs=1, required=True, type=int, \
                        help='Specify the run number for the selection of '+ \
                        'the lumisections')
    args = parser.parse_args()

    from importlib import import_module
    from lsctools import config
    from lsctools.config import options as O, EOSPATH as eos
    from os import listdir
    from ROOT import TChain, TH1I
    getattr(config, 'PCC'+args.dataset)()
    chain = TChain(O['treename']['minitrees'])
    for directory in O['minitrees'][args.dir[0]-1:args.dir[1]]:
        print '<<< Enter directory', directory
        for filename in listdir(eos+directory+'/'):
            for i in range(args.files[0], args.files[1]+1):
                if not filename.endswith(str(i)+'.root'):
                    continue
                chain.Add(eos+directory+'/'+filename)
    histo = TH1I('hist', '', 1001, -0.5, 1000.5)
    cond = 'run == ' + str(args.run[0]) + ' && LS >= ' + str(args.ls[0]) + \
           ' && LS <= ' + str(args.ls[1])
    chain.Draw('nCluster>>hist', cond, 'goff')
    print histo.GetMean(), '+-', histo.GetMeanError()
Exemple #14
0
coarse = -1.
rising = -1.
diff = int()

fineAll = [-1]

f = ROOT.TFile.Open("dabc_[18201172953].root")
myTree = f.Get("FTAB_Timeslots")
Nentries = myTree.GetEntries()
#Nentries = 100000
bar = progressbar.ProgressBar(maxval=Nentries, widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
barIter=0
bar.start()

#for ch_indx in range (0,40):
respad = TH1I( 'pad2', 'Res', 510, -255, 255 )
barIter=0
#print "ChIndx:", ch_indx
for entry in myTree:
    if barIter == 1000:#Nentries:#10000:
        break
    barIter = barIter + 1
    bar.update(barIter)
    # Now you have acess to the leaves/branches of each entry in the tree, e.g.
    
    for idx, val in enumerate(myTree.FTAB_Fine):  
        #print "idx ", idx, "val", val      
        #print "coarse",  myTree.FTAB_Coarse[idx]        
        #print "fine",  myTree.FTAB_Fine[idx]
        #print "channel",  myTree.FTAB_Channel[idx]
        #print "rising",  myTree.FTAB_Rising[idx]
def SaveInTH1(ch_sim, counts_sim, name, nbins, xlow, xup):
    from ROOT import TH1I
    h = TH1I(name, '', nbins, xlow, xup)
    for i in range(len(ch_sim)):
        h.SetBinContent(h.FindBin(ch_sim[i]), counts_sim[i])
    return h
#########################################################################
## Plot evolution vs LB
leg = TLegend(0.52, 0.90 - 0.05 * len(histoKeys), 0.98, 0.95)
leg.SetHeader("Run %d" % runNumber)

if (upperLB >= lowerLB):  # check that at least one noisy LB was found
    c0 = TCanvas()
    gStyle.SetOptStat("")
    if histoType != "2d_xyHotSpot":
        c0.SetLogy(1)
    h0Evol = {}
    first = True
    for iHisto in histoKeys:
        h0Evol[iHisto] = TH1I("h0Evol%s" % (iHisto), summaryTitle,
                              upperLB - lowerLB + 1, lowerLB - 0.5,
                              upperLB + 0.5)
        h0Evol[iHisto].SetXTitle("LumiBlock (Only LB with >= %.0f entries)" %
                                 (minInLB))
        h0Evol[iHisto].SetLineColor(histoColor[iHisto])
        h0Evol[iHisto].SetMarkerColor(histoColor[iHisto])
        h0Evol[iHisto].SetMarkerStyle(20)
        leg.AddEntry(
            h0Evol[iHisto], "%s (%d entries in the run)" %
            (histoLegend[iHisto], totalInRegion[iHisto]))
        for i in range(lowerLB, upperLB + 1):
            h0Evol[iHisto].Fill(i, nbHitInHot[iHisto][i])
        if first:
            h0Evol[iHisto].Draw("P HIST")
            if histoType != "2d_xyHotSpot":
                h0Evol[iHisto].SetMinimum(minInLB - 0.8)
Exemple #17
0
def run_analysis(options,args):    
    tm = tree_manager()
    pu_weight_sum = 0.0
    selected_events = []
    metaInfoTrees = []
    nEvents_total = int(0)
    pwd = ROOT.gDirectory.GetPath()
    for kFile,input_file in enumerate(args):
        print
        print 'processing input file %i/%i: %s'%(kFile+1,
                                                 len(args),
                                                 input_file)
        in_file = TFile.Open(input_file,'read')
        ROOT.gDirectory.cd(pwd)
        
        leptonType = options.leptonType    
        
        tree = None
        nEvents_sample = 0    
        specific = None
        treeName = 'Ntuple'
        if not options.allBranches:    
            if leptonType == 'muon':                
                #specific = muonBranches+commonBranches
                mmg = in_file.Get('mmg')
                tree = mmg.Get('final').Get(treeName)
                metaInfoTrees.append(mmg.Get('metaInfo').CloneTree())
                nEvents_sample = mmg.Get('eventCount').GetBinContent(1)
                nEvents_total += mmg.Get('skimCounter').GetBinContent(1)
                mmg = None
            elif leptonType == 'electron':                 
                #specific = electronBranches+commonBranches
                eeg = in_file.Get('eeg')
                tree = eeg.Get('final').Get(treeName)
                metaInfoTrees.append(eeg.Get('metaInfo').CloneTree())
                nEvents_sample = eeg.Get('eventCount').GetBinContent(1)
                nEvents_total += eeg.Get('skimCounter').GetBinContent(1)
                eeg = None
            else:             
                raise Exception('invalid lepton type: %s'%options.leptonType)
                
        total_events = tree.GetEntriesFast()    
        tick_size = total_events/100.0
        if tick_size < 1: tick_size = 1.0
        
        #tm.importTree(treeName,tree,specific)

        
        #tm.cloneTree(treeName,'%s_zs'%treeName,specific)
        #tm.cloneTree(treeName,'%s_zgs'%treeName,specific)
        #tm.cloneTree(treeName,'%s_zgs_nosihih'%treeName,specific)
        
        #setup process dependent stuff
        cuts = setupCuts(options)
        #lepton_mass = lepton_masses[options.leptonType]
        #z_info = z_infos[options.leptonType]
        #lepton_info = lepton_infos[options.leptonType]

        #setup pu-reweighing
        #pu_weight = pu_weight_nominal 
        #if options.isSummer11:
        #    pu_weigt = pu_weight_summer11
        
        procWeight = 1.0
        if options.datType != 'data':
            procWeight = (options.crossSection *
                          run_lumi[options.leptonType][options.runYear]\
                                  [options.runType])

        # setup the corrector (this links the appropriate four momenta
        # into a common naming scheme
        correct = setup_corrections(options.runYear   , options.runType,
                                    options.leptonType, options.datType,
                                    options.leptonCor , options.gamCor,
                                    options.vanilla                       )
        
        ievent = long(0)        
        for event in tree:
            ievent+=1
            #print ievent,total_events,fmod(ievent/total_events,0.01)
            if( not (ievent+1)%int(tick_size) or
                ievent+1 == total_events ):  
                sys.stdout.write('\r%3.0f%s complete! (%i/%i)'%(((ievent+1)/
                                                                 tick_size),
                                                                '%',
                                                                ievent+1,
                                                                total_events))
                sys.stdout.flush()
            
            # setup the common event momentum
            # ell1 = lepton1, ell2 = lepton2
            # gam = photon, Z = dilepton, Zg = Z+photon        
            correct(event)
            
            run_idx = getRunIndex(event.run[0],options.runYear,
                                  options.runType,options.datType,
                                  options.leptonType)
            setattr(event,'procWeight',procWeight)
            setattr(event,'puWeight',1.0)
            if options.datType != 'data':            
                setattr(event,'eventFraction',float(ievent+1)/total_events)
                event.puWeight = pu_S10_CD_reweight(event.nTruePU[0])
                
            #selected_z = []
            #selected_pho_nosihih = []
            #selected_pho = []        
            #bad_leptons = []
            
            if options.datType == 'data':
                # kill run 170722
                # kill the obvious pile up combinatorial event
                if ( event.run[0] == 170722 or
                     (event.run[0]   == 166512 and
                      event.lumi[0] == 1678 and
                      event.evt[0] == 1822682238) ):
                    continue
        
            bestLLG = None
            bestZdiff = -1
            
            for i in range(event.N_PATFinalState):            

                cuts.getCutflow('trigger')(event,i)
                if options.exlProc and not cuts.getCutflow('trigger') :
                    continue        
            
                cuts.getCutflow('pho')(event,i)            
                cuts.getCutflow('leptons')(event,i) 
                if ( options.exlProc and
                     not cuts.getCutflow('leptons') and
                     not cuts.getCutflow('pho') ):
                    continue

                cuts.getCutflow('z')(event,i)
                if options.exlProc and not cuts.getCutflow('z'):
                    continue

                if ( cuts.getCutflow('trigger') and
                     cuts.getCutflow('leptons') and
                     cuts.getCutflow('pho') and
                     cuts.getCutflow('z') ):
                    thisZdiff = abs(Z_POLE-event.Z[i].M())
                    if( cuts.getCut('mindr')[0](event.ell1[i],
                                                event.ell2[i],
                                                event.gam[i]) and
                        (thisZdiff < bestZdiff or bestLLG is None) ):
                        bestZdiff = thisZdiff
                        bestLLG = i
                    
            #event object selection done        
            if options.exlProc and bestLLG is None:
                continue
             
            bestZ = bestLLG
        
            if bestLLG is not None:
                setattr(event,'ell1SF',1.0)
                setattr(event,'ell2SF',1.0)
                #if run_idx != -1:
                #    event.ell1SF = leptonSF_nominal(event.nGoodVtx,
                #                     getattr(event,lepton_info['pt'])[idx1],
                #                    getattr(event,lepton_info['eta'])[idx1],
                #                                    run_idx,
                #                                    options.leptonType)
                #    event.ell2SF = leptonSF_nominal(event.nGoodVtx,
                #                      getattr(event,lepton_info['pt'])[idx2],
                #                     getattr(event,lepton_info['eta'])[idx2],
                #                                    run_idx,
                #                                    options.leptonType)
                setattr(event,'bestZ',bestLLG)
                outTrees.bestZTree(event,tm)
                #tm.fillTree('%s_zs'%treeName,{})
            
            #bestPhoNoSihih = None
            #bestPhoNoSihihPt = -1
            #for idxph in selected_pho_nosihih:
            #    pho.SetPtEtaPhiM(event.phoCorEt[idxph],
            #                     event.phoEta[idxph],
            #                     event.phoPhi[idxph],
            #                     0.0)
            #    if bestPhoNoSihih is None or pho.Pt() > bestPhoNoSihihPt:
            #        if ( bestZ is not None and
            #             cuts.getCut('mindr')[0](event.bestZLeg1,
            #                                     event.bestZLeg2,
            #                                     pho) ):
            #            bestPhoNoSihih = idxph
            #            bestPhoNoSihihPt = pho.Pt()
            #        elif( bestZ is None ):
            #            bestPhoSihih = idxph
            #            bestPhoSihihPt = pho.Pt()
            
            bestPho = bestLLG #and bestPhoNoSihih is None: (below)
            if  options.exlProc and bestPho is None:
                continue

            if bestPho is not None:            
                setattr(event,'phoSF',1.0)
                #if run_idx != -1:
                #    event.phoSF = phoSF_nominal(event.nGoodVtx,
                #                                event.phoEt[bestPho],
                #                                event.phoEta[bestPho],
                #                                run_idx)            
                setattr(event,'bestPho',bestPho)
                
                #if bestPhoNoSihih is not None:            
                #    setattr(event,'phoNoSihihSF',event.phoSF)                
                #    setattr(event,'bestPhoNoSihihIdx',bestPho)
                #    setattr(event,'bestPhoNoSihih',pho)
                #elif bestPhoNoSihih is not None:
                #    pho.SetPtEtaPhiM(event.phoCorEt[bestPhoNoSihih],
                #                     event.phoEta[bestPhoNoSihih],
                #                     event.phoPhi[bestPhoNoSihih],
                #                     0.0)
                #    setattr(event,'phoNoSihihSF',1.0)
                #    if run_idx != -1:
                #        event.phoNoSihihSF = phoSF_nominal(event.nGoodVtx,
                #                                 event.phoEt[bestPhoNoSihih],
                #                                 event.phoEta[bestPhoNoSihih],
                #                                           run_idx)
                #    setattr(event,'bestPhoNoSihihIdx',bestPhoNoSihih)
                #    setattr(event,'bestPhoNoSihih',pho)
        
            if bestLLG is not None:
                #if bestPhoNoSihih is not None:
                #    thezg = event.bestZ + event.bestPhoNoSihih
                #    setattr(event,'bestZGNoSihih',thezg)
                #    outTrees.bestZGTreeNoSihih(event,tm)
                #    tm.fillTree('EventTree_zgs_nosihih',{})
                hzg_r94cat = hzg_4cat_r9based[leptonType](event,bestLLG)
                setattr(event,'bestZG_r94cat',hzg_r94cat)
                hzg_r94cat_mod = \
                               hzg_4cat_r9based_mod[leptonType](event,bestLLG)
                setattr(event,'bestZG_r94cat_mod',hzg_r94cat_mod)
                thezg = event.Zg[bestLLG]            
                selected_events.append((event.run[bestLLG],
                                        event.lumi[bestLLG],
                                        event.evt[bestLLG]))
                setattr(event,'bestZG',thezg)
                outTrees.bestZGTree(event,tm)
                pu_weight_sum += event.puWeight
                #tm.fillTree('%s_zgs'%treeName,{})
            tree = None
        in_file.Close()
        del in_file
        
    #make a nice file name
    input_file = args[0]
    nameparts = input_file[input_file.rfind('/')+1:]
    nameparts = nameparts.split('.')
    
    #output selected event numbers to file if needed
    print
    print 'Selected %i (%.2f) events after processing!'%(len(selected_events),
                                                         pu_weight_sum)

    try:
        os.makedirs(options.prefix)
        print 'Created prefix directory: %s'%options.prefix
    except os.error:
        print 'Prefix directory: %s already exists'%options.prefix
    
    if options.dumpSelectedEvents:
        #sort events
        selected_events.sort(key=lambda event: event[2])
        selected_events.sort(key=lambda event: event[1])
        selected_events.sort(key=lambda event: event[0])
        evf = open(options.prefix +
                   '%s_%s_%s_processed.%s'%('_'.join(nameparts[:-1]),
                                            options.runType,
                                            options.leptonType,
                                            'txt'),
                   'w')
        for ev in selected_events:
            evf.write('Run, Lumi, Event #:\t%i\t%i\t%i\n'%ev)
        evf.close()
        
    #push all of our output trees to a file
    outFileName = ''
    if options.vanilla:
        outFileName = '%s_%s_%s_%s_%s_processed.%s'\
                      %('_'.join(nameparts[:-1]),
                        options.runType,
                        options.datType,
                        options.leptonType,
                        'vanilla',
                        nameparts[-1])
    else:
        outFileName = '%s_%s_%s_%s_%s_%s_processed.%s'\
                      %('_'.join(nameparts[:-1]),
                        options.runType,
                        options.datType,
                        options.leptonType,
                        options.leptonCor,
                        options.gamCor,
                        nameparts[-1])    
    
    hEventCount = TH1I('eventCount','Total Events Processed',1,0,1)
    hEventCount.SetBinContent(1,nEvents_total)
    metaTList = TList()
    for tree in metaInfoTrees:
        metaTList.Add(tree)
    metaTree = TTree.MergeTrees(metaTList)    
    outf = TFile.Open(options.prefix + outFileName,'RECREATE')
    outf.cd()    
    metaTree.Write()    
    hEventCount.Write()
    tm.write()
    outf.Close()
    ROOT.gDirectory.cd(pwd)
def take_data(resolution, low, up, config, rangeval, mapsa, buffnum, daq,
              strobe_sets, sdur, smode, savestr, singlepixel):
    direction = 1 if ((up - low) > 0) else -1
    steps = int(round(abs(low - up) / resolution)) + 1
    c1 = TCanvas('c1', 'Source Monitor ', 700, 900)
    c1.Divide(2, 2)

    totalcounts = TH1I('Totalcounts',
                       'Totalcounts; DAC Value (1.456 mV); Counts (1/1.456)',
                       steps, low - .5, up + .5)
    channelcounts = TH2I(
        'Totalcounts_pixel',
        'Totalcounts; DAC Value (1.456 mV); Counts (1/1.456)', 288, .5, 288.5,
        steps, low - .5, up + .5)
    totalcounts.SetDirectory(0)
    channelcounts.SetDirectory(0)

    # f = TFile( 'sourcetest'+savestr+'.root', 'RECREATE' )
    f = TFile(savestr + '.root', 'RECREATE')

    tree_vars = {}
    tree_vars["TIMESTAMP"] = array('i', [0])
    tree_vars["SEQ_PAR"] = array('i', [0])
    tree_vars["TRIG_COUNTS_SHUTTER"] = array('i', [0])
    tree_vars["THRESHOLD"] = array('i', [0])
    tree_vars["REPETITION"] = array('i', [0])
    tree_vars["AR_MPA"] = array('i', [0] * 288)
    tree_vars["MEM_MPA"] = array('i', [0] * (96 * no_mpa_light))

    tree = TTree('datatree', 'datatree')
    for key in tree_vars.keys():
        # if "SR" in key:
        # 	tree.Branch(key,tree_vars[key],key+"[96]/i")
        if "AR" in key:
            tree.Branch(key, tree_vars[key], key + "[288]/i")
        if "MEM" in key:
            tree.Branch(key, tree_vars[key], key + "[384]/i")
        if "TRIG_COUNTS" in key:
            tree.Branch(key, tree_vars[key], key + "[1]/i")
        if "THRESHOLD" in key:
            tree.Branch(key, tree_vars[key], key + "[1]/i")
        if "REPETITION" in key:
            tree.Branch(key, tree_vars[key], key + "[1]/i")

    # daq.Strobe_settings(strobe_sets[0],strobe_sets[1],strobe_sets[2],strobe_sets[3],strobe_sets[4])
    mapsa.daq().Strobe_settings(snum, sdel, slen, sdist, CE)

    if (singlepixel == True):
        tree_vars["SEQ_PAR"][0] = 1
        for iy1 in range(0, 50):
            if iy1 % 2 == 0:
                config.modifypixel((iy1) / 2 + 1, 'PML', pmmask)
            if iy1 % 2 == 1:
                config.modifypixel((iy1 + 1) / 2, 'PMR', pmmask)
    if (singlepixel == False):
        tree_vars["SEQ_PAR"][0] = 0

    for z in range(0, rangeval):
        for xx in range(0, steps):
            x = xx * resolution * direction + low
            if (x < 0):
                x = 0
            if (x > 255):
                x = 255
            if (singlepixel == False and x % 10 == 0):
                print "THDAC " + str(x)
            if (singlepixel == True):
                print "THDAC " + str(x)
            # tstamp = str(datetime.datetime.now().time().isoformat().replace(":","").replace(".",""))
            # print "Timestamp: " + tstamp
            tree_vars["REPETITION"][0] = z
            tree_vars["THRESHOLD"][0] = x
            config.modifyperiphery('THDAC', [x] * 6)

            tree_vars["AR_MPA"][:] = array('i', 48 * no_mpa_light * [0])
            if (singlepixel == False):
                config.upload()
                config.write()
                # print tree_vars["REPETITION"]
                # print 'sdur', hex(sdur)
                mapsa.daq().Sequencer_init(smode, sdur)
                time.sleep(0.002)
                pix, mem = mapsa.daq().read_data(buffnum)
                time.sleep(0.002)
                # print "pix", pix
                ipix = 0
                # treevars["MEM"][0,384]=array('i',mem[:])
                # print mem
                for p in pix:
                    p.pop(0)
                    p.pop(0)
                    tree_vars["AR_MPA"][ipix * 48:(ipix + 1) * 48] = array(
                        'i', p[:])
                    # print 'p ', p[:]
                    # print 'ipix, p ', ipix, p[:]
                    ipix += 1
                    sum_hits = np.sum(tree_vars["AR_MPA"][:])
                # totalcounts.Fill(x,sum_hits)
                # print tree_vars["AR_MPA"][:]
                # print len(tree_vars["AR_MPA"][:])
                # for counter,hits in enumerate(tree_vars["AR_MPA"]):
                # 	channelcounts.Fill(counter+1,x,hits)
            if (singlepixel == True):
                count_arr = np.zeros((no_mpa_light, 48))
                for iy1 in range(2, 50):
                    if iy1 % 2 == 1:
                        config.modifypixel((iy1 - 1) / 2, 'PML', pmmaskon)
                        config.modifypixel((iy1 - 1) / 2, 'PMR', pmmask)
                    if iy1 % 2 == 0:
                        if iy1 != 2:
                            config.modifypixel(iy1 / 2 - 1, 'PML', pmmask)
                            config.modifypixel(iy1 / 2, 'PMR', pmmaskon)
                        else:
                            config.modifypixel(24, 'PML', pmmask)
                            config.modifypixel(24, 'PMR', pmmask)
                            config.modifypixel(1, 'PML', pmmask)
                            config.modifypixel(1, 'PMR', pmmaskon)
                    config.upload()
                    config.write()
                    mapsa.daq().Sequencer_init(smode, sdur)
                    time.sleep(0.002)
                    pix, mem = mapsa.daq().read_data(buffnum)
                    time.sleep(0.002)

                    ipix = 0
                    # treevars["MEM"][0,384]=array('i',mem[:])
                    # print mem
                    for pixcounter, p in enumerate(pix):
                        p.pop(0)
                        p.pop(0)
                        count_arr[ipix] = count_arr[ipix] + np.array(
                            array('i', p))
                        # print 'p ', p[:]
                        ipix += 1
                tree_vars["AR_MPA"][:] = array(
                    'i',
                    count_arr.astype(int).flatten().tolist()[:])
            # print tree_vars["AR_MPA"][:]
            # print len(tree_vars["AR_MPA"][:])
            for counter, hits in enumerate(tree_vars["AR_MPA"]):
                channelcounts.Fill(counter + 1, x, hits)
            sum_hits = np.sum(tree_vars["AR_MPA"][:])
            totalcounts.Fill(x, sum_hits)
            tree.Fill()
        tree.Write('tree', ROOT.TObject.kOverwrite)
        c1.cd(1)
        totalcounts.Draw('hist e1')
        c1.cd(2)
        channelcounts.Draw('colz')
        c1.Modified()
        c1.Update()
    # c1.Write("test")
    # time.sleep(2)
    channelcounts.Write("channelcounts")
    totalcounts.Write("totalcounts")
    f.Close()
Exemple #19
0
from ROOT import TH1I
from ROOT import TCanvas
from ROOT import TLegend
from math import sqrt
from math import hypot
from sys import argv

fileName = argv[1]
resonanceFile = TFile(argv[1] + ".root")
resonanceDecaysTree = resonanceFile.Get("resonanceDecays")

outputFile = TFile(argv[1] + "_plots" + ".root", "RECREATE")

numberOfEntries = resonanceDecaysTree.GetEntries()
'''Plot of the pt distribution of the resonance'''
resonancePtHisto = TH1I("resonancePtHisto", "Resonance pt distribution", 100,
                        0, 500)
'''Plot of both decay products' pt distribution'''
decayPtHisto = TH1I("decayPtHisto", "pt distribution of the decay products",
                    100, 0, 500)
'''Plot of the leading pt distribution of the charged decay products'''
decayLeadingPtHisto = TH1I("decayLeadingPtHisto",
                           "Leading pt charged decay product distribution",
                           100, 0, 500)
'''Plot of the sub-leading pt distribution of the charged decay products'''
decaySubLeadingPtHisto = TH1I("decaySubLeadingPtHisto",
                              "Sub-leading pt decay product distribution", 100,
                              0, 500)
'''Plot of the eta distribution of the resonance'''
resonanceEtaHisto = TH1I("resonanceEtaHisto", "Resonance eta distribution",
                         100, -10, +10)
'''Plot of the eta distribution of both decay products'''
Exemple #20
0
    for j in xrange(52):
        kanal = []
        for k in range(32):
            kanal.append(int(galaz.GetLeaf("kanal" + str(j)).GetValue(k)))
        dodajDane.append(rozlozPomiarNaSkladowe(kanal))
    dane = dane + [dodajDane]

plik.Close()

plik = TFile("histogramy " + czas + ".root", "recreate")

wykresy = []
for i in range(51):
    wykresy = wykresy + [
        TH1I(("Wykres " + str(i + 1)),
             ("Roznica miedzy kanalem " + str(i) + " a " + str(i + 1)), 131071,
             -65535, 65535)
    ]
    wykresy[i].SetDirectory(plik)

poleWykr = TCanvas("Rozkład", "Rozklad roznic pomiarowych miedzy kanalami",
                   1280, 720)

sigmy = []
#czas=time.strftime("%d.%m.%Y %H:%M:%S")
os.mkdir("./Wykresy " + czas)
for j in range(51):
    for i in xrange(liczbaDanych):
        chwilowa = dane[i][j][3] - dane[i][j + 1][3]
        wykresy[j].AddBinContent(chwilowa + 65535)
    wykresy[j].Fit("gaus", "Q", "", -65535, 65535)
Exemple #21
0
 # meangraph.SetTitle('Mean; Channel; DAC Value (1.456 mV)')
 meangraph.SetTitle('Mean; Channel; DAC Value (a.u.)')
 # sigmagraph.SetTitle('Sigma; Channel; DAC Value (1.456 mV)')
 sigmagraph.SetTitle('Sigma; Channel; DAC Value (a.u.)')
 chisquaregraph.SetTitle('Chisquared/NDF_gr; Channel; Chisquared/NDF ')
 ROOT.gStyle.SetOptFit(1111)
 # stack = THStack('a','Pixel Curves;DAC Value (1.456 mV);Counts (1/1.456)')
 stack = THStack('a', ';DAC Value (a.u.);Counts ')
 fitfuncs = []
 fitparams = []
 gr1 = []
 for pixel in range(0, channels):
     # gr1.append(TH1I(str(pixel),str(pixel+1)+';DAC Value (1.456 mV);Counts (1/1.456)',256,0.5,256.5))
     gr1.append(
         TH1I(str(pixel),
              str(pixel + 1) + ';DAC Value (a.u.);Counts ', 256, 0.5,
              256.5))
     color = pixel % 9 + 1
     gr1[pixel].SetLineColor(color)
     gr1[pixel].SetMarkerColor(color)
     gr1[pixel].SetFillColor(color)
     gr1[pixel].SetLineStyle(1)
     gr1[pixel].SetLineWidth(1)
     gr1[pixel].SetFillStyle(1)
     gr1[pixel].SetMarkerStyle(1)
     gr1[pixel].SetMarkerSize(.5)
     gr1[pixel].SetMarkerStyle(20)
     gr1[pixel].Sumw2(ROOT.kFALSE)
     stack.Add(gr1[pixel])
     fitfuncs.append(TF1('gauss' + str(pixel + 1), 'gaus(0)', 0, 256))
     fitfuncs[pixel].SetNpx(2560)
Exemple #22
0
            kanal.append(
                int(galaz.GetLeaf("kanal" + str(j) + "nar").GetValue(k)))
        dodajDane.append(rozlozPomiarNaSkladowe(kanal))
    dane = dane + [dodajDane]
#koniec odczytu danych
plik.Close()

#tworzenie wykresów
plik = TFile("histogramy " + czas + ".root", "recreate")

#wykresy różnic między kanałami
wykresy = []
for i in range(51):
    wykresy = wykresy + [
        TH1I(("Wykres " + str(i + 1) + " op."),
             ("Roznica miedzy kanalem " + str(i) + " a " + str(i + 1) +
              " (zbocze opadajace)"), 1023, -511, 511)
    ]
    wykresy[2 * i].SetDirectory(plik)
    wykresy = wykresy + [
        TH1I(("Wykres " + str(i + 1) + " nar."),
             ("Roznica miedzy kanalem " + str(i) + " a " + str(i + 1) +
              " (zbocze narastajace)"), 1023, -511, 511)
    ]
    wykresy[2 * i + 1].SetDirectory(plik)

poleWykr = TCanvas("Rozkład", "Rozklad roznic pomiarowych miedzy kanalami",
                   1280, 720)

#tworzenie poszczególnych wykresów i pobieranie wartości odchylenia standardowego z dopasowanej funkcji
sigmy = []
Exemple #23
0
#!/usr/bin/env python
#coding=utf-8

from array import array
from ROOT import TH1I
import sys

step = array('i')
data = array('i')
file = open(sys.argv[1])
for line in file:
    step.append(int(line.split()[0]))
    data.append(int(line.split()[1]))
file.close()

histogram = TH1I("fondo", "fondo", 15, 115, 130)
fondo = TH1I("fondo_scan", "scan", 4600, -2300, 2300)

for s, i in zip(step, data):
    fondo.Fill(s, i)
    histogram.Fill(i)

histogram.Draw()
fondo.Draw()
raw_input('Press ENTER to continue...')
Exemple #24
0
def plot_results(caldac, no_mpa_light, x1, y1, c1, backup):
    savestr = str(caldac)
    col = 1
    xvec = np.array(x1, dtype='uint16')
    xdacval = 0.
    thdacvv = []
    yarrv = []
    xdvals = []
    linearr = []
    stackarr = []
    fitfuncarr = []
    fitparameterarray = []
    for i in range(0, no_mpa_light):
        if (backup.GetDirectory("MPA_" + str(i))):
            backup.cd("MPA_" + str(i))
        else:
            backup.mkdir("MPA_" + str(i))
            backup.cd("MPA_" + str(i))
        calibconfxmlroot = calibconfsxmlroot[i]
        xdvals.append(0.)
        c1.cd(i + 1)
        thdacv = []
        yarr = np.array(y1[i])
        linearr.append([])
        gr1 = []
        lines = []
        fitfuncarr.append([])
        fitfuncs = []
        fitparameterarray.append([])
        fitparams = []
        yarrv.append(yarr)
        stackarr.append(
            THStack('a', 'pixel curves;DAC Value (1.456 mV);Counts (1/1.456)'))
        for iy1 in range(0, len(yarr[0, :])):
            yvec = yarr[:, iy1]
            # if max(yvec)==0:
            # print "zero"
            gr1.append(
                TH1I(str(iy1), ';DAC Value (1.456 mV);Counts (1/1.456)',
                     len(x1), 0, x1[-1]))
            gr1[iy1].Sumw2(ROOT.kFALSE)
            for j in np.nditer(xvec):
                gr1[iy1].SetBinContent(gr1[iy1].FindBin(j),
                                       (np.array(yvec, dtype='int')[j]))
            gr1[iy1].Sumw2(ROOT.kTRUE)
            color = iy1 % 9 + 1
            gr1[iy1].SetLineColor(color)
            gr1[iy1].SetMarkerColor(color)
            gr1[iy1].SetFillColor(color)
            gr1[iy1].SetLineStyle(1)
            gr1[iy1].SetLineWidth(1)
            gr1[iy1].SetFillStyle(1)
            gr1[iy1].SetMarkerStyle(1)
            gr1[iy1].SetMarkerSize(.5)
            gr1[iy1].SetMarkerStyle(20)
            fitfuncs.append(TF1('gaus', 'gaus', 0, 256))
            fitfuncs[iy1].SetNpx(256)
            fitfuncs[iy1].SetParameters(gr1[iy1].GetMaximum(),
                                        gr1[iy1].GetMean(), gr1[iy1].GetRMS())
            cloned = gr1[iy1].Clone()
            cloned.SetDirectory(0)
            fitparams.append([])
            mean = 0
            if gr1[iy1].GetMaximum() < -1:
                gr1[iy1].Fit(fitfuncs[iy1], 'rq +rob=0.95', '', 0, 256)
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(0))
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(1))
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(2))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(0))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(1))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(2))
                if (fitfuncs[iy1].GetNDF() > 0):
                    fitparams[iy1].append(fitfuncs[iy1].GetChisquare() /
                                          fitfuncs[iy1].GetNDF())
                else:
                    fitparams[iy1].append(0)
                mean = fitfuncs[iy1].GetParameter(1)
            else:
                for kk in range(0, 7):
                    fitparams[iy1].append(0)
            fitparameterarray[i].append(fitparams[iy1])
            fitfuncarr[i].append(fitfuncs[iy1])
            stackarr[i].Add(cloned)
            if iy1 == (len(yarr[0, :]) - 1):
                stackarr[i].Draw('nostack hist e1 x0')
                # for fitfuncs1 in fitfuncarr[i]:
                # 	fitfuncs1.Draw("same")
                # for lines1 in linearr[i]:
                # 	lines1.Draw("same")
                if (stackarr[i].GetMaximum() > 1):
                    Maximum = TMath.Power(
                        10, (round(TMath.Log10(stackarr[i].GetMaximum())) - 1))
                    stackarr[i].SetMinimum(.1)
                    stackarr[i].SetMaximum(Maximum)
                    # gPad.SetLogy()
                gPad.Modified()
                gPad.Update()
            gr1[iy1].SetLineColor(1)
            gr1[iy1].SetMarkerColor(1)
            gr1[iy1].SetFillColor(1)
            gr1[iy1].Write(str(iy1) + 'CAL' + savestr)
            # fitfuncs[iy1].Write(str(iy1)+savestr+'fit')
        # print thdacv
    backup.cd()
    if (backup.GetDirectory("Canvas")):
        backup.cd("Canvas")
    else:
        backup.mkdir("Canvas")
        backup.cd("Canvas")
    c1.Write('CALDAC_' + savestr)
    c1.Clear('D')
    return 0
Exemple #25
0
    mmin = 1.5
    mmax = 5.

    ptmax = 0.17

    outnam = "evt_per_run_muDst_run1_sel5.txt"

    rmin = 15084000
    rmax = 15167100

    #get the input
    gROOT.SetBatch()
    inp = TFile.Open(basedir + "/" + infile)
    tree = inp.Get("jRecTree")

    hrun = TH1I("hrun", "hrun", rmax - rmin, rmin, rmax)
    tree.Draw(
        "jRunNum >> hrun",
        "jRecM>{0:.3f} && jRecM<{1:.3f} && jRecPt<{2:.3f}".format(
            mmin, mmax, ptmax))

    print hrun.IsBinUnderflow(0)
    print hrun.IsBinOverflow(hrun.GetNbinsX() + 1)
    print hrun.GetEntries(), hrun.GetBinContent(0), hrun.GetBinContent(
        hrun.GetNbinsX() + 1)

    #content list
    rlist = []
    for i in xrange(hrun.GetNbinsX()):
        if hrun.GetBinContent(i) < 0.1: continue
        rlist.append((int(hrun.GetBinLowEdge(i)), int(hrun.GetBinContent(i))))
Exemple #26
0
def execute( fname ):
    file = open( fname, 'r' )

    # first count number of lines in file and find run numbers
    ic = -1
    minRun = 1e20
    maxRun = -1
    for line in file:
        if '--------------------' in line:
            if ic<0: 
                ic = 0
                continue
            else: break
        if ic >= 0: 
            # get run number
            r, sep, line = line.partition(':')
            runno = int(r.strip('run').strip())
            if runno > maxRun: maxRun = runno
            if runno < minRun: minRun = runno
            ic += 1       

    print 'Found: %i runs in file; run range: [%i, %i]' % (ic,minRun, maxRun)
    maxRun += 1
    minRun -= 1

    # --- read detectors ----

    print ' '
    print 'Reading detectors and DQ flags'
    (dName, NotInAll) = InitDetectorMaskDecoder()
    dqchans           = DQChannels()

    # create graphs and histograms
    rootfile = TFile.Open( "queryresults.root", "RECREATE" )        
    detgraphs = {}
    dethists  = {}
    for det in dName:
        detc = det.strip().replace(' ','_')        
        if 'unknown' in detc: continue

        detgraphs[det] = TGraph( ic )
        detgraphs[det].SetName( 'Det_%s_vs_run_graph' % detc )
        dethists[det] = TH1I( 'Det_%s_vs_run_hist' % detc, 'Det_%s_vs_run_hist' % detc, maxRun-minRun+1, minRun, maxRun )

    dqhists   = {}
    for key, dq in dqchans.items():
        dqhists[dq] = TH1I( 'DQ_%s_vs_run_hist' % dq, 'DQ_%s_vs_run_hist' % dq, maxRun-minRun+1, minRun, maxRun )

    # read lines
    ip = -1
    file.seek(0)
    for line in file:
        # search for start of output block
        if '--------------------' in line:
            for line in file:
                if '--------------------' in line: break
                # get run number
                r, sep, line = line.partition(':')
                ip += 1
                runno = int(r.strip('run').strip())

                # check detector
                for det in dName:
                    if 'unknown' in det: continue
                    if det in line: v = 2
                    else:           v = 1
                    detgraphs[det].SetPoint( ip, runno, v )
                    dethists[det].SetBinContent( runno - minRun + 1, v )

                # check DQ flag
                for key, dq in dqchans.items():
                    if not dq in line: v = -1
                    else:           
                        word = line[line.find( dq ):line.find( dq )+len(dq)+2]
                        if '=' in word:
                            w, sep, status = word.partition('=')
                            status = status.strip().lower()
                            if   status == 'u': v = 0
                            elif status == 'g': v = 3
                            elif status == 'y': v = 2
                            elif status == 'r': v = 1
                            else:
                                print 'ERROR: unknown DQ status: "%s" --> abort' % status
                                sys.exit(1)
                            
                            dqhists[dq].SetBinContent( runno - minRun + 1, v )
                        else:
                            print 'ERROR: format error on DQ parsing: "%s" --> abort' % word
                            sys.exit(1)
                            

    print 'End of file reading. Found: %i runs' % (ip+1)

    # write all graphs, and finish
    for key, g in detgraphs.items(): g.Write()
    for key, h in dethists.items() : h.Write()
    for key, h in dqhists.items()  : h.Write()

    print 'Wrote root file: %s' % rootfile.GetName()
    rootfile.Close()
)
nEntries = chain.GetEntries()
nEntries = 50
print 'processing nEntries= %i / %i' % (nEntries, chain.GetEntries())

subdet = {
    # TIB:3 TID:4 TOB:5 TEC:6
    3: "TIB",
    4: "TID",
    5: "TOB",
    6: "TEC",
}

for i in xrange(nEntries):
    chain.GetEntry(i)
    h_adc = TH1I('adc_%i' % i, 'adc_%i' % i, 800, 0, 800)
    h_baseline = TH1I('baseline_%i' % i, 'baseline_%i' % i, 800, 0, 800)
    h_cluster = TH1I('cluster_%i' % i, 'cluster_%i' % i, 800, 0, 800)
    for strip, adc, baseline, clusteredstrip in itertools.izip(
            chain.strip, chain.adc, chain.baseline, chain.clusteredstrip):
        #        print strip, adc
        h_adc.SetBinContent(strip + 1, adc)
        h_baseline.SetBinContent(strip + 1, baseline)
        h_cluster.SetBinContent(strip + 1, clusteredstrip)
    h_adc.SetMaximum(1000)
    h_adc.GetXaxis().SetTitle("strip")
    h_adc.GetYaxis().SetTitle("ADC counts")
    h_adc.Draw()
    h_baseline.SetLineWidth(2)
    h_baseline.SetLineColor(ROOT.kCyan + 1)
    h_baseline.Draw("same")
Exemple #28
0
def plot_results(switch_pre_post, no_mpa_light, x1, y1, calibconfsxmlroot,
                 prev_fit_mat):
    drawstr = ""
    savestr = ''
    col = 1
    if switch_pre_post == 0:
        savestr = 'pre'
    else:
        savestr = 'post'
        col = 2
        drawstr = " same"

    xvec = np.array(x1, dtype='uint16')
    xdacval = 0.
    thdacvv = []
    yarrv = []
    xdvals = []
    linearr = []
    stackarr = []
    fitfuncarr = []
    fitparameterarray = []
    c1 = TCanvas('c1', 'Pixel Monitor ' + savestr, 700, 900)
    c1.Divide(3, 2)
    for i in range(0, no_mpa_light):
        backup = TFile(
            "plots/backup_" + savestr + "Calibration_" + options.string +
            "_MPA" + str(i) + ".root", "recreate")
        calibconfxmlroot = calibconfsxmlroot[i]
        xdvals.append(0.)
        c1.cd(i + 1)
        thdacv = []
        yarr = np.array(y1[i])
        linearr.append([])
        gr1 = []
        lines = []
        fitfuncarr.append([])
        fitfuncs = []
        fitparameterarray.append([])
        fitparams = []
        yarrv.append(yarr)
        stackarr.append(
            THStack('a', 'pixel curves;DAC Value (1.456 mV);Counts (1/1.456)'))
        # hstack = THStack('a','pixel curves;DAC Value (1.456 mV);Counts (1/1.456)')
        for iy1 in range(0, len(yarr[0, :])):
            yvec = yarr[:, iy1]
            # if max(yvec)==0:
            # 	print "zero"
            gr1.append(
                TH1I(str(iy1), ';DAC Value (1.456 mV);Counts (1/1.456)',
                     len(x1), 0, x1[-1]))
            gr1[iy1].Sumw2(ROOT.kFALSE)
            for j in np.nditer(xvec):
                gr1[iy1].SetBinContent(gr1[iy1].FindBin(j),
                                       (np.array(yvec, dtype='int')[j]))
            gr1[iy1].Sumw2(ROOT.kTRUE)
            color = iy1 % 9 + 1
            gr1[iy1].SetLineColor(color)
            gr1[iy1].SetMarkerColor(color)
            gr1[iy1].SetFillColor(color)
            gr1[iy1].SetLineStyle(1)
            gr1[iy1].SetLineWidth(1)
            gr1[iy1].SetFillStyle(1)
            gr1[iy1].SetMarkerStyle(1)
            gr1[iy1].SetMarkerSize(.5)
            gr1[iy1].SetMarkerStyle(20)
            fitfuncs.append(TF1('gaus', 'gaus', 0, 256))
            fitfuncs[iy1].SetNpx(256)
            fitfuncs[iy1].SetParameters(gr1[iy1].GetMaximum(),
                                        gr1[iy1].GetMean(), gr1[iy1].GetRMS())
            cloned = gr1[iy1].Clone()
            cloned.SetDirectory(0)
            fitparams.append([])
            mean = 0
            if gr1[iy1].GetMaximum() > 1:
                gr1[iy1].Fit(fitfuncs[iy1], 'rq +rob=0.8', '', 0, 256)
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(0))
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(1))
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(2))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(0))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(1))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(2))
                if (fitfuncs[iy1].GetNDF() > 0):
                    fitparams[iy1].append(fitfuncs[iy1].GetChisquare() /
                                          fitfuncs[iy1].GetNDF())
                else:
                    fitparams[iy1].append(0)
                mean = fitfuncs[iy1].GetParameter(1)
            else:
                for kk in range(0, 7):
                    fitparams[iy1].append(0)
            fitparameterarray[i].append(fitparams[iy1])
            fitfuncarr[i].append(fitfuncs[iy1])
            stackarr[i].Add(cloned)
            if iy1 == (len(yarr[0, :]) - 1):
                stackarr[i].Draw('nostack hist e1 x0')
                # for fitfuncs1 in fitfuncarr[i]:
                # 	fitfuncs1.Draw("same")
                # for lines1 in linearr[i]:
                # 	lines1.Draw("same")
                if (stackarr[i].GetMaximum() > 1):
                    Maximum = TMath.Power(
                        10, (round(TMath.Log10(stackarr[i].GetMaximum())) - 1))
                    stackarr[i].SetMinimum(.1)
                    stackarr[i].SetMaximum(Maximum)
                    gPad.SetLogy()
                    gPad.Update()
            gr1[iy1].SetLineColor(1)
            gr1[iy1].SetMarkerColor(1)
            gr1[iy1].SetFillColor(1)
            gr1[iy1].Write(str(iy1))
            fitfuncs[iy1].Write(str(iy1) + 'fit')
            #Get prevous trim value for the channel
            if iy1 % 2 == 0:
                prev_trim = int(calibconfxmlroot[(iy1) / 2 +
                                                 1].find('TRIMDACL').text)
            else:
                prev_trim = int(calibconfxmlroot[(iy1 + 1) /
                                                 2].find('TRIMDACR').text)
            trimdac = 0
            # Now we have the routine to find the midpoint
            # dummy = []
            # dummy = traditional_trim(xvec,yvec,prev_trim,i)
            if (options.cal_type == 0):
                dummy = traditional_trim(xvec, yvec, prev_trim, i)
            elif (options.cal_type == 1):
                dummy = new_trim(xvec, yvec, prev_trim, i, mean)
            elif (options.cal_type == 2):
                dummy = new_trim1(xvec, yvec, prev_trim, i, mean)

            xdacval = dummy[0]
            trimdac = dummy[1]
            xdvals[i] = xdacval
            thdacv.append(trimdac)
            lines.append(
                TLine(xdacval / scalefac, .1, xdacval / scalefac,
                      cloned.GetMaximum()))
            linearr[i].append(lines[iy1])
            linearr[i][iy1].SetLineColor(2)
        thdacvv.append(thdacv)
        # print thdacv
    c1.SaveAs(
        'plots/Scurve_Calibration' + options.string + '_' + savestr + '.root',
        'root')
    c1.SaveAs(
        'plots/Scurve_Calibration' + options.string + '_' + savestr + '.pdf',
        'pdf')
    c1.SaveAs(
        'plots/Scurve_Calibration' + options.string + '_' + savestr + '.png',
        'png')
    backup.Close()
    objarr = []
    normgraph = TGraphErrors(no_mpa_light * 48)
    meangraph = TGraphErrors(no_mpa_light * 48)
    sigmagraph = TGraphErrors(no_mpa_light * 48)
    chisquaregraph = TGraphErrors(no_mpa_light * 48)
    mean_corrgraph = TGraphErrors(no_mpa_light * 48)
    normgraph.SetName('normgraph_' + savestr)
    meangraph.SetName('meangraph_' + savestr)
    sigmagraph.SetName('sigmagraph_' + savestr)
    chisquaregraph.SetName('chisquare_' + savestr)
    mean_corrgraph.SetName('mean_corr_' + savestr)
    meanhist = TH1F('meanhist_' + savestr,
                    'Mean DAC; DAC Value (1.456 mV); counts', 256, 0, 255)
    sigmahist = TH1F('sigmahist_' + savestr,
                     'Sigma DAC; DAC Value (1.456 mV); counts', 250, 0, 10)
    normgraph.SetTitle('Normalization; Channel; Normalization')
    meangraph.SetTitle('Mean; Channel; DAC Value (1.456 mV)')
    sigmagraph.SetTitle('Sigma; Channel; DAC Value (1.456 mV)')
    chisquaregraph.SetTitle('Chisquared/NDF; Channel; Chisquared/NDF ')
    mean_corrgraph.SetTitle('Correction; chann; DAC Value (1.456 mV)')
    objarr.append([
        normgraph, meangraph, sigmagraph, chisquaregraph, meanhist, sigmahist,
        mean_corrgraph
    ])
    A = np.array(fitparameterarray)
    RMSMeanPerChip = []
    pointno = 0
    for j in range(0, A.shape[0]):
        tmparr = []
        for j1 in range(0, A.shape[1]):
            # print A[j][j1][2]
            normgraph.SetPoint(pointno, pointno + 1, A[j][j1][0])
            normgraph.SetPointError(pointno, 0, A[j][j1][3])
            # if (A[j][j1][1]>1):
            tmparr.append(A[j][j1][1])
            meangraph.SetPoint(pointno, pointno + 1, A[j][j1][1])
            meangraph.SetPointError(pointno, 0, A[j][j1][4])
            sigmagraph.SetPoint(pointno, pointno + 1, A[j][j1][2])
            sigmagraph.SetPointError(pointno, 0, A[j][j1][5])
            chisquaregraph.SetPoint(pointno, pointno + 1, A[j][j1][6])
            chisquaregraph.SetPointError(pointno, 0, 0)
            if (switch_pre_post == 1):
                mean_corrgraph.SetPoint(pointno, pointno + 1,
                                        A[j][j1][1] - prev_fit_mat[j][j1][1])
                mean_corrgraph.SetPointError(
                    pointno, 0, A[j][j1][4] - prev_fit_mat[j][j1][4])
            if (A[j][j1][1] > 0):
                meanhist.Fill(A[j][j1][1])
            if (A[j][j1][2] > 0):
                sigmahist.Fill(A[j][j1][2])
            pointno += 1
        tmpmeanarray = np.array(tmparr, dtype=np.float)
        # print tmpmeanarray
        # print tmpmeanarray.shape[0]
        # tmpmeanarray.shape[]
        # print 'the array'
        # print ROOT.TMath.RMS(48,tmpmeanarray)
        RMSMeanPerChip.append(0)
    length = len(yarrv[0][0, :])
    RMSCorrection = []
    if (switch_pre_post == 1):
        corr_arr = np.array(mean_corrgraph.GetY(), dtype='d')
        # print corr_arr
        for j in range(0, no_mpa_light):
            # print j, array('d',corr_arr[(j*48):((j+1)*48):1])
            RMSCorrection.append(
                ROOT.TMath.RMS(48,
                               array('d',
                                     corr_arr[(j * 48):((j + 1) * 48):1])))
        # print ROOT.TMath.RMS(48,corr_arr[(j*48):((j+1)*48):1])
    return thdacvv, xdvals, A, length, objarr, RMSMeanPerChip, RMSCorrection
Exemple #29
0
#!/usr/bin/env python
import ROOT
from ROOT import TH1I, TChain, TCanvas

chGabriel = TChain("evt2l")
chEGamma = TChain("ZeeCandidate")

c = TCanvas("c", "Canvas", 1)
hGabriel = TH1I("hGabriel", "Compare", 10, 0, 10)
hGabriel.Fill(1)
hGabriel.Draw()
c.Print("try.pdf")
from ROOT import TCanvas
from ROOT import TLegend
from math import sqrt
from math import hypot
from sys import argv

fileName = argv[1]
higgsFile = TFile(argv[1] + ".root")
higgsDecaysTree = higgsFile.Get("higgsDecays")

numberOfEntries = higgsDecaysTree.GetEntries()

outputFile = TFile(argv[1] + "_plots" + ".root", "RECREATE")

'''pt distribution of the Higgs bosons'''
higgsPtHisto = TH1I("higgsPtHisto", "Higgs pt distribution", 100, 0, 500)
'''Cumulative pt distribution of both EW bosons'''
ewBosonPtHisto = TH1I("ewBosonPtHisto", "EW Bosons pt distribution", 100, 0, 500)
'''Leading pt distribution of EW bosons'''
ewBosonLeadingPtHisto = TH1I("ewBosonLeadingPtHisto", "EW Boson leading pt distribution", 100, 0, 500)
'''Sub-leading pt distribution of EW bosons'''
ewBosonSubLeadingPtHisto = TH1I("ewBosonSubLeadingPtHisto", "EW Boson sub-leading pt distribution", 100, 0, 500)
'''Plot of the distribution of the pt of one the two EW boson, to check that everything is working fine'''
ewBoson1PtHisto = TH1I("ewBoson1PtHisto", "EW Boson pt distribution", 100, 0, 500)
'''Plot of the distribution of the pt of one the two EW boson, to check that everything is working fine'''
ewBoson2PtHisto = TH1I("ewBoson2PtHisto", "EW Boson pt distribution", 100, 0, 500)
'''Cumulative plot of the distribution of the pt of every charged lepton'''
chargedLeptonPtHisto = TH1I("chargedLeptonPtHisto", "Charged leptons pt distribution", 100, 0, 500)
'''Cumulative plot of the distribution of the pt of every neutral lepton'''
neutralLeptonPtHisto = TH1I("neutralLeptonPtHisto", "Neutral leptons pt distribution", 100, 0, 500)
'''Plot of the distribution of the pt of a lepton'''