def profile_plots(pt_array, ntrk_array, weight, gluon_pt_array,
                  gluon_ntrk_array, gluon_weight_array, quark_pt_array,
                  quark_ntrk_array, quark_weight_array, islogpt):
    #gStyle.SetOptFit()
    print 'total events: ' + str(len(pt_array))
    print 'gluons: ' + str(len(gluon_pt_array))
    print 'quarks: ' + str(len(quark_pt_array))
    c1 = TCanvas('c1', '', 200, 10, 700, 500)
    fittype = 'pol1'
    if islogpt:
        ptmin = 4
        ptmax = 7
        nbins = 10
    else:
        ptmin = 0
        ptmax = 1300
        nbins = 10
    hquark = TProfile('hquark', 'Quark Profile of nTrk vs ln(pt)', nbins,
                      ptmin, ptmax, ntrkmin, ntrkmax)
    weighted_hquark = TProfile('weighted_hquark',
                               'Quark Weighted Profile of nTrk vs ln(pt)',
                               nbins, ptmin, ptmax, ntrkmin, ntrkmax)
    count = 0
    for i, j, k in zip(quark_pt_array, quark_ntrk_array, quark_weight_array):
        count += 1
        if count % 100000 == 0:
            print 'processed ' + str(count)
        hquark.Fill(i, j)
        weighted_hquark.Fill(i, j, k)

    draw_hist_with_tag_eff(hquark, "quark", quark_pt_array, quark_ntrk_array,
                           gluon_pt_array, gluon_ntrk_array)
    draw_hist_with_tag_eff(weighted_hquark, "weightedquark", quark_pt_array,
                           quark_ntrk_array, gluon_pt_array, gluon_ntrk_array)

    hgluon = TProfile('hgluon', 'Gluon Profile of nTrk vs ln(pt)', nbins,
                      ptmin, ptmax, ntrkmin, ntrkmax)
    weighted_hgluon = TProfile('weighted_hgluon',
                               'Gluon Weighted Profile of nTrk vs ln(pt)',
                               nbins, ptmin, ptmax, ntrkmin, ntrkmax)
    for i, j, k in zip(gluon_pt_array, gluon_ntrk_array, gluon_weight_array):
        hgluon.Fill(i, j)
        weighted_hgluon.Fill(i, j, k)

    draw_hist_with_tag_eff(hgluon, "gluon", quark_pt_array, quark_ntrk_array,
                           gluon_pt_array, gluon_ntrk_array)
    draw_hist_with_tag_eff(weighted_hgluon, "weightedgluon", quark_pt_array,
                           quark_ntrk_array, gluon_pt_array, gluon_ntrk_array)

    c3 = TCanvas('c3', '', 200, 10, 700, 500)
    weighted_hquark.SetMaximum(30)
    weighted_hquark.Draw("HIST")
    weighted_hgluon.Draw("HIST SAME")
    weighted_hquark.SetLineColor(2)

    c3.SaveAs(settings.outputdir + '/overlay.pdf')
Exemple #2
0
def staff():

    FitParam = ROOT.FitParameters_t()
    f = TFile("FitParam.root", "RECREATE")
    tree = TTree('T', "Fitparameters from main program")
    tree.Branch("FitParam", FitParam, 'Drift_Velocity:Fit_Gradient')

    fname = "test.txt"

    hdv = TH1F("hdv", "Drift Velocity Distribution", 100, 0.002615, 0.002645)
    hfg = TH1F("hfg", "Track Angle Distribution", 100, 0, 0.3)
    hprof = TProfile("hprof", "Profile of Drift Velocity vs Track Angle", 100,
                     0.002615, 0.002645, 0, 0.3)

    histos = ['hdv', 'hfg', 'hprof']
    for name in histos:
        exec('%sFill = %s.Fill' % (name, name))

    for line in open(fname).readlines():
        t = list(filter(lambda x: x, re.split(',', line)))
        FitParam.Drift_Velocity = float(t[0])
        FitParam.Fit_Gradient = float(t[1])
        hdv.Fill(float(t[0]))
        hfg.Fill(float(t[1]))
        hprof.Fill(float(t[0]), float(t[1]))

        tree.Fill()

    c1 = TCanvas("c1", "Drift Velocity Histogram", 200, 10, 700, 500)
    c1.SetGridx()
    c1.SetGridy()
    hdv.Print()
    hdv.Draw()

    c1.Modified()
    c1.Update()

    c2 = TCanvas("c2", "Angular Distribution Histogram", 200, 10, 700, 500)
    c2.SetGrid()
    hfg.Print()
    hfg.Draw()
    c2.Modified()
    c2.Update()

    c3 = TCanvas("c3", "Profile", 200, 10, 700, 500)
    hprof.Print()
    hprof.Draw()
    c3.Modified()
    c3.Update()

    tree.Print()
    tree.Write()

    for name in histos:
        exec('del %sFill' % name)
    del histos

    x = input("Enter any key to continue")
