Exemplo n.º 1
0
def set_pub_style():
    from ROOT import gStyle
    # No Canvas Border
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetCanvasBorderSize(0)
    # White BG
    gStyle.SetCanvasColor(10)
    # Format for axes
    gStyle.SetLabelFont(42, 'xyz')
    gStyle.SetLabelSize(0.05, 'xyz')
    gStyle.SetLabelOffset(0.01, 'xyz')
    # gStyle->SetNdivisions(510, 'xyz')
    gStyle.SetTitleFont(42, 'xyz')
    gStyle.SetTitleColor(1, 'xyz')
    gStyle.SetTitleSize(0.06, 'xyz')
    gStyle.SetTitleOffset(1.25, 'xyz')
    # No pad borders
    gStyle.SetPadBorderMode(0)
    gStyle.SetPadBorderSize(0)
    # White BG
    gStyle.SetPadColor(10)
    # Margins for labels etc.
    gStyle.SetPadLeftMargin(0.155)
    gStyle.SetPadBottomMargin(0.155)
    gStyle.SetPadRightMargin(0.15)
    gStyle.SetPadTopMargin(0.1)
    # No error bars in x direction
    gStyle.SetErrorX(0)
    # Format legend
    gStyle.SetLegendBorderSize(0)
Exemplo n.º 2
0
def main(extension, network_name, luminosity, output_flag, output_mod,
         veto_all_jets, generator, extra_text, fudge, text,
         Independant_Variable_List, Variable_list, WP_list, MC_list,
         Real_Data):
    gROOT.SetStyle("ATLAS")
    gROOT.ForceStyle()
    gStyle.SetErrorX(0.5)
    TH1.SetDefaultSumw2()

    OUTPUT_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Output")

    ## Changing the name of the input file to match the generator
    if generator == "PowhegPythia":
        pass
    elif generator == "Sherpa":
        MC_list[0].file = "S" + MC_list[0].file
    elif generator == "MadGraph":
        MC_list[0].file = "MG" + MC_list[0].file
    else:
        print("\n\n\nUnknown Generator option\n\n\n")
        return 0

    ## Changing the name of the input files to match the jet selection
    if veto_all_jets:
        for mc in MC_list:
            mc.file = mc.file + "_NOJETS"
        Real_Data.file = Real_Data.file + "_NOJETS"
        extra_text += "0 Jets"

    ########## Plotting the independant variables ##########
    for ivar in Independant_Variable_List:
        STACK(extension, OUTPUT_dir, network_name, luminosity, output_flag,
              output_mod, generator, extra_text, fudge, text, MC_list,
              Real_Data, ivar, None)

    ########## Loading and Plotting the TH1Ds ##########
    for var in Variable_list:
        for wp in WP_list:

            STACK(extension, OUTPUT_dir, network_name, luminosity, output_flag,
                  output_mod, generator, extra_text, fudge, text, MC_list,
                  Real_Data, var, wp)

    return 0
Exemplo n.º 3
0
    def initialize2(self):
        # For the canvas:
        gStyle.SetCanvasBorderMode(0)
        gStyle.SetCanvasColor(kWhite)
        gStyle.SetCanvasDefH(600)  #Height of canvas
        gStyle.SetCanvasDefW(600)  #Width of canvas
        gStyle.SetCanvasDefX(0)  #POsition on screen
        gStyle.SetCanvasDefY(0)

        # For the Pad:
        gStyle.SetPadBorderMode(0)
        # gStyle.SetPadBorderSize(Width_t size = 1)
        gStyle.SetPadColor(kWhite)
        gStyle.SetPadGridX(False)
        gStyle.SetPadGridY(False)
        gStyle.SetGridColor(0)
        gStyle.SetGridStyle(3)
        gStyle.SetGridWidth(1)

        # For the frame:
        gStyle.SetFrameBorderMode(0)
        gStyle.SetFrameBorderSize(1)
        gStyle.SetFrameFillStyle(1000)
        gStyle.SetFrameFillColor(0)
        gStyle.SetFrameFillStyle(0)
        gStyle.SetFrameLineColor(1)
        gStyle.SetFrameLineStyle(1)
        gStyle.SetFrameLineWidth(1)

        # For the histo:
        # gStyle.SetHistFillColor(1)
        # gStyle.SetHistFillStyle(0)
        gStyle.SetHistLineColor(1)
        gStyle.SetHistLineStyle(0)
        gStyle.SetHistLineWidth(1)
        # gStyle.SetLegoInnerR(Float_t rad = 0.5)
        # gStyle.SetNumberContours(Int_t number = 20)

        gStyle.SetEndErrorSize(2)
        # gStyle.SetErrorMarker(20)
        gStyle.SetErrorX(0.)

        gStyle.SetMarkerStyle(20)

        #For the fit/function:
        gStyle.SetOptFit(1)
        gStyle.SetFitFormat("5.4g")
        gStyle.SetFuncColor(2)
        gStyle.SetFuncStyle(1)
        gStyle.SetFuncWidth(1)

        #For the date:
        gStyle.SetOptDate(0)
        # gStyle.SetDateX(Float_t x = 0.01)
        # gStyle.SetDateY(Float_t y = 0.01)

        # For the statistics box:
        gStyle.SetOptFile(0)
        gStyle.SetOptStat(
            0)  # To display the mean and RMS:         SetOptStat("mr")
        gStyle.SetStatColor(kWhite)
        gStyle.SetStatFont(42)
        gStyle.SetStatFontSize(0.025)
        gStyle.SetStatTextColor(1)
        gStyle.SetStatFormat("6.4g")
        gStyle.SetStatBorderSize(1)
        gStyle.SetStatH(0.1)
        gStyle.SetStatW(0.15)
        # gStyle.SetStatStyle(Style_t style = 1001)
        # gStyle.SetStatX(Float_t x = 0)
        # gStyle.SetStatY(Float_t y = 0)

        # Margins:
        gStyle.SetPadTopMargin(0.05)
        gStyle.SetPadBottomMargin(0.13)
        gStyle.SetPadLeftMargin(0.16)
        gStyle.SetPadRightMargin(0.02)

        # For the Global title:

        gStyle.SetOptTitle(0)
        gStyle.SetTitleFont(42)
        gStyle.SetTitleColor(1)
        gStyle.SetTitleTextColor(1)
        gStyle.SetTitleFillColor(10)
        gStyle.SetTitleFontSize(0.05)
        # gStyle.SetTitleH(0) # Set the height of the title box
        # gStyle.SetTitleW(0) # Set the width of the title box
        # gStyle.SetTitleX(0) # Set the position of the title box
        # gStyle.SetTitleY(0.985) # Set the position of the title box
        # gStyle.SetTitleStyle(Style_t style = 1001)
        # gStyle.SetTitleBorderSize(2)

        # For the axis titles:

        gStyle.SetTitleColor(1, "XYZ")
        gStyle.SetTitleFont(42, "XYZ")
        gStyle.SetTitleSize(0.06, "XYZ")
        # gStyle.SetTitleXSize(Float_t size = 0.02) # Another way to set the size?
        # gStyle.SetTitleYSize(Float_t size = 0.02)
        gStyle.SetTitleXOffset(0.9)
        gStyle.SetTitleYOffset(1.25)
        # gStyle.SetTitleOffset(1.1, "Y") # Another way to set the Offset

        # For the axis labels:

        gStyle.SetLabelColor(1, "XYZ")
        gStyle.SetLabelFont(42, "XYZ")
        gStyle.SetLabelOffset(0.007, "XYZ")
        gStyle.SetLabelSize(0.05, "XYZ")

        # For the axis:

        gStyle.SetAxisColor(1, "XYZ")
        gStyle.SetStripDecimals(True)
        gStyle.SetTickLength(0.03, "XYZ")
        gStyle.SetNdivisions(510, "XYZ")
        gStyle.SetPadTickX(
            1)  # To get tick marks on the opposite side of the frame
        gStyle.SetPadTickY(1)

        # Change for log plots:
        gStyle.SetOptLogx(0)
        gStyle.SetOptLogy(0)
        gStyle.SetOptLogz(0)

        # Postscript options:
        gStyle.SetPaperSize(20., 20.)
Exemplo n.º 4
0
from ROOT import TCanvas, TColor, TGaxis, TH1F, TPad, TFile, TGraphAsymmErrors, TLatex, TLine, gStyle, TLegend, gROOT
from ROOT import kBlack, kBlue, kRed
from array import array

f = TFile.Open('Output_HLT_JetMET_ntupels.root')
f2 = TFile.Open('Output_HLT_JetMET_ntupels_NoF.root')

#f = TFile.Open('Output_HLT_JetMET_ntupels.root')
#f2 = TFile.Open('Output_Full_withoutFilter1_ntuples.root')
gStyle.SetErrorX(0.5)
# gStyle.SetFrameLineWidth(3)
# gStyle.SetOptTitle(0)
# gStyle.SetOptStat(0)
gStyle.SetLegendBorderSize(0)
# gStyle.SetFillColor(2)
# gStyle.SetLineWidth(1)
# gStyle.SetHistFillStyle(2)
gROOT.SetBatch(1)
#bins=[0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150,160,170,180,190,200,220,240,260,280,300,350,400,500,600,700,800,1000,1200,1500,2000]
bins = [
    0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90,
    95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 160, 170, 180,
    190, 200, 220, 240, 260, 280, 300, 350, 400, 500, 600, 700, 800, 900, 1000,
    1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000
]

#bins=[500,550,600,650,700,750,800,850,900,950,1000,1050,1100,1150,1200,1250,1300,1350,1400,1450,1500,1550,1600,1650,1700,1750,1800,1850,1900,1950,2000]
#bins=[500,550,600,2000]
#bins=[700,700+260,700+260+260,700+260+260+260,700+260+260+260+260,2000]

Exemplo n.º 5
0
def setTDRStyle(force):

  gStyle.SetCanvasBorderMode(0)
  gStyle.SetCanvasColor(kWhite)
  gStyle.SetCanvasDefH(600)
  gStyle.SetCanvasDefW(600)
  gStyle.SetCanvasDefX(0)
  gStyle.SetCanvasDefY(0)

  gStyle.SetPadBorderMode(0)
  gStyle.SetPadColor(kWhite)
  gStyle.SetPadGridX(False)
  gStyle.SetPadGridY(False)
  gStyle.SetGridColor(0)
  gStyle.SetGridStyle(3)
  gStyle.SetGridWidth(1)

  gStyle.SetFrameBorderMode(0)
  gStyle.SetFrameBorderSize(1)
  gStyle.SetFrameFillColor(0)
  gStyle.SetFrameFillStyle(0)
  gStyle.SetFrameLineColor(1)
  gStyle.SetFrameLineStyle(1)
  gStyle.SetFrameLineWidth(1)

  if force:
      gStyle.SetHistLineColor(1)
      gStyle.SetHistLineStyle(0)
      gStyle.SetHistLineWidth(1)


  gStyle.SetEndErrorSize(2)
  gStyle.SetErrorX(0.)

  gStyle.SetMarkerStyle(20)

  gStyle.SetOptFit(1)
  gStyle.SetFitFormat("5.4g")
  gStyle.SetFuncColor(2)
  gStyle.SetFuncStyle(1)
  gStyle.SetFuncWidth(1)

  gStyle.SetOptDate(0)

  gStyle.SetOptFile(0)
  gStyle.SetOptStat(0)
  gStyle.SetStatColor(kWhite)
  gStyle.SetStatFont(42)
  gStyle.SetStatFontSize(0.04)
  gStyle.SetStatTextColor(1)
  gStyle.SetStatFormat("6.4g")
  gStyle.SetStatBorderSize(1)
  gStyle.SetStatH(0.1)
  gStyle.SetStatW(0.2)


  gStyle.SetPadTopMargin(0.05)
  gStyle.SetPadBottomMargin(0.13)
  gStyle.SetPadLeftMargin(0.16)
  gStyle.SetPadRightMargin(0.04)


  gStyle.SetOptTitle(0)
  gStyle.SetTitleFont(42)
  gStyle.SetTitleColor(1)
  gStyle.SetTitleTextColor(1)
  gStyle.SetTitleFillColor(10)
  gStyle.SetTitleFontSize(0.05)


  gStyle.SetTitleColor(1, "XYZ")
  gStyle.SetTitleFont(42, "XYZ")
  gStyle.SetTitleSize(0.06, "XYZ")
  gStyle.SetTitleXOffset(0.9)
  gStyle.SetTitleYOffset(1.25)


  gStyle.SetLabelColor(1, "XYZ")
  gStyle.SetLabelFont(42, "XYZ")
  gStyle.SetLabelOffset(0.007, "XYZ")
  gStyle.SetLabelSize(0.05, "XYZ")


  gStyle.SetAxisColor(1, "XYZ")
  gStyle.SetStripDecimals(True)
  gStyle.SetTickLength(0.03, "XYZ")
  gStyle.SetNdivisions(510, "XYZ")
  gStyle.SetPadTickX(1)
  gStyle.SetPadTickY(1)

  gStyle.SetOptLogx(0)
  gStyle.SetOptLogy(0)
  gStyle.SetOptLogz(0)

  gStyle.SetPaperSize(20.,20.)


  gROOT.ForceStyle()
Exemplo n.º 6
0
def Draw_1D_Comp(rootfile_name, var, min, max, WP_list, leg, isTail=False):
    gStyle.SetErrorX(0.5)

    ## The TStack is created with min and max set
    stack = THStack("stack", var.name)
    stack.SetMinimum(min)
    stack.SetMaximum(max)

    for wp in WP_list:

        ## Loading the graph using its name and file location
        graph_name = "{}_{}".format(var.name, wp.name)
        if isTail:
            graph_name += "_cumulative"

        graph = GetGraphFromFile(rootfile_name, graph_name)
        if graph == -1:
            continue

        ## Setting the colors specific to the working point
        graph.SetLineColor(wp.colour)
        graph.SetMarkerColor(wp.colour)
        graph.SetMarkerStyle((wp.marker))

        leg.AddEntry(graph, wp.name, "p")

        width = graph.GetBinWidth(0)

        ## We check if the legend requires values for statistics
        if leg.GetNColumns() == 2:

            ## Calculate the MEAN and RMSE and add to the legend
            mean = graph.GetMean()
            stdev = graph.GetStdDev()
            rms = np.sqrt(mean * mean + stdev * stdev)

            ## Adding the legend entry
            # leg.AddEntry( 0, "{:5.2f}".format(mean), "")
            leg.AddEntry(0, "{:5.2f}".format(rms), "")

        ## Adding the object to the stack
        stack.Add(graph)
        del graph

    ## Checking to see if any graphs were found for this variable
    if stack.GetNhists() == 0:
        print("\n\n\nNo graphs found for working point {}\n\n\n".format(
            wp.name))
        return -1

    ## Drawing the stack on the currrent canvas
    stack.Draw("nostack EP")
    leg.Draw()

    ## Setting axis labels
    if isTail:
        stack.GetXaxis().SetTitle(var.x_label + " threshold " + var.units)
        stack.GetYaxis().SetTitle("#it{f}_{tail}")
    else:
        stack_y_label = "Events per {:.0f} GeV".format(
            width) if width > 1 else "Events per GeV"

        stack.GetXaxis().SetTitle(var.x_label + " " + var.units)
        stack.GetYaxis().SetTitle(stack_y_label)

    ## Moving axis tick marks
    stack.GetYaxis().SetMaxDigits(3)
    stack.GetXaxis().SetLabelOffset(0.017)

    return stack
Exemplo n.º 7
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
Exemplo n.º 8
0
def main():

    extension = "pdf"

    luminosity = 44307.4
    ymin = 0
    ymax = 0.024

    data_set_names = [
        (["SZee_all_susy_2l_0jets.root",
          "SZmumu_all_susy_2l_0jets.root"], "Z#rightarrowll", 860 + 0, 23),
        (["ZZ_1in3_susy_2l_0jets.root"], "ZZ#rightarrowll#nu#nu", 416 + 3, 43),
        (["WZ_1in3_susy_2l_0jets.root"], "WZ#rightarrowl#null", 416 - 8, 33),
        (["WW_1in3_susy_2l_0jets.root"], "WW#rightarrowl#nul#nu", 416 + 0, 20),
        ([
            "ttbar_1in3_susy_2l_0jets.root", "top_1in3_susy_2l_0jets.root",
            "antitop_1in3_susy_2l_0jets.root"
        ], "Top", 800 + 4, 21),
    ]

    DATA_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Data", "SR_SUSY")

    ## Creating the plots
    gROOT.SetStyle("ATLAS")
    gROOT.ForceStyle()
    gStyle.SetErrorX(0.5)
    canvas = TCanvas("canvas", 'A basic canvas', 800, 600)
    # canvas.SetLogy()

    ## Adding in the legend
    leg = Plotting.Create_Legend(0.60, 0.60, 0.95, 0.95, ncols=1)

    ## Creating the stack
    stack = THStack("stack", "stack")
    stack.SetMinimum(ymin)
    stack.SetMaximum(ymax)

    ## Cycling through the different datasets
    for datasets, label, colour, style in data_set_names:

        ## Creating the total histogram which will be filled
        myhist = TH1D(label, label, 50, 0, 150)
        myhist.SetStats(True)
        myhist.StatOverflows(True)

        for dataset in datasets:

            ## The root file is opened
            rootfile_name = os.path.join(DATA_dir, dataset)
            print(rootfile_name)
            root_file = TFile.Open(rootfile_name, 'read')
            tree = root_file.Get("mt2_Truth")

            ## Creating the current histogram which will be filled
            thishist = TH1D(label, label, 50, 0, 150)
            thishist.SetStats(True)
            thishist.StatOverflows(True)

            ## Drawing the tree and saving the hist to the matrix
            execution = "mt2>>{}".format(label)
            tree.Draw(execution, "", "goff")

            thishist.SetDirectory(0)
            myhist.Add(thishist)

            ## We are dont with the file
            root_file.Close()
            del root_file

        ## Changing the properties of the histogram
        myhist.Scale(1 / myhist.Integral("width"))

        myhist.SetLineColor(colour)
        myhist.SetMarkerColor(colour)
        myhist.SetMarkerStyle(style)
        myhist.SetMarkerSize(1.5)

        ## Adding the legend entry
        leg.AddEntry(myhist, label, "p")

        ## Adding the object to the stack
        stack.Add(myhist)
        del myhist

    ## Drawing the stack on the currrent canvas
    stack.Draw("NOSTACK HIST P")
    leg.Draw()

    ## Setting axis labels
    stack.GetXaxis().SetTitle("m_{T2} (True #it{E}_{T}^{miss}) [GeV]")
    stack.GetYaxis().SetTitle("Normalised Distributions")

    ## Moving axis tick marks
    stack.GetYaxis().SetMaxDigits(3)
    stack.GetXaxis().SetLabelOffset(0.017)

    ## Drawing all text
    left = 0.2
    size = 1.0
    shift = 0.06
    pos = 0.88
    Plotting.Draw_ATLASLabel(left, pos, "Simulation", scale=1.0)
    pos -= shift
    Plotting.Draw_Text(left, pos, "work in progress", scale=size)
    pos -= shift
    Plotting.Draw_Lumi(left, pos, 0, scale=size)
    pos -= shift

    ## Updating the canvas
    canvas.Update()

    out_file = "true_strans.{}".format(extension)
    canvas.Print(out_file)

    del canvas

    return 0
