Пример #1
0
def DrawStackHistograms(histograms, outname, blind=True, verbose=False):

    #hists_sorted = sorted(histograms, key=lambda h: h.Integral())

    hs = THStack("h_stack", "")
    h_obs = None

    l = TLegend(0.77, 0.60, 0.90, 0.87)

    for hist in histograms:

        hname = hist.GetName()

        if "data_obs" in hname:
            if not blind:
                h_obs = hist
                SetHistogramStyle(h_obs, "Observed")
                l.AddEntry(h_obs, "Observed", "p")
        else:
            SetHistogramStyle(hist)
            label = GetLabelName(hist)
            hs.Add(hist)
            l.AddEntry(hist, label, "f")

    h_est = hs.GetStack().Last().Clone()

    if verbose:
        est_err = Double(0.)
        nbins_est = h_est.GetNbinsX()
        est_yields = h_est.IntegralAndError(1, nbins_est, est_err)
        print "predicted yields :", est_yields, "+/-", est_err
        if not blind:
            print "observed yields :", h_obs.Integral()

    # draw

    # SetCMSStyle()   TODO

    canvas = TCanvas()
    gPad.SetLogy()

    #ymax_hs = hs.GetMaximum()
    #ymax = ymax_hs if h_obs is None else max(ymax_hs, h_obs.GetMaximum())
    ymax = 10000
    ymin = 0.1

    hs.SetMaximum(ymax)
    hs.SetMinimum(ymin)
    hs.Draw("HIST")
    l.Draw("same")
    if not blind:
        h_obs.Draw("same")

    canvas.SaveAs(outname)