def plotting_init(data, trainvar, histo_dict, masses, weights='totalWeight'):
    """ Initializes the plotting

    Parameters:
    -----------
    data : pandas DataFrame
        Data to be used for creating the TProfiles
    trainvar : str
        Name of the training variable.
    histo_dict : dict
        Dictionary containing the info for plotting for a given trainvar
    masses : list
        List of masses to be used
    [weights='totalWeight'] : str
        What column to be used for weight in the data.

    Returns:
    --------
    canvas : ROOT.TCanvas instance
        canvas to be plotted on
    profile : ROOT.TProfile instance
        profile for the fitting
    """
    canvas = TCanvas('canvas', 'TProfile plot', 200, 10, 700, 500)
    canvas.GetFrame().SetBorderSize(6)
    canvas.GetFrame().SetBorderMode(-1)
    signal_data = data.loc[data['target'] == 1]
    gen_mHH_values = np.array(signal_data['gen_mHH'].values, dtype=np.float)
    trainvar_values = np.array(signal_data[trainvar].values, dtype=np.float)
    weights = np.array(signal_data[weights].values, dtype=np.float)
    sanity_check = len(gen_mHH_values) == len(trainvar_values) == len(weights)
    assert sanity_check
    title = 'Profile of ' + str(trainvar) + ' vs gen_mHH'
    num_bins = (len(masses) - 1)
    xlow = masses[0]
    xhigh = (masses[(len(masses) - 1)] + 100.0)
    ylow = histo_dict["min"]
    yhigh = histo_dict["max"]
    profile = TProfile('profile', title, num_bins, xlow, xhigh, ylow, yhigh)
    mass_bins = np.array(masses, dtype=float)
    profile.SetBins((len(mass_bins) - 1), mass_bins)
    profile.GetXaxis().SetTitle("gen_mHH (GeV)")
    profile.GetYaxis().SetTitle(str(trainvar))
    for x, y, w in zip(gen_mHH_values, trainvar_values, weights):
        profile.Fill(x, y, w)
    profile.Draw()
    canvas.Modified()
    canvas.Update()
    return canvas, profile