Exemplo n.º 9
0
def PlotDataMC(dataFiles_, mcFiles_, signalFiles_, dataDirec_, mcDirec_,
               signalDirec_, drawPads_, Lumi_, SigScale_, ol_, log_, Tags_,
               VarBatch_, CutsType_, verbose_, noQCD_):
    print "Plotting Data / MC"
    gROOT.ProcessLine(
        "gErrorIgnoreLevel = kError"
    )  # kPrint, kInfo, kWarning, kError, kBreak, kSysError, kFatal
    gStyle.SetOptStat(0)
    gStyle.SetErrorX(0.0001)
    HHWWggTags = []

    ##-- Get Tags
    for t in Tags_:
        HHWWggTags.append(t)
    cuts, cutNames = GetCuts(CutsType_)

    ##-- if var batch is loose, need separate titles for variables since it will be sum of vars * bools
    if (VarBatch_ == "Loose"):
        finalStateVars, varNames = GetVars(
            VarBatch_)  # get vars from var batch
        if (verbose_):
            print "finalStateVars = ", finalStateVars
            print "varNames = ", varNames
    else:
        finalStateVars = GetVars(VarBatch_)  # get vars from var batch
    if (verbose_):
        #print"cuts:",cuts
        print "cutNames:", cutNames
        print "vars:", finalStateVars

    ##-- For each data file (can just be one)
    for dF_ in dataFiles_:
        cutBatchTag_pairs = []
        dataNevents_list = []
        MC_names = []
        MC_Nevents_lists = []
        MC_Nevents_noweight_lists = []

        ##-- For each category (Ex: HHWWggTag_0, HHWWggTag_1, HHWWggTag_2, combined)
        for itag, HHWWggTag in enumerate(HHWWggTags):
            if (verbose_):
                print "tag:", HHWWggTag
            dPath = "%s/%s" % (dataDirec_, dF_)
            dFile = TFile.Open(dPath)
            if (HHWWggTag == "combined"):
                ch = TChain('tagsDumper/trees/Data_13TeV_HHWWggTag_0')
                ch.Add("%s/tagsDumper/trees/Data_13TeV_HHWWggTag_0" % (dPath))
                ch.Add("%s/tagsDumper/trees/Data_13TeV_HHWWggTag_1" % (dPath))
                ch.Add("%s/tagsDumper/trees/Data_13TeV_HHWWggTag_2" % (dPath))
            else:
                ch = TChain('tagsDumper/trees/Data_13TeV_%s' % (HHWWggTag))
                ch.Add(dPath)
            BLIND_CUT = "(CMS_hgg_mass < 115 || CMS_hgg_mass > 135)"
            MC_WEIGHT = "1*weight"
            ZERO_CUT = "ZERO_CUT"
            MC_CUT = "%s*(%s)*(%s)" % (MC_WEIGHT, BLIND_CUT, ZERO_CUT)
            DATA_CUT = "%s*(%s)" % (BLIND_CUT, ZERO_CUT)
            SIGNAL_CUT = "%s*(%s)" % (MC_WEIGHT, ZERO_CUT
                                      )  # no blind cut on signal

            ##-- For each cut
            for ic, cut in enumerate(cuts):
                #if(verbose_): print"Plotting with selection:",cut
                cutName = cutNames[ic]
                cutBatchTag = "%s_%s" % (cutName, HHWWggTag)
                cutBatchTag_pairs.append(cutBatchTag)
                dataNevents = -999
                these_MC_Nevents = []
                these_MC_Nevents_noweights = []
                outputFolder = "%s/%s" % (ol_, cutName)
                if (not os.path.exists(outputFolder)):
                    os.system('mkdir %s' % (outputFolder))
                    os.system('cp %s/index.php %s' % (ol_, outputFolder))
                MC_CUT += "*(%s)" % (cut)
                DATA_CUT += "*(%s)" % (cut)
                SIGNAL_CUT += "*(%s)" % (cut)

                ##-- For each variable
                for iv, v in enumerate(finalStateVars):
                    if (VarBatch_ == "Loose"): varTitle = varNames[iv]
                    else: varTitle = GetVarTitle(v)

                    if (verbose_): print "Plotting variable:", varTitle

                    MC_CUT = MC_CUT.replace(
                        "ZERO_CUT", "(%s != 0) && (%s != -999)" % (v, v))
                    DATA_CUT = DATA_CUT.replace(
                        "ZERO_CUT", "(%s != 0) && (%s != -999)" % (v, v))
                    SIGNAL_CUT = SIGNAL_CUT.replace(
                        "ZERO_CUT", "(%s != 0) && (%s != -999)" % (v, v))
                    MC_CUT_NOWEIGHT = MC_WEIGHT.replace(MC_WEIGHT, "(1)")

                    if (varTitle == "weight"):
                        MC_CUT = MC_CUT.replace(
                            MC_WEIGHT, "(1)"
                        )  # if you want to plot the "weight" variable, you should not scale it by weight!

                    ##-- Can add printing of cuts to debug
                    # if(verbose_):
                    # print"MC_CUT:",MC_CUT
                    # print"DATA_CUT:",DATA_CUT
                    ##--

                    legend = TLegend(0.55, 0.65, 0.89, 0.89)
                    legend.SetTextSize(0.025)
                    legend.SetBorderSize(0)
                    legend.SetFillStyle(0)
                    xbins, xmin, xmax = GetBins(varTitle)

                    ##-- Fill histogram with data
                    Data_h_tmp = TH1F('Data_h_tmp', varTitle, xbins, xmin,
                                      xmax)
                    Data_h_tmp.SetTitle("%s" % (varTitle))
                    Data_h_tmp.SetMarkerStyle(8)
                    exec('ch.Draw("%s >> Data_h_tmp","%s")' % (v, DATA_CUT))

                    ##-- Only save number of events for first variable. Should be same for all because same cut is used
                    if (iv == 0):
                        dataNevents = Data_h_tmp.GetEntries()
                        dataNevents_list.append(dataNevents)
                    # print"Blinded Data numEvents:",Data_h_tmp.GetEntries()
                    DataHist = Data_h_tmp.Clone("DataHist")
                    DataHist.SetDirectory(0)
                    legend.AddEntry(DataHist, "Data", "P")

                    ##-- Get histograms with MC Backgrounds
                    bkgStack = THStack("bkgStack", "bkgStack")
                    histos = []
                    histCategories = []
                    for i, mcF_ in enumerate(mcFiles_):
                        mcPath = "%s/%s" % (mcDirec_, mcF_)
                        mcFile = TFile.Open(mcPath)
                        treeName = GetMCTreeName(mcF_)
                        MC_Category = GetMCCategory(mcF_)
                        if (verbose_):
                            # print"Background File:",mcPath
                            print "Background:", MC_Category

                        ##-- If noQCD set to true, skip QCD for Tag_0 and Tag_1
                        if (MC_Category == "QCD") and (
                                noQCD_) and (HHWWggTag == "HHWWggTag_0"
                                             or HHWWggTag == "HHWWggTag_1"):
                            print "Skipping QCD"
                            these_MC_Nevents_noweights.append(
                                0)  # Set yields to 0 for table
                            these_MC_Nevents.append(
                                0)  # Set yields to 0 for table
                            if (itag == 0 and ic == 0 and iv == 0):
                                MCname = GetMCName(mcF_)
                                MC_names.append(
                                    MCname
                                )  # Skipping QCD, but still save name for yields because tag_2 may not be 0
                            continue

                        ##-- Define TChain based on categories
                        if (HHWWggTag == "combined"):
                            mc_ch = TChain(
                                'tagsDumper/trees/%s_13TeV_HHWWggTag_0' %
                                (treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_0" %
                                (mcPath, treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_1" %
                                (mcPath, treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_2" %
                                (mcPath, treeName))
                        else:
                            mc_ch = TChain('tagsDumper/trees/%s_13TeV_%s' %
                                           (treeName, HHWWggTag))
                            mc_ch.Add(mcPath)
                        xbins, xmin, xmax = GetBins(varTitle)
                        exec(
                            "MC_h_tmp_%s = TH1F('MC_h_tmp_%s',varTitle,xbins,xmin,xmax)"
                            % (i, i))
                        exec(
                            "MC_h_tmp_noweight_%s = TH1F('MC_h_tmp_noweight_%s',varTitle,xbins,xmin,xmax)"
                            % (i, i))
                        thisHist = eval("MC_h_tmp_%s" % (i))
                        mcColor = GetMCColor(MC_Category)

                        ##-- If GJet or QCD sample, need to remove prompt-prompt events
                        if (MC_Category == "GJet" or MC_Category == "QCD"):
                            if (verbose_): print "Remove prompt-prompt"
                            removePromptPromptCut = "(!((Leading_Photon_genMatchType == 1) && (Subleading_Photon_genMatchType == 1)))"  # selection: remove events where both photons are prompt
                            original_MC_CUT = "%s" % (MC_CUT)
                            this_MC_CUT = "%s*(%s)" % (original_MC_CUT,
                                                       removePromptPromptCut)
                            this_MC_CUT_NOWEIGHT = this_MC_CUT.replace(
                                MC_WEIGHT, "(1)")

                        eval("MC_h_tmp_%s.SetFillColor(eval(mcColor))" % (i))
                        eval("MC_h_tmp_%s.SetLineColor(eval(mcColor))" % (i))
                        if (MC_Category == "GJet" or MC_Category == "QCD"):
                            exec('mc_ch.Draw("%s >> MC_h_tmp_%s","%s")' %
                                 (v, i, this_MC_CUT))
                        else:
                            exec('mc_ch.Draw("%s >> MC_h_tmp_%s","%s")' %
                                 (v, i, MC_CUT))

                        eval("MC_h_tmp_%s.Scale(float(Lumi_))" % (i))

                        ##-- MC reweighting for HHWWgg backgrounds (turned off for now)
                        # reWeightVals = ReWeightMC(mcF_)
                        # doReWeight, reWeightScale = reWeightVals[0], reWeightVals[1]
                        # print"doReWeight,reWeightScale:",doReWeight, reWeightScale
                        # if(doReWeight):
                        #     if(verbose_):
                        #         print"ReWeighting MC"
                        #         print"With scale: ",reWeightScale
                        #     eval("MC_h_tmp_%s.Scale(float(reWeightScale))"%(i))
                        ##

                        ##-- Only save for 1st variable. Should be same for all variables
                        if (iv == 0):
                            if (MC_Category == "GJet" or MC_Category == "QCD"):
                                exec(
                                    'mc_ch.Draw("%s >> MC_h_tmp_noweight_%s","%s")'
                                    % (v, i, this_MC_CUT_NOWEIGHT))
                            else:
                                exec(
                                    'mc_ch.Draw("%s >> MC_h_tmp_noweight_%s","%s")'
                                    % (v, i, MC_CUT_NOWEIGHT))
                            these_MC_Nevents_noweights.append(
                                eval("MC_h_tmp_noweight_%s.Integral()" % (i)))
                            these_MC_Nevents.append(
                                eval("MC_h_tmp_%s.Integral()" % (i)))

                            ##-- Only need to get MC names once
                            if (itag == 0 and ic == 0 and iv == 0):
                                MCname = GetMCName(mcF_)
                                MC_names.append(
                                    MCname)  # get shorter MC name here

                        newHist = thisHist.Clone("newHist")
                        ##-- Set title based on treeName
                        newHist.SetTitle(MC_Category)
                        newHist.GetXaxis().SetTitle(mcF_)
                        newHist.SetDirectory(0)
                        histos.append(newHist)
                        histCategories.append(MC_Category)

                    sig_histos = []
                    sig_histCategories = []

                    ##-- Add Signal to plots
                    for i, sigF_ in enumerate(signalFiles_):
                        sigPath = "%s/%s" % (signalDirec_, sigF_)
                        sigFile = TFile.Open(sigPath)
                        treeName = GetMCTreeName(sigF_)
                        MC_Category = GetMCCategory(sigF_)
                        if (verbose_):
                            # print"Signal File:",sigPath
                            print "Signal:", MC_Category
                        if (HHWWggTag == "combined"):
                            mc_ch = TChain(
                                'tagsDumper/trees/%s_13TeV_HHWWggTag_0' %
                                (treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_0" %
                                (sigPath, treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_1" %
                                (sigPath, treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_2" %
                                (sigPath, treeName))
                        else:
                            mc_ch = TChain('tagsDumper/trees/%s_13TeV_%s' %
                                           (treeName, HHWWggTag))
                            mc_ch.Add(sigPath)
                        xbins, xmin, xmax = GetBins(varTitle)
                        exec(
                            "MC_h_tmp_%s = TH1F('MC_h_tmp_%s',v,xbins,xmin,xmax)"
                            % (i, i))
                        thisHist = eval("MC_h_tmp_%s" % (i))
                        mcColor = GetMCColor(MC_Category)
                        ##-- Style options for signal to distinguish from Data, Background
                        # eval("MC_h_tmp_%s.SetFillColor(eval(mcColor))"%(i))
                        # eval("MC_h_tmp_%s.SetFillStyle(3004)"%(i))
                        ##--
                        eval("MC_h_tmp_%s.SetFillColorAlpha(eval(mcColor),0.1)"
                             % (i))
                        eval("MC_h_tmp_%s.SetLineColor(eval(mcColor))" % (i))
                        exec('mc_ch.Draw("%s >> MC_h_tmp_%s","%s")' %
                             (v, i, SIGNAL_CUT))
                        eval("MC_h_tmp_%s.Scale(float(Lumi_))" %
                             (i))  # should scale to luminosity by default
                        SigXS_Scale = GetXScale(
                            "HHWWgg_v2-6"
                        )  # how to scale the XS which is by default in flashgg 1fb
                        if (verbose_): print "SigXS_Scale: ", SigXS_Scale
                        eval("MC_h_tmp_%s.Scale(float(SigXS_Scale))" %
                             (i))  # should scale to luminosity by default
                        newHist = thisHist.Clone("newHist")

                        ##-- Set title based on treeName
                        newHist.SetTitle(MC_Category)
                        newHist.GetXaxis().SetTitle(sigF_)
                        newHist.SetLineStyle(1)
                        newHist.SetLineWidth(5)

                        newHist.SetDirectory(0)
                        sig_histos.append(newHist)
                        sig_histCategories.append(MC_Category)

                    MC_AddedtoLegend = {
                        "QCD": 0,
                        "SMhgg": 0,
                        "GJet": 0,
                        "DiPhoJets": 0,
                        "DiPhoJetsBox": 0,
                        # "W1JetsToLNu" : 0,
                        # "W2JetsToLNu" : 0,
                        # "W3JetsToLNu" : 0,
                        # "W4JetsToLNu" : 0,
                        "WJets": 0,
                        "WW": 0,
                        "tt": 0,
                        "DY": 0,
                        "WGGJets": 0,
                        "WGJJ": 0,
                        "ttW": 0
                    }

                    Signals_AddedtoLegend = {"HHWWgg_SM": 0}

                    ##-- Order histograms by MC category
                    orderedHistos = OrderHistos(histos, histCategories)
                    sig_orderedHistos = OrderHistos(sig_histos,
                                                    sig_histCategories)

                    ##-- Add backgrounds to background stack
                    for h in orderedHistos:
                        bkgStack.Add(h, 'hist')
                        bkgName = h.GetTitle()
                        added = MC_AddedtoLegend[bkgName]
                        if (added): continue
                        else:
                            legend.AddEntry(h, bkgName, "F")
                            MC_AddedtoLegend[bkgName] = 1

                    ##-- By default draw background save background contributions. Later delete if not wanted
                    outName = "%s/BackgroundsTest_%s.png" % (outputFolder,
                                                             HHWWggTag)
                    bkgOutName = "%s/BackgroundsPADS_%s_%s.png" % (
                        outputFolder, varTitle, HHWWggTag)
                    SimpleDrawHisto(bkgStack, "PADS", bkgOutName, varTitle)
                    bkgOutName = bkgOutName.replace(".png", ".pdf")
                    SimpleDrawHisto(bkgStack, "PADS", bkgOutName, varTitle)

                    ##-- Add text box with selection type
                    offset = 0
                    selText = TLatex(0.129, 0.85, cutName)
                    selText.SetNDC(1)
                    selText.SetTextSize(0.04)
                    CatText = TLatex(0.129, 0.8, HHWWggTag)
                    CatText.SetNDC(1)
                    CatText.SetTextSize(0.04)
                    stackSum = bkgStack.GetStack().Last(
                    )  #->Draw(); # for computing ratio
                    stackSum.Sumw2()
                    stackSum.SetLineColor(kBlack)
                    stackSum.SetLineStyle(
                        7)  # to distinguish from data uncertainty
                    DataHist.SetLineColor(kBlack)
                    DataHist.Sumw2()
                    xTitle = GetXaxisTitle(varTitle)
                    DataHist.GetXaxis().SetTitle(xTitle)
                    if (log_):
                        DataHist.SetMinimum(0.01)
                        stackSum.SetMinimum(0.01)
                        bkgStack.SetMinimum(0.01)

                    ##-- Define ratio plot for computing Data / MC ratio
                    rp = TRatioPlot(DataHist, stackSum)
                    rp.SetH1DrawOpt("P")
                    rp.SetH2DrawOpt("hist")
                    # rp.SetGraphDrawOpt("PE2")
                    dMax = DataHist.GetMaximum()
                    bMax = stackSum.GetMaximum()
                    maxHeight = max(dMax, bMax)

                    ##-- Create the entire picture: Combine Data, MC, Data / MC ratio and signal in one plot

                    for fileType in ["pdf"]:
                        gStyle.SetErrorX(0.0001)
                        # varTitle = GetVarTitle(v)
                        outName = "%s/DataMC_%s_%s.%s" % (
                            outputFolder, varTitle, HHWWggTag, fileType)
                        if (log_):
                            outName = "%s/DataMC_%s_%s_log.%s" % (
                                outputFolder, varTitle, HHWWggTag, fileType)
                        else:
                            outName = "%s/DataMC_%s_%s_nonLog.%s" % (
                                outputFolder, varTitle, HHWWggTag, fileType)
                        DataMCRatio_c = TCanvas("DataMCRatio_c",
                                                "DataMCRatio_c", 600, 800)
                        rp.Draw("nogrid")
                        rp.GetLowYaxis().SetNdivisions(5)
                        DataMCRatio_c.Update()

                        ratioGraph = rp.GetCalculationOutputGraph()
                        ratioGraph.SetMarkerStyle(8)
                        ratioGraph.SetMarkerSize(0.5)

                        # rp.SetGraphDrawOpt("EP")
                        # rp.SetGraphDrawOpt("EPZ2")
                        # rp.GetLowerRefYaxis().SetTitle("Data / MC")

                        rp.GetUpperRefYaxis().SetTitle("Entries")
                        rp.GetLowerRefYaxis().SetTitle("Data / MC")
                        rp.GetLowerPad().Update()
                        if (log_):
                            rp.GetUpperRefYaxis().SetRangeUser(
                                0.1, maxHeight * 100.)
                        else:
                            rp.GetUpperRefYaxis().SetRangeUser(
                                0, maxHeight * 1.3)

                        UpperPad = rp.GetUpperPad()
                        UpperPad.cd()
                        bkgStack.Draw("same")
                        stackSum.Draw("sameE")
                        DataHist.Draw("samePE")
                        for sig_hist in sig_histos:
                            sigMax = sig_hist.GetMaximum()
                            if sigMax == 0: sigMax = 1

                            ##-- No user input signal scale
                            if (SigScale_ == -999):
                                sigScale = (float(maxHeight) / 10.) / float(
                                    sigMax
                                )  # in order to scale signal to 10th of max of plot
                                sig_hist.Scale(sigScale)

                            ##-- User input signal scale
                            else:
                                if (verbose_):
                                    print "user sig scale:", SigScale_
                                sigScale = SigScale_
                                sig_hist.Scale(sigScale)

                            for sig_h in sig_orderedHistos:
                                # sigName = "%s X %d"%(sig_h.GetTitle(),sigScale)
                                sigName = sig_h.GetTitle()
                                added = Signals_AddedtoLegend[sigName]
                                if (added): continue
                                else:
                                    legend.AddEntry(
                                        sig_h, "%s * %.5g" %
                                        (sig_h.GetTitle(), sigScale), "FL")
                                    Signals_AddedtoLegend[sigName]
                            sig_hist.Draw("samehist")
                        legend.Draw("same")
                        selText.Draw("same")
                        CatText.Draw("same")
                        rp.GetLowerRefGraph().SetMinimum(0.5)
                        rp.GetLowerRefGraph().SetMaximum(1.5)
                        Npoints = rp.GetLowerRefGraph().GetN()
                        for ip in range(0, Npoints):
                            rp.GetLowerRefGraph().SetPointEXhigh(ip, 0)
                            rp.GetLowerRefGraph().SetPointEXlow(ip, 0)
                        if (log_):
                            UpperPad.SetLogy()
                            UpperPad.Update()
                        rp.GetLowerPad().cd()
                        lowerPad = rp.GetLowerPad()
                        rp.GetLowerRefYaxis().SetTitle("Data / MC")
                        lineAtOne = TLine(lowerPad.GetUxmin(), 1,
                                          lowerPad.GetUxmax(), 1)
                        lineAtOne.SetLineStyle(3)
                        lineAtOne.Draw("same")
                        rp.GetLowerPad().Update()
                        DataMCRatio_c.Update()
                        DataMCRatio_c.SaveAs(outName)
                        outName = outName.replace(".pdf", ".png")
                        DataMCRatio_c.SaveAs(outName)
                    if (not drawPads_):
                        bkgOutName = "%s/BackgroundsPADS_%s_%s.png" % (
                            outputFolder, varTitle, HHWWggTag)
                        os.system('rm %s' % (bkgOutName))
                        bkgOutName = bkgOutName.replace(".png", ".pdf")
                        os.system('rm %s' % (bkgOutName))
                    MC_CUT = MC_CUT.replace(
                        "(%s != 0) && (%s != -999)" % (v, v), "ZERO_CUT")
                    DATA_CUT = DATA_CUT.replace(
                        "(%s != 0) && (%s != -999)" % (v, v), "ZERO_CUT")

                MC_Nevents_lists.append(these_MC_Nevents)
                MC_Nevents_noweight_lists.append(these_MC_Nevents_noweights)

        ##-- Produce table with number of events for each MC, total MC, and data
        CreateYieldsTables(cutBatchTag_pairs, dataNevents_list, MC_names,
                           MC_Nevents_lists, MC_Nevents_noweight_lists, ol_)
Exemplo n.º 10
0
def main():

    extension = "pdf"

    ####### File names and locations ########
    network_name = "deep_ann"
    data_set_name = "ttbar_1in3_tt_strict"  #_NOJETS _SOMEJETS
    ######################################

    process = "#it{t#bar{t}}"
    luminosity = 44307.4

    ## Initialising plotting variables
    Var_Lin = Plotting.Variable(
        "Lin",
        "Linear_Response",
        "#Delta_{T}^{lin}",
        "",
    )
    Var_Truth = Plotting.Variable("Truth", "TrueET", "True #it{E}_{T}^{miss}",
                                  "[GeV]")

    ymin = -0.2
    ymax = 0.5

    plot_list = [
        ("main_ann", "Tight", "", 4, 21),
        ("main_ann", "Network", "", 2, 20),
        ("flat_ann", "Network", "(A) ", 3, 22),
        ("smpl_ann", "Network", "(B) ", 6, 23),
    ]

    ## Creating the plots
    gROOT.SetStyle("ATLAS")
    gROOT.ForceStyle()
    gStyle.SetErrorX(0.5)
    canvas = TCanvas("canvas_{}_{}".format(Var_Truth.name, Var_Lin.name),
                     'A basic canvas', 800, 600)

    ## Adding in the legend
    leg = Plotting.Create_Legend(0.65, 0.70, 0.95, 0.95)

    ## Creating the stack
    stack = THStack("stack", Var_Truth.name + Var_Lin.name)
    stack.SetMinimum(ymin)
    stack.SetMaximum(ymax)

    ## Cycling through the different network directories
    for network_name, wp_name, prefix, colour, marker in plot_list:

        OUTPUT_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Output")
        hist_dir = os.path.join(OUTPUT_dir, network_name, data_set_name)
        rootfile_name = os.path.join(hist_dir, "histograms.root")

        ## Creating the working point variable
        wp = Plotting.WorkingPoint(wp_name)

        ## Generating the graph name
        graph_name = "{}_vs_{}_{}".format(Var_Truth.name, Var_Lin.name,
                                          wp.name)

        ## Loading the graph using its name and file location
        graph = Plotting.GetGraphFromFile(rootfile_name, graph_name)
        if graph == -1:
            continue

        ## Setting the colors specific to the working point
        graph.SetLineColor(colour)
        graph.SetMarkerColor(colour)
        graph.SetMarkerStyle(marker)

        ## Adding the legend entry
        leg.AddEntry(graph, prefix + wp.name, "p")

        ## Adding the object to the stack
        stack.Add(graph)
        del graph

    ## Drawing the stack on the currrent canvas
    stack.Draw("nostack")
    leg.Draw()

    ## Setting axis labels
    stack.GetXaxis().SetTitle(Var_Truth.x_label + " " + Var_Truth.units)
    stack.GetYaxis().SetTitle(Var_Lin.x_label + " " + Var_Lin.units)

    ## Moving axis tick marks
    stack.GetYaxis().SetMaxDigits(3)
    stack.GetXaxis().SetLabelOffset(0.017)

    ## Drawing all text
    left = 0.29
    size = 1.0
    shift = 0.06
    pos = 0.88

    Plotting.Draw_ATLASLabel(left, pos, "Simulation", scale=1.0)
    pos -= shift
    Plotting.Draw_Text(left, pos, "work in progress", scale=size)
    pos -= shift
    Plotting.Draw_Lumi(left, pos, 0, scale=size)
    pos -= shift
    Plotting.Draw_Text(left, pos, process, scale=size)
    pos -= shift

    ## Updating the canvas
    canvas.Update()

    out_file = "response_comparison_zoom.{}".format(extension)
    canvas.Print(out_file)

    del canvas

    return 0
Exemplo n.º 11
0
    def initStyle():
        gROOT.SetStyle("Plain")

        # For the canvas:
        gStyle.SetCanvasBorderMode(0)
        gStyle.SetCanvasColor(kWhite)
        gStyle.SetCanvasDefH(700)  #Height of canvas
        gStyle.SetCanvasDefW(700)  #Width of canvas
        gStyle.SetCanvasDefX(0)  #Position on screen
        gStyle.SetCanvasDefY(0)

        # For the line:
        gStyle.SetLineWidth(2)

        # For the Pad:
        gStyle.SetPadBorderMode(0)
        # gStyle.SetPadBorderSize(Width_t size = 1)
        gStyle.SetPadColor(kWhite)
        gStyle.SetPadGridX(True)
        gStyle.SetPadGridY(True)
        gStyle.SetGridColor(0)
        gStyle.SetGridStyle(3)
        gStyle.SetGridWidth(1)

        # For the frame:
        gStyle.SetFrameBorderMode(0)
        gStyle.SetFrameBorderSize(1)
        gStyle.SetFrameFillColor(0)
        gStyle.SetFrameFillStyle(0)
        gStyle.SetFrameLineColor(1)
        gStyle.SetFrameLineStyle(1)
        gStyle.SetFrameLineWidth(1)

        # For the histo:
        # gStyle.SetHistFillColor(1)
        # gStyle.SetHistFillStyle(0)
        gStyle.SetHistLineColor(1)
        gStyle.SetHistLineStyle(0)
        gStyle.SetHistLineWidth(2)
        # gStyle.SetLegoInnerR(Float_t rad = 0.5)
        # gStyle.SetNumberContours(Int_t number = 20)

        gStyle.SetEndErrorSize(2)
        #gStyle.SetErrorMarker(20)
        gStyle.SetErrorX(0.)

        gStyle.SetMarkerStyle(8)
        gStyle.SetMarkerSize(1)

        #For the fit/function:
        gStyle.SetOptFit(0)
        gStyle.SetFitFormat("5.4g")
        gStyle.SetFuncColor(2)
        gStyle.SetFuncStyle(1)
        gStyle.SetFuncWidth(1)

        #For the date:
        gStyle.SetOptDate(0)
        # gStyle.SetDateX(Float_t x = 0.01)
        # gStyle.SetDateY(Float_t y = 0.01)

        # For the statistics box:
        gStyle.SetOptFile(0)
        gStyle.SetOptStat(0)  # To display the mean and RMS:   SetOptStat("mr")
        gStyle.SetStatColor(kWhite)
        gStyle.SetStatFont(42)
        gStyle.SetStatFontSize(0.025)
        gStyle.SetStatTextColor(1)
        gStyle.SetStatFormat("6.4g")
        gStyle.SetStatBorderSize(1)
        gStyle.SetStatH(0.1)
        gStyle.SetStatW(0.15)
        # gStyle.SetStatStyle(Style_t style = 1001)
        # gStyle.SetStatX(Float_t x = 0)
        # gStyle.SetStatY(Float_t y = 0)

        # Margins:
        gStyle.SetPadTopMargin(0.11)
        gStyle.SetPadBottomMargin(0.13)
        gStyle.SetPadLeftMargin(0.17)
        gStyle.SetPadRightMargin(0.07)

        # For the Global title:
        gStyle.SetOptTitle(0)
        gStyle.SetTitleFont(42)
        gStyle.SetTitleColor(1)
        gStyle.SetTitleTextColor(1)
        gStyle.SetTitleFillColor(10)
        gStyle.SetTitleFontSize(0.04)
        # gStyle.SetTitleH(0) # Set the height of the title box
        # gStyle.SetTitleW(0) # Set the width of the title box
        #gStyle.SetTitleX(0.35) # Set the position of the title box
        #gStyle.SetTitleY(0.986) # Set the position of the title box
        # gStyle.SetTitleStyle(Style_t style = 1001)
        #gStyle.SetTitleBorderSize(0)

        # For the axis titles:
        gStyle.SetTitleColor(1, "XYZ")
        gStyle.SetTitleFont(42, "XYZ")
        gStyle.SetTitleSize(0.05, "XYZ")
        # gStyle.SetTitleXSize(Float_t size = 0.02) # Another way to set the size?
        # gStyle.SetTitleYSize(Float_t size = 0.02)
        gStyle.SetTitleXOffset(1.)
        gStyle.SetTitleYOffset(1.3)
        #gStyle.SetTitleOffset(1.1, "Y") # Another way to set the Offset

        # For the axis labels:

        gStyle.SetLabelColor(1, "XYZ")
        gStyle.SetLabelFont(42, "XYZ")
        gStyle.SetLabelOffset(0.007, "XYZ")
        gStyle.SetLabelSize(0.035, "XYZ")

        # For the axis:
        gStyle.SetAxisColor(1, "XYZ")
        gStyle.SetStripDecimals(True)
        gStyle.SetTickLength(0.03, "XYZ")
        gStyle.SetNdivisions(510, "XYZ")
        gStyle.SetPadTickX(
            1)  # To get tick marks on the opposite side of the frame
        gStyle.SetPadTickY(1)

        # Change for log plots:
        gStyle.SetOptLogx(0)
        gStyle.SetOptLogy(0)
        gStyle.SetOptLogz(0)

        gStyle.SetPalette(1)  #(1,0)

        # another top group addition
        gStyle.SetHatchesSpacing(1.0)

        # Postscript options:
        gStyle.SetPaperSize(20., 20.)
        #gStyle.SetPaperSize(TStyle.kA4)
        #gStyle.SetPaperSize(27., 29.7)
        #TGaxis.SetMaxDigits(3)
        # gStyle.SetLineScalePS(Float_t scale = 3)
        # gStyle.SetLineStyleString(Int_t i, const char* text)
        # gStyle.SetHeaderPS(const char* header)
        # gStyle.SetTitlePS(const char* pstitle)
        #gStyle.SetColorModelPS(1)

        # gStyle.SetBarOffset(Float_t baroff = 0.5)
        # gStyle.SetBarWidth(Float_t barwidth = 0.5)
        # gStyle.SetPaintTextFormat(const char* format = "g")
        # gStyle.SetPalette(Int_t ncolors = 0, Int_t* colors = 0)
        # gStyle.SetTimeOffset(Double_t toffset)
        # gStyle.SetHistMinimumZero(kTRUE)

        #gStyle.cd()
        print "TDR Style initialized"
Exemplo n.º 12
0
    def initialize(fitresults=True, grid=False):
        gROOT.SetStyle("Plain")
        gStyle.SetOptFit()
        gStyle.SetOptStat(0)
        # For the canvas:
        gStyle.SetCanvasBorderMode(0)
        gStyle.SetCanvasColor(kWhite)
        gStyle.SetCanvasDefH(600) #Height of canvas
        gStyle.SetCanvasDefW(600) #Width of canvas
        gStyle.SetCanvasDefX(0)   #POsition on screen
        gStyle.SetCanvasDefY(0)

        # For the Pad:
        gStyle.SetPadBorderMode(0)
        gStyle.SetPadColor(kWhite)
        gStyle.SetPadGridX(False)
        gStyle.SetPadGridY(False)
        gStyle.SetGridColor(0)
        gStyle.SetGridStyle(3)
        gStyle.SetGridWidth(1)

        # For the frame:
        gStyle.SetFrameBorderMode(0)
        gStyle.SetFrameBorderSize(1)
        gStyle.SetFrameFillColor(kWhite)
        gStyle.SetFrameFillStyle(1000)
        gStyle.SetFrameLineColor(1)
        gStyle.SetFrameLineStyle(1)
        gStyle.SetFrameLineWidth(1)

        # For the histo:
        gStyle.SetHistLineColor(1)
        gStyle.SetHistLineStyle(0)
        gStyle.SetHistLineWidth(2)

        gStyle.SetEndErrorSize(2)
        gStyle.SetErrorX(0.)

        gStyle.SetMarkerStyle(20)

        #For the fit/function:
        gStyle.SetOptFit(1)
        gStyle.SetFitFormat("5.4g")
        gStyle.SetFuncColor(2)
        gStyle.SetFuncStyle(1)
        gStyle.SetFuncWidth(1)

        #For the date:
        gStyle.SetOptDate(0)

        # For the statistics box:
        gStyle.SetOptFile(0)
        gStyle.SetOptStat(0) # To display the mean and RMS:   SetOptStat("mr")
        gStyle.SetStatColor(kWhite)
        gStyle.SetStatFont(42)
        gStyle.SetStatFontSize(0.025)
        gStyle.SetStatTextColor(1)
        gStyle.SetStatFormat("6.4g")
        gStyle.SetStatBorderSize(1)
        gStyle.SetStatH(0.1)
        gStyle.SetStatW(0.15)

        # Margins:
        gStyle.SetPadTopMargin(0.05)
        gStyle.SetPadLeftMargin(0.16)
        gStyle.SetPadRightMargin(0.04) # top group adaption, original is 0.02
        gStyle.SetPadBottomMargin(0.13)

        # For the Global title:

        gStyle.SetOptTitle(0)
        gStyle.SetTitleFont(42)
        gStyle.SetTitleColor(1)
        gStyle.SetTitleTextColor(1)
        gStyle.SetTitleFillColor(10)
        gStyle.SetTitleFontSize(0.05)

        # For the axis titles:
        gStyle.SetTitleColor(1, "XYZ")
        gStyle.SetTitleFont(42, "XYZ")
        gStyle.SetTitleSize(0.06, "XYZ")
        gStyle.SetTitleXOffset(0.9)
        gStyle.SetTitleYOffset(1.25)

        # For the axis labels:

        gStyle.SetLabelColor(1, "XYZ")
        gStyle.SetLabelFont(42, "XYZ")
        gStyle.SetLabelOffset(0.007, "XYZ")
        gStyle.SetLabelSize(0.05, "XYZ")
        #gStyle.SetLabelSize(0.04, "XYZ")

        # For the axis:

        gStyle.SetAxisColor(1, "XYZ")
        gStyle.SetStripDecimals(True)
        gStyle.SetTickLength(0.03, "XYZ")
        gStyle.SetNdivisions(510, "XYZ")
        gStyle.SetPadTickX(1)  # To get tick marks on the opposite side of the frame
        gStyle.SetPadTickY(1)

        # Change for log plots:
        gStyle.SetOptLogx(0)
        gStyle.SetOptLogy(0)
        gStyle.SetOptLogz(0)

        gStyle.SetPalette(1) #(1,0)

        # another top group addition
        gStyle.SetHatchesSpacing(1.0)

        # Postscript options:
        gStyle.SetPaperSize(20., 20.)
        # For graphs
        gStyle.SetErrorX(0)  # suppress error along x

        if grid:
          gStyle.SetPadGridX(gridOn)
          gStyle.SetPadGridY(gridOn)
          gStyle.SetGridColor(kGray)
Exemplo n.º 13
0
def main():

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-i", "--inputfile", dest="inputfile")
    parser.add_option("-N", "--multiplicity", dest="N", type="int", default=3)
    parser.add_option("-x", "--exclusive", action="store_true",\
          dest="isExclusive", default=False)
    parser.add_option("-l", "--label", dest="label", type="string", default="")
    parser.add_option("-z",
                      "--zeyneplabel",
                      action="store_true",
                      dest="zeynep",
                      default=True)
    (options, args) = parser.parse_args()

    N = options.N
    isExclusive = options.isExclusive
    label_text = options.label

    zeynep = options.zeynep

    if isExclusive and not (N == 2 or N == 3):
        parser.error("Exclusive plot only for N =2 or 3")

    import configurations as config
    from ROOT import TFile, TCanvas, THStack, TLegend, TPaveText, gStyle, TPad, TH1F, TGraphAsymmErrors, TMath
    from ModelParser import ModelKey

    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadBottomMargin(0.20)

    gStyle.SetErrorX(0.)

    suffix = ""
    if not isExclusive:
        suffix = "up"

    sm_files = []
    for model in config.sm_models:
        f = TFile("%s/%s.root" % (config.sm_dir, model), "READ")
        sm_files.append(f)

    bh_weights = []
    bh_files = []
    from BHXsec import BHXsec
    xsec = BHXsec()
    for model in config.bh_showcase:
        f = TFile("%s/%s.root" % (config.bh_dir, model), "READ")
        bh_files.append(f)
        h = f.Get("plotsNoCut/ST")
        nEvents = h.GetEntries()
        bh_weights.append(
            xsec.get(model) / nEvents * config.integrated_luminosity)

    c = TCanvas("ST_Mul%d%s" % (N, suffix), "ST_Mul%d%s" % (N, suffix), 500,
                600)
    hs = THStack()
    hs1 = THStack()

    infile = TFile(options.inputfile, "READ")
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    #hnewBkg = infile.Get("histoTemplateN3_0")
    hnewBkg = infile.Get("ReferenceTemplateN3_0")
    gBkg = infile.Get("BackgroundGraph_N%d%s" % (N, suffix))
    hData = infile.Get("Data_N%d%s" % (N, suffix))
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    hBkg.SetMarkerSize(0)
    hBkg_ = hBkg.Clone("BkgLine")
    hBkg.SetFillColor(33)
    hBkg.SetLineColor(33)
    hBkg_.SetLineWidth(3)
    hBkg_.SetLineColor(862)

    hs.Add(hBkg, "e3")
    hnewBkg.SetLineWidth(3)
    hnewBkg.Scale(10 * 3.407)
    hs.Add(hnewBkg, "l")

    legend = TLegend(0.2826613, 0.4819492, 0.6094355,
                     0.9416102)  # - only for N >= 2 and 3
    #legend = TLegend(0.3026613,0.5519492,0.6094355,0.9416102) # was 0.4919...zeynep

    #legend = TLegend(0.3526613,0.5519492,0.6094355,0.9416102) # was 0.4919...

    #legend.SetTextSize(0.041); #was 0.02966102
    legend.SetTextSize(0.037)
    legend.SetTextFont(42)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    if isExclusive:
        legend.SetHeader("Multiplicity N = %d" % N)
    else:
        legend.SetHeader("Multiplicity N #geq %d" % N)
    legend.AddEntry(hData, "Data", "lep")
    #legend.AddEntry(hnewBkg, "N=3 Fit Rescaled","l")
    legend.AddEntry(hBkg_, "Background", "l")
    legend.AddEntry(hBkg, "Uncertainty", "f")

    legend_sm = TLegend(0.6471774, 0.7069492, 0.8508065, 0.8471186)
    #   legend_sm = TLegend(0.6271774,0.7369492,0.8308065,0.8771186)
    #   legend_sm.SetTextSize(0.037);
    legend_sm.SetTextSize(0.037)

    legend_sm.SetTextFont(42)
    legend_sm.SetFillColor(0)
    legend_sm.SetLineColor(0)

    for i, f in enumerate(bh_files):
        h = f.Get("plotsN%d%s/ST" % (N, suffix))
        h.Rebin(config.rebin)
        h.Scale(bh_weights[i])

        # Add background
        for ibin in range(h.GetNbinsX()):
            h.SetBinContent(ibin+1,\
                  h.GetBinContent(ibin+1)\
                  + hBkg.GetBinContent(ibin+1))

            h.SetLineWidth(3)
            #h.SetLineColor(i+2)
            h.SetLineStyle(i + 2)

            #if i == 0:
            #h.SetLineColor(814)
            if i == 0:
                h.SetLineStyle(5)
                h.SetLineColor(899)
            if i == 1:
                h.SetLineStyle(9)
                h.SetLineColor(4)
            if i == 2:
                h.SetLineStyle(3)
                h.SetLineColor(614)

        hs.Add(h, "hist")
        model = ModelKey(config.bh_showcase[i])
        bh_legend = "M_{D} = %.1f TeV, M_{BH}^{ min} = %.1f TeV, n = %d" % (\
              model.parameter["MD"],
              model.parameter["M"],
              model.parameter["n"])
        if i == 3:
            bh_legend = "M_{D} = 3.0 TeV, M_{QBH}^{ min} = 4.0 TeV, n = 4"

        legend.AddEntry(h, bh_legend, "l")

#      qbh_legend = "M_{D} = 4.0 TeV, M_{QBH}^{ min} = 5.0 TeV, n = 5"

#      legend.AddEntry(h, qbh_legend, "l")

#if isExclusive:
    zeynep = True
    if zeynep:
        for i, f in enumerate(sm_files):
            h = f.Get("plotsN%d%s/ST" % (N, suffix))
            h.Rebin(config.rebin)
            h.Scale(config.integrated_luminosity)
            h.SetFillColor(config.sm_colors[i])
            h.SetLineColor(config.sm_colors[i])
            hs1.Add(h, "hist")
            legend_sm.AddEntry(h, config.sm_models[i], "f")

    #hs.Add(hData, "e")

    hs.Draw("nostack")
    hs1.Draw("same")

    c.SetLogy(1)
    hs.GetXaxis().SetTitle("S_{T} (GeV)")
    hs.GetYaxis().SetTitle(hData.GetYaxis().GetTitle())
    hs.GetYaxis().SetTitleOffset(1.25)

    hs.GetYaxis().SetTitleSize(0.04)
    hs.GetYaxis().SetLabelSize(0.04)
    hs.GetXaxis().SetTitleSize(0.01)
    hs.GetXaxis().SetLabelSize(0.01)

    ibin = 0
    #if isExclusive:
    #   hs.GetXaxis().SetRangeUser(config.fit_range[0], config.maxST)
    #   ibin = hData.FindBin(config.fit_range[0])
    #else:
    #   hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
    #   ibin = hData.FindBin(config.norm_range[0])

    if isExclusive:
        hs.GetXaxis().SetRangeUser(1800, config.maxST)
        ibin = hData.FindBin(1800)
    else:
        hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
        ibin = hData.FindBin(config.norm_range[0])

    from Styles import formatUncertainty
    formatUncertainty(gBkg)
    gBkg.Draw("LX")
    hData.Draw("sameex0")

    hs.SetMinimum(5e-1)
    if isExclusive:
        hs.SetMaximum(1e7)

#     hs.SetMaximum(hData.GetBinContent(ibin) * 40)
    else:
        #hs.SetMaximum(1e8)
        hs.SetMaximum(hData.GetBinContent(ibin) *
                      20)  # or 1e7 for N>=3 and use 4 models

    legend.Draw("plain")
    #if isExclusive:
    if zeynep:
        legend_sm.Draw("plain")

    if isExclusive:
        cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC")
    else:
        cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC")
    cmslabel.AddText(config.cmsTitle)
    #cmslabel.AddText(config.cmsSubtitle)
    cmslabel.SetFillColor(0)
    cmslabel.SetTextSize(0.041)
    cmslabel.Draw("plain")

    label = TPaveText(0.8891129, 0.8644068, 0.9435484, 0.9258475, "brNDC")
    label.SetFillColor(0)
    #label.SetTextSize(0.0529661);
    label.SetTextSize(0.0529661)
    label.AddText(label_text)
    label.Draw("plain")

    c.RedrawAxis()

    #Divide

    ibin = hData.FindBin(config.norm_range[0])
    #print ibin

    fbin = hData.FindBin(config.maxST)
    #print fbin

    hData.Sumw2()
    hBkg_.Sumw2()

    Pull = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100)
    Pull2 = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100)

    Ratio = hData.Clone()
    Ratio.Add(hBkg_, -1)
    #Ratio.Divide(hBkg_)

    Band = TGraphAsymmErrors(fbin - ibin + 1)

    for i in range(ibin - 1, fbin + 1):
        i += 1
        if hData.GetBinContent(i) != 0:
            value = hData.GetBinContent(i) + (hBkg_.GetBinError(i) *
                                              hBkg_.GetBinError(i))
            #print Ratio.GetBinError(i),  value**(0.5)
            #print i-19,i,(i)*100, hData.GetBinContent(i) , hBkg_.GetBinContent(i),hData.GetBinContent(i) - hBkg_.GetBinContent(i)
            Pull.SetBinContent(
                i - 19, (hData.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                Ratio.GetBinError(i))
            #print Ratio.GetBinError(i), abs(Ratio.GetBinContent(i))*0.05
            #Pull.SetBinContent(i-19,(hData.GetBinContent(i) - hBkg_.GetBinContent(i))/ Ratio.GetBinError(i))
            #Pull.SetBinContent(i-19,(hData.GetBinContent(i) / hBkg_.GetBinContent(i)))
            Pull.SetBinError(i - 19, Ratio.GetBinError(i))
            #Pull.SetBinError(i-19,hData.GetBinError(i)/gBkg.GetErrorY(i))
            if (hBkg_.GetBinContent(i) * 0.05 > hBkg_.GetBinError(i)):
                #print "bin error too small changing the error to: ", hBkg_.GetBinContent(i)*0.05
                Pull2.SetBinContent(
                    i - 19,
                    (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                    (hBkg_.GetBinContent(i) * 0.05))
            else:
                Pull2.SetBinContent(
                    i - 19,
                    (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                    hBkg_.GetBinError(i))
            #print hBkg_.GetBinError(i), hBkg_.GetBinContent(i)*0.05
            #print i, " Pull2: ", Pull2.GetBinContent(i-19), "hnewBkg.GetBinContent(i-1): " , hnewBkg.GetBinContent(i-1), "hBkg_.GetBinContent(i): ", hBkg_.GetBinContent(i)
        else:
            Pull.SetBinContent(i - 19, 0)
            Pull2.SetBinContent(
                i - 19,
                (hnewBkg.GetBinContent(i - 1) - hBkg_.GetBinContent(i)) /
                hBkg_.GetBinError(i))

        Band.SetPoint(i, hBkg_.GetBinCenter(i), 1.0)
        #print hBkg_.GetBinContent(i), hBkg_.GetBinError(i)
        up = abs(1. - ((hBkg_.GetBinContent(i) + hBkg_.GetBinError(i)) /
                       hBkg_.GetBinContent(i)))
        down = abs(1. - ((hBkg_.GetBinContent(i) - hBkg_.GetBinError(i)) /
                         hBkg_.GetBinContent(i)))
        Band.SetPointError(i, 0., 0., down, up)

    #Band.Print()
    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)

    pad.SetTopMargin(0.799999)
    pad.SetRightMargin(0.05)
    pad.SetBottomMargin(0.09)

    pad.SetFillColor(0)
    #pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw("same")
    pad.cd(0)

    Ratio.SetMarkerStyle(20)
    Pull.SetMarkerStyle(20)
    Pull.SetLineColor(1)
    Pull.SetMarkerSize(0.9)
    #Pull.SetMaximum(3)
    #Pull.SetMinimum(-1)

    Pull.SetMaximum(2.5)
    Pull.SetMinimum(-2.5)
    Pull.GetYaxis().SetNdivisions(5, 1)

    Pull.GetXaxis().SetTitle('S_{T} (GeV)')
    Pull.GetXaxis().SetLabelSize(0.04)

    Pull.GetYaxis().SetTitleOffset(1.05)
    Pull.GetYaxis().SetLabelSize(0.02)
    Pull.GetYaxis().SetTitleSize(0.025)
    Pull.GetYaxis().CenterTitle(1)

    Pull.GetYaxis().SetTitle('#sigma(Data-Bkg)')

    Pull.SetFillColor(2)
    Pull.Draw("HIST")
    Pull2.SetLineColor(862)
    Pull2.SetLineWidth(3)
    Pull2.SetLineStyle(2)
    #Pull2.Draw("SAME")
    formatUncertainty(Band)
    Band.SetFillStyle(3001)

    # Band.Draw("le3")
    # Pull.Draw("ex0same")
    pad.RedrawAxis()

    gStyle.SetOptStat(0)

    #block1 =TPaveText(0.370,0.84,0.351,0.86,"brNDC"); # for N>=2 and >=3 only
    #block1 =TPaveText(0.361,0.85,0.377,0.87,"brNDC");
    #block1 =TPaveText(0.333,0.88,0.354,0.85,"brNDC") #for n = 2 only

    block1 = TPaveText(0.331, 0.82, 0.357, 0.85, "brNDC")
    #FOR n=3 only
    block1.SetFillColor(0)
    block1.Draw("plain")

    #block2 =TPaveText(0.305,0.84,0.333,0.86,"brNDC"); # for N>=2 and >=3 only
    #block2 =TPaveText(0.395,0.85,0.41,0.87,"brNDC");
    #block2 =TPaveText(0.296,0.88,0.316,0.85,"brNDC"); for n =2 only

    block2 = TPaveText(0.295, 0.82, 0.317, 0.85, "brNDC")
    #FOR n=3 only
    block2.SetFillColor(0)
    block2.Draw("plain")

    if isExclusive:
        c.Print("ST_Mul%d.pdf" % N)
        c.Print("ST_Mul%d.png" % N)
    else:
        c.Print("ST_Mul%dup.pdf" % N)
        c.Print("ST_Mul%dup.png" % N)
    c.Update()

    raw_input("Press Enter to continue...")
Exemplo n.º 14
0
def dependencies(path, selection, plots, runRange, isMC, backgrounds, cmsExtra,
                 fit):

    pathMC = locations.dataSetPathMC
    #~ backgroundsTT = ["TT_Powheg"]
    #~ backgroundsMC = ["TT_Powheg","DrellYan"]
    backgroundsMC = [
        "Rare", "SingleTop", "TT_Powheg", "Diboson", "DrellYanTauTau",
        "DrellYan"
    ]

    for name in plots:
        plot = getPlot(name)
        plot.addRegion(selection)
        plot.cleanCuts()
        plot.cuts = plot.cuts % runRange.runCut

        if not "Forward" in selection.name:
            relSyst = systematics.rMuE.central.val
            if "Central" in selection.name:
                region = "central"
            else:
                region = "inclusive"
        else:
            relSyst = systematics.rMuE.forward.val
            region = "forward"

        if isMC:
            histEE, histMM = getHistograms(pathMC, plot, runRange, True,
                                           backgrounds, region)
        else:
            histEE, histMM = getHistograms(path, plot, runRange, False,
                                           backgrounds, region)
        #~ histEEMC, histMMMC = getHistograms(pathMC,plot,runRange,True, backgroundsTT,region)
        histEEMC, histMMMC = getHistograms(pathMC, plot, runRange, True,
                                           backgroundsMC, region)

        hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)

        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        setTDRStyle()
        plotPad.UseCurrentStyle()

        plotPad.Draw()
        plotPad.cd()

        latex = ROOT.TLatex()
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.04)
        latex.SetNDC(True)
        latexCMS = ROOT.TLatex()
        latexCMS.SetTextFont(61)
        latexCMS.SetTextSize(0.06)
        latexCMS.SetNDC(True)
        latexCMSExtra = ROOT.TLatex()
        latexCMSExtra.SetTextFont(52)
        latexCMSExtra.SetTextSize(0.045)
        latexCMSExtra.SetNDC(True)

        intlumi = ROOT.TLatex()
        intlumi.SetTextAlign(12)
        intlumi.SetTextSize(0.03)
        intlumi.SetNDC(True)

        rMuE = histMM.Clone("rMuE")
        rMuE.Divide(histEE)
        rMuEMC = histMMMC.Clone("rMuEMC")
        rMuEMC.Divide(histEEMC)

        for i in range(1, rMuE.GetNbinsX() + 1):
            if rMuE.GetBinContent(i) > 0:
                rMuE.SetBinContent(i, pow(rMuE.GetBinContent(i), 0.5))
            if rMuEMC.GetBinContent(i) > 0:
                rMuEMC.SetBinContent(i, pow(rMuEMC.GetBinContent(i), 0.5))
            if rMuE.GetBinContent(i) > 0:
                #~ rMuE.SetBinError(i, 0.5*rMuE.GetBinContent(i)*pow(1./abs(histMM.GetBinContent(i)) + 1./abs(histEE.GetBinContent(i)), 0.5))
                rMuE.SetBinError(
                    i, 0.5 * pow(
                        histMM.GetBinError(i)**2 /
                        (abs(histEE.GetBinContent(i)) *
                         abs(histMM.GetBinContent(i))) +
                        histEE.GetBinError(i)**2 * abs(histMM.GetBinContent(i))
                        / abs(histEE.GetBinContent(i)**3), 0.5))
                #~ rMuE.SetBinError(i, 0.5*rMuE.GetBinError(i))
            if rMuEMC.GetBinContent(i) > 0:
                #~ rMuEMC.SetBinError(i, 0.5*rMuEMC.GetBinContent(i)*pow(1./abs(histMMMC.GetBinContent(i)) + 1./abs(histEEMC.GetBinContent(i)), 0.5))
                #~ rMuEMC.SetBinError(i, pow( pow(histMMMC.GetBinError(i)/histEEMC.GetBinContent(i),2) + pow(histEEMC.GetBinError(i)*histMMMC.GetBinContent(i)/(histEEMC.GetBinContent(i)**2),2), 0.5))
                rMuEMC.SetBinError(
                    i, 0.5 * pow(
                        histMMMC.GetBinError(i)**2 /
                        (abs(histEEMC.GetBinContent(i)) *
                         abs(histMMMC.GetBinContent(i))) +
                        histEEMC.GetBinError(i)**2 *
                        abs(histMMMC.GetBinContent(i)) /
                        abs(histEEMC.GetBinContent(i)**3), 0.5))
                #~ rMuEMC.SetBinError(i, 0.5*rMuEMC.GetBinError(i))

        rMuEMC.SetMarkerStyle(21)
        rMuEMC.SetLineColor(ROOT.kGreen - 2)
        rMuEMC.SetMarkerColor(ROOT.kGreen - 2)

        rMuE.SetMarkerStyle(20)
        rMuE.SetLineColor(ROOT.kBlack)
        rMuE.SetMarkerColor(ROOT.kBlack)

        plotPad.DrawFrame(plot.firstBin, 1, plot.lastBin,
                          histMM.GetBinContent(histMM.GetMaximumBin()) * 10,
                          "; %s; N_{Events}" % plot.xaxis)

        legend = ROOT.TLegend(0.65, 0.7, 0.9, 0.9)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.AddEntry(histMM, "#mu#mu events", "p")
        legend.AddEntry(histEE, "ee events", "p")
        histMM.SetMarkerColor(ROOT.kRed)
        histMM.SetLineColor(ROOT.kRed)
        histMM.SetMarkerStyle(20)
        histEE.SetMarkerStyle(21)
        histMM.Draw("samepe")
        histEE.Draw("samepe")
        legend.Draw("same")
        ROOT.gPad.SetLogy(1)

        latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % runRange.printval)

        latexCMS.DrawLatex(0.19, 0.88, "CMS")
        if "Simulation" in cmsExtra:
            yLabelPos = 0.81
        else:
            yLabelPos = 0.84

        latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

        hCanvas.Print("fig/rMuE_%s_%s_%s_%s_RawInputs.pdf" %
                      (selection.name, runRange.label, plot.variablePlotName,
                       plot.additionalName))

        hCanvas.Clear()
        ROOT.gPad.SetLogy(0)

        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        setTDRStyle()
        plotPad.UseCurrentStyle()

        plotPad.Draw()
        plotPad.cd()
        plotPad.DrawFrame(plot.firstBin, 0., plot.lastBin, 2.5,
                          "; %s; r_{#mue}" % plot.xaxis)
        gStyle.SetErrorX(0.5)

        latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % runRange.printval)

        latexCMS.DrawLatex(0.19, 0.88, "CMS")
        if "Simulation" in cmsExtra:
            yLabelPos = 0.81
        else:
            yLabelPos = 0.84

        latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

        if os.path.isfile("shelves/rMuE_%s_%s.pkl" %
                          (selection.name, runRange.label)):
            centralVals = pickle.load(
                open(
                    "shelves/rMuE_%s_%s.pkl" %
                    (selection.name, runRange.label), "rb"))
        else:
            centralVals = centralValues(path, selection, runRange, isMC,
                                        backgrounds)

        x = array("f", [plot.firstBin, plot.lastBin])
        y = array("f", [centralVals["rMuE"], centralVals["rMuE"]])
        ex = array("f", [0., 0.])
        ey = array("f",
                   [centralVals["rMuESystErr"], centralVals["rMuESystErr"]])
        ge = ROOT.TGraphErrors(2, x, y, ex, ey)
        ge.SetFillColor(ROOT.kOrange - 9)
        ge.SetFillStyle(1001)
        ge.SetLineColor(ROOT.kWhite)
        ge.Draw("SAME 3")

        rmueLine = ROOT.TF1("rmueline", "%f" % centralVals["rMuE"],
                            plot.firstBin, plot.lastBin)
        rmueLine.SetLineColor(ROOT.kOrange + 3)
        rmueLine.SetLineWidth(3)
        rmueLine.SetLineStyle(2)
        rmueLine.Draw("SAME")

        rMuEMC.Draw("hist E1P SAME")

        leg = ROOT.TLegend(0.6, 0.7, 0.85, 0.95)
        if not isMC:
            rMuE.Draw("hist E1P SAME")
            leg.AddEntry(rMuE, "Data", "p")
            #~ leg.AddEntry(rMuEMC,"t#bar{t} MC","p")
            leg.AddEntry(rMuEMC, "MC", "p")

        else:
            rMuE.Draw("hist E1P SAME")
            leg.AddEntry(rMuE, "all MC", "p")
            leg.AddEntry(rMuEMC, "t#bar{t} MC", "p")
        if not isMC:
            leg.AddEntry(rmueLine, "r_{#mu e} central value", "l")
        else:
            leg.AddEntry(rmueLine, "r_{#mu e} central value on MC", "l")
        leg.AddEntry(ge, "syst. unc. of r_{#mu e}", "f")

        leg.SetBorderSize(0)
        leg.SetLineWidth(2)
        leg.SetTextAlign(22)

        if fit:
            fit = TF1("dataFit", "pol1", 0, 300)
            fit.SetLineColor(ROOT.kGreen + 3)
            fitMC = TF1("mcFit", "pol1", 0, 300)
            fitMC.SetLineColor(ROOT.kBlue + 3)
            rMuE.Fit("dataFit")
            rMuEMC.Fit("mcFit")

            latex = ROOT.TLatex()
            latex.SetTextSize(0.035)
            latex.SetNDC()
            latex.DrawLatex(
                0.2, 0.25,
                "Fit on data: %.2f #pm %.2f %.5f #pm %.5f * m_{ll}" %
                (fit.GetParameter(0), fit.GetParError(0), fit.GetParameter(1),
                 fit.GetParError(1)))
            latex.DrawLatex(
                0.2, 0.20,
                "Fit on MC:   %.2f #pm %.2f %.5f #pm %.5f * m_{ll}" %
                (fitMC.GetParameter(0), fitMC.GetParError(0),
                 fitMC.GetParameter(1), fitMC.GetParError(1)))

        # Pfeile

        if "eta" in plot.variable:
            yMin = 0.8
            yMax = 1.6
            lineU1 = ROOT.TLine(1.4, yMin, 1.4, yMax - 0.2)
            lineU1.SetLineColor(ROOT.kBlue - 3)
            lineU1.SetLineWidth(2)
            lineU1.Draw("")
            lineU2 = ROOT.TLine(1.6, yMin, 1.6, yMax - 0.2)
            lineU2.SetLineColor(ROOT.kBlue - 3)
            lineU2.SetLineWidth(2)
            lineU2.Draw("")
            arrow1 = ROOT.TArrow(1.55, 1.3, 1.6, 1.3, 0.01, "<|")
            arrow1.SetFillColor(ROOT.kBlue - 3)
            arrow1.SetLineColor(ROOT.kBlue - 3)
            arrow1.SetLineWidth(3)
            arrow1.Draw("")
            arrow2 = ROOT.TArrow(1.4, 1.3, 1.45, 1.3, 0.01, "|>")
            arrow2.SetFillColor(ROOT.kBlue - 3)
            arrow2.SetLineColor(ROOT.kBlue - 3)
            arrow2.SetLineWidth(3)
            arrow2.Draw("")

            lineE = ROOT.TLine(2.4, yMin, 2.4, yMax - 0.2)  #3.5 -> 1.7
            lineE.SetLineColor(ROOT.kRed - 3)
            lineE.SetLineWidth(2)
            lineE.Draw("")

        hCanvas.RedrawAxis()
        leg.Draw("SAME")
        ROOT.gPad.RedrawAxis()
        hCanvas.Update()

        hCanvas.Print("fig/rMuE_%s_%s_%s_%s.pdf" %
                      (selection.name, runRange.label, plot.variablePlotName,
                       plot.additionalName))

        for i in range(1, rMuE.GetNbinsX() + 1):
            if rMuE.GetBinContent(i) > 0:
                rMuE.SetBinError(
                    i, 0.5 * (1. - (1. / rMuE.GetBinContent(i)**2)) *
                    rMuE.GetBinError(i))
            if rMuEMC.GetBinContent(i) > 0:
                rMuEMC.SetBinError(
                    i, 0.5 * (1. - (1. / rMuEMC.GetBinContent(i)**2)) *
                    rMuEMC.GetBinError(i))
            if rMuE.GetBinContent(i) > 0:
                rMuE.SetBinContent(
                    i,
                    0.5 * (rMuE.GetBinContent(i) + 1. / rMuE.GetBinContent(i)))
            if rMuEMC.GetBinContent(i) > 0:
                rMuEMC.SetBinContent(
                    i, 0.5 *
                    (rMuEMC.GetBinContent(i) + 1. / rMuEMC.GetBinContent(i)))

        rMuEMC.SetMarkerStyle(21)
        rMuEMC.SetLineColor(ROOT.kGreen - 2)
        rMuEMC.SetMarkerColor(ROOT.kGreen - 2)

        rMuE.SetMarkerStyle(20)
        rMuE.SetLineColor(ROOT.kBlack)
        rMuE.SetMarkerColor(ROOT.kBlack)

        hCanvas.Clear()
        ROOT.gPad.SetLogy(0)

        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        setTDRStyle()
        plotPad.UseCurrentStyle()

        plotPad.Draw()
        plotPad.cd()
        plotPad.DrawFrame(plot.firstBin, 0.95, plot.lastBin, 1.2,
                          "; %s; 0.5(r_{#mue} + 1/r_{#mue})" % plot.xaxis)
        gStyle.SetErrorX(0.5)

        latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % runRange.printval)

        latexCMS.DrawLatex(0.19, 0.88, "CMS")
        if "Simulation" in cmsExtra:
            yLabelPos = 0.81
        else:
            yLabelPos = 0.84

        latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

        if os.path.isfile("shelves/rMuE_%s_%s.pkl" %
                          (selection.name, runRange.label)):
            centralVals = pickle.load(
                open(
                    "shelves/rMuE_%s_%s.pkl" %
                    (selection.name, runRange.label), "rb"))
        else:
            centralVals = centralValues(path, selection, runRange, isMC,
                                        backgrounds)

        x = array("f", [plot.firstBin, plot.lastBin])
        y = array("f", [
            0.5 * (centralVals["rMuE"] + 1. / centralVals["rMuE"]), 0.5 *
            (centralVals["rMuE"] + 1. / centralVals["rMuE"])
        ])
        ex = array("f", [0., 0.])
        ey = array("f", [
            0.5 * (1. - (1. / (centralVals["rMuE"]**2))) *
            centralVals["rMuESystErr"], 0.5 *
            (1. - (1. / (centralVals["rMuE"]**2))) * centralVals["rMuESystErr"]
        ])
        ge = ROOT.TGraphErrors(2, x, y, ex, ey)
        ge.SetFillColor(ROOT.kOrange - 9)
        ge.SetFillStyle(1001)
        ge.SetLineColor(ROOT.kWhite)
        ge.Draw("SAME 3")

        rmueLine = ROOT.TF1(
            "rmueline",
            "%f" % (0.5 * (centralVals["rMuE"] + 1. / centralVals["rMuE"])),
            plot.firstBin, plot.lastBin)
        rmueLine.SetLineColor(ROOT.kOrange + 3)
        rmueLine.SetLineWidth(3)
        rmueLine.SetLineStyle(2)
        rmueLine.Draw("SAME")

        rMuEMC.Draw("hist E1P SAME")

        leg = ROOT.TLegend(0.6, 0.7, 0.85, 0.95)
        if not isMC:
            rMuE.Draw("hist E1P SAME")
            leg.AddEntry(rMuE, "Data", "p")
            #~ leg.AddEntry(rMuEMC,"t#bar{t} MC","p")
            leg.AddEntry(rMuEMC, "MC", "p")

        else:
            rMuE.Draw("hist E1P SAME")
            leg.AddEntry(rMuE, "all MC", "p")
            leg.AddEntry(rMuEMC, "t#bar{t} MC", "p")
        if not isMC:
            leg.AddEntry(rmueLine, "central value", "l")
        else:
            leg.AddEntry(rmueLine, "central value on MC", "l")
        leg.AddEntry(ge, "syst. unc. of r_{#mu e}", "f")

        leg.SetBorderSize(0)
        leg.SetLineWidth(2)
        leg.SetTextAlign(22)

        if fit:
            fit = TF1("dataFit", "pol1", 0, 300)
            fit.SetLineColor(ROOT.kGreen + 3)
            fitMC = TF1("mcFit", "pol1", 0, 300)
            fitMC.SetLineColor(ROOT.kBlue + 3)
            rMuE.Fit("dataFit")
            rMuEMC.Fit("mcFit")

            latex = ROOT.TLatex()
            latex.SetTextSize(0.035)
            latex.SetNDC()
            latex.DrawLatex(
                0.2, 0.25,
                "Fit on data: %.2f #pm %.2f %.5f #pm %.5f * m_{ll}" %
                (fit.GetParameter(0), fit.GetParError(0), fit.GetParameter(1),
                 fit.GetParError(1)))
            latex.DrawLatex(
                0.2, 0.20,
                "Fit on MC:   %.2f #pm %.2f %.5f #pm %.5f * m_{ll}" %
                (fitMC.GetParameter(0), fitMC.GetParError(0),
                 fitMC.GetParameter(1), fitMC.GetParError(1)))

        # Pfeile

        if "eta" in plot.variable:
            yMin = 0.975
            yMax = 1.05
            lineU1 = ROOT.TLine(1.4, yMin, 1.4, yMax)
            lineU1.SetLineColor(ROOT.kBlue - 3)
            lineU1.SetLineWidth(2)
            lineU1.Draw("")
            lineU2 = ROOT.TLine(1.6, yMin, 1.6, yMax)
            lineU2.SetLineColor(ROOT.kBlue - 3)
            lineU2.SetLineWidth(2)
            lineU2.Draw("")
            arrow1 = ROOT.TArrow(1.55, 1.3, 1.6, 1.3, 0.01, "<|")
            arrow1.SetFillColor(ROOT.kBlue - 3)
            arrow1.SetLineColor(ROOT.kBlue - 3)
            arrow1.SetLineWidth(3)
            arrow1.Draw("")
            arrow2 = ROOT.TArrow(1.4, 1.3, 1.45, 1.3, 0.01, "|>")
            arrow2.SetFillColor(ROOT.kBlue - 3)
            arrow2.SetLineColor(ROOT.kBlue - 3)
            arrow2.SetLineWidth(3)
            arrow2.Draw("")

            lineE = ROOT.TLine(2.4, yMin, 2.4, yMax)  #3.5 -> 1.7
            lineE.SetLineColor(ROOT.kRed - 3)
            lineE.SetLineWidth(2)
            lineE.Draw("")

        hCanvas.RedrawAxis()
        leg.Draw("SAME")
        ROOT.gPad.RedrawAxis()
        hCanvas.Update()

        hCanvas.Print("fig/rSFOFFromRMuE_%s_%s_%s_%s.pdf" %
                      (selection.name, runRange.label, plot.variablePlotName,
                       plot.additionalName))
Exemplo n.º 15
0
def setgstyle():
    # Zero horizontal error bars
    gStyle.SetErrorX(0)

    # For the canvas
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetCanvasColor(0)
    gStyle.SetCanvasDefH(800)  # Height of canvas
    gStyle.SetCanvasDefW(800)  # Width of canvas
    gStyle.SetCanvasDefX(0)  # Position on screen
    gStyle.SetCanvasDefY(0)

    # For the frame
    gStyle.SetFrameBorderMode(0)
    gStyle.SetFrameBorderSize(1)
    gStyle.SetFrameFillColor(1)
    gStyle.SetFrameFillStyle(0)
    gStyle.SetFrameLineColor(1)
    gStyle.SetFrameLineStyle(0)
    gStyle.SetFrameLineWidth(1)

    # For the Pad
    gStyle.SetPadBorderMode(0)
    gStyle.SetPadColor(0)
    gStyle.SetPadGridX(False)
    gStyle.SetPadGridY(False)
    gStyle.SetGridColor(0)
    gStyle.SetGridStyle(3)
    gStyle.SetGridWidth(1)

    # Margins
    gStyle.SetPadTopMargin(0.08)
    gStyle.SetPadBottomMargin(0.19)
    gStyle.SetPadLeftMargin(0.17)
    #gStyle.SetPadRightMargin(0.07)

    # For the histo:
    gStyle.SetHistLineColor(1)
    gStyle.SetHistLineStyle(0)
    gStyle.SetHistLineWidth(2)
    gStyle.SetMarkerSize(1.4)
    gStyle.SetEndErrorSize(4)

    # For the statistics box:
    gStyle.SetOptStat(0)

    # For the axis
    gStyle.SetAxisColor(1, "XYZ")
    gStyle.SetTickLength(0.03, "XYZ")
    gStyle.SetNdivisions(510, "XYZ")
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetStripDecimals(False)

    # For the axis labels and titles
    gStyle.SetTitleColor(1, "XYZ")
    gStyle.SetLabelColor(1, "XYZ")
    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelOffset(0.007, "XYZ")
    gStyle.SetLabelSize(0.045, "XYZ")
    gStyle.SetTitleFont(42, "XYZ")
    gStyle.SetTitleSize(0.06, "XYZ")

    # For the legend
    gStyle.SetLegendBorderSize(0)
Exemplo n.º 16
0
    def draw(self, *args, **kwargs):
        """Central method of Plot class: make plot with canvas, axis, error, ratio..."""
        # https://root.cern.ch/doc/master/classTHStack.html
        # https://root.cern.ch/doc/master/classTHistPainter.html#HP01e
        verbosity = LOG.getverbosity(self, kwargs)
        xtitle = (args[0] if args else self.xtitle) or ""
        ratio = kwargs.get('ratio', self.ratio)  # make ratio plot
        square = kwargs.get('square', False)  # square canvas
        lmargin = kwargs.get('lmargin', 1.)  # canvas left margin
        rmargin = kwargs.get('rmargin', 1.)  # canvas righ margin
        tmargin = kwargs.get('tmargin', 1.)  # canvas bottom margin
        bmargin = kwargs.get('bmargin', 1.)  # canvas top margin
        errbars = kwargs.get('errbars', True)  # add error bars to histogram
        staterr = kwargs.get('staterr', False)  # create stat. error band
        sysvars = kwargs.get('sysvars',
                             [])  # create sys. error band from variations
        errtitle = kwargs.get('errtitle', None)  # title for error band
        norm = kwargs.get('norm', self.norm)  # normalize all histograms
        title = kwargs.get('title', self.title)  # title for legend
        xtitle = kwargs.get('xtitle', xtitle)  # x axis title
        ytitle = kwargs.get(
            'ytitle', self.ytitle
        )  # y axis title (if None, automatically set by Plot.setaxis)
        rtitle = kwargs.get('rtitle', "Ratio")  # y axis title of ratio panel
        latex = kwargs.get(
            'latex',
            self.latex)  # automatically format strings as LaTeX with makelatex
        xmin = kwargs.get('xmin', self.xmin)
        xmax = kwargs.get('xmax', self.xmax)
        ymin = kwargs.get('ymin', self.ymin)
        ymax = kwargs.get('ymax', self.ymax)
        rmin = kwargs.get('rmin', self.rmin) or 0.45  # ratio ymin
        rmax = kwargs.get('rmax', self.rmax) or 1.55  # ratio ymax
        ratiorange = kwargs.get('rrange',
                                self.ratiorange)  # ratio range around 1.0
        binlabels = kwargs.get(
            'binlabels', self.binlabels)  # list of alphanumeric bin labels
        ytitleoffset = kwargs.get('ytitleoffset', 1.0)
        xtitleoffset = kwargs.get('xtitleoffset', 1.0)
        logx = kwargs.get('logx', self.logx)
        logy = kwargs.get('logy', self.logy)
        ymargin = kwargs.get(
            'ymargin',
            self.ymargin)  # margin between hist maximum and plot's top
        logyrange = kwargs.get(
            'logyrange',
            self.logyrange)  # log(y) range from hist maximum to ymin
        grid = kwargs.get('grid', True)
        tsize = kwargs.get('tsize', _tsize)  # text size for axis title
        pair = kwargs.get('pair', False)
        triple = kwargs.get('triple', False)
        lcolors = kwargs.get('colors', None)
        lcolors = kwargs.get('lcolors', lcolors) or self.lcolors  # line colors
        fcolors = kwargs.get('fcolors', None) or self.fcolors  # fill colors
        lstyles = kwargs.get('lstyle', None)
        lstyles = kwargs.get('lstyles', lstyles) or self.lstyles  # line styles
        lwidth = kwargs.get('lwidth', 2)  # line width
        mstyle = kwargs.get('mstyle', None)  # marker style
        option = kwargs.get('option',
                            'HIST')  # draw option for every histogram
        options = kwargs.get('options', [])  # draw option list per histogram
        roption = kwargs.get('roption', None)  # draw option of ratio plot
        enderrorsize = kwargs.get('enderrorsize',
                                  2.0)  # size of line at end of error bar
        errorX = kwargs.get('errorX', True)  # horizontal error bars
        dividebins = kwargs.get('dividebins', self.dividebins)
        lcolors = ensurelist(lcolors)
        fcolors = ensurelist(fcolors)
        lstyles = ensurelist(lstyles)
        self.ratio = ratio
        self.lcolors = lcolors
        self.fcolors = fcolors
        self.lstyles = lstyles
        if not xmin: xmin = self.xmin
        if not xmax: xmax = self.xmax
        hists = self.hists
        denom = ratio if isinstance(ratio, int) and (ratio != 0) else False
        denom = max(0, min(len(hists), kwargs.get(
            'denom', denom)))  # denominator histogram in ratio plot

        # NORMALIZE
        if norm:
            if ytitle == None:
                ytitle = "A.U."
            scale = 1.0 if isinstance(norm, bool) else norm
            normalize(self.hists, scale=scale)

        # DIVIDE BY BINSIZE
        if dividebins:
            for i, oldhist in enumerate(self.hists):
                newhist = dividebybinsize(oldhist, zero=True, zeroerrs=False)
                if oldhist != newhist:
                    LOG.verb(
                        "Plot.draw: replace %s -> %s" % (oldhist, newhist),
                        verbosity, 2)
                    self.hists[i] = newhist
                    self.garbage.append(oldhist)
            #if sysvars:
            #  histlist = sysvars.values() if isinstance(sysvars,dict) else sysvars
            #  for (histup,hist,histdown) in histlist:
            #    dividebybinsize(histup,  zero=True,zeroerrs=False)
            #    dividebybinsize(histdown,zero=True,zeroerrs=False)
            #    if hist not in self.hists:
            #      dividebybinsize(hist,zero=True,zeroerrs=False)

        # DRAW OPTIONS
        if errbars:
            option = 'E0 ' + option  #E01
            if not roption:
                roption = 'HISTE'
        if len(options) == 0:
            options = [option] * len(hists)
            if staterr:
                options[0] = 'HIST'  # E3'
        else:
            while len(options) < len(hists):
                options.append(options[-1])
        #if not self.histsD and staterr and errbars:
        #  i = denominator-1 if denominator>0 else 0
        #  options[i] = options[i].replace('E0','')
        gStyle.SetEndErrorSize(enderrorsize)
        if errorX:
            gStyle.SetErrorX(0.5)
        else:
            gStyle.SetErrorX(0)

        # CANVAS
        self.canvas = self.setcanvas(square=square,
                                     ratio=ratio,
                                     lmargin=lmargin,
                                     rmargin=rmargin,
                                     tmargin=tmargin,
                                     bmargin=bmargin)

        # DRAW
        self.canvas.cd(1)
        #self.frame.Draw('AXIS') # 'AXIS' breaks grid
        for i, (hist, option1) in enumerate(zip(hists, options)):
            if triple and i % 3 == 2:
                option1 = 'E1'
            option1 += " SAME"
            hist.Draw(option1)
            LOG.verb(
                "Plot.draw: i=%s, hist=%s, option=%r" % (i, hist, option1),
                verbosity, 2)

        # STYLE
        lhists, mhists = [], []
        for hist, opt in zip(hists, options):
            if 'H' in opt: lhists.append(hist)
            else: mhists.append(hist)
        self.setlinestyle(lhists,
                          colors=lcolors,
                          styles=lstyles,
                          mstyle=mstyle,
                          width=lwidth,
                          pair=pair,
                          triple=triple)
        self.setmarkerstyle(*mhists, colors=lcolors)

        # CMS STYLE
        if CMSStyle.lumiText:
            #mainpad = self.canvas.GetPad(1 if ratio else 0)
            CMSStyle.setCMSLumiStyle(gPad, 0)

        # ERROR BAND
        if staterr or sysvars:
            #seterrorbandstyle(hists[0],fill=False)
            self.errband = geterrorband(self.hists[0],
                                        sysvars=sysvars,
                                        color=self.hists[0].GetLineColor(),
                                        name=makehistname(
                                            "errband", self.name),
                                        title=errtitle)
            self.errband.Draw('E2 SAME')

        # AXES
        self.setaxes(self.frame,
                     *hists,
                     xmin=xmin,
                     xmax=xmax,
                     ymin=ymin,
                     ymax=ymax,
                     logy=logy,
                     logx=logx,
                     xtitle=xtitle,
                     ytitle=ytitle,
                     ytitleoffset=ytitleoffset,
                     xtitleoffset=xtitleoffset,
                     binlabels=binlabels,
                     ymargin=ymargin,
                     logyrange=logyrange,
                     main=ratio,
                     grid=grid,
                     latex=latex)

        # RATIO
        if ratio:
            self.canvas.cd(2)
            self.ratio = Ratio(*hists,
                               errband=self.errband,
                               denom=denom,
                               drawzero=True,
                               option=roption)
            self.ratio.draw(roption, xmin=xmin, xmax=xmax)
            self.setaxes(self.ratio,
                         xmin=xmin,
                         xmax=xmax,
                         ymin=rmin,
                         ymax=rmax,
                         logx=logx,
                         binlabels=binlabels,
                         center=True,
                         nydiv=506,
                         rrange=ratiorange,
                         xtitle=xtitle,
                         ytitle=rtitle,
                         xtitleoffset=xtitleoffset,
                         grid=grid,
                         latex=latex)
            self.canvas.cd(1)
Exemplo n.º 17
0
def sample(nsample=1000,
           acc=0.8,
           resolutionFactor=0.02,
           mnevent=1000,
           opt="sme",
           width=7,
           precision=4):

    if "s" in opt:
        print "Sample from truth and gaussian smearing"
    elif "d" in opt:
        print "Sample from reference detector level"
    if "m" in opt:
        print "Use matrix correction"
    elif "b" in opt:
        print "Use bin-by-bin correction"
    if "e" in opt:
        print "Use x*exp(-x) function"
    elif "g" in opt:
        print "Use Gaus function"
    if "u" in opt:
        print "Use expected errors for sampled detector level"
    import re
    mo = re.search("w[0-5]", opt)
    if mo:
        print "Use weighted distribution", mo.group()

    # Initialise ROOT random numbers
    gRandom = TRandom3()

    # Function to sample
    if "e" in opt:
        fun = TF1("fun", "1000*x*exp(-x*20)", 0.0, 0.5)
    elif "g" in opt:
        fun = TF1("fun", "TMath::Gaus(x,0.25,0.15)", 0.0, 0.5)
    fun.SetNormalized(True)

    # Correction factors, matrix and reference histo
    cf, CR, cf2, CR2, eventAcc, histref, histdet, histref2, histdet2 = generate(
        fun, 1000000, acc, resolutionFactor, opt)

    # Create and fill sample histos
    if "s" in opt:
        histds, histd2s, hisths = fillSampleHistosSmear(
            fun, nsample, mnevent, resolutionFactor, opt)
    elif "d" in opt:
        histds, histd2s, hisths = fillSampleHistosDraw(histref, histdet,
                                                       histdet2, nsample,
                                                       mnevent, fun.GetTitle())

    # Error matrices after filling
    errorMatrixhSample = sampleErrorMatrix(hisths)
    errorMatrixdSample = sampleErrorMatrix(histds)

    # Get results with migration matrix or bin-by-bin correction
    if "b" in opt:
        histcs, errorMatricesCorr = bbbCorrection(histds, cf, eventAcc,
                                                  histdet, opt)
        histc2s, errorMatricesCorr2 = bbbCorrection(histd2s, cf2, eventAcc,
                                                    histdet2, opt)
    elif "m" in opt:
        histcs, errorMatricesCorr = matrixCorrection(histds, cf, CR, eventAcc,
                                                     histdet, opt)
        histc2s, errorMatricesCorr2 = matrixCorrection(histd2s, cf2, CR2,
                                                       eventAcc, histdet2, opt)

    # Error matrices after correction
    errorMatrixCorrAvg = averageMatrix(errorMatricesCorr)
    errorMatrixCorrSample = sampleErrorMatrix(histcs)

    print "Error matrix hadron"
    printMatrix(errorMatrixhSample, 7, 4)

    corr = cov2corr(errorMatrixhSample)
    print "Correlation matrix hadron"
    printMatrix(corr)

    print "Error matrix detector"
    printMatrix(errorMatrixdSample, 7, 4)

    corr = cov2corr(errorMatrixdSample)
    print "Correlation matrix detector"
    printMatrix(corr)

    print "Error matrix after correction calculated avg."
    printMatrix(errorMatrixCorrAvg, 7, 4)
    print "Error matrix after correction sampled"
    printMatrix(errorMatrixCorrSample, 7, 4)

    # Normalise
    errorMatricesNorm = dict()
    for isample in range(nsample):
        histc = histcs[isample]
        # Take error matrix from sampling or calculated
        errorMatrix = errorMatricesCorr[isample]
        # errorMatrix= errorMatrixCorrAvg
        # errorMatrix= errorMatrixCorrSample
        errorMatricesNorm[isample] = normalise(histc, errorMatrix)
        histh = hisths[isample]
        normalise(histh)

    # Sample averages
    mvalues = np.array(nbin * [0.0])
    merrors = np.array(nbin * [0.0])
    mvaluesh = np.array(nbin * [0.0])
    merrorsh = np.array(nbin * [0.0])
    merrors2 = np.array(nbin * [0.0])
    mmomentc = 0.0
    mmomentc2 = 0.0
    mmomerrc = 0.0
    mmomenth = 0.0
    mmomenth2 = 0.0
    for isample in range(nsample):
        histc = histcs[isample]
        histc2 = histc2s[isample]
        histh = hisths[isample]
        for i in range(nbin):
            valueh = histh.GetBinContent(i + 1)
            mvaluesh[i] += valueh
            merrorsh[i] += valueh**2
            valuei = histc.GetBinContent(i + 1)
            mvalues[i] += valuei
            merrors[i] += valuei**2
            error = histc.GetBinError(i + 1)
            merrors2[i] += error
        momentc = calcIntegral(histc)
        momentc2 = histc2.Integral(1, nbin) / histc2.GetEntries()
        mmomentc += momentc
        mmomentc2 += momentc**2
        mmomerrc += np.sqrt(np.sum(
            errorMatricesCorr[isample])) / histc.GetEntries()
        # mmomerrc+= sqrt( ( momentc2 - momentc**2 ) / histc2.GetEntries() )
        momenth = calcIntegral(histh)
        mmomenth += momenth
        mmomenth2 += momenth**2
    mvaluesh /= float(nsample)
    merrorsh /= float(nsample)
    mvalues /= float(nsample)
    merrors /= float(nsample)
    merrors -= mvalues**2
    merrors = np.sqrt(merrors)
    merrorsh -= mvaluesh**2
    merrorsh = np.sqrt(merrorsh)
    merrors2 /= float(nsample)
    mmomentc /= float(nsample)
    mmomentc2 /= float(nsample)
    mmomerrc /= float(nsample)
    mmomenth /= float(nsample)
    mmomenth2 /= float(nsample)

    errorMatrixNormSample = sampleErrorMatrix(histcs)
    errorMatrixNormAvg = averageMatrix(errorMatricesNorm)

    # Reference from histref
    normalise(histref)

    # Pulls
    pulls = np.array(nbin * [0.0])
    pullsstd = np.array(nbin * [0.0])
    pullmom = 0.0
    pullmom2 = 0.0
    for isample in range(nsample):
        histc = histcs[isample]
        # errorMatrix= errorMatricesNorm[isample]
        # errorMatrix= errorMatrixNormAvg
        errorMatrix = errorMatrixNormSample
        for i in range(nbin):
            if errorMatrix[i, i] != 0.0:
                pull = ((histc.GetBinContent(i + 1) -
                         histref.GetBinContent(i + 1)) /
                        sqrt(errorMatrix[i, i]))
                pulls[i] += pull
                pullsstd[i] += pull**2
        # Error from covariance matrix or from sampling
        pullmerr = np.sqrt(np.sum(
            errorMatricesCorr[isample])) / histc.GetEntries()
        # pullmerr= sqrt( mmomentc2 - mmomentc**2 )
        histc2 = histc2s[isample]
        moment = calcIntegral(histc)
        nevent = histc2.GetEntries()
        moment2 = histc2.Integral(1, nbin) / nevent
        # pullmerr= sqrt( ( moment2 - moment**2 ) / nevent )
        pullm = (moment - calcIntegral(histref)) / pullmerr
        pullmom += pullm
        pullmom2 += pullm**2
    pulls /= float(nsample)
    pullsstd /= float(nsample)
    pullsstd -= pulls**2
    pullsstd = np.sqrt(pullsstd)
    pullmom /= float(nsample)
    pullmom2 /= float(nsample)

    # Chi^2s w.r.t. reference
    hchi2diag = TH1D("hchi2diag", "P(Chi^2) diag. errors", 20, 0.0, 1.0)
    hchi2matrix = TH1D("hchi2matrix", "P(Chi^2) error matrix calc", 20, 0.0,
                       1.0)
    hchi2matrixs = TH1D("hchi2matrixs", "P(Chi^2) error matrix sample", 20,
                        0.0, 1.0)
    hchi2matrixa = TH1D("hchi2matrixa", "P(Chi^2) error matrix calc avg", 20,
                        0.0, 1.0)
    SetOwnership(hchi2diag, False)
    SetOwnership(hchi2matrix, False)
    SetOwnership(hchi2matrixs, False)
    SetOwnership(hchi2matrixa, False)
    for isample in range(nsample):
        histc = histcs[isample]
        chi2diag = 0.0
        for i in range(1, nbin + 1):
            error = histc.GetBinError(i)
            if error > 0.0:
                chi2diag += (
                    (histc.GetBinContent(i) - histref.GetBinContent(i)) /
                    error)**2
        hchi2diag.Fill(TMath.Prob(chi2diag, nbin))
        chi2matrix = chi2Matrix(errorMatricesNorm[isample], histc, histref)
        hchi2matrix.Fill(TMath.Prob(chi2matrix, nbin - 1))
        chi2matrix = chi2Matrix(errorMatrixNormSample, histc, histref)
        hchi2matrixs.Fill(TMath.Prob(chi2matrix, nbin - 1))
        chi2matrix = chi2Matrix(errorMatrixNormAvg, histc, histref)
        hchi2matrixa.Fill(TMath.Prob(chi2matrix, nbin - 1))

    # Printing
    fmt = "{:" + str(width) + "." + str(precision) + "f}"
    print "Sample averages"
    print "Avg. rec. moment:", fmt.format(mmomentc), "+/-", fmt.format(
        mmomerrc), "(avg.)",
    print fmt.format(sqrt(mmomentc2 - mmomentc**2)), "(sample)"
    print "Avg. had. moment:", fmt.format(mmomenth), "+/-", fmt.format(
        sqrt(mmomenth2 - mmomenth**2))
    print "Ref. moment, pull:", fmt.format(
        histref.Integral("width")), fmt.format(pullmom), fmt.format(
            sqrt(pullmom2 - pullmom**2))
    print "val.corr.err.sam.err.avg.M.sam.  M.calc. val.had.err.had.ref.    pull    pull.std."
    for i in range(nbin):
        print fmt.format(mvalues[i]),
        print fmt.format(merrors[i]),
        print fmt.format(merrors2[i]),
        print fmt.format(sqrt(errorMatrixNormSample[i][i])),
        print fmt.format(sqrt(errorMatrixNormAvg[i][i])),
        print fmt.format(mvaluesh[i]),
        print fmt.format(merrorsh[i]),
        print fmt.format(histref.GetBinContent(i + 1)),
        print fmt.format(pulls[i]),
        print fmt.format(pullsstd[i])
    corr = cov2corr(errorMatrixNormSample)
    print "Correlation from sampled error matrix"
    printMatrix(corr)
    corr = cov2corr(errorMatrixNormAvg)
    print "Correlation from average calculated error matrix"
    printMatrix(corr)

    # Plots
    gStyle.SetErrorX(0.0)
    canv1 = TCanvas("canv1", "Chi^2", 800, 1000)
    canv1.Divide(2, 3)
    canv1.cd(1)
    hchi2diag.SetMarkerStyle(20)
    hchi2diag.SetMarkerSize(0.5)
    hchi2diag.Draw()
    canv1.cd(2)
    hchi2matrix.SetMarkerStyle(20)
    hchi2matrix.SetMarkerSize(0.5)
    hchi2matrix.Draw()
    canv1.cd(3)
    hchi2matrixs.SetMarkerStyle(20)
    hchi2matrixs.SetMarkerSize(0.5)
    hchi2matrixs.Draw()
    canv1.cd(4)
    hchi2matrixa.SetMarkerStyle(20)
    hchi2matrixa.SetMarkerSize(0.5)
    hchi2matrixa.Draw()

    canv1.cd(5)
    SetOwnership(histref, False)
    histref.SetMarkerStyle(20)
    histref.SetMarkerSize(0.5)
    histref.Draw("hist")
    histres = TH1D("histres", "1000*x*exp(-x*20) avg. result", nbin, binEdges)
    SetOwnership(histres, False)
    for i in range(nbin):
        histres.SetBinContent(i + 1, mvalues[i])
        histres.SetBinError(i + 1, sqrt(errorMatrixNormAvg[i][i]))
    histres.SetMarkerStyle(20)
    histres.SetMarkerSize(0.5)
    histres.Draw("samepE1")
    canv1.cd(6)
    histpulls = TH1D("histpulls", "pulls corrected - reference ", nbin,
                     binEdges)
    SetOwnership(histpulls, False)
    for i in range(nbin):
        histpulls.SetBinContent(i + 1, pulls[i])
        histpulls.SetBinError(i + 1, pullsstd[i])
    histpulls.SetMarkerStyle(20)
    histpulls.SetMarkerSize(0.5)
    histpulls.Draw("pE1")

    # Fin
    return
Exemplo n.º 18
0
def main(extension, network_name, data_set_name, process, luminosity, WP_list,
         H1D_hist_list, H1D_tail_list, profile_list, tgraph_list,
         H2D_hist_list):
    gROOT.SetStyle("ATLAS")
    gROOT.ForceStyle()
    gStyle.SetErrorX(0.5)

    OUTPUT_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Output")
    hist_dir = os.path.join(OUTPUT_dir, network_name, data_set_name)
    rootfile_name = os.path.join(hist_dir, "histograms.root")

    ########## Loading and Plotting the TH1Ds ##########
    for (var, min, max) in H1D_hist_list:

        ## Creating the canvas object
        canvas = TCanvas("canvas_{}".format(var.name), 'A basic canvas', 800,
                         600)

        ## Adding a legend
        leg = Plotting.Create_Legend(0.72, 0.60, 0.95, 0.95, show_stats=True)

        ## Superimposing all of the graphs into a stack
        stack = Plotting.Draw_1D_Comp(rootfile_name, var, min, max, WP_list,
                                      leg)

        ## If the stack fails then we skip
        if stack == -1:
            continue

        ## Drawing all text
        draw_all_text(data_set_name, luminosity, process)

        ## Updating the canvas
        canvas.Update()

        ## Saving the file
        out_file = "{}/{}_{}.{}".format(hist_dir, data_set_name, var.plotname,
                                        extension)
        canvas.Print(out_file)

        del canvas

    ########## Loading and Plotting the Tails ##########
    for (var, min, max) in H1D_tail_list:

        ## Creating the canvas object
        canvas = TCanvas("canvas_tail_{}".format(var.name), 'A basic canvas',
                         800, 600)

        ## Adding in the legend
        leg = Plotting.Create_Legend(0.75, 0.65, 0.95, 0.95)

        ## Superimposing all of the graphs into a stack
        filled_stack = Plotting.Draw_1D_Comp(rootfile_name,
                                             var,
                                             min,
                                             max,
                                             WP_list,
                                             leg,
                                             isTail=True)

        ## If the stack fails then we skip
        if filled_stack == -1:
            continue

        ## Drawing all text
        draw_all_text(data_set_name, luminosity, process)

        ## Adding the legend
        leg.Draw()
        canvas.Update()
        canvas.SetLogy()

        out_file = "{}/{}_{}_tail.{}".format(hist_dir, data_set_name,
                                             var.plotname, extension)
        canvas.Print(out_file)

        del canvas

    ########## Profiles and TGraphs ##########
    for (var_x, var_y, min, max) in profile_list + tgraph_list:

        ## Are we looking at a TGraph or a TProfile
        isTgraph = True if (var_x, var_y, min, max) in tgraph_list else False

        ## Creating the canvas object
        canvas = TCanvas("canvas_{}_{}".format(var_x.name, var_y.name),
                         'A basic canvas', 800, 600)

        ## Adding in the legend
        leg = Plotting.Create_Legend(0.75, 0.65, 0.95, 0.95)

        ## Superimposing all of the graphs into a stack
        filled_stack = Plotting.Draw_2D_Comp(rootfile_name,
                                             var_x,
                                             var_y,
                                             min,
                                             max,
                                             WP_list,
                                             leg,
                                             isTgraph=isTgraph)

        ## If the stack fails then we skip
        if filled_stack == -1:
            continue

        ## Drawing all text
        draw_all_text(data_set_name, luminosity, process)

        ## Updating the canvas
        canvas.Update()

        out_file = "{}/{}_{}_{}.{}".format(hist_dir, data_set_name,
                                           var_x.plotname, var_y.plotname,
                                           extension)
        canvas.Print(out_file)

        del canvas

    ########## 2D histograms (each as their own) ##########
    for (vx, vy) in H2D_hist_list:
        for wp in WP_list:

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

            canvas = TCanvas(
                "{}_{}_{}_2D".format(vx.plotname, vy.plotname, wp.name),
                'A basic canvas', 800, 800)
            # gStyle.SetPalette(53)
            # TColor.InvertPalette()

            graph_name = "2D_{}_vs_{}_{}".format(vx.name, vy.name, wp.name)
            hist = Plotting.GetGraphFromFile(rootfile_name, graph_name)

            ylabel = wp.name + " " + vy.x_label + " " + vy.units

            if wp.name == "Network":
                if network_name == "flat_ann":
                    ylabel = "(A) " + ylabel
                if network_name == "smpl_ann":
                    ylabel = "(B) " + ylabel
                if network_name == "deep_ann":
                    ylabel = "(Z) " + ylabel

            hist.GetXaxis().SetTitle(vx.x_label + " " + vx.units)
            hist.GetYaxis().SetTitle(ylabel)

            # canvas.SetLogz()
            hist.Draw("col")

            if vx.name == "Truth" or "Tghtx":

                xline = TLine(0, 0, 200, 200)
                xline.SetLineColor(1)
                xline.SetLineWidth(2)
                xline.Draw()

                # dline = TLine(0,0,80,-80)
                # dline.SetLineColor(1)
                # dline.SetLineWidth(2)
                # dline.Draw()

            else:

                hist.GetXaxis().SetTitle("E_{x}^{miss} - E_{x}^{miss, true} " +
                                         vx.units)
                hist.GetYaxis().SetTitle("E_{y}^{miss} - E_{y}^{miss, true} " +
                                         vy.units)

                xline = TLine(-50, 0, 50, 0)
                xline.SetLineColor(1)
                xline.SetLineWidth(2)
                xline.Draw()

                yline = TLine(0, -50, 0, 50)
                yline.SetLineColor(1)
                yline.SetLineWidth(2)
                yline.Draw()

            hist.GetYaxis().SetMaxDigits(3)
            hist.GetXaxis().SetLabelOffset(0.017)

            # Adding in some text and the ATLAS Labels
            leg = Plotting.Create_Legend(0.19, 0.78, 0.58, 0.94)
            leg.Draw()

            Plotting.Draw_ATLASLabel(0.2, 0.89, text="Simulation")
            Plotting.Draw_Text(0.2, 0.84, text="work in progress", scale=1)
            Plotting.Draw_Text(0.2, 0.79, text=process, scale=1)

            canvas.Update()

            out_file = "{}/{}_{}.{}".format(hist_dir, data_set_name,
                                            graph_name, extension)
            canvas.Print(out_file)

    return 0
def main():  # pylint: disable=too-many-locals, too-many-statements, too-many-branches
    """
    Main plotting function
    """
    gROOT.SetBatch(True)

    # pylint: disable=unused-variable

    parser = argparse.ArgumentParser()
    parser.add_argument("--database-analysis",
                        "-d",
                        dest="database_analysis",
                        help="analysis database to be used",
                        required=True)
    parser.add_argument("--analysis",
                        "-a",
                        dest="type_ana",
                        help="choose type of analysis",
                        required=True)
    parser.add_argument("--input",
                        "-i",
                        dest="input_file",
                        help="results input file",
                        required=True)

    args = parser.parse_args()

    typean = args.type_ana
    shape = typean[len("jet_"):]
    print("Shape:", shape)

    file_in = args.input_file
    with open(args.database_analysis, "r") as file_db:
        data_param = yaml.safe_load(file_db)
    case = list(data_param.keys())[0]
    datap = data_param[case]

    logger = get_logger()

    i_cut = file_in.rfind("/")
    rootpath = file_in[:i_cut]

    # plotting
    # LaTeX string
    p_latexnhadron = datap["analysis"][typean]["latexnamehadron"]
    p_latexbin2var = datap["analysis"][typean]["latexbin2var"]
    v_varshape_latex = datap["analysis"][typean]["var_shape_latex"]

    # first variable (hadron pt)
    lpt_finbinmin = datap["analysis"][typean]["sel_an_binmin"]
    lpt_finbinmax = datap["analysis"][typean]["sel_an_binmax"]
    var1ranges = lpt_finbinmin.copy()
    var1ranges.append(lpt_finbinmax[-1])

    # second variable (jet pt)
    v_var2_binning = datap["analysis"][typean]["var_binning2"]  # name
    lvar2_binmin_reco = datap["analysis"][typean].get("sel_binmin2_reco", None)
    lvar2_binmax_reco = datap["analysis"][typean].get("sel_binmax2_reco", None)
    p_nbin2_reco = len(lvar2_binmin_reco)  # number of reco bins
    lvar2_binmin_gen = datap["analysis"][typean].get("sel_binmin2_gen", None)
    lvar2_binmax_gen = datap["analysis"][typean].get("sel_binmax2_gen", None)
    p_nbin2_gen = len(lvar2_binmin_gen)  # number of gen bins
    var2ranges_reco = lvar2_binmin_reco.copy()
    var2ranges_reco.append(lvar2_binmax_reco[-1])
    var2binarray_reco = array(
        "d",
        var2ranges_reco)  # array of bin edges to use in histogram constructors
    var2ranges_gen = lvar2_binmin_gen.copy()
    var2ranges_gen.append(lvar2_binmax_gen[-1])
    var2binarray_gen = array(
        "d",
        var2ranges_gen)  # array of bin edges to use in histogram constructors

    # observable (z, shape,...)
    v_varshape_binning = datap["analysis"][typean][
        "var_binningshape"]  # name (reco)
    v_varshape_binning_gen = datap["analysis"][typean][
        "var_binningshape_gen"]  # name (gen)
    lvarshape_binmin_reco = \
        datap["analysis"][typean].get("sel_binminshape_reco", None)
    lvarshape_binmax_reco = \
        datap["analysis"][typean].get("sel_binmaxshape_reco", None)
    p_nbinshape_reco = len(lvarshape_binmin_reco)  # number of reco bins
    lvarshape_binmin_gen = \
        datap["analysis"][typean].get("sel_binminshape_gen", None)
    lvarshape_binmax_gen = \
        datap["analysis"][typean].get("sel_binmaxshape_gen", None)
    p_nbinshape_gen = len(lvarshape_binmin_gen)  # number of gen bins
    varshaperanges_reco = lvarshape_binmin_reco.copy()
    varshaperanges_reco.append(lvarshape_binmax_reco[-1])
    varshapebinarray_reco = array(
        "d", varshaperanges_reco
    )  # array of bin edges to use in histogram constructors
    varshaperanges_gen = lvarshape_binmin_gen.copy()
    varshaperanges_gen.append(lvarshape_binmax_gen[-1])
    varshapebinarray_gen = array(
        "d", varshaperanges_gen
    )  # array of bin edges to use in histogram constructors

    file_results = TFile.Open(file_in)
    if not file_results:
        logger.fatal(make_message_notfound(file_in))

    ibin2 = 1

    suffix = "%s_%g_%g" % (v_var2_binning, lvar2_binmin_gen[ibin2],
                           lvar2_binmax_gen[ibin2])

    # HF data
    nameobj = "%s_hf_data_%d_stat" % (shape, ibin2)
    hf_data_stat = file_results.Get(nameobj)
    if not hf_data_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_hf_data_%d_syst" % (shape, ibin2)
    hf_data_syst = file_results.Get(nameobj)
    if not hf_data_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # HF PYTHIA
    nameobj = "%s_hf_pythia_%d_stat" % (shape, ibin2)
    hf_pythia_stat = file_results.Get(nameobj)
    if not hf_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # HF ratio
    nameobj = "%s_hf_ratio_%d_stat" % (shape, ibin2)
    hf_ratio_stat = file_results.Get(nameobj)
    if not hf_ratio_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_hf_ratio_%d_syst" % (shape, ibin2)
    hf_ratio_syst = file_results.Get(nameobj)
    if not hf_ratio_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive data
    nameobj = "%s_incl_data_%d_stat" % (shape, ibin2)
    incl_data_stat = file_results.Get(nameobj)
    if not incl_data_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_data_%d_syst" % (shape, ibin2)
    incl_data_syst = file_results.Get(nameobj)
    if not incl_data_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive PYTHIA
    nameobj = "%s_incl_pythia_%d_stat" % (shape, ibin2)
    incl_pythia_stat = file_results.Get(nameobj)
    if not incl_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_pythia_%d_syst" % (shape, ibin2)
    incl_pythia_syst = file_results.Get(nameobj)
    if not incl_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive ratio
    nameobj = "%s_incl_ratio_%d_stat" % (shape, ibin2)
    incl_ratio_stat = file_results.Get(nameobj)
    if not incl_ratio_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_ratio_%d_syst" % (shape, ibin2)
    incl_ratio_syst = file_results.Get(nameobj)
    if not incl_ratio_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # quark PYTHIA
    nameobj = "%s_quark_pythia_%d_stat" % (shape, ibin2)
    quark_pythia_stat = file_results.Get(nameobj)
    if not quark_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_quark_pythia_%d_syst" % (shape, ibin2)
    quark_pythia_syst = file_results.Get(nameobj)
    if not quark_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # gluon PYTHIA
    nameobj = "%s_gluon_pythia_%d_stat" % (shape, ibin2)
    gluon_pythia_stat = file_results.Get(nameobj)
    if not gluon_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_gluon_pythia_%d_syst" % (shape, ibin2)
    gluon_pythia_syst = file_results.Get(nameobj)
    if not gluon_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # plot the results with systematic uncertainties and models

    size_can = [800, 800]
    offsets_axes = [0.8, 1.1]
    margins_can = [0.1, 0.13, 0.1, 0.03]
    size_thg = 0.05
    offset_thg = 0.85

    gStyle.SetErrorX(0)  # do not plot horizontal error bars of histograms
    fontsize = 0.035
    opt_leg_g = "FP"
    opt_plot_g = "2"

    list_new = []  # list to avoid loosing objects created in loops

    # labels

    x_latex = 0.16
    y_latex_top = 0.83
    y_step = 0.055

    title_x = v_varshape_latex
    title_y = "(1/#it{N}_{jet}) d#it{N}/d%s" % v_varshape_latex
    title_full = ";%s;%s" % (title_x, title_y)
    title_full_ratio = ";%s;data/MC: ratio of %s" % (title_x, title_y)

    text_alice = "#bf{ALICE} Preliminary, pp, #sqrt{#it{s}} = 13 TeV"
    text_alice_sim = "#bf{ALICE} Simulation, pp, #sqrt{#it{s}} = 13 TeV"
    text_pythia = "PYTHIA 8 (Monash)"
    text_pythia_split = "#splitline{PYTHIA 8}{(Monash)}"
    text_jets = "charged jets, anti-#it{k}_{T}, #it{R} = 0.4"
    text_ptjet = "%g #leq %s < %g GeV/#it{c}, #left|#it{#eta}_{jet}#right| #leq 0.5" % (
        lvar2_binmin_reco[ibin2], p_latexbin2var, lvar2_binmax_reco[ibin2])
    text_pth = "%g #leq #it{p}_{T}^{%s} < %g GeV/#it{c}, #left|#it{y}_{%s}#right| #leq 0.8" % (
        lpt_finbinmin[0], p_latexnhadron,
        min(lpt_finbinmax[-1], lvar2_binmax_reco[ibin2]), p_latexnhadron)
    text_ptcut = "#it{p}_{T, incl. ch. jet}^{leading track} #geq 5.33 GeV/#it{c}"
    text_ptcut_sim = "#it{p}_{T, incl. ch. jet}^{leading h^{#pm}} #geq 5.33 GeV/#it{c} (varied)"
    text_sd = "Soft Drop (#it{z}_{cut} = 0.1, #it{#beta} = 0)"

    title_thetag = "#it{#theta}_{g} = #it{R}_{g}/#it{R}"
    radius_jet = 0.4

    # colour and marker indeces
    c_hf_data = 0
    c_incl_data = 1
    c_hf_mc = 2
    c_incl_mc = 6
    c_quark_mc = 5
    c_gluon_mc = 0

    # markers
    m_hf_data = get_marker(0)
    m_incl_data = get_marker(1)
    m_hf_mc = get_marker(0, 2)
    m_incl_mc = get_marker(1, 2)
    m_quark_mc = get_marker(2)
    m_gluon_mc = get_marker(3)

    # make the horizontal error bars smaller
    if shape == "nsd":
        for gr in [
                hf_data_syst, incl_data_syst, hf_ratio_syst, incl_ratio_syst,
                incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst
        ]:
            for i in range(gr.GetN()):
                gr.SetPointEXlow(i, 0.1)
                gr.SetPointEXhigh(i, 0.1)

    # data, HF and inclusive

    hf_data_syst_cl = hf_data_syst.Clone()

    leg_pos = [.72, .75, .85, .85]
    list_obj = [hf_data_syst, incl_data_syst, hf_data_stat, incl_data_stat]
    labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive", "", ""]
    colours = [
        get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data,
                                          c_incl_data), (2, 2, 1, 1))
    ]
    markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_data, list_obj_data_new = make_plot("cshape_data_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip((hf_data_syst, incl_data_syst), (c_hf_data, c_incl_data)):
        gr.SetMarkerColor(get_colour(c))
    list_obj_data_new[0].SetTextSize(fontsize)
    if shape == "nsd":
        hf_data_syst.GetXaxis().SetNdivisions(5)
    # Draw a line through the points.
    if shape == "nsd":
        for h in (hf_data_stat, incl_data_stat):
            h_line = h.Clone(h.GetName() + "_line")
            h_line.SetLineStyle(2)
            h_line.Draw("l hist same")
            list_new.append(h_line)
    cshape_data.Update()
    if shape == "rg":
        # plot the theta_g axis
        gr_frame = hf_data_syst
        axis_rg = gr_frame.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data = []
    for text_latex in [
            text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data.Update()
    cshape_data.SaveAs("%s/%s_data_%s.pdf" % (rootpath, shape, suffix))

    # data and PYTHIA, HF

    leg_pos = [.72, .65, .85, .85]
    list_obj = [hf_data_syst_cl, hf_data_stat, hf_pythia_stat]
    labels_obj = ["data", "", text_pythia_split]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_hf_data, c_hf_data, c_hf_mc), (2, 1, 1))
    ]
    markers = [m_hf_data, m_hf_data, m_hf_mc]
    y_margin_up = 0.4
    y_margin_down = 0.05
    cshape_data_mc_hf, list_obj_data_mc_hf_new = make_plot("cshape_data_mc_hf_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip([hf_data_syst_cl], [c_hf_data]):
        gr.SetMarkerColor(get_colour(c))
    leg_data_mc_hf = list_obj_data_mc_hf_new[0]
    leg_data_mc_hf.SetHeader("%s-tagged" % p_latexnhadron)
    leg_data_mc_hf.SetTextSize(fontsize)
    if shape == "nsd":
        hf_data_syst_cl.GetXaxis().SetNdivisions(5)
        #axis_nsd = hf_data_syst_cl.GetHistogram().GetXaxis()
        #x1 = axis_nsd.GetBinLowEdge(1)
        #x2 = axis_nsd.GetBinUpEdge(axis_nsd.GetNbins())
        #axis_nsd.Set(5, x1, x2)
        #for ibin in range(axis_nsd.GetNbins()):
        #    axis_nsd.SetBinLabel(ibin + 1, "%d" % ibin)
        #axis_nsd.SetNdivisions(5)
    cshape_data_mc_hf.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_data_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data_mc_hf.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data_mc_hf.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data_mc_hf = []
    for text_latex in [text_alice, text_jets, text_ptjet, text_pth, text_sd]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data_mc_hf.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data_mc_hf.Update()
    cshape_data_mc_hf.SaveAs("%s/%s_data_mc_hf_%s.pdf" %
                             (rootpath, shape, suffix))

    # data and PYTHIA, inclusive

    #leg_pos = [.68, .65, .85, .85]
    list_obj = [
        incl_data_syst, incl_pythia_syst, incl_data_stat, incl_pythia_stat
    ]
    labels_obj = ["data", text_pythia_split]
    colours = [
        get_colour(i, j) for i, j in zip((c_incl_data, c_incl_mc, c_incl_data,
                                          c_incl_mc), (2, 2, 1, 1))
    ]
    markers = [m_incl_data, m_incl_mc, m_incl_data, m_incl_mc]
    y_margin_up = 0.4
    y_margin_down = 0.05
    cshape_data_mc_incl, list_obj_data_mc_incl_new = make_plot("cshape_data_mc_incl_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip([incl_data_syst, incl_pythia_syst],
                     [c_incl_data, c_incl_mc]):
        gr.SetMarkerColor(get_colour(c))
    leg_data_mc_incl = list_obj_data_mc_incl_new[0]
    leg_data_mc_incl.SetHeader("inclusive")
    leg_data_mc_incl.SetTextSize(fontsize)
    if shape == "nsd":
        incl_data_syst.GetXaxis().SetNdivisions(5)
    cshape_data_mc_incl.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = incl_data_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data_mc_incl.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data_mc_incl.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data_mc_incl = []
    for text_latex in [text_alice, text_jets, text_ptjet, text_ptcut, text_sd]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data_mc_incl.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data_mc_incl.Update()
    cshape_data_mc_incl.SaveAs("%s/%s_data_mc_incl_%s.pdf" %
                               (rootpath, shape, suffix))

    # Ratios data/MC, HF and inclusive

    line_1 = TLine(lvarshape_binmin_reco[0], 1, lvarshape_binmax_reco[-1], 1)
    line_1.SetLineStyle(9)
    line_1.SetLineColor(1)
    line_1.SetLineWidth(3)

    #leg_pos = [.72, .7, .85, .85] # with header
    leg_pos = [.72, .75, .85, .85]  # without header
    list_obj = [
        hf_ratio_syst, line_1, incl_ratio_syst, hf_ratio_stat, incl_ratio_stat
    ]
    labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive"]
    colours = [
        get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data,
                                          c_incl_data), (2, 2, 1, 1))
    ]
    markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data]
    y_margin_up = 0.52
    y_margin_down = 0.05
    if shape == "nsd":
        y_margin_up = 0.22
    cshape_ratio, list_obj_ratio_new = make_plot("cshape_ratio_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full_ratio)
    cshape_ratio.Update()
    for gr, c in zip((hf_ratio_syst, incl_ratio_syst),
                     (c_hf_data, c_incl_data)):
        gr.SetMarkerColor(get_colour(c))
    leg_ratio = list_obj_ratio_new[0]
    leg_ratio.SetTextSize(fontsize)
    #leg_ratio.SetHeader("data/MC")
    if shape == "nsd":
        hf_ratio_syst.GetXaxis().SetNdivisions(5)
    cshape_ratio.Update()
    if shape == "rg":
        # plot the theta_g axis
        gr_frame = hf_ratio_syst
        axis_rg = gr_frame.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_ratio.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_ratio.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_ratio = []
    for text_latex in [
            text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd,
            text_pythia
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_ratio.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_ratio.Update()
    cshape_ratio.SaveAs("%s/%s_ratio_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, inclusive, quark, gluon

    incl_pythia_syst_cl = incl_pythia_syst.Clone()

    y_min_h, y_max_h = get_y_window_his([
        hf_pythia_stat, incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat
    ])
    y_min_g, y_max_g = get_y_window_gr(
        [incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst])
    y_min = min(y_min_h, y_min_g)
    y_max = max(y_max_h, y_max_g)
    y_margin_up = 0.46
    y_margin_down = 0.05
    y_min_plot, y_max_plot = get_plot_range(y_min, y_max, y_margin_down,
                                            y_margin_up)

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .55, .85, .85]
    list_obj = [
        incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat,
        incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["inclusive", "quark", "gluon", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_mc, c_quark_mc, c_gluon_mc, c_hf_mc, c_incl_mc,
                         c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1, 1))
    ]
    markers = [
        m_incl_mc, m_quark_mc, m_gluon_mc, m_hf_mc, m_incl_mc, m_quark_mc,
        m_gluon_mc
    ]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    cshape_mc.Update()
    for gr, c in zip((incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst),
                     (c_incl_mc, c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        incl_pythia_syst.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, quark, gluon

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .61, .85, .85]
    list_obj = [
        quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat,
        quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["quark", "gluon", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_quark_mc, c_gluon_mc, c_hf_mc, c_quark_mc,
                         c_gluon_mc), (2, 2, 1, 1, 1))
    ]
    markers = [m_quark_mc, m_gluon_mc, m_hf_mc, m_quark_mc, m_gluon_mc]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_qgd_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    cshape_mc.Update()
    for gr, c in zip((quark_pythia_syst, gluon_pythia_syst),
                     (c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        quark_pythia_syst.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_qgd_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, inclusive

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .67, .85, .85]
    list_obj = [incl_pythia_syst_cl, incl_pythia_stat, hf_pythia_stat]
    labels_obj = ["inclusive", "", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_mc, c_incl_mc, c_hf_mc), (2, 1, 1))
    ]
    markers = [m_incl_mc, m_incl_mc, m_hf_mc]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_id_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    # Draw a line through the points.
    if shape == "nsd":
        for h in (incl_pythia_stat, hf_pythia_stat):
            h_line = h.Clone(h.GetName() + "_line")
            h_line.SetLineStyle(2)
            h_line.Draw("l hist same")
            list_new.append(h_line)
    cshape_mc.Update()
    incl_pythia_syst_cl.SetMarkerColor(get_colour(c_incl_mc))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        incl_pythia_syst_cl.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_id_%s.pdf" % (rootpath, shape, suffix))

    # data inclusive vs PYTHIA, quark, gluon

    #leg_pos = [.6, .65, .75, .85]
    #leg_pos = [.72, .55, .85, .85]
    leg_pos = [.6, .7, .85, .85]
    list_obj = [
        incl_data_syst, quark_pythia_syst, gluon_pythia_syst, incl_data_stat,
        quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["inclusive (data)", "quark (PYTHIA 8)", "gluon (PYTHIA 8)"]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_data, c_quark_mc, c_gluon_mc, c_incl_data,
                         c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1))
    ]
    markers = [
        m_incl_data, m_quark_mc, m_gluon_mc, m_incl_data, m_quark_mc,
        m_gluon_mc
    ]
    y_margin_up = 0.3
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_data_iqg" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip((incl_data_syst, quark_pythia_syst, gluon_pythia_syst),
                     (c_incl_data, c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_data_i_mc_qg_%s.pdf" % (rootpath, shape, suffix))
def set_root_env():
    #//TStyle* genieStyle = new TStyle("genieStyle", "GENIE Style")
    #//set the background color to white
    gStyle.SetFillColor(10)
    gStyle.SetFrameFillColor(10)
    gStyle.SetCanvasColor(10)
    gStyle.SetPadColor(10)
    gStyle.SetTitleFillColor(0)
    gStyle.SetStatColor(10)

    #dont put a colored frame around the plots
    gStyle.SetFrameBorderMode(0)
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetPadBorderMode(0)
    gStyle.SetLegendBorderSize(3)

    #use the primary color palette
    #gStyle.SetPalette(1,0)

    #set the default line color for a histogram to be black
    gStyle.SetHistLineColor(ROOT.kBlack)

    #set the default line color for a fit function to be red
    gStyle.SetFuncColor(ROOT.kRed)

    #make the axis labels black
    gStyle.SetLabelColor(ROOT.kBlack, "xyz")

    #set the default title color to be black
    gStyle.SetTitleColor(ROOT.kBlack)

    #set the margins
    gStyle.SetPadBottomMargin(0.18)
    gStyle.SetPadTopMargin(0.08)
    gStyle.SetPadRightMargin(0.08)
    gStyle.SetPadLeftMargin(0.17)

    #set axis label and title text sizes
    gStyle.SetLabelFont(42, "xyz")
    gStyle.SetLabelSize(0.04, "xyz")
    gStyle.SetLabelOffset(0.015, "xyz")
    gStyle.SetTitleFont(42, "xyz")
    gStyle.SetTitleSize(0.04, "xyz")
    gStyle.SetTitleOffset(1.4, "y")
    gStyle.SetTitleOffset(1.3, "x")
    gStyle.SetStatFont(42)
    gStyle.SetStatFontSize(0.07)
    gStyle.SetTitleBorderSize(1)
    gStyle.SetStatBorderSize(0)
    gStyle.SetTextFont(42)
    gStyle.SetTitleW(0.5)
    gStyle.SetTitleH(0.1)

    #set line widths
    gStyle.SetFrameLineWidth(2)
    gStyle.SetFuncWidth(2)
    gStyle.SetHistLineWidth(2)

    #set the number of divisions to show
    gStyle.SetNdivisions(506, "xy")
    #gStyle.SetPadTickX(-50202)

    #turn off xy grids
    gStyle.SetPadGridX(0)
    gStyle.SetPadGridY(0)

    #set the tick mark style
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)

    #turn off stats
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(0)

    #marker/line settings
    #gStyle.SetMarkerStyle(20)
    gStyle.SetMarkerSize(.95)  #0.7
    gStyle.SetLineWidth(2)
    gStyle.SetErrorX(0)
    gStyle.SetHistLineStyle(0)  #It was 3 for a dotted line

    #done
    gStyle.cd()
    gROOT.ForceStyle()
