Esempio n. 1
0
    def read(self, i):

        #read a given event

        self.tree.GetEntry(i)

        #hits loop
        nhsel = 0
        for ihit in range(self.hits.GetN()):

            hit = self.hits.GetHit(ihit)
            hit.GlobalToLocal()

            nhsel += 1

        #just one selected hit, miss otherwise
        if nhsel != 1: return False

        #hit quantities
        self.hit_x = hit.x
        self.hit_y = hit.y
        self.hit_E = hit.en

        #event quantities
        self.true_el_theta = self.inp_el_theta.value
        self.true_el_E = self.inp_el_E.value
        self.true_Q2 = self.inp_Q2.value
        #derived quantities
        self.true_mlt = -TMath.Log10(TMath.Pi() - self.inp_el_theta.value)
        self.true_lq = TMath.Log10(self.inp_Q2.value)

        return True
Esempio n. 2
0
 def verifyEnergyBounds(fname, emin, emax):
     if debug: print 'verify energy range from DmpRunSimuHeader'
     ch = TChain("CollectionTree")
     ch.Add(fname)
     nentries = ch.GetEntries()
     h1 = TH1D("h1", "hEnergy", 10, TMath.Log10(emin), TMath.Log10(emax))
     ch.Project("h1", "TMath::Log10(DmpEvtSimuPrimaries.pvpart_ekin)")
     underflow = h1.GetBinContent(0)
     overflow = h1.GetBinContent(11)
     assert (
         underflow == 0), "{n} events found below emin={emin} MeV".format(
             n=int(underflow), emin=emin)
     assert (
         overflow == 0), "{n} events found above emax={emax} MeV".format(
             n=int(overflow), emax=emax)
     del h1
     del ch
Esempio n. 3
0
def cut_line(cut_val, yl, hx, logy=False):

    #vertical line representing a cut value

    if logy == False:
        tsel_pos = yl * hx.GetMaximum()
    else:
        if hx.GetMinimum() > 0.:
            tsel_pos = TMath.Log10(hx.GetMinimum()) + yl * (
                TMath.Log10(hx.GetMaximum()) - TMath.Log10(hx.GetMinimum()))
        else:
            tsel_pos = yl * TMath.Log10(hx.GetMaximum())
        tsel_pos = TMath.Power(10, tsel_pos)

    lin = TLine(cut_val, 0., cut_val, tsel_pos)
    lin.SetLineColor(rt.kViolet)
    lin.SetLineStyle(rt.kDashed)
    lin.SetLineWidth(4)

    return lin
Esempio n. 4
0
                    if j < 6:
                        hists[j][sALL].Fill(t_in.jet_pt[j], sclfac_[sam])
                    elif (j >= 6 and j < 12):
                        hists[j][sALL].Fill(t_in.jet_eta[j - 6], sclfac_[sam])
                    elif (j >= 12 and j < 18):
                        hists[j][sALL].Fill(t_in.jet_phi[j - 12], sclfac_[sam])
                    elif (j >= 18 and j < 24):
                        hists[j][sALL].Fill(t_in.jet_qgl[j - 18], sclfac_[sam])

                hists[24][sALL].Fill(t_in.isotropy, sclfac_[sam])
                hists[25][sALL].Fill(t_in.sphericity, sclfac_[sam])
                hists[26][sALL].Fill(t_in.min_dr_btag, sclfac_[sam])
                hists[27][sALL].Fill(t_in.aplanarity, sclfac_[sam])
                hists[28][sALL].Fill(t_in.nBCSVM, sclfac_[sam])
                hists[29][sALL].Fill(t_in.njets, sclfac_[sam])
                hists[30][sALL].Fill(TMath.Log10(t_in.C), sclfac_[sam])
                hists[31][sALL].Fill(TMath.Log10(t_in.D), sclfac_[sam])
                hists[32][sALL].Fill(t_in.DD5j[12], sclfac_[sam])
                hists[33][sALL].Fill(t_in.DD3j4[12], sclfac_[sam])
                hists[34][sALL].Fill(t_in.Deta5j, sclfac_[sam])
                hists[35][sALL].Fill(t_in.Deta3j4, sclfac_[sam])
                hists[36][sALL].Fill(t_in.Dphi5j, sclfac_[sam])
                hists[37][sALL].Fill(t_in.Dphi4j5, sclfac_[sam])
                hists[38][sALL].Fill(t_in.DR5j, sclfac_[sam])
                hists[39][sALL].Fill(t_in.DR4j5, sclfac_[sam])
                hists[40][sALL].Fill(t_in.DW3j, sclfac_[sam])
                hists[41][sALL].Fill(t_in.DW5j6, sclfac_[sam])

    leg1_.AddEntry(hists[0][sALL], sam_nicknames[sALL])

