Ejemplo n.º 1
0
def draw(hist,
         fit,
         channel,
         data,
         back,
         sign,
         snorm=1,
         lumi=-1,
         ratio=0,
         log=False):
    # If not present, create BkgSum
    if not 'BkgSum' in hist.keys():
        hist['BkgSum'] = hist['data_obs'].Clone(
            "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
        hist['BkgSum'].Reset("MICES")
        for i, s in enumerate(back):
            hist['BkgSum'].Add(hist[s])
    hist['BkgSum'].SetMarkerStyle(0)

    setHistStyle(hist['BkgSum'], 1.1 if ratio else 1.0)
    # Create stack
    bkg = THStack(
        "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";" +
        hist['BkgSum'].GetYaxis().GetTitle())
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    n = len([x for x in data + back + ['BkgSum'] + sign if sample[x]['plot']])
    leg = TLegend(0.69, 0.86 - 0.04 * n, 0.95, 0.86)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pl")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            leg.AddEntry(hist[s],
                         sample[s]['label'].replace("m_{#Chi}=1 GeV",
                                                    ""), "fl")

    ### data/bkg ratio and systematics
    err = hist['BkgSum'].Clone("BkgErr;")
    err.SetTitle("")
    err.GetYaxis().SetTitle("data / bkg")
    if fit == "prefit":
        err.SetFillColor(ROOT.kOrange - 2)
    elif fit == "postfit":
        err.SetFillColor(ROOT.kBlue)
    err.SetFillStyle(3001)
    for i in range(1, err.GetNbinsX() + 1):
        err.SetBinContent(i, 1)
        if hist['BkgSum'].GetBinContent(i) > 0:
            err.SetBinError(
                i, hist['BkgSum'].GetBinError(i) /
                hist['BkgSum'].GetBinContent(i))
    errLine = err.Clone("errLine")
    errLine.SetLineWidth(1)
    errLine.SetFillStyle(0)
    res = hist['data_obs'].Clone("residues")
    for i in range(0, res.GetNbinsX() + 1):
        if hist['BkgSum'].GetBinContent(i) > 0:
            res.SetBinContent(
                i,
                res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
            res.SetBinError(
                i,
                res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))

    # Legend
    leg1 = TLegend(0.12, 0.45, 0.25, 0.5)
    leg1.SetBorderSize(0)
    leg1.SetFillStyle(0)
    leg1.SetFillColor(0)
    leg1.SetTextSize(0.05)
    leg1.AddEntry(err, "systematic uncertainty (" + fit + ")", "f")

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if ratio else 600)
    gStyle.SetOptStat(0)
    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)
    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.08)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if log:
        c1.GetPad(bool(ratio)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    #    hist['BkgSum'].Draw("SAME, E2") # sum of bkg
    if len(data) > 0: hist['data_obs'].Draw("SAME, PE")  # data
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST",
                                   hist[s].Integral() * snorm)  # signals
        pass

    bkg.SetMaximum((2. if log else 1.1) * max(
        bkg.GetMaximum(), hist['data_obs'].GetMaximum() +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 1.e-1) if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)

    setHistStyle(bkg, 1.1 if ratio else 1.0)

    leg.Draw()
    #    drawCMS(lumi, "Preliminary",True)
    drawCMS(lumi, "Private", True)
    drawRegion(channel)
    drawAnalysis(channel)
    drawFit(fit)

    if ratio:
        c1.cd(2)
        setBotStyle(err, 3, True)
        setBotStyle(res)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if len(data) > 0:
            res.Draw("SAME, PE0")
            drawRatio(hist['data_obs'], hist['BkgSum'])
            drawKolmogorov(hist['data_obs'], hist['BkgSum'])

        leg1.Draw()

    c1.Update()

    # return list of objects created by the draw() function
    return [c1, bkg, leg, leg1, err, errLine, res]
Ejemplo n.º 2
0
def myStack(fname_, region_, isSR, prefitbackgroundlist_, legendname_,
            colorlist_, regionName_, dirName_, isMerged, pad1ymax_):

    nbins = 4
    edges = arr.array('f')

    openfile = TFile(fname_)

    print " "
    print "*************************"
    print region_, "for", dirName_
    print " "

    prefit_path = "shapes_prefit/" + region_ + "/"
    postfit_path = "shapes_fit_b/" + region_ + "/"

    #get the histograms from prefit directory

    print "get histograms from", prefit_path
    print " "

    backgroundlist_ = []

    for j in prefitbackgroundlist_:
        jh = openfile.Get(prefit_path + j)
        backgroundlist_.append(jh)

    if isSR: signal_ = openfile.Get(prefit_path + "signal")

    edges = arr.array('f')
    for i in range(nbins):
        low = backgroundlist_[0].GetXaxis().GetBinLowEdge(i + 1)
        edges.append(low)
    up = backgroundlist_[0].GetXaxis().GetBinUpEdge(nbins)
    edges.append(up)

    data = openfile.Get(prefit_path + "data")
    data_ = TH1F("data_", "", nbins, edges)
    nPoints = data.GetN()
    for i in range(nPoints):
        x = ROOT.Double(0)
        y = ROOT.Double(0)
        data.GetPoint(i, x, y)
        k = data_.FindFixBin(x)
        data_.SetBinContent(k, y)
        data_.SetBinError(i + 1, data.GetErrorY(i))

    prefit_ = openfile.Get(prefit_path + "total_background")

    #get the histogram from post fit directory

    print "get histograms from", postfit_path
    print " "

    postfit_ = openfile.Get(postfit_path + "total_background")

    # draw the histograms #

    leg = myLegend(ncol=2)
    pad = myPad()

    pad[1].cd()

    gPad.SetLogy()

    data_.SetLineColor(1)
    data_.SetLineWidth(3)
    data_.SetMarkerStyle(20)
    data_.SetMarkerColor(1)
    data_.SetMarkerSize(1.5)
    data_.GetXaxis().SetLabelSize(0)
    data_.GetYaxis().SetLabelSize(0.05)
    data_.GetYaxis().SetTitleOffset(1.2)
    data_.GetYaxis().SetTitleSize(0.05)
    data_.GetYaxis().SetNdivisions(510)
    data_.SetMaximum(pad1ymax_)
    data_.GetYaxis().SetTitle("Events/GeV")
    data_.Draw("e1")

    hs = THStack("hs", "")
    for j in range(len(colorlist_)):
        h = backgroundlist_[j]
        h.SetFillColor(colorlist_[j])
        h.SetLineColor(colorlist_[j])
        hs.Add(h, "")
        leg.AddEntry(h, legendname_[j], "f")
    hs.Draw("histsame")

    postfit_.SetLineColor(634)
    postfit_.SetLineWidth(4)
    leg.AddEntry(postfit_, "Post-fit", "l")
    postfit_.Draw("histsame")

    if isSR:
        signal_.SetLineColor(416)
        signal_.SetLineWidth(4)
        signal_.SetMarkerStyle(21)
        #signal_.SetMarkerColor(824)
        leg.AddEntry(signal_, "Signal", "l")
        signal_.Draw("histsame")

    leg.AddEntry(data_, "Data", "lep")
    data_.Draw("e1same")

    leg.Draw()

    drawE = drawenergy()
    for i in drawE:
        i.Draw()

    pt4 = TPaveText(0.2577181, 0.815, 0.5580537, 0.875, "brNDC")
    pt4.SetBorderSize(0)
    pt4.SetTextAlign(12)
    pt4.SetFillStyle(0)
    pt4.SetTextFont(52)
    pt4.AddText(regionName_)
    pt4.Draw()

    pad[2].cd()

    gPad.GetUymax()

    leg1 = myLegend(coordinate=[0.5, 0.80, 0.87, 0.95])
    leg1.SetTextSize(0.1)

    prefithist = dataPredRatio(data_=data_, totalBkg_=prefit_)
    prefithist.SetLineColor(1)
    prefithist.SetLineWidth(3)
    prefithist.SetMarkerSize(1.5)
    prefithist.GetXaxis().SetLabelSize(0.13)
    prefithist.GetXaxis().SetTitleOffset(1)
    prefithist.GetXaxis().SetTitleSize(0.13)
    prefithist.GetXaxis().SetTickLength(0.1)
    prefithist.GetYaxis().SetLabelSize(0.12)
    prefithist.GetYaxis().SetRangeUser(-0.5, 0.5)
    prefithist.GetYaxis().SetTitleOffset(0.5)
    prefithist.GetYaxis().SetTitleSize(0.13)
    prefithist.GetYaxis().SetNdivisions(505)
    prefithist.GetYaxis().SetTitle("#frac{Data-Pred}{Pred}")
    prefithist.GetXaxis().SetTitle("Recoil (GeV)")
    leg1.AddEntry(prefithist, "Prefit", "lep")
    prefithist.Draw("e1")

    postfithist = dataPredRatio(data_=data_, totalBkg_=postfit_)
    postfithist.SetLineColor(634)
    postfithist.SetLineWidth(3)
    postfithist.SetMarkerSize(1.5)
    postfithist.SetMarkerColor(634)
    postfithist.GetYaxis().SetTitle("#frac{Data-Pred}{Pred}")
    postfithist.GetXaxis().SetTitle("Recoil (GeV)")
    leg1.AddEntry(postfithist, "Postfit", "lep")
    postfithist.Draw("e1same")

    leg1.Draw()

    if not os.path.exists(dirName_):
        os.mkdir(dirName_)

    pad[0].Modified()
    pad[0].Update()
    if isMerged:
        pad[0].SaveAs(dirName_ + region_ + "_merged_2017.pdf")
        pad[0].SaveAs(dirName_ + region_ + "_merged_2017.png")
    if not isMerged:
        pad[0].SaveAs(dirName_ + region_ + "_resolved_2017.pdf")
        pad[0].SaveAs(dirName_ + region_ + "_resolved_2017.png")
Ejemplo n.º 3
0
def createPlotsReco_(reco_file, label, debug=False):
    """Cumulative material budget from reconstruction.


       Internal function that will produce a cumulative profile of the
       material budget in the reconstruction starting from the single
       detectors that compose the tracker. It will iterate over all
       existing detectors contained in the sDETS dictionary. The
       function will automatically stop everytime it encounters a
       non-existent detector, until no more detectors are left to
       try. For this reason the keys in the sDETS dictionary can be as
       inclusive as possible.

    """

    cumulative_matbdg = None
    sPREF = ["Original_RadLen_vs_Eta_", "RadLen_vs_Eta_"]

    c = TCanvas("c", "c", 1024, 1024);
    diffs = []
    if not checkFile_(reco_file):
        print("Error: missing file %s" % reco_file)
        raise RuntimeError
    file = TFile(reco_file)
    prefix = "/DQMData/Run 1/Tracking/Run summary/RecoMaterial/"
    for s in sPREF:
        hs = THStack("hs","");
        histos = []
        for det, color in sDETS.iteritems():
            layer_number = 0
            while True:
                layer_number += 1
                name = "%s%s%s%d" % (prefix, s, det, layer_number)
                prof = file.Get(name)
                # If we miss an object, since we are incrementally
                # searching for consecutive layers, we may safely
                # assume that there are no additional layers and skip
                # to the next detector.
                if not prof:
                    if debug:
                        print("Missing profile %s" % name)
                    break
                else:
                    histos.append(prof.ProjectionX("_px", "hist"));
                    diffs.append(histos[-1]);
                    histos[-1].SetFillColor(color + layer_number);
                    histos[-1].SetLineColor(color + layer_number + 1);

        name = "CumulativeRecoMatBdg_%s" % s
        if s == "RadLen_vs_Eta_":
            cumulative_matbdg = TH1D(name, name,
                                     histos[0].GetNbinsX(),
                                     histos[0].GetXaxis().GetXmin(),
                                     histos[0].GetXaxis().GetXmax())
            cumulative_matbdg.SetDirectory(0)
        for h in histos:
            hs.Add(h)
            if cumulative_matbdg:
                cumulative_matbdg.Add(h, 1.)
        hs.Draw()
        hs.GetYaxis().SetTitle("RadLen")
        c.Update()
        c.Modified()
        c.SaveAs("%sstacked_%s.png" % (s, label))
    hs = THStack("diff","")
    for d in range(0,len(diffs)/2):
        diffs[d+len(diffs)/2].Add(diffs[d], -1.)
        hs.Add(diffs[d+len(diffs)/2]);
    hs.Draw()
    hs.GetYaxis().SetTitle("RadLen")
    c.Update()
    c.Modified()
    c.SaveAs("RadLen_difference_%s.png" % label)
    return cumulative_matbdg
Ejemplo n.º 4
0
for i in range(0, N_hist):

    #printHistName = "nJets"
    #printHistName = "sigTop"
    printHistName = "leptauDR"

    hnames = sig1samples[sig1samples.keys()[0]]["hname"][i].split("_")
    if hnames[1] == printHistName:
        string0 = "%s \n" % hnames
        fNevt.write(string0)

    if hnames[1] == printHistName:
        print hnames[1], " ", hnames[2], " ", hnames[3]

    hs = THStack()
    l = TLegend(0.15, 0.71, 0.89, 0.87)
    l.SetNColumns(4)
    l.SetTextSize(0.04)
    l.SetLineColor(0)
    l.SetFillColor(0)

    ntotalbkg = 0
    k = 0
    for fname in bkgsamples.keys():
        h_tmp = bkgsamples[fname]["file"].Get(bkgsamples[fname]["hname"][i])
        nbins = h_tmp.GetNbinsX()
        h_tmp.AddBinContent(nbins, h_tmp.GetBinContent(nbins + 1))  #overflow
        h_tmp.SetFillColor(bkgsamples[fname]["col"])
        scale = lumi / (bkgsamples[fname]["total"] /
                        bkgsamples[fname]["xsection"])
Ejemplo n.º 5
0
def plot_hist(histlist,
              labellist,
              norm,
              log,
              overflow,
              filename,
              options,
              scaling=[]):
    canv = TCanvas("c1", "c1", 800, 600)
    canv.SetTopMargin(10)
    canv.SetRightMargin(100)
    if log: gPad.SetLogy()
    histstack = THStack("stack", histlist[0].GetTitle())
    legend = TLegend(0.76, 0.88 - 0.08 * len(histlist), 0.91, 0.88, '', 'NDC')
    colorlist = [4, 8, 2, 6, 1]
    if len(scaling) > 1 and scaling[1] == 0: scaling = []

    if options: options += " NOSTACK"
    else: options = "NOSTACK"

    maximum = 0
    for i in range(len(histlist)):
        entries = histlist[i].GetEntries()
        mean = histlist[i].GetMean()
        histlist[i].SetLineColorAlpha(colorlist[i], 0.65)
        histlist[i].SetLineWidth(3)
        nbins = histlist[i].GetNbinsX()
        legend.AddEntry(
            histlist[i], "#splitline{" + labellist[i] +
            "}{#splitline{%d entries}{mean=%.2f}}" % (entries, mean), "l")

        if overflow:
            histlist[i].SetBinContent(
                nbins, histlist[i].GetBinContent(nbins) +
                histlist[i].GetBinContent(nbins + 1))  #overflow
            histlist[i].SetBinContent(1, histlist[i].GetBinContent(0) +
                                      histlist[i].GetBinContent(1))  #underflow
        if entries and norm: histlist[i].Scale(1. / entries)

        if histlist[i].GetMaximum() > maximum:
            maximum = histlist[i].GetMaximum()
        histstack.Add(histlist[i])

    histstack.SetMaximum(maximum * 1.4)
    histstack.Draw(options)
    histstack.GetXaxis().SetTitle(histlist[0].GetXaxis().GetTitle())
    histstack.GetYaxis().SetTitle(histlist[0].GetYaxis().GetTitle())
    xlimit = [
        histlist[0].GetBinLowEdge(1),
        histlist[0].GetBinLowEdge(histlist[0].GetNbinsX()) +
        histlist[0].GetBinWidth(histlist[0].GetNbinsX())
    ]
    if len(scaling) != 0:
        top_axis = TGaxis(xlimit[0], maximum * 1.4, xlimit[1], maximum * 1.4,
                          (xlimit[0] - scaling[0]) / scaling[1],
                          (xlimit[1] - scaling[0]) / scaling[1], 510, "-")
        top_axis.SetTitle("normalized scale")
        top_axis.SetTickSize(0)
        top_axis.Draw("SAME")

    legend.SetTextSize(0.02)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.Draw("SAME")
    canv.SaveAs(filename)
    if log: gPad.Clear()
    canv.Clear()
    del canv
Ejemplo n.º 6
0
def plotStack(name,histo,index,indexName,histoIntLumi,lumiBool,resStack,resCanvas,resLegend,recovBool = True,compBool = False,approvedPlots = False):
# name: Mainly an index of the output. Also used to define TAxis Title
# histo: dict of histograms or TProfile to be displayed
# index: list of keys of histo to be displayed
# indexName: dict of namesof index used for the TLegend
# histoIntLumi : integrated lumi with the same x binning as histo
# lumiBool : display results in term of lumi and not percent
# resStack, resCanvas, resLegend: dict of (stacks, canvas, legend) outputs
# recovBool: display the recoverable histograms (referenced as %%%__recov in histo
# compBool: this is a 2 yearTag plots. Write all numbers in TLegend and not only last bin (that is not meaningful in yearTag)

  # unit is the main unit. unitAux is the complementary one used only the TLegend
  if (lumiBool):
    unit = "pb^{-1}"
    unitAux = "%%"
  else:
    unit = "%%"
    unitAux = "pb^{-1}"

  nameSplitted = name.split("--") # Assume that the name is "Veto/defect (y axis) - Year/Run (x axis)- Dataset name"
  xAxisTitle = nameSplitted[1]
  if unit == "%%":
    yAxisTitle = "Lost luminosity due to %s [%%]"%(nameSplitted[0])
  else:
    yAxisTitle = "Lost luminosity due to %s [%s]"%(nameSplitted[0],unit)
  legendHeader = nameSplitted[2]

  resCanvas[name] = TCanvas(name,"%s - %s"%(yAxisTitle,xAxisTitle),200, 10, 1150, 500)
  resCanvas[name].SetLeftMargin(0.08)
  resCanvas[name].SetRightMargin(0.28)
  resCanvas[name].SetGridy(1)
  resStack[name] = THStack("%s_stack"%name,"")
  resLegend[name] = MakeLegend(0.725,0.8,0.98,0.95) # Y1 will be redefined later according tp the number of entries
  first = True
  totalIneff = 0.
  totalIneff1 = 0.

  nBinsX = histoIntLumi.GetNbinsX()
  totalIntegratedLumi = histoIntLumi.GetBinContent(nBinsX)
  if lumiBool:
    auxScaleFactor = 100./totalIntegratedLumi
  else:
    auxScaleFactor = totalIntegratedLumi/100.

  for iIndex in sorted(index,reverse=True):
    if first: # Create a recoverable histograms just in case of
      resStack["%s__recov"%name] = MakeTH1("h1_%s__recovTotal"%(name),"Recoverable","",-0.5,-0.5+nBinsX,nBinsX,1)
      resStack["%s__recov"%name].SetMarkerStyle(23)  
      first = False
    iIndexName = iIndex.split("_")[0]

    # Fill histo["%s_toStack"] the main histo
    # and histo["%s_aux"] the complementary one used only for TLegend
    if (histo[iIndex]).IsA().InheritsFrom("TProfile"):
      histo['%s_toStack'%iIndex] = histo[iIndex].ProjectionX()
      histo['%s_toStack'%iIndex].SetFillColor(histo[iIndex].GetFillColor())
    else:
      histo['%s_toStack'%iIndex] = histo[iIndex]
    if lumiBool:
      histo['%s_toStack'%iIndex].Multiply(histo['%s_toStack'%iIndex],histoIntLumi,0.01)
    resStack[name].Add(histo['%s_toStack'%iIndex])

  entryNb = 0
  for iIndex in sorted(index): # Reverse order to have the TLegend ordered as the stacks
    iIndexName = iIndex.split("__")[0] # Trick needed to get the defect name for the recoverable defect histogram    
    baseEntry = "%s"%(strLumi(histo['%s_toStack'%iIndex].GetBinContent(nBinsX),unit))
    auxEntry = "%s"%(strLumi(histo['%s_toStack'%iIndex].GetBinContent(nBinsX)*auxScaleFactor,unitAux))

    if (recovBool and "%s__recov"%iIndex in histo.keys() and histo["%s__recov"%iIndex].GetBinContent(nBinsX) != 0.):
      baseEntryRecov = "%s"%(strLumi(histo["%s__recov"%iIndex].GetBinContent(nBinsX),unit))
      entry = "#splitline{%s}{%s(recov:%s) / %s}"%(indexName[iIndexName],baseEntry,baseEntryRecov,auxEntry) # Second part of Legend to fix
      for iBin in range(nBinsX+1):
        resStack["%s__recov"%name].Fill(iBin-1,histo["%s__recov"%iIndex].GetBinContent(iBin))
    else:
      entry = "#splitline{%s}{%s / %s}"%(indexName[iIndex],baseEntry,auxEntry)

    if (compBool): # This is a >=2 yearTag histograms
      if histo[iIndex].GetNbinsX() == 2:
        entry = "#splitline{%s}{%s / %s }"%(indexName[iIndexName],strLumi(histo[iIndex].GetBinContent(1),unit),strLumi(histo[iIndex].GetBinContent(2),unit))
      elif histo[iIndex].GetNbinsX() == 3:
        entry = "#splitline{%s}{%s / %s / %s}"%(indexName[iIndexName],strLumi(histo[iIndex].GetBinContent(1),unit),strLumi(histo[iIndex].GetBinContent(2),unit),strLumi(histo[iIndex].GetBinContent(3),unit))
      else:
        entry = "%s"%(indexName[iIndexName])
        

    if (histo[iIndex].GetMaximum() != 0): 
      resLegend[name].AddEntry(histo[iIndex],entry,"f")
      entryNb = entryNb+1
      totalIneff = totalIneff + histo['%s_toStack'%iIndex].GetBinContent(nBinsX)
      if compBool:
        totalIneff1 = totalIneff1 + histo['%s_toStack'%iIndex].GetBinContent(1)          
      
  mx = resStack[name].GetMaximum()*1.2
  resStack[name].SetMaximum(mx)
  resStack[name].Draw("hist")
  resStack[name].GetXaxis().SetTitle("%s"%xAxisTitle)
  resStack[name].GetYaxis().SetTitle("%s"%yAxisTitle)
  resStack[name].GetYaxis().SetTitleOffset(0.7)
  if resStack[name].GetMaximum()>10.:
    resCanvas[name].SetLogy(1)

  if compBool:
    resLegend[name].SetHeader("#splitline{%s}{Total loss: %s / %s}"%(legendHeader,strLumi(totalIneff1,unit),strLumi(totalIneff,unit)))
  else:
    totalIneffAux = totalIneff*auxScaleFactor
    if (approvedPlots):
      resLegend[name].SetHeader("#splitline{%s}{Total loss: %s / %s}"%(legendHeader,strLumi(totalIneff,unit),strLumi(totalIneffAux,unitAux)))
    else:
      resLegend[name].SetHeader("#splitline{%s (%s)}{Total loss: %s / %s}"%(legendHeader,strLumi(totalIntegratedLumi,"pb"),strLumi(totalIneff,unit),strLumi(totalIneffAux,unitAux)))
  if resStack["%s__recov"%name].GetEntries() != 0.:
    resStack["%s__recov"%name].SetMarkerStyle(20)
    resStack["%s__recov"%name].SetMarkerColor(kAzure+8)
    resStack["%s__recov"%name].Draw("PSAME HIST")
    resLegend[name].AddEntry(resStack["%s__recov"%name],"#splitline{Recoverable}{total: %.2f%%}"%(resStack["%s__recov"%name].GetBinContent(nBinsX)),"p")
    entryNb = entryNb + 1
          
  resLegend[name].SetY1(max(0.83-entryNb*0.12,0.05))
  resLegend[name].Draw()

  resCanvas[name].Update()
  
  return totalIneff # totalIneff is used only with the savePage1 option in DeMoStatus
 def DrawHisto(self,
               doSF=False,
               name='',
               chan='',
               level='',
               rebin=1,
               log=True):
     self.SetChanAndLevel('', level)
     self.SetMode('SF' if doSF else 'OF')
     if name == '':
         name = 'DYDD_%s_%s' % ('SF' if doSF else 'OF', self.GetLevel())
     hData = self.GetDYhisto(chan, level, True)
     hMC = self.GetDYhisto(chan, level, False)
     hemu = self.GetDYhisto('ElMu', level, True)
     hData.SetMarkerStyle(20)
     hData.SetMarkerColor(1)
     hData.SetLineColor(1)
     hData.SetMarkerSize(1.3)
     hMC.SetFillStyle(1000)
     hMC.SetLineColor(kAzure - 8)
     hMC.SetFillColor(kAzure - 8)
     hemu.SetFillStyle(1000)
     hemu.SetLineColor(kGray)
     hemu.SetFillColor(kGray)
     hData.Rebin(rebin)
     hemu.Rebin(rebin)
     hMC.Rebin(rebin)
     ke, kee = self.GetKfactor(elname)
     km, kme = self.GetKfactor(muname)
     hemu.Scale(0.5 * (ke if chan == 'ElE' else km))
     hs = THStack()
     hs.Add(hemu)
     hs.Add(hMC)
     lab = 'e^{#pm}e^{#mp}' if chan == 'ElEl' else '#mu^{#pm}#mu^{#mp}'
     rlab = 'ee' if chan == 'ElEl' else '#mu#mu'
     processes = [
         'Z/#gamma*#rightarrow %s' % (lab),
         '0.5 k_{%s} #times Data(e#mu)' % rlab
     ]
     colors = {processes[0]: kAzure - 9, processes[1]: kGray}
     s = Stack(doRatio=False)
     s.SetXtitle(size=0.06, offset=0.8, nDiv=510, labSize=0.05)
     s.SetTextCMS(cmstex='CMS', x=0.13, y=0.88, s=0.06)
     s.SetTextCMSmode(texcmsMode='Preliminary', x=0.225, y=0.875, s=0.052)
     s.SetLumi(304.32)
     s.SetTextLumi(texlumi='%2.1f pb^{-1} (5.02 TeV)',
                   texlumiX=0.68,
                   texlumiY=0.95,
                   texlumiS=0.045)
     s.SetDataHisto(hData)
     s.SetColors(colors)
     s.SetStack(hs)
     s.SetOutName('DYestimate_%s%s' % (chan, level) +
                  ('_log' if log else ''))
     s.SetOutPath(self.outpath)
     plotMinimum = 0.5 if log else 0
     plotMaxScale = 10 if log else 1.3
     s.SetLogY(log)
     s.SetPlotMaxScale(plotMaxScale)
     s.SetPlotMinimum(plotMinimum)
     maximum = hData.GetMaximum() * (5 if log else 1.2)
     s.AddLine(76, 0.5, 76, maximum)
     s.AddLine(106, 0.5, 106, maximum)
     s.processes = processes
     s.SetLegendPos(x0=0.60, y0=0.55, x1=0.93, y1=0.91, size=0.042, ncol=1)
     s.DrawStack('m_{%s} (GeV)' % rlab)