Exemplo n.º 21
0
def featureSizePlots(optunf="Bayes",
                     leff=True,
                     optfun="exp",
                     opttfun="",
                     loufl=False,
                     gmean=-1.0,
                     nrebin=4):

    if opttfun == "":
        opttfun = optfun

    if optfun == "blobel":
        gmean = 0.0

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

    global hReco, hMeas, hTrue, hPulls, canv, histos
    histos = []
    canv = TCanvas("canv", "feature size plots", 600, 800)
    canv.Divide(1, 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]]:
        measurement = createMeasurement(gmean, sigma, leff, optfun)
        response = trainer.train(measurement, loufl=loufl)
        unfold, hTrue, hMeas = unfoldtester.rununfoldtest(
            tester, measurement, response)
        hReco = unfold.Hreco(2)

        hRecoMeasured = unfold.HrecoMeasured()

        chisqm = unfold.Chi2measured()
        pchisqm = TMath.Prob(chisqm, hMeas.GetNbinsX() - hReco.GetNbinsX())
        print "Chisq measured=", chisqm, "P(chi^2)=", pchisqm

        if hbininfo["nrebin"] > 1:
            hTrue = hTrue.Rebin(nrebin)
        histos.append([hTrue, hMeas, hReco])
        canv.cd(ipad)
        gStyle.SetErrorX(0)
        hReco.SetTitle(optunf + ", smear mu, s.d.= " + str(gmean) + ", " +
                       str(sigma) + ", train: " + funttxt + ", test: " +
                       funtxt)
        hReco.SetYTitle("Entries")
        hReco.SetMinimum(0.0)
        hReco.SetMarkerStyle(20)
        hReco.SetMarkerSize(0.75)
        hReco.SetStats(False)
        hReco.Draw("pe")
        hRecoMeasured.Draw("same")
        hMeas.SetMarkerStyle(20)
        hMeas.SetMarkerSize(0.5)
        hMeas.Draw("samepe")
        hTrue.SetLineColor(8)
        hTrue.Draw("same")

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

    return