for sALL in samples_overall:
Esempio n. 5
0
def fill_ntuple():
    print('*** starting fill_ntuple() ')
    AtlasStyle.SetAtlasStyle()

    #    # get key list
    #    tfile = TFile(BasicConfig.workdir + 'systTree.root')
    #    key_list_all = [key.GetName() for key in gDirectory.GetListOfKeys()]
    #    regex = re.compile('PRW|JET|MET.*')
    #    key_list = [key for key in key_list_all if re.match(regex, key)]
    #    tfile.Close()

    # start making ttree
    #output_tfile = TFile('rhadron_v06-00-05.root', 'recreate')
    output_tfile = TFile(args.outputFile, 'recreate')

    # initialize TTree
    tree = TTree('rhadron', 'tree of rhadron properties for limit setting')
    # leaf variables
    from array import array
    mass_gluino = array('f', [0.])
    delta_mass = array('f', [0.])
    ctau = array('f', [0.])
    eff = array('f', [0.])
    eff_stat_error = array('f', [0.])
    eff_syst_error = array('f', [0.])
    eff_syst_error_ISR = array('f', [0.])
    eff_syst_error_PRW = array('f', [0.])
    eff_syst_error_JET = array('f', [0.])
    eff_syst_error_MET = array('f', [0.])
    # set branch
    tree.Branch("mGluino", mass_gluino, 'mGluino/F')
    tree.Branch("deltaM", delta_mass, 'deltaM/F')
    tree.Branch("ctau", ctau, 'ctau/F')
    tree.Branch("eff", eff, 'eff/F')
    tree.Branch("effRelStatErr", eff_stat_error, 'effRelStatErr/F')
    tree.Branch("effRelSystErr", eff_syst_error, 'effRelSystErr/F')
    tree.Branch("effRelSystErrISR", eff_syst_error_ISR, 'effRelSystErrISR/F')
    tree.Branch("effRelSystErrPRW", eff_syst_error_PRW, 'effRelSystErrPRW/F')
    tree.Branch("effRelSystErrJET", eff_syst_error_JET, 'effRelSystErrJET/F')
    tree.Branch("effRelSystErrMET", eff_syst_error_MET, 'effRelSystErrMET/F')

    #directory = '/afs/cern.ch/work/k/kmotohas/DisplacedVertex/DV_xAODAnalysis/submitDir_LSF/mc/hist_DVPlusMETSys/'
    #directory = BasicConfig.workdir + 'hist_DVPlusMETSys/'
    #directory = '/home/motohash/data/mc15_13TeV/DVPlusMETSys/v06-00-05/'

    #tfile = TFile(args.referenceFile)
    tfile = TFile(args.inputFile)
    key_list_all = [key.GetName() for key in gDirectory.GetListOfKeys()]
    print(len(key_list_all), key_list_all)
    regex = re.compile('Nominal|PRW|JET|MET.*')
    key_list = [key for key in key_list_all if re.match(regex, key)]
    print(len(key_list), key_list)
    tfile.Close()
    #c = 299792458.  # [m/s]
    #tchains = [[dsid, TChain('Nominal', str(dsid))] for dsid in range(402700, 402740)]
    #tchains = [[dsid, TChain('Nominal', str(dsid))] for dsid in mc.parameters.keys()]
    #tchains = [[dsid, [TChain(key, key+str(dsid)) for key in key_list]] for dsid in mc.parameters.keys()]
    dsids = [args.DSID]
    tchains = [[dsid, [TChain(key, key + str(dsid)) for key in key_list]]
               for dsid in dsids]

    cut_flow = [
        'Initial', 'Trigger', 'Filter', 'Cleaning', 'GRL', 'PV', 'NCB veto',
        'MET', 'DV Selection'
    ]
    #systematic_tables = TFile('systematic_summary_SimpleMETFilter.root', 'open')
    #table = TH1F()

    m_MET_min = 250.

    # loop over dsid
    try:
        for dsid, each_tchain in tchains:
            print('')
            print(dsid)
            #index = 0
            #for input in glob(directory + 'systTree_' + str(dsid) + '_*.root'):
            for tchain in each_tchain:
                #for input_file in glob(directory+'systTree_mc15_13TeV.' + str(dsid) + '*.root'):
                #    print(input_file)
                #    tchain.Add(input_file)
                tchain.Add(args.inputFile)

            mass_gluino[0] = mc.parameters[dsid]['g']
            delta_mass[0] = mass_gluino[0] - mc.parameters[dsid]['chi0']
            n_reweight_steps = 40
            xmin = 1.
            xmax = 10000.
            ratio = xmax / xmin
            bins = []
            for ii in range(n_reweight_steps):
                bins.append(
                    xmax *
                    10**(ii * TMath.Log10(xmax / xmin) / n_reweight_steps -
                         TMath.Log10(xmax / xmin)))
            #n_passed_w1 = [0. for _ in range(n_reweight_steps)]
            #n_passed = [0. for _ in range(n_reweight_steps)]
            from array import array
            limitsLifetime = array('d', bins)
            #
            tefficiency = [[
                TEfficiency('tefficiency_{0}_{1}_{2}'.format(key, step, dsid),
                            ';c#tau [mm]; Event-level efficiency',
                            len(limitsLifetime) - 1, limitsLifetime)
                for step in range(n_reweight_steps)
            ] for key in key_list]
            #h_syst_diff = [[TH1F('syst_diff_{0}_{1}_{2}'.format(key, step, dsid), ';;(N_{shifted} - N_{nominal}) / N_{nominal}', len(key_list)+1, 0, len(key_list)+1)
            #                for step in range(n_reweight_steps)] for key in key_list]
            h_syst_diff = [
                TH1F('syst_diff_{0}_{1}_{2}'.format(key, step, dsid),
                     ';;(N_{shifted} - N_{nominal}) / N_{nominal}',
                     len(key_list) + 1, 0,
                     len(key_list) + 1) for step in range(n_reweight_steps)
            ]

            for step in range(n_reweight_steps):
                for jj, key in enumerate(key_list):
                    h_syst_diff[step].GetXaxis().SetBinLabel(jj + 1, key)
                h_syst_diff[step].GetXaxis().SetBinLabel(
                    len(key_list) + 1, 'ISR_Py2MG_SF_removed')
            n_events_weighted = [[0. for _ in range(n_reweight_steps)]
                                 for key in key_list]
            n_events_weighted_noISR = [[0. for _ in range(n_reweight_steps)]
                                       for key in key_list]

            # loop over tchain of each systematic
            for ii, tchain in enumerate(each_tchain):
                entries = tchain.GetEntries()
                print('*** processed systs: {0} / {1}'.format(
                    ii, len(each_tchain)))
                #n_reweight_steps = 50
                #for step in range(n_reweight_steps):
                #    tefficiency.append(TEfficiency('tefficiency_'+str(step), ';c#tau [mm]; Event-level efficiency',
                #                                   len(limitsLifetime)-1, limitsLifetime))
                #    h_syst_diff.append(TH1F('syst_diff_'+str(step), ';;(N_{shifted} - N_{nominal}) / N_{nominal}', len(key_list)+1, 0, len(key_list)+1))
                for step in range(n_reweight_steps):
                    tefficiency[ii][step].SetUseWeightedEvents()
                    #for jj, key in enumerate(key_list):
                    #     h_syst_diff[ii][step].GetXaxis().SetBinLabel(jj+1, key)
                    #h_syst_diff[ii][step].GetXaxis().SetBinLabel(len(key_list)+1, 'ISR_Py2MG_SF_removed')
                #    h_syst_diff[step].SetMinimum(-0.3)
                #    h_syst_diff[step].SetMaximum(0.3)
                if entries == 0:
                    continue
                for entry in range(entries):
                    #if entry % 1000 == 0:
                    #    print('* processed events: {0} / {1}'.format(entry, entries))
                    utils.show_progress(entry, entries)
                    #if entry == 605:
                    #    break
                    # get the next tree in the chain and verify
                    ientry = tchain.LoadTree(entry)
                    if ientry < 0:
                        break
                    # copy next entry into memory and verify
                    nb = tchain.GetEntry(entry)
                    if nb <= 0:
                        continue
                    event_weight = tchain.McEventWeight * tchain.PileupWeight * tchain.ISRWeight
                    ctau_MC = TMath.C(
                    ) * mc.parameters[dsid]['t'] * 1e-9  # [nm]->[m]
                    for step in range(n_reweight_steps):
                        #print(tchain.GetListOfBranches())
                        pass_all = pass_event_cut(tchain, len(cut_flow) - 1)
                        if pass_all:
                            matched = False
                            for idv in range(len(tchain.DV_x)):
                                matched = matched or match(
                                    tchain, idv, cut=1.0)
                            #print('pass_all is ', pass_all, ', matched is ', matched)
                            pass_all = pass_all and matched
                        target_ctau = xmax * 10**(
                            step * TMath.Log10(xmax / xmin) / n_reweight_steps
                            - TMath.Log10(xmax / xmin)) * 1e-3  # [mm]->[m]
                        #print(target_ctau)
                        lifetime_weight = get_lifetime_weight(
                            tchain, target_ctau, ctau_MC)
                        n_events_weighted[ii][
                            step] += event_weight * lifetime_weight
                        n_events_weighted_noISR[ii][
                            step] += tchain.McEventWeight * tchain.PileupWeight * lifetime_weight
                        #print(event_weight)
                        #print(event_weight*lifetime_weight)
                        #print(pass_all)
                        tefficiency[ii][step].FillWeighted(
                            pass_all, event_weight * lifetime_weight,
                            target_ctau * 1e3)
                # end of loop over entries of each TChain
            # end loop over tchain of each systematic
            for step in range(n_reweight_steps):
                n_events_nominal = [0. for _ in range(n_reweight_steps)]
                for ii in range(len(each_tchain)):
                    # if Nominal TTree, set syst diff of ISR as well
                    if ii == 0:
                        n_events_nominal[step] = n_events_weighted[ii][step]
                        if n_events_nominal[step] < 1e-4:
                            #h_syst_diff[ii][step].SetBinContent(len(key_list)+1, 0)
                            h_syst_diff[step].SetBinContent(
                                len(key_list) + 1, 0)
                        else:
                            #h_syst_diff[ii][step].SetBinContent(len(key_list)+1,
                            h_syst_diff[step].SetBinContent(
                                len(key_list) + 1,
                                float((n_events_weighted_noISR[ii][step] -
                                       n_events_nominal[step]) /
                                      n_events_nominal[step]))
                            #float((n_events_weighted[ii][step]-n_events_nominal[step])/n_events_nominal[step]))
                    diff = n_events_weighted[ii][step] - n_events_nominal[step]
                    #print(n_events_nominal, n_events_weighted, diff)
                    if n_events_nominal[step] < 1e-4:
                        #h_syst_diff[ii][step].SetBinContent(ii+1, 0)
                        h_syst_diff[step].SetBinContent(ii + 1, 0)
                    else:
                        #h_syst_diff[ii][step].SetBinContent(ii+1, float(diff/n_events_nominal[step]))
                        h_syst_diff[step].SetBinContent(
                            ii + 1, float(diff / n_events_nominal[step]))
                    #systematic_tables.GetObject('systematic_table_'+str(dsid), table)
                    #syst_up, syst_down = root_sum_squares(table, 'x')
                #systs = root_sum_squares(h_syst_diff[ii][step], 'x')
                systs = root_sum_squares(h_syst_diff[step], 'x')
                #eff_syst_error[0] = max(syst_up, syst_down)  # TODO
                #eff_syst_error[0] = (syst_up**2 + syst_down**2)**0.5

                ####    ############################
                eff_syst_error[0] = (systs[0]**2 + systs[1]**2)**0.5
                eff_syst_error_ISR[0] = systs[2]
                eff_syst_error_PRW[0] = systs[3]
                eff_syst_error_JET[0] = systs[4]
                eff_syst_error_MET[0] = systs[5]
                if eff_syst_error[0] > 1:
                    print('eff_syst_error[0] = ' + str(eff_syst_error[0]))
                    #eff_syst_error[0] = 1.
                #for step in range(n_reweight_steps):
                #for ct in bins:
                #    print(len(bins), bins)
                #print(n_total_w1[step], n_total[step])
                #sf =  n_total_w1[step] / n_total[step]
                #n_passed[step] *= sf
                #n_total[step] *= sf
                #eff_no_weight, stat_error_no_weight = utils.division_error_propagation(n_passed_w1[step], n_total_w1[step])
                #ctau[0] = TMath.Power(300, step/float(n_reweight_steps-1)) * 1e-3  # [mm]->[m]
                ct = bins[step]
                #print(ct)
                ctau[0] = ct * 1e-3  # [mm]->[m]
                #print(ctau[0])
                bin_ctau = tefficiency[0][step].GetPassedHistogram().FindBin(
                    ct)
                print(tefficiency[0][step].GetPassedHistogram().GetBinContent(
                    bin_ctau))
                print(tefficiency[0][step].GetTotalHistogram().GetBinContent(
                    bin_ctau))
                #print(bin_ctau)
                #print('ct', ct, 'bin_ctau', bin_ctau)
                eff[0] = tefficiency[0][step].GetEfficiency(bin_ctau)
                print(eff[0])
                abs_stat_error = (
                    tefficiency[0][step].GetEfficiencyErrorLow(bin_ctau)**2 +
                    tefficiency[0][step].GetEfficiencyErrorUp(bin_ctau)**
                    2)**0.5
                #eff[0], abs_stat_error = utils.binomial_ratio_and_error(n_passed[step], n_total[step])
                #if eff[0] < 1e-4:
                if eff[0] == 0:
                    eff_stat_error[
                        0] = 1.  # avoid zero division error and divergence
                    continue  # not fill values in tree if efficiency is too small
                else:
                    eff_stat_error[0] = abs_stat_error / eff[0]
                #if eff_stat_error[0] > 1:
                #    print(n_passed[step], n_total[step], abs_stat_error, eff[0], eff_stat_error[0])
                #    eff_stat_error[0] = 1.
                tree.Fill()
            # end loop over n_reweight_steps
    except KeyboardInterrupt:
        pass
    output_tfile.Write()
    output_tfile.Close()
Esempio n. 6
0
h_LbMdss_cut = TH1F('h_LbMdss_cut', 'Lb_M evts with IPCHI2>1', 100, 0, 10000)

h_muTrueID = TH1F('h_muTrueID', '', 8000, -4000, 4000)

h_Eld = TH1F('h_Eld', '; E_{#mu} (MeV);', 20, 0, 2500)
h_q2d = r.TH1F('h_q2d', ';q^{2} (MeV^{2});', 20, -2E6, 18E6)
h_Mmissd = r.TH1F('h_Mmissd', ';Mmiss^{2} (MeV^{2});', 20, -2E6, 18E6)

h_Eldss = TH1F('h_Eldss', '; E_{#mu} (MeV);', 20, 0, 2500)
h_q2dss = r.TH1F('h_q2dss', ';q^{2} (MeV^{2});', 20, -2E6, 18E6)
h_Mmissdss = r.TH1F('h_Mmissdss', ';Mmiss^{2} (MeV^{2});', 20, -2E6, 18E6)

for i in range(td.GetEntries()):
    td.GetEntry(i)
    h_LbMMd.Fill(td.Lb_MM, td.sw_sig)
    h_IPCHI2d.Fill(m.Log10(td.Lc_IPCHI2_OWNPV), td.sw_sig)