Ejemplo n.º 8
0
def makeDiTauStack(outDir,
                   inFile,
                   rootDir,
                   s,
                   labelX,
                   units="GeV",
                   left=False,
                   channel="",
                   json="Golden",
                   log=False,
                   dndm=False,
                   doRatio=False,
                   year=2017,
                   sign='OS',
                   LTcut=0.,
                   cat='mmtt',
                   wait='wait'):

    tdrstyle.setTDRStyle()

    writeExtraText = True  # if extra text
    extraText = "Preliminary"  # default extra text is "Preliminary"
    lumi_sqrtS = "13 TeV"
    if json == "Golden": lumi_13TeV = channel + "    41.8 fb^{-1}, 2017"
    iPeriod = 4  # 1=7TeV, 2=8TeV, 3=7+8TeV, 7=7+8+13TeV

    xR = 0.65  #legend parameters
    xR = 0.2  #legend parameters
    H = 600
    W = 600
    H_ref = 600
    W_ref = 600

    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.16 * W_ref
    R = 0.04 * W_ref

    #margins for inbetween the pads in a ratio plot
    B_ratio = 0.1 * H_ref
    T_ratio = 0.03 * H_ref

    #margin required for lebal on bottom of raito plot
    B_ratio_label = 0.3 * H_ref

    c = TCanvas('c1', 'c1', 50, 50, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)

    if not doRatio:
        c.SetLeftMargin(L / W)
        c.SetRightMargin(R / W)
        c.SetTopMargin(T / H)
        c.SetBottomMargin(B / H)

    c.cd()

    ratioPad = TPad("pad2", "", 0.0, 0.0, 1.0, 0.29)
    plotPad = TPad("pad1", "", 0.0016, 0.291, 1.0, 1.0)
    if doRatio:
        plotPad.SetTicks(0, 0)
        plotPad.SetLeftMargin(L / W)
        plotPad.SetRightMargin(R / W)
        plotPad.SetTopMargin(T / H)
        plotPad.SetBottomMargin(B_ratio / H)
        plotPad.SetFillColor(0)
        plotPad.SetBottomMargin(0)

        ratioPad.SetLeftMargin(L / W)
        ratioPad.SetRightMargin(R / W)
        ratioPad.SetTopMargin(T_ratio / H)
        ratioPad.SetTopMargin(0.007)
        ratioPad.SetBottomMargin(B_ratio_label / H)
        ratioPad.SetGridy(1)
        ratioPad.SetFillColor(4000)

    else:
        plotPad = TPad("pad1", "", 0.0, 0.03, 1.0, 1.0)
        plotPad.SetLeftMargin(L / W)
        plotPad.SetRightMargin(R / W)
        plotPad.SetTopMargin(T / H)
        plotPad.SetBottomMargin(B / H)

    plotPad.Draw()
    plotPad.cd()

    print("In makeStack inFile={0:s}".format(inFile))
    f = TFile(inFile)

    groups = ['data', 'Reducible', 'Rare', 'ZZ4L', 'Signal']
    histo = {}
    colors = {
        'data': 0,
        'Reducible': kMagenta - 10,
        'Rare': kBlue - 8,
        'ZZ4L': kAzure - 9,
        'Signal': kRed
    }
    hs = THStack("hs", "")
    for group in groups:
        if len(cat) == 4:
            histo[group] = f.Get("h{0:s}_{1:s}_Mtt".format(group, cat))
        else:
            histo[group] = f.Get("h{0:s}_ee{1:s}_Mtt".format(group, cat))
            histo2 = f.Get("h{0:s}_mm{1:s}_Mtt".format(group, cat))
            histo[group].Add(histo2)

        if dndm: convertToDNDM(histo[group])
        if group == 'data':
            applyDATAStyle(histo[group])
        else:
            applyStyle(histo[group], colors[group], 1, 1001)
        if group != 'data': hs.Add(histo[group])

    try:
        hMax = 1.2 * max(histo['data'].GetMaximum(), hs.GetMaximum())
    except KeyError:
        hMax = 1.2 * hs.GetMaximum()

    hs.SetMaximum(hMax)
    hs.Draw("HIST")
    try:
        histo['data'].Draw("e,SAME")
    except KeyError:
        pass

    if doRatio:
        hs.GetXaxis().SetLabelSize(0)
    else:
        if units != "":
            hs.GetXaxis().SetTitle(labelX + " [" + units + "]")
        else:
            hs.GetXaxis().SetTitle(labelX)

    hs.GetYaxis().SetTitle("Events")
    hs.GetYaxis().SetTitleOffset(1)

    if dndm: hs.GetYaxis().SetTitle("dN/d" + labelX)
    c.cd()
    if doRatio:
        data2 = histo['data'].Clone("data")
        mc = histo['Rare']
        mc.Add(histo['Reducible'])
        mc.Add(histo['ZZ4L'])
        xmin = mc.GetXaxis().GetXmin()
        xmax = mc.GetXaxis().GetXmax()
        line = TLine(xmin, 1.0, xmax, 1.0)
        line.SetLineWidth(1)
        line.SetLineColor(kBlack)

        ratioPad.Draw()
        ratioPad.cd()

        data2.Divide(data2, mc)

        data2.SetMarkerStyle(20)
        data2.SetTitleSize(0.12, "Y")
        data2.SetTitleOffset(0.40, "Y")
        data2.SetTitleSize(0.12, "X")
        data2.SetLabelSize(0.10, "X")
        data2.SetLabelSize(0.08, "Y")
        data2.GetYaxis().SetRangeUser(0.62, 1.38)
        data2.GetYaxis().SetNdivisions(305)
        data2.GetYaxis().SetTitle("Obs/Exp   ")

        if units != "":
            data2.GetXaxis().SetTitle(labelX + " [" + units + "]")
        else:
            data2.GetXaxis().SetTitle(labelX)

        data2.Draw("P")
        line.Draw()

    c.cd()
    plotPad.cd()

    l = TLegend(xR, 0.55, xR + 0.28, 0.9)
    for group in groups:
        try:
            l.AddEntry(histo[group], group, "F")
        except KeyError:
            continue

    l.SetBorderSize(0)
    l.SetFillColor(0)
    l.SetFillStyle(0)
    l.SetTextSize(0.04)
    l.Draw()

    lTex1 = TLatex(120., 0.97 * hMax, 'Preliminary {0:d}'.format(year))
    lTex1.SetTextSize(0.04)
    lTex1.Draw()
    signText = 'Same Sign'
    if sign == 'OS': signText = 'Opposite Sign'
    lTex2 = TLatex(120., 0.90 * hMax, '{0:s}'.format(signText))
    lTex2.SetTextSize(0.04)
    lTex2.Draw()
    if len(cat) == 4:
        lt = {
            'eeet': '#it{l}#it{l}#it{e}#tau',
            'eemt': '#it{l}#it{l}#mu#tau',
            'eett': '#it{l}#it{l}#tau#tau',
            'mmet': '#mu#mu#it{e}#tau',
            'mmmt': '#mu#mu#mu#tau',
            'mmtt': '#mu#mu#tau#tau'
        }
    else:
        lt = {
            'et': '#it{l}#it{l}#it{e}#tau',
            'mt': '#it{l}#it{l}#mu#tau',
            'tt': '#it{l}#it{l}#tau#tau'
        }
    lTex3 = TLatex(120., 0.83 * hMax,
                   '{0:s} H_LT > {1:d} '.format(lt[cat], int(LTcut)))
    lTex3.SetTextSize(0.04)
    lTex3.Draw()

    plotPad.Draw()
    #CMS_lumi(plotPad,4,11)

    outFileBase = "Stack_{0:d}_{1:s}_{2:s}_LT{3:02d}".format(
        year, cat, sign, int(LTcut))
    c.SaveAs("{0:s}.png".format(outFileBase))
    c.SaveAs("{0:s}.root".format(outFileBase))
    if wait == 'wait':
        raw_input()
    else:
        import time
        time.sleep(5.)
Ejemplo n.º 9
0
def print_single_min(vec_beg, vec_end, name, text):

    total_beg = vec_beg[0].Clone()
    c = 0
    for v in vec_beg:
        if c != 0:
            total_beg.Add(vec_beg[c])
        c = c + 1
    
    norm = 1/total_beg.Integral()
    total_beg.Scale(norm)

    if 'buff' in name:
        legb = TLegend(0.25,0.93,0.90,0.60)
        legb.SetNColumns(5)
    else:
        legb = TLegend(0.60,0.80,0.90,0.60)
        legb.SetNColumns(2)
    legb.SetLineColor(0)
    legb.SetFillStyle(0)
    legb.SetShadowColor(0)
    legb.SetBorderSize(0)

    if 'buff' in name:
        lege = TLegend(0.25,0.93,0.90,0.60)
        lege.SetNColumns(5)
    else:
        lege = TLegend(0.22,0.90,0.52,0.70)
        lege.SetNColumns(2)
    lege.SetLineColor(0)
    lege.SetFillStyle(0)
    lege.SetShadowColor(0)
    lege.SetBorderSize(0)


    #vec_beg = sorted(vec_beg, key=lambda x: x.Integral(), reverse=True)


    stack1  = THStack("stack1","stack1")
    for v in vec_beg:
        if v.Integral() != 0:
            v.Scale(norm)
            legb.AddEntry(v, v.GetTitle()[4:], "f")
            stack1.Add(v)

    total_end = vec_end[0].Clone()
    c = 0
    for v in vec_end:
        if c != 0:
            total_end.Add(vec_end[c])
        c = c + 1
    
    norm = 1/total_end.Integral()
    total_end.Scale(norm)

    stack2  = THStack("stack2","stack2")
    for v in vec_end:
        if v.Integral() != 0:
            v.Scale(norm)
            lege.AddEntry(v, v.GetTitle()[4:], "f")
            stack2.Add(v)


    total_beg.SetLineColor(kRed)
    total_beg.SetLineWidth(1)
    total_end.SetLineColor(kRed)
    total_end.SetLineWidth(1)

    total_beg.GetXaxis().SetTitle("Minutes after stable beams declared [min]")
    total_end.GetXaxis().SetTitle("Minutes before stable beams ended [min]")

    if '0_4' in name:
        total_beg.GetYaxis().SetTitle("Arbitrary units / 3 mins")
        total_end.GetYaxis().SetTitle("Arbitrary units / 3 mins")
    else:
        total_beg.GetYaxis().SetTitle("Arbitrary units / 5 mins")
        total_end.GetYaxis().SetTitle("Arbitrary units / 5 mins")

    c4 = TCanvas( 'c4', 'c4',1000, 1200)
    c4.Divide(1,2)
    c4.cd(1)
    total_beg.Draw("HIST")
    stack1.Draw("PFC PLC SAME HIST")
    total_beg.Draw("SAMEHIST")
    AtlasStyle.ATLAS_LABEL(0.18,.96, 1, "Internal")
    AtlasStyle.myText(0.40, 0.96, kBlack, text)
    legb.Draw()
    c4.cd(2)
    total_end.Draw("HIST")
    stack2.Draw("PFC PLC SAME HIST")
    total_end.Draw("SAMEHIST")
    AtlasStyle.ATLAS_LABEL(0.18,.96, 1, "Internal")
    AtlasStyle.myText(0.40, 0.96, kBlack, text)
    lege.Draw()
    c4.Update()
    c4.Print("plots/"+name+".pdf")
Ejemplo n.º 10
0
class Plot_Multi_TH1:
    def __init__(self,filepath,filename,tree,list_variable,weight,list_cut,list_legend,list_color,name,bins,xmin,xmax,title,xlabel,ylabel,option='hist',logx=False,logy=False,legend_pos=[0.5,0.5,0.9,0.85],stack=False,norm=False):
        self.filepath = filepath
        self.filename = filename
        self.tree = tree
        self.weight = weight
        self.name = name
        self.bins = bins
        self.xmin = xmin
        self.xmax = xmax
        self.title = title
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.legend_pos = legend_pos
        self.logx = logx
        self.logy = logy
        self.option = option
        self.stack = stack
        self.norm = norm

        if not isinstance(list_cut,list):
            list_cut = [list_cut]
        if not isinstance(list_variable,list):
            list_variable = [list_variable]
        if not isinstance(list_legend,list):
            list_legend = [list_legend]


        if len(list_variable) == 1 and len(list_cut) > 1:
            logging.debug('\tOnly one variable but several cuts')
            self.list_variable = list_variable*len(list_cut)
            self.list_cut = list_cut
        elif len(list_variable) > 1 and len(list_cut) == 1:
            logging.debug('\tOnly one cut but several variables')
            self.list_cut = list_cut*len(list_variable)
            self.list_variable = list_variable
        elif len(list_variable) == 1 and len(list_cut) == 1:
            logging.warning('\tWhy do you even need to stack ?')
        elif len(list_variable) != len(list_cut):
            raise RuntimeError('Inconsistent number of variables and cuts')
            print (len(list_variable))
            print (len(list_cut))
        else:
            self.list_variable = list_variable
            self.list_cut = list_cut
        if len(list_legend) != max(len(list_variable),len(list_cut)):
            raise RuntimeError('Inconsistent number of legends compared to variables and cuts')
        else:
            self.list_legend = list_legend
        if len(list_color) != len(list_legend):
            raise RuntimeError('Inconsistent number of colors compared to legends')
        else:
            self.list_color = list_color

        for i in range(len(self.list_color)):
            if isinstance(self.list_color[i],str):
                self.list_color[i] = ROOT.TColor.GetColor(self.list_color[i])
        
    def MakeHisto(self):
        self.list_obj = []
        for i in range(0,len(self.list_variable)):
            instance = Plot_TH1(filepath = self.filepath,
                                filename = self.filename,
                                tree     = self.tree,
                                variable = self.list_variable[i],
                                weight   = self.weight,
                                cut      = self.list_cut[i],
                                name     = self.name,
                                bins     = self.bins,
                                xmin     = self.xmin,
                                xmax     = self.xmax,
                                title    = self.title,
                                xlabel   = self.xlabel,
                                ylabel   = self.ylabel,
                                logx     = self.logx,
                                logy     = self.logy)
            instance.MakeHisto()
            self.list_obj.append(copy.deepcopy(instance.histo))

    def PlotOnCanvas(self,pdf_name):
        tdrstyle.setTDRStyle() 

        # Canvas #
        canvas = TCanvas("c", "c", 600, 600)
        canvas.SetTopMargin(0.15)
        canvas.SetBottomMargin(0.15)
        canvas.SetRightMargin(0.05)
        canvas.SetLeftMargin(0.15)
        if self.title == '':
            canvas.SetTopMargin(0.05)

        if self.logx:
            canvas.SetLogx()
        if self.logy:
            canvas.SetLogy()
            self.list_obj[0].SetMinimum(10)

        # Norm #
        if self.norm:
            for obj in self.list_obj:
                if obj.Integral() != 0:
                    obj.Scale(1./obj.Integral())

        # Axes #
        maxY = max([h.GetMaximum() for h in self.list_obj])
        if self.logy:
            maxY *= 2
        else:
            maxY *= 1.1
            
        self.list_obj[0].SetMaximum(maxY)

        self.list_obj[0].GetXaxis().SetLabelSize(0.03)
        self.list_obj[0].GetXaxis().SetTitleSize(0.05)
        if len(self.xlabel) > 30:
            self.list_obj[0].GetXaxis().SetTitleSize(0.035)
        if len(self.xlabel) > 60:
            self.list_obj[0].GetXaxis().SetTitleSize(0.03)
        if "frac" in self.xlabel:
            self.list_obj[0].GetXaxis().SetTitleSize(0.03)
            self.list_obj[0].GetXaxis().SetTitleOffset(1.9)
        else:
            self.list_obj[0].GetXaxis().SetTitleOffset(1.6)
            
            
        self.list_obj[0].GetYaxis().SetTitleOffset(1.5)
        self.list_obj[0].GetYaxis().SetLabelSize(0.03)
        self.list_obj[0].GetYaxis().SetTitleSize(0.05)
        self.list_obj[0].GetYaxis().SetNdivisions(10)
        if len(self.ylabel) > 30:
            self.list_obj[0].GetYaxis().SetTitleSize(0.035)
        if len(self.ylabel) > 60:
            self.list_obj[0].GetYaxis().SetTitleSize(0.03)

        # Stacking #
        if self.stack:
            self.stack_hist = THStack("hs","") # Needs to be in self, otherwise destroyed at end of function
            opt = self.option
            for col,obj in zip(self.list_color,self.list_obj):
                obj.SetFillColor(col)
                obj.SetLineColor(col)
                self.stack_hist.Add(obj)
                obj.Draw(opt)
                if not "same" in opt :  
                    opt += " same"
            self.stack_hist.Draw(self.option+" same")
            maxY = self.stack_hist.GetMaximum()
            if self.logy:
                maxY *= 10
            else:
                maxY *= 1.1
            self.list_obj[0].SetMaximum(maxY)
        # Regular plotting
        else:
            opt = self.option
            for col,obj in zip(self.list_color,self.list_obj):
                obj.SetLineColor(col)
                obj.SetLineWidth(2)
                obj.Draw(opt)
                if not "same" in opt :  
                    opt += " same"
        # Legend #
        legend = TLegend(*self.legend_pos)
        for leg,obj in zip(self.list_legend,self.list_obj):
            legend.AddEntry(obj,leg,"f" if self.stack else "l")
        legend.SetBorderSize(0)
        legend.SetFillColor(0)
        legend.Draw()
        ROOT.SetOwnership(legend,0) # Otherwise goes out of scope and not printed

        return canvas,self.filename