Exemple #4
0
def plotPulls(optunf="Bayes",
              ntest=10,
              leff=True,
              loufl=False,
              optfun="exp",
              opttfun="",
              gmean=-1.0,
              nrebin=4):

    if opttfun == "":
        opttfun = optfun

    if optfun == "blobel":
        gmean = 0.0

    funttxt, funtxt = funtxts(opttfun, optfun, leff, loufl)

    global histos, canv, canv2
    histos = []

    canv = TCanvas("canv", "thruth vs reco pulls", 600, 800)
    canv.Divide(1, 3)
    canv2 = TCanvas("canv2", "P(chi^2)", 600, 800)
    canv2.Divide(2, 3)

    if optunf == "BasisSplines":
        bininfo = BinInfo(nrebin)
        unfoldtester = UnfoldTester(optunf, nrebin)
    else:
        bininfo = BinInfo()
        unfoldtester = UnfoldTester(optunf)
    trainer = Trainer(bininfo, opttfun, optfun)
    tester = Tester(bininfo, optfun)
    hbininfo = bininfo.create(optfun)
    dx = hbininfo["mhi"]
    for sigma, ipad in [[0.01 * dx, 1], [0.03 * dx, 2], [0.1 * dx, 3]]:
        txt = optunf + ", smear mu, s.d.= " + str(gmean) + ", " + str(
            sigma) + ", train: " + funttxt + ", test: " + funtxt + ", " + str(
                ntest) + " tests"
        hPulls = TProfile("pulls", txt, hbininfo["tbins"], hbininfo["tlo"],
                          hbininfo["thi"])
        hPulls.SetErrorOption("s")
        hPulls.SetYTitle("Thruth reco pull")
        histos.append(hPulls)
        hChisq = TH1D("chisq", "P(chi^2) rec " + txt, 10, 0.0, 1.0)
        hChisqm = TH1D("chisqm", "P(chi^2) mea " + txt, 10, 0.0, 1.0)
        histos.append(hChisq)
        histos.append(hChisqm)
        measurement = createMeasurement(gmean, sigma, leff, optfun)
        response = trainer.train(measurement, loufl=loufl)
        for itest in range(ntest):
            print "Test", itest
            unfold, hTrue, hMeas = unfoldtester.rununfoldtest(
                tester, measurement, response)
            unfold.PrintTable(cout, hTrue, 2)
            hReco = unfold.Hreco(2)
            nbin = hReco.GetNbinsX()
            if hbininfo["nrebin"] > 1:
                hTrue = hTrue.Rebin(nrebin)
            for ibin in range(nbin + 1):
                truevalue = hTrue.GetBinContent(ibin)
                recvalue = hReco.GetBinContent(ibin)
                error = hReco.GetBinError(ibin)
                if error > 0.0:
                    pull = (recvalue - truevalue) / error
                    hPulls.Fill(hReco.GetBinCenter(ibin), pull)
            chisq = unfold.Chi2(hTrue, 2)
            hChisq.Fill(TMath.Prob(chisq, hTrue.GetNbinsX()))
            chisqm = unfold.Chi2measured()
            pchisqm = TMath.Prob(chisqm, hMeas.GetNbinsX() - hReco.GetNbinsX())
            print "Chisq measured=", chisqm, "P(chi^2)=", pchisqm
            hChisqm.Fill(pchisqm)

        canv.cd(ipad)
        gStyle.SetErrorX(0)
        hPulls.SetMinimum(-3.0)
        hPulls.SetMaximum(3.0)
        hPulls.SetMarkerSize(1.0)
        hPulls.SetMarkerStyle(20)
        hPulls.SetStats(False)
        hPulls.Draw()
        canv2.cd(ipad * 2 - 1)
        hChisq.Draw()
        canv2.cd(ipad * 2)
        hChisqm.Draw()

    fname = "RooUnfoldTestPulls_" + optunf + "_" + opttfun + "_" + optfun
    if loufl:
        fname += "_oufl"
    canv.Print(fname + ".pdf")
    fname = "RooUnfoldTestChisq_" + optunf + "_" + opttfun + "_" + optfun
    if loufl:
        fname += "_oufl"
    canv2.Print(fname + ".pdf")

    return
Exemple #5
0
# In[12]:
hpxpy.Draw('COLZ')
c2.Modified()
c2.Update()
c2.Draw()
# In[13]:
hpxpy.Draw('LEGO')
c2.Modified()
c2.Update()
c2.Draw()
# In[14]:
c3 = gROOT.FindObject('c3')
if c3:
    c3 = 0
c3 = TCanvas('c3', 'c3', 200, 10, 700, 500)
hprof.Draw()
c3.Modified()
c3.Update()
c3.Draw()
# In[15]:
c4 = gROOT.FindObject('c4')
if c4:
    c4 = 0