for i in range(tdf.GetEntries()):
    tdf.GetEntry(i)
    h_LbMMdf.Fill(tdf.Lb_MM, tdf.sw_sig)
    h_IPCHI2df.Fill(m.Log10(tdf.Lc_IPCHI2_OWNPV), tdf.sw_sig)

for i in range(tdss.GetEntries()):
    tdss.GetEntry(i)
    h_LbMMdss.Fill(tdss.Lb_MM, tdss.sw_sig)
    h_IPCHI2dss.Fill(m.Log10(tdss.Lc_IPCHI2_OWNPV), tdss.sw_sig)

    if (m.Log10(tdss.Lc_IPCHI2_OWNPV) > 1):
        h_LbMdss_cut.Fill(tdss.Lb_M, tdss.sw_sig)

for i in range(tdfss.GetEntries()):
Esempio n. 7
0
def read_file(arr, meas_type, mapsa_fitter_inst, path):
    if not os.path.isfile(str(path + arr[0])):
        print "Root file not found at", str(path + arr[0])
        #sys.exit(1)
        return
    f = TFile(str(path + arr[0]), 'READ')
    if (f.IsZombie()):
        print "Error opening file"
        return
    else:
        print "Reading File ", arr[0]
    #f.ls()
    tree = f.Get('tree')
    f_GlobalData_Map = ROOT.TMap()
    f_GlobalData_Map.Add(ROOT.TObjString("tree"), tree)
    #tree.Print()
    outfile = TString(arr[0])
    outfile.ReplaceAll(".root", "")
    outfile.ReplaceAll(" ", "")
    # print outfile
    if (meas_type == 0):
        outfile = "pedestal"
    if (not g.FindKey(str(outfile))):
        g.mkdir(str(outfile))
        g.cd(str(outfile))
    else:
        return
    channels = 288
    if (arr[2] == 'inv'):
        channels = 96
        mapsa_mat = [[1, 0, 0], [1, 0, 0]]
    elif (arr[2] == 'norm'):
        channels = 288
        mapsa_mat = [[1, 1, 1], [1, 0, 1]]
    #print "channels", channels
    #print "mapsa_mat", mapsa_mat

    c1 = TCanvas('c1', 'Pixel Monitor ', 700, 900)
    c2 = TCanvas('c2', 'Pixel Monitor ', 500, 500)
    c3 = TCanvas('c3', 'Pixel Monitor ', 1280, 720)
    c4 = TCanvas('c4', 'Pixel Monitor ', 500, 500)
    c5 = TCanvas('c5', 'Pixel Monitor ', 500, 500)

    f_GlobalData_Map.Add(ROOT.TObjString("c1"), c1)
    f_GlobalData_Map.Add(ROOT.TObjString("c2"), c2)
    f_GlobalData_Map.Add(ROOT.TObjString("c3"), c3)
    f_GlobalData_Map.Add(ROOT.TObjString("c4"), c4)
    f_GlobalData_Map.Add(ROOT.TObjString("c5"), c5)

    # c2.Divide(2,1)
    #c2.cd(0)
    c1.Divide(3, 2)
    for i in range(1, 7):
        c1.cd(i)
        ROOT.gPad.SetGridx()
        ROOT.gPad.SetGridy()

    # channelcounts = TH2I('HitMap','Counts; Channel; DAC Value (1.456 mV)', 288, .5,288.5,256, .5, 256.5)
    channelcounts = TH2I('HitMap', 'Counts; Channel; DAC Value (a.u.)', 288,
                         .5, 288.5, 256, .5, 256.5)
    channelcounts_norm = TH2F('HitMap_norm',
                              'Occupancy ; Channel; DAC Value (a.u.)', 288, .5,
                              288.5, 256, .5, 256.5)
    f_GlobalData_Map.Add(ROOT.TObjString("HitMap"), channelcounts)
    f_GlobalData_Map.Add(ROOT.TObjString("HitMap"), channelcounts_norm)

    norm_2d = TH2F('Norm2D', 'Normalization; Column; Row', 48, .5, 48.5, 6, .5,
                   6.5)
    mean_2d = TH2F('Mean2D', 'Mean; Column; Row', 48, .5, 48.5, 6, .5, 6.5)
    sigma_2d = TH2F('Sigma2D', 'Sigma; Column; Row', 48, .5, 48.5, 6, .5, 6.5)
    chisquare = TH2F('Chisquare2D', 'Chisquare; Column; Row', 48, .5, 48.5, 6,
                     .5, 6.5)

    f_GlobalData_Map.Add(ROOT.TObjString("Norm2D"), norm_2d)
    f_GlobalData_Map.Add(ROOT.TObjString("Mean2D"), mean_2d)
    f_GlobalData_Map.Add(ROOT.TObjString("Sigma2D"), sigma_2d)
    f_GlobalData_Map.Add(ROOT.TObjString("Chisquare2D"), chisquare)

    objarr2d = []
    objarr2d.append(norm_2d)
    objarr2d.append(mean_2d)
    objarr2d.append(sigma_2d)
    objarr2d.append(chisquare)
    normgraph = TGraphErrors()
    meangraph = TGraphErrors()
    sigmagraph = TGraphErrors()
    chisquaregraph = TGraphErrors()
    mean_corrgraph = TGraphErrors()

    f_GlobalData_Map.Add(ROOT.TObjString("normgraph     "), normgraph)
    f_GlobalData_Map.Add(ROOT.TObjString("meangraph     "), meangraph)
    f_GlobalData_Map.Add(ROOT.TObjString("sigmagraph    "), sigmagraph)
    f_GlobalData_Map.Add(ROOT.TObjString("chisquaregraph"), chisquaregraph)
    f_GlobalData_Map.Add(ROOT.TObjString("mean_corrgraph"), mean_corrgraph)

    meanhist = TH1F('meanhist', 'Mean DAC; DAC Value (a.u.); counts', 2560, 0,
                    255)
    sigmahist = TH1F('sigmahist', 'Sigma DAC; DAC Value (a.u.); counts', 100,
                     0, 10)
    meanhist_std = TH1F('meanhist_std',
                        'Mean DAC Standard; DAC Value   (a.u.); counts', 2560,
                        0, 255)
    sigmahist_std = TH1F('sigmahist_std',
                         'Sigma DAC Standard; DAC Value (a.u.); counts', 100,
                         0, 10)
    meanhist_double = TH1F('meanhist_double',
                           'Mean DAC Double; DAC Value   (a.u.); counts', 2560,
                           0, 255)
    sigmahist_double = TH1F('sigmahist_double',
                            'Sigma DAC Double; DAC Value (a.u.); counts', 100,
                            0, 10)
    meanhist_double_neighbour = TH1F(
        'meanhist_double_neighbour',
        'Mean DAC Double Neighbour; DAC Value   (a.u.); counts', 2560, 0, 255)
    sigmahist_double_neighbour = TH1F(
        'sigmahist_double_neighbour',
        'Sigma DAC Double Neighbour; DAC Value (a.u.); counts', 100, 0, 10)
    objarr = []
    objarr.append(normgraph)
    objarr.append(meangraph)
    objarr.append(sigmagraph)
    objarr.append(chisquaregraph)
    objarr.append(mean_corrgraph)

    f_GlobalData_Map.Add(ROOT.TObjString('meanhist'), meanhist)
    f_GlobalData_Map.Add(ROOT.TObjString('sigmahist'), sigmahist)
    f_GlobalData_Map.Add(ROOT.TObjString('meanhist_std'), meanhist_std)
    f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_std'), sigmahist_std)
    f_GlobalData_Map.Add(ROOT.TObjString('meanhist_double'), meanhist_double)
    f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_double'), sigmahist_double)
    f_GlobalData_Map.Add(ROOT.TObjString('meanhist_double_neighbour'),
                         meanhist_double_neighbour)
    f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_double_neighbour'),
                         sigmahist_double_neighbour)

    objarr.append(meanhist)
    objarr.append(sigmahist)
    objarr.append(meanhist_std)
    objarr.append(sigmahist_std)
    objarr.append(meanhist_double)
    objarr.append(sigmahist_double)
    objarr.append(meanhist_double_neighbour)
    objarr.append(sigmahist_double_neighbour)

    for objs in objarr:
        objs.SetMarkerColor(2)
        objs.SetMarkerStyle(20)
        objs.SetMarkerSize(1)
    normgraph.SetName('normgraph')
    meangraph.SetName('meangraph')
    sigmagraph.SetName('sigmagraph')
    chisquaregraph.SetName('chisquare')
    mean_corrgraph.SetName('mean_corr')
    normgraph.SetTitle('Normalization; Channel; Normalization')
    meangraph.SetTitle('Mean; Channel; DAC Value (a.u.)')
    sigmagraph.SetTitle('Sigma; Channel; DAC Value (a.u.)')
    chisquaregraph.SetTitle('Chisquared/NDF_gr; Channel; Chisquared/NDF ')
    ROOT.gStyle.SetOptFit(1111)
    stack = THStack('a', ';DAC Value (a.u.); Occupancy')
    f_GlobalData_Map.Add(ROOT.TObjString("stack"), stack)
    fitfuncs = []
    fitparams = []
    gr1 = []
    for pixel in range(0, channels):
        gr1.append(
            TH1D(
                str(pixel).zfill(3),
                str(pixel + 1).zfill(3) + ';DAC Value (a.u.); Occupancy ', 256,
                0.5, 256.5))
        f_GlobalData_Map.Add(ROOT.TObjString(str(pixel).zfill(3)), gr1[pixel])
        #gr2.append(TH1F('th1f_'+str(pixel).zfill(3),str(pixel+1).zfill(3)+';DAC Value (a.u.); Occupancy',256,0.5,256.5))
        color = pixel % 8 + 1
        formating_th1(gr1[pixel], color)
        if (meas_type == 0):
            fitfuncs.append(
                TF1('gauss' + str(pixel + 1).zfill(3), 'gaus(0)', 0, 256))
            fitfuncs[pixel].SetNpx(256)
            fitfuncs[pixel].SetLineColor(color)
            f_GlobalData_Map.Add(
                ROOT.TObjString('gauss' + str(pixel).zfill(3)),
                fitfuncs[pixel])
    #Here we read the data and fill the histogram
    for event in tree:
        eventstr = []
        for counter, vals in enumerate(tree.AR_MPA):
            #eventstr.append(vals)
            channelcounts.Fill(counter, tree.THRESHOLD, vals)
            if (counter < channels):
                gr1[counter].Fill(tree.THRESHOLD, vals)
        #if tree.THRESHOLD%20==0 and tree.REPETITION==0:
        #print eventstr
        #print ("Threshold %d Repetion %d" % (tree.THRESHOLD,tree.REPETITION))
        #print tree.AR_MPA
    #now we make a small analysis of the curves fitting different functions to it:
    print "Finished Reading the Tree\n Normalization of Histograms\n"
    for pixel in range(0, channels):
        #gr1[pixel].ResetStats()
        for j in range(0, gr1[pixel].GetXaxis().GetNbins() + 1):
            gr1[pixel].SetBinError(
                gr1[pixel].GetBin(j),
                TMath.Sqrt(gr1[pixel].GetBinContent(gr1[pixel].GetBin(j))))
        #if(pixel==0):
        #gr1[pixel].Print("all")
        #gr1[pixel].Sumw2(ROOT.kTRUE)
        gr1[pixel].Scale(1 / arr[1])
        #if(pixel==0):
        #gr1[pixel].Print("all")
        stack.Add(gr1[pixel])
    #first create a THStack with histograms:
    iterator = stack.GetHists()
    if (meas_type == 0):
        for idx, it in enumerate(iterator):
            fitparams.append([])
            if (it.Integral() > 0):
                if (idx < channels):
                    #fitfuncs.append(TF1('combined'+str(idx),combined, 0,256,5))
                    #fitfuncs.append(TF1('combined_same_mean'+str(idx),combined_mean, 0,256,4))
                    #fitfuncs.append(TF1('double_gauss'+str(idx),'gaus(0)+gaus(3)',0,256))
                    #fitfuncs.append(TF1('gauss'+str(idx),'gaus(0)',0,256))
                    #fitfuncs.append(TF1('double_gauss_same_mean'+str(idx),double_gauss, 0,256,5))
                    #print it.GetName(), idx
                    #fitfuncs[idx].SetParameters(it.GetMaximum(),it.GetMean()+1,it.GetRMS(),it.GetMean()-1,it.GetRMS());
                    #fitfuncs[idx].SetParameters(it.GetMaximum(),it.GetMean(),it.GetRMS()*0.1,it.GetRMS()*0.1);
                    #print ("Channels %f\t%f\t%f\n" % (it.GetMaximum(),it.GetMean(),it.GetRMS()))
                    fitfuncs[idx].SetParameters(it.GetMaximum(), it.GetMean(),
                                                it.GetRMS())
                    #fitfuncs[idx].SetParameters(0.999*it.GetMaximum(),it.GetMean(),.7*it.GetRMS(),0.001*it.GetMaximum(),it.GetMean(),10*it.GetRMS());
                    #fitfuncs[idx].SetParameters(0.999*it.GetMaximum(),it.GetMean(),.7*it.GetRMS(),0.001*it.GetMaximum(),10*it.GetRMS());
                    #it.Fit(fitfuncs[idx],'lr0 rob=0.95','same',0,256)
                    #it.Fit(fitfuncs[idx],'lr0q ','',0,256)
                    it.Fit(fitfuncs[idx], 'r0q ', '', 0, 256)
                    fitparams[idx].append(fitfuncs[idx].GetParameter(0))
                    fitparams[idx].append(fitfuncs[idx].GetParameter(1))
                    fitparams[idx].append(fitfuncs[idx].GetParameter(2))
                    fitparams[idx].append(fitfuncs[idx].GetParError(0))
                    fitparams[idx].append(fitfuncs[idx].GetParError(1))
                    fitparams[idx].append(fitfuncs[idx].GetParError(2))
                    if (fitfuncs[idx].GetNDF() > 0):
                        fitparams[idx].append(fitfuncs[idx].GetChisquare() /
                                              fitfuncs[idx].GetNDF())
            else:
                for kk in range(0, 7):
                    fitparams[idx].append(0)
        #print "fitparamarray"
        fitarray = np.array(fitparams)
        ## print fitarray
        for pointno, it in enumerate(fitarray):
            if (fitarray[pointno][0] > 0):
                normgraph.SetPoint(pointno, pointno + 1, fitarray[pointno][0])
                normgraph.SetPointError(pointno, 0, fitarray[pointno][3])
                meangraph.SetPoint(pointno, pointno + 1, fitarray[pointno][1])
                meangraph.SetPointError(pointno, 0, fitarray[pointno][4])
                meanhist.Fill(fitarray[pointno][1])
                sigmagraph.SetPoint(pointno, pointno + 1, fitarray[pointno][2])
                sigmagraph.SetPointError(pointno, 0, fitarray[pointno][5])
                sigmahist.Fill(fitarray[pointno][2])
                chisquaregraph.SetPoint(pointno, pointno + 1,
                                        fitarray[pointno][6])
                chisquaregraph.SetPointError(pointno, 0, 0)
        ## iterator.ls()
        # Map the data to the pixel layout:
        tmp_objarr = []
        tmp_objarr.extend(
            [meanhist_std, meanhist_double, meanhist_double_neighbour])
        tmp_objarr.extend(
            [sigmahist_std, sigmahist_double, sigmahist_double_neighbour])
        for i in tmp_objarr:
            print str(i.GetName())

        fill2d(fitarray[:, 0], mapsa_mat, objarr2d[0])
        fill2d(fitarray[:, 1], mapsa_mat, objarr2d[1])
        fill2d(fitarray[:, 2], mapsa_mat, objarr2d[2])
        fill2d(fitarray[:, 6], mapsa_mat, objarr2d[3])
        fill1d_edges(objarr2d[1], tmp_objarr[0:3])
        fill1d_edges(objarr2d[2], tmp_objarr[3:])

    g.cd(str(outfile))
    mapsa_fitter_inst.Make_dirs()
    mapsa_fitter_inst.Set_run_no(outfile)
    if (meas_type == 1):
        for idx, it in enumerate(iterator):
            if (it.Integral() > 0):
                if (idx < channels):
                    mapsa_fitter_inst.Find_signal(it, idx, 0.0025, 3)
    g.cd()
    #g.mkdir(str(outfile)+"/Channels")
    #g.cd(str(outfile)+"/Channels")
    #iterator.Write()

    g.cd(str(outfile))
    g.mkdir(str(outfile) + "/Overview")
    ## iterator.First().Print("all")
    Maximum = TMath.Power(10, (round(TMath.Log10(stack.GetMaximum())) - 1))
    #Minimum = TMath.Power(10,(round(TMath.Log10(stack.GetMinimum()))+1))
    Minimum = .1

    ROOT.gStyle.SetLabelSize(0.06, "xyz")
    ROOT.gStyle.SetTitleSize(0.06, "xyz")
    ROOT.gStyle.SetTitleOffset(1.2, "y")
    ROOT.gStyle.SetTitleOffset(.825, "x")
    ROOT.gStyle.SetPadGridX(1)
    ROOT.gStyle.SetPadGridY(1)
    ROOT.gStyle.SetOptStat(0)
    # ROOT.gStyle.SetPadLeftMargin(.2);
    # ROOT.gStyle.SetPadRightMargin(.1);
    c1.cd(1)
    stack.Draw("nostack hist e1 x0")
    stack.GetXaxis().SetRangeUser(0, 256)
    stack.SetMinimum(Minimum)
    stack.SetMaximum(Maximum)
    ROOT.gPad.SetLogy()
    c2.cd(0)
    stack.Draw("nostack hist e1 x0")
    #if(outfile.Contains("SR_90_on_top")):
    #stack.GetXaxis().SetRangeUser(0,256)
    #else:
    #stack.GetXaxis().SetRangeUser(0,100)
    stack.SetMinimum(Minimum)
    stack.SetMaximum(Maximum)
    ROOT.gPad.SetLeftMargin(.15)
    ROOT.gPad.SetRightMargin(.05)

    ROOT.gPad.SetLogy()
    ROOT.gPad.Update()
    #for idx, it in enumerate(fitfuncs):
    ## if idx>0 and idx<7:
    #c1.cd(1)
    #fitfuncs[idx].Draw("same")
    #c2.cd(0)
    #fitfuncs[idx].DrawCopy("psame")
    ## it.SetLineColor(idx%9+1)
    ## it.Draw("same")
    #g.cd(str(outfile)+"/Channels")
    #it.Write("HitMap_py_"+str(idx+1)+"_fit")
    g.cd(str(outfile) + "/Overview")
    c1.cd(2)
    chisquaregraph.Draw("ap")
    c1.cd(3)
    normgraph.Draw("ap")
    c1.cd(4)
    sigmagraph.Draw("ap")
    sigmagraph.GetYaxis().SetRangeUser(0, 5)
    sigmagraph.GetXaxis().SetRangeUser(0, channels + 1)
    c2.cd(2)
    sigmagraph.Draw("ap")
    ROOT.gPad.SetLeftMargin(.15)
    ROOT.gPad.SetRightMargin(.05)
    c1.cd(5)
    meangraph.Draw("ap")
    c1.cd(6)
    channelcounts.Draw("colz")
    channelcounts.GetXaxis().SetRangeUser(0, channels + 1)
    # c2.cd(3)
    c3.cd(0)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gPad.SetRightMargin(.15)
    ROOT.gPad.SetLeftMargin(.15)
    ROOT.gPad.SetGrid(0)
    copy = channelcounts.DrawCopy("colz")
    #f_GlobalData_Map.Add(ROOT.TObjString("copy"),copy)
    #if(outfile.Contains("SR_90_on_top")):
    #copy.SetMaximum(100)
    #copy.SetMinimum(1)
    copy.GetYaxis().SetTitle("DAC Value (a.u.)")
    c4.cd(0)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gPad.SetRightMargin(.15)
    ROOT.gPad.SetLeftMargin(.15)
    ROOT.gPad.SetGrid(0)
    copy1 = sigma_2d.DrawCopy("colz")
    #f_GlobalData_Map.Add(ROOT.TObjString("copy1"),copy1)
    copy1.GetZaxis().SetTitle("Sigma (a.u.)")
    copy1.GetZaxis().SetTitleOffset(1.2)
    ROOT.gPad.SetRightMargin(.2)
    if (arr[2] == 'inv'):
        copy1.GetXaxis().SetRangeUser(.5, 16.5)
    copy1.SetMaximum(5)
    copy1.SetMinimum(0)

    c5.cd(0)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gPad.SetRightMargin(.15)
    ROOT.gPad.SetLeftMargin(.15)
    ROOT.gPad.SetGrid(0)
    #copy1 = chisquare.DrawCopy("colz")
    #f_GlobalData_Map.Add(ROOT.TObjString("copy2"),copy1)
    copy1 = sigma_2d.DrawCopy("colz")
    #f_GlobalData_Map.Add(ROOT.TObjString("copy2"),copy1)
    copy1.GetZaxis().SetTitle("sigma (a.u.)")
    if (arr[2] == 'inv'):
        copy1.GetXaxis().SetRangeUser(.5, 16.5)
    copy1.SetMaximum(5)
    copy1.SetMinimum(0)

    c1.Update()
    c1.Modified()
    c2.Update()
    c2.Modified()
    c3.Update()
    c3.Modified()
    c4.Update()
    c4.Modified()
    c5.Update()
    c5.Modified()

    ## c1.SaveAs("double_gauss_same_mean.pdf")
    ## time.sleep(2)
    g.cd(str(outfile) + "/Overview")
    #for objs in objarr:
    #objs.Write(objs.GetName())
    #norm_2d.GetZaxis().SetRangeUser(1E5,2E6)
    #mean_2d.GetZaxis().SetRangeUser(54,64)
    ## norm_2d.GetZaxis().SetRangeUser(TMath.Power(10,(round(TMath.Log10(norm_2d.GetStdDev(3))-2)), TMath.Power(10,(round(TMath.Log10(norm_2d.GetStdDev(3)))-1)))
    ## mean_2d.GetZaxis().SetRangeUser(TMath.Power(10,(round(TMath.Log10(mean_2d.mean_2d.GetStdDev(3)))-1))-5,TMath.Power(10,(round(TMath.Log10(mean_2d.GetStdDev(3)))-1))+5)
    #sigma_2d.GetZaxis().SetRangeUser(0,5)
    #chisquare.GetZaxis().SetRangeUser(0,10000 )
    #for objs in objarr2d:
    #objs.Write(objs.GetName())
    #c1.Write("c1")
    #outfile1=outfile+TString(".pdf")
    #c2.SaveAs(str(outfile1))
    #c2.Write("c2")
    #c3.SaveAs("c3"+str(outfile1))
    #c3.Write("c3")
    #c4.SaveAs("c4"+str(outfile1))
    #c4.Write("c4")
    ## while (TObject(iterator.Next())):
    ##       print iterator.Next().Title()
    #stack.Write("stack")
    #g.cd(str(outfile))
    #channelcounts.Write(str(outfile))
    #f.Close()
    c1.Close()
    c2.Close()
    c3.Close()
    c4.Close()
    c5.Close()
    f_GlobalData_Map.DeleteAll()
    f.Close()