Ejemplo n.º 11
0
    def PlotOnCanvas(self,pdf_name):
        tdrstyle.setTDRStyle() 

        # Canvas #
        canvas = TCanvas("c", "c", 600, 600)
        canvas.SetTopMargin(0.15)
        canvas.SetBottomMargin(0.15)
        canvas.SetRightMargin(0.05)
        canvas.SetLeftMargin(0.15)
        if self.title == '':
            canvas.SetTopMargin(0.05)

        if self.logx:
            canvas.SetLogx()
        if self.logy:
            canvas.SetLogy()
            self.list_obj[0].SetMinimum(10)

        # Norm #
        if self.norm:
            for obj in self.list_obj:
                if obj.Integral() != 0:
                    obj.Scale(1./obj.Integral())

        # Axes #
        maxY = max([h.GetMaximum() for h in self.list_obj])
        if self.logy:
            maxY *= 2
        else:
            maxY *= 1.1
            
        self.list_obj[0].SetMaximum(maxY)

        self.list_obj[0].GetXaxis().SetLabelSize(0.03)
        self.list_obj[0].GetXaxis().SetTitleSize(0.05)
        if len(self.xlabel) > 30:
            self.list_obj[0].GetXaxis().SetTitleSize(0.035)
        if len(self.xlabel) > 60:
            self.list_obj[0].GetXaxis().SetTitleSize(0.03)
        if "frac" in self.xlabel:
            self.list_obj[0].GetXaxis().SetTitleSize(0.03)
            self.list_obj[0].GetXaxis().SetTitleOffset(1.9)
        else:
            self.list_obj[0].GetXaxis().SetTitleOffset(1.6)
            
            
        self.list_obj[0].GetYaxis().SetTitleOffset(1.5)
        self.list_obj[0].GetYaxis().SetLabelSize(0.03)
        self.list_obj[0].GetYaxis().SetTitleSize(0.05)
        self.list_obj[0].GetYaxis().SetNdivisions(10)
        if len(self.ylabel) > 30:
            self.list_obj[0].GetYaxis().SetTitleSize(0.035)
        if len(self.ylabel) > 60:
            self.list_obj[0].GetYaxis().SetTitleSize(0.03)

        # Stacking #
        if self.stack:
            self.stack_hist = THStack("hs","") # Needs to be in self, otherwise destroyed at end of function
            opt = self.option
            for col,obj in zip(self.list_color,self.list_obj):
                obj.SetFillColor(col)
                obj.SetLineColor(col)
                self.stack_hist.Add(obj)
                obj.Draw(opt)
                if not "same" in opt :  
                    opt += " same"
            self.stack_hist.Draw(self.option+" same")
            maxY = self.stack_hist.GetMaximum()
            if self.logy:
                maxY *= 10
            else:
                maxY *= 1.1
            self.list_obj[0].SetMaximum(maxY)
        # Regular plotting
        else:
            opt = self.option
            for col,obj in zip(self.list_color,self.list_obj):
                obj.SetLineColor(col)
                obj.SetLineWidth(2)
                obj.Draw(opt)
                if not "same" in opt :  
                    opt += " same"
        # Legend #
        legend = TLegend(*self.legend_pos)
        for leg,obj in zip(self.list_legend,self.list_obj):
            legend.AddEntry(obj,leg,"f" if self.stack else "l")
        legend.SetBorderSize(0)
        legend.SetFillColor(0)
        legend.Draw()
        ROOT.SetOwnership(legend,0) # Otherwise goes out of scope and not printed

        return canvas,self.filename
Ejemplo n.º 12
0
    myfile = TFile.Open(plotDirectory + "myZJets_Prefit.root", "recreate")
    for ih in summedHist:
        rebinnedHist[ih] = summedHist[ih].Rebin(len(binning) - 1, "", binning)
        rebinnedHist[ih].SetLineColor(template_category[ih])
        rebinnedHist[ih].SetFillColor(template_category[ih])
        rebinnedHist[ih].Write()

    rebinnedData = data_obs.Rebin(len(binning) - 1, "", binning)
    rebinnedData.Write()
    myfile.Close()
    sys.exit()
else:
    if postfitPlots:
        rebinnedHist['myZJets'].Scale(ZJetSF)

    stack = THStack()
    stack.Add(rebinnedHist['myBackground'])
    stack.Add(rebinnedHist['myZJets'])

    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()
