Exemplo n.º 1
0
def getLabelCmsPrivateData( x1ndc = 0.6, y1ndc = 0.90, x2ndc = 0.9, y2ndc = 0.93):
	labelCmsPrivateSimulation = TPaveText(x1ndc,y1ndc,x2ndc,y2ndc,"NDC")
	labelCmsPrivateSimulation.AddText("#font[62]{CMS private work}, #font[72]{2015 data}")
	labelCmsPrivateSimulation.SetBorderSize(1)
	labelCmsPrivateSimulation.SetFillColor(0) # 0 == White
	return labelCmsPrivateSimulation
Exemplo n.º 2
0
#gROOT.Reset()

c1 = TCanvas('c1', 'Tree Data Structure', 200, 10, 750, 940)
c1.Range(0, -0.1, 1, 1.15)

gBenchmark.Start('tree')

branchcolor = 26
leafcolor = 30
basketcolor = 42
offsetcolor = 43
#title = TPaveLabel(.3,1.05,.8,1.13,c1.GetTitle())
title = TPaveLabel(.3, 1.05, .8, 1.13, 'Tree Data Structure')
title.SetFillColor(16)
title.Draw()
tree = TPaveText(.01, .75, .15, 1.00)
tree.SetFillColor(18)
tree.SetTextAlign(12)
tnt = tree.AddText('Tree')
tnt.SetTextAlign(22)
tnt.SetTextSize(0.030)
tree.AddText('fScanField')
tree.AddText('fMaxEventLoop')
tree.AddText('fMaxVirtualSize')
tree.AddText('fEntries')
tree.AddText('fDimension')
tree.AddText('fSelectedRows')
tree.Draw()
farm = TPavesText(.01, 1.02, .15, 1.1, 9, 'tr')
tfarm = farm.AddText('CHAIN')
tfarm.SetTextSize(0.024)
Exemplo n.º 3
0
def add_desc_to_canvas(config, xmin, ymin, xmax, ymax, size, content):
    txt1 = TPaveText(xmin, ymin, xmax, ymax, "NDC")
    txt1.SetFillColor(kWhite)
    txt1.SetFillStyle(0)
    txt1.SetBorderSize(0)
    txt1.SetTextAlign(12) # middle,left
    txt1.SetTextFont(42) # helvetica
    txt1.SetTextSize(size)
    if content["add_alice"]:
        txt1.AddText("ALICE work in progress")
    if content["add_gran"]:
        gran_desc = "#it{n}_{#it{#varphi}} #times #it{n}_{#it{r}} #times #it{n}_{#it{z}}"
        gran_str = "%d #times %d #times %d" % (config.grid_phi, config.grid_r,
                                               config.grid_z)
        txt1.AddText("%s = %s" % (gran_desc, gran_str))
    if content["add_inputs"]:
        if config.opt_train[0] == 1 and config.opt_train[1] == 1:
            txt1.AddText("inputs: #it{#rho}_{SC} - <#it{#rho}_{SC}>, <#it{#rho}_{SC}>")
        elif config.opt_train[1] == 1:
            txt1.AddText("inputs: #it{#rho}_{SC} - <#it{#rho}_{SC}>")
    if content["add_events"]:
        txt1.AddText("#it{N}_{ev}^{training} = %d" % config.train_events)
        # txt1.AddText("#it{N}_{ev}^{validation} = %d" % config.val_events)
        # txt1.AddText("#it{N}_{ev}^{apply} = %d" % config.apply_events)
    if config.name == "dnn":
        txt1.AddText("%d epochs" % config.epochs)
    return txt1
Exemplo n.º 4
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, TMath
    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()
    hs1 = THStack()

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

    legend = TLegend(0.3026613, 0.4919492, 0.6094355, 0.8816102)
    legend.SetTextSize(0.041)
    #was 0.02966102
    legend.SetTextFont(42)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    if isExclusive:
        legend.SetHeader("Multiplicity, N = %d" % N)
    else:
        legend.SetHeader("Multiplicity, N #geq %d" % N)
    legend.AddEntry(hData, "Observed", "p")
    legend.AddEntry(hBkg_, "Background", "l")
    legend.AddEntry(hBkg, "Uncertainty", "f")

    legend_sm = TLegend(0.6271774, 0.6769492, 0.8308065, 0.8171186)
    legend_sm.SetTextSize(0.041)
    legend_sm.SetTextFont(42)
    legend_sm.SetFillColor(0)
    legend_sm.SetLineColor(0)

    #pulls
    hPull = infile.Get("Background_N%d%s" % (N, suffix))
    for ibin in range(hData.GetNbinsX()):
        if hBkg.GetBinContent(ibin + 1) != 0 and hData.GetBinContent(ibin +
                                                                     1) != 0:
            cont = hData.GetBinContent(ibin + 1) / hBkg.GetBinContent(ibin +
                                                                      1) - 1
            cont_err = cont * TMath.Sqrt(
                1 / hData.GetBinContent(ibin + 1) +
                (hBkg.GetBinError(ibin + 1) / hBkg.GetBinContent(ibin + 1)) *
                (hBkg.GetBinError(ibin + 1) / hBkg.GetBinContent(ibin + 1)))
            print ibin + 1, hData.GetBinContent(ibin + 1), hBkg.GetBinContent(
                ibin + 1), hBkg.GetBinError(ibin + 1), hData.GetBinContent(
                    ibin + 1) / hBkg.GetBinContent(ibin + 1) - 1, TMath.Sqrt(
                        1 / hData.GetBinContent(ibin + 1) +
                        (hBkg.GetBinError(ibin + 1) /
                         hBkg.GetBinContent(ibin + 1)) *
                        (hBkg.GetBinError(ibin + 1) /
                         hBkg.GetBinContent(ibin + 1)))

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

    #hs.Add(hData, "e")

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

    hs.GetYaxis().SetTitleSize(0.045)
    hs.GetYaxis().SetLabelSize(0.045)
    hs.GetXaxis().SetTitleSize(0.045)
    hs.GetXaxis().SetLabelSize(0.045)

    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(2e-2)
    if isExclusive:
        hs.SetMaximum(hData.GetBinContent(ibin) * 200)
    else:
        #hs.SetMaximum(4e4)
        hs.SetMaximum(hData.GetBinContent(ibin) * 200)

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

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

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

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

    raw_input("Press Enter to continue...")
Exemplo n.º 5
0
def CMSPrelim(dataset, channel, lowX, lowY):
    cmsprel  =  TPaveText(lowX, lowY+0.06, lowX+0.30, lowY+0.16, "NDC")
    cmsprel.SetBorderSize(   0 )
    cmsprel.SetFillStyle(    0 )
    cmsprel.SetTextAlign(   12 )
    cmsprel.SetTextSize ( 0.04 )
    cmsprel.SetTextColor(    1 )
    cmsprel.SetTextFont (   62 )
    cmsprel.AddText(dataset)
    
##     lumi     =  TPaveText(lowX+0.38, lowY+0.061, lowX+0.45, lowY+0.161, "NDC")
##     lumi.SetBorderSize(   0 )
##     lumi.SetFillStyle(    0 )
##     lumi.SetTextAlign(   12 )
##     lumi.SetTextSize ( 0.04 )
##     lumi.SetTextColor(    1 )
##     lumi.SetTextFont (   62 )
##     lumi.AddText(dataset)
    
    chan     =  TPaveText(lowX+0.68, lowY+0.061, lowX+0.80, lowY+0.161, "NDC")
    chan.SetBorderSize(   0 )
    chan.SetFillStyle(    0 )
    chan.SetTextAlign(   12 )
    chan.SetTextSize ( 0.05 )
    chan.SetTextColor(    1 )
    chan.SetTextFont (   62 )
    chan.AddText(channel)
    
    return cmsprel, chan
Exemplo n.º 6
0
            metMinusOne.Multiply(triggerEfficiency)
            for i in range(0, metMinusOne.GetNbinsX() + 2):
                content = metMinusOne.GetBinContent(i)
                error = metMinusOne.GetBinError(i)
                upperEdge = metMinusOne.GetBinLowEdge(
                    i) + metMinusOne.GetBinWidth(i)

                newContent = content * pPassVeto if self._metCut < upperEdge else 0.0
                newError = error * pPassVeto if self._metCut < upperEdge else 0.0

                metMinusOne.SetBinContent(i, newContent)
                metMinusOne.SetBinError(i, newError)

            metMinusOne = metMinusOne.Rebin(self._rebinFactor, "metMinusOne")

            pt = TPaveText(0.522556, 0.838501, 0.921053, 0.885013, "brNDC")
            pt.SetBorderSize(0)
            pt.SetFillStyle(0)
            pt.SetTextFont(42)
            pt.SetTextSize(0.0387597)
            pt.AddText(str(self._plotLabel))

            cmsLabel = TPaveText(0.134085, 0.937984, 0.418546, 0.984496,
                                 "brNDC")
            cmsLabel.SetBorderSize(0)
            cmsLabel.SetFillStyle(0)
            cmsLabel.SetTextFont(62)
            cmsLabel.SetTextSize(0.0387597)
            cmsLabel.AddText("CMS Preliminary")

            lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894,
Exemplo n.º 7
0
    def plotMetForNback(self):
        if hasattr(self, "CandTrkIdPt35"):
            if self._fout and self._canvas:
                sample = self.CandTrkIdPt35["sample"]
                condorDir = self.CandTrkIdPt35["condorDir"]
                name = self.CandTrkIdPt35["name"]
                hist = "Track-met Plots/metNoMuMinusOnePtVsMaxSigmaForFiducialTracks"
                met = self.getHistFromProjectionZ(
                    sample,
                    condorDir,
                    name + "Plotter",
                    hist,
                    alternate1DHist="Met Plots/metNoMu")

                # explicitly get metNoMuMinusOne instead of using
                # _metMinusOneHist since we plot both metNoMu and
                # metNoMuMinusOne here
                hist = self._Flavor + " Plots/" + self._flavor + "MetNoMuMinusOnePt"
                hist = "Track-" + self._flavor + " Plots/" + self._flavor + "NoMuMinusOnePtVsMaxSigmaForFiducialTracks"
                metMinusOne = self.getHistFromProjectionZ(
                    sample,
                    condorDir,
                    name + "Plotter",
                    hist,
                    alternate1DHist=self._Flavor + " Plots/" + self._flavor +
                    "MetNoMuMinusOnePt")
                if not isinstance(met, TObject) or not isinstance(
                        metMinusOne, TObject):
                    print "Warning [plotMetForNback]: Could not get required hists from sample=", sample, "condorDir=", condorDir, "name=", name
                    return

                met.Rebin(self._rebinFactor)
                metMinusOne.Rebin(self._rebinFactor)

                pt = TPaveText(0.522556, 0.838501, 0.921053, 0.885013, "brNDC")
                pt.SetBorderSize(0)
                pt.SetFillStyle(0)
                pt.SetTextFont(42)
                pt.SetTextSize(0.0387597)
                pt.AddText(str(self._plotLabel))

                cmsLabel = TPaveText(0.134085, 0.937984, 0.418546, 0.984496,
                                     "brNDC")
                cmsLabel.SetBorderSize(0)
                cmsLabel.SetFillStyle(0)
                cmsLabel.SetTextFont(62)
                cmsLabel.SetTextSize(0.0387597)
                cmsLabel.AddText("CMS Preliminary")

                lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894,
                                      "brNDC")
                lumiLabel.SetBorderSize(0)
                lumiLabel.SetFillStyle(0)
                lumiLabel.SetTextFont(42)
                lumiLabel.SetTextSize(0.0387597)
                lumiLabel.AddText(str(self._luminosityLabel))

                setStyle(met)
                setAxisStyle(met, "E_{T}^{miss, no #mu} [GeV]",
                             "Entries / " + str(met.GetBinWidth(1)) + " GeV")
                self._canvas.cd()
                met.Draw()
                pt.Draw("same")
                cmsLabel.Draw("same")
                lumiLabel.Draw("same")
                self._fout.cd()
                self._canvas.Write("metForNback")

                setStyle(metMinusOne)
                setAxisStyle(
                    metMinusOne, "E_{T}^{miss, no #mu} " +
                    ("excluding selected " +
                     self._flavor if self._flavor != "muon" else "") + "[GeV]",
                    "Entries / " + str(metMinusOne.GetBinWidth(1)) + " GeV")
                self._canvas.cd()
                metMinusOne.Draw()
                pt.Draw("same")
                cmsLabel.Draw("same")
                lumiLabel.Draw("same")
                self._fout.cd()
                self._canvas.Write("metMinusOneForNback")
            else:
                print "A TFile and TCanvas must be added. Not making plots..."
        else:
            print "CandTrkIdPt35 not defined. Not plotting MET for N_back..."