c4 = TCanvas('c4', 'c4', 200, 10, 700, 500)
c4.Divide(2, 2)
c4.cd(1)
ntuple.Draw("pz:px")
c4.cd(2)
ntuple.Draw("pz:py")
c4.cd(3)
ntuple.Draw("pz:px*px + py*py")
Exemple #6
0
def main():
    parser = ArgumentParser(description='Scan over ROOT files to find the '+ \
                            'lumisections belonging to a specific run.')
    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('-n', nargs=1, default=1, type=int, help='Specify '+ \
                        'the number of ZeroBias datasets to be included')
    parser.add_argument('-run', nargs=1, required=True, type=int, \
                        help='Specify the run number for the selection of '+ \
                        'the lumisections')
    parser.add_argument('-range', nargs=2, type=int, help='Specify a range '+ \
                        'in lumisections for the histogram')
    parser.add_argument('-X', dest='coords', action='append_const', \
                        const='vtx_x', help='look for vtx_x')
    parser.add_argument('-Y', dest='coords', action='append_const', \
                        const='vtx_y', help='look for vtx_y')
    parser.add_argument('-noscan', action='store_const', const=True, \
                        default=False, help='don\'t repeat the scan of the '+ \
                        'ROOT files, just do the plotting')
    parser.add_argument('-title', nargs=1, help='Specify a title for the '+ \
                        'histogram')
    args = parser.parse_args()

    from importlib import import_module
    from lsctools import config
    from lsctools.config import options as O, EOSPATH as eos
    from lsctools.tools import openRootFileU, closeRootFile, writeFiles, \
                               plotName, plotTitle, loadFiles, plotPath, \
                               drawSignature
    from lsctools.prepare import loopOverRootFiles
    from ROOT import TChain, TObject, TProfile, TCanvas, gStyle, gPad
    getattr(config, 'PCC' + args.dataset)()
    O['fulltrees'] = O['fulltrees'][:args.n]
    run = args.run[0]
    files = []
    if args.noscan:
        files = loadFiles('fulltrees_' + str(run))
    else:

        def action(tree, filename):
            condition = 'run == ' + str(run)
            if tree.GetEntries(condition) > 0:
                files.append(filename)
                print '<<< Found file:', filename

        loopOverRootFiles(action, 'fulltrees')
        writeFiles(files, 'fulltrees_' + str(run))
    chain = TChain(O['treename']['fulltrees'])
    for filename in files:
        chain.Add(eos + filename)
    name = 'vtxPos_perLS'
    title1 = 'run' + str(run) + '_perLS'
    title2 = 'Run ' + str(run)
    if (args.title):
        title2 = args.title[0] + ' (' + title2 + ')'
    f = openRootFileU(name)
    if args.range:
        mini = args.range[0]
        maxi = args.range[1]
        title1 += '_from' + str(mini) + 'to' + str(maxi)
    else:
        print '<<< Get minimum lumisection'
        mini = int(chain.GetMinimum('LS'))
        print '<<< Get maximum lumisection'
        maxi = int(chain.GetMaximum('LS'))
    for coord in args.coords:
        print '<<< Analyze coordinate', coord
        histname = plotName(coord + '_' + title1, timestamp=False)
        histtitl = plotTitle('- ' + title2)
        histfile = plotName(coord + '_' + title1)
        histpath = plotPath(coord + '_' + title1)
        hist = TProfile(histname, histtitl, maxi - mini + 1, mini - 0.5,
                        maxi + 0.5)
        chain.Draw(coord + '*1e4:LS>>' + histname, 'run == ' + str(run),
                   'goff')
        hist.Write('', TObject.kOverwrite)
        print '<<< Save plot:', histpath
        canvas = TCanvas()
        gStyle.SetOptStat(0)
        hist.Draw()
        hist.GetXaxis().SetTitle('LS')
        hist.GetYaxis().SetTitle(coord + ' [#mum]')
        hist.GetYaxis().SetTitleOffset(1.2)
        for axis in [hist.GetXaxis(), hist.GetYaxis()]:
            axis.SetTitleFont(133)
            axis.SetTitleSize(16)
            axis.SetLabelFont(133)
            axis.SetLabelSize(12)
            axis.CenterTitle()
        drawSignature(histfile)
        gPad.Modified()
        gPad.Update()
        canvas.Print(histpath)
        canvas.Close()
    closeRootFile(f, name)