Ejemplo n.º 13
0
def draw(hist,
         channel,
         data,
         back,
         sign,
         snorm=1,
         lumi=-1,
         ratio=0,
         log=False):
    # If not present, create BkgSum
    if not 'BkgSum' in hist.keys():
        hist['BkgSum'] = hist['data_obs'].Clone(
            "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
        hist['BkgSum'].Reset("MICES")
        for i, s in enumerate(back):
            hist['BkgSum'].Add(hist[s])
    hist['BkgSum'].SetMarkerStyle(0)

    # Set Poisson error bars
    #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work

    alpha = 1 - 0.6827
    hist['data_obs'].SetBinErrorOption(TH1.kPoisson)
    data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX())
    data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle())
    data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize())
    res_graph = data_graph.Clone()
    for i in range(hist['data_obs'].GetNbinsX()):
        N = hist['data_obs'].GetBinContent(i + 1)
        B = hist['BkgSum'].GetBinContent(i + 1)
        L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.)
        U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1)
        data_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                            N if not N == 0 else -1.e99)
        data_graph.SetPointError(
            i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N)
        res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                           N / B if not B == 0 and not N == 0 else -1.e99)
        res_graph.SetPointError(
            i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            (N - L) / B if not B == 0 else -1.e99,
            (U - N) / B if not B == 0 else -1.e99)

    # Create stack
    bkg = THStack("Bkg",
                  ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    n = len([x for x in data + back + ['BkgSum'] + sign if sample[x]['plot']])
    leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pl")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            leg.AddEntry(hist[s],
                         sample[s]['label'].replace("m_{#Chi}=1 GeV",
                                                    ""), "fl")

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if ratio else 600)

    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)
    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.06)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if log:
        c1.GetPad(bool(ratio)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    #if len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data
    data_graph.Draw("SAME, PE")
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST",
                                   hist[s].Integral() * snorm)  # signals

    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075)
    bkg.SetMaximum((2. if log else 1.2) * max(
        bkg.GetMaximum(),
        hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)

    #if log: bkg.SetMinimum(1)
    leg.Draw()
    drawCMS(lumi, "Preliminary")
    drawRegion(channel)
    drawAnalysis(channel)

    #if nm1 and not cutValue is None: drawCut(cutValue, bkg.GetMinimum(), bkg.GetMaximum()) #FIXME
    if len(sign) > 0:
        if channel.startswith('X') and len(sign) > 0:
            drawNorm(0.9 - 0.04 * (n + 1),
                     "#sigma(X) #times B(X #rightarrow Vh) = %.1f pb" % snorm)
            #elif "SR" in channel: drawNorm(0.9-0.04*(n+1), "DM+bb/tt, scaled by %.0f" % snorm, "m_{#chi}=1 GeV, scalar mediator")
        elif "SR" in channel:
            drawNorm(0.9 - 0.04 * (n + 1), "DM+bb/tt, m_{#chi}=1 GeV",
                     "scalar mediator")

    setHistStyle(bkg, 1.2 if ratio else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1)

    if ratio:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        res = hist['data_obs'].Clone("Residues")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                res.SetBinContent(
                    i,
                    res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                res.SetBinError(
                    i,
                    res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
        setBotStyle(res)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if len(data) > 0:
            #res.Draw("SAME, PE0")
            res_graph.Draw("SAME, PE0")


#            if len(err.GetXaxis().GetBinLabel(1))==0: # Bin labels: not a ordinary plot
#                drawRatio(hist['data_obs'], hist['BkgSum'])
#                drawKolmogorov(hist['data_obs'], hist['BkgSum'])

    c1.Update()

    # return list of objects created by the draw() function
    return [c1, bkg, leg, err, errLine, res, data_graph, res_graph]
Ejemplo n.º 14
0
def plot(path, leg_title, ecms, xmin, xmax, xbins, runNolow, runNoup, ymax):
    try:
        f_data = TFile(path[0])
        f_incMC1 = TFile(path[1])
        f_incMC2 = TFile(path[2])
        f_sigMC1 = TFile(path[3])
        f_sigMC2 = TFile(path[4])
        t_data = f_data.Get('save')
        t_incMC1 = f_incMC1.Get('save')
        t_incMC2 = f_incMC2.Get('save')
        t_sigMC1 = f_sigMC1.Get('save')
        t_sigMC2 = f_sigMC2.Get('save')
        entries_data = t_data.GetEntries()
        entries_incMC1 = t_incMC1.GetEntries()
        entries_incMC2 = t_incMC2.GetEntries()
        entries_sigMC1 = t_sigMC1.GetEntries()
        entries_sigMC2 = t_sigMC2.GetEntries()
        logging.info('data entries :' + str(entries_data))
        logging.info('inclusive MC(open charm) entries :' +
                     str(entries_incMC1))
        logging.info('inclusive MC(qqbar) entries :' + str(entries_incMC2))
        logging.info('signal MC(D1(2420)) entries :' + str(entries_sigMC1))
        logging.info('signal MC(psi(3770)) entries :' + str(entries_sigMC2))
    except:
        logging.error('File paths are invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    content = (xmax - xmin) / xbins * 1000
    ytitle = 'Events/%.1f MeV' % content
    xtitle = 'M(D^{+}#pi^{0})(GeV)'
    h_data = TH1F('data', 'data', xbins, xmin, float(xmax))
    h_incMC1 = TH1F('incMC1', 'inclusive MC: open charm', xbins, xmin,
                    float(xmax))
    h_incMC2 = TH1F('incMC2', 'inclusive MC: qqbar', xbins, xmin, float(xmax))
    h_sigMC1 = TH1F('sigMC1', 'signal MC: D1(2420)', xbins, xmin, float(xmax))
    h_sigMC2 = TH1F('sigMC2', 'signal MC: psi(3770)', xbins, xmin, float(xmax))

    set_histo_style(h_data, h_incMC1, h_incMC2, h_sigMC1, h_sigMC2, xtitle,
                    ytitle, ymax)
    rm_pipi_fill(t_data, t_incMC1, t_incMC2, t_sigMC1, t_sigMC2, h_data,
                 h_incMC1, h_incMC2, h_sigMC1, h_sigMC2, runNolow, runNoup)

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    h_sigMC1.Scale(scale_factor(ecms, 'D1_2420'))
    h_sigMC2.Scale(scale_factor(ecms, 'psipp'))
    h_incMC1.Scale(scale_factor(ecms, 'DD'))
    h_incMC2.Scale(scale_factor(ecms, 'qq'))
    h_data.Draw('E1')
    h_incMC1.SetFillColor(ROOT.kBlue)
    h_incMC2.SetFillColor(ROOT.kYellow)
    h_sigMC1.SetFillColor(ROOT.kGreen)
    h_sigMC2.SetFillColor(ROOT.kRed)
    hs = THStack('hs', 'Stacked')
    hs.Add(h_sigMC1)
    hs.Add(h_sigMC2)
    hs.Add(h_incMC2)
    hs.Add(h_incMC1)
    hs.Draw('same')
    h_data.Draw('sameE1')

    legend = TLegend(0.55, 0.6, 0.8, 0.75)
    set_legend(legend, h_data, h_incMC1, h_incMC2, h_sigMC1, h_sigMC2,
               leg_title)
    legend.Draw()

    mbc.SaveAs('./figs/m_Dpi0_' + str(ecms) + '.pdf')
Ejemplo n.º 15
0
for ch in [
        'STHct_j3b3_01', 'STHct_j4b2_01', 'STHct_j4b3_01', 'STHut_j3b3_01',
        'STHut_j4b2_01', 'STHut_j4b3_01'
]:

    gen = False

    bdt_data = TH1F('bdt_data', ch + ' BDT Score', 20, -0.3, 0.3)
    bdt_sig = TH1F('bdt_sig', '', 20, -0.3, 0.3)
    bdt_sig_gen = TH1F('bdt_sig_gen', '', 20, -0.3, 0.3)

    keras_data = TH1F('keras_data', ch + ' Keras Score', 20, 0, 1)
    keras_sig = TH1F('keras_sig', '', 20, 0, 1)
    keras_sig_gen = TH1F('keras_sig_gen', '', 20, 0, 1)

    hs_bdt_bkg = THStack()
    hs_keras_bkg = THStack()

    shape_file = TFile.Open(
        '/home/minerva1993/fcnc/analysis_2017/limitSetting/limitSettingInput/shape_'
        + tmva_version + '_' + ch + '.root')

    ########################################
    bdt_ttbb = shape_file.Get('bdt_ttbb')
    bdt_ttbj = shape_file.Get('bdt_ttbj')
    bdt_ttcc = shape_file.Get('bdt_ttcc')
    bdt_ttLF = shape_file.Get('bdt_ttLF')
    bdt_singletop = shape_file.Get('bdt_singletop')
    bdt_others = shape_file.Get('bdt_others')
    bdt_data = shape_file.Get('bdt_data_obs')
    bdt_sig = shape_file.Get('bdt_sig')
Ejemplo n.º 16
0
def make_plot_all_rods(error_dict, rod_dict, name):
    

    leg = TLegend(0,0,0,0)
    if 'lock' in name:
        leg = TLegend(0.18,0.85,0.50,0.55)
    else:
        leg = TLegend(0.18,0.85,0.40,0.55)
    leg.SetLineColor(0)
    leg.SetFillStyle(0)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetNColumns(3)
    gStyle.SetLegendTextSize(0.045)

   
    v_hists = []
    #for e,c in zip(error_bits, error_colors):
    for e in error_bits:
        h = TH1F('h'+e,'h'+e, len(rod_dict), 0, len(rod_dict))
        h.SetFillStyle(1001)
        h.SetLineWidth(0)
        v_hists.append(h)
        v_hists[-1].SetDirectory(0)
        if bin(int('0x'+e, 16))[2:].zfill(4) == '0111':
            leg.AddEntry(v_hists[-1],'GOL 3',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1011':
            leg.AddEntry(v_hists[-1],'GOL 2',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1101':
            leg.AddEntry(v_hists[-1],'GOL 1',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1110':
            leg.AddEntry(v_hists[-1],'GOL 0',"f");
        else:
            leg.AddEntry(v_hists[-1],bin(int('0x'+e, 16))[2:].zfill(4),"f");
    h = leg.GetY2()-leg.GetY1();
    w = leg.GetX2()-leg.GetX1()*.6;
    leg.SetMargin(leg.GetNColumns()*h/(leg.GetNRows()*w))
    

    for key,val in error_dict.items():
        idx_rod = 0
        for i, key2 in enumerate(rod_dict):
            if key2 == key[:8]:
                idx_rod = i
        v_hists[int(key[11:12], 16)].Fill(idx_rod, val)
  
    stack  = THStack("stack","stack")
    for hist in v_hists:
        stack.Add(hist)

    if 'buff' in name:
        c1 = TCanvas( 'c1', 'c1', 2000, 500)
    else:
        c1 = TCanvas( 'c1', 'c1', 1000, 500)


    h1 = TH1F('h_1','h_1', len(rod_dict), 0, len(rod_dict))
    for i, key in enumerate(rod_dict):
        h1.GetXaxis().SetBinLabel(i+1,key)
        h1.SetBinContent(i+1,rod_dict[key])

 
    h1.GetXaxis().LabelsOption("v")
    h1.GetXaxis().SetTitle("ROD")
    h1.GetXaxis().SetTitleOffset(2.2)
    h1.GetYaxis().SetTitle("# of rocketio errors")
    h1.SetLineColor(kRed)
    h1.SetLineWidth(1)

    leg.AddEntry(h1,'total',"l");
    
    c1.SetBottomMargin(0.23)  
    h1.GetXaxis().SetTitle("ROD")
    h1.Draw("HIST")
    stack.Draw("PFC PLC SAME HIST")
    h1.Draw("SAMEHIST")
    AtlasStyle.ATLAS_LABEL(0.19,.88, 1, "Internal")
    leg.Draw()
    c1.Update()
    c1.Print("plots/"+name +".pdf")
    c1.Clear()
    SipMCTTbar.append(histoMCTTbar_input.Get('Z_ExtraEl_SIP_MC_TTbar_hist'))
    SipMCTTbar.append(histoMCTTbar_input.Get('Z_ExtraEl_SIP_MC_TTbar_hist_EB'))
    SipMCTTbar.append(histoMCTTbar_input.Get('Z_ExtraEl_SIP_MC_TTbar_hist_EE'))
    SipMCTTbar.append(histoMCTTbar_input.Get('Z_ExtraMu_SIP_MC_TTbar_hist'))
    SipMCTTbar.append(histoMCTTbar_input.Get('Z_ExtraMu_SIP_MC_TTbar_hist_MB'))
    SipMCTTbar.append(histoMCTTbar_input.Get('Z_ExtraMu_SIP_MC_TTbar_hist_ME'))

# ******************************
# do DATA vs MC comparison plots
# ******************************

for i in range(len(SipDATA)):

    canvas = TCanvas("canvas", "canvas", 800, 800)

    hs = THStack("hs", "")

    norm = 1  # Normalize to MC cross-section
    #norm = SipDATA[i].Integral() / (SipMCTTbar[i].Integral() + SipMCDY[i].Integral()) # Normalize MC to data

    #DATA hist
    SipDATA[i].SetMarkerStyle(20)
    SipDATA[i].SetMarkerSize(0.6)

    #MC TTbar hist
    SipMCTTbar[i].Scale(norm)  # MC normalization
    SipMCTTbar[i].SetFillColor(kAzure - 3)
    SipMCTTbar[i].SetLineColor(kBlack)
    hs.Add(SipMCTTbar[i])

    #MC DY hist
Ejemplo n.º 18
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():
        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)

    # Draw
    stack_X0.Draw("HIST")

    # Legenda
    theLegend = TLegend(0.70, 0.70, 0.89, 0.89)
    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))
Ejemplo n.º 19
0
i = 0  #counter for histos lists

for key in keyList :

    # debug
    # print key, massFitDATA_dict[key]
    # print key, widthFitDATA_dict[key]                  
    # print key, massFitMC_dict[key]
    # print key, widthFitMC_dict[key]


    if (ZTree and massFitDATA_dict[key]==0) : continue

    canvas = TCanvas("canvas","canvas",800,800)
    
    hs = THStack("hs","")

    norm = 1 # normalize to MC xsection 
    # norm = ZMass_DATA[i].Integral() / (ZMass_MC_TTJets[i].Integral() + ZMass_MC_DY[i].Integral()) #normalize MC to data


    #DATA hist
    ZMass_DATA[i].SetMarkerStyle(20)
    ZMass_DATA[i].SetMarkerSize(0.6)
            
    #TTJets MC hist 
    ZMass_MC_TTJets[i].Scale(norm) #normalize MC 
    ZMass_MC_TTJets[i].SetFillColor(3)
    ZMass_MC_TTJets[i].SetLineColor(kBlack)
    hs.Add(ZMass_MC_TTJets[i])
Ejemplo n.º 20
0
def createPlots_(plot):
    """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.

    """

    IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"]
    theDirname = "Figures"

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

    hist_X0_IB = None
    # 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)

        # Merge together the "inner barrel detectors".
        if subDetector in IBs:
            hist_X0_IB = assignOrAddIfExists_(hist_X0_IB, prof_X0_XXX)

        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_IB.GetNbinsX(),
                             hist_X0_IB.GetXaxis().GetXmin(),
                             hist_X0_IB.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 + Pixel + TIB/TID + TOB + TEC + Outside
    # stack
    stackTitle_SubDetectors = "Tracker 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.180, 0.8, 0.98, 0.92)
    theLegend_SubDetectors.SetNColumns(3)
    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.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/Tracker_SubDetectors_%s.pdf" %
                            (theDirname, plot))
    can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.root" %
                            (theDirname, plot))

    # Second Plot: BeamPipe + SEN + ELE + CAB + COL + SUP + OTH/AIR +
    # Outside stack
    stackTitle_Materials = "Tracker Material Budget;%s;%s" % (
        plots[plot].abscissa, plots[plot].ordinate)
    stack_X0_Materials = THStack("stack_X0", stackTitle_Materials)
    stack_X0_Materials.Add(hist_X0_detectors["BeamPipe"])
    for label, [num, color, leg] in hist_label_to_num.iteritems():
        stack_X0_Materials.Add(hist_X0_elements[label])

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

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

    # Legenda
    theLegend_Materials = TLegend(0.180, 0.8, 0.95, 0.92)
    theLegend_Materials.SetNColumns(3)
    theLegend_Materials.SetFillColor(0)
    theLegend_Materials.SetBorderSize(0)

    theLegend_Materials.AddEntry(hist_X0_detectors["BeamPipe"], "Beam Pipe",
                                 "f")
    for label, [num, color, leg] in hist_label_to_num.iteritems():
        theLegend_Materials.AddEntry(hist_X0_elements[label], leg, "f")
    theLegend_Materials.Draw()

    # text
    text_Materials = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC")
    text_Materials.SetFillColor(0)
    text_Materials.SetBorderSize(0)
    text_Materials.AddText("CMS Simulation")
    text_Materials.SetTextAlign(11)
    text_Materials.Draw()

    # Store
    can_Materials.Update()
    can_Materials.SaveAs("%s/Tracker_Materials_%s.pdf" % (theDirname, plot))
    can_Materials.SaveAs("%s/Tracker_Materials_%s.root" % (theDirname, plot))

    return cumulative_matbdg
Ejemplo n.º 21
0
# FILTER EVENTS
# configure total rate hist
totalRateHist.SetMarkerStyle(22)
totalRateHist.SetMarkerSize(1.2)
if (last_lb - first_lb) > 600:
    totalRateHist.SetMarkerSize(0.6)
totalRateHist.SetMarkerColor(ROOT.kBlack)
totalRateHist.SetLineColor(ROOT.kBlack)
for bin in range(1, totalRateHist.GetNbinsX() + 1):
    totalRateHist.SetBinError(bin, 0)  # no appreciable errors on rate
# add total rpvll event hist entry to legend
l1.AddEntry(totalRateHist, "Overall RPVLL Events", "lp")

# initialize stack for all filter rate hists
hs1 = THStack("hs1", "")
# add individual filter rate hists to stack
for i, hist in enumerate(rateHists):
    hist.SetFillColor(colors[i % len(colors)])
    hist.SetLineColor(colors[i % len(colors)])
    if i >= len(colors):
        hist.SetFillStyle(3004)
    hs1.Add(hist)
    # add individual event entries to legend
    l1.AddEntry(hist, filterNames_mAug[i], "f")

# draw individual filter stack + overall rate hist
hs1.Draw("HIST")
totalRateHist.Draw("pSAME")

## configure axes
Ejemplo n.º 22
0
cAll = TCanvas("cAllPosts", "All Posts", 600, 600)
hAllPosts.Draw("histo")

cEmojis = TCanvas("cEmojis", "Emojis Relative", 600, 600)

colour = 1

leg = TLegend(0.6, 0.7, 0.9, 0.9)
leg.SetHeader("Emoticonos: uso relativo")
gStyle.SetFillStyle(0)
gStyle.SetLineWidth(0)
gStyle.SetOptStat(0)
gStyle.SetOptTitle(0)

hs = THStack("hs", "")

for h in histos:
    h.Divide(hAllPosts)
    h.SetLineColor(1)
    h.SetFillColor(colour)
    h.SetLineWidth(1)
    for binn in range(1, 8):
        h.GetXaxis().SetBinLabel(binn, binlabels[binn-1])
    leg.AddEntry(h, h.GetTitle(), "f")
    hs.Add(h)
    colour += 1

hs.Draw()
leg.Draw()
Ejemplo n.º 23
0
def plot(path, ecms, xmin, xmax, num_charm):
    try:
        f_data = TFile(path[0])
        t_data = f_data.Get('save')
        entries_data = t_data.GetEntries()
        logging.info('data entries :' + str(entries_data))
    except:
        logging.error(path[0] + 'is invalid!')
        sys.exit()
    try:
        f_side1 = TFile(path[1])
        t_side1 = f_side1.Get('save')
        entries_side1 = t_side1.GetEntries()
        logging.info('data(side1) entries :' + str(entries_side1))
    except:
        logging.error(path[1] + ' is invalid!')
        sys.exit()
    try:
        f_side2 = TFile(path[2])
        t_side2 = f_side2.Get('save')
        entries_side2 = t_side2.GetEntries()
        logging.info('data(side2) entries :' + str(entries_side2))
    except:
        logging.error(path[2] + ' is invalid!')
        sys.exit()
    try:
        f_side3 = TFile(path[3])
        t_side3 = f_side3.Get('save')
        entries_side3 = t_side3.GetEntries()
        logging.info('data(side3) entries :' + str(entries_side3))
    except:
        logging.error(path[3] + ' is invalid!')
        sys.exit()
    try:
        f_side4 = TFile(path[4])
        t_side4 = f_side4.Get('save')
        entries_side4 = t_side4.GetEntries()
        logging.info('data(side4) entries :' + str(entries_side4))
    except:
        logging.error(path[4] + ' is invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    xbins = 100
    ytitle = 'Eentries'
    xtitle = 'E(OtherTrks) (GeV)'

    h_data = TH1F('data', 'data', xbins, xmin, xmax)
    set_histo_style(h_data, xtitle, ytitle, 1, -1)
    E_othertrks_fill(t_data, h_data, num_charm)

    h_side1 = TH1F('side1', 'side1', xbins, xmin, xmax)
    set_histo_style(h_side1, xtitle, ytitle, 3, 3004)
    E_othertrks_fill(t_side1, h_side1, num_charm)

    h_side2 = TH1F('side2', 'side2', xbins, xmin, xmax)
    set_histo_style(h_side2, xtitle, ytitle, 3, 3004)
    E_othertrks_fill(t_side2, h_side2, num_charm)

    h_side3 = TH1F('side3', 'side3', xbins, xmin, xmax)
    set_histo_style(h_side3, xtitle, ytitle, 3, 3004)
    E_othertrks_fill(t_side3, h_side3, num_charm)

    h_side4 = TH1F('side4', 'side4', xbins, xmin, xmax)
    set_histo_style(h_side4, xtitle, ytitle, 3, 3004)
    E_othertrks_fill(t_side4, h_side4, num_charm)

    h_side1.Add(h_side2)
    h_side1.Scale(0.5)
    h_side3.Add(h_side4)
    h_side3.Scale(0.25)
    h_side1.Add(h_side3, -1)
    h_data.Draw('E1')
    hs = THStack('hs', 'Stacked')
    hs.Add(h_side1)
    hs.Draw('same')
    h_data.Draw('sameE1')

    legend = TLegend(0.5, 0.6, 0.8, 0.85)
    leg_title = str(ecms) + ' MeV'
    set_legend(legend, h_data, h_side1, leg_title)
    legend.Draw()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    mbc.SaveAs('./figs/E_othertrks_' + str(ecms) + '_' + str(num_charm) +
               '.pdf')

    raw_input('Enter anything to end...')
Ejemplo n.º 24
0
            legend = TLegend(0.5, 0.7, 0.9, 0.9)

            drawOpt = 'HE1'

            rf_stack = []
            rf_sup = []

            maxY = 0

            for file in inputFiles:
                if (file in tofill):
                    rf_stack.append(TFile(path + file, 'READ'))
                else:
                    rf_sup.append(TFile(path + file, 'READ'))

            stack = THStack('stack', plottitle)
            hist_counter = 0

            for rf in rf_stack:
                if (rebin):
                    hist_oldbin = rf.Get(dir + '/' + histname)
                    hist = hist_oldbin.Rebin(nBins, "new binning", xbins)
                else:
                    hist = rf.Get(dir + '/' + histname)

                hist.SetFillColor(867 + hist_counter)
                hist.SetLineColor(867 + hist_counter)
                hist.SetTitle('stack')
                stack.Add(hist)
                hist_counter = hist_counter + 1
Ejemplo n.º 25
0
def plotStack():
    inputfile = TFile(filename, "read")
    if inputfile.IsZombie():
        print("inputfile is Zombie")
        sys.exit()

    # loop over features
    for feature, values in features.items():
        file = open(
            "%s%s_%s_isNorm%s_wtStat%s_isBlind%s.txt" %
            (outputdir, feature, plotname, normalization, showStats, blind),
            "w")

        file.write(
            "\\begin{table}[]\n\\resizebox{!}{.33\\paperheight}{\n \\begin{tabular}{|l|l|l|}\n\\hline\nProcess & Yield & Entries \\\\ \\hline \n"
        )
        # set up legend
        legend = TLegend(0.2, 0.6, 0.7, 0.88)
        legend.SetHeader("%i  %s" % (year, region))
        legend.SetNColumns(4)
        legend.SetBorderSize(0)

        c, pad1, pad2 = createCanvasPads()

        hstack = THStack("hstack", "hstack")
        hstack.SetTitle(
            "#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary}                                                            %i at %.2f fb^{-1}(13TeV)}"
            % (year, luminosity[year]))

        histName = "TTH_" + feature  # assuming TTH is always there
        if not inputfile.GetListOfKeys().Contains(histName):
            print("%s doesn't have histogram %s, please use another hist " %
                  (inputfile, histName))
            sys.exit()

        h0 = inputfile.Get(histName)

        h_totalsig = h0.Clone("h_totalsig")
        h_totalsig.SetDirectory(0)
        h_totalsig.Reset()
        h_totalsig.SetMarkerStyle(20)
        h_totalsig.Sumw2()

        h_totalbkg = h0.Clone("h_totalbkg")
        h_totalbkg.SetDirectory(0)
        h_totalbkg.Reset()
        h_totalbkg.SetMarkerStyle(20)
        h_totalbkg.Sumw2()

        h_totalmc = h0.Clone("h_totalmc")
        h_totalmc.SetDirectory(0)
        h_totalmc.Reset()
        h_totalmc.SetLineColor(kBlack)
        h_totalmc.SetFillColor(kGray + 3)
        h_totalmc.SetFillStyle(3001)
        h_totalmc.SetTitle("")
        #h_totalmc.SetMinimum(0.8)
        #h_totalmc.SetMaximum(1.35)
        h_totalmc.Sumw2()
        h_totalmc.SetStats(0)

        h_dataobs = h0.Clone("h_dataobs")
        h_dataobs.SetDirectory(0)
        h_dataobs.Reset()
        h_dataobs.SetMarkerStyle(20)

        # loop over samples
        for sample in Samples:
            hist = h_totalmc.Clone(sample)
            hist.SetDirectory(0)
            hist.Reset()
            if sample not in Process:
                print("sample %s is not in Process " % sample)
                continue
            # loop over data:
            if sample == "Data" or sample == "data":
                for p in Process[sample]:
                    if p not in sampleName:
                        print("process %s is not in sampleName " % s)
                        continue
                    hist_name = p + "_" + feature
                    if not inputfile.GetListOfKeys().Contains(hist_name):
                        print("%s doesn't have histogram %s" %
                              (inputfile, hist_name))
                        continue
                    h1 = inputfile.Get(hist_name).Clone(hist_name)
                    h1.SetDirectory(0)
                    h_dataobs.Add(h1)
                    error = Double(0)
                    h1.IntegralAndError(0, h1.GetNbinsX(), error)
                    if not blind:
                        file.write(
                            "%s &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                            (p.replace('_', '\\_'), h1.Integral(), error,
                             h1.GetEntries()))
            # loop over mc
            # loop over signal
            elif sample in Signals:
                for p in Process[sample]:
                    if p not in sampleName:
                        print("process %s is not in sampleName " % s)
                        continue
                    hist_name = p + "_" + feature
                    if not inputfile.GetListOfKeys().Contains(hist_name):
                        print("%s doesn't have histogram %s" %
                              (filename, hist_name))
                        continue
                    h1 = inputfile.Get(hist_name).Clone(hist_name)
                    h1.SetDirectory(0)
                    if p == "FakeSub" and sample == "Fakes":
                        hist.Add(h1, -1)
                        h_totalsig.Add(h1, -1)
                        h_totalmc.Add(h1, -1)
                    else:
                        hist.Add(h1)
                        h_totalsig.Add(h1)
                        h_totalmc.Add(h1)
                    error = Double(0)
                    h1.IntegralAndError(0, h1.GetNbinsX(), error)
                    if h1.Integral() < 0.05 or h1.GetEntries() < 100:
                        file.write(
                            "\\textcolor{red}{%s} &  %.2f +/- %.2f &   %i \\\\ \\hline \n"
                            % (p.replace('_', '\\_'), h1.Integral(), error,
                               h1.GetEntries()))
                    else:
                        file.write(
                            "%s &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                            (p.replace('_', '\\_'), h1.Integral(), error,
                             h1.GetEntries()))
                hist.SetFillColor(Color[sample])
                hist.SetLineColor(kBlack)
                hist.SetFillStyle(Style[sample])
                if sample == "TH" and tH != 1:
                    hist.Scale(tH)
                    hist.SetFillColor(Color[sample])
                    hist.SetLineColor(kBlack)
                    hist.SetFillStyle(Style[sample])
                    hstack.Add(hist)
                    legend.AddEntry(hist, "%s * %i" % (sample, tH), "f")
                else:
                    hstack.Add(hist)
                    legend.AddEntry(hist, sample, "f")

        # create required parts
        # loop over bkg
            else:
                for p in Process[sample]:
                    if p not in sampleName:
                        print("process %s is not in sampleName " % p)
                        continue
                    hist_name = p + "_" + feature
                    if not inputfile.GetListOfKeys().Contains(hist_name):
                        print("%s doesn't have histogram %s" %
                              (filename, hist_name))
                        continue
                    h1 = inputfile.Get(hist_name).Clone(hist_name)
                    h1.SetDirectory(0)
                    if p == "FakeSub" and sample == "Fakes":
                        hist.Add(h1, -1)
                        h_totalmc.Add(h1, -1)
                        h_totalbkg.Add(h1, -1)
                    else:
                        hist.Add(h1)
                        h_totalmc.Add(h1)
                        h_totalbkg.Add(h1)
                    error = Double(0)
                    h1.IntegralAndError(0, h1.GetNbinsX(), error)
                    if h1.Integral() < 0.05 or h1.GetEntries() < 100:
                        file.write(
                            "\\textcolor{red}{%s} &  %.2f +/- %.2f &   %i \\\\ \\hline \n"
                            % (p.replace('_', '\\_'), h1.Integral(), error,
                               h1.GetEntries()))
                    else:
                        file.write(
                            "%s &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                            (p.replace('_', '\\_'), h1.Integral(), error,
                             h1.GetEntries()))
                hist.SetFillColor(Color[sample])
                hist.SetLineColor(kBlack)
                hist.SetFillStyle(Style[sample])
                if sample == "TH" and tH != 1:
                    hist.Scale(tH)
                    hist.SetFillColor(Color[sample])
                    hist.SetLineColor(kBlack)
                    hist.SetFillStyle(Style[sample])
                    hstack.Add(hist)
                    legend.AddEntry(hist, "%s * %i" % (sample, tH), "f")
                else:
                    hstack.Add(hist)
                    legend.AddEntry(hist, sample, "f")

        error = Double(0)
        h_totalsig.IntegralAndError(0, h_totalsig.GetNbinsX(), error)
        file.write("signal &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                   (h_totalsig.Integral(), error, h_totalsig.GetEntries()))

        error = Double(0)
        h_totalbkg.IntegralAndError(0, h_totalbkg.GetNbinsX(), error)
        file.write("bkg &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                   (h_totalbkg.Integral(), error, h_totalbkg.GetEntries()))

        # create required parts

        if blind:
            h_sqrtB = createSqrt(h_totalbkg)
            h_MCerr = createTotalMCErr(h_sqrtB, values["xlabel"])
            h_ratio = createRatio(h_totalsig, h_sqrtB, values["xlabel"],
                                  normalization)
        else:
            h_MCerr = createTotalMCErr(h_totalmc, feature)
            h_ratio = createRatio(h_dataobs, h_totalmc, values["xlabel"],
                                  normalization)
            legend.AddEntry(h_dataobs, "observed", "lep")

        legend.AddEntry(h_totalmc, "Uncertainty", "f")

        # draw everything

        pad1.cd()
        if values["logy"] == 1:
            pad1.SetLogy()
        maximum = h_dataobs.GetMaximum()
        upperbound = 2. * maximum
        lowerbound = -maximum / 40.
        if values["logy"] == 1:
            upperbound = 1000 * maximum
            lowerbound = 0.1

        hstack.SetMinimum(lowerbound)
        hstack.SetMaximum(upperbound)
        hstack.Draw("HISTY")
        # Adjust y-axis settings
        y = hstack.GetYaxis()
        y.SetTitle("Events ")
        y.SetTitleSize(25)
        y.SetTitleFont(43)
        y.SetTitleOffset(1.55)
        y.SetLabelFont(43)
        y.SetLabelSize(20)

        nbins = h_ratio.GetNbinsX()
        #hstack.GetXaxis().SetRange(0, nbins+1)
        hstack.GetXaxis().SetRangeUser(values["min"], values["max"])

        h_totalmc.Draw("e2same")
        if not blind:
            h_dataobs.Draw("same")
        legend.Draw("same")

        pad2.cd()
        if blind:
            h_ratio.SetMinimum(0.)
            #maximum = h_ratio.GetMaximum()
            #upperbound = 1.5*maximum
            #h_ratio.SetMaximum(upperbound)
            h_ratio.SetMaximum(3.)
            h_ratio.GetXaxis().SetRangeUser(values["min"], values["max"])
            h_ratio.Draw("")
        else:
            h_MCerr.SetMinimum(0.5)
            h_MCerr.SetMaximum(1.8)
            h_MCerr.GetXaxis().SetRangeUser(values["min"], values["max"])
            h_MCerr.Draw("e2")
            h_ratio.Draw("same")

        c.SaveAs(
            "%s%s_%s_isNorm%s_wtStat%s_isBlind%s_stack.png" %
            (outputdir, feature, plotname, normalization, showStats, blind))
        file.write("\\end{tabular}\n}\n\\end{table}\n")
        file.close()
    inputfile.Close()
Ejemplo n.º 26
0
def read_file(arr, meas_type, mapsa_fitter_inst, path):
    if not os.path.isfile(str(path + arr[0])):
        print "Root file not found at", str(path + arr[0])
        #sys.exit(1)
        return
    f = TFile(str(path + arr[0]), 'READ')
    if (f.IsZombie()):
        print "Error opening file"
        return
    else:
        print "Reading File ", arr[0]
    #f.ls()
    tree = f.Get('tree')
    f_GlobalData_Map = ROOT.TMap()
    f_GlobalData_Map.Add(ROOT.TObjString("tree"), tree)
    #tree.Print()
    outfile = TString(arr[0])
    outfile.ReplaceAll(".root", "")
    outfile.ReplaceAll(" ", "")
    # print outfile
    if (meas_type == 0):
        outfile = "pedestal"
    if (not g.FindKey(str(outfile))):
        g.mkdir(str(outfile))
        g.cd(str(outfile))
    else:
        return
    channels = 288
    if (arr[2] == 'inv'):
        channels = 96
        mapsa_mat = [[1, 0, 0], [1, 0, 0]]
    elif (arr[2] == 'norm'):
        channels = 288
        mapsa_mat = [[1, 1, 1], [1, 0, 1]]
    #print "channels", channels
    #print "mapsa_mat", mapsa_mat

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ## c1.SaveAs("double_gauss_same_mean.pdf")
    ## time.sleep(2)
    g.cd(str(outfile) + "/Overview")
    #for objs in objarr:
    #objs.Write(objs.GetName())
    #norm_2d.GetZaxis().SetRangeUser(1E5,2E6)
    #mean_2d.GetZaxis().SetRangeUser(54,64)
    ## norm_2d.GetZaxis().SetRangeUser(TMath.Power(10,(round(TMath.Log10(norm_2d.GetStdDev(3))-2)), TMath.Power(10,(round(TMath.Log10(norm_2d.GetStdDev(3)))-1)))
    ## mean_2d.GetZaxis().SetRangeUser(TMath.Power(10,(round(TMath.Log10(mean_2d.mean_2d.GetStdDev(3)))-1))-5,TMath.Power(10,(round(TMath.Log10(mean_2d.GetStdDev(3)))-1))+5)
    #sigma_2d.GetZaxis().SetRangeUser(0,5)
    #chisquare.GetZaxis().SetRangeUser(0,10000 )
    #for objs in objarr2d:
    #objs.Write(objs.GetName())
    #c1.Write("c1")
    #outfile1=outfile+TString(".pdf")
    #c2.SaveAs(str(outfile1))
    #c2.Write("c2")
    #c3.SaveAs("c3"+str(outfile1))
    #c3.Write("c3")
    #c4.SaveAs("c4"+str(outfile1))
    #c4.Write("c4")
    ## while (TObject(iterator.Next())):
    ##       print iterator.Next().Title()
    #stack.Write("stack")
    #g.cd(str(outfile))
    #channelcounts.Write(str(outfile))
    #f.Close()
    c1.Close()
    c2.Close()
    c3.Close()
    c4.Close()
    c5.Close()
    f_GlobalData_Map.DeleteAll()
    f.Close()
Ejemplo n.º 27
0
def MakeOneDHist(pathToDir, distribution):

    numFittingSamples = 0

    HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right,
                             header_y_top, HeaderText, "NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right,
                           topLeft_y_top, LumiText, "NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)

    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)

    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"
    elif arguments.normalizeToData:
        NormText = "MC scaled to data"
        NormLabel.SetLabel(NormText)

    YieldsLabel = TPaveText(0.39, 0.7, 0.59, 0.9, "NDC")
    YieldsLabel.SetBorderSize(0)
    YieldsLabel.SetFillColor(0)
    YieldsLabel.SetFillStyle(0)
    YieldsLabel.SetTextAlign(12)

    RatiosLabel = TPaveText()
    RatiosLabel.SetDrawOption("NDC")
    RatiosLabel.SetBorderSize(0)
    RatiosLabel.SetFillColor(0)
    RatiosLabel.SetFillStyle(0)
    RatiosLabel.SetTextAlign(32)

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    fittingIntegral = 0
    scaleFactor = 1

    HistogramsToFit = []
    TargetDataset = distribution['target_dataset']

    FittingLegendEntries = []
    DataLegendEntries = []

    FittingHistogramDatasets = []

    Stack_list = []
    Stack_list.append(THStack("stack_before", distribution['name']))
    Stack_list.append(THStack("stack_after", distribution['name']))

    fileName = condor_dir + "/" + distribution['target_dataset'] + ".root"
    if not os.path.exists(fileName):
        return
    inputFile = TFile(fileName)
    if inputFile.IsZombie() or not inputFile.GetNkeys():
        return

    Target = inputFile.Get("OSUAnalysis/" + distribution['channel'] + "/" +
                           distribution['name']).Clone()
    Target.SetDirectory(0)
    inputFile.Close()

    Target.SetMarkerStyle(20)
    Target.SetMarkerSize(0.8)
    Target.SetFillStyle(0)
    Target.SetLineColor(colors[TargetDataset])
    Target.SetLineStyle(1)
    Target.SetLineWidth(2)
    targetIntegral = Target.Integral()
    if (arguments.normalizeToUnitArea and Target.Integral() > 0):
        Target.Scale(1. / Target.Integral())
    if arguments.rebinFactor:
        RebinFactor = int(arguments.rebinFactor)
        #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
        if Target.GetNbinsX() >= RebinFactor * 5 and Target.GetName().find(
                "GenMatch") is -1:
            Target.Rebin(RebinFactor)

    ### formatting target histogram and adding to legend
    legendIndex = 0
    Legend.AddEntry(Target, labels[TargetDataset], "LEP")
    legendIndex = legendIndex + 1

    if not outputFile.Get("OSUAnalysis"):
        outputFile.mkdir("OSUAnalysis")
    if not outputFile.Get("OSUAnalysis/" + distribution['channel']):
        outputFile.Get("OSUAnalysis").mkdir(distribution['channel'])

    for sample in distribution[
            'datasets']:  # loop over different samples requested to be fit

        dataset_file = "%s/%s.root" % (condor_dir, sample)
        inputFile = TFile(dataset_file)
        HistogramObj = inputFile.Get(pathToDir + "/" +
                                     distribution['channel'] + "/" +
                                     distribution['name'])
        if not HistogramObj:
            print "WARNING:  Could not find histogram " + pathToDir + "/" + distribution[
                'channel'] + "/" + distribution[
                    'name'] + " in file " + dataset_file + ".  Will skip it and continue."
            continue
        Histogram = HistogramObj.Clone()
        Histogram.SetDirectory(0)
        inputFile.Close()
        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetName(
            ).find("GenMatch") is -1:
                Histogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1:  #x axis has a unit
            yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(
                1)) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex]
        else:
            yAxisLabel = "Entries per bin (" + str(
                Histogram.GetXaxis().GetBinWidth(1)) + " width)"

        if not arguments.makeFancy:
            histoTitle = Histogram.GetTitle()
        else:
            histoTitle = ""

        legLabel = labels[sample]
        if (arguments.printYields):
            yieldHist = Histogram.Integral()
            legLabel = legLabel + " (%.1f)" % yieldHist
        FittingLegendEntries.append(legLabel)

        if (types[sample] == "bgMC"):

            numFittingSamples += 1
            fittingIntegral += Histogram.Integral()

            Histogram.SetLineStyle(1)
            if (arguments.noStack):
                Histogram.SetFillStyle(0)
                Histogram.SetLineColor(colors[sample])
                Histogram.SetLineWidth(2)
            else:
                Histogram.SetFillStyle(1001)
                Histogram.SetFillColor(colors[sample])
                Histogram.SetLineColor(1)
                Histogram.SetLineWidth(1)

        elif (types[sample] == "signalMC"):

            numFittingSamples += 1

            Histogram.SetFillStyle(0)
            Histogram.SetLineColor(colors[sample])
            Histogram.SetLineStyle(1)
            Histogram.SetLineWidth(2)
        if (arguments.normalizeToUnitArea and Histogram.Integral() > 0):
            Histogram.Scale(1. / Histogram.Integral())

        HistogramsToFit.append(Histogram)
        FittingHistogramDatasets.append(sample)

    #scaling histograms as per user's specifications
    if targetIntegral > 0 and fittingIntegral > 0:
        scaleFactor = targetIntegral / fittingIntegral
    for fittingHist in HistogramsToFit:
        if arguments.normalizeToData:
            fittingHist.Scale(scaleFactor)

        if arguments.normalizeToUnitArea and not arguments.noStack and fittingIntegral > 0:
            fittingHist.Scale(1. / fittingIntegral)
        elif arguments.normalizeToUnitArea and arguments.noStack and fittingHist.Integral(
        ) > 0:
            fittingHist.Scale(1. / fittingHist.Integral())

    def fitf(x, par):
        xBin = HistogramsToFit[0].FindBin(x[0])
        value = 0.0

        for i in range(0, len(HistogramsToFit)):
            value += par[i] * HistogramsToFit[i].GetBinContent(xBin) + par[
                i +
                len(HistogramsToFit)] * HistogramsToFit[i].GetBinError(xBin)

        return value

    lowerLimit = Target.GetBinLowEdge(1)
    upperLimit = Target.GetBinLowEdge(Target.GetNbinsX()) + Target.GetBinWidth(
        Target.GetNbinsX())
    if 'lowerLimit' in distribution:
        lowerLimit = distribution['lowerLimit']
    if 'upperLimit' in distribution:
        upperLimit = distribution['upperLimit']
    func = TF1("fit", fitf, lowerLimit, upperLimit, 2 * len(HistogramsToFit))

    for i in range(0, len(HistogramsToFit)):
        if 'fixed_datasets' in distribution and distribution['datasets'][
                i] in distribution['fixed_datasets']:
            func.FixParameter(i, 1.0)
        else:
            func.SetParameter(i, 1.0)