LCurve = thisUnfold.GetLCurve()
LogTauX = thisUnfold.GetLogTauX()
LogTauY = thisUnfold.GetLogTauY()
Tau = thisUnfold.GetTau()
bestLCurve = TGraph(1)

nPoints = LogTauX.GetNp()
for ip in xrange(0, nPoints):
    logTau = Double(0)
    tmpX = Double(0)
    tmpY = Double(0)
    LogTauX.GetKnot(ip, logTau, tmpX)
    LogTauY.GetKnot(ip, logTau, tmpY)
    print 'Point ' + str(ip) + ': logTau = ' + str(logTau) + ', x = ' + str(
        tmpX) + ', y = ' + str(tmpY)
    if logTau == TMath.Log10(Tau):
        print 'Best tau is ' + str(Tau) + ' at point ' + str(ip)
        bestLCurve.SetPoint(1, tmpX, tmpY)

bestLCurve.SetMarkerColor(2)

c2 = TCanvas("c2", "c2", 700, 700)
c2.cd()
LCurve.Draw()
bestLCurve.Draw("*")

tl2 = TLatex()
tl2.SetNDC()
tl2.SetTextFont(42)
legend = "#tau = %.3e" % Tau
tl2.DrawLatex(0.55, 0.8, legend)
Esempio n. 9
0
    def __init__(self, parse, tree, hepmc_attrib):

        print("Quasi-real configuration:")

        #electron and proton beam energy, GeV
        self.Ee = parse.getfloat("main", "Ee")
        self.Ep = parse.getfloat("main", "Ep")
        print("Ee =", self.Ee, "GeV")
        print("Ep =", self.Ep, "GeV")

        #electron and proton mass
        self.me = TDatabasePDG.Instance().GetParticle(11).Mass()
        mp = TDatabasePDG.Instance().GetParticle(2212).Mass()

        #boost vector pbvec of proton beam
        pbeam = TLorentzVector()
        pbeam.SetPxPyPzE(0, 0, TMath.Sqrt(self.Ep**2-mp**2), self.Ep)
        self.pbvec = pbeam.BoostVector()

        #electron beam energy Ee_p in proton beam rest frame
        ebeam = TLorentzVector()
        ebeam.SetPxPyPzE(0, 0, -TMath.Sqrt(self.Ee**2-self.me**2), self.Ee)
        ebeam.Boost(-self.pbvec.x(), -self.pbvec.y(), -self.pbvec.z()) # transform to proton beam frame
        self.Ee_p = ebeam.E()

        #center-of-mass squared s, GeV^2
        self.s = self.get_s(self.Ee, self.Ep)
        print("s =", self.s, "GeV^2")
        print("sqrt(s) =", TMath.Sqrt(self.s), "GeV")

        #range in x
        xmin = parse.getfloat("main", "xmin")
        xmax = parse.getfloat("main", "xmax")
        print("xmin =", xmin)
        print("xmax =", xmax)

        #range in u = log_10(x)
        umin = TMath.Log10(xmin)
        umax = TMath.Log10(xmax)
        print("umin =", umin)
        print("umax =", umax)

        #range in y
        ymin = parse.getfloat("main", "ymin")
        ymax = parse.getfloat("main", "ymax")

        #range in W
        wmin = -1.
        wmax = -1.
        if parse.has_option("main", "Wmin"):
            wmin = parse.getfloat("main", "Wmin")
            print("Wmin =", wmin)
        if parse.has_option("main", "Wmax"):
            wmax = parse.getfloat("main", "Wmax")
            print("Wmax =", wmax)

        #adjust range in y according to W
        if wmin > 0 and ymin < wmin**2/self.s:
            ymin = wmin**2/self.s
        if wmax > 0 and ymax > wmax**2/self.s:
            ymax = wmax**2/self.s

        print("ymin =", ymin)
        print("ymax =", ymax)

        #range in v = log_10(y)
        vmin = TMath.Log10(ymin)
        vmax = TMath.Log10(ymax)
        print("vmin =", vmin)
        print("vmax =", vmax)

        #range in Q2
        self.Q2min = parse.getfloat("main", "Q2min")
        self.Q2max = parse.getfloat("main", "Q2max")
        print("Q2min =", self.Q2min)
        print("Q2max =", self.Q2max)

        #constant term in the cross section
        self.const = TMath.Log(10)*TMath.Log(10)*(1./137)/(2.*math.pi)

        #cross section formula for d^2 sigma / dxdy, Eq. II.6
        #transformed as x -> u = log_10(x) and y -> v = log_10(y)
        self.eq_II6_uv_par = self.eq_II6_uv(self)
        self.eq = TF2("d2SigDuDvII6", self.eq_II6_uv_par, umin, umax, vmin, vmax)

        self.eq.SetNpx(1000)
        self.eq.SetNpy(1000)

        #uniform generator for azimuthal angles
        self.rand = TRandom3()
        self.rand.SetSeed(5572323)

        #generator event variables in output tree
        tnam = ["gen_u", "gen_v", "true_x", "true_y", "true_Q2", "true_W2"]
        tnam += ["true_el_Q2"]
        tnam += ["true_el_pT", "true_el_theta", "true_el_phi", "true_el_E"]

        #create the tree variables
        tcmd = "struct gen_out { Double_t "
        for i in tnam:
            tcmd += i + ", "
        tcmd = tcmd[:-2] + ";};"
        gROOT.ProcessLine( tcmd )
        self.out = rt.gen_out()

        #put zero to all variables
        for i in tnam:
            exec("self.out."+i+"=0")

        #set the variables in the tree
        if tree is not None:
            for i in tnam:
                tree.Branch(i, addressof(self.out, i), i+"/D")

        #event attributes for hepmc
        self.hepmc_attrib = hepmc_attrib

        #counters for all generated and selected events
        self.nall = 0
        self.nsel = 0

        #print generator statistics at the end
        atexit.register(self.show_stat)

        #total integrated cross section
        self.sigma_tot = self.eq.Integral(umin, umax, vmin, vmax)
        print("Total integrated cross section for a given x and y range:", self.sigma_tot, "mb")

        print("Quasi-real photoproduction initialized")