Exemple #7
0
def showENC():
    fname1 = '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat'

    tree1 = TTree()
    tree1.ReadFile(
        '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat',
        'idX/i:vL/F:vH:A:D/i:R:W')
    tree1.ReadFile(
        '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan2_mod.dat'
    )

    tree1.Show(500)

    p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', 50, 0.12, 0.2)
    tree1.Draw("D:(vH-vL)>>p1", "", "profE")

    ### change it to tgraph
    g1 = TGraphErrors()
    for i in range(p1.GetNbinsX() + 2):
        N = p1.GetBinEntries(i)
        if N > 0:
            print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(
                i), p1.GetBinError(i)
            n = g1.GetN()
            g1.SetPoint(n, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i))
            g1.SetPointError(n, 0, p1.GetBinError(i))


#     g1.SetMarkerColor(3)
#     g1.SetLineColor(3)

    p1.Draw("axis")
    g1.Draw('Psame')

    fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))',
               0.05, 0.3)
    fun1.SetParameter(0, 0.155)
    fun1.SetParameter(1, 0.005)

    g1.Fit(fun1)
    fun1a = g1.GetFunction('fun1')

    #     p1.Fit(fun1)
    #     fun1a = p1.GetFunction('fun1')
    fun1a.SetLineColor(2)

    #     p1.Draw("Esame")

    v0 = fun1a.GetParameter(0)
    e0 = fun1a.GetParError(0)
    v1 = fun1a.GetParameter(1)
    e1 = fun1a.GetParError(1)

    print v0, v1

    fUnit = 1000.
    lt = TLatex()
    lt.DrawLatexNDC(
        0.185, 0.89,
        '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit))
    lt.DrawLatexNDC(
        0.185, 0.84,
        '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit))

    print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)
    fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1))
    fun2.SetLineColor(4)
    fun2.SetLineStyle(2)
    fun2.Draw('same')

    lg = TLegend(0.7, 0.4, 0.95, 0.5)
    lg.SetFillStyle(0)
    lg.AddEntry(p1, 'Measurement', 'p')
    lg.AddEntry(fun1a, 'Fit', 'l')
    lg.AddEntry(fun2, 'Gaus', 'l')
    lg.Draw()

    waitRootCmdX()
Exemple #8
0
    def showENC(self):
        tree1 = TTree()
        header = 'idX/i:vL/F:vH:A:D/i:R:W'
        first = True
        for f in self.dataFiles:
            if first: tree1.ReadFile(f, header)
            else: tree1.ReadFile(f)

        p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', self.bins[0],
                      tree1.GetMinimum('vH-vL') * 0.8,
                      tree1.GetMaximum('vH-vL') * 1.2)
        tree1.Draw("D:(vH-vL)>>p1", "", "profE")

        ### change it to tgraph
        g1 = TGraphErrors()
        for i in range(p1.GetNbinsX() + 2):
            N = p1.GetBinEntries(i)
            if N > 0:
                print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(
                    i), p1.GetBinError(i)
                n = g1.GetN()
                g1.SetPoint(n,
                            p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i))
                g1.SetPointError(n, 0, p1.GetBinError(i))

        p1.Draw("axis")
        g1.Draw('Psame')

        fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))',
                   0.05, 0.3)
        fun1.SetParameter(0, 0.155)
        fun1.SetParameter(1, 0.005)

        g1.Fit(fun1)
        fun1a = g1.GetFunction('fun1')

        fun1a.SetLineColor(2)

        v0 = fun1a.GetParameter(0)
        e0 = fun1a.GetParError(0)
        v1 = fun1a.GetParameter(1)
        e1 = fun1a.GetParError(1)

        print v0, v1

        fUnit = 1000.
        self.lt.DrawLatexNDC(
            0.185, 0.89,
            '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit))
        self.lt.DrawLatexNDC(
            0.185, 0.84,
            '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit))
        if self.Info:
            self.lt.DrawLatexNDC(0.185, 0.6, self.Info)

        print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)
        fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1))
        fun2.SetLineColor(4)
        fun2.SetLineStyle(2)
        fun2.Draw('same')

        lg = TLegend(0.7, 0.4, 0.95, 0.5)
        lg.SetFillStyle(0)
        lg.AddEntry(p1, 'Measurement', 'p')
        lg.AddEntry(fun1a, 'Fit', 'l')
        lg.AddEntry(fun2, 'Gaus', 'l')
        lg.Draw()

        waitRootCmdX()