Exemplo n.º 22
0
def main():

   from optparse import OptionParser
   parser = OptionParser()
   parser.add_option("-i", "--inputfile", dest="inputfile")
   parser.add_option("-N", "--multiplicity", dest="N", type="int", default=3)
   parser.add_option("-x", "--exclusive", action="store_true",\
         dest="isExclusive", default=False)
   parser.add_option("-l", "--label", dest="label", type="string", default="")
   (options, args) = parser.parse_args()

   N = options.N
   isExclusive = options.isExclusive
   label_text = options.label

   if isExclusive and not (N == 2 or N == 3):
      parser.error("Exclusive plot only for N =2 or 3")

   import configurations as config
   from ROOT import TFile, TCanvas, THStack, TLegend, TPaveText, gStyle
   from ModelParser import ModelKey

   gStyle.SetPadTopMargin(0.05)
   gStyle.SetPadRightMargin(0.05)
   gStyle.SetErrorX(0.)

   suffix = ""
   if not isExclusive:
      suffix = "up"

   sm_files = []
   for model in config.sm_models:
      f = TFile("%s/%s.root" % (config.sm_dir, model), "READ")
      sm_files.append(f)

   bh_weights = []
   bh_files = []
   from BHXsec import BHXsec
   xsec = BHXsec()
   for model in config.bh_showcase:
      f = TFile("%s/%s.root" % (config.bh_dir, model), "READ")
      bh_files.append(f)
      h = f.Get("plotsNoCut/ST")
      nEvents= h.GetEntries()
      bh_weights.append(xsec.get(model) / nEvents * config.integrated_luminosity)

   c = TCanvas("ST_Mul%d%s" % (N, suffix),
         "ST_Mul%d%s" % (N, suffix), 500, 500)
   hs = THStack()
   hs1 = THStack()

   infile = TFile(options.inputfile, "READ")
   hBkg = infile.Get("Background_N%d%s" % (N, suffix))
   gBkg = infile.Get("BackgroundGraph_N%d%s" % (N, suffix))
   hData = infile.Get("Data_N%d%s" % (N, suffix))
   hBkg = infile.Get("Background_N%d%s" % (N, suffix))
   hBkg.SetMarkerSize(0)
   hBkg_ = hBkg.Clone("BkgLine")
   hBkg.SetFillColor(33)
   hBkg.SetLineColor(33)
   hBkg_.SetLineWidth(3)
   hBkg_.SetLineColor(862)
   hs.Add(hBkg, "e3")

   #legend = TLegend(0.2826613,0.4819492,0.6094355,0.9416102) # - only for N >= 2 and 3
   legend = TLegend(0.3026613,0.5519492,0.6094355,0.9416102) # was 0.4919...
   legend.SetTextSize(0.041); #was 0.02966102
   legend.SetTextFont(42);
   legend.SetFillColor(0)
   legend.SetLineColor(0)
   if isExclusive:
      legend.SetHeader("Multiplicity N = %d" % N)
   else:
      legend.SetHeader("Multiplicity N #geq %d" % N)
   legend.AddEntry(hData, "Data", "lep")
   legend.AddEntry(hBkg_, "Background", "l")
   legend.AddEntry(hBkg, "Uncertainty", "f")

   legend_sm = TLegend(0.6271774,0.7369492,0.8308065,0.8771186)
   legend_sm.SetTextSize(0.041);
   legend_sm.SetTextFont(42);
   legend_sm.SetFillColor(0)
   legend_sm.SetLineColor(0)

   for i, f in enumerate(bh_files):
      h = f.Get("plotsN%d%s/ST" % (N, suffix))
      h.Rebin(config.rebin)
      h.Scale(bh_weights[i])

      # Add background
      for ibin in range(h.GetNbinsX()):
         h.SetBinContent(ibin+1,\
               h.GetBinContent(ibin+1)\
               + hBkg.GetBinContent(ibin+1))

         h.SetLineWidth(3)
         #h.SetLineColor(i+2)
         h.SetLineStyle(i+2)

         if i == 0:
            h.SetLineColor(814)
         if i == 1:
            h.SetLineStyle(5)
            h.SetLineColor(899)
         if i == 2:
            h.SetLineStyle(9)
            h.SetLineColor(4)
         if i == 3:
            h.SetLineStyle(3)
            h.SetLineColor(614)

      hs.Add(h, "hist")
      model = ModelKey(config.bh_showcase[i])
      bh_legend = "M_{D} = %.1f TeV, M_{BH}^{ min} = %.1f TeV, n = %d" % (\
            model.parameter["MD"],
            model.parameter["M"],
            model.parameter["n"])
      if i == 3:
         bh_legend = "M_{D} = 3.0 TeV, M_{QBH}^{ min} = 4.0 TeV, n = 4"    

      legend.AddEntry(h, bh_legend, "l")