Exemplo n.º 8
0
            for iLB in listLB:
                if (nbHitInHot[iPath][iLB] != 0
                        or nbHitInHot[iPath2][iLB] != 0.):
                    hCorrel[corr].Fill(nbHitInHot[iPath][iLB],
                                       nbHitInHot[iPath2][iLB])
                    print "LB: %d -> %.2f / %.2f" % (
                        iLB, nbHitInHot[iPath][iLB], nbHitInHot[iPath2][iLB])
                if nbHitRatio[corr][iLB] != -999:
                    hRatio[corr].Fill(nbHitRatio[corr][iLB])
                if nbHitRatio[corr2][iLB] != -999:
                    hRatio[corr2].Fill(nbHitRatio[corr2][iLB])

            cCorrel[corr] = TCanvas("Correl-%s" % corr, "Correl-%s" % corr)
            hCorrel[corr].Draw("COLZ")
            paveCorrel[corr] = TPaveText(.1, .72, .9, .9, "NDC")
            paveCorrel[corr].SetFillColor(kBlue - 10)
            paveCorrel[corr].AddText(
                "Run %d / %d LBs in total - %d LBs with >=1 entry in either plot"
                % (runNumber, len(listLB), hCorrel[corr].GetEntries()))
            paveCorrel[corr].AddText("Correlation factor:%.3f" %
                                     (hCorrel[corr].GetCorrelationFactor()))
            fractionNonZero = hRatio[corr].Integral(
                2, 100) / hRatio[corr].Integral(1, 100)
            if fractionNonZero != 0.:
                meanNonZero = hRatio[corr].GetMean() / fractionNonZero
            else:
                meanNonZero = 0.
            paveCorrel[corr].AddText(
                "When >=1 entry in X plot(%d LBs), %.0f %% events with >=1 entry in Y plot(<ratio>=%.2f)"
                % (hRatio[corr].Integral(
def plot(chan, plot_expected, plot_data, report_lumi=True):
    gROOT.SetBatch()
    gStyle.SetOptStat(0)

    c1 = TCanvas("c1", "Expected Bias Band Graph", 200, 10, 800, 800)

    #c1.SetGrid();
    c1.DrawFrame(0.85, 0.75, 1.15, 1.25)

    # prepare data files
    if plot_data:
        fn_full, fn_notau, fn_stat = the_files[chan]

        file_full = TFile(fn_full)
        file_notau = TFile(fn_notau)
        file_stat = TFile(fn_stat)

        ttree_full = file_full.Get("limit")
        n = ttree_full.Draw(draw_command, "2*deltaNLL>0 && 2*deltaNLL< 10",
                            "L")
        g_full = TGraph(n, ttree_full.GetV2(), ttree_full.GetV1())

        ttree_notau = file_notau.Get("limit")
        n = ttree_notau.Draw(draw_command, "2*deltaNLL>0 && 2*deltaNLL< 10",
                             "L")
        g_notau = TGraph(n, ttree_notau.GetV2(), ttree_notau.GetV1())

        ttree_stat = file_stat.Get("limit")
        n = ttree_stat.Draw(draw_command, "2*deltaNLL>0 && 2*deltaNLL< 10",
                            "L")
        g_stat = TGraph(n, ttree_stat.GetV2(), ttree_stat.GetV1())

        g_full.SetLineWidth(3)
        g_notau.SetLineWidth(2)
        g_stat.SetLineWidth(2)
        g_stat.SetLineStyle(7)

        # removing the title
        #g_full .SetTitle(";\\text{fitted } #hat{r};") # ROOT latex cannot put a hat on a letter
        #g_full .SetTitle(";\\text{fitted } r;-2\\Delta ln L")
        #g_full .SetTitle(";\\text{fitted signal strength};-2\\Delta ln L")
        g_full.SetTitle(";\\text{visible cross section [pb]};-2\\Delta ln L")
        g_notau.SetTitle(";;")
        g_stat.SetTitle(";;")

        #g_full .GetXaxis().SetRange(0.75, 1.35)
        #g_notau.GetXaxis().SetRange(0.75, 1.35)
        #g_stat .GetXaxis().SetRange(0.75, 1.35)
        g_full.GetXaxis().SetRangeUser(0.75, 1.35)
        g_notau.GetXaxis().SetRangeUser(0.75, 1.35)
        g_stat.GetXaxis().SetRangeUser(0.75, 1.35)

        print "set up data plots", g_full

    # prepare expected files
    if plot_expected:
        fn_full, fn_notau, fn_stat = the_files_expected[chan]

        exp_file_full = TFile(fn_full)
        exp_file_notau = TFile(fn_notau)
        exp_file_stat = TFile(fn_stat)

        print fn_full, fn_notau, fn_stat

        exp_ttree_full = exp_file_full.Get("limit")
        n = exp_ttree_full.Draw(draw_command, "2*deltaNLL>0 && 2*deltaNLL< 10",
                                "L")
        exp_g_full = TGraph(n, exp_ttree_full.GetV2(), exp_ttree_full.GetV1())

        exp_ttree_notau = exp_file_notau.Get("limit")
        n = exp_ttree_notau.Draw(draw_command,
                                 "2*deltaNLL>0 && 2*deltaNLL< 10", "L")
        exp_g_notau = TGraph(n, exp_ttree_notau.GetV2(),
                             exp_ttree_notau.GetV1())

        exp_ttree_stat = exp_file_stat.Get("limit")
        n = exp_ttree_stat.Draw(draw_command, "2*deltaNLL>0 && 2*deltaNLL< 10",
                                "L")
        exp_g_stat = TGraph(n, exp_ttree_stat.GetV2(), exp_ttree_stat.GetV1())

        exp_g_full.SetLineWidth(3)
        exp_g_notau.SetLineWidth(2)
        exp_g_stat.SetLineWidth(2)
        exp_g_stat.SetLineStyle(7)

        # removing the title
        #g_full .SetTitle(";\\text{fitted } #hat{r};") # ROOT latex cannot put a hat on a letter
        #exp_g_full .SetTitle(";\\text{fitted } r;-2\\Delta ln L")
        #exp_g_full .SetTitle(";\\text{fitted signal strength};-2\\Delta ln L")
        exp_g_full.SetTitle(
            ";\\text{visible cross section [pb]};-2\\Delta ln L")
        exp_g_notau.SetTitle(";;")
        exp_g_stat.SetTitle(";;")

        #exp_g_full .GetXaxis().SetRange(0.75, 1.35)
        #exp_g_notau.GetXaxis().SetRange(0.75, 1.35)
        #exp_g_stat .GetXaxis().SetRange(0.75, 1.35)
        exp_g_full.GetXaxis().SetRangeUser(0.75, 1.35)
        exp_g_notau.GetXaxis().SetRangeUser(0.75, 1.35)
        exp_g_stat.GetXaxis().SetRangeUser(0.75, 1.35)

        print "set up expectation plots", exp_g_full

    ## add X axis title
    #g_full .SetXTitle("fitted \\mu")
    #g_notau.SetXTitle("fitted \\mu")
    #g_stat .SetXTitle("fitted \\mu")
    leg = TLegend(0.6, 0.7, 0.89, 0.89)

    if plot_expected and plot_data:
        print "plotting both"
        exp_g_full.SetLineStyle(7)

        exp_g_full.Draw("ap")  # this cast makes the following work
        exp_g_full.Draw("L")
        #exp_g_notau.Draw("L same")
        #exp_g_stat .Draw("L same")

        leg.AddEntry(exp_g_full, "expected", "L")
        #leg.AddEntry(exp_g_full, "exp. full unc.", "L")
        #leg.AddEntry(exp_g_stat, "exp. stat unc.", "L")

        g_full.Draw("L same")
        #g_notau.Draw("L same")
        #g_stat .Draw("L same")

        leg.AddEntry(g_full, "observed", "L")
        #leg.AddEntry(g_full, "fitted full unc.", "L")
        #leg.AddEntry(g_stat, "fitted stat unc.", "L")

    elif plot_data:
        print "plotting data"
        g_full.Draw("ap")  # this cast makes the following work
        g_full.Draw("L")
        g_notau.Draw("L same")
        g_stat.Draw("L same")

        leg.AddEntry(g_full, "fitted full unc.", "L")
        leg.AddEntry(g_notau, "#splitline{fitted unc.}{w.o. tau ID}", "L")
        leg.AddEntry(g_stat, "fitted stat unc.", "L")

    elif plot_expected:
        print "plotting expected"

        exp_g_full.SetLineColor(43)
        exp_g_notau.SetLineColor(43)
        exp_g_stat.SetLineColor(43)

        exp_g_full.Draw("ap")
        exp_g_full.Draw("L")
        exp_g_notau.Draw("L same")
        exp_g_stat.Draw("L same")

        leg.AddEntry(exp_g_full, "exp. full unc.", "L")
        leg.AddEntry(exp_g_notau, "#splitline{exp. unc.}{w.o. tau ID}", "L")
        leg.AddEntry(exp_g_stat, "exp. stat unc.", "L")

    #left_title = TPaveText(0.1, 0.9, 0.4, 0.94, "brNDC")
    #left_title.AddText("CMS preliminary at 13 TeV")
    #left_title.SetTextFont(1)

    left_title = TPaveText(0.15, 0.82, 0.3, 0.88, "brNDC")
    left_title.AddText("CMS")
    left_title.SetTextFont(1)
    left_title.SetFillColor(0)
    left_title.Draw("same")

    #right_title = TPaveText(0.75, 0.9, 0.9, 0.94, "brNDC")
    #right_title.AddText("L = %s fb^{-1}" % (31.3 if chan == 'el' else 35.8))
    #right_title.SetTextFont(132)
    #right_title.SetFillColor(0)

    right_title = TPaveText(0.5, 0.9, 0.9, 0.95, "brNDC")
    both = True
    if report_lumi:
        right_title.AddText("%s fb^{-1} (13 TeV)" %
                            (35.8 if chan == 'el' else 35.8))
    elif both:
        right_title.AddText("%s fb^{-1} (13 TeV)" % '35.8')
    else:
        right_title.AddText("(13 TeV)")

    right_title.SetTextFont(132)
    right_title.SetFillColor(0)
    right_title.Draw("same")

    leg.Draw("same")

    plotted = ''
    plotted += '_exp' if plot_expected else ''
    plotted += '_obs' if plot_data else ''
    c1.SaveAs("uncertainty_scans_%s_%s%s.png" %
              (args.fit_release, chan, plotted))
Exemplo n.º 10
0
line1 = TLine(80.358, Min, 80.442, Min)
line2 = TLine(80.358, Min + 1, 80.442, Min + 1)

line3 = TLine(XMin, -1, XMin, Min + 1)
line4 = TLine(XMin + 0.001 * stepEval, -1, XMin + 0.001 * stepEval, Min + 1)
line5 = TLine(XMin - 0.001 * stepEval, -1, XMin - 0.001 * stepEval, Min + 1)

# Save the plot
c = TCanvas("c", "c", 800, 600)
gStyle.SetPadBorderMode(1)
gStyle.SetOptFit(1)
Graph.Draw("AC*")
line1.Draw("same")
line2.Draw("same")
line3.Draw("same")
line4.Draw("same")
line5.Draw("same")

pt = TPaveText(0.14, 0.7, 0.4, 0.85, "NDC")
pt.SetTextSize(0.04)
pt.SetFillColor(0)
pt.SetTextAlign(12)
mwstring = "Mw = " + str(f1.GetMinimumX())
Statstring = "#delta^{Stat} = " + str(stepEval) + " MeV"
pt.AddText(mwstring)
pt.AddText(Statstring)
pt.Draw("same")

c.SaveAs("Chi2_Stat.pdf")
Exemplo n.º 11
0
                mglist.append(
                    TMultiGraph('mg_' + str(listind), objs.GetTitle()))
                mglist[listind].Add(objarr[1][0][index], 'p')
                mglist[listind].Add(objs, 'p')
                mglist[listind].Draw('a')
                listind += 1
            elif objs.InheritsFrom("TH1"):
                stacklist.append(
                    THStack('stack_' + str(stackind), objs.GetTitle()))
                stacklist[stackind].Add(objarr[1][0][index])
                stacklist[stackind].Add(objs)
                stacklist[stackind].Draw('nostack hist x0')
                stackind += 1
    c3.Update()
    c3.cd(8)
    text = TPaveText(.05, .1, .95, .8)

    RMS1 = ROOT.TMath.RMS(240, array('d', objarr[0][0][1].GetY()))
    RMS2 = ROOT.TMath.RMS(240, array('d', objarr[1][0][1].GetY()))
    text.AddText("RMS (Mean) before calibration = " + str(RMS1))
    text.AddText("RMS (Mean) after  calibration = " + str(RMS2))
    text.Draw()

    c3.cd(9)
    pixelvec = np.linspace(1, 288, num=288)
    TRIMDAC_graph = TGraphErrors(no_mpa_light * 48, pixelvec, final_TRIMDAC)
    TRIMDAC_graph.SetTitle("TRIMDACMATRIX; channel; TRIMDACVAL (a.U)")
    TRIMDAC_graph.SetMarkerStyle(6)
    TRIMDAC_graph.SetMarkerColor(2)
    TRIMDAC_graph.Draw("ap")
    c3.Update()
Exemplo n.º 12
0
h_average.SetFillColor(7)
h_day.SetFillColor(8)
h_players.SetFillColor(9)

h_day_vs_fdif_avg.SetMarkerStyle(3)
h_day_vs_fdif_avg.SetMarkerColor(3)
h_day_vs_fdif_avg.GetXaxis().SetTitle("Day")
h_day_vs_fdif_avg.GetYaxis().SetTitle(
    "Average Fractional Difference between Player scores and Public scores")
#h_day_vs_fdif_avg.SetStats(kFALSE)

c_forgov = TCanvas("forgov", "Canvas for Gov. <3", 1000, 1000)
h_fracdifference.GetXaxis().SetTitle("This is the x axis")
h_fracdifference.GetYaxis().SetTitle("This is the y axis")
h_fracdifference.Draw()
text = TPaveText(0.1, 0.7, 0.3, 0.9)
text.AddText("There is no z axis")
text.Draw()
c_forgov.BuildLegend()
c_forgov.Print("canvasforgov.png")

#tree_file = TFile("TreeSporcleAnalysis.root", "RECREATE")
#tSporcleData.Write("SporcleData")
#tree_file.Close()

s_file = TFile("SporcleAnalysis.root", "RECREATE")
h_difference.Write("Difference")
h_fracdifference.Write("FractionalDifference")
h_score.Write("Score")
h_maximum.Write("Maximum")
h_percentage.Write("Percentage")
Exemplo n.º 13
0
def drawenergy1D(is2017, text_="Work in progress 2018", data=True):
    pt = TPaveText(0.0877181, 0.9, 0.9580537, 0.96, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(52)

    cmstextSize = 0.07
    preliminarytextfize = cmstextSize * 0.7
    lumitextsize = cmstextSize * 0.7
    pt.SetTextSize(cmstextSize)
    text = pt.AddText(0.063, 0.57, "#font[61]{CMS}")

    pt1 = TPaveText(0.0877181, 0.9, 0.9580537, 0.96, "brNDC")
    pt1.SetBorderSize(0)
    pt1.SetTextAlign(12)
    pt1.SetFillStyle(0)
    pt1.SetTextFont(52)

    pt1.SetTextSize(preliminarytextfize)
    text1 = pt1.AddText(0.215, 0.4, text_)

    pt2 = TPaveText(0.0877181, 0.9, 0.9580537, 0.96, "brNDC")
    pt2.SetBorderSize(0)
    pt2.SetTextAlign(12)
    pt2.SetFillStyle(0)
    pt2.SetTextFont(52)
    pt2.SetTextFont(42)
    pt2.SetTextSize(lumitextsize)
    #    text3 = pt2.AddText(0.53,0.5,"#sqrt{s} = 13 TeV(2017)")

    #pavetext = ''
    #if is2017: pavetext = "#sqrt{s} = 13 TeV(2017)"
    #if not is2017: pavetext = "#sqrt{s} = 13 TeV(2018)"
    #text3 = pt2.AddText(0.61,0.5,pavetext)

    pavetext = ''
    if is2017 and data: pavetext = "(13 TeV)"
    if (not is2017) and data: pavetext = "(13 TeV)"

    if is2017 and not data: pavetext = "13 TeV"
    if (not is2017) and not data: pavetext = "13 TeV"

    if data: text3 = pt2.AddText(0.81, 0.5, pavetext)
    if not data: text3 = pt2.AddText(0.85, 0.5, pavetext)

    return [pt, pt1, pt2]
    return [pt, pt1, pt2]
Exemplo n.º 14
0
def createPlots_(plot, geometry):
    """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"

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

    hist_X0_detectors = OrderedDict()
    hist_X0_IB = None
    hist_X0_elements = OrderedDict()

    for subDetector, color in DETECTORS.items():
        h = get1DHisto_(subDetector, plots[plot].plotNumber, geometry)
        if not h:
            print('Warning: Skipping %s' % subDetector)
            continue
        hist_X0_detectors[subDetector] = h

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

        # category profiles
        for label, [num, color, leg] in hist_label_to_num.items():
            if label is 'SUM': continue
            hist_label = get1DHisto_(subDetector, num + plots[plot].plotNumber,
                                     geometry)
            hist_X0_elements[label] = assignOrAddIfExists_(
                hist_X0_elements.setdefault(label, None),
                hist_label,
            )
            hist_X0_elements[label].SetFillColor(color)

    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.items():
        setColorIfExists_(hist_X0_detectors, det, 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.items():
        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.items():
        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.items():
        if label is 'SUM':
            continue
        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.items():
        if label is 'SUM':
            continue
        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
Exemplo n.º 15
0
def createPlots_(plot, compounddetectorname):
    """Cumulative material budget from simulation.
    
       Internal function that will produce a cumulative profile of the
       material budget inferred from the simulation starting from the
       single detectors that compose the tracker. It will iterate over
       all existing detectors contained in the DETECTORS
       dictionary. The function will automatically skip non-existent
       detectors.

    """

    theDirname = "Figures"

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

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

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

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

        hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionX()

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

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

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

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

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

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

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

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

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

    theLegend_SubDetectors.Draw()

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

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

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

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

    return cumulative_matbdg
Exemplo n.º 16
0
VI = n.array(b.P())

varrs = [PE, T, VI]
j = 0
#Negative covariance - variable is inversely related!!!!!

means = [n.mean(varrs[i]) for i in xrange(len(varrs))]
names = ["Pot Energy", "Temp", "Virial"]
corrs = []
corr = 0.0
CORR = []

tg = [TGraph() for i in xrange(len(varrs))]
tc = [TCanvas() for i in xrange(len(varrs))]
title = [
    TPaveText(0.549569, 0.8241525, 0.950431, 0.8983051, "nbNDC")
    for t in xrange(3)
]

for k in xrange(len(varrs)):
    corrs = []
    for nn in xrange(0, 250):
        corr = 0.0
        for i in xrange(len(varrs[k]) - nn):
            corr += (varrs[k][i + nn] - means[k]) * (varrs[k][i] - means[k])
        corrs.append(corr / (len(varrs[k]) - nn))

    tc[k].cd()
    for x in xrange(len(corrs)):
        tg[k].SetPoint(x, x, corrs[x] / corrs[0])
Exemplo n.º 17
0
def main():
    #############################################################################################
    # Options #
    #############################################################################################
    parser = argparse.ArgumentParser(
        description=
        'From given set of root files, make different histograms in a root file'
    )
    parser.add_argument('-m',
                        '--model',
                        action='store',
                        required=True,
                        type=str,
                        default='',
                        help='NN model to be used')
    parser.add_argument('-f',
                        '--file',
                        action='store',
                        required=False,
                        type=str,
                        default='',
                        help='File (full path) to be used')
    parser.add_argument('--mA',
                        action='store',
                        required=False,
                        type=int,
                        default=0,
                        help='Print as PDf only some of the mass config')
    parser.add_argument('--mH',
                        action='store',
                        required=False,
                        type=int,
                        default=0,
                        help='Print as PDf only some of the mass config')
    parser.add_argument('-n',
                        '--number',
                        action='store',
                        required=False,
                        type=int,
                        default=0,
                        help='Number of events to build the likelihood map')
    parser.add_argument('--xmax',
                        action='store',
                        required=False,
                        type=float,
                        default=1500,
                        help='Maximum values for mA in the graph')
    parser.add_argument('--ymax',
                        action='store',
                        required=False,
                        type=float,
                        default=1500,
                        help='Maximum values for mH in the graph')
    parser.add_argument('--xmin',
                        action='store',
                        required=False,
                        type=float,
                        default=0,
                        help='Minimum values for mA in the graph')
    parser.add_argument('--ymin',
                        action='store',
                        required=False,
                        type=float,
                        default=0,
                        help='Minimum values for mH in the graph')
    parser.add_argument('--zmin',
                        action='store',
                        required=False,
                        type=float,
                        default=0,
                        help='Minimum values for z axis in the graph')
    parser.add_argument('--zmax',
                        action='store',
                        required=False,
                        type=float,
                        default=None,
                        help='Maximum values for z axis in the graph')
    parser.add_argument('--bins',
                        action='store',
                        required=False,
                        type=int,
                        default=100,
                        help='Bins in both the graph axes')
    parser.add_argument(
        '--suffix',
        action='store',
        required=False,
        type=str,
        default='',
        help=
        'Suffix to be added to output name (likelihood_suffix.pdf/.root), default to empty string'
    )
    parser.add_argument('--PDF',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Produce PDF from the root file')
    parser.add_argument(
        '--profile',
        action='store_true',
        required=False,
        default=False,
        help='Whether to make the profile likelihood starting from the TGraph2D'
    )
    parser.add_argument('--zoom',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Zoom the TGraph2D according to given boundaries')
    parser.add_argument(
        '--norm',
        action='store_true',
        required=False,
        default=False,
        help='Use the normalization by the visible cross section')
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Show DEGUG logging')
    opt = parser.parse_args()

    # Logging #
    if opt.verbose:
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s - %(levelname)s - %(message)s')
    else:
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s - %(levelname)s - %(message)s')
    #############################################################################################
    # Get objects in TFile #
    #############################################################################################
    def getall(d, basepath="/"):
        "Generator function to recurse into a ROOT file/dir and yield (path, obj) pairs"
        for key in d.GetListOfKeys():
            kname = key.GetName()
            if key.IsFolder():
                for i in getall(d.Get(kname), basepath + kname + '/'):
                    yield i
            else:
                yield basepath + kname, d.Get(kname)

    #############################################################################################
    # Profile Likelihood #
    #############################################################################################
    if opt.profile:
        # Path to graph #
        path_root = os.path.abspath(
            os.path.join('PDF', opt.model,
                         'likelihood_' + opt.suffix + '.root'))
        path_out = os.path.abspath(os.path.join('PDF', opt.model))
        # Load TGraph2D #
        f = TFile(path_root)
        graphs = [(key, obj) for (key, obj) in getall(f)]
        for key, obj in graphs:
            if key.find('HToZA') == -1:
                continue
            mH_value = int(re.findall(r'\d+', key)[2])
            mA_value = int(re.findall(r'\d+', key)[3])

            if mH_value != opt.mH or mA_value != opt.mA:
                continue

            MakeProfile(graph=obj,
                        mH=mH_value,
                        mA=mA_value,
                        N=10000,
                        path=path_out,
                        step=5,
                        slices=10)
        sys.exit(0)

    #############################################################################################
    # Make PDF #
    #############################################################################################
    def ZoomHist(graph, bins, xmin, xmax, ymin, ymax):
        x = np.linspace(xmin, xmax, bins)
        y = np.linspace(ymin, ymax, bins)
        X, Y = np.meshgrid(x, y)
        X = X.ravel()
        Y = Y.ravel()
        valid = np.logical_and(np.greater_equal(Y, X),
                               np.greater_equal(Y, 125))
        X = X[valid]
        Y = Y[valid]
        N = X.shape[0]
        new_graph = TGraph2D(N)
        manager = enlighten.get_manager()
        pbar = manager.counter(total=N, desc='Progress', unit='Point')
        for i in range(N):
            content = graph.Interpolate(X[i], Y[i])
            if content != 0 or Y[i] > 125:
                new_graph.SetPoint(i, X[i], Y[i], content)
            pbar.update()
        new_graph.SetTitle(graph.GetTitle())
        return copy.deepcopy(new_graph)

    if opt.PDF or opt.zoom:
        path_root = os.path.abspath(
            os.path.join('PDF', opt.model,
                         'likelihood_' + opt.suffix + '.root'))
        path_pdf = os.path.abspath(
            os.path.join('PDF', opt.model,
                         'likelihood_' + opt.suffix + '.pdf'))
        path_zoom = os.path.abspath(
            os.path.join('PDF', opt.model,
                         'likelihood_' + opt.suffix + '_zoom.root'))
        f = TFile(path_root)
        if opt.PDF:
            c1 = TCanvas('c1', 'c1', 1100, 900)
            c1.SetGrid()
            #canvas = TCanvas('canvas','canvas',900,900)
            #canvas.Print(path_pdf+'[')
            c1.Print(path_pdf + '[')
            c1.SetTopMargin(0.05)
            c1.SetBottomMargin(0.18)
            c1.SetLeftMargin(0.18)
            c1.SetRightMargin(0.2)
        graphs = [(key, obj) for (key, obj) in getall(f)]
        graphs = sorted(graphs,
                        key=lambda tup: tup[0])  # Sort according to name
        for i, (key, obj) in enumerate(graphs):
            mH_value = 0
            mA_value = 0
            if key.find('DY') != -1:
                title = 'DY'
            elif key.find('TT') != -1:
                title = 'TT'
            else:
                mH_value = int(re.findall(r'\d+', key)[2])
                mA_value = int(re.findall(r'\d+', key)[3])
                title = 'HToZATo2L2B_mH_%d_mA_%d' % (mH_value, mA_value)

            if (mH_value != opt.mH
                    or mA_value != opt.mA) and opt.mA != 0 and opt.mH != 0:
                continue
            logging.info('Processing %s' % key)
            try:
                if opt.zoom:
                    new_graph = ZoomHist(obj, opt.bins, opt.xmin, opt.xmax,
                                         opt.ymin, opt.ymax)
                    if os.path.exists(path_zoom):
                        root_file = TFile(path_zoom, "update")
                        new_graph.Write(title, TObject.kOverwrite)
                        logging.info("Zoomed Graph saved in %s" % path_zoom)
                    else:
                        root_file = TFile(path_zoom, "recreate")
                        new_graph.Write(title)
                        logging.info("Zoomed Graph replaced in %s" % path_zoom)

                if opt.PDF:
                    base_hist = TH2F('', '', opt.bins, opt.xmin, opt.xmax,
                                     opt.bins, opt.ymin, opt.ymax)
                    obj.SetHistogram(base_hist)
                    hist = obj.GetHistogram()
                    hist.SetContour(1000)
                    hist.GetXaxis().SetRangeUser(opt.xmin, opt.xmax)
                    hist.GetYaxis().SetRangeUser(opt.ymin, opt.ymax)
                    hist.SetMinimum(max(opt.zmin, hist.GetMinimum()))
                    amax = hist.GetMaximum() if opt.zmax is None else opt.zmax
                    hist.SetMaximum(amax)
                    hist.SetTitle(";M_{A} [GeV];M_{H} [GeV];-2 log L")
                    hist.GetXaxis().SetTitleOffset(1.2)
                    hist.GetYaxis().SetTitleOffset(1.2)
                    hist.GetZaxis().SetTitleOffset(1.2)
                    hist.GetXaxis().SetLabelSize(0.04)
                    hist.GetYaxis().SetLabelSize(0.04)
                    hist.GetZaxis().SetLabelSize(0.04)
                    hist.GetXaxis().SetTitleSize(0.06)
                    hist.GetYaxis().SetTitleSize(0.06)
                    hist.GetZaxis().SetTitleSize(0.06)
                    hist.Draw('colz')
                    text = TPaveText(.55, .2, .80, .4, 'brNDC')
                    text.AddText("Events with")
                    text.AddText("M_{A} = %d GeV" % mA_value)
                    text.AddText("M_{H} = %d GeV" % mH_value)
                    text.SetTextColor(1)
                    text.SetFillStyle(4100)
                    text.Draw("same")

                    #hist.SetTitle(obj.GetTitle())
                    c1.Print(
                        path_pdf,
                        'Title:' + key.replace('.root', '').replace('/', ''))
            except Exception as e:
                logging.critical('Could not save %s due to error "%s"' %
                                 (key, e))
        if opt.PDF:
            #            canvas.Print(path_pdf)
            #            canvas.Print(path_pdf+']')
            logging.info('PDF saved as %s' % path_pdf)
            c1.Print(path_pdf + ']')

        sys.exit()
    #############################################################################################
    # Make likelihood map #
    #############################################################################################
    # Get events from tree #
    logging.info('Looking at file %s' % opt.file)
    variables = [
        'lep1_p4.Pt()',
        'lep1_p4.Eta()',
        'lep2_p4.Pt()',
        'lep2_p4.Eta()',
        'lep2_p4.Phi()-lep1_p4.Phi()',
        'jet1_p4.Pt()',
        'jet1_p4.Eta()',
        'jet1_p4.Phi()-lep1_p4.Phi()',
        'jet2_p4.Pt()',
        'jet2_p4.Eta()',
        'jet2_p4.Phi()-lep1_p4.Phi()',
        'met_pt',
        'met_phi-lep1_p4.Phi()',
    ]

    events = Tree2Pandas(input_file=opt.file,
                         variables=variables,
                         n=opt.number).values
    if events.shape[0] == 0:
        raise RuntimeError("Did you forget -n ?")

    # Instantiate the map #
    likelihood = LikelihoodMap(name=opt.model,
                               xmin=opt.xmin,
                               ymin=opt.ymin,
                               xmax=opt.xmax,
                               ymax=opt.ymax,
                               N=300,
                               normalize=opt.norm)

    # Loop over events #
    logging.info('Adding events')
    manager = enlighten.get_manager()
    pbar = manager.counter(total=opt.number, desc='Progress', unit='Event')
    for i in range(events.shape[0]):
        likelihood.AddEvent(events[i, :])
        pbar.update()
    manager.stop()

    # Make and print map #
    likelihood.MakeGraph(title=os.path.basename(opt.file), suffix=opt.suffix)
Exemplo n.º 18
0
        ccos = cos(2 * pi / numberOfPoints * i) + 1
        esin = sin(2 * pi / (numberOfCircles * d) * j) + 1
        x = j * (csin + esin)
        y = j * ccos
        z = j
        pm3d.SetPoint(i, x, y, z)

# set marker size, color & style
    pm3d.SetMarkerSize(1)
    pm3d.SetMarkerColor(2 + (d == (j & d)))
    pm3d.SetMarkerStyle(3)

    # draw
    pm3d.Draw()

    # save a reference
    polymarkers.append(pm3d)

gBenchmark.Show('tornado')

ct = gBenchmark.GetCpuTime('tornado')
timeStr = 'Execution time: %g sec.' % ct

text = TPaveText(0.1, 0.81, 0.9, 0.97)
text.SetFillColor(42)
text.AddText('PyROOT example: tornado.py')
text.AddText(timeStr)
text.Draw()

sky.Update()
Exemplo n.º 19
0
    def plotTriggerEfficiency(self, passesHist, totalHist):
        if self._fout and self._canvas:
            passesHist = passesHist.Rebin(self._rebinFactor, "passesHist")
            totalHist = totalHist.Rebin(self._rebinFactor, "totalHist")

            self.makePassesConsistentWithTotal(passesHist, totalHist)
            metGraph = TGraphAsymmErrors(passesHist, totalHist)
            metGraph.SetEditable(0)

            pt = TPaveText(0.522556, 0.838501, 0.921053, 0.885013, "brNDC")
            pt.SetBorderSize(0)
            pt.SetFillStyle(0)
            pt.SetTextFont(42)
            pt.SetTextSize(0.0387597)
            pt.AddText(str(self._plotLabel))

            cmsLabel = TPaveText(0.134085, 0.937984, 0.418546, 0.984496,
                                 "brNDC")
            cmsLabel.SetBorderSize(0)
            cmsLabel.SetFillStyle(0)
            cmsLabel.SetTextFont(62)
            cmsLabel.SetTextSize(0.0387597)
            cmsLabel.AddText("CMS Preliminary")

            lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894,
                                  "brNDC")
            lumiLabel.SetBorderSize(0)
            lumiLabel.SetFillStyle(0)
            lumiLabel.SetTextFont(42)
            lumiLabel.SetTextSize(0.0387597)
            lumiLabel.AddText(str(self._luminosityLabel))

            setStyle(metGraph)
            self._canvas.cd()
            metGraph.Draw("ap")
            setAxisStyle(metGraph, "E_{T}^{miss, no #mu} [GeV]",
                         "trigger efficiency", (0.0, 500.0), (0.0, 1.4))
            pt.Draw("same")
            cmsLabel.Draw("same")
            lumiLabel.Draw("same")
            self._fout.cd()
            self._canvas.Write("triggerEfficiency")
        else:
            print "A TFile and TCanvas must be added. Not making plots..."
Exemplo n.º 20
0
def DrawOverlap(fileVec,
                histVec,
                titleVec,
                legendtext,
                pngname,
                logstatus=[0, 0],
                xRange=[-99999, 99999, 1]):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    gStyle.SetTitleOffset(1.1, "Y")
    gStyle.SetTitleOffset(0.9, "X")
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3)

    i = 0

    histList_ = []
    histList = []
    histList1 = []
    maximum = []

    ## Legend
    leg = TLegend(0.1, 0.70, 0.89, 0.89)  #,NULL,"brNDC");
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(22)
    leg.SetTextSize(0.045)

    c = TCanvas("c1", "c1", 0, 0, 500, 500)
    #c.SetBottomMargin(0.15)
    #c.SetLeftMargin(0.15)
    #c.SetLogy(0)
    #c.SetLogx(0)
    c1_2 = TPad("c1_2", "newpad", 0.04, 0.13, 1, 0.994)
    c1_2.Draw()

    print("you have provided " + str(len(fileVec)) + " files and " +
          str(len(histVec)) + " histograms to make a overlapping plot")
    print "opening rootfiles"
    c.cd()
    c1_2.SetBottomMargin(0.13)
    c1_2.SetLogy(logstatus[1])
    c1_2.SetLogx(logstatus[0])

    c1_2.cd()
    ii = 0
    inputfile = {}
    print str(fileVec[(len(fileVec) - 1)])

    for ifile_ in range(len(fileVec)):
        print("opening file  " + fileVec[ifile_])
        inputfile[ifile_] = TFile(fileVec[ifile_])
        print "fetching histograms"
        for ihisto_ in range(len(histVec)):
            print("printing histo " + str(histVec[ihisto_]))
            histo = inputfile[ifile_].Get(histVec[ihisto_])
            #status_ = type(histo) is TGraphAsymmErrors
            histList.append(histo)
            # for ratio plot as they should nt be normalize
            histList1.append(histo)
            print histList[ii].Integral()
            #histList[ii].Rebin(xRange[2])
            type_obj = type(histList[ii])
            if (type_obj is TH1D) or (type_obj is TH1F) or (
                    type_obj is TH1) or (type_obj is TH1I):
                histList[ii].Rebin(5)
            histList[ii].Scale(1.0 / histList[ii].Integral())
            maximum.append(histList[ii].GetMaximum())
            maximum.sort()
            ii = ii + 1

    print histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
        if logstatus[1] is 1:
            histList[ih].SetMaximum(maximum[(len(maximum) - 1)] *
                                    25)  #1.4 for log
            histList[ih].SetMinimum(1)  #1.4 for log
        if logstatus[1] is 0:
            histList[ih].SetMaximum(maximum[(len(maximum) - 1)] *
                                    1.2)  #1.4 for log
            histList[ih].SetMinimum(0)  #1.4 for log


#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0:
            if (tt is TGraphAsymmErrors) | (tt is TGraph):
                histList[ih].Draw("AL3")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("CHIST")
        if ih > 0:
            #histList[ih].SetLineWidth(2)
            if (tt is TGraphAsymmErrors) | (tt is TGraph):
                histList[ih].Draw("L3 same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("CHISTsame")

        if (tt is TGraphAsymmErrors) | (tt is TGraph):
            histList[ih].SetMaximum(10000.0)
            histList[ih].SetMinimum(0.0001)
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            histList[ih].SetLineStyle(linestyle[ih])

            #histList[ih].SetMarkerStyle(markerStyle[ih])
            #histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih], legendtext[ih], "PL")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
            histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            leg.AddEntry(histList[ih], legendtext[ih], "L")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.052)
        histList[ih].GetYaxis().SetTitleOffset(0.88)
        histList[ih].GetYaxis().SetTitleFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelSize(.052)
        histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1])
        histList[ih].GetXaxis().SetLabelSize(0.0000)
        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        histList[ih].GetXaxis().SetTitleOffset(1.04)
        histList[ih].GetXaxis().SetTitleFont(22)
        histList[ih].GetXaxis().SetTickLength(0.07)
        histList[ih].GetXaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        # histList[ih].GetXaxis().SetNdivisions(508)
        #

        i = i + 1
    pt = TPaveText(0.0877181, 0.9, 0.9580537, 0.96, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(22)
    pt.SetTextSize(0.046)
    text = pt.AddText(0.05, 0.5, "CMS Work in Progress")
    #text = pt.AddText(0.5,0.5,"12.9 fb^{-1} (13 TeV)")
    text = pt.AddText(0.8, 0.5, " (13 TeV)")
    text = pt.AddText(0.65, 0.5, " AK8")
    pt.Draw()

    #    t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC")
    #    t2a.SetBorderSize(0)
    #    t2a.SetFillStyle(0)
    #    t2a.SetTextSize(0.040)
    #    t2a.SetTextAlign(12)
    #    t2a.SetTextFont(62)
    #    histolabel1= str(fileVec[(len(fileVec)-1)])
    #    text1 = t2a.AddText(0.06,0.5,"CMS Internal")
    #    t2a.Draw()
    leg.Draw()
    #
    #    c.cd()
    outputdirname = 'MonoHPlots/'
    histname = outputdirname + pngname
    c.SaveAs(histname + '.png')
    c.SaveAs(histname + '.pdf')
    outputname = 'cp  -r ' + outputdirname + ' /afs/hep.wisc.edu/home/khurana/public_html/'
    os.system(outputname)
Exemplo n.º 21
0
## \author Wim Lavrijsen

from ROOT import TCanvas, TPaveLabel, TPaveText, TText, TArrow, TLine
from ROOT import gROOT

c1 = TCanvas('c1', 'ROOT FilDir description', 700, 900)
c1.Range(1, 1, 19, 24.5)

title = TPaveLabel(4, 23, 16, 24.2, 'ROOT File/Directory/Key description')
title.SetFillColor(16)
title.Draw()

keycolor = 42
dircolor = 21
objcolor = 46
file = TPaveText(2, 19, 6, 22)
file.SetFillColor(39)
file.Draw()
file.SetTextSize(0.04)
file.AddText('TFile')
file.AddText('Header')
arrow = TArrow(6, 20.5, 17, 20.5, 0.02, '|>')
arrow.SetFillStyle(1001)
arrow.SetLineWidth(2)
arrow.Draw()
free = TPaveText(8, 20, 11, 21)
free.SetFillColor(18)
free.Draw()
free.AddText('First:Last')
free2 = TPaveText(12, 20, 15, 21)
free2.SetFillColor(18)
Exemplo n.º 22
0
def DrawOverlap(fileVec,
                histVec,
                titleVec,
                legendtext,
                pngname,
                logstatus=[0, 0],
                xRange=[-99999, 99999, 1]):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    gStyle.SetTitleOffset(1.1, "Y")
    gStyle.SetTitleOffset(0.9, "X")
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3)

    i = 0

    histList_ = []
    histList = []
    histList1 = []
    maximum = []

    ## Legend
    leg = TLegend(0.65, 0.650, 0.89, 0.85)  #,NULL,"brNDC");
    leg.SetBorderSize(0)
    #    leg.SetNColumns(3)
    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(22)
    leg.SetTextSize(0.045)

    c = TCanvas("c1", "c1", 0, 0, 500, 500)
    #c.SetBottomMargin(0.15)
    #c.SetLeftMargin(0.15)
    #c.SetLogy(0)
    #c.SetLogx(0)
    c1_2 = TPad("c1_2", "newpad", 0., 0.30, 1, 0.994)
    c1_2.Draw()
    c1_1 = TPad("c1_1", "newpad1", 0, 0.02, 1, 0.30)
    c1_1.Draw()

    print("you have provided " + str(len(fileVec)) + " files and " +
          str(len(histVec)) + " histograms to make a overlapping plot")
    print "opening rootfiles"
    c.cd()
    c1_2.SetBottomMargin(0.013)
    c1_2.SetLogy(logstatus[1])
    c1_2.SetLogx(logstatus[0])

    c1_2.cd()
    ii = 0
    inputfile = {}
    print str(fileVec[(len(fileVec) - 1)])
    for ifile_ in range(len(fileVec)):
        print("opening file  " + fileVec[ifile_])
        inputfile[ifile_] = TFile(fileVec[ifile_])
        print "fetching histograms"
        for ihisto_ in range(len(histVec)):
            print("printing histo " + str(histVec[ihisto_]))
            histo = inputfile[ifile_].Get(histVec[ihisto_])
            #status_ = type(histo) is TGraphAsymmErrors
            histList.append(histo)
            # for ratio plot as they should nt be normalize
            histList1.append(histo)
            print histList[ii].Integral()
            histList[ii].Rebin(xRange[2])
            print('after', histList[ii].Integral(0, -1))
            histList[ii].Scale(1.0 / histList[ii].Integral(0, -1))
            maximum.append(histList[ii].GetMaximum())
            maximum.sort()
            ii = ii + 1

    print histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
        if logstatus[1] is 1:
            histList[ih].SetMaximum(maximum[(len(maximum) - 1)] *
                                    25)  #1.4 for log
            histList[ih].SetMinimum(0.001)  #1.4 for log
        if logstatus[1] is 0:
            histList[ih].SetMaximum(maximum[(len(maximum) - 1)] *
                                    1.2)  #1.4 for log
            histList[ih].SetMinimum(0)  #1.4 for log


#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0:
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("AP")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("hist")
        if ih > 0:
            #histList[ih].SetLineWidth(2)
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("P same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("hist same")

        if tt is TGraphAsymmErrors:
            histList[ih].SetMaximum(1.4)
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetMarkerStyle(markerStyle[ih])
            histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih], legendtext[ih], "PL")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
            histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            leg.AddEntry(histList[ih], legendtext[ih], "L")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.062)
        histList[ih].GetYaxis().SetTitleOffset(0.78)
        histList[ih].GetYaxis().SetTitleFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelSize(.062)
        histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1])
        histList[ih].GetXaxis().SetLabelSize(0.0000)
        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        histList[ih].GetXaxis().SetTitleOffset(1.04)
        histList[ih].GetXaxis().SetTitleFont(22)
        histList[ih].GetXaxis().SetTickLength(0.07)
        histList[ih].GetXaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        # histList[ih].GetXaxis().SetNdivisions(508)
        #

        i = i + 1
    pt = TPaveText(0.0877181, 0.91, 0.9580537, 0.95, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(22)
    pt.SetTextSize(0.046)
    #    text = pt.AddText(0.05,0.5,"ATLAS Internal ")
    text = pt.AddText(0.65, 1.0, "#sqrt{s} = 13 TeV (36fb^{-1})")
    pt.Draw()

    t2a = TPaveText(0.277181, 0.81, 0.6780537, 0.89, "brNDC")
    t2a.SetBorderSize(0)
    t2a.SetFillStyle(0)
    t2a.SetTextSize(0.046)
    t2a.SetTextAlign(12)
    t2a.SetTextFont(22)
    histolabel1 = str(fileVec[(len(fileVec) - 1)])
    text1 = t2a.AddText(0.065, 0.5, "ATLAS Internal")
    t2a.Draw()
    leg.Draw()
    #
    c.cd()

    h_inc = histList1[0].Clone()
    h_vbs = histList1[1].Clone()
    h_qcd = histList1[2].Clone()
    h_int = histList1[3].Clone()

    h_inc.Add(h_vbs, -1)
    h_inc.Add(h_qcd, -1)

    ## ratio plot
    hdivide_1 = h_int.Clone()
    hdivide_1.Divide(h_vbs)
    # hdivide_1.GetYaxis().SetTitle(str(legendtext[(len(legendtext)-1)]))
    hdivide_1.GetYaxis().SetTitleSize(0.11)
    hdivide_1.GetYaxis().SetTitle("ratio")

    hdivide_1.GetYaxis().SetTitleOffset(0.43)
    hdivide_1.GetYaxis().SetTitleFont(22)
    hdivide_1.GetYaxis().SetLabelSize(0.13)
    hdivide_1.GetYaxis().CenterTitle()

    hdivide_1.GetXaxis().SetTitleSize(0.14)
    hdivide_1.GetXaxis().SetTitleOffset(0.89)
    hdivide_1.GetXaxis().SetTitleFont(22)
    hdivide_1.GetXaxis().SetLabelSize(0.14)

    hdivide_1.GetYaxis().SetLabelFont(22)
    c.cd()
    c1_1.cd()

    #    c1_1.Range(-7.862408,-629.6193,53.07125,486.5489)
    c1_1.SetFillColor(0)
    c1_1.SetTicky(1)
    c1_1.SetTopMargin(0.0510)
    c1_1.SetBottomMargin(0.3006666678814)
    c1_1.SetFrameFillStyle(0)
    c1_1.SetFrameBorderMode(0)
    c1_1.SetFrameFillStyle(0)
    c1_1.SetFrameBorderMode(0)
    c1_1.SetLogy(0)
    hdivide_1.GetXaxis().SetRangeUser(xRange[0], xRange[1])
    hdivide_1.GetYaxis().SetNdivisions(505)
    c1_1.Draw()
    c1_1.SetGridy()

    hdivide_1.SetMarkerStyle(20)
    hdivide_1.SetMarkerColor(2)
    hdivide_1.SetMarkerSize(1)
    hdivide_1.Draw("P")

    hdivide_2 = h_int.Clone()
    hdivide_2.Divide(h_qcd)
    hdivide_2.SetMarkerStyle(21)
    hdivide_2.SetMarkerColor(4)
    hdivide_2.SetMarkerSize(1)
    hdivide_2.Draw("Psame")

    hdivide_3 = h_int.Clone()
    hdivide_3.Divide(h_inc)
    hdivide_3.SetMarkerStyle(22)
    hdivide_3.SetMarkerColor(1)
    hdivide_3.SetMarkerSize(1)
    hdivide_3.Draw("Psame")

    hdivide_1.SetMinimum(-1.01)
    hdivide_1.SetMaximum(3.20)

    c.cd()

    outputdirname = 'plots/'
    histname = outputdirname + pngname
    c.SaveAs(histname + '.png')
    c.SaveAs(histname + '.pdf')
    c.SaveAs(histname + '.root')
    c.SaveAs(histname + '.C')
Exemplo n.º 23
0
def producePlots(filelist_handle,identifier):
    """

    produce plots for filelist

    """

    files = {}
    plots = []
    failures = []

    for line in filelist_handle.readlines():
        array = line.split()
        if len(array) > 3 :
            name = str(array[0])
            size = float(float(array[1])/1000000000000)
            events = int(array[2])
            run = int(array[3])
            lumi = int(array[4])
            if array[-1] != 'GMT' :
                failures.append(line)
            else :
                thetime = int(time.mktime(time.strptime(' '.join(array[5:]),'%a, %d %b %Y %H:%M:%S %Z')))
                if name in files.keys():
                    files[name]['lumi'].append(lumi)
                else :
                    entry = {}
                    entry['size'] = size
                    entry['events'] = events
                    entry['run'] = [run]
                    entry['lumi'] = [lumi]
                    entry['time'] = thetime
                    files[name] = entry

        if debug == 1 :
            for name in files.keys():
                print name,'size:',files[name]['size'],'events:',files[name]['events'],'runs:',','.join(map(str,files[name]['run'])),'lumis:',','.join(map(str,files[name]['lumi'])),'date:',files[name]['time']


    # print failures
    if len(failures) > 0 :
        print ""
        print "failures:"
        for line in failures :
            print line

    # define time axis
    times = [ files[name]['time'] for name in files ]
    times.sort()
    first_day = times[0]-times[0]%86400
    last_day  = times[len(times)-1]+(86400-times[len(times)-1]%86400)
    days = int((last_day - first_day)/86400.)

    # determine x axis division
    if days%10 == 0:
        bigdiv = 10
        smalldiv = days/10
    elif days%9 == 0:
        bigdiv = 9
        smalldiv = days/9
    elif days%8 == 0:
        bigdiv = 8
        smalldiv = days/8
    elif days%7 == 0:
        bigdiv = 7
        smalldiv = days/7
    elif days%6 == 0:
        bigdiv = 6
        smalldiv = days/6
    elif days%5 == 0:
        bigdiv = 5
        smalldiv = days/5
    elif days%4 == 0:
        bigdiv = 4
        smalldiv = days/4
    elif days%3 == 0:
        bigdiv = 3
        smalldiv = days/3
    elif days%2 == 0:
        bigdiv = 2
        smalldiv = days/2
    else :
        bigdiv = 1
        smalldiv = days


    gROOT.SetBatch(1)

    myStyle = TStyle("Default","Default");
    myStyle.cd();
    myStyle.SetFrameBorderMode(0);
    myStyle.SetCanvasBorderMode(0);
    myStyle.SetPadBorderMode(0);
    myStyle.SetPadColor(0);
    myStyle.SetCanvasColor(0);
    myStyle.SetTitleFillColor(0);
    myStyle.SetTitleBorderSize(1);
    myStyle.SetStatColor(0);
    myStyle.SetStatBorderSize(1);
    myStyle.SetOptStat(0);
    myStyle.SetTimeOffset(first_day+86400)

    c = TCanvas()

    c.SetLeftMargin(0.171)
    c.SetRightMargin(0.04)
    c.SetBottomMargin(0.093)
    c.SetTopMargin(0.08)
    c.SetGridx(1)
    c.SetGridy(1)

    # events histogram
    print 'Drawing histograms for average number of events per day'
    h_events = TH1D("NumberOfEvents" + identifier,"",days,0.,days*86400.)

    h_events.GetYaxis().SetTitle("Number of events [1/24h]")
    h_events.GetYaxis().SetTitleSize(0.08)
    h_events.GetYaxis().SetTitleColor(4)
    h_events.GetYaxis().SetTitleOffset(1.14)
    h_events.GetYaxis().SetLabelSize(0.07)
    h_events.GetYaxis().SetLabelOffset(0.01)
    
    h_events.GetXaxis().SetTimeDisplay(1)
    h_events.GetXaxis().SetTimeFormat("%m/%d")
    h_events.GetXaxis().SetLabelSize(0.05)
    h_events.GetXaxis().SetLabelOffset(0.035)
    h_events.GetXaxis().SetNdivisions(smalldiv * 100 + bigdiv,0)

    h_events.SetLineColor(4)
    h_events.SetLineWidth(3)

    total_events = 0

    for name in files.keys():
        total_events += files[name]['events']
        h_events.Fill(files[name]['time']-first_day,files[name]['events'])
    h_events.SetMaximum(h_events.GetMaximum()*1.3)
    h_events.Draw()

    t_events = TPaveText(0.2,0.75,0.9,0.9,'brNDC')
    t_events.AddText('CMS 2010: %s' % identifier)
    t_events.AddText('Total number of events: %.2E' % (total_events))
    t_events.AddText('Last updated on: %s' % (timestring))
    t_events.SetFillColor(0)
    t_events.SetFillStyle(0)
    t_events.SetBorderSize(0)
    t_events.SetTextAlign(12)
    t_events.Draw()

    name = timefilestring + '_events' + identifier.replace('/','_') + '.png'
    plots.append(name)
    c.SaveAs(name)
    c.Clear()

    # rate histogram
    print 'Drawing histograms for average rate per day'
    h_rate = TH1D("Rate" + identifier,"",days,0.,days*86400.)
    h_rate.GetYaxis().SetTitle("Average Rate [Hz/24h]")
    h_rate.GetYaxis().SetTitleSize(0.08)
    h_rate.GetYaxis().SetTitleColor(4)
    h_rate.GetYaxis().SetTitleOffset(1.14)
    h_rate.GetYaxis().SetLabelSize(0.07)
    h_rate.GetYaxis().SetLabelOffset(0.01)
    
    h_rate.GetXaxis().SetTimeDisplay(1)
    h_rate.GetXaxis().SetTimeFormat("%m/%d")
    h_rate.GetXaxis().SetLabelSize(0.05)
    h_rate.GetXaxis().SetLabelOffset(0.035)
    h_rate.GetXaxis().SetNdivisions(smalldiv * 100 + bigdiv,0)

    h_rate.SetLineColor(4)
    h_rate.SetLineWidth(3)

    h_rate_max = 0.

    for bin in range(days):
        rate = h_events.GetBinContent(bin+1)/24./3600.
        if rate > h_rate_max :
            h_rate_max = rate
        h_rate.SetBinContent(bin+1,rate)

    h_rate.SetMaximum(h_rate_max*1.3)
    h_rate.Draw()

    t_rate = TPaveText(0.2,0.75,0.9,0.9,'brNDC')
    t_rate.AddText('CMS 2010: %s' % identifier)
    t_rate.AddText('Average rate: %.2f Hz' % (float(total_events)/float(days)/24./3600.))
    t_rate.AddText('Last updated on: %s' % (timestring))
    t_rate.SetFillColor(0)
    t_rate.SetFillStyle(0)
    t_rate.SetBorderSize(0)
    t_rate.SetTextAlign(12)
    t_rate.Draw()

    name = timefilestring + '_rate' + identifier.replace('/','_') + '.png'
    plots.append(name)
    c.SaveAs(name)
    c.Clear()

    # size histogram
    print 'Drawing histograms for average size per day'
    h_size = TH1D("Size"+identifier,"",days,0.,days*86400.)

    h_size.GetYaxis().SetTitle("Size [TB/24h]")
    h_size.GetYaxis().SetTitleSize(0.08)
    h_size.GetYaxis().SetTitleColor(4)
    h_size.GetYaxis().SetTitleOffset(1.12)
    h_size.GetYaxis().SetLabelSize(0.07)
    h_size.GetYaxis().SetLabelOffset(0.01)

    h_size.GetXaxis().SetTimeDisplay(1)
    h_size.GetXaxis().SetTimeFormat("%m/%d")
    h_size.GetXaxis().SetLabelSize(0.05)
    h_size.GetXaxis().SetLabelOffset(0.035)
    h_size.GetXaxis().SetNdivisions(smalldiv * 100 + bigdiv,0)

    h_size.SetLineColor(4)
    h_size.SetLineWidth(3)

    total_size = 0.
    for name in files.keys():
        total_size += files[name]['size']
        h_size.Fill(files[name]['time']-first_day,files[name]['size'])
    h_size.SetMaximum(h_size.GetMaximum()*1.3)
    h_size.Draw()

    t_size = TPaveText(0.2,0.75,0.9,0.9,'brNDC')
    t_size.AddText('CMS 2010: %s' % identifier)
    t_size.AddText('Total size: %.2f TB' % (total_size))
    t_size.AddText('Last updated on: %s' % (timestring))
    t_size.SetFillColor(0)
    t_size.SetFillStyle(0)
    t_size.SetBorderSize(0)
    t_size.SetTextAlign(12)
    t_size.Draw()

    #raw_input('Press Enter...')
    name = timefilestring + '_size' + identifier.replace('/','_') + '.png'
    plots.append(name)
    c.SaveAs(name)
    c.Clear()
    return plots
Exemplo n.º 24
0
    def makeCombinedEtaPlot(self, tight=False):
        hist = self.makeL1TimeVsEtaPlot(('tight_' if tight else '') +
                                        'dtOnly_bxidVsEta')[2]
        countsInL1 = []
        for x in np.arange(-.95, 1.05, 0.1):
            totalCounter = 0
            zeroCount = 0
            for y in range(-2, 3):
                totalCounter += hist.GetBinContent(hist.FindBin(x, y))
                if y == 0:
                    zeroCount = hist.GetBinContent(hist.FindBin(x, y))
            countsInL1.append({
                'total': totalCounter,
                'zero': zeroCount,
                'eta': x
            })

        #Graph for results
        graph1 = TEfficiency(hist.GetName(), "", 8, -9.195, -.5)
        graph2 = TEfficiency(hist.GetName(), "", 8, .5, 9.195)

        for item in countsInL1:
            if item['total'] == 0:
                continue
            print item['total'], item['zero'], item['eta']
            if item['eta'] < 0:
                graph1.SetTotalEvents(
                    graph1.FindFixBin(-0.5 + item['eta'] / 0.087),
                    int(item['total']))
                graph1.SetPassedEvents(
                    graph1.FindFixBin(-0.5 + item['eta'] / 0.087),
                    int(item['zero']))
            else:
                graph2.SetTotalEvents(
                    graph2.FindFixBin(0.5 + item['eta'] / 0.087),
                    int(item['total']))
                graph2.SetPassedEvents(
                    graph2.FindFixBin(0.5 + item['eta'] / 0.087),
                    int(item['zero']))

        histHo = None
        if tight:
            histHo = self.plotTightHoTimeVsEta()[3][1]
        else:
            histHo = self.plotHoTimeVsEta()[3][1]

        histHo.SetTitle(('Tight ' if tight else '') + 'Unmatched DT + HO')

        canvas = TCanvas(
            'combinedPlot' + ('Tight ' if tight else '') + hist.GetName(),
            'combinedPlot')
        canvas.cd().SetTopMargin(.15)
        histHo.Draw('ap')
        canvas.Update()
        canvas.cd().SetTicks(0, 0)

        histHo.SetMarkerStyle(2)
        histHo.SetLineColor(colorRwthDarkBlue)
        histHo.SetMarkerColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetRangeUser(-12, 12)
        histHo.GetPaintedGraph().GetXaxis().SetLabelColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetTitleColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetAxisColor(colorRwthDarkBlue)
        yMax = gPad.GetFrame().GetY2()
        yMin = gPad.GetFrame().GetY1()

        #Print average Fraction excluding iEta +/-2
        x = Double(0)
        y = Double(0)
        mean = 0
        var = 0
        for i in range(0, histHo.GetPaintedGraph().GetN()):
            histHo.GetPaintedGraph().GetPoint(i, x, y)
            if abs(x) == 2:
                continue
            mean += y
            var += histHo.GetPaintedGraph().GetErrorY(
                i) * histHo.GetPaintedGraph().GetErrorY(i)

        mean /= histHo.GetPaintedGraph().GetN() - 2
        sigma = sqrt(var / (histHo.GetPaintedGraph().GetN() - 2))

        self.debug(
            "Average fraction excluding iEta +/- 2 %s: %5.2f%% +/- %5.2f%%" %
            ('[Tight]' if tight else '', mean * 100, sigma * 100))

        nTotal = 0
        nPassed = 0
        for item in countsInL1:
            if fabs(item['eta']) == 2 or fabs(item['eta'] == 0):
                continue
            nTotal += item['total']
            nPassed += item['zero']

        #Print again with ClopperPearson uncertainty, the counts are for L1!!!
        mean = nPassed / nTotal * 100
        sigmaPlus = TEfficiency.ClopperPearson(int(nTotal), int(nPassed), .68,
                                               1) * 100 - mean
        sigmaMinus = mean - TEfficiency.ClopperPearson(
            int(nTotal), int(nPassed), .68, 0) * 100
        #self.debug("Average fraction excluding iEta +/- 2 %s with Clop.Pear.: %5.2f%% +%5.2f%% -%5.2f%%"
        #		% ('[Tight]' if tight else '',mean,sigmaPlus,sigmaMinus))

        #Left axis part
        f1 = TF1("f1", "x", -0.87, 0)
        A1 = TGaxis(-10, yMax, -0.5, yMax, "f1", 010, "-")
        A1.SetLineColor(colorRwthRot)
        A1.SetLabelColor(colorRwthRot)
        A1.Draw()

        #Right axis part
        f2 = TF1("f2", "x", 0, 0.87)
        A2 = TGaxis(0.5, yMax, 10, yMax, "f2", 010, "-")
        A2.SetLineColor(colorRwthRot)
        A2.SetLabelColor(colorRwthRot)
        A2.Draw()

        #Box for shading out 0
        box = TBox(-.5, yMin, 0.5, yMax)
        box.SetLineColor(colorRwthDarkGray)
        box.SetFillColor(colorRwthDarkGray)
        box.SetFillStyle(3013)
        box.Draw('same')

        #Left L1 eta
        graph1.SetMarkerColor(colorRwthRot)
        graph1.SetLineColor(colorRwthRot)
        graph1.SetMarkerStyle(20)
        graph1.Draw('same,p')

        #Right L1Eta
        graph2.SetMarkerColor(colorRwthRot)
        graph2.SetLineColor(colorRwthRot)
        graph2.SetMarkerStyle(20)
        graph2.Draw('same,p')

        #Label for extra axis
        axisLabel = TPaveText(0.83, 0.85, 0.89, 0.9, "NDC")
        axisLabel.AddText('#eta_{L1}')
        axisLabel.SetBorderSize(0)
        axisLabel.SetFillStyle(0)
        axisLabel.SetTextColor(colorRwthRot)
        axisLabel.SetTextSize(0.05)
        axisLabel.Draw()

        #Legend
        legend = getLegend(x1=0.1, y1=0.1, x2=0.4, y2=.35)
        legend.AddEntry(histHo, 'HO #in #pm12.5 ns', 'pe')
        legend.AddEntry(graph1, ('Tight ' if tight else '') + 'L1 BXID = 0',
                        'pe')
        legend.Draw()

        canvas.Update()
        self.storeCanvas(canvas,
                         "combinedFractionL1AndHo" +
                         ('Tight' if tight else ''),
                         drawMark=False)

        return histHo, graph1, canvas, A1, f1, A2, f2, box, graph2, axisLabel, legend
Exemplo n.º 25
0
print "******"
print "mistag SF:", SF

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

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

sfMerge.Draw("e1hist")

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

c3.SaveAs("Merge_SF.pdf")
Exemplo n.º 26
0
                if 'pt' in params['FILE_PREFIX']:
                    xplot_range = [
                        params['PT_BINS'][0],
                        params['PT_BINS'][len(params['PT_BINS']) - 1]
                    ]
                else:
                    xplot_range = [
                        params['CT_BINS'][0],
                        params['CT_BINS'][len(params['CT_BINS']) - 1]
                    ]

                frame = gPad.DrawFrame(
                    xplot_range[0], rangePad[0], xplot_range[1], rangePad[1],
                    label['title'] + ";" + xlabel + ";" + label[meas][0] +
                    "[ GeV" + label[meas][1] + "]")
                pinfo2 = TPaveText(0.5, 0.65, 0.88, 0.86, "NDC")
                pinfo2.SetBorderSize(0)
                pinfo2.SetFillStyle(0)
                pinfo2.SetTextAlign(22)
                pinfo2.SetTextFont(43)
                pinfo2.SetTextSize(33)
                string1 = '#bf{ALICE Internal}'
                string2 = 'Pb-Pb  #sqrt{#it{s}_{NN}} = 5.02 TeV,  0-90%'
                pinfo2.AddText(string1)
                pinfo2.AddText(string2)
                string = label[meas][0] + ' = {:.2f} #pm {:.2f} '.format(
                    pol0.GetParameter(0) * 10**(3),
                    pol0.GetParError(0) * 10**(3)) + 'MeV' + label[meas][1]
                if bkgModels == 'pol2':
                    pol2_meas.append(
                        [pol0.GetParameter(0),
Exemplo n.º 27
0
def Fitting(scalestring,Fit_id):
   list_scale = scalestring.split(",")

   # Set up canvas, remove titles and stats boxes
   gStyle.SetOptTitle(0)
   gStyle.SetOptStat(0)
   c = TCanvas("c","c",1600,800)

   # Legend
   mylegend = TLegend(1.0,0.3,0.75,1.0,"Legend")
   mylegend.SetTextSize(0.04)

   dict_scale_hist= {}
   dict_gaus_fit= {}
   dict_bukin_fit= {}
   colorcounter= 1

   for scale in list_scale:
       histname = "Higgs_"+scale+"_M"
       dict_scale_hist[scale] = file.Get(histname)
       h=dict_scale_hist[scale]

       xmin = h.GetMean()-3*h.GetRMS()
       xmax = h.GetMean()+3*h.GetRMS()

       # If error here, check Bukin.py has: import math
       dict_gaus_fit[scale] = TF1 ("Gauss",Gauss(),xmin,xmax,3) 
       dict_bukin_fit[scale] = TF1 ("Bukin",Bukin(),xmin,xmax,6)

   for scale in list_scale:
       h=dict_scale_hist[scale]
       if Fit_id==1:
          print
          print "The ROOT Gaussian fit produces: "
          h.Fit("gaus","0 +")  # zero option to not draw

          print
          print "The user defined Gaussian fit produces: "
          dict_gaus_fit[scale].SetParName(0,"User_Constant")
          dict_gaus_fit[scale].SetParName(1,"User_Mean")
          dict_gaus_fit[scale].SetParName(2,"User_Sigma")
          dict_gaus_fit[scale].SetLineColor(colorcounter)
          dict_gaus_fit[scale].SetParameters(100, h.GetMean(),h.GetRMS())
 
          # Add legend entry for Gaussian
          mylegend.AddEntry(dict_gaus_fit[scale],scale+"_Gauss","l")

          if DrawBothHistAndFit:
              h.Fit(dict_gaus_fit[scale],"+ R")
              f = h.GetFunction("Gauss")
              f.SetLineColor(colorcounter)

          if DrawJustFit:
              h.Fit(dict_gaus_fit[scale],"RQ","RO SAME",xmin,xmax)
              f = h.GetFunction("Gauss")
              f.SetLineColor(colorcounter)

       elif Fit_id==2:
          print
          print "The Bukin fit produces: "
          dict_bukin_fit[scale].SetParameters(0, h.GetMean(), h.GetRMS(), 0, 0, 0)
          dict_bukin_fit[scale].SetLineColor(colorcounter)


          # Add legend entry
          mylegend.AddEntry(dict_bukin_fit[scale],scale+"_Bukin","l")

          if DrawBothHistAndFit:
              h.Fit(dict_bukin_fit[scale],"+ R")
              f = h.GetFunction("Bukin")
              f.SetLineColor(colorcounter)

          if DrawJustFit:
              h.Fit(dict_bukin_fit[scale],"RQ","RO SAME",xmin,xmax)
              f = h.GetFunction("Bukin")
              f.SetLineColor(colorcounter)

       colorcounter += 1

   for scale in list_scale:
       h=dict_scale_hist[scale]
       if DrawBothHistAndFit:
           h.Draw("same")
       if DrawJustFit:
           h.Draw("func same")

   #Set Canvas Title
   pave = TPaveText(0.00,0.9,0.3,1.0,"tblrNDC")
   pave.SetTextColor(1)
   pave.SetTextSize(0.05)
   pave.AddText("Histogram Fits")
   pave.Draw("same")

   # Draw legend
   mylegend.Draw("same")

   c.Print("output/fitted.pdf")
Exemplo n.º 28
0
def createPlots2D_(plot, compounddetectorname):
    """2D material budget map to know exactly what we are adding.
    """

    #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

    # 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.items():
        subDetectorFilename = "matbdg_%s.root" % subDetector
        if not checkFile_(subDetectorFilename):
            print("Error opening file: %s" % subDetectorFilename)
            continue

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

        #hist_X0_detectors[subDetector] = prof_X0_XXX
        hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionXY("_pxy", "B")
        print(subDetector)

    # First Plot: BeamPipe + Tracker + ECAL + HCal + HGCal + MB + MGNT

    # Create "null" histo
    minX = 1.03 * hist_X0_detectors["BeamPipe"].GetXaxis().GetXmin()
    maxX = 1.03 * hist_X0_detectors["BeamPipe"].GetXaxis().GetXmax()
    minY = 1.03 * hist_X0_detectors["BeamPipe"].GetYaxis().GetXmin()
    maxY = 1.03 * hist_X0_detectors["BeamPipe"].GetYaxis().GetXmax()

    frame = TH2F("frame", "", 10, minX, maxX, 10, minY, maxY)
    frame.SetMinimum(0.1)
    frame.SetMaximum(10.)
    frame.GetXaxis().SetTickLength(frame.GetXaxis().GetTickLength() * 0.50)
    frame.GetYaxis().SetTickLength(frame.GetXaxis().GetTickLength() / 4.)

    hist2d_X0_total = hist_X0_detectors["BeamPipe"]

    # stack
    hist2dTitle = (
        '%s %s;%s;%s;%s' %
        (plots[plot].quotaName, "All detectors", plots[plot].abscissa,
         plots[plot].ordinate, plots[plot].quotaName))

    hist2d_X0_total.SetTitle(hist2dTitle)
    frame.SetTitle(hist2dTitle)
    frame.SetTitleOffset(0.5, "Y")

    #If here you put different histomin,histomaxin plot_utils you won't see anything
    #for the material plots.
    if plots[plot].histoMin != -1.:
        hist2d_X0_total.SetMinimum(plots[plot].histoMin)
    if plots[plot].histoMax != -1.:
        hist2d_X0_total.SetMaximum(plots[plot].histoMax)

    #
    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors",
                               2480 + 248, 580 + 58 + 58)
    can_SubDetectors.SetTopMargin(0.1)
    can_SubDetectors.SetBottomMargin(0.1)
    can_SubDetectors.SetLeftMargin(0.04)
    can_SubDetectors.SetRightMargin(0.06)
    can_SubDetectors.SetFillColor(kWhite)
    gStyle.SetOptStat(0)
    gStyle.SetTitleFillColor(0)
    gStyle.SetTitleBorderSize(0)
    gStyle.SetOptTitle(0)

    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.SetTitleOffset(0.5, "Y")
    hist2d_X0_total.GetYaxis().SetTitleOffset(0.50)
    #hist2d_X0_total.GetXaxis().SetTitleOffset(1.15);
    #hist2d_X0_total.GetXaxis().SetNoExponent(True)
    #hist2d_X0_total.GetYaxis().SetNoExponent(True)

    # colors
    for det, color in DETECTORS.items():
        hist_X0_detectors[det].SetMarkerColor(color)
        hist_X0_detectors[det].SetFillColor(color)

    for det, histo in hist_X0_detectors.items():
        print(det)
        histo.Draw("same")

    # Legenda
    theLegend_SubDetectors = TLegend(0.100, 0.7, 0.90,
                                     0.90)  #(0.180,0.8,0.98,0.90)
    theLegend_SubDetectors.SetNColumns(3)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in hist_X0_detectors.items():
        theLegend_SubDetectors.AddEntry(histo, det, "f")
    #theLegend_SubDetectors.AddEntry(hgbound1, "HGCal Eta Boundaries [1.3, 3.0]",  "l")

    theLegend_SubDetectors.Draw()

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

    #Add eta labels
    keep_alive = []
    if plots[plot].iDrawEta:
        keep_alive.extend(drawEtaValues())

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.png" %
                            (theDirname, compounddetectorname, plot))
    #It seems that it is too heavy to create .pdf and .root
    #can_SubDetectors.SaveAs("%s/MaterialBdg_FromVertexToEndofHGCal_%s.pdf" % (theDirname, plot))
    #can_SubDetectors.SaveAs("%s/MaterialBdg_FromVertexToEndofHGCal_%s.root" % (theDirname, plot))

    hist2d_X0_total.GetXaxis().SetRangeUser(0., 7000.)
    #Draw eta values in the zoom case
    keep_alive = []
    keep_alive.extend(drawHalfEtaValues())
    #hist2d_X0_total.Draw("COLZ")
    can_SubDetectors.Update()
    can_SubDetectors.Modified()
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s_Zpluszoom.png" %
                            (theDirname, compounddetectorname, plot))
Exemplo n.º 29
0
## \file
## \ingroup tutorial_pyroot
## Display demo help.
##
## \macro_code
##
## \author Wim Lavrijsen

import os
from ROOT import TCanvas, TPaveText
from ROOT import gROOT

chelp = TCanvas('chelp', 'Help to run demos', 200, 10, 700, 500)

welcome = TPaveText(.1, .8, .9, .97)
welcome.AddText('Welcome to the ROOT demos')
welcome.SetTextFont(32)
welcome.SetTextColor(4)
welcome.SetFillColor(24)
welcome.Draw()

hdemo = TPaveText(.05, .05, .95, .7)
hdemo.SetTextAlign(12)
hdemo.SetTextFont(52)

text = """- Run demo hsimple.py first. Then in any order
- Click left mouse button to execute one demo
- Click right mouse button to see the title of the demo
- Click on 'Close Bar' to exit from the demo menu
- Select 'File/Print' to print a Postscript view of the canvas
- You can execute a demo with the mouse or type commands
Exemplo n.º 30
0
    hs.GetYaxis().SetLabelSize(15)
    hs.GetYaxis().SetTitle("Events")

    # legend
    legend = TLegend(0.74, 0.68, 0.94, 0.87)
    legend.AddEntry(ZMass_DATA[i], "Data", "p")
    legend.AddEntry(ZMass_MC_DY[i], "Drell-Yan", "f")
    legend.AddEntry(ZMass_MC_TTJets[i], "t#bar{t}", "f")
    legend.SetFillColor(kWhite)
    legend.SetLineColor(kBlack)
    legend.SetTextFont(43)
    legend.SetTextSize(20)
    legend.Draw()

    # box with fit results
    pv = TPaveText(0.64, 0.35, 0.94, 0.65, "brNDC")
    pv.AddText("DATA:")
    pv.AddText("Z DCBmean = " + str(round(massFitDATA_dict[key], 2)) + " GeV")
    pv.AddText("Z DCBwidth = " + str(round(widthFitDATA_dict[key], 2)) +
               " GeV")
    pv.AddText("MC:")
    pv.AddText("Z DCBmean = " + str(round(massFitMC_dict[key], 2)) + " GeV")
    pv.AddText("Z DCBwidth = " + str(round(widthFitMC_dict[key], 2)) + " GeV")
    pv.SetFillColor(kWhite)
    pv.SetBorderSize(1)
    pv.SetTextFont(40)
    pv.SetTextSize(0.037)
    pv.SetTextFont(42)
    pv.SetTextAlign(12)  #text left aligned
    # cange color of text
    if "ele" in nameList[i]: