Ejemplo n.º 1
0
def load_cck():

    #model by Guillermo at. al.
    f = open("data/data-dtdy-y_0-RHIC-clean_CCK.dat", "read")
    sigma = []
    for line in f:
        if line[0] == "#": continue
        p = line.split("\t")
        t = float(p[3])
        nucl = float(p[4])
        hs = float(p[8])
        sigma.append({"t": t, "nucl": nucl, "hs": hs})

    #correction from gamma-Au to AuAu by Michal
    k_auau = 9.0296

    #scaling to XnXn
    kx = 0.1702

    gCCK = TGraphErrors(len(sigma))
    for i in xrange(len(sigma)):
        gCCK.SetPoint(i, sigma[i]["t"], sigma[i]["hs"] * k_auau * kx)

    gCCK.SetLineColor(rt.kRed)
    gCCK.SetLineWidth(3)
    gCCK.SetLineStyle(rt.kDashed)  # 9

    return gCCK
Ejemplo n.º 2
0
def make_tgrapherrors(name,
                      title,
                      color=1,
                      marker=20,
                      marker_size=1,
                      width=1,
                      asym_err=False,
                      style=1,
                      x=None,
                      y=None):
    if (x and y) is None:
        gr = TGraphErrors() if not asym_err else TGraphAsymmErrors()
    else:
        gr = TGraphErrors(len(x), array(x, 'd'), array(
            y, 'd')) if not asym_err else TGraphAsymmErrors(
                len(x), array(x, 'd'), array(y), 'd')
    gr.SetTitle(title)
    gr.SetName(name)
    gr.SetMarkerStyle(marker)
    gr.SetMarkerColor(color)
    gr.SetLineColor(color)
    gr.SetMarkerSize(marker_size)
    gr.SetLineWidth(width)
    gr.SetLineStyle(style)
    return gr
Ejemplo n.º 3
0
def CompareToys(MwValuemT, MwValuemTStat):
    print(len(MwValuemT), len(MwValuemTStat))

    n = len(MwValuemT)
    x, y = array('d'), array('d')
    ex, ey = array('d'), array('d')

    for i in range(0, n):
        x.append(i + 1)
        ex.append(0)
        y.append(MwValuemT[i])
        ey.append(MwValuemTStat[i])

    gr = TGraphErrors(n, x, y, ex, ey)
    gr.Draw("P")
    gr.SetLineWidth(0)
    gr.SetMarkerStyle(20)
    gr.SetMarkerSize(1)

    xax = gr.GetXaxis()
    for i in range(0, n):
        binIndex = xax.FindBin(i)
        xax.SetBinLabel(binIndex, "toys")

    Output = ROOT.TFile.Open("Matrix.root", "RECREATE")
    gr.Write("gr")
Ejemplo n.º 4
0
def getGraph(data, name='graph', offset=0):
    from ROOT import TGraphErrors
    g = TGraphErrors(len(data))
    for n, (_, throughput, throughputE) in enumerate(data):
        g.SetPoint(n, offset + n, throughput)
        g.SetPointError(n, 0., throughputE)
    g.SetName(name)
    g.SetLineWidth(2)
    g.SetMarkerSize(1.7)
    return g
Ejemplo n.º 5
0
  def plotGraph(self, x='vv', y='acc'): 
    '''
    Plot a graph with specified quantities on x and y axes , and saves the graph
    '''

    if (x not in self.quantities.keys()) or (y not in self.quantities.keys()):
      raise RuntimeError('selected quantities not available, available quantities are: \n{}'.format(self.quantities.keys()))

    xq = self.quantities[x]
    yq = self.quantities[y]

    #graph = TGraphAsymmErrors()
    #graph = TGraph()
    graph = TGraphErrors()
    for i,s in enumerate(self.samples):
      graph.SetPoint(i,getattr(s, xq.name), getattr(s, yq.name) )
      #if xq.err: 
      #  graph.SetPointEXhigh(i, getattr(s, xq.name+'_errup'))   # errup errdn
      #  graph.SetPointEXlow (i, getattr(s, xq.name+'_errdn'))
      if yq.err: 
        graph.SetPointError(i, 0, getattr(s, yq.name+'_errup'))
      #  graph.SetPointEYhigh(i, getattr(s, yq.name+'_errup'))  
      #  graph.SetPointEYlow (i, getattr(s, yq.name+'_errdn'))

    c = TCanvas()
    graph.SetLineWidth(2)
    graph.SetMarkerStyle(22)
    graph.SetTitle(';{x};{y}'.format(y=yq.title,x=xq.title))
    graph.Draw('APLE')

    if yq.forceRange:
      graph.SetMinimum(yq.Range[0])
      graph.SetMaximum(yq.Range[1])

    gPad.Modified()
    gPad.Update()
    if yq.name=='expNevts':
      line = TLine(gPad.GetUxmin(),3,gPad.GetUxmax(),3)
      line.SetLineColor(ROOT.kBlue)
      line.Draw('same')
      #graph.SetMinimum(0.01)
      #graph.SetMaximum(1E06)

    if xq.log: c.SetLogx()
    if yq.log: c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    c.SaveAs('./plots/{}{}/{}_{}VS{}.pdf'.format(self.label,suffix,self.name,yq.name,xq.name))
    c.SaveAs('./plots/{}{}/{}_{}VS{}.C'.format(self.label,suffix,self.name,yq.name,xq.name))
    c.SaveAs('./plots/{}{}/{}_{}VS{}.png'.format(self.label,suffix,self.name,yq.name,xq.name))

    self.graphs['{}VS{}'.format(yq.name,xq.name)] = graph
    # add the graph container for memory?
    graph_saver.append(graph)
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig,
                             lower1sig, upper2sig, lower2sig):

    channel = np.array(
        [3. * nchannels - 1.5 - 3. * i for i in range(0, nchannels)])
    ey = np.array([0.8 for i in range(0, nchannels)])
    zero = np.zeros(nchannels)

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    x1 = gStyle.GetPadLeftMargin() + 0.01
    y2 = 1 - gStyle.GetPadTopMargin() - 0.01
    leg = TLegend(x1, y2 - 0.17, x1 + 0.25, y2)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    leg.AddEntry(gobs, "Observed", "pl")
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
Ejemplo n.º 7
0
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig,
                             lower1sig, upper2sig, lower2sig):

    channel = np.array(
        [nchannels - 1.5 - float(i) for i in range(0, nchannels)])
    ey = np.full(nchannels, 0.494)
    zero = np.zeros(nchannels)

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    #gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    leg = TLegend(0.75, 0.75, 0.95, 0.9)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    #leg.AddEntry( gobs,        "Observed", "pl" )
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
Ejemplo n.º 8
0
def Plot2DHist( th2, slope, offset, x_points, y_points, error_points, outname, xlabel='',
            etBinIdx=None, etaBinIdx=None, etBins=None,etaBins=None):

    from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack,TLine,kBird, kOrange,kGray
    from ROOT import TGraphErrors,TF1,TColor
    import array

    def AddTopLabels(can, etlist = None, etalist = None, etidx = None, etaidx = None, logger=None):

        extraText = [GetAtlasInternalText()]
        if etlist and etidx is not None:
            etlist=copy(etlist)
            if etlist[-1]>9999:  etlist[-1]='#infty'
            binEt = (str(etlist[etidx]) + ' < E_{T} [GeV] < ' + str(etlist[etidx+1]) if etidx+1 < len(etlist) else
                                     'E_{T} > ' + str(etlist[etidx]) + ' GeV')
            extraText.append(binEt)
        if etalist and etaidx is not None:
            binEta = (str(etalist[etaidx]) + ' < #eta < ' + str(etalist[etaidx+1]) if etaidx+1 < len(etalist) else
                                        str(etalist[etaidx]) + ' < #eta < 2.47')
            extraText.append(binEta)
        DrawText(can,extraText,.14,.68,.35,.93,totalentries=4)

    gStyle.SetPalette(kBird)
    drawopt='lpE2'
    canvas = TCanvas('canvas','canvas',500, 500)
    canvas.SetRightMargin(0.15)
    th2.GetXaxis().SetTitle('Neural Network output (Discriminant)')
    th2.GetYaxis().SetTitle(xlabel)
    th2.GetZaxis().SetTitle('Count')
    th2.Draw('colz')
    canvas.SetLogz()
    g = TGraphErrors(len(x_points), array.array('d',x_points), array.array('d',y_points), array.array('d',error_points), array.array('d',[0]*len(x_points)))
    g.SetLineWidth(1)
    g.SetLineColor(kBlue)
    g.SetMarkerColor(kBlue)
    g.Draw("P same")
    line = TLine(slope*th2.GetYaxis().GetXmin()+offset,th2.GetYaxis().GetXmin(), slope*th2.GetYaxis().GetXmax()+offset, th2.GetYaxis().GetXmax())
    line.SetLineColor(kBlack)
    line.SetLineWidth(2)
    line.Draw()
    AddTopLabels( canvas, etlist=etBins,etalist=etaBins,etidx=etBinIdx,etaidx=etaBinIdx)
    FormatCanvasAxes(canvas, XLabelSize=16, YLabelSize=16, XTitleOffset=0.87, ZLabelSize=14,ZTitleSize=14, YTitleOffset=0.87, ZTitleOffset=1.1)
    SetAxisLabels(canvas,'Neural Network output (Discriminant)',xlabel)
    canvas.SaveAs(outname+'.pdf')
    canvas.SaveAs(outname+'.C')
    return outname+'.pdf'