#      qbh_legend = "M_{D} = 4.0 TeV, M_{QBH}^{ min} = 5.0 TeV, n = 5"

#      legend.AddEntry(h, qbh_legend, "l")

   if isExclusive:
      for i, f in enumerate(sm_files):
         h = f.Get("plotsN%d%s/ST" % (N, suffix))
         h.Rebin(config.rebin)
         h.Scale(config.integrated_luminosity)
         h.SetFillColor(config.sm_colors[i])
         h.SetLineColor(config.sm_colors[i])
         hs1.Add(h, "hist")
         legend_sm.AddEntry(h, config.sm_models[i], "f")
   
   #hs.Add(hData, "e")   
   
   hs.Draw("nostack")
   hs1.Draw("same")  
   c.SetLogy(1)
   hs.GetXaxis().SetTitle("S_{T} (GeV)")
   hs.GetYaxis().SetTitle(hData.GetYaxis().GetTitle())
   hs.GetYaxis().SetTitleOffset(1.25)

   hs.GetYaxis().SetTitleSize(0.04)
   hs.GetYaxis().SetLabelSize(0.04)
   hs.GetXaxis().SetTitleSize(0.04)
   hs.GetXaxis().SetLabelSize(0.04)
    
   ibin = 0
   #if isExclusive:
   #   hs.GetXaxis().SetRangeUser(config.fit_range[0], config.maxST)
   #   ibin = hData.FindBin(config.fit_range[0])
   #else:
   #   hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
   #   ibin = hData.FindBin(config.norm_range[0])
   
   if isExclusive:
      hs.GetXaxis().SetRangeUser(1800, config.maxST)
      ibin = hData.FindBin(1800)
   else:
      hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
      ibin = hData.FindBin(config.norm_range[0])

   from Styles import formatUncertainty
   formatUncertainty(gBkg)
   gBkg.Draw("LX")
   hData.Draw("sameex0")

   hs.SetMinimum(5e-1)
   if isExclusive:
      hs.SetMaximum(hData.GetBinContent(ibin) * 40)
   else:
      #hs.SetMaximum(4e4)
      hs.SetMaximum(hData.GetBinContent(ibin) * 20) # or 1e7 for N>=3 and use 4 models

   legend.Draw("plain")
   if isExclusive:
      legend_sm.Draw("plain")

   if isExclusive:
      cmslabel =TPaveText(0.45,0.96,0.60,0.99,"brNDC");
   else:
      cmslabel = TPaveText(0.45,0.96,0.60,0.99,"brNDC")
   cmslabel.AddText(config.cmsTitle)
   #cmslabel.AddText(config.cmsSubtitle)
   cmslabel.SetFillColor(0)
   cmslabel.SetTextSize(0.041)
   cmslabel.Draw("plain")

   label = TPaveText(0.8891129,0.8644068,0.9435484,0.9258475,"brNDC")
   label.SetFillColor(0)
   label.SetTextSize(0.0529661);
   label.AddText(label_text);
   label.Draw("plain")

   #block1 =TPaveText(0.333,0.84,0.354,0.86,"brNDC"); # for N>=2 and >=3 only
   block1 =TPaveText(0.351,0.85,0.37,0.87,"brNDC");
   block1.SetFillColor(0)
   block1.Draw("plain")

   #block2 =TPaveText(0.295,0.84,0.315,0.86,"brNDC"); # for N>=2 and >=3 only
   block2 =TPaveText(0.314,0.85,0.332,0.87,"brNDC");
   block2.SetFillColor(0)
   block2.Draw("plain")
   
   if isExclusive:
     c.Print("ST_Mul%d.pdf" % N)
     c.Print("ST_Mul%d.png" % N)
   else:
     c.Print("ST_Mul%dup.pdf" % N)
     c.Print("ST_Mul%dup.png" % N)    
   c.Update()

   raw_input("Press Enter to continue...")