#            func.SetParLimits (i, 0.0, 1.0e2) # comment this out so we don't have to pre-normalize the QCD input sample
        func.SetParName(i, labels[FittingHistogramDatasets[i]])

    shiftedScaleFactors = []
    if arguments.parametricErrors:
        # loop over all input histograms and shift them +- 1 sigma
        for i in range(0, len(HistogramsToFit)):
            sfs = []

            # -1 => -1 sigma, +1 => +1 sigma
            for j in [-1, 1]:
                # loop over the parameters holding the errors for each dataset, fixing all to 0
                for k in range(len(HistogramsToFit), 2 * len(HistogramsToFit)):
                    func.FixParameter(k, 0)
                # fix the error of the dataset of interest to +-1
                func.FixParameter(i + len(HistogramsToFit), j)

                # perform new fit
                for k in range(0, distribution['iterations'] - 1):
                    if j == -1:
                        print "Scale down " + labels[FittingHistogramDatasets[
                            i]] + " iteration " + str(k + 1) + "..."
                    if j == 1:
                        print "Scale up " + labels[FittingHistogramDatasets[
                            i]] + " iteration " + str(k + 1) + "..."
                    Target.Fit("fit", "QEMR0")
                Target.Fit("fit", "VEMR0")

                # save the new scale factors for each dataset
                for k in range(0, len(HistogramsToFit)):
                    sfs.append(func.GetParameter(k))

            shiftedScaleFactors.append(sfs)

    # reset the parameters with the errors of each dataset to 0
    for i in range(len(HistogramsToFit), 2 * len(HistogramsToFit)):
        func.FixParameter(i, 0)
    # do the fit to get the central values
    for i in range(0, distribution['iterations'] - 1):
        print "Iteration " + str(i + 1) + "..."
        Target.Fit("fit", "QEMR0")
    Target.Fit("fit", "VEMR0")

    if arguments.parametricErrors:
        # make a list of the largest errors on each contribution by shifting any other contribution
        parErrors = []
        # loop over all the datasets
        for i in range(0, len(HistogramsToFit)):
            centralValue = func.GetParameter(i)
            maxError = 0
            # find the maximum deviation from the central value and save that
            for shiftedScaleFactor in shiftedScaleFactors[i]:
                currentError = abs(shiftedScaleFactor - centralValue)
                if currentError > maxError:
                    maxError = currentError

            parErrors.append(maxError)

    finalMax = 0
    if not arguments.noStack:
        for fittingHist in HistogramsToFit:
            finalMax += fittingHist.GetMaximum()
        else:
            for fittingHist in HistogramsToFit:
                if (fittingHist.GetMaximum() > finalMax):
                    finalMax = fittingHist.GetMaximum()
    if (Target.GetMaximum() > finalMax):
        finalMax = Target.GetMaximum()

    Target.SetMaximum(1.1 * finalMax)
    Target.SetMinimum(0.0001)

    Canvas = TCanvas(distribution['name'] + "_FitFunction")
    Canvas.cd(1)
    Target.Draw()
    func.Draw("same")

    outputFile.cd("OSUAnalysis/" + distribution['channel'])
    Canvas.Write()
    if arguments.savePDFs:
        if histogram == input_histograms[0]:
            Canvas.Print(pdfFileName + "(", "pdf")
        else:
            Canvas.Print(pdfFileName, "pdf")
    Target.SetStats(0)

    ### formatting bgMC histograms and adding to legend
    legendIndex = numFittingSamples - 1
    for Histogram in reversed(HistogramsToFit):
        if (arguments.noStack):
            Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "L")
        else:
            Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "F")
        legendIndex = legendIndex - 1

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    ### Draw everything to the canvases !!!!

    for i in range(0, 2):  # 0 => before, 1 => after

        integrals = []
        ratios = []
        errors = []

        if i == 1:
            # loop over each dataset, saving it's yield and the errors on it
            for j in range(0, len(HistogramsToFit)):

                integrals.append(HistogramsToFit[j].Integral())
                HistogramsToFit[j].Scale(func.GetParameter(j))
                ratios.append(func.GetParameter(j))
                errors.append(func.GetParError(j))

        for fittingHist in HistogramsToFit:
            if not arguments.noStack:
                Stack_list[i].Add(fittingHist)

        #creating the histogram to represent the statistical errors on the stack
        if not arguments.noStack:
            ErrorHisto = HistogramsToFit[0].Clone("errors")
            ErrorHisto.SetFillStyle(3001)
            ErrorHisto.SetFillColor(13)
            ErrorHisto.SetLineWidth(0)
            if i == 1:
                Legend.AddEntry(ErrorHisto, "Stat. Errors", "F")
            for Histogram in HistogramsToFit:
                if Histogram is not HistogramsToFit[0]:
                    ErrorHisto.Add(Histogram)

        if i == 0:
            Canvas = TCanvas(distribution['name'] + "_Before")
        if i == 1:
            Canvas = TCanvas(distribution['name'] + "_After")

        if makeRatioPlots or makeDiffPlots:
            Canvas.SetFillStyle(0)
            Canvas.Divide(1, 2)
            Canvas.cd(1)
            gPad.SetPad(0, 0.25, 1, 1)
            gPad.SetMargin(0.15, 0.05, 0.01, 0.07)
            gPad.SetFillStyle(0)
            gPad.Update()
            gPad.Draw()
            if arguments.setLogY:
                gPad.SetLogy()
            Canvas.cd(2)
            gPad.SetPad(0, 0, 1, 0.25)
            # format: gPad.SetMargin(l,r,b,t)
            gPad.SetMargin(0.15, 0.05, 0.4, 0.01)
            gPad.SetFillStyle(0)
            gPad.SetGridy(1)
            gPad.Update()
            gPad.Draw()

            Canvas.cd(1)

        ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
        finalMax = 0
        if numFittingSamples is not 0 and not arguments.noStack:
            finalMax = ErrorHisto.GetMaximum() + ErrorHisto.GetBinError(
                ErrorHisto.GetMaximumBin())
        else:
            for bgMCHist in HistogramsToFit:
                if (bgMCHist.GetMaximum() > finalMax):
                    finalMax = bgMCHist.GetMaximum()
        if (Target.GetMaximum() > finalMax):
            finalMax = Target.GetMaximum() + Target.GetBinError(
                Target.GetMaximumBin())
        finalMax = 1.15 * finalMax
        if arguments.setYMax:
            finalMax = float(arguments.setYMax)

        if not arguments.noStack:  # draw stacked background samples
            Stack_list[i].SetTitle(histoTitle)
            Stack_list[i].Draw("HIST")
            Stack_list[i].GetXaxis().SetTitle(xAxisLabel)
            Stack_list[i].GetYaxis().SetTitle(yAxisLabel)
            Stack_list[i].SetMaximum(finalMax)
            Stack_list[i].SetMinimum(yAxisMin)
            if makeRatioPlots or makeDiffPlots:
                Stack_list[i].GetHistogram().GetXaxis().SetLabelSize(0)
            #draw shaded error bands
            ErrorHisto.Draw("A E2 SAME")

        else:  #draw the unstacked backgrounds
            HistogramsToFit[0].SetTitle(histoTitle)
            HistogramsToFit[0].Draw("HIST")
            HistogramsToFit[0].GetXaxis().SetTitle(xAxisLabel)
            HistogramsToFit[0].GetYaxis().SetTitle(yAxisLabel)
            HistogramsToFit[0].SetMaximum(finalMax)
            HistogramsToFit[0].SetMinimum(yAxisMin)
            for bgMCHist in HistogramsToFit:
                bgMCHist.Draw("A HIST SAME")

        Target.Draw("A E X0 SAME")

        #legend coordinates, empirically determined :-)
        x_left = 0.6761745
        x_right = 0.9328859
        x_width = x_right - x_left
        y_max = 0.9
        entry_height = 0.05

        if (numFittingSamples is not 0):  #then draw the data & bgMC legend

            numExtraEntries = 2  # count the target and (lack of) title
            Legend.SetX1NDC(x_left)
            numExtraEntries = numExtraEntries + 1  # count the stat. errors entry

            Legend.SetY1NDC(y_max - entry_height *
                            (numExtraEntries + numFittingSamples))
            Legend.SetX2NDC(x_right)
            Legend.SetY2NDC(y_max)
            Legend.Draw()

            RatiosLabel.SetX1NDC(x_left - 0.1)
            RatiosLabel.SetX2NDC(x_right)
            RatiosLabel.SetY2NDC(Legend.GetY1NDC() - 0.1)
            RatiosLabel.SetY1NDC(RatiosLabel.GetY2NDC() - entry_height *
                                 (numFittingSamples))

            # Deciding which text labels to draw and drawing them
            drawLumiLabel = False
            drawNormLabel = False
            offsetNormLabel = False
            drawHeaderLabel = False

            if not arguments.normalizeToUnitArea:  #don't draw the lumi label if there's no data and it's scaled to unit area
                drawLumiLabel = True
                # move the normalization label down before drawing if we drew the lumi. label
                offsetNormLabel = True
            if arguments.normalizeToUnitArea or arguments.normalizeToData:
                drawNormLabel = True
            if arguments.makeFancy:
                drawHeaderLabel = True
                drawLumiLabel = False

            # now that flags are set, draw the appropriate labels

            if drawLumiLabel:
                LumiLabel.Draw()

            if drawNormLabel:
                if offsetNormLabel:
                    NormLabel.SetY1NDC(topLeft_y_bottom - topLeft_y_offset)
                    NormLabel.SetY2NDC(topLeft_y_top - topLeft_y_offset)
                else:
                    NormLabel.SetY1NDC(topLeft_y_bottom)
                    NormLabel.SetY2NDC(topLeft_y_top)
                NormLabel.Draw()

            if drawHeaderLabel:
                HeaderLabel.Draw()

            YieldsLabel.Clear()
            mcYield = Stack_list[i].GetStack().Last().Integral()
            dataYield = Target.Integral()
            if i == 0:
                YieldsLabel.AddText("Before Fit to Data")
            if i == 1:
                YieldsLabel.AddText("After Fit to Data")
            YieldsLabel.AddText("data yield: " + '%.1f' % dataYield)
            YieldsLabel.AddText("bkgd yield: " + '%.1f' % mcYield)
            YieldsLabel.AddText("data/bkgd: " + '%.2f' % (dataYield / mcYield))
            if i == 1:
                for j in range(0, len(FittingLegendEntries)):
                    if abs(ratios[j] - 1) < 0.001 and abs(
                            errors[j]
                    ) < 0.001:  #then it probably was held fixed
                        continue
                    if arguments.showFittedYields:
                        yield_ = ratios[j] * integrals[j]
                        yielderror_ = errors[j] * yield_
                        text = FittingLegendEntries[
                            j] + " yield: " + '%.0f' % yield_ + ' #pm %.0f' % yielderror_
                    else:
                        text = FittingLegendEntries[
                            j] + " ratio: " + '%.2f' % ratios[
                                j] + ' #pm %.2f' % errors[j]
                    text = text + " (fit)"
                    if arguments.parametricErrors:
                        yield_ = ratios[j] * integrals[j]
                        yieldParError_ = parErrors[j] * yield_
                        if arguments.showFittedYields:
                            text += ' #pm %.2f' % yieldParError_
                        else:
                            text += ' #pm %.2f' % parErrors[j]
                        text = text + " (sys)"
                    RatiosLabel.AddText(text)
            YieldsLabel.Draw()
            RatiosLabel.Draw()

        # drawing the ratio or difference plot if requested
        if (makeRatioPlots or makeDiffPlots):
            Canvas.cd(2)
            BgSum = Stack_list[i].GetStack().Last()
            if makeRatioPlots:
                if arguments.ratioRelErrMax:
                    Comparison = ratioHistogram(Target, BgSum,
                                                arguments.ratioRelErrMax)
                else:
                    Comparison = ratioHistogram(Target, BgSum)
            elif makeDiffPlots:
                Comparison = Target.Clone("diff")
                Comparison.Add(BgSum, -1)
                Comparison.SetTitle("")
                Comparison.GetYaxis().SetTitle("Data-Bkgd")
            Comparison.GetXaxis().SetTitle(xAxisLabel)
            Comparison.GetYaxis().CenterTitle()
            Comparison.GetYaxis().SetTitleSize(0.1)
            Comparison.GetYaxis().SetTitleOffset(0.5)
            Comparison.GetXaxis().SetTitleSize(0.15)
            Comparison.GetYaxis().SetLabelSize(0.1)
            Comparison.GetXaxis().SetLabelSize(0.15)
            if makeRatioPlots:
                RatioYRange = 1.15
                if arguments.ratioYRange:
                    RatioYRange = float(arguments.ratioYRange)
                Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange,
                                                   RatioYRange)
            elif makeDiffPlots:
                YMax = Comparison.GetMaximum()
                YMin = Comparison.GetMinimum()
                if YMax <= 0 and YMin <= 0:
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0)
                elif YMax >= 0 and YMin >= 0:
                    Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax)
                else:  #axis crosses y=0
                    if abs(YMax) > abs(YMin):
                        Comparison.GetYaxis().SetRangeUser(
                            -1.2 * YMax, 1.2 * YMax)
                    else:
                        Comparison.GetYaxis().SetRangeUser(
                            -1.2 * YMin, 1.2 * YMin)

            Comparison.GetYaxis().SetNdivisions(205)
            Comparison.Draw("E0")

        if i == 0:
            Canvas.Write(distribution['name'] + "_Before")
            if arguments.savePDFs:
                pathToDirString = plainTextString(pathToDir)
                Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" +
                              pathToDirString + "/" + distribution['name'] +
                              "_Before.pdf")

        if i == 1:
            Canvas.Write(distribution['name'] + "_After")
            if arguments.savePDFs:
                pathToDirString = plainTextString(pathToDir)
                Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" +
                              pathToDirString + "/" + distribution['name'] +
                              "_After.pdf")