Esempio n. 10
0
def reconstruct(config):

    #configuration
    cf = read_con(config)

    #input reconstruction matrix Rijk
    mat = rmat(infile=cf.str("inp_rec_Rijk"))

    #input data for reconstruction
    inlist = glob(cf.str("inp_rec_data"))
    tree = TChain("DetectorTree")
    for i in inlist:
        tree.Add(i)

    #output from reconstruction
    out = TFile(cf.str("out_rec"), "recreate")
    rec_tree = TTree("Q2rec", "Q2rec")

    #set the output tree
    gROOT.ProcessLine("struct Entry {Double_t v;};")
    true_Q2 = make_branch("true_Q2", rec_tree, rt.Entry)
    true_el_E = make_branch("true_el_E", rec_tree, rt.Entry)
    true_el_theta = make_branch("true_el_theta", rec_tree, rt.Entry)
    true_mlt = make_branch("true_mlt", rec_tree, rt.Entry)
    true_lq = make_branch("true_lq", rec_tree, rt.Entry)

    hit_x = make_branch("hit_x", rec_tree, rt.Entry)
    hit_y = make_branch("hit_y", rec_tree, rt.Entry)
    hit_E = make_branch("hit_E", rec_tree, rt.Entry)
    rec_mlt = make_branch("rec_mlt", rec_tree, rt.Entry)
    rec_Q2 = make_branch("rec_Q2", rec_tree, rt.Entry)
    rec_lq = make_branch("rec_lq", rec_tree, rt.Entry)

    #number of events
    nev = cf.int("nev")
    if nev < 0: nev = tree.GetEntries()

    #range in mlt
    mlt_range = [cf("tmin"), cf("tmax")]

    print("Event loop, events:", nev)
    iprint = int(nev / 12)
    evt = TagV2Evt(tree, cf)
    for iev in range(nev):

        if iev % iprint == 0:
            print("{0:.1f} %".format(100. * iev / nev))
            stdout.flush()

        #read the event
        if not evt.read(iev): continue

        #input true values
        true_lq.v = evt.true_lq

        #energy index 'i'
        i = mat.hEi.FindBin(evt.hit_E)
        if i < 1 or i > mat.hEi.GetNbinsX(): continue

        #mlt at 'j' and 'k'
        jk = mat.tjks[i].hTjk.FindBin(evt.hit_x, evt.hit_y)
        #print jk
        mlt = mat.tjks[i].hTjk.GetBinContent(jk)
        if mlt < mlt_range[0] or mlt > mlt_range[1]:
            continue

        #electron scattering angle
        theta = 10**(-mlt)
        #print theta

        #reconstructed Q^2
        rec_Q2.v = 2. * 18 * evt.hit_E * (1. - TMath.Cos(theta))
        rec_lq.v = TMath.Log10(rec_Q2.v)
        #print(rec_lq.v, true_lq.v)

        #print mlt, evt.true_mlt

        rec_tree.Fill()

    rec_tree.Write()
    out.Close()

    print("All done")