Exemplo n.º 23
0
def Draw_2D_Comp(rootfile_name,
                 var_x,
                 var_y,
                 min,
                 max,
                 WP_list,
                 leg,
                 isTgraph=False):
    gStyle.SetErrorX(0.5)

    ## Creating a multigraph for the canvas if we are looking at TGraphs
    if isTgraph:
        stack = TMultiGraph()
        args = "AP"

    ## Creating a stack for the canvas if we are looking at TPofiles
    else:
        stack = THStack("stack", var_x.name + var_y.name)
        args = "nostack "

    stack.SetMinimum(min)
    stack.SetMaximum(max)

    for wp in WP_list:

        ## Generating the graph name
        graph_name = "{}_vs_{}_{}".format(var_x.name, var_y.name, wp.name)
        if isTgraph:
            graph_name += "_res"

        ## Loading the graph using its name and file location
        graph = GetGraphFromFile(rootfile_name, graph_name)
        if graph == -1:
            continue

        ## Setting the colors specific to the working point
        graph.SetLineColor(wp.colour)
        graph.SetMarkerColor(wp.colour)
        graph.SetMarkerStyle(wp.marker)

        ## Adding the legend entry
        leg.AddEntry(graph, wp.name, "p")

        ## Adding the object to the stack
        stack.Add(graph)
        del graph

    ## Checking to see if any graphs were found for this variable
    nhists = stack.GetListOfGraphs().GetSize(
    ) if isTgraph else stack.GetNhists()
    if nhists == 0:
        print("\n\n\nNo graphs found for working point {}\n\n\n".format(
            wp.name))
        return -1

    ## Drawing the stack on the currrent canvas
    stack.Draw(args)
    leg.Draw()

    ## Setting axis labels
    stack.GetXaxis().SetTitle(var_x.x_label + " " + var_x.units)
    stack.GetYaxis().SetTitle(var_y.x_label + " " + var_y.units)

    ## Moving axis tick marks
    stack.GetYaxis().SetMaxDigits(3)
    stack.GetXaxis().SetLabelOffset(0.017)

    return stack