Exemple #9
0
effsSignal = computeEff(namesSignal)

for name in namesBackground:
    print "running on background sample", name
    os.system("./Run.sh \"" + name + "\"" + " \"" +
              str(startingParallelDiffCut) + "\"")

effsBackground = computeEff(namesBackground)

# Draw the histogram
from ROOT import gROOT, TCanvas, TH1F, TProfile

gROOT.Reset()
c1 = TCanvas('c1', '<eff(signal)>/sqrt(eff(background))')

#
# Create a one dimensional function and draw it
#

histo = TProfile('effSoverSqrtEffB', '<eff(signal)>/sqrt(eff(background))',
                 int(len(effsSignal)), float(sorted(effsSignal.iterkeys())[0]),
                 float(sorted(effsSignal.iterkeys())[len(effsSignal) - 1]))
for key in sorted(effsSignal.iterkeys()):
    print "eff(signal)/sqrt(eff(background))[" + key + "] =", effsSignal[
        key] / math.sqrt(effsBackground[key])
    histo.Fill(float(key), effsSignal[key] / math.sqrt(effsBackground[key]))
histo.Draw()
histo.SetXTitle("parallelism cut")
c1.SaveAs("canvas.pdf")
        print("Processed %d of %d events..." % (ievent, NEntries))

    ntuple.GetEntry(ievent)

    n_weight = ntuple.__getattr__('weight')
    n_ptPruned = ntuple.__getattr__('ptPruned')
    if (170 < n_ptPruned < 1000):
        x.append(n_ptPruned)
        y.append(n_weight)
        print(n_weight)
        hprof2d.Fill(n_ptPruned, n_weight)

# hprof2d.LabelsOption("h","pT")
hprof2d.SetMinimum(-0.2)
hprof2d.SetMaximum(0.3)
hprof2d.Draw()

c.SaveAs("old2dhist.png")