Пример #2
0
        ntotalbkg = ntotalbkg + numevt
        if bkgsamples[fname]["name"] == "QCD": numqcd = numevt
        if hnames[1] == printHistName:
            string = "%s :  %s = %f \n" % (fname, bkgsamples[fname]["name"],
                                           numevt)
            fNevt.write(string)
            print fname, " : ", bkgsamples[fname][
                "name"], " = ", "{0:.5g}".format(
                    numevt), " scale : ", "{0:.3g}".format(scale)
        #print fname, " : ", scale

        ## Add to Stack
        hs.Add(h_tmp)  #hh_tmp -> add h tmp sig, hs->other
        k = k + 1

    h_bkg = hs.GetStack().Last()
    """
  #Sig Stack 
  hsHct = THStack()

  ntotalHct = 0
  m = 0

  for fname in hctsamples.keys():
    h_Hct = hctsamples[fname]["file"].Get(hctsamples[fname]["hname"][i])
    nbins = h_Hct.GetNbinsX()
    h_Hct.AddBinContent( nbins, h_Hct.GetBinContent( nbins+1 ) ) 
    h_Hct.SetLineColor(hctsamples[fname]["col"])

    ## normalization
    scale = datasamples[datasamples.keys()[mode]]["lumi"]/(hctsamples[fname]["total"]/hctsamples[fname]["xsection"])
Пример #3
0
def createPlots_(plot, compounddetectorname):
    """Cumulative material budget from simulation.
    
       Internal function that will produce a cumulative profile of the
       material budget inferred from the simulation starting from the
       single detectors that compose the tracker. It will iterate over
       all existing detectors contained in the DETECTORS
       dictionary. The function will automatically skip non-existent
       detectors.

    """

    theDirname = "Figures"

    hist_X0_detectors = OrderedDict()
    if plot not in plots.keys():
        print("Error: chosen plot name not known %s" % plot)
        return

    # We need to keep the file content alive for the lifetime of the
    # full function....
    subDetectorFiles = []

    hist_X0_elements = OrderedDict()
    prof_X0_elements = OrderedDict()
    for subDetector, color in DETECTORS.iteritems():
        subDetectorFilename = "matbdg_%s.root" % subDetector
        if not checkFile_(subDetectorFilename):
            print("Error opening file: %s" % subDetectorFilename)
            continue

        subDetectorFiles.append(TFile(subDetectorFilename))
        subDetectorFile = subDetectorFiles[-1]
        print("Opening file: %s" % subDetectorFilename)
        prof_X0_XXX = subDetectorFile.Get("%d" % plots[plot].plotNumber)

        hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionX()

        # category profiles
        for label, [num, color, leg] in hist_label_to_num.iteritems():
            prof_X0_elements[label] = subDetectorFile.Get(
                "%d" % (num + plots[plot].plotNumber))
            hist_X0_elements[label] = assignOrAddIfExists_(
                hist_X0_elements.setdefault(label, None),
                prof_X0_elements[label])

    cumulative_matbdg = TH1D(
        "CumulativeSimulMatBdg", "CumulativeSimulMatBdg",
        hist_X0_detectors["BeamPipe"].GetNbinsX(),
        hist_X0_detectors["BeamPipe"].GetXaxis().GetXmin(),
        hist_X0_detectors["BeamPipe"].GetXaxis().GetXmax())
    cumulative_matbdg.SetDirectory(0)

    # colors
    for det, color in DETECTORS.iteritems():
        setColorIfExists_(hist_X0_detectors, det, color)

    for label, [num, color, leg] in hist_label_to_num.iteritems():
        hist_X0_elements[label].SetFillColor(color)

    # First Plot: BeamPipe + Tracker + ECAL + HCal + HGCal + MB + MGNT
    # stack
    stackTitle_SubDetectors = "Material Budget;%s;%s" % (plots[plot].abscissa,
                                                         plots[plot].ordinate)
    stack_X0_SubDetectors = THStack("stack_X0", stackTitle_SubDetectors)
    for det, histo in hist_X0_detectors.iteritems():
        stack_X0_SubDetectors.Add(histo)
        cumulative_matbdg.Add(histo, 1)

    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors", 800,
                               800)
    #can_SubDetectors.Range(0,0,25,25)
    can_SubDetectors.SetFillColor(kWhite)

    # Draw
    stack_X0_SubDetectors.SetMinimum(plots[plot].ymin)
    stack_X0_SubDetectors.SetMaximum(plots[plot].ymax)
    stack_X0_SubDetectors.Draw("HIST")
    #stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax)

    # Legenda
    theLegend_SubDetectors = TLegend(0.130, 0.7, 0.93,
                                     0.90)  #(0.180,0.8,0.98,0.90)
    theLegend_SubDetectors.SetNColumns(2)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in hist_X0_detectors.iteritems():
        theLegend_SubDetectors.AddEntry(histo, det, "f")

    theLegend_SubDetectors.Draw()

    # text
    text_SubDetectors = TPaveText(0.130, 0.627, 0.352, 0.687,
                                  "NDC")  #(0.180,0.727,0.402,0.787,"NDC")
    text_SubDetectors.SetFillColor(0)
    text_SubDetectors.SetBorderSize(0)
    text_SubDetectors.AddText("CMS Simulation")
    text_SubDetectors.SetTextAlign(11)
    text_SubDetectors.Draw()

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.pdf" %
                            (theDirname, compounddetectorname, plot))
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.png" %
                            (theDirname, compounddetectorname, plot))
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.root" %
                            (theDirname, compounddetectorname, plot))

    if plot == "x_vs_eta" or plot == "l_vs_eta":
        canname = "MBCan_1D_%s_%s_total" % (compounddetectorname, plot)
        can2 = TCanvas(canname, canname, 800, 800)
        can2.Range(0, 0, 25, 25)
        can2.SetFillColor(kWhite)
        gStyle.SetOptStat(0)
        gStyle.SetOptTitle(0)
        #title = TPaveLabel(.11,.95,.35,.99,"Total accumulated material budget","brndc")
        stack_X0_SubDetectors.GetStack().Last().SetMarkerStyle(34)
        stack_X0_SubDetectors.GetStack().Last().GetXaxis().SetRangeUser(
            1.0, 3.5)
        stack_X0_SubDetectors.GetStack().Last().Draw()
        stack_X0_SubDetectors.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zplus.pdf" %
                    (theDirname, compounddetectorname, plot))
        can2.SaveAs("%s/%s_%s_total_Zplus.png" %
                    (theDirname, compounddetectorname, plot))
        stack_X0_SubDetectors.GetStack().Last().GetXaxis().SetRangeUser(
            -3.5, -1.0)
        stack_X0_SubDetectors.GetStack().Last().Draw()
        stack_X0_SubDetectors.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zminus.pdf" %
                    (theDirname, compounddetectorname, plot))
        can2.SaveAs("%s/%s_%s_total_Zminus.png" %
                    (theDirname, compounddetectorname, plot))

        #Also print them to give them exact numbers
        etavalues = []
        matbudginX0 = []
        matbudginIntLen = []
        for binx in range(
                0,
                stack_X0_SubDetectors.GetStack().Last().GetXaxis().GetNbins()):
            bincontent = stack_X0_SubDetectors.GetStack().Last().GetBinContent(
                binx)
            if bincontent == 0: continue
            etavalues.append(
                stack_X0_SubDetectors.GetStack().Last().GetBinCenter(binx))
            if plot == "x_vs_eta":
                matbudginX0.append(bincontent)
                d1 = {'Eta': etavalues, 'MatBudInX0': matbudginX0}
                df1 = pd.DataFrame(data=d1).round(2)
                df1.to_csv(
                    r'/afs/cern.ch/work/a/apsallid/CMS/PFCalStudies/CMS-HGCAL/matbudV10fromVertexToBackofHGCal/CMSSW_11_0_X_2019-06-04-2300/src/Validation/Geometry/test/EtavsMatBudinXo.txt',
                    sep=' ',
                    index=False,
                    header=False)
                #print df1
            if plot == "l_vs_eta":
                matbudginIntLen.append(bincontent)
                d2 = {'Eta': etavalues, 'MatBudInIntLen': matbudginIntLen}
                df2 = pd.DataFrame(data=d2).round(2)
                df2.to_csv(
                    r'/afs/cern.ch/work/a/apsallid/CMS/PFCalStudies/CMS-HGCAL/matbudV10fromVertexToBackofHGCal/CMSSW_11_0_X_2019-06-04-2300/src/Validation/Geometry/test/EtavsMatBudInIntLen.txt',
                    sep=' ',
                    index=False,
                    header=False)
                #print df2

    return cumulative_matbdg
Пример #4
0
def createCompoundPlots(detector, plot):
    """Produce the requested plot for the specified detector.

       Function that will plot the requested @plot for the specified
       @detector. The specified detector could either be a real
       detector or a compound one. The list of available plots are the
       keys of plots dictionary (imported from plot_utils.

    """

    theDirname = 'Images'
    if not checkFile_(theDirname):
        os.mkdir(theDirname)

    goodToGo, theDetectorFilename = paramsGood_(detector, plot)
    if not goodToGo:
        return

    theDetectorFile = TFile(theDetectorFilename)
    #

    # get TProfiles
    prof_X0_elements = OrderedDict()
    hist_X0_elements = OrderedDict()
    for label, [num, color, leg] in hist_label_to_num.iteritems():
        #print label, num, color, leg
        prof_X0_elements[label] = theDetectorFile.Get(
            "%d" % (num + plots[plot].plotNumber))
        hist_X0_elements[label] = prof_X0_elements[label].ProjectionX()
        hist_X0_elements[label].SetFillColor(color)
        hist_X0_elements[label].SetLineColor(kBlack)

    files = []
    if detector in COMPOUNDS.keys():
        for subDetector in COMPOUNDS[detector][1:]:
            subDetectorFilename = "matbdg_%s.root" % subDetector

            # open file
            if not checkFile_(subDetectorFilename):
                continue

            subDetectorFile = TFile(subDetectorFilename)
            files.append(subDetectorFile)
            print("*** Open file... %s" % subDetectorFilename)

            # subdetector profiles
            for label, [num, color, leg] in hist_label_to_num.iteritems():
                prof_X0_elements[label] = subDetectorFile.Get(
                    "%d" % (num + plots[plot].plotNumber))
                hist_X0_elements[label].Add(
                    prof_X0_elements[label].ProjectionX(
                        "B_%s" % prof_X0_elements[label].GetName()), +1.000)

    # stack
    stackTitle = "Material Budget %s;%s;%s" % (detector, plots[plot].abscissa,
                                               plots[plot].ordinate)
    stack_X0 = THStack("stack_X0", stackTitle)
    for label, [num, color, leg] in hist_label_to_num.iteritems():
        stack_X0.Add(hist_X0_elements[label])

    # canvas
    canname = "MBCan_1D_%s_%s" % (detector, plot)
    can = TCanvas(canname, canname, 800, 800)
    can.Range(0, 0, 25, 25)
    can.SetFillColor(kWhite)
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(1)

    # Draw
    stack_X0.Draw("HIST")
    stack_X0.GetYaxis().SetTitleOffset(1.15)

    # Legenda
    theLegend = TLegend(0.40, 0.65, 0.60, 0.89)
    if plot == "x_vs_phi" or plot == "l_vs_phi":
        theLegend = TLegend(0.65, 0.30, 0.89, 0.70)
    if plot == "x_vs_R" or plot == "l_vs_R":
        theLegend = TLegend(0.75, 0.60, 0.95, 0.90)

    for label, [num, color, leg] in hist_label_to_num.iteritems():
        theLegend.AddEntry(hist_X0_elements[label], leg, "f")
    theLegend.Draw()

    # Store
    can.Update()
    can.SaveAs("%s/%s_%s.pdf" % (theDirname, detector, plot))
    can.SaveAs("%s/%s_%s.png" % (theDirname, detector, plot))

    #Let's also save the total accumulated budget vs eta since muon id relies
    #on adequate calorimeter thickness
    if plot == "x_vs_eta" or plot == "l_vs_eta":
        canname = "MBCan_1D_%s_%s_total" % (detector, plot)
        can2 = TCanvas(canname, canname, 800, 800)
        can2.Range(0, 0, 25, 25)
        can2.SetFillColor(kWhite)
        gStyle.SetOptStat(0)
        gStyle.SetOptTitle(0)
        #title = TPaveLabel(.11,.95,.35,.99,"Total accumulated material budget","brndc")
        stack_X0.GetStack().Last().GetXaxis().SetRangeUser(0., 3.)
        stack_X0.GetStack().Last().Draw()
        stack_X0.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zplus.pdf" % (theDirname, detector, plot))
        can2.SaveAs("%s/%s_%s_total_Zplus.png" % (theDirname, detector, plot))
        stack_X0.GetStack().Last().GetXaxis().SetRangeUser(-3., 0.)
        stack_X0.GetStack().Last().Draw()
        stack_X0.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zminus.pdf" % (theDirname, detector, plot))
        can2.SaveAs("%s/%s_%s_total_Zminus.png" % (theDirname, detector, plot))
    rebinnedHist[ih].Write()

rebinnedData.Write()
# forget about plotting right now. Just make a template.

## purpose for plotting
rebinnedData.Scale(1., "width")

stack = THStack()
print rebinnedHist.keys()
for ih in rebinnedHist:
    rebinnedHist[ih].Scale(1., "width")
    stack.Add(rebinnedHist[ih])

if postfitPlots:
    MC = stack.GetStack().Last().Clone("MC")
    x = rebinnedData.Chi2Test(MC, "UW CHI2/NDF")
    chi2Text = "#chi^{2}/NDF=%.2f" % x

canvasRatio = TCanvas('c1Ratio', 'c1Ratio', W, H)
canvasRatio.SetFillColor(0)
canvasRatio.SetBorderMode(0)
canvasRatio.SetFrameFillStyle(0)
canvasRatio.SetFrameBorderMode(0)
canvasRatio.SetLeftMargin(L / W)
canvasRatio.SetRightMargin(R / W)
canvasRatio.SetTopMargin(T / H)
canvasRatio.SetBottomMargin(B / H)
canvasRatio.SetTickx(0)
canvasRatio.SetTicky(0)
canvasRatio.Draw()
Пример #6
0
def createCompoundPlots(detector, plot, geometry):
    """Produce the requested plot for the specified detector.

       Function that will plot the requested @plot for the specified
       @detector. The specified detector could either be a real
       detector or a compound one. The list of available plots are the
       keys of plots dictionary (imported from plot_utils.

    """
    setTDRStyle()
    
    theDirname = 'Images'
    if not checkFile_(theDirname):
        os.mkdir(theDirname)

    goodToGo, theDetectorFilename = paramsGood_(detector, plot, geometry)
    if not goodToGo:
        return

    hist_X0_elements = OrderedDict()

    # stack
    stackTitle = "%s;%s;%s" % (detector,
                                               plots[plot].abscissa,
                                               plots[plot].ordinate)
    stack_X0 = THStack("stack_X0", stackTitle);
    theLegend = TLegend(0.50, 0.70, 0.70, 0.90);

    def setRanges(h):
        legendSpace = 1. + 0.3 # 30%
        minY = h.GetYaxis().GetXmin()
        maxY = h.GetBinContent(h.GetMaximumBin()) * legendSpace
        h.GetYaxis().SetRangeUser(minY, maxY)

    for label, [num, color, leg] in six.iteritems(hist_label_to_num):
        # We don't want the sum to be added as part of the stack
        if label is 'SUM':
            continue
        hist_X0_elements[label] = get1DHisto_(detector,
                                              num + plots[plot].plotNumber,
                                              geometry)
        hist_X0_elements[label].SetFillColor(color)
        hist_X0_elements[label].SetLineColor(kBlack)
        stack_X0.Add(hist_X0_elements[label])
        if hist_X0_elements[label].Integral() > 0.: theLegend.AddEntry(hist_X0_elements[label], leg, "f")

    # canvas
    canname = "MBCan_1D_%s_%s"  % (detector, plot)
    can = TCanvas(canname, canname, 800, 800)
    can.Range(0,0,25,25)
    gStyle.SetOptTitle(0)

    # Draw
    setRanges(stack_X0.GetStack().Last())
    stack_X0.Draw("HIST");
    stack_X0.GetXaxis().SetLabelSize(0.035)
    stack_X0.GetYaxis().SetLabelSize(0.035)
    theLegend.Draw();

    cmsMark = TLatex()
    cmsMark.SetNDC();
    cmsMark.SetTextAngle(0);
    cmsMark.SetTextColor(kBlack);    
    cmsMark.SetTextFont(61)
    cmsMark.SetTextSize(5e-2)
    cmsMark.SetTextAlign(11)
    cmsMark.DrawLatex(0.16,0.86,"CMS")

    simuMark = TLatex()
    simuMark.SetNDC();
    simuMark.SetTextAngle(0);
    simuMark.SetTextColor(kBlack);    
    simuMark.SetTextSize(3e-2)
    simuMark.SetTextAlign(11)
    simuMark.DrawLatex(0.16,0.82,"#font[52]{Simulation Internal}")
 
    # Store
    can.Update();
    can.SaveAs( "%s/%s_%s_%s.pdf" 
                % (theDirname, detector, plot, geometry))
    can.SaveAs( "%s/%s_%s_%s.png" 
                % (theDirname, detector, plot, geometry))
Пример #7
0
    bdt_data.Draw('P SAME')
    bdt_sig.SetFillStyle(0)
    bdt_sig.Draw('HIST SAME E')
    if gen:
        bdt_sig_gen.SetFillStyle(0)
        bdt_sig_gen.Draw('HIST SAME E')
    bdt_data.Draw("axis same")
    l.Draw("same")
    label.Draw("same")
    pad2.cd()
    r_bdt_data = bdt_data.Clone("r_bdt_data")
    r_bdt_data.SetLineColor(1)
    r_bdt_data.SetMarkerStyle(20)
    r_bdt_data.SetMarkerSize(0.5)
    r_bdt_data.SetTitle("")
    r_bdt_data.Divide(hs_bdt_bkg.GetStack().Last())
    y = r_bdt_data.GetYaxis()
    y.SetTitle("Data/MC")
    y.SetNdivisions(505)
    y.SetTitleSize(0.11)
    y.SetRangeUser(0.6, 1.4)
    y.SetTitleOffset(0.35)
    y.SetLabelSize(0.1)
    x = r_bdt_data.GetXaxis()
    x.SetTitleSize(0.11)
    x.SetTitleOffset(1.0)
    x.SetLabelSize(0.1)
    r_bdt_data.Draw("EP")
    c1.Print('histo_' + tmva_version + '_' + ch + '_bdt.pdf')

    ################################################
Пример #8
0
        if bkgsamples[fname]["name"] == "QCD": numqcd = numevt
        if hnames[1] == printHistName:
            string = "%s :  %s = %f \n" % (fname, bkgsamples[fname]["name"],
                                           numevt)
            fNevt.write(string)
            print fname, " : ", bkgsamples[fname][
                "name"], " = ", "{0:.5g}".format(
                    numevt)  # " scale : " ,"{0:.1g}".format(scale)

        #print fname, " : ", scale

        ## Add to Stack
        hs.Add(h_tmp)  #hh_tmp -> add h tmp sig, hs->other
        k = k + 1

    h_bkg = hs.GetStack().Last()

    #Sig Stack
    hsHct = THStack()

    ntotalHct = 0
    m = 0

    for fname in hctsamples.keys():
        h_Hct = hctsamples[fname]["file"].Get(hctsamples[fname]["hname"][i])
        nbins = h_Hct.GetNbinsX()
        h_Hct.AddBinContent(nbins, h_Hct.GetBinContent(nbins + 1))
        h_Hct.SetLineColor(hctsamples[fname]["col"])

        ## normalization
        scale = datasamples[datasamples.keys()[mode]]["lumi"] / (
Пример #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_)
Пример #10
0
hist1 = TH1D("hist1", "hist1", 10, 0, 100)
hist2 = TH1D("hist2", "hist2", 10, 0, 100)
hist1.Sumw2()
hist2.Sumw2()
stack = THStack("stack", "stack")

for i in xrange(1000):
    weight1 = gRandom.Gaus(1, 0.1)
    weight2 = gRandom.Gaus(1, 0.2)
    hist1.Fill(gRandom.Gaus(55, 20), weight1)
    hist2.Fill(gRandom.Gaus(50, 25), weight2)

stack.Add(hist1)
stack.Add(hist2)

hist_stack = stack.GetStack().Last()
print "\n>>> hist_stack = stack.GetStack().Last()"
print ">>>   hist_stack = %s" % hist_stack
print ">>>   type(hist_stack) = %s" % type(hist_stack)
print ">>>   hist_stack.GetName() = %s" % hist_stack.GetName()
print ">>>   hist_stack.GetTitle() = %s" % hist_stack.GetTitle()

print "\n>>> comparing integrals"
print ">>>   stack = %s" % hist_stack.Integral()
print ">>>   hist1 = %s" % hist1.Integral()
print ">>>   hist2 = %s" % hist2.Integral()

print "\n>>> comparing entries"
print ">>>   stack = %s" % hist_stack.GetEntries()
print ">>>   hist1 = %s" % hist1.GetEntries()
print ">>>   hist2 = %s" % hist2.GetEntries()
Пример #11
0
class Histogram:
    def __init__(self, Samples, directory):
        self.PropName = directory.GetName()

        dircontents = directory.GetListOfKeys()
        firsthisto = directory.Get(dircontents.At(0).GetName())
        #firsthisto.Print("ALL")
        self.ForLegend = {}
        self.XSections = {}
        self.AllSampleHistos = {}

        for sample in Samples:
            if sample.IsData:
                self.DataSName = sample.HistoCat

            # h_in_dir = directory.Get( "%s_%s" % ( self.PropName , sample.Name ) )
            # if h_in_dir :
            #     h_in_dir.reset()
            #     setattr( self , sample.Name , h_in_dir )
            # else:
            gROOT.cd()
            hnew = firsthisto.Clone("%s_%s" % (self.PropName, sample.Name))
            hnew.Reset()
            setattr(self, sample.Name, hnew)

            hhh = getattr(self, sample.Name)
            hhh.SetLineColor(1)
            hhh.SetLineWidth(2)
            if not sample.IsData:
                hhh.SetFillColor(sample.Color)
                hhh.SetFillStyle(1001)
            else:
                hhh.SetStats(0)

            self.AllSampleHistos[sample.Name] = hhh

            if (self.ForLegend.get(sample.HistoCat)):
                self.ForLegend[sample.HistoCat].append(sample.Name)
            else:
                self.ForLegend[sample.HistoCat] = [sample.Name]

            self.XSections[sample.Name] = sample.XSection

    def AddFile(self, directory, catname=""):
        ##find all relevant histograms in the file and add them to your histos
        for sample in self.AllSampleHistos:
            h_name = ""
            if catname == "":
                h_name = "%s/%s_%s" % (self.PropName, self.PropName, sample)
            else:
                h_name = "%s/%s_%s_%s" % (self.PropName, catname,
                                          self.PropName, sample)
            h_in_dir = directory.Get(h_name)
            if h_in_dir:
                # print h_name
                # print directory.GetPath()
                # h_in_dir.Print("ALL")
                self.AllSampleHistos[sample].Add(h_in_dir)

    def Write(self, fout):
        fout.mkdir(self.PropName).cd()
        for sample in self.AllSampleHistos:
            self.AllSampleHistos[sample].Write()
        if hasattr(self, "Canvas"):
            self.Canvas.Write()
            for leg in self.FinalHistos:
                self.FinalHistos[leg].Write()
            self.Stack.GetStack().Last().Write("SumMC")
        fout.cd()

    @staticmethod
    def AddLabels(histo, labels):
        if labels:
            for i in range(1, histo.GetNbinsX() + 1):
                if not i > len(labels):
                    histo.GetXaxis().SetBinLabel(i, labels[i - 1])

    def Draw(self, lumi, cft, labels=None, catname=""):
        gStyle.SetOptTitle(0)
        self.FinalHistos = {}
        for sample in self.AllSampleHistos:
            Histogram.AddLabels(self.AllSampleHistos[sample], labels)
            self.AllSampleHistos[sample].SetBit(TH1.kNoTitle)
            if sample in self.ForLegend[self.DataSName]:
                continue
            ntotal = getattr(cft, sample).GetBinContent(1)
            if ntotal == 0:
                print "Sample %s has no entries" % (sample)
                continue
            factor = lumi * self.XSections[sample] / ntotal
            #print "%s factor : (%.2f*%.2f)/%.0f = %.3f" % (sample , lumi , self.XSections[sample] , ntotal  , factor)
            self.AllSampleHistos[sample].Scale(factor)

        self.Stack = THStack("%s_stack" % (self.PropName), self.PropName)
        #Histogram.AddLabels( self.Stack.GetHistogram() , labels )
        for finalh in self.ForLegend:
            for hname in self.ForLegend[finalh]:
                #print "Adding %s to %s" % ( hname , finalh )
                if self.FinalHistos.get(finalh):
                    self.FinalHistos[finalh].Add(self.AllSampleHistos[hname])
                else:
                    self.FinalHistos[finalh] = self.AllSampleHistos[
                        hname].Clone("_%s_%s" % (self.PropName, finalh))
                    Histogram.AddLabels(self.FinalHistos[finalh], labels)
                    self.FinalHistos[finalh].SetBit(TH1.kNoTitle)
                    #self.FinalHistos[finalh].SetLineColor( 0 )
                    self.FinalHistos[finalh].SetTitle(finalh)

            if finalh == self.DataSName:
                self.DataHisto = self.FinalHistos[finalh]
            else:
                self.Stack.Add(self.FinalHistos[finalh])

        self.Canvas = TCanvas("%s_%s_C" % (self.PropName, catname))
        self.Pad1 = TPad("pad1", "pad1", 0, 0.25, 1, 1)
        self.Pad1.SetBottomMargin(0.1)
        self.Pad1.Draw()
        self.Pad1.cd()

        self.DataHisto.Draw("E")
        #getattr( self , self.DataSName ).Draw("E")
        self.Stack.Draw("HIST SAME")
        self.DataHisto.Draw("E SAME P")
        #getattr( self , self.DataSName ).Draw("E SAME")

        self.Legend = TLegend(0.7, 0.6, 0.9, 0.9, "", "brNDC")
        entry = self.Legend.AddEntry(self.DataHisto, "Data", "lp")
        for finalh in reversed(self.ForLegend.keys()):
            if finalh == self.DataSName:
                continue
            self.Legend.AddEntry(self.FinalHistos[finalh], finalh, "f")
        self.Legend.Draw()

        self.Canvas.cd()
        self.Pad2 = TPad("pad2", "pad2", 0, 0, 1, 0.24)
        self.Pad2.SetTopMargin(0.1)
        self.Pad2.SetBottomMargin(0.1)
        self.Pad2.Draw()
        self.Pad2.cd()

        self.Ratio = self.DataHisto.Clone("Ratio_%s" % (self.PropName))
        self.Ratio.SetStats(0)
        self.Ratio.Divide(self.Stack.GetStack().Last())
        if labels:
            Histogram.AddLabels(self.Ratio, ["" for s in labels])
        self.Ratio.SetMarkerStyle(20)
        self.Ratio.GetYaxis().SetRangeUser(0, 2)
        self.Ratio.GetXaxis().SetLabelSize(0.)
        self.Ratio.GetYaxis().SetTitle("Data / MC")
        #self.Ratio.GetXaxis().SetTitle(xtitle)
        self.Ratio.GetXaxis().SetTitleSize(0.2)
        self.Ratio.GetXaxis().SetTitleOffset(0.25)
        self.Ratio.GetYaxis().SetLabelSize(0.1)
        self.Ratio.GetXaxis().SetTickLength(0.09)
        self.Ratio.GetYaxis().SetTitleSize(0.18)
        self.Ratio.GetYaxis().SetNdivisions(509)
        self.Ratio.GetYaxis().SetTitleOffset(0.25)
        self.Ratio.SetFillStyle(3001)
        self.Ratio.Draw("ep")

        self.LineOne = TLine(self.Ratio.GetXaxis().GetXmin(), 1.00,
                             self.Ratio.GetXaxis().GetXmax(), 1.00)
        self.LineOne.SetLineWidth(2)
        self.LineOne.SetLineStyle(7)
        self.LineOne.Draw()
Пример #12
0
        rawevt = h_tmp.GetEntries()
        ntotalbkg = ntotalbkg + numevt
        if hnames[1] == printHistName or 'DNN' in hnames[1]:
            string_nevt += "%f \n" % (numevt)
            string_fname += "%s :  %s = %f \n" % (
                fname, bkgsamples[fname]["name"], numevt)
            print fname, " : ", bkgsamples[fname][
                "name"], " = ", "{0:.5g}".format(
                    numevt), " scale : ", "{0:.3g}".format(scale)
        if printscale: print scale

        ## Add to Stack
        hs.Add(h_tmp)  #hh_tmp -> add h tmp sig, hs->other
        k = k + 1

    h_bkg = hs.GetStack().Last()

    #Sig Stack
    #Add Hut
    hsHut = THStack()
    ntotalHut = 0
    n = 0

    for fname in hutsamples.keys():
        h_Hut = hutsamples[fname]["file"].Get(
            datasamples[datasamples.keys()[0]]["hname"][i])
        nbins = h_Hut.GetNbinsX()
        h_Hut.AddBinContent(nbins, h_Hut.GetBinContent(nbins + 1))
        h_Hut.SetLineColor(hutsamples[fname]["col"])

        ## normalization
Пример #13
0
def drawHisto(histlist,histoD,xTitle,yTitle,outName,uncHists=""):    
    legend = TLegend(0.35, 0.72, 0.85, 0.92,"") #,"brNDC"
    legend.SetFillStyle(0)

    legend.SetTextSize(0.045)
    legend.SetNColumns(2)

    myStack = THStack("myStack","")
    for hist in histlist:
        myStack.Add(hist,"hist")
    
    histoErr = histlist[0].Clone()
    for iHist in range(1,len(histlist)):
        histoErr.Add(histlist[iHist])
        
    MCCount = myStack.GetStack().Last().Integral()
    DataCount = histoD.Integral()
    MCNormFactor = DataCount/MCCount

#    myStack.Delete()
    myStack = THStack("myStack","")

    for hist in histlist:
        hist.Scale(MCNormFactor)
        myStack.Add(hist,"hist")
        

    histoErr.Scale(MCNormFactor)
    

    if uncHists!="":
        MCMean = myStack.GetStack().Last().Clone()
        MCErr = MCMean.Clone()
        MCErr.Reset()
        for ibin in range(1,MCMean.GetNbinsX()+1):
            thisbinunc = 0
            for ihist in uncHists:
                thisbinunc += ihist.GetBinContent(ibin)**2     #sum assuming correlated
            sfunc = thisbinunc**0.5*MCNormFactor
            if args.nostat:
                MCMean.SetBinError(ibin, sfunc)
                MCErr.SetBinContent(ibin, sfunc)
            else:
                MCMean.SetBinError(ibin, math.sqrt(sfunc**2 + histoErr.GetBinError(ibin)**2))
                MCErr.SetBinContent(ibin, math.sqrt(sfunc**2 + histoErr.GetBinError(ibin)**2))
        
    c = TCanvas("main","main",1200,1200)
    c.SetCanvasSize(1200,1200)
    
    upperCanvas = TPad("up","up",0,0.24,1,1)
    upperCanvas.SetBottomMargin(0.03)
    upperCanvas.SetLeftMargin(0.12)
    upperCanvas.SetTopMargin(0.06)
#    upperCanvas.SetLogy(isLog)
    upperCanvas.Draw()
    upperCanvas.cd()
    
    myStack.Draw()
    myStack.GetYaxis().SetTitle(yTitle)
    myStack.GetHistogram().GetZaxis().SetTitle()

    myStack.GetYaxis().SetLabelSize(0.048)
    myStack.GetYaxis().SetTitleSize(0.07)
    myStack.GetYaxis().SetTitleOffset(0.78)
    myStack.GetYaxis().SetTitleFont(42)
    legend.Draw("same")

    if uncHists!="":
        MCMean.Draw("e2 same")
        MCMean.SetFillColor(kGreen)
        MCMean.SetLineColor(kGreen)
        MCMean.SetMarkerSize(0)
        MCMean.SetFillStyle(3013)
        
    if not args.nostat:
        histoErr.Draw("e2 same")
        # histoErr.Sumw2()
        histoErr.SetFillColor(kGray+3)
        histoErr.SetLineColor(kGray+3)
        histoErr.SetMarkerSize(0)
        histoErr.SetFillStyle(3013)       

    histoMC = myStack.GetStack().Last()
    histoBkg= myStack.GetStack().Before(histoMC)

    print "Total MC:", histoMC.Integral(), ", Data:",histoD.Integral()


    histoD.Draw("same p e")
    legend.AddEntry(histoD,"Data","PE")
    
    for hist in histlist:
        legend.AddEntry(hist,hist.GetName().replace('uds','udsg').replace('b','bottom').replace('c','charm'),'f')
    legend.AddEntry(histoErr,"MC Stat. Unc.",'f')
    if uncHists!="": legend.AddEntry(MCMean,"SF Unc.",'f')
    maxY = histoD.GetMaximum()
    
    #if myStack.GetMinimum() >= 0:
    myStack.SetMinimum(1e-3)
    myStack.SetMaximum(maxY*1.35)


    c.cd()
    lowerCanvas = TPad("down","down",0,0,1,0.26)
    lowerCanvas.Draw()
    lowerCanvas.cd()
    lowerCanvas.SetTicky(1)
    lowerCanvas.SetLeftMargin(0.1)
    lowerCanvas.SetRightMargin(0.1)
    lowerCanvas.SetTopMargin(0.0)
    lowerCanvas.SetBottomMargin(0.4)
    lowerCanvas.SetLeftMargin(0.12)
    lowerCanvas.SetFrameFillStyle(0)
    lowerCanvas.SetFrameBorderMode(0)
    lowerCanvas.SetGridy()

    histoRatio = histoD.Clone()
    histoRatio.Divide(histoMC)
    for ib in range(1,histoRatio.GetNbinsX()+1):
        if histoD.GetBinContent(ib) != 0:
            histoRatio.SetBinError(ib, histoD.GetBinError(ib)/histoD.GetBinContent(ib)*histoRatio.GetBinContent(ib))
        else:
            histoRatio.SetBinError(ib,0.)

    histoRatio.GetYaxis().SetTitle("Data/MC")
    histoRatio.GetYaxis().SetTitleSize(0.15)
    histoRatio.GetYaxis().SetTitleOffset(0.38)
    histoRatio.GetYaxis().SetTitleFont(42)
    histoRatio.GetYaxis().SetLabelSize(0.14)
    histoRatio.GetYaxis().CenterTitle()
    histoRatio.GetYaxis().SetLabelFont(42)
    histoRatio.GetYaxis().SetNdivisions(5)

    histoRatio.GetXaxis().SetTitle(xTitle)
    histoRatio.GetXaxis().SetLabelSize(0.14)
    histoRatio.GetXaxis().SetTitleSize(0.19)
    histoRatio.GetXaxis().SetTitleOffset(0.88)
    histoRatio.GetXaxis().SetTitleFont(42)
    histoRatio.GetXaxis().SetTickLength(0.07)
    histoRatio.GetXaxis().SetLabelFont(42)
    histoRatio.SetTitle("")

    histoRatio.Draw("P e")
    histoRatio.SetMaximum(1.49)
    histoRatio.SetMinimum(0.51)

    if uncHists!="":
        RatioErr = MCErr.Clone()
        RatioErr.Divide(histoMC)
        RatioErrVals = RatioErr.Clone()
        for ibin in range(1,RatioErr.GetNbinsX()+1):
            RatioErrVals.SetBinContent(ibin,1.)
            RatioErrVals.SetBinError(ibin,RatioErr.GetBinContent(ibin))

        RatioErrVals.Draw("e2 same")
        RatioErrVals.SetFillColor(kGreen)
        RatioErrVals.SetLineColor(kGreen)
        RatioErrVals.SetMarkerSize(0)
        RatioErrVals.SetFillStyle(3013)

    if not args.nostat:
        RatioStatUnc = histoMC.Clone()
        for ibin in range(1,RatioStatUnc.GetNbinsX()+1):
            RatioStatUnc.SetBinContent(ibin,1)
            if histoMC.GetBinContent(ibin) != 0:
                RatioStatUnc.SetBinError(ibin,histoMC.GetBinError(ibin)/histoMC.GetBinContent(ibin))
            else:
                RatioStatUnc.SetBinError(ibin,0)

        RatioStatUnc.Draw("e2 same")
        RatioStatUnc.SetFillColor(kGray+3)
        RatioStatUnc.SetLineColor(kGray+3)
        RatioStatUnc.SetMarkerSize(0)
        RatioStatUnc.SetFillStyle(3013) 
    
    histoRatio.Draw("P e same")  # To bring on top

    hLine = TLine(-0.2,1,1,1)
    hLine.SetLineColor(kRed)
    hLine.Draw()

#    if drawDataMCRatioLine:
#        MCCount = histoMC.Integral()
#        if MCCount > 0.:
#            DataCount = histoD.Integral()
#            MCNormFactor = DataCount/MCCount
#            hLine2 = TLine(start,MCNormFactor,end,MCNormFactor)
#            hLine2.SetLineColor(kBlue)
#            hLine2.Draw()

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

    # ======================== LaTeX ==========================
    texTL = TLatex()
    texTL.SetTextSize(0.07)
    texTL.SetTextAlign(13)

    texTR = TLatex()
    texTR.SetTextSize(0.05)
    texTR.SetTextAlign(31)

#    if dataset=="" or noRatio:
#        texTL.DrawLatexNDC(0.13,0.87, "CMS #it{#bf{Preliminary}}")
#        texTR.DrawLatexNDC(0.89,0.91, "#bf{"+str(lumi/1000.)+" fb^{-1} (13 TeV)}")
#    else:
    upperCanvas.cd()
    
    texTL.DrawLatexNDC(0.16,0.92, "CMS") # #it{#bf{Preliminary}}")
    if args.prelim:
        texTL2 = TLatex()
        texTL2.SetTextSize(0.05)
        texTL2.SetTextAlign(13)
        suff = "#it{#bf{Preliminary}}"
        texTL2.DrawLatexNDC(0.16,0.85, suff)

    texTR.DrawLatexNDC(0.89,0.95, "#bf{"+str(lumi/1000.)+" fb^{-1} (13 TeV)}")
    # ----------------------------------------------------------

    c.SaveAs(outName+".pdf")
    c.SaveAs(outName+".png")