Ejemplo n.º 9
0
	def getGraph(self, filename):
		data = self.getData(filename)

		from ROOT import TFile, TTree, gDirectory, TGraphErrors, TCanvas
		from array import array

		nsteps = len(data)
		g = TGraphErrors(nsteps)

		## Loop on the data
		for	n,(fragsize,tp,tpE) in enumerate(data):
			g.SetPoint(      n, fragsize, tp)
			g.SetPointError( n,       0., tpE)

		g.SetLineWidth(2)
		g.SetMarkerSize(1.7)

		return g
Ejemplo n.º 10
0
def load_ms():

    #model by Heikki and Bjorn
    f = open("data/to_star_ms.txt", "read")
    t_sigma = []
    for line in f:
        if line[0] == "#": continue
        point = line.split(" ")
        t_sigma.append([float(point[0]), float(point[1])])

    #scaling to XnXn
    kx = 0.1702

    gMS = TGraphErrors(len(t_sigma))
    for i in xrange(len(t_sigma)):
        gMS.SetPoint(i, t_sigma[i][0], t_sigma[i][1] * kx)

    gMS.SetLineColor(rt.kViolet)
    gMS.SetLineWidth(3)
    gMS.SetLineStyle(rt.kDashDotted)  # kDashed

    return gMS
Ejemplo n.º 11
0
def load_sartre():

    sartre = TFile.Open(
        "/home/jaroslav/sim/sartre_tx/sartre_AuAu_200GeV_Jpsi_coh_2p7Mevt.root"
    )
    sartre_tree = sartre.Get("sartre_tree")

    hSartre = ut.prepare_TH1D("hSartre", 0.002, 0., 0.12)
    sartre_tree.Draw("-tval >> hSartre", "rapidity>-1 && rapidity<1")

    ut.norm_to_integral(hSartre, 0.025)  # now same as Starlight

    gSartre = TGraphErrors(hSartre.GetNbinsX())
    for ibin in xrange(1, hSartre.GetNbinsX() + 1):
        gSartre.SetPoint(ibin - 1, hSartre.GetBinCenter(ibin),
                         hSartre.GetBinContent(ibin))

    gSartre.SetLineColor(rt.kYellow + 1)
    gSartre.SetLineWidth(3)
    #gSartre.SetLineStyle(rt.kDashDotted)

    return gSartre