Ejemplo n.º 28
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)

    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()

    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.3326613, 0.6419492, 0.9294355, 0.9216102)
    legend.SetTextSize(0.02966102)
    legend.SetTextFont(42)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    if isExclusive:
        legend.SetHeader("N = %d" % N)
    else:
        legend.SetHeader("N #geq %d" % N)
    legend.AddEntry(hData, "Data", "p")
    legend.AddEntry(hBkg_, "Background", "l")
    legend.AddEntry(hBkg, "Uncertainty", "f")

    legend_sm = TLegend(0.6471774, 0.7669492, 0.8508065, 0.8771186)
    legend_sm.SetTextSize(0.02966102)
    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(2)
            h.SetLineStyle(i + 2)

        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"])

        legend.AddEntry(h, bh_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])
            hs.Add(h, "hist")
            legend_sm.AddEntry(h, config.sm_models[i], "f")

    #hs.Add(hData, "e")

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

    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])
    from Styles import formatUncertainty
    formatUncertainty(gBkg)
    gBkg.Draw("LX")
    hData.Draw("esame")

    hs.SetMinimum(5e-2)
    if isExclusive:
        hs.SetMaximum(hData.GetBinContent(ibin) * 20)
    else:
        #hs.SetMaximum(4e4)
        hs.SetMaximum(hData.GetBinContent(ibin) * 20)

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

    if isExclusive:
        cmslabel = TPaveText(0.5544355, 0.5127119, 0.8991935, 0.6292373,
                             "brNDC")
    else:
        cmslabel = TPaveText(0.1955645, 0.1631356, 0.5403226, 0.279661,
                             "brNDC")
    cmslabel.AddText(config.cmsTitle)
    cmslabel.AddText(config.cmsSubtitle)
    cmslabel.SetFillColor(0)
    cmslabel.Draw("plain")

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

    c.Update()

    raw_input("Press Enter to continue...")