# # H = verification
# nbins = 100
# # xedges = 101
# # yedges =4
# H, xedges, yedges = np.histogram2d(x,y,bins=nbins)
#
# # print (xedges)
# print (yedges)
# # H= H.T
# # print (H)
# # verification = H
# # print (verification)
Exemple #11
0
def loop(fname):
    genPars = Handle("vector<reco::GenParticle>")
    genParsLabel = "prunedGenParticles"

    gPar = [Handle("vector<pat::PackedGenParticle>"), "packedGenParticles"]
    vertices = [
        Handle("vector<reco::Vertex>"), "offlineSlimmedPrimaryVertices"
    ]

    mus = [Handle("vector<pat::Muon>"), "slimmedMuons"]

    sip2d = TH1F("SIP2D", "SIP2D", 40, -10., 10.)
    sip3d = TH1F("SIP3D", "SIP3D", 40, -10., 10.)
    sipxy = TH1F("tk2d", "TK SIPXY", 40, -10., 10.)
    sipz = TH1F("tk3z", "TK SIPZ", 40, -10., 10.)

    sip3d_l = TH1F("SIP2D l", "SIP2D l", 40, -10., 10.)
    sip3d_h = TH1F("SIP2D h", "SIP2D h", 40, -10., 10.)
    sip3d_best = TH1F("SIP2D best", "SIP2D best", 40, -10., 10.)
    vert = TH1F("zpv", "zpv", 100, -10., 10.)
    sip_v = TProfile("SIP2D vs zpv", "SIP2D best vs zpv", 50, 0., 5., 0., 10.)
    #
    eventsRef = Events(fname)
    nw = 0
    nehpt = 0
    nwhpt = 0
    nech = 0
    nwch = 0
    #
    for i in range(0, eventsRef.size()):
        a = eventsRef.to(i)
        print "Event", i
        a = eventsRef.getByLabel(genParsLabel, genPars)
        zpv = 0
        gpvp = genPars.product()[0].vertex()
        for part in genPars.product():
            if (part.vz() != 0):
                zpv = part.vz()
                gpvp = part.vertex()
                break
        print "zpv ", zpv
        #
        nmu = 0
        nel = 0
        nch1 = 0
        nch2 = 0
        gmu = []
        for part in genPars.product():
            if (part.status() != 1): continue
            if (abs(part.pdgId()) == 13 and part.pt() > 5
                    and abs(part.eta()) < 2.4):
                gmu.append((part.phi(), part.eta(), part.charge() * part.pt()))
            if (abs(part.pdgId()) == 13 and part.pt() > 5
                    and abs(part.eta()) < 2.4):
                nmu += 1
            if (abs(part.pdgId()) == 11 and part.pt() > 7
                    and abs(part.eta()) < 2.4):
                nel += 1
            if (abs(part.pdgId()) == 13 and part.pt() > 8
                    and abs(part.eta()) < 2.4):
                nch1 += 1
            if (abs(part.pdgId()) == 11 and part.pt() > 10
                    and abs(part.eta()) < 2.4):
                nch1 += 1
            if (abs(part.pdgId()) == 13 and part.pt() > 20
                    and abs(part.eta()) < 2.4):
                nch2 += 1
            if (abs(part.pdgId()) == 11 and part.pt() > 20
                    and abs(part.eta()) < 2.4):
                nch2 += 1
            #    if (abs(part.pdgId())==13):
            #        print "part", part.phi(),part.eta(), part.pt(), part.vz(), part.vx(), part.vy(), part.mass(), part.pdgId(), part.status()
        #  print "nmu ", nmu,nel
        #  print gmu
        a = eventsRef.getByLabel(vertices[1], vertices[0])
        minz = 99999.
        iv = 0
        ii = 0
        pv = vertices[0].product()[0]
        pvp = vertices[0].product()[0].position()
        nv = vertices[0].product().size()
        for v in vertices[0].product():
            if (abs(v.z() - zpv) < minz):
                minz = abs(v.z() - zpv)
                iv = ii
            ii += 1
        print "pv ", iv, minz
        if (iv != 0): nw += 1
        #   if (nmu+nel>3) :
        if (nmu > 1):
            nehpt += 1
            if (iv != 0): nwhpt += 1
        #    if (nch1>0 and nch2>0) :
        if (nch1 < 1): continue
        #
        nech += 1
        if (iv != 0): nwch += 1
        a = eventsRef.getByLabel(mus[1], mus[0])
        pmus = []
        for mu in mus[0].product():
            if (mu.pt() < 5): continue
            #         if (  mu.isTrackerMuon() or mu.isGlobalMuon()) :
            if (mu.isGlobalMuon()):
                pmus.append(
                    (mu.phi(), mu.eta(), mu.pt() * mu.charge(),
                     mu.dB(2) / mu.edB(2), mu.dB(1) / mu.edB(1),
                     mu.track().dxy(gpvp) / mu.track().dxyError(),
                     mu.track().dz(gpvp) / mu.track().dzError(),
                     mu.track().hitPattern().pixelLayersWithMeasurement()))
                #        print 'mu', iv, mu.phi(), mu.eta(), mu.pt(), mu.dB(2)/mu.edB(2), mu.dB(1)/mu.edB(1), mu.isTrackerMuon(), mu.isGlobalMuon()
        #     print pmus
        matches = []
        i = 0
        for g in gmu:
            j = 0
            for mu in pmus:
                j += 1
                if (g[2] / mu[2] < 0.5 or g[2] / mu[2] > 2.0): continue
                dr = dR2(g[0], g[1], mu[0], mu[1])
                if (dr > 0.04): continue
                matches.append((i, j - 1, dr, abs(1. - g[2] / mu[2])))
                #print "matched mu", mu
            i += 1
        if (len(matches) < 1): continue

        vert.Fill((pv.z() - zpv) / pv.zError())

        k = matches[0][0]
        best = 99999
        dr = 999999
        for m in matches:
            #            if (abs(pv.z()-zpv)<3*pv.zError()) :
            if (pmus[m[1]][7] > 2):
                # if (nv<21) :
                sip3d_l.Fill(pmus[m[1]][3])
            else:
                sip3d_h.Fill(pmus[m[1]][3])
            sip2d.Fill(pmus[m[1]][4])
            sip3d.Fill(pmus[m[1]][3])
            sipxy.Fill(pmus[m[1]][5])
            sipz.Fill(pmus[m[1]][6])
            sip_v.Fill(abs(pv.z() - zpv) / pv.zError(), abs(pmus[m[1]][5]))
            if (m[0] != k):
                sip3d_best.Fill(best)
                k = m[0]
                best = pmus[m[1]][4]
                dr = m[3]
            else:
                if (m[3] < dr):
                    dr = m[3]
                    best = pmus[m[1]][4]
        if (dr < 9999): sip3d_best.Fill(best)

    print "wrong pv", nw, nehpt, nwhpt, nech, nwch

    c1 = TCanvas('c1', fname, 200, 10, 1000, 1400)
    gStyle.SetOptStat(111111)
    gStyle.SetHistLineWidth(2)
    c1.Divide(2, 4)
    c1.cd(1).SetLogy()
    sip2d.DrawNormalized()
    e = TF1("q", "0.5*exp(-0.5*x*x)/sqrt(6.28)", -10., 10.)
    e.Draw("same")
    c1.cd(2).SetLogy()
    sip3d.DrawNormalized()
    e.Draw("same")
    c1.cd(3).SetLogy()
    sipxy.DrawNormalized()
    e.Draw("same")
    c1.cd(4).SetLogy()
    sipz.DrawNormalized()
    e.Draw("same")
    c1.cd(5).SetLogy()
    sip3d_l.DrawNormalized()
    e.Draw("same")
    c1.cd(6).SetLogy()
    sip3d_h.DrawNormalized()
    e.Draw("same")

    #    sip3d_best.DrawNormalized()
    c1.cd(7).SetLogy()
    vert.DrawNormalized()
    #    ev = TF1("qv","0.2*exp(-0.5*x*x)/sqrt(6.28)",-10.,10.)
    #    ev.Draw("same")
    c1.cd(8)
    sip_v.Draw()

    c1.Print("sipall" + fname + ".png")
Exemple #12
0
nameY = "pT-pT(true)/pT(true)"
h = gPad.DrawFrame(Xmin, Ymin, Xmax, Ymax)
ax = h.GetXaxis()
ax.SetTitleOffset(0.8)
ax.SetTitle(nameX)
ay = h.GetYaxis()
ay.SetTitleOffset(0.8)
ay.SetTitle(nameY)
ax.SetTitleOffset(1.1)
ay.SetTitleOffset(1.4)
ax.Draw("same")
ay.Draw("same")

prof_eta.SetMarkerSize(1.1)
prof_eta.SetMarkerColor(1)
prof_eta.Draw("pe same")
prof_eta_nn.SetMarkerSize(1)
prof_eta_nn.SetMarkerColor(2)
prof_eta_nn.Draw("pe same")

out = "histo_" + outfile
hfile = TFile(out, "RECREATE", "DijetsMC")
c1.Write()
prof_eta.Write()
prof_pt.Write()

prof_eta_nn.Write()
prof_pt_nn.Write()
hfile.ls()
hfile.Close()
print "Write with cross sections written=", out
Exemple #13
0
    print "Event", i
    a = eventsRef.getByLabel(label, tracksRef)
    for track in tracksRef.product():
        if (not track.quality(track.qualityByName(quality))): continue
        dp = abs(track.outerPosition().phi() - track.outerMomentum().phi())
        res = track.residuals()
        hitP = track.hitPattern()
        bin = lostHit.Fill(
            dp,
            hitP.numberOfLostHits(),
        )
        j = 0
        for ih in range(0, hitP.numberOfHits()):
            p = hitP.getHitPattern(ih)
            if hitP.validHitFilter(p):
                if hitP.stripHitFilter(p):
                    bin = pulls.Fill(res.residualX(j))
                j += 1

c1 = TCanvas('c1', 'vi', 200, 10, 1000, 1000)
gStyle.SetOptStat(111111)
c1.Divide(2)
c1.cd(1)
#c1.SetLogy()
pulls.Draw()
c1.cd(2)
lostHit.Draw()

c1.Print("pullsttbar.png")
os.system("mv pullsttbar.png ~/www/histos/.")