Ejemplo n.º 12
0
def main(network_name, do_weights, general_weights, electron_weights,
         muon_weights, data_files, no_true_comp, nbins, veto_all_jets,
         require_jets, WorkingP_List, Independant_Variable_List,
         Histogram_Variable_List, Profile_List, TH2D_List):

    TH1.SetDefaultSumw2()

    ## First we check that you havent vetoed and requested jets
    if veto_all_jets and require_jets:
        print("\n\n\nYOU CANT ASK FOR NONE YET SOME JETS\n\n\n")
        return 0

    for data_dir, data_set_name in data_files:
        OUTPUT_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Output")
        DATA_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Data")
        data_base_dir = os.path.join(DATA_dir, data_dir)
        print("\n\n" + data_set_name)
        """
         ____    ____    _____   ____       _      ____       _      _____   ___    ___    _   _
        |  _ \  |  _ \  | ____| |  _ \     / \    |  _ \     / \    |_   _| |_ _|  / _ \  | \ | |
        | |_) | | |_) | |  _|   | |_) |   / _ \   | |_) |   / _ \     | |    | |  | | | | |  \| |
        |  __/  |  _ <  | |___  |  __/   / ___ \  |  _ <   / ___ \    | |    | |  | |_| | | |\  |
        |_|     |_| \_\ |_____| |_|     /_/   \_\ |_| \_\ /_/   \_\   |_|   |___|  \___/  |_| \_|

        """

        ## The list of matrices
        Indp_output = [None for var in Independant_Variable_List]
        TH1D_output = [[None for wp in WorkingP_List]
                       for var in Histogram_Variable_List]
        Tail_output = [[None for wp in WorkingP_List]
                       for var in Histogram_Variable_List]
        Prof_output = [[None for wp in WorkingP_List] for var in Profile_List]
        TH2D_output = [[None for wp in WorkingP_List] for var in TH2D_List]

        ## Open the root file
        root_file = TFile.Open(os.path.join(data_base_dir, data_set_name))

        ## Loading the tree containing the working point information
        wpt_tree = root_file.Get("wpt_tree")

        ## Making the wpt_tree and the other trees friends so that they can be compared
        wpt_tree.AddFriend(network_name, root_file)
        wpt_tree.AddFriend("alt_tree", root_file)
        wpt_tree.AddFriend("var_tree", root_file)

        ## Creating a string of all the weights to be applied
        event_weights = []
        if "SR" in data_dir: event_weights += general_weights
        if "ee" in data_dir: event_weights += electron_weights
        if "mumu" in data_dir: event_weights += muon_weights

        if veto_all_jets:
            event_weights += ["(var_tree.Jets_Loose_SumET==0)"]
        if require_jets:
            event_weights += ["(var_tree.Jets_Loose_SumET>0)"]

        if do_weights: weight_string = " * ".join(event_weights)
        else: weight_string = ""

        if len(weight_string):
            print("Events are weighted using: {}".format(weight_string))

        ## The strings to call up the Truth Values
        if no_true_comp:
            True_Et = "0"
            True_Ex = "0"
            True_Ey = "0"
            True_Phi = "0"
        else:
            True_Et = "WP_Truth_ET"
            True_Ex = "WP_Truth_X"
            True_Ey = "WP_Truth_Y"
            True_Phi = "WP_Truth_Phi"
        """
         ____    ____       _     __        __  ___   _   _    ____
        |  _ \  |  _ \     / \    \ \      / / |_ _| | \ | |  / ___|
        | | | | | |_) |   / _ \    \ \ /\ / /   | |  |  \| | | |  _
        | |_| | |  _ <   / ___ \    \ V  V /    | |  | |\  | | |_| |
        |____/  |_| \_\ /_/   \_\    \_/\_/    |___| |_| \_|  \____|

        """

        ## Before the workingpoint loop, the independant variables are drawn
        for v, var in enumerate(Independant_Variable_List):
            print(" -- {}".format(var.name))

            ## Creating the histogram which will be filled
            hist_name = var.name
            myhist = TH1D(hist_name, hist_name, var.nbins, var.xmin, var.xmax)
            myhist.SetStats(True)
            myhist.StatOverflows(True)

            ## Get Maths Function from variable
            maths_string = var.tree + "." + var.branch

            ## Drawing the tree and saving the hist to the matrix
            execution = "{}>>{}".format(maths_string, hist_name)
            wpt_tree.Draw(execution, weight_string, "goff")

            ## Saving the Histogram to the Matrix
            myhist.SetDirectory(0)
            Indp_output[v] = myhist

        ## First we select the working point and create the correct strings
        for w, wp in enumerate(WorkingP_List):
            print(" -- {}:".format(wp.name))

            Rec_Et = wp.Et
            Rec_Ex = wp.Ex
            Rec_Ey = wp.Ey
            Rec_Phi = wp.Phi
            if wp.tree == "ann_tree":
                Rec_Et = network_name + "." + Rec_Et
                Rec_Ex = network_name + "." + Rec_Ex
                Rec_Ey = network_name + "." + Rec_Ey

            rec_and_truth_vars = [
                Rec_Et, Rec_Ex, Rec_Ey, Rec_Phi, True_Et, True_Ex, True_Ey,
                True_Phi
            ]

            ## Drawing the 1D histograms
            for v, var in enumerate(Histogram_Variable_List):
                print(" -- -- {}".format(var.name))

                ## Creating the histogram which will be filled
                hist_name = "{}_{}".format(var.name, wp.name)
                myhist = TH1D(hist_name, hist_name, var.nbins, var.xmin,
                              var.xmax)
                myhist.SetStats(True)
                myhist.StatOverflows(True)

                ## Individual special plots
                if var.name == "XY":
                    ## Plot the X histogram
                    maths_string = Evaluation.TH1D_Maths_String(
                        "X", *rec_and_truth_vars)
                    execution = "{} >> {}".format(maths_string, hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff")

                    ## Add the y histogram
                    maths_string = Evaluation.TH1D_Maths_String(
                        "Y", *rec_and_truth_vars)
                    execution = "{} >> +{}".format(maths_string, hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff")

                else:
                    ## Get Maths Function from variable
                    maths_string = Evaluation.TH1D_Maths_String(
                        var.name, *rec_and_truth_vars)

                    ## Drawing the tree and saving the hist to the matrix
                    execution = "{} >> {}".format(maths_string, hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff")

                ## Saving the Histogram to the Matrix
                myhist.SetDirectory(0)
                TH1D_output[v][w] = myhist

            ## Drawing the Profiles
            for v, (vx, vy) in enumerate(Profile_List):
                print(" -- -- {} vs {}".format(vx.name, vy.name))

                ## Creating the profile which will be filled
                hist_name = "{}_vs_{}_{}".format(vx.name, vy.name, wp.name)
                myhist = TProfile(hist_name, hist_name, vx.nbins, vx.xmin,
                                  vx.xmax)

                if vy.reso: myhist.SetErrorOption('s')

                ## The x variable is called from its branch in the correct tree
                x_string = vx.tree + "." + vx.branch

                ## Individual special plots
                if vy.name == "XY":
                    y_string = Evaluation.TH1D_Maths_String(
                        "X", *rec_and_truth_vars)
                    execution = "{}:{} >> {}".format(y_string, x_string,
                                                     hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff prof")

                    y_string = Evaluation.TH1D_Maths_String(
                        "Y", *rec_and_truth_vars)
                    execution = "{}:{} >>+{}".format(y_string, x_string,
                                                     hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff prof")

                elif vy.name == "AZ":
                    z_x = "(alt_tree.ll_px)"
                    z_y = "(alt_tree.ll_py)"
                    z_pt = "(alt_tree.ll_pt)"

                    x_string = z_pt
                    y_string = "({rx}*{zx} + {ry}*{zy})/{zpt}".format(
                        rx=Rec_Ex, ry=Rec_Ey, zx=z_x, zy=z_y, zpt=z_pt)
                    execution = "{}:{} >> {}".format(y_string, x_string,
                                                     hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff prof")

                else:
                    y_string = Evaluation.TH1D_Maths_String(
                        vy.name, *rec_and_truth_vars)
                    execution = "{}:{} >> {}".format(y_string, x_string,
                                                     hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff prof")

                ## Saving the Histogram to the Matrix
                myhist.SetDirectory(0)
                Prof_output[v][w] = myhist

            if wp.name not in ["Network", "Tight"]:
                continue

            ## Drawing the TH2Ds
            for v, (vx, vy) in enumerate(TH2D_List):
                print(" -- -- {} vs {}".format(vx.name, vy.name))

                ## Creating the profile which will be filled
                hist_name = "2D_{}_vs_{}_{}".format(vx.name, vy.name, wp.name)
                myhist = TH2D(hist_name, hist_name, vx.nbins2d, vx.xmin2d,
                              vx.xmax2d, vy.nbins2d, vy.xmin2d, vy.xmax2d)

                x_string = Evaluation.TH1D_Maths_String(
                    vx.name, *rec_and_truth_vars)
                y_string = Evaluation.TH1D_Maths_String(
                    vy.name, *rec_and_truth_vars)

                ## The x variable is called from its branch in the correct tree
                if x_string is None:
                    x_string = vx.tree + "." + vx.branch

                execution = "{}:{} >> {}".format(y_string, x_string, hist_name)
                wpt_tree.Draw(execution, weight_string, "goff")

                ## Saving the Histogram to the Matrix
                myhist.SetDirectory(0)
                TH2D_output[v][w] = myhist

        root_file.Close()
        """
         _____   ____    ___   _____   ___   _   _    ____
        | ____| |  _ \  |_ _| |_   _| |_ _| | \ | |  / ___|
        |  _|   | | | |  | |    | |    | |  |  \| | | |  _
        | |___  | |_| |  | |    | |    | |  | |\  | | |_| |
        |_____| |____/  |___|   |_|   |___| |_| \_|  \____|

        """

        ## We now go through the 1D histograms and make them include overflow and underflow
        for v, var in enumerate(Histogram_Variable_List):
            for w, wp in enumerate(WorkingP_List):

                ## Include the overflow
                last_bin = TH1D_output[v][w].GetBinContent(nbins)
                overflow = TH1D_output[v][w].GetBinContent(nbins + 1)
                TH1D_output[v][w].SetBinContent(nbins, last_bin + overflow)
                TH1D_output[v][w].SetBinContent(nbins + 1, 0)

                ## Include the underflow
                first_bin = TH1D_output[v][w].GetBinContent(1)
                underflow = TH1D_output[v][w].GetBinContent(0)
                TH1D_output[v][w].SetBinContent(1, first_bin + underflow)
                TH1D_output[v][w].SetBinContent(0, 0)

                ## We create a tail distrobution if it is requested
                if var.tail:
                    tail_temp = TH1D_output[v][w].GetCumulative(False)
                    tail_temp.Scale(1 / tail_temp.GetBinContent(1))
                    Tail_output[v][w] = tail_temp

        ## We go through the resolution profiles and replace their entries with the RMSE for each bin
        for v, (vx, vy) in enumerate(Profile_List):

            if not vy.reso:
                continue

            for w, wp in enumerate(WorkingP_List):

                old_prof = Prof_output[v][w]
                bin_width = old_prof.GetBinWidth(1)

                name = "{}_vs_{}_{}_res".format(vx.name, vy.name, wp.name)
                new_prof = TGraphErrors(vx.nbins)
                new_prof.SetName(name)
                new_prof.SetTitle(name)

                new_prof.SetLineWidth(2)

                for b_idx in range(vx.nbins):
                    new_prof.SetPoint(b_idx, old_prof.GetBinCenter(b_idx + 1),
                                      old_prof.GetBinError(b_idx + 1))
                    new_prof.SetPointError(b_idx, bin_width / 2, 0)

                Prof_output[v][w] = new_prof
        """
         ____       _     __     __  ___   _   _    ____
        / ___|     / \    \ \   / / |_ _| | \ | |  / ___|
        \___ \    / _ \    \ \ / /   | |  |  \| | | |  _
         ___) |  / ___ \    \ V /    | |  | |\  | | |_| |
        |____/  /_/   \_\    \_/    |___| |_| \_|  \____|

        """

        ## Creating the output directory
        output_dir = os.path.join(OUTPUT_dir, network_name, data_set_name[:-5])
        if veto_all_jets:
            output_dir = output_dir + "_NOJETS"
        if require_jets:
            output_dir = output_dir + "_SOMEJETS"

        ## Check that the file can be saved
        if not os.path.exists(output_dir):
            os.system("mkdir -p " + output_dir)

        ## We create an output file for the histograms
        output_file = TFile(os.path.join(output_dir, "histograms.root"),
                            "update")
        gFile = output_file

        ## We save the independants
        for v, var in enumerate(Independant_Variable_List):
            Indp_output[v].Write("", TObject.kOverwrite)

        ## We save the TH1Ds and tails
        for v, var in enumerate(Histogram_Variable_List):
            for w in range(len(WorkingP_List)):
                TH1D_output[v][w].Write("", TObject.kOverwrite)
                if var.tail:
                    Tail_output[v][w].Write("", TObject.kOverwrite)

        ## We save the profiles
        for v in range(len(Profile_List)):
            for w in range(len(WorkingP_List)):
                Prof_output[v][w].Write("", TObject.kOverwrite)

        ## We save the TH2Ds
        for v in range(len(TH2D_List)):
            for w in range(len(WorkingP_List[:2])):
                TH2D_output[v][w].Write("", TObject.kOverwrite)

        output_file.Close()
    return 0
Ejemplo n.º 13
0
def mistagSFtopEMu(year_, ana_):
    if year_ == 2017:
        dir = "monohbb.v06.00.05.2017_NCU/withSingleTop/" + ana_ + "/"
    if year_ == 2018:
        dir = "monohbb.v06.00.05.2018_NCU/withSingleTop/" + ana_ + "/"

    print "Top Electron Region"
    print " "

    openfile1 = TFile(dir + "TopE.root")  #

    topmatchTopE = openfile1.Get("h_TopMatch")
    WmatchTopE = openfile1.Get("h_Wmatch")
    unmatchTopE = openfile1.Get("h_unmatch")
    wjetsTopE = openfile1.Get("h_sumWJets")
    dibosonTopE = openfile1.Get("h_sumDiboson")
    unsubtractedDataTopE = openfile1.Get("h_Data")

    failMCsubtractTopE = openfile1.Get("h_ttFailed")
    passMCsubtractTopE = openfile1.Get("h_ttPassed")
    subtractedDataTopE = openfile1.Get("SubtractedData")

    datafailTopE = openfile1.Get("SubtractedDataFailed")
    datapassTopE = openfile1.Get("SubtractedDataPassed")  #
    totaldataTopE = openfile1.Get("h_totaldata")
    totalMCtopE = openfile1.Get("h_tt")

    passedTopEdataBfrSubtract = openfile1.Get("h_Data_Passed")
    wjetsTopEpassed = openfile1.Get("h_sumWJetsPassed")
    dibosonTopEpassed = openfile1.Get("h_sumDibosonPassed")

    failedTopEdataBfrSubtract = openfile1.Get("h_Data_Failed")
    wjetsTopEfailed = openfile1.Get("h_sumWJetsFailed")
    dibosonTopEfailed = openfile1.Get("h_sumDibosonFailed")

    stTopE = openfile1.Get("h_sumST")
    stTopEpassed = openfile1.Get("h_sumSTPassed")
    stTopEfailed = openfile1.Get("h_sumSTFailed")

    print "Top Muon Region"
    print " "

    openfile2 = TFile(dir + "TopMu.root")  #

    topmatchTopMu = openfile2.Get("h_TopMatch")
    WmatchTopMu = openfile2.Get("h_Wmatch")
    unmatchTopMu = openfile2.Get("h_unmatch")
    wjetsTopMu = openfile2.Get("h_sumWJets")
    dibosonTopMu = openfile2.Get("h_sumDiboson")
    unsubtractedDataTopMu = openfile2.Get("h_Data")

    failMCsubtractTopMu = openfile2.Get("h_ttFailed")
    passMCsubtractTopMu = openfile2.Get("h_ttPassed")
    subtractedDataTopMu = openfile2.Get("SubtractedData")

    datafailTopMu = openfile2.Get("SubtractedDataFailed")
    datapassTopMu = openfile2.Get("SubtractedDataPassed")  #
    totaldataTopMu = openfile2.Get("h_totaldata")
    totalMCtopMu = openfile2.Get("h_tt")

    passedTopMudataBfrSubtract = openfile2.Get("h_Data_Passed")
    wjetsTopMupassed = openfile2.Get("h_sumWJetsPassed")
    dibosonTopMupassed = openfile2.Get("h_sumDibosonPassed")

    failedTopMudataBfrSubtract = openfile2.Get("h_Data_Failed")
    wjetsTopMufailed = openfile2.Get("h_sumWJetsFailed")
    dibosonTopMufailed = openfile2.Get("h_sumDibosonFailed")

    stTopMu = openfile2.Get("h_sumST")
    stTopMupassed = openfile2.Get("h_sumSTPassed")
    stTopMufailed = openfile2.Get("h_sumSTFailed")

    print "get histograms from root files: done"
    print " "

    SubtractedDataPassedTopE = datapassTopE.Clone("SubtractedDataPassedTopE")
    SubtractedDataPassedTopMu = datapassTopMu.Clone(
        "SubtractedDataPassedTopMu")

    #merge histogram"
    print "merge histograms"
    print " "

    topmatchMerge = topmatchTopE + topmatchTopMu
    WmatchMerge = WmatchTopE + WmatchTopMu
    unmatchMerge = unmatchTopE + unmatchTopMu
    wjetsMerge = wjetsTopE + wjetsTopMu
    stMerge = stTopE + stTopMu
    dibosonMerge = dibosonTopE + dibosonTopMu
    unsubtractedDataMerge = unsubtractedDataTopE + unsubtractedDataTopMu

    failMCsubtractMerge = failMCsubtractTopE.Clone("failMCsubtractMerge")
    failMCsubtractMerge = failMCsubtractMerge + failMCsubtractTopMu
    passMCsubtractMerge = passMCsubtractTopE.Clone("passMCsubtractMerge")
    passMCsubtractMerge = passMCsubtractMerge + passMCsubtractTopMu
    subtractedDataMerge = subtractedDataTopE + subtractedDataTopMu

    ttData_fraction = arr.array('d')
    ttData_error = arr.array('d')

    totaldataMerge = totaldataTopE + totaldataTopMu
    totaldata = totaldataMerge.Integral()
    totaldataMerge.Rebin(14)

    datafailMerge = datafailTopE + datafailTopMu
    faildata = datafailMerge.Integral()
    datafailMerge.Rebin(14)
    datafailMerge.Sumw2()
    datafailMerge.Divide(totaldataMerge)
    frac_ttData_fail = datafailMerge.Integral()
    ttData_fraction.append(frac_ttData_fail)
    ttData_error.append(datafailMerge.GetBinError(1))

    datapassMerge = datapassTopE + datapassTopMu
    passdata = datapassMerge.Integral()
    datapassMerge.Rebin(14)
    datapassMerge.Sumw2()
    datapassMerge.Divide(totaldataMerge)
    frac_ttData_pass = datapassMerge.Integral()
    ttData_fraction.append(frac_ttData_pass)
    ttData_error.append(datapassMerge.GetBinError(1))

    ttMC_fraction = arr.array('d')
    ttMC_error = arr.array('d')

    totalMCmerge = totalMCtopE + totalMCtopMu
    totalMCmerge.Rebin(14)

    MCfailTopE = failMCsubtractTopE.Clone("MCfailTopE")
    MCfailTopMu = failMCsubtractTopMu.Clone("MCfailTopMu")
    MCfailMerge = MCfailTopE + MCfailTopMu
    MCfailMerge.Rebin(14)
    MCfailMerge.Sumw2()
    MCfailMerge.Divide(totalMCmerge)
    frac_Failed_fin = MCfailMerge.Integral()
    ttMC_fraction.append(frac_Failed_fin)
    ttMC_error.append(MCfailMerge.GetBinError(1))

    MCpassTopE = passMCsubtractTopE.Clone("MCpassTopE")
    MCpassTopMu = passMCsubtractTopMu.Clone("MCpassTopMu")
    MCpassMerge = MCpassTopE + MCpassTopMu
    MCpassMerge.Rebin(14)
    MCpassMerge.Sumw2()
    MCpassMerge.Divide(totalMCmerge)
    frac_Passed_fin = MCpassMerge.Integral()
    ttMC_fraction.append(frac_Passed_fin)
    ttMC_error.append(MCpassMerge.GetBinError(1))

    #print "\nttMC_fraction:", ttMC_fraction
    #print "ttMC_error:", ttMC_error

    sfMerge = datapassMerge.Clone("sfMerge")
    sfMerge.Sumw2()
    sfMerge.Divide(MCpassMerge)

    stacklist = []
    stacklist.append(dibosonMerge)
    stacklist.append(stMerge)
    stacklist.append(wjetsMerge)
    stacklist.append(unmatchMerge)
    stacklist.append(WmatchMerge)
    stacklist.append(topmatchMerge)

    print "merge histograms: done"
    print " "

    print "draw histograms"
    print " "
    #----------------------- canvas 1 -----------------------#

    c1 = TCanvas("c1", "", 800, 900)  #width-height
    c1.SetTopMargin(0.4)
    c1.SetBottomMargin(0.05)
    c1.SetRightMargin(0.1)
    c1.SetLeftMargin(0.15)
    gStyle.SetOptStat(0)

    binvalues1 = []
    for i in range(14):
        binvalue = unsubtractedDataMerge.GetBinContent(i)
        binvalues1.append(binvalue)
    totalmax = max(binvalues1) + 100

    padMain = TPad("padMain", "", 0.0, 0.25, 1.0, 0.97)
    padMain.SetTopMargin(0.4)
    padMain.SetRightMargin(0.05)
    padMain.SetLeftMargin(0.17)
    padMain.SetBottomMargin(0.03)
    padMain.SetTopMargin(0.1)

    padRatio = TPad("padRatio", "", 0.0, 0.0, 1.0, 0.25)
    padRatio.SetRightMargin(0.05)
    padRatio.SetLeftMargin(0.17)
    padRatio.SetTopMargin(0.05)
    padRatio.SetBottomMargin(0.3)
    padMain.Draw()
    padRatio.Draw()

    padMain.cd()

    gPad.GetUymax()
    leg1 = myLegend(coordinate=[0.45, 0.57, 0.65, 0.6])

    unsubtractedDataMerge.SetMaximum(totalmax)
    unsubtractedDataMerge.SetLineColor(1)
    unsubtractedDataMerge.SetMarkerStyle(20)
    unsubtractedDataMerge.SetMarkerSize(1.5)
    unsubtractedDataMerge.GetXaxis().SetLabelSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitleSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitle("DDB")
    unsubtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg1.AddEntry(unsubtractedDataMerge, "Data", "lep")
    unsubtractedDataMerge.Draw("e1")

    stackhisto = myStack(colorlist_=[627, 800, 854, 813, 822, 821],
                         backgroundlist_=stacklist,
                         legendname_=[
                             "Diboson", "Single Top", "W+Jets",
                             "Top (unmtch.)", "Top (W-mtch.)", "Top (mtch.)"
                         ])
    stackhisto[0].Draw("histsame")
    unsubtractedDataMerge.Draw("e1same")
    stackhisto[1].Draw()
    leg1.Draw()

    lt = TLatex()
    lt.DrawLatexNDC(0.23, 0.85,
                    "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    if ana_ == "Inclusive":
        lt.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt.DrawLatexNDC(0.17, 0.92,
                            "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt.DrawLatexNDC(0.71, 0.92,
                        "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    padRatio.cd()

    gPad.GetUymax()

    h_totalBkg = topmatchMerge.Clone("h_totalBkg")
    h_totalBkg = h_totalBkg + WmatchMerge + unmatchMerge + wjetsMerge + dibosonMerge
    ratio = dataPredRatio(data_=unsubtractedDataMerge, totalBkg_=h_totalBkg)
    ratio.SetLineColor(1)
    ratio.SetLineWidth(3)
    ratio.SetMarkerSize(1.5)
    ratio.GetXaxis().SetLabelSize(0.13)
    ratio.GetXaxis().SetTitleOffset(1)
    ratio.GetXaxis().SetTitleSize(0.13)
    ratio.GetXaxis().SetTickLength(0.1)
    ratio.GetYaxis().SetLabelSize(0.12)
    ratio.GetYaxis().SetTitleOffset(0.5)
    ratio.GetYaxis().SetTitleSize(0.13)
    ratio.GetYaxis().SetNdivisions(405)
    ratio.GetYaxis().SetTitle("#frac{Data-Pred}{Pred}")
    ratio.GetXaxis().SetTitle("DDB")
    ratio.Draw("e1")

    c1.SaveAs(dir + "Merge_all.pdf")  #

    #----------------------- canvas 2 -----------------------#

    c2 = myCanvas(c="c2")
    gPad.GetUymax()
    leg2 = myLegend()

    binvalues2 = []
    for i in range(14):
        binvalue = subtractedDataMerge.GetBinContent(i)
        binvalues2.append(binvalue)
    ttmax = max(binvalues2) + 50

    failMCsubtractMerge.SetMaximum(ttmax)
    failMCsubtractMerge.SetFillColor(821)
    failMCsubtractMerge.SetLineColor(821)  #922
    failMCsubtractMerge.GetXaxis().SetTitle("DDB")
    failMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(failMCsubtractMerge, "t#bar{t}", "f")

    passMCsubtractMerge.SetFillColor(622)
    passMCsubtractMerge.SetLineColor(622)
    #passMCsubtractMerge.GetXaxis().SetTitle("DDB")
    #passMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(passMCsubtractMerge, "t#bar{t} mistag", "f")

    subtractedDataMerge.SetLineColor(1)
    subtractedDataMerge.SetMarkerStyle(20)
    subtractedDataMerge.SetMarkerSize(1.5)
    #subtractedDataMerge.GetXaxis().SetTitle("DDB")
    #subtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(subtractedDataMerge, "Subtracted Data", "lep")

    failMCsubtractMerge.Draw("hist")
    passMCsubtractMerge.Draw("histsame")
    subtractedDataMerge.Draw("e1same")
    leg2.Draw()

    lt2 = TLatex()
    if ana_ == "Inclusive":
        lt2.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt2.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt2.DrawLatexNDC(0.23, 0.85,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt2.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt2.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt2.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt2.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    c2.SaveAs(dir + "Merged_subtrac.pdf")  #

    #----------------------- canvas 3 -----------------------#

    c3 = myCanvas(c="c3", size=[700, 900])

    pad1 = TPad("pad1", "", 0.01, 0.25, 0.93, 1.0)
    pad1.SetTopMargin(0.1)
    pad1.SetRightMargin(0.05)
    pad1.SetLeftMargin(0.17)
    pad1.SetBottomMargin(0.05)

    pad2 = TPad("pad2", "", 0.0, 0.0, 0.375, 0.24)
    pad2.SetTopMargin(0.0)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.0)
    pad2.SetBottomMargin(0.0)

    pad3 = TPad("pad3", "", 0.38, 0.025, 0.94, 0.25)
    pad2.SetTopMargin(0.05)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.45)
    pad2.SetBottomMargin(0.2)

    pad1.Draw()
    pad2.Draw()
    pad3.Draw()

    #* Pad 1 *#
    pad1.cd()
    leg3 = myLegend(coordinate=[0.65, 0.4, 0.75, 0.5])

    xaxisname = arr.array('d', [1, 2])
    zero1 = np.zeros(2)

    gPad.Modified()
    gPad.SetGridy()

    gr1 = TGraphErrors(2, xaxisname, ttMC_fraction, zero1, ttMC_error)
    gr1.SetTitle("t#bar{t}")
    gr1.SetLineColor(870)
    gr1.SetLineWidth(3)
    gr1.SetMarkerStyle(20)
    gr1.SetMarkerColor(870)
    leg3.AddEntry(gr1, "t#bar{t}", "lep")

    gr2 = TGraphErrors(2, xaxisname, ttData_fraction, zero1, ttData_error)
    gr2.SetTitle("t#bar{t} Data")
    gr2.SetLineColor(1)
    gr2.SetLineWidth(2)
    gr2.SetMarkerStyle(20)
    gr2.SetMarkerColor(1)
    leg3.AddEntry(gr2, "t#bar{t} Data", "lep")

    mg = TMultiGraph("mg", "")
    mg.Add(gr1)
    mg.Add(gr2)
    mg.GetHistogram().SetMaximum(1.5)
    mg.GetHistogram().SetMinimum(0)
    mg.GetYaxis().SetTitle("Fraction")
    mg.GetXaxis().SetLimits(0, 3)
    mg.GetXaxis().SetTickLength(0.03)
    mg.GetXaxis().SetNdivisions(103)
    mg.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Fail")
    mg.GetXaxis().ChangeLabel(1, -1, 0)
    mg.GetXaxis().ChangeLabel(-1, -1, 0)
    mg.GetXaxis().ChangeLabel(3, -1, -1, -1, -1, -1, "Pass")
    mg.Draw("AP")
    leg3.Draw()

    lt3 = TLatex()
    if ana_ == "Inclusive":
        lt3.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt3.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt3.DrawLatexNDC(0.19, 0.855,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt3.DrawLatexNDC(0.19, 0.805, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt3.DrawLatexNDC(0.19, 0.755, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt3.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt3.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")
    lt3.Draw()

    pad1.Update()

    #* Pad 2 *#
    pad2.cd()

    MCpassMerge.SetFillColor(0)
    MCpassMerge.SetLineColor(870)
    MCpassMerge.SetLineWidth(3)
    MCpassMerge.SetMarkerColor(870)
    MCpassMerge.SetMarkerStyle(20)
    MCpassMerge.GetYaxis().SetTitle("Fraction")
    MCpassMerge.GetYaxis().SetTitleSize(0.09)
    MCpassMerge.GetYaxis().SetLabelSize(0.1)
    MCpassMerge.GetYaxis().SetNdivisions(404)
    MCpassMerge.SetMaximum(0.3)
    MCpassMerge.SetMinimum(0.0)
    MCpassMerge.GetXaxis().SetTitle("")
    MCpassMerge.GetXaxis().SetLabelOffset(0.02)
    MCpassMerge.GetXaxis().SetLabelSize(0.09)
    MCpassMerge.GetXaxis().SetNdivisions(104)
    MCpassMerge.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Pass")
    MCpassMerge.GetXaxis().ChangeLabel(1, -1, 0)
    MCpassMerge.GetXaxis().ChangeLabel(-1, -1, 0)

    datapassMerge.SetFillColor(0)
    datapassMerge.SetLineColor(1)
    datapassMerge.SetLineWidth(2)
    datapassMerge.SetMarkerColor(1)
    datapassMerge.SetMarkerStyle(20)

    MCpassMerge.Draw("e1")
    datapassMerge.Draw("e1histsame")

    #* Pad 3 *#
    pad3.cd()

    SF = sfMerge.Integral()
    print "******"
    print "mistag SF:", SF

    SFfinal = round(SF, 3)
    SFtext = "SF = " + str(SFfinal)

    mistagSFmax = SF + 0.2
    mistagSFmin = SF - 0.2

    sfMerge.SetLineColor(797)
    sfMerge.SetMarkerColor(797)
    sfMerge.SetLineWidth(3)
    sfMerge.SetMaximum(mistagSFmax)
    sfMerge.SetMinimum(mistagSFmin)
    sfMerge.GetXaxis().SetTitle(" ")
    sfMerge.GetXaxis().SetLabelOffset(999)
    sfMerge.GetXaxis().SetLabelSize(0)
    sfMerge.GetXaxis().SetTickLength(0)
    sfMerge.GetYaxis().SetLabelSize(0.1)
    sfMerge.GetYaxis().SetNdivisions(404)
    sfMerge.GetYaxis().SetTitle(" ")

    sfMerge.Draw("e1hist")

    pt = TPaveText(0.21, 0.72, 0.31, 0.8, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.SetTextSize(0.1)
    pt.AddText(SFtext)
    pt.Draw()

    c3.SaveAs(dir + "Merge_SF.pdf")  #

    passedBfrSubtactDataMerge = (passedTopEdataBfrSubtract +
                                 passedTopMudataBfrSubtract).Integral()
    failedBfrSubtractDataMerge = (failedTopEdataBfrSubtract +
                                  failedTopMudataBfrSubtract).Integral()

    passbackground = (wjetsTopEpassed + wjetsTopMupassed + dibosonTopEpassed +
                      dibosonTopMupassed + stTopEpassed +
                      stTopMupassed).Integral()
    failbackground = (wjetsTopEfailed + wjetsTopMufailed + dibosonTopEfailed +
                      dibosonTopMufailed + stTopEfailed +
                      stTopMufailed).Integral()
    totalbackground = (wjetsMerge + dibosonMerge + stMerge).Integral()

    #get the statistical uncertainty#

    dx = ttData_error[1]
    print "data efficiency error", dx

    dy = ttMC_error[1]
    print "MC efficiency error", dy

    x = datapassMerge.Integral()
    y = MCpassMerge.Integral()

    statUnc = TMath.Sqrt(((dx**2) / (y**2)) + ((x**2) * (dy**2) / (y**4)))
    #print "statistical Uncertainty in Top (e+muon) CR", statUnc
    #print " "
    print "relative statistical Uncertainty in Top (e+muon) CR", statUnc / SF * 100, " %"
    print " "

    print "DDB Mistag SF and stat: ", round(SF, 3), " +- ", round(statUnc,
                                                                  3), " (stat)"
    #print "theoretical statistical uncertainty of data efficiency", TMath.Sqrt((x*(1-x))/(subtractedDataMerge.Integral()))
    #print "theoretical statistical uncertainty of MC efficiency", TMath.Sqrt((y*(1-y))/(totalMCmerge.Integral()))
    #print " "

    header = ["Process", "Number of Events", "Top (e+muon)"]
    row1 = [
        " ", "DDB mistag SF",
        str(SFfinal) + " +- " + str(round(statUnc, 3)) + " (stat)"
    ]
    row2 = ["tt MC", "Pass (not normalized)", ""]
    row3 = [
        " ", "Pass (normalized)",
        str(round(passMCsubtractMerge.Integral(), 2))
    ]
    row4 = [" ", "Fail (not normalized)", ""]
    row5 = [
        " ", "Fail (normalized)",
        str(round(failMCsubtractMerge.Integral(), 2))
    ]
    row6 = [" ", "Total (not normalized)", ""]
    row7 = [" ", "Total (normalized)", str(round(totalMCmerge.Integral(), 2))]

    inforMC = [row2, row3, row4, row5, row6, row7]

    row8 = [
        "tt DATA", "Pass (before subtraction)",
        str(round(passedBfrSubtactDataMerge, 2))
    ]
    row9 = [" ", "Pass (after subtraction)", str(round(passdata, 2))]
    row10 = [
        " ", "Fail (before subtraction)",
        str(round(failedBfrSubtractDataMerge, 2))
    ]
    row11 = [" ", "Fail (after subtraction)", str(round(faildata, 2))]
    row12 = [
        " ", "Total (before subtraction)",
        str(round(unsubtractedDataMerge.Integral(), 2))
    ]
    row13 = [" ", "Total (after subtraction)", str(round(totaldata, 2))]

    inforDATA = [row8, row9, row10, row11, row12, row13]

    row14 = ["Background", "Pass (normalized)", str(round(passbackground, 2))]
    row15 = [" ", "Fail (normalized)", str(round(failbackground, 2))]
    row16 = [" ", "Total (normalized)", str(round(totalbackground, 2))]

    inforBKG = [row14, row15, row16]

    DDB_mistagSF.makeTable(header, row1, inforMC, inforDATA, inforBKG)
Ejemplo n.º 14
0
        galpha2.GetYaxis().SetRangeUser(0., 2.)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(category)
        gslope2.GetYaxis().SetRangeUser(0., 20.)

    c1.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalShape.pdf")
    c1.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalShape.png")

    c2 = TCanvas("c2", "Signal Efficiency", 800, 600)
    c2.cd(1)
    gnorm.SetMarkerColor(cColor)
    gnorm.SetMarkerStyle(20)
    gnorm.SetLineColor(cColor)
    gnorm.SetLineWidth(2)
    gnorm.Draw("APL")
    inorm.Draw("P, SAME")
    gnorm.GetXaxis().SetRangeUser(genPoints[0]-100, genPoints[-1]+100)
    gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum()*1.25)
    #drawCMS(-1, "Simulation Preliminary", year=YEAR)
    #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True) 
    drawCMS(-1, "", year=YEAR, suppressCMS=True) 
    drawAnalysis(category)
    drawRegion(category)
    c2.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalNorm.pdf")
    c2.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalNorm.png")


    #*******************************************************#
    #                                                       #
Ejemplo n.º 15
0
def plot_2(var, cuts):
    for s in attr:
        if ct_dep == 0:
            c1 = TCanvas("c1", "Signals", 800, 800)
            c1.cd()
            c1.SetGrid()
            #gStyle.SetTitleFontSize(8.1)
            if s in ('elf', 'muf', 'chm', 'cm', 'nm'):
                c1.SetLogx()
            for cc in channel:
                hist[cc][s].Draw('colz same')
                hist_CHS[cc][s].Draw('colz same')
            legend = TLegend(0.90, 0.90, 0.99, 0.99)
            #legend.SetHeader('Samples')
            for cc in channel:
                legend.AddEntry(hist[cc][s], cc)
                legend.AddEntry(hist_CHS[cc][s], cc + 'CHS')
            legend.Draw()
            c1.Print(path1 + s + var +
                     cuts.replace('(', '_').replace(')', '_').replace(
                         '&&', 'A').replace('>', 'LG').replace('<', 'LS').
                     replace('=', 'EQ').replace('.', 'P').replace('-', 'N').
                     replace('Jet', 'J').replace('GenBquark', 'GBQ') + ".pdf")
            c1.Update()
            c1.Close()
            print('|||||||||||||||||||||||||||||||||||||||||||||||||||')
        elif ct_dep == 1:
            eac0 = str(entries_after_cut['ct0'][s])
            c1 = TCanvas("c1", "Signals", 800, 800)
            c1.SetGrid()
            c1.cd()
            c1.SetLogx()
            #gr = TGraph( len_of_lt , x , yy['sgn'][s] )
            gr = TGraphErrors(len_of_lt, x, yy['sgn'][s], ex, ey['sgn'][s])
            gr.SetMarkerSize(1.5)
            gr.SetMarkerStyle(21)
            gr.SetLineColor(4)
            gr.SetLineWidth(4)
            gr.SetTitle(
                'averaged ' + s + ' cut: ' +
                cuts.replace('(', '_').replace(')', '_').replace('&&', ',').
                replace('Jet', 'J').replace('GenBquark', 'GBQ') + '[entries:' +
                eac0 + ']')
            gr.GetXaxis().SetTitle('decaying length (mm)')
            gr.GetYaxis().SetTitle('mean frequency')
            gr.SetName('sgn')
            gr.Draw('ACP')  # '' sets up the scattering style
            gr1 = TGraphErrors(len_of_lt, x, yy['qcd'][s], ex, ey['qcd'][s])
            gr1.SetMarkerSize(1.0)
            gr1.SetMarkerStyle(2)
            gr1.SetLineColor(2)
            gr1.SetLineWidth(2)
            gr1.SetName('qcd')
            #gr1.SetTitle('averaged ' + s)
            #gr1.GetXaxis().SetTitle('decaying length (mm)')
            #gr1.GetYaxis().SetTitle('mean frequency')
            gr1.Draw('CP')  # '' sets up the scattering style
            legend = TLegend(0.89, 0.89, 0.99, 0.99)
            legend.AddEntry('qcd', legendb)
            legend.AddEntry('sgn', legends)
            legend.Draw()
            c1.Print(path1 + 'mean_' + s + var +
                     cuts.replace('(', '_').replace(')', '_').replace(
                         '&&', 'A').replace('>', 'LG').replace('<', 'LS').
                     replace('=', 'EQ').replace('.', 'P').replace('-', 'N').
                     replace('Jet', 'J').replace('GenBquark', 'GBQ') + ".pdf")
            c1.Update()
            c1.Close()
            print('|||||||||||||||||||||||||||||||||||||||||||||||||||')
Ejemplo n.º 16
0
def makePlot1D(filepath, foutname, plottitle='', masstitle=''):
    br = 1 if 'Resonant' in plottitle else 0.68
    limits = parseLimitFiles2D(filepath, br)

    xaxis = []
    xseclist = []
    xsecerr = []
    cent = []
    obs = []
    up1 = []
    up2 = []
    down1 = []
    down2 = []
    maxval = 0
    minval = 999
    for m in sorted(limits):
        l = limits[m]
        xaxis.append(m)
        xseclist.append(l.xsec)
        xsecerr.append(l.xsec * .2)
        cent.append(l.cent)
        up1.append(l.up1 - l.cent)
        up2.append(l.up2 - l.cent)
        down1.append(l.cent - l.down1)
        down2.append(l.cent - l.down2)
        obs.append(l.obs)
        maxval = max(maxval, l.up2)
        minval = min(minval, l.down2)

    N = len(xaxis)

    up1Sigma = array('f', up1)
    up2Sigma = array('f', up2)
    down1Sigma = array('f', down1)
    down2Sigma = array('f', down2)
    cent = array('f', cent)
    obs = array('f', obs)
    xarray = array('f', xaxis)
    xsecarray = array('f', xseclist)
    xsecerrarray = array('f', xsecerr)
    zeros = array('f', [0 for i in xrange(N)])

    graphXsec = TGraphErrors(N, xarray, xsecarray, zeros, xsecerrarray)

    graphCent = TGraph(N, xarray, cent)
    graphObs = TGraph(N, xarray, obs)
    graph1Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down1Sigma,
                                    up1Sigma)
    graph2Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down2Sigma,
                                    up2Sigma)

    c = TCanvas('c', 'c', 700, 600)
    c.SetLogy()
    c.SetLeftMargin(.15)

    graph2Sigma.GetXaxis().SetTitle(masstitle + ' [GeV]')
    graph2Sigma.GetYaxis().SetTitle(
        '95% C.L. upper limit [#sigma/#sigma_{theory}]')
    c2 = root.kOrange
    c1 = root.kGreen + 1
    graph2Sigma.SetLineColor(c2)
    graph1Sigma.SetLineColor(c1)
    graph2Sigma.SetFillColor(c2)
    graph1Sigma.SetFillColor(c1)
    graph2Sigma.SetMinimum(0.5 * minval)
    graph2Sigma.SetMaximum(10 * maxval)
    graphCent.SetLineWidth(2)
    graphCent.SetLineStyle(2)
    graphObs.SetLineColor(1)
    graphObs.SetLineWidth(3)
    graphObs.SetMarkerStyle(20)
    graphObs.SetMarkerSize(1)
    graphObs.SetMarkerColor(1)
    graph1Sigma.SetLineStyle(0)
    graph2Sigma.SetLineStyle(0)

    leg = TLegend(0.55, 0.7, 0.9, 0.9)
    leg.AddEntry(graphCent, 'Expected', 'L')
    if not BLIND:
        leg.AddEntry(graphObs, 'Observed', 'Lp')
    leg.AddEntry(graph1Sigma, '1 std. dev.', 'F')
    leg.AddEntry(graph2Sigma, '2 std. dev.', 'F')
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    graph2Sigma.Draw('A3')
    graph1Sigma.Draw('3 same')
    graphCent.Draw('same L')
    if not BLIND:
        graphObs.Draw('same Lp')

    subscript = 'SR' if 'Resonant' in plottitle else 'FC'
    coupling = '0.1' if 'Resonant' in plottitle else '0.25'

    graphXsec.SetLineColor(2)
    graphXsec.SetLineWidth(2)
    graphXsec.SetLineStyle(2)
    graphXsec.SetFillColor(2)
    graphXsec.SetFillStyle(3005)
    graphXsec.Draw('same L3')
    '''
  if not scale:
    if 'Resonant' in plottitle:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=100 GeV}'%(subscript,subscript,coupling),'l')
    else:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=10 GeV}'%(subscript,subscript,coupling),'l')
  '''
    if not BLIND:
        findIntersect1D(graphObs, graphXsec, xaxis[0], xaxis[-1])
    findIntersect1D(graphCent, graphXsec, xaxis[0], xaxis[-1])

    leg.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.8 * c.GetTopMargin())
    label.SetTextFont(62)
    label.SetTextAlign(11)
    label.DrawLatex(0.15, 0.94, "CMS")
    label.SetTextFont(52)
    label.SetTextSize(0.6 * c.GetTopMargin())
    #  label.DrawLatex(0.25,0.94,"Preliminary")
    label.SetTextFont(42)
    label.SetTextSize(0.7 * c.GetTopMargin())
    label.DrawLatex(0.19, 0.83, plottitle)
    if 'Resonant' in plottitle:
        label.DrawLatex(0.19, 0.75, "a_{SR} = b_{SR} = %s" % coupling)
        label.DrawLatex(0.19, 0.68, "m_{#chi}=100 GeV")
    else:
        label.DrawLatex(0.19, 0.75, "g_{DM}^{V}=1,g_{q}^{V}=0.25")
        label.DrawLatex(0.19, 0.68, "m_{#chi}=1 GeV")
    label.SetTextSize(0.6 * c.GetTopMargin())
    label.SetTextFont(42)
    label.SetTextAlign(31)  # align right
    label.DrawLatex(0.95, 0.94, "%.1f fb^{-1} (13 TeV)" % (plotConfig.lumi))

    c.SaveAs(foutname + '.pdf')
    c.SaveAs(foutname + '.png')
Ejemplo n.º 17
0
            H8_Projection_40TeV.Sumw2()
            H8_Projection_40TeV.Scale(1 / H8_Projection_40TeV.Integral())
            Fraction_WW_Use = H8_Projection_40TeV.GetBinContent(Sort_particle)
            Fraction_WW_40TeV.append(Fraction_WW_Use)
            Y_Error_WW_40TeV.append(
                np.sqrt(H8_Projection_40TeV.GetEntries() * Fraction_WW_Use *
                        (1 - Fraction_WW_Use)) /
                H8_Projection_40TeV.GetEntries())
        else:
            Y_Error_WW_40TeV.append(0)
            Fraction_WW_40TeV.append(0)

    gr_QQ_5TeV = TGraphErrors(4, X_PT, Fraction_QQ_5TeV, X_Error,
                              Y_Error_QQ_5TeV)
    gr_QQ_5TeV.SetLineColor(1)
    gr_QQ_5TeV.SetLineWidth(1)
    gr_QQ_5TeV.SetLineStyle(1)
    gr_QQ_5TeV.SetMarkerColor(1)
    gr_QQ_5TeV.SetMarkerStyle(8)
    gr_QQ_5TeV.SetMarkerSize(1)
    gr_QQ_5TeV.GetXaxis().SetTitle("Log(PT)")
    gr_QQ_5TeV.GetYaxis().SetTitle("Arbitrary")

    gr_WW_5TeV = TGraphErrors(4, X_PT, Fraction_WW_5TeV, X_Error,
                              Y_Error_WW_5TeV)
    gr_WW_5TeV.SetLineColor(2)
    gr_WW_5TeV.SetLineWidth(1)
    gr_WW_5TeV.SetLineStyle(1)
    gr_WW_5TeV.SetMarkerColor(2)
    gr_WW_5TeV.SetMarkerStyle(8)
    gr_WW_5TeV.SetMarkerSize(1)
Ejemplo n.º 18
0
leg.AddEntry(jetRatePlot, "Jets", "l")
leg.AddEntry(jetToMETRatePlot, "MET", "l")
leg.AddEntry(jetToElectronRatePlot, "Electrons", "l")
leg.AddEntry(jetToMuonRatePlot, "Muons", "l")

## Removing stat info
#jetRatePlot.SetStats(False)
#jetToMuonRatePlot.SetStats(False)
#jetToElectronRatePlot.SetStats(False)
## jetToPhotonRatePlot.SetStats(False)
#jetToMETRatePlot.SetStats(False)

# Plotting stuff
ratePlot.Add(jetRatePlot, "A3L")
jetRatePlot.SetFillStyle(1001)
jetRatePlot.SetLineWidth(2)
jetRatePlot.SetLineStyle(1)
ratePlot.Add(jetToMuonRatePlot, "A3")
jetToMuonRatePlot.SetFillStyle(1001)
jetToMuonRatePlot.SetLineWidth(2)
jetToMuonRatePlot.SetLineStyle(1)
ratePlot.Add(jetToElectronRatePlot, "A3")
jetToElectronRatePlot.SetFillStyle(1001)
jetToElectronRatePlot.SetLineWidth(2)
jetToElectronRatePlot.SetLineStyle(1)
# ratePlot.Add(jetToPhotonRatePlot, "A3")
# jetToPhotonRatePlot.SetFillStyle(1001)
# jetToPhotonRatePlot.SetLineWidth(2)
# jetToPhotonRatePlot.SetLineStyle(1)
ratePlot.Add(jetToMETRatePlot, "A3")
jetToMETRatePlot.SetFillStyle(1001)
Ejemplo n.º 19
0
def draw(hist,
         var_type,
         log='',
         plotdir=None,
         plotname='foop',
         more_hists=None,
         write_csv=False,
         stats=None,
         bounds=None,
         errors=False,
         shift_overflows=False,
         csv_fname=None,
         scale_errors=None,
         rebin=None,
         plottitle='',
         colors=None,
         linestyles=None,
         cwidth=None,
         cheight=None,
         imagetype='svg',
         xtitle=None,
         ytitle=None,
         xline=None,
         yline=None,
         draw_str=None,
         normalize=False,
         normalization_bounds=None,
         linewidths=None,
         markersizes=None,
         no_labels=False,
         graphify=False,
         translegend=(0.0, 0.0)):
    assert os.path.exists(plotdir)
    if not has_root:
        return

    if normalization_bounds is not None:
        assert bounds is None
    if bounds is not None:
        assert normalization_bounds is None

    cvn = TCanvas('cvn-' + plotname, '', 700 if cwidth is None else cwidth,
                  600 if cheight is None else cheight)

    hists = [
        hist,
    ]
    if more_hists != None:
        hists = hists + more_hists

    xmin, xmax, ymax = None, None, None
    ih = 0
    for htmp in hists:
        if rebin is not None:
            htmp.Rebin(rebin)
        if scale_errors is not None:
            factor = float(
                scale_errors[0]) if len(scale_errors) == 1 else float(
                    scale_errors[ih])
            for ibin in range(htmp.GetNbinsX() + 2):
                htmp.SetBinError(ibin, htmp.GetBinError(ibin) * factor)

        if not normalize:
            assert normalization_bounds is None
            if bounds is not None:
                ibin_start = htmp.FindBin(bounds[0])
                ibin_end = htmp.FindBin(bounds[1])
                this_y_max = GetMaximumWithBounds(
                    htmp,
                    htmp.GetXaxis().GetBinLowEdge(ibin_start),
                    htmp.GetXaxis().GetBinUpEdge(ibin_end))
            else:
                this_y_max = htmp.GetMaximum()
        else:  # renormalize the hist within these bounds
            if normalization_bounds is None:
                factor = 1. / htmp.Integral() if htmp.Integral() > 0.0 else 0.0
                htmp.Scale(factor)
                this_y_max = htmp.GetMaximum()
            else:
                ibin_start = 0 if normalization_bounds[
                    0] is None else htmp.FindBin(normalization_bounds[0])
                ibin_end = htmp.GetNbinsX(
                ) if normalization_bounds[1] is None else htmp.FindBin(
                    normalization_bounds[1])
                factor = htmp.Integral(ibin_start, ibin_end) if htmp.Integral(
                    ibin_start, ibin_end
                ) > 0.0 else 0.0  # NOTE this is inclusive, i.e. includes <ibin_end>
                htmp.Scale(factor)
                this_y_max = GetMaximumWithBounds(
                    htmp,
                    htmp.GetXaxis().GetBinLowEdge(ibin_start),
                    htmp.GetXaxis().GetBinUpEdge(ibin_end))

        if ymax is None or this_y_max > ymax:
            ymax = this_y_max

        if xmin is None or htmp.GetBinLowEdge(1) < xmin:
            xmin = htmp.GetBinLowEdge(1)
        if xmax is None or htmp.GetXaxis().GetBinUpEdge(
                htmp.GetNbinsX()) > xmax:
            xmax = htmp.GetXaxis().GetBinUpEdge(htmp.GetNbinsX())

        ih += 1

    if bounds is not None:
        xmin, xmax = bounds
    hframe = TH1D('hframe', '', hist.GetNbinsX(), xmin, xmax)
    if not no_labels and (var_type == 'string' or var_type == 'bool'):
        for ib in range(1, hframe.GetNbinsX() + 1):
            hframe.GetXaxis().SetBinLabel(ib, hist.GetXaxis().GetBinLabel(ib))

    if 'y' in log:
        hframe.SetMaximum(3 * ymax)
    else:
        hframe.SetMaximum(1.2 * ymax)
    if var_type == 'bool':
        hframe.GetXaxis().SetLabelSize(0.1)

    if plottitle == '':
        plottitle = plotname

    if xtitle is None:
        xtitle = hist.GetXaxis().GetTitle()
    if ytitle is None:
        ytitle = hframe.GetYaxis().GetTitle()

    hframe.SetTitle(plottitle + ';' + xtitle + ';' + ytitle)
    # gStyle.SetTitleFontSize(.075)
    # gStyle.SetTitleY(gStyle.GetTitleY() + .0004)
    if cwidth is not None:
        gStyle.SetTitleOffset(0.99 * gStyle.GetTitleOffset('y'), 'y')
    # gStyle.SetTitleFillStyle(0)
    # hframe.SetTitleSize(gStyle.GetTitleSize())
    # hframe.SetTitleFont(gStyle.GetTitleFont())
    hframe.Draw('txt')

    if shift_overflows:
        for htmp in hists:
            if htmp == None:
                continue
            underflows, overflows = 0.0, 0.0
            first_shown_bin, last_shown_bin = -1, -1
            for ib in range(0, htmp.GetXaxis().GetNbins() + 2):
                if htmp.GetXaxis().GetBinCenter(ib) <= xmin:
                    underflows += htmp.GetBinContent(ib)
                    htmp.SetBinContent(ib, 0.0)
                elif first_shown_bin == -1:
                    first_shown_bin = ib
                else:
                    break
            for ib in reversed(range(0, htmp.GetXaxis().GetNbins() + 2)):
                if htmp.GetXaxis().GetBinCenter(ib) >= xmax:
                    overflows += htmp.GetBinContent(ib)
                    htmp.SetBinContent(ib, 0.0)
                elif last_shown_bin == -1:
                    last_shown_bin = ib
                else:
                    break

            if 'd_hamming' in plotname:
                print htmp.GetTitle()
                print '  underflow', underflows, htmp.GetBinContent(
                    first_shown_bin)
                print '  overflow', overflows, htmp.GetBinContent(
                    last_shown_bin)
                print '  first', htmp.GetXaxis().GetBinCenter(first_shown_bin)
                print '  last', htmp.GetXaxis().GetBinCenter(last_shown_bin)
            htmp.SetBinContent(
                first_shown_bin,
                underflows + htmp.GetBinContent(first_shown_bin))
            htmp.SetBinContent(last_shown_bin,
                               overflows + htmp.GetBinContent(last_shown_bin))

    if colors is None:
        assert len(hists) < 5
        colors = (kRed, kBlue - 4, kGreen + 2, kOrange + 1
                  )  # 632, 596, 418, 801
    else:
        assert len(hists) <= len(colors)
    if linestyles is None:
        # assert len(hists) < 5
        linestyles = [1 for _ in range(len(hists))]
    else:
        assert len(hists) <= len(linestyles)

    # legends
    x0, y0, x1, y1 = 0.57 + translegend[0], 0.66 + translegend[
        1], 0.99 + translegend[0], 0.88 + translegend[1]
    if len(hists) < 5:
        leg = TLegend(x0, y0, x1, y1)
    else:
        leg = TLegend(x0, y0 - 0.05, x1, y1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    # draw
    if graphify:
        graphs = []
        for ih in range(len(hists)):
            htmp = hists[ih]
            n_bins = hists[ih].GetNbinsX()
            xvals, yvals, xerrs, yerrs = array(
                'f', [0 for i in range(n_bins)]), array(
                    'f', [0 for i in range(n_bins)]), array(
                        'f', [0 for i in range(n_bins)]), array(
                            'f', [0 for i in range(n_bins)])
            for ib in range(1, n_bins + 1):  # NOTE ignoring overflows
                xvals[ib - 1] = hists[ih].GetXaxis().GetBinCenter(ib)
                xerrs[ib - 1] = 0.0
                yvals[ib - 1] = hists[ih].GetBinContent(ib)
                yerrs[ib - 1] = hists[ih].GetBinError(ib) if errors else 0.0
            gr = TGraphErrors(n_bins, xvals, yvals, xerrs, yerrs)

            if markersizes is not None:
                imark = ih if len(markersizes) > 1 else 0
                gr.SetMarkerSize(markersizes[imark])
            gr.SetMarkerColor(colors[ih])
            if linewidths is None:
                if ih < 6:  # and len(hists) < 5:
                    gr.SetLineWidth(6 - ih)
            else:
                ilw = ih if len(linewidths) > 1 else 0
                gr.SetLineWidth(linewidths[ilw])
            gr.SetLineColor(colors[ih])
            # if int(linewidth) == 1:
            #     gr.SetLineColorAlpha(colors[ih], 0.4)
            gr.SetLineStyle(linestyles[ih])

            if draw_str is None:
                draw_str = 'lpz'
            if hists[ih].Integral() != 0.0:
                gr.Draw(draw_str + ' same')

                statstr = ''
                if stats is not None:
                    if 'rms' in stats:
                        statstr += ' (%.2f)' % htmp.GetRMS()
                    if 'mean' in stats:
                        statstr += ' (%.2f)' % htmp.GetMean()
                    if '0-bin' in stats:
                        statstr += ' (%.2f)' % htmp.GetBinContent(1)

                leg.AddEntry(gr, hists[ih].GetTitle() + ' ' + statstr, 'pl')

            graphs.append(
                gr
            )  # yes, you really do have to do this to keep root from giving you only one graph
    else:
        if draw_str is None:
            draw_str = 'hist same'
        else:
            draw_str += ' same'
        if errors:
            draw_str += ' e'
        for ih in range(len(hists)):
            htmp = hists[ih]

            if stats is not None:
                if 'rms' in stats:
                    htmp.SetTitle(htmp.GetTitle() +
                                  (' (%.2f)' % htmp.GetRMS()))
                if 'mean' in stats:
                    htmp.SetTitle(htmp.GetTitle() +
                                  (' (%.2f)' % htmp.GetMean()))
                if '0-bin' in stats:
                    htmp.SetTitle(htmp.GetTitle() +
                                  (' (%.2f)' % htmp.GetBinContent(1)))

            htmp.SetLineColor(colors[ih])
            if markersizes is not None:
                imark = ih if len(markersizes) > 1 else 0
                htmp.SetMarkerSize(markersizes[imark])
            htmp.SetMarkerColor(colors[ih])
            htmp.SetLineStyle(linestyles[ih])
            if linewidths is None:
                if ih < 6:  # and len(hists) < 5:
                    htmp.SetLineWidth(6 - ih)
            else:
                ilw = ih if len(linewidths) > 1 else 0
                htmp.SetLineWidth(linewidths[ilw])

            leg.AddEntry(htmp, htmp.GetTitle(), 'l')
            htmp.Draw(draw_str)

    leg.Draw()

    if xline is not None:
        # if xline < hframe.GetXaxis().GetXmin() or xline > hframe.GetXaxis().GetXmax():  # make sure we got valid a x position for the line
        #     print 'WARNING plotting x line at %f out of bounds (%f, %f)' % (float(xmin), hframe.GetXaxis().GetXmin(), hframe.GetXaxis().GetXmax())
        # xl = TLine(xline, hframe.GetYaxis().GetXmin(), xline, 0.5*ymax)
        xl = TLine(xline, -0.1 * ymax, xline, 0.5 * ymax)
        xl.SetLineStyle(2)
        xl.Draw()
    if yline is not None:
        # if yline < hframe.GetYaxis().GetXmin() or xline > hframe.GetYaxis().GetXmax():  # make sure we got valid a x position for the line
        #     print 'WARNING plotting y line at %f out of bounds (%f, %f)' % (float(ymin), hframe.GetYaxis().GetXmin(), hframe.GetYaxis().GetXmax())
        yl = TLine(hframe.GetXaxis().GetXmin(), yline,
                   hframe.GetXaxis().GetXmax(), yline)
        yl.Draw()

    cvn.SetLogx('x' in log)
    cvn.SetLogy('y' in log)
    if not os.path.exists(plotdir + '/plots'):
        print 'ERROR dir \'' + plotdir + '/plots\' d.n.e.'
        assert False

    if write_csv:
        assert more_hists == None
        if csv_fname == None:
            write_hist_to_file(plotdir + '/plots/' + plotname + '.csv', hist)
        else:
            write_hist_to_file(csv_fname, hist)
    cvn.SaveAs(plotdir + '/plots/' + plotname + '.' + imagetype)
Ejemplo n.º 20
0
                continue
            title = fLine[9:]

#define some data points . . .
x = array('f', kineticEnergy)
y = array('f', crossSec)
exl = array('f', zero)
exr = array('f', zero)

nPoints = len(x)
# . . . and hand over to TGraphErros object
gr = TGraphErrors(nPoints, x, y, exl, exr)
gr.SetTitle(title + "; Kinetic Energy [MeV]; Cross Section [barn]")
gr.GetXaxis().SetRangeUser(0, 1000)
gr.GetYaxis().SetRangeUser(0, 2.)
gr.SetLineWidth(2)
gr.SetLineColor(kGreen - 2)
gr.SetFillColor(0)

## Data
data_FileName = "/Volumes/Seagate/Elena/TPC/Data60A.root"
data_File = TFile.Open(data_FileName)
interactingPlotString = "RecoXS/hRecoInteractingKE"
incidentPlotString = "RecoXS/hRecoIncidentKE"
data_Int = data_File.Get(interactingPlotString)
data_Inc = data_File.Get(incidentPlotString)
XSDataRecoPion = data_Int.Clone("pionMCXSData")
XSDataRecoPion.Sumw2()
data_Inc.Sumw2()
XSDataRecoPion.Scale(101.10968)
XSDataRecoPion.Divide(data_Inc)