Esempio n. 11
0
            sigmagraph.SetPoint(pointno, pointno + 1, fitarray[pointno][2])
            sigmagraph.SetPointError(pointno, 0, fitarray[pointno][5])
            sigmahist.Fill(fitarray[pointno][2])
            chisquaregraph.SetPoint(pointno, pointno + 1, fitarray[pointno][6])
            chisquaregraph.SetPointError(pointno, 0, 0)
# iterator.ls()
    for i in range(0, 3):
        fill2d(fitarray[:, i], mapsa_mat, objarr2d[i])
    fill2d(fitarray[:, 6], mapsa_mat, objarr2d[3])

    g.cd(str(outfile))
    g.mkdir(str(outfile) + "/Channels")
    g.cd(str(outfile) + "/Channels")
    iterator.Write()
    # iterator.First().Print("all")
    Maximum = TMath.Power(10, (round(TMath.Log10(stack.GetMaximum())) - 1))

    ROOT.gStyle.SetLabelSize(0.06, "xyz")
    ROOT.gStyle.SetTitleSize(0.06, "xyz")
    ROOT.gStyle.SetTitleOffset(1.2, "y")
    ROOT.gStyle.SetTitleOffset(.825, "x")
    ROOT.gStyle.SetPadGridX(1)
    ROOT.gStyle.SetPadGridY(1)
    ROOT.gStyle.SetOptStat(0)
    # ROOT.gStyle.SetPadLeftMargin(.2);
    # ROOT.gStyle.SetPadRightMargin(.1);

    c1.cd(1)

    stack.Draw("nostack hist e1 x0")
    stack.GetXaxis().SetRangeUser(0, 256)