Exemplo n.º 24
0
import subprocess
from array import array
from ROOT import TH1D, TH2D, TFile, TMath, TCanvas, THStack, TLegend, TPave, TLine, TLatex, TPaveText
from ROOT import gROOT, gStyle, gPad, gStyle
from ROOT import Double, kBlue, kRed, kOrange, kMagenta, kYellow, kCyan, kGreen, kGray, kBlack, kTRUE

gROOT.Macro("~/rootlogon.C")
gStyle.SetOptStat(0)
#gROOT.SetBatch()
gROOT.SetStyle("Plain")
gStyle.SetOptStat()
gStyle.SetOptTitle(0)
gStyle.SetPalette(1)
gStyle.SetNdivisions(405, "x")
gStyle.SetEndErrorSize(0.)
gStyle.SetErrorX(0.1000)
gStyle.SetPadTickX(1)
gStyle.SetPadTickY(1)

from optparse import OptionParser
parser = OptionParser()
parser.add_option('--plotDir',
                  metavar='P',
                  type='string',
                  action='store',
                  default='Summer2018Plots',
                  dest='plotDir',
                  help='output directory of plots')
(options, args) = parser.parse_args()

outDir = options.plotDir
Exemplo n.º 25
0
# loop over filter rate histograms
for j, h in enumerate(rateHists):
    h.SetMarkerStyle(22)
    h.SetMarkerSize(1.2)
    if (last_lb - first_lb) > 600:
        h.SetMarkerSize(0.6)
    h.SetMarkerColor(colors[j % len(colors)])
    h.SetLineColor(colors[j % len(colors)])
    h.Draw("P")
    h.SetTitle(filterNames_mAug[j])
    h.GetXaxis().SetTitle("lumi block")
    h.GetYaxis().SetTitle("n events")
    h.GetXaxis().SetRangeUser(first_lb - 20, last_lb + 20)
    h.SetStats(ROOT.kFALSE)
    gPad.SetTicks(1, 1)
    gStyle.SetErrorX(0)
    latex3.Draw()
    latex4.Draw()
    c2.Update()
    c2.Print("run_" + runNumber + "_" + str(j) + "_events.pdf")