Ejemplo n.º 29
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))
Ejemplo n.º 30
0
def plot(path, pt_title, ecms, xmin, xmax, xbins, ymax):
    try:
        f_data = TFile(path[0])
        t_data = f_data.Get('save')
        entries_data = t_data.GetEntries()
        logging.info('data entries :' + str(entries_data))
    except:
        logging.error(path[0] + ' is invalid!')
        sys.exit()
    try:
        f_DDPIPI = TFile(path[1])
        t_DDPIPI = f_DDPIPI.Get('save')
        entries_DDPIPI = t_DDPIPI.GetEntries()
        logging.info('DDPIPI entries :' + str(entries_DDPIPI))
    except:
        logging.error(path[1] + ' is invalid!')
        sys.exit()
    try:
        f_DDPI = TFile(path[2])
        t_DDPI = f_DDPI.Get('save')
        entries_DDPI = t_DDPI.GetEntries()
        logging.info('DDPI entries :' + str(entries_DDPI))
    except:
        logging.error(path[2] + ' is invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    content = (xmax - xmin) / xbins * 1000
    ytitle = 'Events/%.1f MeV' % content
    xtitle = 'RM(D^{+}#pi_{0}^{+}#pi_{0}^{-})(GeV)'

    h_data = TH1F('data', 'data', xbins, xmin, float(xmax))
    set_histo_style(h_data, xtitle, ytitle, 1, False)
    rm_Dpipi_fill(t_data, h_data)

    h_DDPIPI = TH1F('DDPIPI', 'DDPIPI', xbins, xmin, float(xmax))
    set_histo_style(h_DDPIPI, xtitle, ytitle, 2, True)
    rm_Dpipi_fill(t_DDPIPI, h_DDPIPI)

    h_DDPI = TH1F('DDPI', 'DDPI', xbins, xmin, float(xmax))
    set_histo_style(h_DDPI, xtitle, ytitle, 3, True)
    rm_Dpipi_fill(t_DDPI, h_DDPI)

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    F_DDPIPI = scale(ecms, 'DDPIPI')
    F_DDPI = scale(ecms, 'DDPI')
    h_DDPIPI.Scale(F_DDPIPI)
    h_DDPI.Scale(F_DDPI)
    h_data.GetYaxis().SetRangeUser(0, ymax)
    h_data.Draw('E1')
    hs = THStack('hs', 'Stacked')
    hs.Add(h_DDPIPI)
    hs.Add(h_DDPI)
    hs.Draw('same')
    h_data.Draw('sameE1')

    if ecms > 4320: legend = TLegend(0.2, 0.25, 0.5, 0.55)
    if ecms < 4320: legend = TLegend(0.2, 0.2, 0.55, 0.4)
    set_legend(legend, h_data, h_DDPIPI, h_DDPI, pt_title, ecms)
    legend.Draw()

    mbc.SaveAs('./figs/rm_Dpipi_' + str(ecms) + '_raw_sideband.pdf')

    raw_input('Enter anything to end...')