Esempio n. 12
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
def main():

    identifier = inputFiles[0][inputFiles[0].rfind('/') + 1:].replace(
        '.root', '').replace('_step2',
                             '').replace('_AODSIM',
                                         '').replace('_1*',
                                                     '').replace('*', '')
    identifier += 'nFiles' + str(len(inputFiles))

    print(identifier)

    fnew = TFile('histsEDM_' + identifier + '.root', 'recreate')
    events = Events(inputFiles)

    # GEN chi20 histos

    hChi20StatusBefore = TH1F("hChi20StatusBefore", "hChi20StatusBefore", 200,
                              0., 200.)
    hChi20StatusAfter = TH1F("hChi20StatusAfter", "hChi20StatusAfter", 200, 0.,
                             200.)

    hPdgIdDaughters = TH1F("hPdgIdDaughters", "hPdgIdDaughters", 50, 0., 50.)
    hPdgIdDaughtersSUSY = TH1F("hPdgIdDaughtersSUSY", "hPdgIdDaughtersSUSY",
                               50, 0., 50.)

    hPtChi20Before = TH1F("hPtChi20Before", "hPtChi20Before", 150, 0, 1500.)
    hPtChi20After = TH1F("hPtChi20After", "hPtChi20After", 150, 0, 1500.)

    hChi20LogLabLengthVsPtLepton = TH2F("hChi20LogLabLengthVsPtLepton",
                                        "hChi20LogLabLengthVsPtLepton", 50,
                                        -2.0, 0., 150, 0., 1.5)

    # GEN lepton finding histos

    hLeptonsFound = TH1F("hLeptonsFound", "hLeptonsFound", 3, 0., 3.)

    hPtZgamma = TH1F("hPtZgamma", "hPtZgamma", 50, 0, 5.)

    hPtLepton = TH1F("hPtLepton", "hPtLepton", 50, 0, 5.)
    hEtaLepton = TH1F("hEtaLepton", "hEtaLepton", 100, -5., 5.)
    hLogTransverseDistLepton = TH1F("hLogTransverseDistLepton",
                                    "hLogTransverseDistLepton", 100, -3., 3.)

    hDrLeptonLepton = TH1F("hDrLeptonLepton", "hDrLeptonLepton", 100, 0., 5.)
    hLogDrLeptonLepton = TH1F("hLogDrLeptonLepton", "hLogDrLeptonLepton", 100,
                              -5., 1.)

    hInvMassLepton = TH1F("hInvMassLepton", "hInvMassLepton", 100, 0, 5.)
    hLogInvMassLepton = TH1F("hLogInvMassLepton", "hLogInvMassLepton", 100,
                             -5., 1.)

    # lepton matching histos

    hDrLeptonPfc = TH1F("hDrLeptonPfc", "hDrLeptonPfc", 100, 0, 1.)
    hDrLeptonTrack = TH1F("hDrLeptonTrack", "hDrLeptonTrack", 100, 0, 1.)

    hSamePfcMatched = TH1F("hSamePfcMatched", "hSamePfcMatched", 2, 0., 2.)
    hParticleIdPfcMatched = TH1F("hParticleIdPfcMatched",
                                 "hParticleIdPfcMatched", 10, 0., 10.)

    hPtPfcMatched = TH1F("hPtPfcMatched", "hPtPfcMatched", 50, 0, 5.)
    hPtTrackMatched = TH1F("hPtTrackMatched", "hPtTrackMatched", 50, 0, 5.)

    # efficiency histos

    hChi20LabLengthAll = TH1F("hChi20LabLengthAll", "hChi20LabLengthAll", 50,
                              0., 1.)
    hChi20LabLengthPass = TH1F("hChi20LabLengthPass", "hChi20LabLengthPass",
                               50, 0., 1.)

    hChi20LogLabLengthAll = TH1F("hChi20LogLabLengthAll",
                                 "hChi20LogLabLengthAll", 50, -2.0, 0.)
    hChi20LogLabLengthPass = TH1F("hChi20LogLabLengthPass",
                                  "hChi20LogLabLengthPass", 50, -2.0, 0.)

    hChi20LabLengthPfcMatchedAll = TH1F("hChi20LabLengthPfcMatchedAll",
                                        "hChi20LabLengthPfcMatchedAll", 50, 0.,
                                        1.)
    hChi20LabLengthPfcMatchedPass = TH1F("hChi20LabLengthPfcMatchedPass",
                                         "hChi20LabLengthPfcMatchedPass", 50,
                                         0., 1.)

    hChi20LogLabLengthPfcMatchedAll = TH1F("hChi20LogLabLengthPfcMatchedAll",
                                           "hChi20LogLabLengthPfcMatchedAll",
                                           50, -2.0, 0.)
    hChi20LogLabLengthPfcMatchedPass = TH1F(
        "hChi20LogLabLengthPfcMatchedPass", "hChi20LogLabLengthPfcMatchedPass",
        50, -2.0, 0.)

    hChi20LabLengthOnePfcMatchedAll = TH1F("hChi20LabLengthOnePfcMatchedAll",
                                           "hChi20LabLengthOnePfcMatchedAll",
                                           50, 0., 1.)
    hChi20LabLengthOnePfcMatchedPass = TH1F(
        "hChi20LabLengthOnePfcMatchedPass", "hChi20LabLengthOnePfcMatchedPass",
        50, 0., 1.)

    hChi20LogLabLengthOnePfcMatchedAll = TH1F(
        "hChi20LogLabLengthOnePfcMatchedAll",
        "hChi20LogLabLengthOnePfcMatchedAll", 50, -2.0, 0.)
    hChi20LogLabLengthOnePfcMatchedPass = TH1F(
        "hChi20LogLabLengthOnePfcMatchedPass",
        "hChi20LogLabLengthOnePfcMatchedPass", 50, -2.0, 0.)

    hPtLeptonAll = TH1F("hPtLeptonAll", "hPtLeptonAll", 30, 0, 3.)
    hPtLeptonPass = TH1F("hPtLeptonPass", "hPtLeptonPass", 30, 0, 3.)

    hPtLeptonPfcMatchedAll = TH1F("hPtLeptonPfcMatchedAll",
                                  "hPtLeptonPfcMatchedAll", 30, 0, 3.)
    hPtLeptonPfcMatchedPass = TH1F("hPtLeptonPfcMatchedPass",
                                   "hPtLeptonPfcMatchedPass", 30, 0, 3.)

    hPtLeptonPfcMatchedCorrectIdAll = TH1F("hPtLeptonPfcMatchedCorrectIdAll",
                                           "hPtLeptonPfcMatchedCorrectIdAll",
                                           30, 0, 3.)
    hPtLeptonPfcMatchedCorrectIdPass = TH1F(
        "hPtLeptonPfcMatchedCorrectIdPass", "hPtLeptonPfcMatchedCorrectIdPass",
        30, 0, 3.)

    hPtAllLeptonPfcMatchedCorrectIdAll = TH1F(
        "hPtAllLeptonPfcMatchedCorrectIdAll",
        "hPtAllLeptonPfcMatchedCorrectIdAll", 30, 0, 3.)
    hPtAllLeptonPfcMatchedCorrectIdPass = TH1F(
        "hPtAllLeptonPfcMatchedCorrectIdPass",
        "hPtAllLeptonPfcMatchedCorrectIdPass", 30, 0, 3.)

    handle_tracks = Handle("vector<reco::Track>")
    label_tracks = ('generalTracks')
    handle_pfcands = Handle("std::vector<reco::PFCandidate>")
    label_pfcands = ('particleFlow')
    handle_genparticles = Handle("vector<reco::GenParticle>")
    # 	label_genparticles = ('genParticlePlusGeant')
    label_genparticles = ('genParticles')

    nevents = events.size()
    # 	nevents = 100

    allChi20s = 0.
    passedTrackMatched = 0.
    passedPfcMatched = 0.
    passedOnePfcMatched = 0.

    for ievent, event in enumerate(events):

        if ievent >= nevents: break
        if ievent % 20 == 0:
            print('analyzing event %d of %d' % (ievent, nevents))

        event.getByLabel(label_tracks, handle_tracks)
        event.getByLabel(label_pfcands, handle_pfcands)
        event.getByLabel(label_genparticles, handle_genparticles)

        tracks = handle_tracks.product()
        pfcands = handle_pfcands.product()
        genparticles = handle_genparticles.product()

        for gp in genparticles:

            if not (abs(gp.pdgId()) == 11 or abs(gp.pdgId()) == 13): continue

            gpTlv = TLorentzVector()
            gpTlv.SetPxPyPzE(gp.px(), gp.py(), gp.pz(), gp.energy())

            hPtAllLeptonPfcMatchedCorrectIdAll.Fill(gp.pt())

            drmin = 10
            idx = -1
            for ipfc, pfc in enumerate(pfcands):
                pfcTlv = TLorentzVector()
                pfcTlv.SetPxPyPzE(pfc.px(), pfc.py(), pfc.pz(), pfc.energy())

                dr = pfcTlv.DeltaR(gpTlv)
                if dr < drmin:
                    drmin = dr
                    idx = ipfc

            if drmin < 0.02 and pfcands[idx].pdgId() == gp.pdgId():
                hPtAllLeptonPfcMatchedCorrectIdPass.Fill(gp.pt())

        for gp in genparticles:

            if not (abs(gp.pdgId()) == 1000023): continue

            decaylength = TMath.Sqrt(
                pow(gp.vx() - gp.daughter(0).vx(), 2) +
                pow(gp.vy() - gp.daughter(0).vy(), 2))
            logdecaylength = TMath.Log10(decaylength)

            hChi20StatusBefore.Fill(gp.status())
            hPtChi20Before.Fill(gp.pt())
            hLeptonsFound.Fill(0)

            if not decaylength > 0: continue

            ### GEN lepton finding ###

            zgammaDaughterFound = False
            oneleptonDaughterFound = False
            twoleptonDaughtersFound = False

            lepton1 = None
            lepton2 = None

            for i in range(gp.numberOfDaughters()):
                pdgIdDaughter = abs(gp.daughter(i).pdgId())

                if pdgIdDaughter > 1000000:
                    hPdgIdDaughtersSUSY.Fill(pdgIdDaughter % 1000000)
                else:
                    hPdgIdDaughters.Fill(pdgIdDaughter)

                if pdgIdDaughter == 22 or pdgIdDaughter == 23:
                    zgammaDaughterFound = True
                    zgamma = gp.daughter(i)
                    hPtZgamma.Fill(zgamma.pt())

                if pdgIdDaughter == 11 or pdgIdDaughter == 13:
                    if oneleptonDaughterFound:
                        twoleptonDaughtersFound = True
                        hLeptonsFound.Fill(1)
                        lepton2 = gp.daughter(i)
                        hPtZgamma.Fill(
                            TMath.Sqrt(
                                pow(lepton1.px() + lepton2.px(), 2) +
                                pow(lepton1.py() + lepton2.py(), 2)))
                    else:
                        oneleptonDaughterFound = True
                        lepton1 = gp.daughter(i)

                if zgammaDaughterFound or twoleptonDaughtersFound: break

            if zgammaDaughterFound and not oneleptonDaughterFound:

                for i in range(zgamma.numberOfDaughters()):
                    pdgIdDaughter = abs(zgamma.daughter(i).pdgId())

                    if pdgIdDaughter == 11 or pdgIdDaughter == 13:
                        if oneleptonDaughterFound:
                            twoleptonDaughtersFound = True
                            hLeptonsFound.Fill(2)
                            lepton2 = zgamma.daughter(i)
                        else:
                            oneleptonDaughterFound = True
                            lepton1 = zgamma.daughter(i)

                    if twoleptonDaughtersFound: break

            if not twoleptonDaughtersFound: continue
            if not lepton1.charge() * lepton2.charge() < 0: continue

            hChi20StatusAfter.Fill(gp.status())
            hPtChi20After.Fill(gp.pt())

            ### fill efficiency histos for 'All' ###

            allChi20s += 1

            hChi20LabLengthAll.Fill(decaylength)
            hChi20LabLengthPfcMatchedAll.Fill(decaylength)
            hChi20LabLengthOnePfcMatchedAll.Fill(decaylength)

            hChi20LogLabLengthAll.Fill(logdecaylength)
            hChi20LogLabLengthPfcMatchedAll.Fill(logdecaylength)
            hChi20LogLabLengthOnePfcMatchedAll.Fill(logdecaylength)

            ### fill GEN lepton histos ###

            lepton1Tlv = TLorentzVector()
            lepton1Tlv.SetPxPyPzE(lepton1.px(), lepton1.py(), lepton1.pz(),
                                  lepton1.energy())
            lepton2Tlv = TLorentzVector()
            lepton2Tlv.SetPxPyPzE(lepton2.px(), lepton2.py(), lepton2.pz(),
                                  lepton2.energy())

            hDrLeptonLepton.Fill(lepton1Tlv.DeltaR(lepton2Tlv))
            hLogDrLeptonLepton.Fill(TMath.Log10(lepton1Tlv.DeltaR(lepton2Tlv)))

            hInvMassLepton.Fill((lepton1Tlv + lepton2Tlv).M())
            hLogInvMassLepton.Fill(TMath.Log10((lepton1Tlv + lepton2Tlv).M()))

            ### lepton matching ###

            oneLeptonMatched = False
            twoLeptonsMatched = False
            oneLeptonPfcMatched = False
            twoLeptonsPfcMatched = False

            lepton1Matched = False
            lepton2Matched = False
            lepton1PfcMatched = False
            lepton2PfcMatched = False

            lepton1matchedPfcIdx = -1
            lepton2matchedPfcIdx = -1

            for lepton in (lepton1, lepton2):
                hLogTransverseDistLepton.Fill(
                    TMath.Log10(
                        TMath.Sqrt(pow(lepton.vx(), 2) + pow(lepton.vy(), 2))))

                leptonTlv = TLorentzVector()
                leptonTlv.SetPxPyPzE(lepton.px(), lepton.py(), lepton.pz(),
                                     lepton.energy())

                ### fill GEN lepton histos ###
                hEtaLepton.Fill(lepton.eta())
                hPtLepton.Fill(lepton.pt())
                hChi20LogLabLengthVsPtLepton.Fill(logdecaylength, lepton.pt())

                ### fill efficiency histos for 'All' ###
                hPtLeptonAll.Fill(lepton.pt())
                hPtLeptonPfcMatchedAll.Fill(lepton.pt())
                hPtLeptonPfcMatchedCorrectIdAll.Fill(lepton.pt())

                ### matching to PFcandidates ###
                drmin = 10
                idx = -1
                for ipfc, pfc in enumerate(pfcands):
                    pfcTlv = TLorentzVector()
                    pfcTlv.SetPxPyPzE(pfc.px(), pfc.py(), pfc.pz(),
                                      pfc.energy())

                    dr = pfcTlv.DeltaR(leptonTlv)
                    if dr < drmin:
                        drmin = dr
                        idx = ipfc

                if not idx == -1:
                    hPtPfcMatched.Fill(pfcands[idx].pt())
                    hDrLeptonPfc.Fill(drmin)

                    if drmin < 0.02:
                        hPtLeptonPfcMatchedPass.Fill(lepton.pt())
                        hParticleIdPfcMatched.Fill(pfcands[idx].particleId())

                        if pfcands[idx].pdgId() == lepton.pdgId():
                            hPtLeptonPfcMatchedCorrectIdPass.Fill(lepton.pt())

                        if lepton == lepton1:
                            lepton1PfcMatched = True
                            lepton1matchedPfcIdx = idx
                        if lepton == lepton2:
                            lepton2PfcMatched = True
                            lepton2matchedPfcIdx = idx

                        if oneLeptonPfcMatched: twoLeptonsPfcMatched = True
                        else: oneLeptonPfcMatched = True

                ### matching to tracks ###
                drmin = 10
                idx = -1
                for itrack, track in enumerate(tracks):
                    if track.numberOfValidHits() == 0: continue
                    if track.ndof() == 0: continue

                    trkTlv = TLorentzVector()
                    trkTlv.SetPxPyPzE(track.px(), track.py(), track.pz(),
                                      track.p())

                    dr = trkTlv.DeltaR(leptonTlv)
                    if dr < drmin:
                        drmin = dr
                        idx = itrack

                if not idx == -1:
                    hPtTrackMatched.Fill(tracks[idx].pt())
                    hDrLeptonTrack.Fill(drmin)

                    if drmin < 0.02:
                        hPtLeptonPass.Fill(lepton.pt())

                        if lepton == lepton1:
                            lepton1Matched = True
                        if lepton == lepton2:
                            lepton2Matched = True

                        if oneLeptonMatched: twoLeptonsMatched = True
                        else: oneLeptonMatched = True

            ### fill efficiency histos for 'Pass' ###

            if twoLeptonsMatched:

                passedTrackMatched += 1

                hChi20LabLengthPass.Fill(decaylength)
                hChi20LogLabLengthPass.Fill(logdecaylength)

            if twoLeptonsPfcMatched:

                passedPfcMatched += 1

                hChi20LabLengthPfcMatchedPass.Fill(decaylength)
                hChi20LogLabLengthPfcMatchedPass.Fill(logdecaylength)

                if lepton1matchedPfcIdx == lepton2matchedPfcIdx:
                    hSamePfcMatched.Fill(1)
                else:
                    hSamePfcMatched.Fill(0)

            if (lepton1Matched and lepton2PfcMatched) or \
             (lepton1PfcMatched and lepton2Matched) or \
             (lepton1PfcMatched and lepton2PfcMatched):

                passedOnePfcMatched += 1

                hChi20LabLengthOnePfcMatchedPass.Fill(decaylength)
                hChi20LogLabLengthOnePfcMatchedPass.Fill(logdecaylength)

    print('efficiencies:')
    print('both track matched: ', passedTrackMatched / allChi20s)
    print('both Pfc matched: ', passedPfcMatched / allChi20s)
    print('at least one Pfc matched: ', passedOnePfcMatched / allChi20s)

    ### write histos ###

    fnew.cd()

    # GEN chi20 histos
    hChi20StatusBefore.Write()
    hChi20StatusAfter.Write()
    hPdgIdDaughters.Write()
    hPdgIdDaughtersSUSY.Write()
    hPtChi20Before.Write()
    hPtChi20After.Write()
    hChi20LogLabLengthVsPtLepton.Write()

    # GEN lepton finding histos
    hLeptonsFound.Write()
    hPtZgamma.Write()
    hPtLepton.Write()
    hEtaLepton.Write()
    hLogTransverseDistLepton.Write()
    hDrLeptonLepton.Write()
    hLogDrLeptonLepton.Write()
    hInvMassLepton.Write()
    hLogInvMassLepton.Write()

    # lepton matching histos
    hDrLeptonPfc.Write()
    hDrLeptonTrack.Write()
    hSamePfcMatched.Write()
    hParticleIdPfcMatched.Write()
    hPtPfcMatched.Write()
    hPtTrackMatched.Write()

    # efficiency histos
    hChi20LabLengthAll.Write()
    hChi20LabLengthPass.Write()
    hChi20LogLabLengthAll.Write()
    hChi20LogLabLengthPass.Write()
    hChi20LabLengthPfcMatchedAll.Write()
    hChi20LabLengthPfcMatchedPass.Write()
    hChi20LogLabLengthPfcMatchedAll.Write()
    hChi20LogLabLengthPfcMatchedPass.Write()
    hChi20LabLengthOnePfcMatchedAll.Write()
    hChi20LabLengthOnePfcMatchedPass.Write()
    hChi20LogLabLengthOnePfcMatchedAll.Write()
    hChi20LogLabLengthOnePfcMatchedPass.Write()
    hPtLeptonAll.Write()
    hPtLeptonPass.Write()
    hPtLeptonPfcMatchedAll.Write()
    hPtLeptonPfcMatchedPass.Write()
    hPtLeptonPfcMatchedCorrectIdAll.Write()
    hPtLeptonPfcMatchedCorrectIdPass.Write()
    hPtAllLeptonPfcMatchedCorrectIdAll.Write()
    hPtAllLeptonPfcMatchedCorrectIdPass.Write()

    print('just created ' + fnew.GetName())
    fnew.Close()
            mytree.variables['meanDeltaRbtag'][0] = t.mean_dr_btag
            mytree.variables['meanCSVbtag'][0] = t.mean_bdisc
            mytree.variables['meanCSV'][0] = t.mean_bdisc_btag
            mytree.variables['btagLR3b'][0] = t.btag_LR_3b_2b_btagCSV
            mytree.variables['btagLR4b'][0] = t.btag_LR_4b_2b_btagCSV
            mytree.variables['nBCSVM'][0] = t.nBCSVM

            qgLR3b = t.qg_LR_3b_flavour_5q_0q
            qgLR4b = t.qg_LR_4b_flavour_5q_0q

            #                  mytree.variables['memttbb'][0]  = max(t.mem_ttbb_FH_4w2h1t_p/(t.mem_tth_FH_4w2h1t_p) if t.mem_tth_FH_4w2h1t_p > 0 else -10,t.mem_ttbb_FH_4w2h2t_p/(t.mem_tth_FH_4w2h2t_p) if t.mem_tth_FH_4w2h2t_p > 0 else -10)

            if nbjets == 3:
                mytree.variables['qgLR'][0] = qgLR3b
                if t.mem_ttbb_FH_4w2h1t_p > 0:
                    mytree.variables['memttbb'][0] = -TMath.Log10(
                        t.mem_ttbb_FH_4w2h1t_p)
                else:
                    mytree.variables['memttbb'][0] = -10
                #print mytree.variables['memttbb'][0]
                # if nljets == 4:
                #       mytree.variables['qgLR'][0] = t.qg_LR_3b_flavour_4q_0q
                # elif nljets >= 5:
                #       mytree.variables['qgLR'][0] = t.qg_LR_3b_flavour_5q_0q
            if nbjets >= 4:
                mytree.variables['qgLR'][0] = qgLR4b
                if t.mem_ttbb_FH_4w2h2t_p > 0:
                    mytree.variables['memttbb'][0] = -TMath.Log10(
                        t.mem_ttbb_FH_4w2h2t_p)
                else:
                    mytree.variables['memttbb'][0] = -10
                #print mytree.variables['memttbb'][0]