# FILTER RATES
c1.cd()
# configure total rate hist
totalRateHist.Divide(lbTimeHist)
totalRateHist.Multiply(lbScaleHist)
for bin in range(1, totalRateHist.GetNbinsX() + 1):
    totalRateHist.SetBinError(bin, 0)  # no appreciable errors on rate
# add total rpvll rate hist entry to legend
l1.AddEntry(totalRateHist, "Overall RPVLL Rate", "lp")
Exemplo n.º 26
0
def ExportPlot(TDirName, NominalHists, DataHists, SystBand, BatchMode = False):
	if BatchMode:
		ROOT.gROOT.SetBatch()

	c = ROOT.TCanvas("c2", "",800,700)
	c.cd()
	gStyle.SetOptStat(0)
	gStyle.SetHatchesLineWidth(1)
	gStyle.SetErrorX(0)

	logging.info("Defining colour palette ... ")
	colours = {}
	colours["Singletop"]= TColor(3000,54./255, 121./255,191./255)
	colours["ttbar"]=       TColor(3001,123./255, 178./255, 116./255)
	colours["Wjets"]= TColor(3002,130./255, 95./255, 135./255)
	colours["Zjets"]= TColor(3003,252./255, 176./255, 8./255)
	colours["Diboson"]=TColor(3007,168./255, 164./255, 150./255)

	# # Begin work on top pad
	pad1 = CreateTopPad("pad1")
	pad1.cd()
	pad1.SetLogy()
	SetTicks(pad1)

	# Create TLegend
	Legend = CreateLegend()

	# Get systematic band but dont draw
	TopUncertBand = DrawUncHist(SystBand, colours, Legend)

	# Draw MC
	SMHist, MCStack = DrawSMHists(NominalHists, colours, Legend)
	# Then draw the MC stack
	MCStack.Draw("HIST L")
	logging.info("Drawn MC stack")

	SMHist = ApplySystematicBand(SMHist, TopUncertBand)
	# This gives us the error on the SM Hist
	SMHist.Draw("E3 SAME")
	# This gives us the line as well as the hashed fill
	# SMHist.Draw("C SAME")
	logging.info("Drawn SM total with systematic band")

	# Draw Data
	DataHist = DrawDataHists(DataHists, colours, Legend)
	DataHist.Draw("E0 SAME")
	logging.info("Drawn data")

	# Draw Legend
	logging.info("Drawing legend ... ")
	Legend.Draw()

	logging.info("Adding more aesthetic changes ...")
	# Draw ATLAS Text
	ATLASText = DrawATLAS()

	# Begin work on DataMC Ratio
	c.cd()
	pad2 = CreateBottomPad("pad2")
	SetTicks(pad2)
	
	DataMCHist, UncBand = DrawDataMCPad(DataHist, SMHist, pad2)
	DataMCHist.Draw("ep")
	UncBand.Draw("E3 SAME")
	logging.info("Drawn dataMC ratio")

	c.Update()
	logging.info("Finished this plot!")

	PlotName = "Final_"+DataHist.GetName().split("_nominal")[0]
	c.SaveAs("Plots/" + TDirName + "/" + PlotName+".pdf")
	if not BatchMode:
		raw_input()
Exemplo n.º 27
0
if outd == "-1":
    outdir = "./"
else:
    outdir = outd + "/"
if not os.path.isdir(outdir): os.system("mkdir " + outdir)

# Setup ROOT
print "Setting ROOT options"
gROOT.SetBatch()
gROOT.SetStyle("Plain")
gStyle.SetOptStat(11111111)
gStyle.SetOptTitle(0)
gStyle.SetPalette(1)
gStyle.SetNdivisions(405, "x")
gStyle.SetEndErrorSize(0.)
gStyle.SetErrorX(0.001)

#########################################################
# Make fitFuncs dictionary containing all information
# for defining three fit functions
#########################################################

fitFuncs = {}

# Power law
######################
fitFuncs["f1", "col"] = 1
fitFuncs["f1", "npar"] = 1
fitFuncs["f1", "name"] = "1 / x^{p0}"
fitFuncs["f1", "str"] = "1. / ( st/7000.)^(f1_p0)"
fitFuncs["f1", "par"] = ("f1_p0", 5.0, 0., 10.)
Exemplo n.º 28
0
#change the CMS_lumi variables (see CMS_lumi.py)
CMS_lumi.lumi_7TeV = "4.8 fb^{-1}"
CMS_lumi.lumi_8TeV = "18.3 fb^{-1}"
CMS_lumi.writeExtraText = 1
CMS_lumi.extraText = "Preliminary"
CMS_lumi.lumi_sqrtS = ""  #"13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)

iPos = 11
if (iPos == 0): CMS_lumi.relPosX = 0.12

H_ref = 700
W_ref = 700
W = W_ref
H = H_ref

gStyle.SetErrorX(
    0.5)  # owen: need to add this to get horizontal bars on data hist

#------------------------------------------------------------


def printEvtYields(hist, name):
    if not hist: return
    #  printout = [name+":"]
    printout = ["{0: <19}:".format(name)]
    for ibin in range(1, hist.GetXaxis().GetNbins() + 1):
        #    content = hist.GetBinContent(ibin)
        #    error = hist.GetBinError(ibin)
        #error = Double() # owen
        error = ctypes.c_double()
        content = hist.IntegralAndError(ibin, ibin, error)
        ##########yields = "{0:10.2f}".format(content) +" +- " + "{0:<10.2f}".format(error)
Exemplo n.º 29
0
def efficiencytracking(var):
    # plots the efficiency vs pT, eta and phi for all the species(it extracts the
    # Efficiency from qa - tracking - efficiency if you have ran with-- make - eff)
    hadron_list = [
        "pion",
        "proton",
        "kaon",
        "electron",
        "muon",
    ]
    color_list = [1, 2, 4, 6, 8]
    marker_list = [20, 21, 22, 34, 45]
    fileo2 = TFile("../codeHF/AnalysisResults_O2.root")

    c1 = TCanvas("c1", "Efficiency")
    gStyle.SetOptStat(0)
    gStyle.SetErrorX(0)
    gStyle.SetFrameLineWidth(2)
    gStyle.SetTitleSize(0.045, "x")
    gStyle.SetTitleSize(0.045, "y")
    gStyle.SetMarkerSize(1)
    gStyle.SetLabelOffset(0.015, "x")
    gStyle.SetLabelOffset(0.02, "y")
    gStyle.SetTickLength(-0.02, "x")
    gStyle.SetTickLength(-0.02, "y")
    gStyle.SetTitleOffset(1.1, "x")
    gStyle.SetTitleOffset(1.0, "y")

    c1.SetCanvasSize(800, 600)
    c1.cd()
    c1.SetGridy()
    c1.SetGridx()
    eff_list = []

    if var == "Pt":
        hempty = TH1F("hempty", ";Transverse Momentum(GeV/c);Efficiency", 100,
                      0.05, 10)
        gPad.SetLogx()
    elif var == "Eta":
        hempty = TH1F("hempty", ";Pseudorapidity;Efficiency", 100, -4.0, 4.0)
    elif var == "Phi":
        hempty = TH1F("hempty", ";Azimuthal angle(rad);Efficiency", 100, 0.0,
                      6.0)

    hempty.GetYaxis().CenterTitle()
    hempty.GetXaxis().CenterTitle()
    hempty.GetXaxis().SetNoExponent()
    hempty.GetXaxis().SetMoreLogLabels(1)
    hempty.Draw()
    leg = TLegend(0.55, 0.15, 0.89, 0.35, "P")
    leg.SetNColumns(2)
    leg.SetHeader("Minimum bias KrKr #sqrt{s} = 6.46TeV", "C")
    leg.SetFillColor(0)

    for i, had in enumerate(hadron_list):
        leff = fileo2.Get("qa-tracking-efficiency-%s/Efficiency" % had)
        if var == "Pt":
            eff = leff.At(0)
        elif var == "Eta":
            eff = leff.At(1)
        elif var == "Phi":
            eff = leff.At(2)
        gPad.Update()
        eff.Paint("p")
        gr = eff.GetPaintedGraph().Clone()
        for j in range(0, gr.GetN()):
            gr.GetEXlow()[j] = 0
            gr.GetEXhigh()[j] = 0

        gr.SetLineColor(color_list[i])
        gr.SetMarkerColor(color_list[i])
        gr.SetMarkerStyle(marker_list[i])
        eff_list.append(gr)
        gr.Draw(" same p")
        leg.AddEntry(eff_list[i], had, "p")
    leg.Draw()
    saveCanvas(c1, "efficiency_tracking_%s" % var)
Exemplo n.º 30
0
def dependencies(source,modifier,path,selection,plots,runRange,isMC,nonNormalized,backgrounds,cmsExtra,fit,ptCut):
        era = runRange.era
        pathMC = locations[era].dataSetPathMC
        if isMC:
                backgrounds = ["Rare","SingleTop","TT_Powheg","Diboson","DrellYanTauTau","DrellYan"]
        backgroundsTTbar = ["TT_Powheg", "DibosonFS", "RareFS"]
        backgroundsOnZ = ["DrellYan", "DibosonNonFS", "RareNonFS"]
        #backgroundsTTbar = ["Rare","SingleTop","TT_Powheg","Diboson","DrellYanTauTau","DrellYan"]
        
        for name in plots:
                plot = getPlot(name)
                plot.addRegion(selection)
                plot.addRunRange(runRange)
                baseCuts = plot.cuts
                
                #~ plot.cuts = plot.cuts.replace("p4.M()","mll")
                #~ plot.variable = plot.variable.replace("p4.M()","mll")
                #plot.cuts = plot.cuts.replace("mll","p4.M()")
                #plot.cuts = plot.cuts.replace("pt > 25","p4.Pt() > 25")
                #plot.variable = plot.variable.replace("mll","p4.M()")
                #~ plot.cuts = plot.cuts.replace("p4.Pt()","pt")
                plot.cuts = plot.cuts.replace("&& metFilterSummary > 0","")
                #~ plot.cuts = plot.cuts.replace("genWeight*weight*","")
                #~ plot.cuts = plot.cuts.replace("weight*","")
                plot.variable = plot.variable.replace("p4.Pt()","pt")
                
                if "Forward" in selection.name:
                        label = "forward"
                elif "Central" in selection.name:
                        label = "central"
                else:           
                        label = "inclusive"
                
                if isMC:        
                        if os.path.isfile("shelves/rSFOF_Control_%s_MC.pkl"%(runRange.label)):
                                centralVals = pickle.load(open("shelves/rSFOF_Control_%s_MC.pkl"%(runRange.label),"rb"))
                        else:
                                centralVals = centralValues(source,modifier,path,selection,runRange,isMC,nonNormalized,backgrounds,cmsExtra)
                else:   
                        if os.path.isfile("shelves/rSFOF_Control_%s.pkl"%(runRange.label)):
                                centralVals = pickle.load(open("shelves/rSFOF_Control_%s.pkl"%(runRange.label),"rb"))
                        else:
                                centralVals = centralValues(source,modifier,path,selection,runRange,isMC,nonNormalized,backgrounds,cmsExtra)
        
                if os.path.isfile("shelves/rSFOF_Control_%s_MC.pkl"%(runRange.label)):
                        centralValsTTbar = pickle.load(open("shelves/rSFOF_Control_%s_MC.pkl"%(runRange.label),"rb"))
                else:
                        centralValsTTbar = centralValues(source,modifier,path,selection,runRange,True,nonNormalized,backgroundsTTbar,cmsExtra)

                print plot.cuts
                histEE, histMM, histEM = getHistograms(path,source,modifier,plot,runRange,isMC,nonNormalized, backgrounds,label)
                histRSFOF = histEE.Clone("histRSFOF")
                histRSFOF.Add(histMM.Clone())
                histRSFOF.Divide(histEM)                                
                histEE.Divide(histEM)                           
                histMM.Divide(histEM)
                
                plot.cleanCuts()
                
                histEETTbar, histMMTTbar, histEMTTbar = getHistograms(path,source,modifier,plot,runRange,True,nonNormalized, backgroundsTTbar,label)                            
                histRSFOFTTbar = histEETTbar.Clone("histRSFOFTTbar")
                histRSFOFTTbar.Add(histMMTTbar.Clone())
                histRSFOFTTbar.Divide(histEMTTbar)                              
                histEETTbar.Divide(histEMTTbar)                         
                histMMTTbar.Divide(histEMTTbar)                         
                
                hCanvas = TCanvas("hCanvas", "Distribution", 800,800)
                
                plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
                style = setTDRStyle()
                plotPad.UseCurrentStyle()               
                plotPad.Draw()  
                plotPad.cd()    
                                        
        
                plotPad.DrawFrame(plot.firstBin,0.8,plot.lastBin,1.8,"; %s ; %s" %(plot.xaxis,"SF/OF"))
                gStyle.SetErrorX(0.5)
                
                
                from ROOT import TH1F,kWhite
                        


                zeroLine = ROOT.TLine(plot.firstBin, 1., plot.lastBin , 1.)
                zeroLine.SetLineWidth(1)
                zeroLine.SetLineColor(ROOT.kBlack)
                zeroLine.SetLineStyle(2)
                zeroLine.Draw("same")
                
                
                if isMC:
                        err = corrections[runRange.era].rSFOFDirect.inclusive.errMC
                else:
                        err = corrections[runRange.era].rSFOFDirect.inclusive.err
                        
                x= array("f",[plot.firstBin, plot.lastBin]) 
                y= array("f", [centralVals["rSFOF"],centralVals["rSFOF"]]) 
                #~ y= array("f", [centralValsTTbar["rSFOF"],centralValsTTbar["rSFOF"]]) 
                ex= array("f", [0.,0.])
                ey= array("f", [err,err])
                                                
                ge= ROOT.TGraphErrors(2, x, y, ex, ey)
                ge.SetFillColor(ROOT.kOrange-9)
                ge.SetFillStyle(1001)
                ge.SetLineColor(ROOT.kWhite)
                ge.Draw("SAME 3")               
                
                rsfofLine= ROOT.TF1("rsfofline","%f"%centralVals["rSFOF"],plot.firstBin,plot.lastBin)
                rsfofLine.SetLineColor(ROOT.kOrange+3)
                rsfofLine.SetLineWidth(3)
                rsfofLine.SetLineStyle(2)
                rsfofLine.Draw("SAME")
                
                rsfofLineTTbar= ROOT.TF1("rsfoflineTTbar","%f"%centralValsTTbar["rSFOF"],plot.firstBin,plot.lastBin)
                rsfofLineTTbar.SetLineColor(ROOT.kGreen-2)
                #~ rsfofLineTTbar.SetLineColor(ROOT.kBlack)
                rsfofLineTTbar.SetLineWidth(3)
                rsfofLineTTbar.SetLineStyle(2)
                rsfofLineTTbar.Draw("SAME")
                
                legendHistDing = TH1F()
                legendHistDing.SetFillColor(kWhite)
                legend = ROOT.TLegend(0.4,0.55,0.92,0.92)
                legend.SetFillStyle(0)
                legend.SetBorderSize(0)                 
                legend.AddEntry(legendHistDing,"%s"%selection.latex,"h")
                #~ if isMC:
                        #~ legend.AddEntry(histRSFOF, "All MC", "p")
                if not isMC:
                        legend.AddEntry(histRSFOF, "Data", "p")
                
                legend.AddEntry(histRSFOFTTbar,"MC (FS)","p")
                #~ if isMC:
                        #~ legend.AddEntry(rsfofLine, "R_{SF/OF} centr. val. contr. region: All MC", "l")
                if not isMC:
                        legend.AddEntry(rsfofLine, "R_{SF/OF} centr. val. contr. region", "l")
                legend.AddEntry(rsfofLineTTbar, "R_{SF/OF} centr. val. contr. region: MC", "l")
                legend.AddEntry(ge,"syst. unc. of R_{SF/OF}","f")
                
                
                
                histRSFOF.SetLineColor(ROOT.kBlack)
                histRSFOF.SetMarkerColor(ROOT.kBlack)
                histRSFOF.SetMarkerStyle(20)
                if not isMC:
                        histRSFOF.Draw("hist E1P SAME")
                
                histRSFOFTTbar.SetMarkerStyle(21)
                histRSFOFTTbar.SetLineColor(ROOT.kGreen-2) 
                histRSFOFTTbar.SetMarkerColor(ROOT.kGreen-2)
                #~ histRSFOFTTbar.SetLineColor(ROOT.kBlack) 
                #~ histRSFOFTTbar.SetMarkerColor(ROOT.kBlack)
                
                histRSFOFTTbar.Draw("hist E1P SAME") 
                
                legend.Draw("same")

                
                latex = ROOT.TLatex()
                latex.SetTextFont(42)
                latex.SetTextAlign(31)
                latex.SetTextSize(0.04)
                latex.SetNDC(True)
                latexLumi = ROOT.TLatex()
                latexLumi.SetTextFont(42)
                latexLumi.SetTextAlign(31)
                latexLumi.SetTextSize(0.04)
                latexLumi.SetNDC(True)
                latexCMS = ROOT.TLatex()
                latexCMS.SetTextFont(61)
                latexCMS.SetTextSize(0.06)
                latexCMS.SetNDC(True)
                latexCMSExtra = ROOT.TLatex()
                latexCMSExtra.SetTextFont(52)
                #latexCMSExtra.SetTextAlign(31)
                latexCMSExtra.SetTextSize(0.045)
                latexCMSExtra.SetNDC(True)      
                latexLumi.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)"%runRange.printval)
                

                latexCMS.DrawLatex(0.19,0.88,"CMS")
                if "Simulation" in cmsExtra and "Private Work" in cmsExtra:
                        yLabelPos = 0.81        
                else:
                        yLabelPos = 0.84        

                latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra)) 


                if fit:
                        fit = TF1("dataFit","pol1",0,300)
                        fit.SetLineColor(ROOT.kBlack)
                        histRSFOF.Fit("dataFit")                
                        
                        latex = ROOT.TLatex()
                        latex.SetTextSize(0.035)        
                        latex.SetNDC()  
                        latex.DrawLatex(0.2, 0.25, "Fit: %.2f #pm %.2f %.5f #pm %.5f * m_{ll}"%(fit.GetParameter(0),fit.GetParError(0),fit.GetParameter(1),fit.GetParError(1)))


                ROOT.gPad.RedrawAxis()
                hCanvas.Update()
                ensurePathExists("fig/%s"%(runRange.label))
                if isMC:
                        hCanvas.Print("fig/%s/rSFOF_%s_%s_%s_%s_MC.pdf"%(runRange.label, selection.name,runRange.label,plot.variablePlotName,plot.additionalName)) 
                else:
                        hCanvas.Print("fig/%s/rSFOF_%s_%s_%s_%s.pdf"%(runRange.label, selection.name,runRange.label,plot.variablePlotName,plot.additionalName))