Esempio n. 15
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
Esempio n. 16
0
def recchar():

    #reconstruction characteristics

    #tagger configuration
    #config = "recchar_s1.ini"
    config = "recchar_s2.ini"

    cf = read_con(config)

    #tagger parametrization
    xpos = cf("xpos")
    zpos = cf("zpos")
    rot_y = cf("rot_y")
    zmin = cf("zmin")

    can = ut.box_canvas(3 * 768)
    can.Divide(3, 1)
    hXY = ut.prepare_TH2D("hXY", cf("xybin"), -cf("xsiz") / 2.,
                          cf("xsiz") / 2., cf("xybin"), -cf("ysiz") / 2.,
                          cf("ysiz") / 2.)
    hET = ut.prepare_TH2D("hET", cf("tbin"), cf("tmin"), cf("tmax"),
                          cf("ebin"), cf("emin"), cf("emax"))
    hQ2 = ut.prepare_TH1D("hQ2", cf("qbin"), cf("qmin"), cf("qmax"))

    #numerical minima and maxima
    xlo = 1e9
    xhi = -1e9
    ylo = 1e9
    yhi = -1e9
    elo = 1e9
    ehi = -1e9
    tlo = 1e9
    thi = -1e9
    qlo = 1e9
    qhi = -1e9

    nevt = tree.GetEntries()
    #nevt = 1200

    hits = BoxCalV2Hits(cf.str("name"), tree)
    gROOT.ProcessLine("struct Entry {Double_t v;};")
    true_el_theta = rt.Entry()
    true_el_E = rt.Entry()
    true_Q2 = rt.Entry()
    tree.SetBranchAddress("true_el_theta", AddressOf(true_el_theta, "v"))
    tree.SetBranchAddress("true_el_E", AddressOf(true_el_E, "v"))
    tree.SetBranchAddress("true_Q2", AddressOf(true_Q2, "v"))

    for ievt in xrange(nevt):
        tree.GetEntry(ievt)

        nhsel = 0

        for ihit in xrange(hits.GetN()):

            hit = hits.GetHit(ihit)
            hit.GlobalToLocal(xpos, 0, zpos, rot_y)

            if hit.z < zmin: continue

            nhsel += 1

        #just one selected hit
        if nhsel != 1: continue

        #hit coordinats on front of the tagger
        hXY.Fill(hit.x, hit.y)

        if hit.x < xlo: xlo = hit.x
        if hit.y < ylo: ylo = hit.y

        if hit.x > xhi: xhi = hit.x
        if hit.y > yhi: yhi = hit.y

        #true electron energy and angle for the hit
        en = true_el_E.v
        lt = -TMath.Log10(TMath.Pi() - true_el_theta.v)
        hET.Fill(lt, en)

        if en < elo: elo = en
        if en > ehi: ehi = en

        if lt < tlo: tlo = lt
        if lt > thi: thi = lt

        #event true Q^2
        lq = TMath.Log10(true_Q2.v)
        hQ2.Fill(lq)

        if lq < qlo: qlo = lq
        if lq > qhi: qhi = lq

    print "xlo:", xlo, "xhi:", xhi, "ylo:", ylo, "yhi:", yhi
    print "elo:", elo, "ehi:", ehi, "tlo:", tlo, "thi:", thi
    print "qlo:", qlo, "qhi:", qhi

    ut.put_yx_tit(hXY, "#it{y} (mm)", "#it{x} (mm)")
    hXY.SetMinimum(0.98)
    hXY.SetContour(300)

    ut.put_yx_tit(hET, "#it{E} (GeV)", "-log_{10}(#pi-#theta) (rad)")
    hET.SetMinimum(0.98)
    hET.SetContour(300)

    ut.put_yx_tit(hQ2, "Counts", "log_{10}(#it{Q}^{2}) (GeV^{2})")
    ut.line_h1(hQ2, rt.kBlue)

    can.cd(1)
    ut.set_margin_lbtr(gPad, 0.11, 0.08, 0.01, 0.12)
    hXY.Draw()
    gPad.SetGrid()
    gPad.SetLogz()

    can.cd(2)
    ut.set_margin_lbtr(gPad, 0.11, 0.09, 0.02, 0.12)
    hET.Draw()
    gPad.SetGrid()
    gPad.SetLogz()

    can.cd(3)
    ut.set_margin_lbtr(gPad, 0.11, 0.09, 0.02, 0.12)
    hQ2.Draw()
    gPad.SetGrid()

    #ut.invert_col(rt.gPad)
    ut.invert_col_can(can)
    can.SaveAs("01fig.pdf")