示例#1
0
            hEffFDRatio[iFile].SetBinError(iBin + 1, 1.e-20)

PtMin = hEffPrompt[0].GetBinLowEdge(1)
PtMax = hEffPrompt[0].GetBinLowEdge(
    hEffPrompt[0].GetNbinsX()) + hEffPrompt[0].GetBinWidth(
        hEffPrompt[0].GetNbinsX())
for histo in hEffPrompt:
    if histo.GetBinLowEdge(1) < PtMin:
        PtMin = histo.GetBinLowEdge(1)
    if histo.GetBinLowEdge(histo.GetNbinsX()) + histo.GetBinWidth(
            histo.GetNbinsX()) > PtMax:
        PtMax = histo.GetBinLowEdge(histo.GetNbinsX()) + histo.GetBinWidth(
            histo.GetNbinsX())

cPrompt = TCanvas('cPrompt', '', 1000, 500)
cPrompt.Divide(2, 1)
cPrompt.cd(1).DrawFrame(
    PtMin, hEffPrompt[0].GetMinimum() / 5, PtMax, 1.,
    ';#it{p}_{T} (GeV/#it{c}); Prompt (Acc #times #epsilon)')
cPrompt.cd(1).SetLogy()
for iFile in range(len(inFileNames)):
    hEffPrompt[iFile].Draw('same')
leg.Draw()
cPrompt.cd(2).DrawFrame(
    PtMin, hEffPromptRatio[1].GetMinimum() / 2, PtMax,
    hEffPromptRatio[1].GetMaximum() * 1.5,
    ';#it{p}_{T} (GeV/#it{c}); Prompt (Acc #times #epsilon) ratio')
for iFile in range(len(inFileNames)):
    if iFile == 0:
        continue
    hEffPromptRatio[iFile].Draw('same')
                multEHistTest[1].Fill(endataTest[i].sum()*100000000000000,1/176.16)
            elif countedPeaks2Test[i]==2:
                multEHistTest[2].Fill(endataTest[i].sum()*100000000000000,1/176.16)
            elif countedPeaks2Test[i]==3:
                multEHistTest[3].Fill(endataTest[i].sum()*100000000000000,1/176.16)
            elif countedPeaks2Test[i]==4:
                multEHistTest[4].Fill(endataTest[i].sum()*100000000000000,1/176.16)
            elif countedPeaks2Test[i]==5:
                multEHistTest[5].Fill(endataTest[i].sum()*100000000000000,1/176.16)
            else:
                multEHistTest[6].Fill(endataTest[i].sum()*100000000000000,1/176.16)


##draw histograms
canvas6=TCanvas('canvas6','2e Separation Comparison',1200,800)
canvas6.Divide(2,2)
canvas6.cd(1)
#sep2TotHist.Draw()
#sep2TotHist.SetStats(0)
#sep2TagHist.Draw("same")
#sep2TagHist.SetStats(0)
SepHistC.Draw()
#SepHistC.SetStats(0)
#sep2TagHist.SetLineColor(ROOT.kGreen+3)
#SepHistC.SetLineColor(ROOT.kRed)
#sep2SimLegend.AddEntry(sep2TotHist,"True 2e events","l")
#sep2SimLegend.AddEntry(sep2TagHist,"Tagged 2e events","l")
#sep2SimLegend.AddEntry(SepHistC,"Correctly tagged 2e events","l")
#sep2SimLegend.Draw()
canvas6.cd(2)
sep2Hist.Draw()
            hyieldHM.SetLineColor(colors[imult % len(colors)])
            hyieldHM.SetMarkerColor(colors[imult % len(colors)])
            hyieldHM.SetMarkerStyle(21)
            hyieldHM.SetMarkerSize(0.8)
            hyieldHM.Draw("same")
            legyieldstring = "%.1f #leq %s < %.1f (HM)" % \
                  (binsmin[imult], latexbin2var, binsmax[imult])
            legyield.AddEntry(hyieldHM, legyieldstring, "LEP")
        legyield.Draw()

        ccross.SaveAs("%s/PtSpec_ComparisonCorrYields_%s_%scombined%s.eps" % \
                  (folder_plots, case, arraytype[0], arraytype[1]))

    #Efficiency plot
    cEff = TCanvas('cEff', '', 800, 400)
    cEff.Divide(2)
    cEff.cd(1).DrawFrame(0, 1.e-4, 25, 1., \
                         ";#it{p}_{T} (GeV/#it{c});Prompt %s (Acc #times eff)" % name)
    cEff.cd(1).SetLogy()

    legeff = TLegend(.3, .15, .7, .35)
    legeff.SetBorderSize(0)
    legeff.SetFillColor(0)
    legeff.SetFillStyle(0)
    legeff.SetTextFont(42)
    legeff.SetTextSize(0.035)

    lstyle = [1, 2, 3, 4, 5]
    for imult, iplot in enumerate(plotbinMB):
        if not iplot:
            continue
示例#4
0
def MakePlot(spectra, triggers, options):
    """
        Make 2-panel comparison plot (left spectra for the different trigger classes, right the ratio
        to min bias)
        """
    plot = TCanvas("comparisonTriggers",
                   "Comparison of the raw spectra for different triggers",
                   1000, 500)
    plot.Divide(2, 1)

    ratios = dict()

    plotstyles = {"MinBias":Style(kBlack,20), "EMCJHigh":Style(kRed,24), "EMCJLow":Style(kBlue,25), \
                    "EMCGHigh":Style(kGreen+2, 26), "EMCGLow":Style(kOrange+2, 27) }

    specpad = plot.cd(1)
    specpad.SetGrid(False, False)
    specpad.SetLogx(True)
    specpad.SetLogy(True)
    axispec = TH1F("axispec",
                   "; p_{T} (GeV/c); 1/N_{ev} dN/dp_{t} ((GeV/c)^{-1})", 1000,
                   0., 100.)
    axispec.SetStats(False)
    axispec.GetYaxis().SetRangeUser(1e-10, 100)
    axispec.Draw("axis")
    gObjects.append(axispec)

    leg = TLegend(0.15, 0.15, 0.35, 0.35)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    gObjects.append(leg)

    mbspectrum = spectra["MinBias"]
    for trigger, spectrum in spectra.iteritems():
        SetStyle(spectrum, plotstyles[trigger])
        spectrum.Draw("epsame")
        gObjects.append(spectrum)
        leg.AddEntry(spectrum, trigger, "lep")
        if trigger != "MinBias":
            ratios[trigger] = deepcopy(spectrum)
            ratios[trigger].Divide(mbspectrum)
            SetStyle(ratios[trigger], plotstyles[trigger])
    leg.Draw()
    label = TPaveText(0.35, 0.75, 0.89, 0.89, "NDC")
    label.SetBorderSize(0)
    label.SetFillStyle(0)
    label.SetTextFont(42)
    label.SetTextAlign(12)
    label.AddText("Cuts:        %s" % (options["cuts"]))
    label.AddText("Pileup rej.: %s" % (options["pileup"]))
    label.Draw()
    gObjects.append(label)

    ratiopad = plot.cd(2)
    ratiopad.SetLogx(True)
    ratiopad.SetGrid(False, False)
    axiratio = TH1F("axiratio", "; p_{t} (GeV/c); Ratio to Min. Bias", 1000,
                    0., 100.)
    axiratio.GetYaxis().SetRangeUser(0., 1000.)
    axiratio.SetStats(False)
    axiratio.Draw("axis")
    gObjects.append(axiratio)

    for ratio in ratios.values():
        ratio.Draw("epsame")
        gObjects.append(ratio)

    plot.cd()
    gObjects.append(plot)
    return plot
示例#5
0
from ROOT import TH1D, TCanvas
from alarm import *

inFile = open("log.txt")
lines = inFile.readlines()

histIn = TH1D("mean inside", "meanInside", 60, 0, 10)
histOut = TH1D("mean outside", "meanOutside", 300, 0, 6)

for i in lines[0::2]:
    histIn.Fill(float(i))

for i in lines[1::2]:
    histOut.Fill(float(i))

c = TCanvas("mean", "mean", 1000, 500)
c.Divide(2, 1)

c.cd(1)
histIn.Draw()
c.cd(2)
histOut.Draw()

alarm = Alarm()
alarm.send_message("Finished!")

try:
    input()
except:
    pass
示例#6
0
                               'fp')
legCatania['CorrYield'].AddEntry(gCorrYieldCatania,
                                 'FONLL x Catania (frag+coal)', 'fp')
legCatania['Raa'].AddEntry(sCatania['Cent'], 'Catania (frag+coal)', 'l')
legCatania['Signif'].AddEntry(gCorrYieldCatania, 'FONLL x Catania (frag+coal)',
                              'fp')

lineAtOne = TLine(cutVars['Pt']['min'][0] - 1, 1.,
                  cutVars['Pt']['max'][len(cutVars['Pt']['max']) - 1] + 1, 1.)
lineAtOne.SetLineColor(kBlack)
lineAtOne.SetLineStyle(9)

outfile.cd()

cRaa = TCanvas('cRaa', '', 1000, 1000)
cRaa.Divide(2, 2)
cRaa.cd(1).DrawFrame(cutVars['Pt']['min'][0] - 1, 0,
                     cutVars['Pt']['max'][len(cutVars['Pt']['max']) - 1] + 1,
                     2, ';#it{p}_{T} (GeV/#it{c});#it{R}_{AA}')
lineAtOne.Draw('same')
for iRaaTAMU in sTAMU:
    SetSplineStyle(sTAMU[iRaaTAMU], colorsFill['TAMU'])
    sTAMU[iRaaTAMU].Draw('same')
    sTAMU[iRaaTAMU].Write('sTAMU%s' % iRaaTAMU)
if inputCfg['PublishedResult']['plotPublished']:
    hDRaaStat.Draw('same')
    gDRaaSyst.Draw('2')
legTAMU['Raa'].Draw('same')
cRaa.cd(2).DrawFrame(cutVars['Pt']['min'][0] - 1, 0,
                     cutVars['Pt']['max'][len(cutVars['Pt']['max']) - 1] + 1,
                     2, ';#it{p}_{T} (GeV/#it{c});#it{R}_{AA}')
示例#7
0
def fitChicSpectrum(dataset, binname):
    """ Fit chic spectrum"""

    x = RooRealVar('Qvalue', 'Q', 9.7, 10.1)
    x.setBins(80)

    mean_1 = RooRealVar("mean_1", "mean ChiB1", 9.892, 9, 10, "GeV")
    sigma_1 = RooRealVar("sigma_1", "sigma ChiB1", 0.0058, 'GeV')
    a1_1 = RooRealVar('#alpha1_1', '#alpha1_1', 0.748)
    n1_1 = RooRealVar('n1_1', 'n1_1', 2.8)
    a2_1 = RooRealVar('#alpha2_1', '#alpha2_1', 1.739)
    n2_1 = RooRealVar('n2_1', 'n2_1', 3.0)

    deltam = RooRealVar('deltam', 'deltam', 0.01943)

    mean_2 = RooFormulaVar("mean_2", "@0+@1", RooArgList(mean_1, deltam))
    sigma_2 = RooRealVar("sigma_2", "sigma ChiB2", 0.0059, 'GeV')
    a1_2 = RooRealVar('#alpha1_2', '#alpha1_2', 0.738)
    n1_2 = RooRealVar('n1_2', 'n1_2', 2.8)
    a2_2 = RooRealVar('#alpha2_2', '#alpha2_2', 1.699)
    n2_2 = RooRealVar('n2_2', 'n2_2', 3.0)

    parameters = RooArgSet()

    parameters.add(RooArgSet(sigma_1, sigma_2))
    parameters = RooArgSet(a1_1, a2_1, n1_1, n2_1)
    parameters.add(RooArgSet(a1_2, a2_2, n1_2, n2_2))

    chib1_pdf = My_double_CB('chib1', 'chib1', x, mean_1, sigma_1, a1_1, n1_1,
                             a2_1, n2_1)
    chib2_pdf = My_double_CB('chib2', 'chib2', x, mean_2, sigma_2, a1_2, n1_2,
                             a2_2, n2_2)

    #background
    q01S_Start = 9.5
    alpha = RooRealVar("#alpha", "#alpha", 1.5, -1, 3.5)  #0.2 anziche' 1
    beta = RooRealVar("#beta", "#beta", -2.5, -7., 0.)
    q0 = RooRealVar("q0", "q0", q01S_Start)  #,9.5,9.7)
    delta = RooFormulaVar("delta", "TMath::Abs(@0-@1)", RooArgList(x, q0))
    b1 = RooFormulaVar("b1", "@0*(@1-@2)", RooArgList(beta, x, q0))
    signum1 = RooFormulaVar("signum1", "( TMath::Sign( -1.,@0-@1 )+1 )/2.",
                            RooArgList(x, q0))

    background = RooGenericPdf("background", "Background",
                               "signum1*pow(delta,#alpha)*exp(b1)",
                               RooArgList(signum1, delta, alpha, b1))

    parameters.add(RooArgSet(alpha, beta, q0))

    #together
    chibs = RooArgList(chib1_pdf, chib2_pdf, background)

    n_chib = RooRealVar("n_chib", "n_chib", 2075, 0, 100000)
    ratio_21 = RooRealVar("ratio_21", "ratio_21", 0.5, 0, 1)
    n_chib1 = RooFormulaVar("n_chib1", "@0/(1+@1)",
                            RooArgList(n_chib, ratio_21))
    n_chib2 = RooFormulaVar("n_chib2", "@0/(1+1/@1)",
                            RooArgList(n_chib, ratio_21))
    n_background = RooRealVar('n_background', 'n_background', 4550, 0, 50000)
    ratio_list = RooArgList(n_chib1, n_chib2, n_background)

    modelPdf = RooAddPdf('ModelPdf', 'ModelPdf', chibs, ratio_list)

    frame = x.frame(RooFit.Title('m'))
    range = x.setRange('range', 9.7, 10.1)
    result = modelPdf.fitTo(dataset, RooFit.Save(), RooFit.Range('range'))
    dataset.plotOn(frame, RooFit.MarkerSize(0.7))

    modelPdf.plotOn(frame, RooFit.LineWidth(2))

    #plotting
    canvas = TCanvas('fit', "", 1400, 700)
    canvas.Divide(1)
    canvas.cd(1)
    gPad.SetRightMargin(0.3)
    gPad.SetFillColor(10)
    modelPdf.paramOn(frame, RooFit.Layout(0.725, 0.9875, 0.9))
    frame.Draw()
    canvas.SaveAs('out-' + binname + '.png')
示例#8
0
	def plotMatchedHoTime(self):
		c2 = TCanvas("cTimeforMatchedHoHits","Matched Ho time",1200,400)
		c2.Divide(3,1)
		
		### Plot matched DT/RPC
		c2.cd(1).SetLogy()
		hBxIdBest = self.fileHandler.getHistogram('timingSupport_MatchedDtRpcHo_Time')
		hBxIdDtOnly = self.fileHandler.getHistogram('timingSupport_UnmatchedDtHo_Time')
		hBxIdDtOnlyTight = self.fileHandler.getHistogram('timingSupport_tight_UnmatchedDtHo_Time')
		hBxIdOther = self.fileHandler.getHistogram('timingSupport_OtherCodesHo_Time')
		
		hIntegral = hBxIdDtOnly.Integral()
		hIntegralCentral = hBxIdDtOnly.Integral(
			hBxIdDtOnly.FindBin(-12.5),
			hBxIdDtOnly.FindBin(12.5))
		hIntegralTight = hBxIdDtOnlyTight.Integral()
		hIntegralTighCentral = hBxIdDtOnlyTight.Integral(
			hBxIdDtOnlyTight.FindBin(-12.5),
			hBxIdDtOnlyTight.FindBin(12.5))
		
#		hBxIdBest.Sumw2()
#		hBxIdDtOnly.Sumw2()
#		hBxIdOther.Sumw2()
		hBxIdBest.SetLineColor(colorRwthDarkBlue)
		hBxIdBest.SetLineWidth(3)
		hBxIdBest.SetStats(0)
		hBxIdBest.SetTitle("Matched DT/RPC + HO")
		hBxIdBest.GetXaxis().SetRangeUser(-50,50)
		#hBxIdBest.GetYaxis().SetRangeUser(2e-4,1)
		hBxIdBest.Scale(1/hBxIdBest.Integral())
		hBxIdBest.GetYaxis().SetTitle("rel. fraction")
		setupAxes(hBxIdBest)
		setBigAxisTitles(hBxIdBest)
		hBxIdBest.Draw()
		label = self.drawLabel()
		
		### Plot unmatched DT
		c2.cd(2).SetLogy()
		hBxIdDtOnly.SetLineColor(colorRwthDarkBlue)
		hBxIdDtOnly.SetLineWidth(3)
		hBxIdDtOnly.SetStats(0)
		hBxIdDtOnly.SetTitle("Unmatched DT + HO")
		hBxIdDtOnly.GetXaxis().SetRangeUser(-50,50)
		#hBxIdDtOnly.GetYaxis().SetRangeUser(2e-4,1)
		hBxIdDtOnly.Scale(1/hBxIdDtOnly.Integral())
		hBxIdDtOnly.GetYaxis().SetTitle("rel. fraction")
		setupAxes(hBxIdDtOnly)
		setBigAxisTitles(hBxIdDtOnly)
		hBxIdDtOnly.Draw()
		
		### Plot other codes
		c2.cd(3).SetLogy()
		hBxIdOther.SetLineColor(colorRwthDarkBlue)
		hBxIdOther.SetLineWidth(3)
		hBxIdOther.SetStats(0)
		hBxIdOther.SetTitle("Lower quality muon + HO")
		hBxIdOther.GetXaxis().SetRangeUser(-50,50)
		#hBxIdOther.GetYaxis().SetRangeUser(2e-4,1)
		hBxIdOther.Scale(1/hBxIdOther.Integral())
		hBxIdOther.GetYaxis().SetTitle("rel. fraction")
		setupAxes(hBxIdOther)
		setBigAxisTitles(hBxIdOther)
		hBxIdOther.Draw()
		
		self.storeCanvas(c2,"matchedHoTime")
		
		c = TCanvas('cDtOnlyWithTight',"DT only with tight",600,600)
		c.SetLogy()
		hBxIdDtOnlyCopy = hBxIdDtOnly.DrawCopy()
		hBxIdDtOnlyTight.Scale(1/hBxIdDtOnlyTight.Integral())
		hBxIdDtOnlyTight.SetLineColor(colorRwthMagenta)
		hBxIdDtOnlyTight.Draw('same')
		
		legend = getLegend(y1=0.75,y2=.9)
		legend.AddEntry(hBxIdDtOnlyCopy,'DT only','l')
		legend.AddEntry(hBxIdDtOnlyTight,'DT only, tight','l')
		legend.Draw()
		
		self.debug(80*'#')
		self.debug('Not tight: Integral in [-12.5,12.5]:\t %8d => %5.2f%% +/- %5.2f%%' % (hIntegral,
				hIntegralCentral/float(hIntegral)*100,calcSigma(hIntegralCentral, hIntegral)*100))
		self.debug('Tight: Integral in [-12.5,12.5]:\t\t %8d => %5.2f%% +/- %5.2f%%' % (hIntegralTight,
				hIntegralTighCentral/float(hIntegralTight)*100,calcSigma(hIntegralTighCentral, hIntegralTight)*100))
		self.debug(80*'#')
		
		self.storeCanvas(c, 'matchedHoDtOnlyWithTight')
				
		return label,c2,hBxIdBest,hBxIdDtOnly,hBxIdOther,hBxIdDtOnlyTight,hBxIdDtOnlyCopy,c,legend
示例#9
0
	def plotDetectorContributionsToTiming(self):
		#Prepare canvas
		canvas = TCanvas("canvasDetectorContributions","detectorContributions",1200,600)
		canvas.Divide(2,1)
		canvas.cd(1).SetGridx(0)
		canvas.cd(1).SetGridy(0)
		canvas.cd(1).SetLogy()
	
		#prepare histogram
		hist = self.fileHandler.getHistogram("multiplicity/detectorIndexBxWrong_Multiplicity")
		hist.GetXaxis().SetRangeUser(0.5,5.5)
		hist.SetLineColor(colorRwthDarkBlue)
		hist.SetFillColor(colorRwthDarkBlue)
		#Prepare the bin labels
		x = ['RPC','DT','DT/RPC','CSC','CSC/RPC']
		for i in range(1,6):
			hist.GetXaxis().SetBinLabel(i+1,x[i-1])
		hist.GetXaxis().SetLabelFont(62)
		hist.GetYaxis().SetLabelFont(62)
		hist.GetYaxis().SetTitleFont(62)
		hist.Scale(1/hist.Integral())
		hist.GetYaxis().SetTitle('rel. fraction')
		hist.SetStats(0)
		hist.SetTitle('Subdetectors in wrong L1 BX ID')
		hist.Draw()
		
		#add label
		label = getLabelCmsPrivateSimulation()
		label.Draw()
		
		#Make a histogram to grey out the CSC parts
		histGrey = TH1D('greyHist','grey hist',2,3.5,5.5)
		histGrey.SetBinContent(1,1)
		histGrey.SetBinContent(2,1)
		histGrey.SetFillStyle(3004)
		histGrey.SetLineWidth(2)
		histGrey.SetLineColor(1)
		histGrey.SetFillColor(1)
		histGrey.Draw('same')
		
		pText = TPaveText(0.7,0.33,0.79,0.62,"NDC")
		tTextPointer = pText.AddText('Not in #eta range')
		tTextPointer.SetTextAngle(90)
		tTextPointer.SetTextSize(0.039)
		pText.SetBorderSize(1)
		pText.SetFillColor(0)
		pText.Draw()
		
		canvas.cd(2).SetGridx(0)
		canvas.cd(2).SetGridy(0)
		canvas.cd(2).SetLogy()
	
		#prepare second histogram
		hist2 = self.fileHandler.getHistogram("multiplicity/detectorIndexBxRight_Multiplicity")
		hist2.GetXaxis().SetRangeUser(0.5,5.5)
		hist2.SetLineColor(colorRwthDarkBlue)
		hist2.SetFillColor(colorRwthDarkBlue)
		#Prepare the bin labels
		x = ['RPC','DT','DT/RPC','CSC','CSC/RPC']
		for i in range(1,6):
			hist2.GetXaxis().SetBinLabel(i+1,x[i-1])
		hist2.GetXaxis().SetLabelFont(62)
		hist2.GetYaxis().SetLabelFont(62)
		hist2.GetYaxis().SetTitleFont(62)
		hist2.Scale(1/hist2.Integral())
		hist2.GetYaxis().SetTitle('rel. fraction')
		hist2.SetStats(0)
		hist2.SetTitle('Subdetectors in right L1 BX ID')
		hist2.Draw()
		
		#add label
		label2 = getLabelCmsPrivateSimulation()
		label2.Draw()
		
		histGrey.DrawCopy('same')
		pText2 = pText.Clone("pText2")
		pText2.Draw()
		
		canvas.Update()
		self.storeCanvas(canvas,"bxWrongDetectorContributions")
		
		
		return canvas,hist,label,histGrey,pText,pText2,label2,hist2
    UnderCount.SetStats(0)
    corrPerc = "{0:.2f}".format(round(corrc / NmbEvents * 100.,
                                      2))  #to display percentages in legend
    overPerc = "{0:.2f}".format(round(overc / NmbEvents * 100., 2))
    underPerc = "{0:.2f}".format(round(underc / NmbEvents * 100., 2))
    totLegend.AddEntry(CorrCount, "Correctly counted - " + str(corrPerc) + "%",
                       "f")
    totLegend.AddEntry(UnderCount, "Undercounted - " + str(underPerc) + "%",
                       "f")
    totLegend.AddEntry(OverCount, "Overcounted - " + str(overPerc) + "%", "f")
    totLegend.Draw()
    allCountedCanvas.SetLogy()
    CorrCount.GetYaxis().SetTitleOffset(1.3)

    eeCanvas = TCanvas('2eCanvas', 'Counting of 2-electron events', 900, 600)
    eeCanvas.Divide(2, 1)
    eeCanvas.cd(1)
    CorrCount2.Draw()
    CorrCount2.SetFillColor(ROOT.kBlue)
    CorrCount2.SetStats(0)
    OverCount2.SetFillColor(ROOT.kRed)
    UnderCount2.SetFillColor(ROOT.kGreen - 2)
    UnderCount2.Draw("same")
    UnderCount2.SetStats(0)
    OverCount2.Draw("same")
    OverCount2.SetStats(0)
    corrPerc2 = "{0:.2f}".format(round(corrc2 / multEArray[1] * 100.,
                                       2))  #to display percentages in legend
    overPerc2 = "{0:.2f}".format(round(overc2 / multEArray[1] * 100., 2))
    underPerc2 = "{0:.2f}".format(round(underc2 / multEArray[1] * 100., 2))
    twoLegend.AddEntry(CorrCount2,
示例#11
0
	def plotL1BxId(self,tight = False):

		TIGHT_TOKEN = '_tight' if tight else ''

		c2 = TCanvas("cBxId" + TIGHT_TOKEN,"BX ID" + TIGHT_TOKEN,1200,400)
		c2.Divide(3,1)

		hBxIdBest = self.fileHandler.getHistogram('timingSupport%s_MatchedDtRpcHo_BxId' % TIGHT_TOKEN)
		hBxIdDtOnly = self.fileHandler.getHistogram('timingSupport%s_UnmatchedDtHo_BxId' % TIGHT_TOKEN)
		hBxIdOther = self.fileHandler.getHistogram('timingSupport%s_OtherCodesHo_BxId' % TIGHT_TOKEN)

		if not hBxIdBest or not hBxIdDtOnly or not hBxIdOther:
			return

		dtBx0BestCentral = hBxIdBest.GetBinContent(hBxIdBest.FindBin(0))
		dtBx0BestIntegral = hBxIdBest.Integral()
		dtBx0BestOther = dtBx0BestIntegral - dtBx0BestCentral
		
		dtBx0DtOnlyCentral = hBxIdDtOnly.GetBinContent(hBxIdDtOnly.FindBin(0))
		dtBx0DtOnlyIntegral = hBxIdDtOnly.Integral()
		dtBx0DtOnlyOther = dtBx0DtOnlyIntegral - dtBx0DtOnlyCentral
		
		dtBx0OtherCentral = hBxIdOther.GetBinContent(hBxIdOther.FindBin(0))
		dtBx0OtherIntegral = hBxIdOther.Integral()
		dtBx0OtherOther = dtBx0OtherIntegral - dtBx0OtherCentral
		
		self.debug('#'*20)
		self.debug('!TIGHT!' if tight else '')
		self.debug('DT/RPC')
		self.debug('-'*10)
		self.debug('Events in BXID 0: %d\t%6.3f%% +/- %6.3f%%' % (dtBx0BestCentral,dtBx0BestCentral/float(dtBx0BestIntegral)*100,calcSigma(dtBx0BestCentral, dtBx0BestIntegral)*100))
		self.debug('Events in other BXID: %d\t%6.3f%% +/- %6.3f%%' % (dtBx0BestOther,dtBx0BestOther/float(dtBx0BestIntegral)*100,calcSigma(dtBx0BestOther, dtBx0BestIntegral)*100))
		self.debug('Consistency check (Central + Other, Integral): %d, %d' % (dtBx0BestCentral + dtBx0BestOther,dtBx0BestIntegral))
		self.debug('')
		self.debug('DT')
		self.debug('-'*10)
		self.debug('Events in BXID 0: %d\t%6.3f%% +/- %6.3f%%' % (dtBx0DtOnlyCentral,dtBx0DtOnlyCentral/float(dtBx0DtOnlyIntegral)*100,calcSigma(dtBx0DtOnlyCentral, dtBx0DtOnlyIntegral)*100))
		self.debug('Events in other BXID: %d\t%6.3f%% +/- %6.3f%%' % (dtBx0DtOnlyOther,dtBx0DtOnlyOther/float(dtBx0DtOnlyIntegral)*100,calcSigma(dtBx0DtOnlyOther, dtBx0DtOnlyIntegral)*100))
		self.debug('Consistency check (Central + Other, Integral): %d, %d' % (dtBx0DtOnlyCentral + dtBx0DtOnlyOther,dtBx0DtOnlyIntegral))
		self.debug('')
		self.debug('Other')
		self.debug('-'*10)
		self.debug('Events in BXID 0: %d\t%6.3f%% +/- %6.3f%%' % (dtBx0OtherCentral,dtBx0OtherCentral/float(dtBx0OtherIntegral)*100,calcSigma(dtBx0OtherCentral, dtBx0OtherIntegral)*100))
		self.debug('Events in other BXID: %d\t%6.3f%% +/- %6.3f%%' % (dtBx0OtherOther,dtBx0OtherOther/float(dtBx0OtherIntegral)*100,calcSigma(dtBx0OtherOther, dtBx0OtherIntegral)*100))
		self.debug('Consistency check (Central + Other, Integral): %d, %d' % (dtBx0OtherCentral + dtBx0OtherOther,dtBx0OtherIntegral))
		self.debug('')
		self.debug('#'*20)

		
		### Plot matched DT/RPC
		c2.cd(1).SetLogy()
		hBxIdBest.SetLineColor(colorRwthDarkBlue)
		hBxIdBest.SetLineWidth(3)
		hBxIdBest.SetStats(0)
		hBxIdBest.SetTitle("Matched DT/RPC + HO")
		hBxIdBest.GetXaxis().SetRangeUser(-5,5)
		hBxIdBest.GetYaxis().SetRangeUser(2e-4,1)
		hBxIdBest.Scale(1/hBxIdBest.Integral())
		hBxIdBest.GetYaxis().SetTitle("rel. fraction")
		setupAxes(hBxIdBest)
		setBigAxisTitles(hBxIdBest)
		hBxIdBest.Draw()
		label = self.drawLabel()
		
		### Plot unmatched DT
		c2.cd(2).SetLogy()
		hBxIdDtOnly.SetLineColor(colorRwthDarkBlue)
		hBxIdDtOnly.SetLineWidth(3)
		hBxIdDtOnly.SetStats(0)
		hBxIdDtOnly.SetTitle("Unmatched DT + HO")
		hBxIdDtOnly.GetXaxis().SetRangeUser(-5,5)
		hBxIdDtOnly.GetYaxis().SetRangeUser(2e-4,1)
		hBxIdDtOnly.Scale(1/hBxIdDtOnly.Integral())
		hBxIdDtOnly.GetYaxis().SetTitle("rel. fraction")
		setupAxes(hBxIdDtOnly)
		setBigAxisTitles(hBxIdDtOnly)
		hBxIdDtOnly.Draw()
		
		### Plot other codes
		c2.cd(3).SetLogy()
		hBxIdOther.SetLineColor(colorRwthDarkBlue)
		hBxIdOther.SetLineWidth(3)
		hBxIdOther.SetStats(0)
		hBxIdOther.SetTitle("Lower quality muon + HO")
		hBxIdOther.GetXaxis().SetRangeUser(-5,5)
		hBxIdOther.GetYaxis().SetRangeUser(2e-4,1)
		hBxIdOther.Scale(1/hBxIdOther.Integral())
		hBxIdOther.GetYaxis().SetTitle("rel. fraction")
		setupAxes(hBxIdOther)
		setBigAxisTitles(hBxIdOther)
		hBxIdOther.Draw()
		
		self.storeCanvas(c2,"bxId" + TIGHT_TOKEN)

		return label,c2,hBxIdBest,hBxIdDtOnly,hBxIdOther
示例#12
0
    print("\nElectron side, layer:", l)
    r = p.Fit("Ele_EofX" + str(l), "WEMRS")
    chi2dof = fEle[l].GetChisquare() / fEle[l].GetNDF()
    print("chi2/dof=", chi2dof)

    print("\nPositron side, layer:", l)
    r = p.Fit("Pos_EofX" + str(l), "WEMRS")
    chi2dof = fPos[l].GetChisquare() / fPos[l].GetNDF()
    print("chi2/dof=", chi2dof)

    l += 1

### plot the  profiles with the fits
cnv = TCanvas("cnv_xE", "", 1000, 1000)
cnv.Divide(1, 5)
p1 = cnv.cd(1)
p2 = cnv.cd(2)
p3 = cnv.cd(3)
p4 = cnv.cd(4)
p5 = cnv.cd(5)
p1.cd()
profiles[4].Draw()
fEle[4].Draw("same")
fPos[4].Draw("same")
p2.cd()
profiles[3].Draw()
fEle[3].Draw("same")
fPos[3].Draw("same")
p3.cd()
profiles[2].Draw()
示例#13
0
tree_name = "pjmca"

r2_channel = 0
background = sys.argv[2]
background_root_file = TFile(background)
background_tree = background_root_file.Get(tree_name)
background_hist = TH1D("background", "background", 2000, 0, 2000)
background_tree.Project("background", "ch{0}".format(r2_channel))

root_file_name = sys.argv[1]
root_file = TFile(root_file_name)
tree = root_file.Get(tree_name)

canvas = TCanvas(root_file_name, root_file_name)
canvas.Divide(2, 2)

intervals = [(480, 500), (600, 620), (700, 740), (840, 860), (920, 960),
             (1020, 1060), (1160, 1180)]

hists = [
    TH1D(root_file_name + str(i), root_file_name + str(i), 2000, 0, 2000)
    for i in range(4)
]

for i in range(4):
    canvas.cd(i + 1)
    tree.Project(root_file_name + str(i), "ch{0}".format(i))
    hists[i].Draw()

hists[r2_channel].Add(background_hist, -1)
示例#14
0
def plot1d(hSM, hXX, hIX, wX, fname, stanb, nameX, mX, ymin=-1, ymax=-1):
    cnv = TCanvas("cnv", "", 600, 600)
    cnv.Divide(1, 2)
    tvp_hists = cnv.cd(1)
    tvp_ratio = cnv.cd(2)
    cnv.Draw()
    tvp_hists.SetPad(0.00, 0.35, 1.00, 1.00)
    tvp_ratio.SetPad(0.00, 0.02, 1.00, 0.35)
    tvp_hists.SetBottomMargin(0.012)
    tvp_ratio.SetBottomMargin(0.20)
    tvp_ratio.SetTopMargin(0.012)
    tvp_hists.SetTicks(1, 1)
    tvp_ratio.SetTicks(1, 1)

    sXtitle = hXX.GetXaxis().GetTitle()
    cloneName_n = hXX.GetName()
    cloneName_d = hSM.GetName()
    th1n_tmp = hXX.Clone(cloneName_n + "_th1n_tmp")
    th1d_tmp = hSM.Clone(cloneName_d + "_th1d_tmp")
    th1n_tmp.SetBinErrorOption(TH1.kPoisson)
    th1d_tmp.SetBinErrorOption(TH1.kPoisson)

    hr = hIX.Clone("ratio")
    hr.Sumw2()
    hr.SetTitle(";" + sXtitle + ";|SM+#it{" + nameX + "}|^{2}/|SM|^{2}-1 [%]")
    hr.Divide(hSM)
    hr.Scale(100.)

    rmin = -11
    rmax = +11
    hr.SetMarkerStyle(20)
    hr.SetMarkerSize(0.8)
    hr.SetMarkerColor(ROOT.kBlack)
    hr.SetLineColor(ROOT.kBlack)
    hr.SetLineStyle(1)
    hr.SetLineWidth(2)
    xLabelSize = hr.GetXaxis().GetLabelSize() * 1.85
    yLabelSize = hr.GetYaxis().GetLabelSize() * 1.85
    xTitleSize = hr.GetXaxis().GetTitleSize() * 1.85
    yTitleSize = hr.GetYaxis().GetTitleSize() * 1.85
    titleSize = hr.GetTitleSize() * 1.85
    hr.GetXaxis().SetLabelSize(xLabelSize)
    hr.GetYaxis().SetLabelSize(yLabelSize)
    hr.GetXaxis().SetTitleSize(xTitleSize)
    hr.GetYaxis().SetTitleSize(yTitleSize)
    hr.SetTitleSize(titleSize)
    hr.GetYaxis().SetTitleOffset(0.55)
    hr.GetXaxis().SetTitleOffset(0.83)
    hr.SetMinimum(rmin)
    hr.SetMaximum(rmax)
    # lineR = TLine(hr.GetXaxis().GetXmin(),1.,hr.GetXaxis().GetXmax(),1.);

    tvp_hists.SetBottomMargin(0)
    tvp_ratio.SetTopMargin(0)
    tvp_ratio.SetBottomMargin(0.20)

    leg = TLegend(0.5, 0.50, 0.87, 0.9, "", "brNDC")
    leg.SetFillStyle(4000)
    # will be transparent
    leg.SetFillColor(0)
    leg.SetTextFont(42)
    leg.SetBorderSize(0)
    leg.AddEntry(0, "MadGraph+Pythia8", "")
    leg.AddEntry(0, "#it{gg}#rightarrow#it{t}#bar{#it{t}} (50k events)", "")
    leg.AddEntry(hSM, "|SM+#it{" + nameX + "}|^{2} reweighted", "ple")
    leg.AddEntry(hXX, "|SM|^{2}", "ple")
    leg.AddEntry(0, "tan#beta=" + stanb, "")
    leg.AddEntry(0, "sin(#beta-#alpha)=1", "")
    leg.AddEntry(0, "#it{m}_{#it{" + nameX + "}}=" + str(mX) + " GeV", "")
    leg.AddEntry(0, "#Gamma_{#it{" + nameX + "}}=" + '%.4f' % wX + "%", "")

    tvp_hists.cd()
    if (ymin > -1): hSM.SetMinimum(ymin)
    if (ymax > -1): hSM.SetMaximum(ymax)
    hXX.Draw()
    hSM.Draw("same")
    leg.Draw("same")
    tvp_hists.Update()
    tvp_hists.RedrawAxis()

    tvp_ratio.cd()
    tvp_ratio.SetGridy()
    hr.Draw("e1p")
    # lineR.Draw("same");
    tvp_ratio.Update()
    tvp_ratio.RedrawAxis()

    cnv.Update()
    cnv.SaveAs(fname)
from ROOT import TH1F, TCanvas, TAxis, gStyle, gPad

gStyle.SetOptFit()
#gStyle.SetOptStat(0)
numMPA = 2  # Number of installed MPAs

c1 = TCanvas("hist", "hist", 1024, 768)
c1.Divide(2)

histo = []
for iMPA in range(0, numMPA):
    c1.cd(iMPA + 1)
    memory = open('data/synchronous_data_noise_MPA' +
                  str(iMPA + 1)).read().splitlines()
    events = []
    for event in memory[:-1]:  # Get everything but the last entry
        events.append(sum([int(pix) for pix in event]))

    histData = [[0, int(memory[-1]) - len(events)]
                ]  # Last entry which contains the number of empty events
    for hits in set(events):
        histData.append([hits, events.count(hits)])
    #histData = [[hits,events.count(hits)] for hits in set(events)] # Calculate how often each number of hits occurs
    print histData

    histo.append(
        TH1F("h1", "Common noise analysis for MPA" + str(iMPA + 1), 10, 0, 10))
    #histo.append(TH1F("h1","Common noise analysis for MPA" +str(iMPA+1), max(events), 0, max(events)))
    for hits in histData:
        for i in range(0, hits[1]):
            histo[iMPA].Fill(hits[0])
示例#16
0
(options, args) = parser.parse_args()
cfgparse.read(options.config)
options.config = cfgparse  # put the parsed config file into our options

cfg = options.config

fit_sections = cfg.sections()
fit_sections.remove(
    'Global')  #don't need to iterate over the global configuration

pwd = ROOT.gDirectory.GetPath()

print 'starting ...'

canv = TCanvas("my_c", "my_c", 1600, 800)
canv.Divide(3, 3)
canv2 = TCanvas("my_c2", "my_c2", 1600, 800)
canv2.Divide(3, 3)

histos = []
histos_norm = []
funcs = []
funcs_norm = []
efficiencies = [0.38, 0.51, 0.62, 0.66, 0.66]

TH1.SetDefaultSumw2()

for section in fit_sections:
    print 'section: ', section
    sigFile = cfg.get(section, 'signal_model').split(':')[0]
    sigObj = cfg.get(section, 'signal_model').split(':')[1]
示例#17
0
  hRatioBkg.append(hBackground[iFile].Clone("hRatioBkg%d" % iFile))
  hRatioBkg[iFile].SetDirectory(0)
  hRatioBkg[iFile].Divide(hBackground[iFile],hBackground[0],1.,1.,"")
  #for iBin in range(hRatioBkg[iFile].GetNbinsX()):
  #  hRatioBkg[iFile].SetBinError(iBin+1,1.e-20)
  hRatioSignif.append(hSignif[iFile].Clone("hRatioSignif%d" % iFile))
  hRatioSignif[iFile].SetDirectory(0)
  hRatioSignif[iFile].Divide(hSignif[iFile],hSignif[0],1.,1.,"")
  #for iBin in range(hRatioSignif[iFile].GetNbinsX()):
  #  hRatioSignif[iFile].SetBinError(iBin+1,1.e-20)

PtMin = hSignal[0].GetBinLowEdge(1)
PtMax = hSignal[0].GetBinLowEdge(hSignal[0].GetNbinsX())+hSignal[0].GetBinWidth(hSignal[0].GetNbinsX())

cSignal = TCanvas('cSignal','',1000,500)
cSignal.Divide(2,1)
cSignal.cd(1).DrawFrame(PtMin,0.,PtMax,3.e-5,';#it{p}_{T} (GeV/#it{c}); raw yields / #it{N}_{events}')
for iFile in range(len(inputfilenames)):
  hSignal[iFile].Draw('same')
leg.Draw()
cSignal.cd(2).DrawFrame(PtMin,0.,PtMax,2.,';#it{p}_{T} (GeV/#it{c}); ratio of raw yields / #it{N}_{events}')
for iFile in range(len(inputfilenames)):
  if iFile==0:
    continue
  hRatioSignal[iFile].Draw('same')

cRatioSignal = TCanvas('cRatioSignal','',800,800)
cRatioSignal.DrawFrame(PtMin,0.5,PtMax,2.,';#it{p}_{T} (GeV/#it{c}); ratio of raw yields / #it{N}_{events}')
for iFile in range(len(inputfilenames)):
  hRatioSignal[iFile].Draw('same')
leg.Draw()
示例#18
0
idx_3 = 28

leg = TLegend(.63, .62, .97, .93)
leg.SetBorderSize(0)
leg.SetFillColor(0)
leg.SetFillStyle(0)
leg.SetTextFont(42)
leg.SetTextSize(0.035)
leg.SetHeader("prim. photon energy", "C")
leg.AddEntry(hLStep[idx_1], "40 keV")
leg.AddEntry(hLStep[idx_2], "110 keV")
leg.AddEntry(hLStep[idx_3], "290 keV")

#step length histo
c1 = TCanvas("c1", "c1", 200, 10, 1200, 500)
c1.Divide(2)
c1.cd(1)
c1.cd(1).SetLogy()
hLStep[idx_1].Draw("hist")
hLStep[idx_2].Draw("hist,same")
hLStep[idx_2].SetLineColor(kBlue)
hLStep[idx_3].Draw("hist,same")
hLStep[idx_3].SetLineColor(kRed)
leg.Draw("same")

c1.cd(2)
c1.cd(2).SetLogy()
hLStep_compt_phot[idx_1].Draw("hist")
hLStep_compt_phot[idx_2].Draw("hist,same")
hLStep_compt_phot[idx_2].SetLineColor(kBlue)
hLStep_compt_phot[idx_3].Draw("hist,same")
示例#19
0
def TrackToFile_ROOT_2D_3D(data,
                           save_path,
                           log_z=False,
                           plot_opt='',
                           force_aspect=True,
                           legend_text='',
                           fitline=None,
                           zmax=None,
                           zmax_supress_ratio=1.0):
    from ROOT import TH2F, TCanvas
    if plot_opt == '': plot_opt = 'colz0'
    if plot_opt != 'box' and plot_opt != 'colz': plot_opt = 'colz0'

    if force_aspect:
        nbinsx = xmax = max(data.shape[0], data.shape[1])
        nbinsy = ymax = max(data.shape[0], data.shape[1])
    else:
        nbinsx = xmax = data.shape[0]
        nbinsy = ymax = data.shape[1]

    if zmax != None and zmax_supress_ratio != 1.0:
        print "Warning - using both zmax absolute and zmax_supress"
        print "zmax will be set at zmax * zmax_supress - is this what you meant to do?"

    xlow = 0
    ylow = 0

    c4 = TCanvas('canvas', 'canvas', 1600, 800)  #create canvas
    c4.Divide(2, 1, 0.002, 0.00001)
    c4.cd(2)

    image_hist = TH2F('', '', nbinsx, xlow, xmax, nbinsy, ylow, ymax)
    for x in range(data.shape[0]):
        for y in range(data.shape[1]):
            value = data[x, y]
            if value != 0:
                image_hist.Fill(float(x), float(y), float(value))

    if zmax_supress_ratio != 1.0 or zmax != None:
        binnum = image_hist.GetMaximumBin()
        true_zmax = image_hist.GetBinContent(binnum)

        if zmax != None:
            new_zmax = zmax * zmax_supress_ratio
        else:
            new_zmax = true_zmax * zmax_supress_ratio

        image_hist.GetZaxis().SetRangeUser(0, new_zmax)

    image_hist.Draw(plot_opt)
    if fitline != None:
        from ROOT import TF1
        a = fitline.a
        b = fitline.b
        formula = str(a) + '*x + ' + str(b)
        plane = TF1("f2", formula, 0, xmax)
        plane.SetNpx(100)
        plane.Draw("same")

    c4.cd(1)
    image_hist.Draw("lego20")  # good for CR Tracks
    #     image_hist.Draw("surf2") # better for Timepix/medipix composites / heatmaps

    if legend_text != '':
        from ROOT import TPaveText
        textbox = TPaveText(0.0, 1, 0.2, 0.9, "NDC")
        for line in legend_text:
            textbox.AddText(line)
        textbox.SetFillColor(0)
        textbox.Draw("same")

    if log_z: c4.SetLogz()
    image_hist.SetStats(False)
    c4.SaveAs(save_path)
示例#20
0
def plotPulls(optunf="Bayes",
              ntest=10,
              leff=True,
              loufl=False,
              optfun="exp",
              opttfun="",
              gmean=-1.0,
              nrebin=4):

    if opttfun == "":
        opttfun = optfun

    if optfun == "blobel":
        gmean = 0.0

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

    global histos, canv, canv2
    histos = []

    canv = TCanvas("canv", "thruth vs reco pulls", 600, 800)
    canv.Divide(1, 3)
    canv2 = TCanvas("canv2", "P(chi^2)", 600, 800)
    canv2.Divide(2, 3)

    if optunf == "BasisSplines":
        bininfo = BinInfo(nrebin)
        unfoldtester = UnfoldTester(optunf, nrebin)
    else:
        bininfo = BinInfo()
        unfoldtester = UnfoldTester(optunf)
    trainer = Trainer(bininfo, opttfun, optfun)
    tester = Tester(bininfo, optfun)
    hbininfo = bininfo.create(optfun)
    dx = hbininfo["mhi"]
    for sigma, ipad in [[0.01 * dx, 1], [0.03 * dx, 2], [0.1 * dx, 3]]:
        txt = optunf + ", smear mu, s.d.= " + str(gmean) + ", " + str(
            sigma) + ", train: " + funttxt + ", test: " + funtxt + ", " + str(
                ntest) + " tests"
        hPulls = TProfile("pulls", txt, hbininfo["tbins"], hbininfo["tlo"],
                          hbininfo["thi"])
        hPulls.SetErrorOption("s")
        hPulls.SetYTitle("Thruth reco pull")
        histos.append(hPulls)
        hChisq = TH1D("chisq", "P(chi^2) rec " + txt, 10, 0.0, 1.0)
        hChisqm = TH1D("chisqm", "P(chi^2) mea " + txt, 10, 0.0, 1.0)
        histos.append(hChisq)
        histos.append(hChisqm)
        measurement = createMeasurement(gmean, sigma, leff, optfun)
        response = trainer.train(measurement, loufl=loufl)
        for itest in range(ntest):
            print "Test", itest
            unfold, hTrue, hMeas = unfoldtester.rununfoldtest(
                tester, measurement, response)
            unfold.PrintTable(cout, hTrue, 2)
            hReco = unfold.Hreco(2)
            nbin = hReco.GetNbinsX()
            if hbininfo["nrebin"] > 1:
                hTrue = hTrue.Rebin(nrebin)
            for ibin in range(nbin + 1):
                truevalue = hTrue.GetBinContent(ibin)
                recvalue = hReco.GetBinContent(ibin)
                error = hReco.GetBinError(ibin)
                if error > 0.0:
                    pull = (recvalue - truevalue) / error
                    hPulls.Fill(hReco.GetBinCenter(ibin), pull)
            chisq = unfold.Chi2(hTrue, 2)
            hChisq.Fill(TMath.Prob(chisq, hTrue.GetNbinsX()))
            chisqm = unfold.Chi2measured()
            pchisqm = TMath.Prob(chisqm, hMeas.GetNbinsX() - hReco.GetNbinsX())
            print "Chisq measured=", chisqm, "P(chi^2)=", pchisqm
            hChisqm.Fill(pchisqm)

        canv.cd(ipad)
        gStyle.SetErrorX(0)
        hPulls.SetMinimum(-3.0)
        hPulls.SetMaximum(3.0)
        hPulls.SetMarkerSize(1.0)
        hPulls.SetMarkerStyle(20)
        hPulls.SetStats(False)
        hPulls.Draw()
        canv2.cd(ipad * 2 - 1)
        hChisq.Draw()
        canv2.cd(ipad * 2)
        hChisqm.Draw()

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

    return
示例#21
0
    print_usage()
    sys.exit(0)

gROOT.SetBatch(True)
gStyle.SetOptFit(1)
inFile = TFile(remainder[1])
events = inFile.Get("cut")

c = TCanvas("c", "c", 1200, 900)
c.Print(remainder[0] + ".pdf[")
outfile = TFile(remainder[0] + ".root", "RECREATE")

#exppol4=TF1("exppol4","min(exp(pol3(0)),2)",-5,100)

c.Clear()
c.Divide(1, 2)
c.cd(1)
gPad.SetLogz(1)
events.Draw("uncVZ-triEndZ:triEndZ>>hnew(50,-5,100,50,-20,20)", "", "colz")
hnew = gDirectory.Get("hnew")
hnew.GetXaxis().SetTitle("vertex Z [mm]")
hnew.GetYaxis().SetTitle("vertex Z residual [mm]")
hnew.FitSlicesY()
hnew_1 = gDirectory.Get("hnew_2")
c.cd(2)
hnew_1.GetXaxis().SetTitle("vertex Z [mm]")
hnew_1.GetYaxis().SetTitle("vertex Z resolution [mm]")
hnew_1.Draw()
hnew_1.Fit("pol1", "", "", -5, 100)
hnew_1.GetYaxis().SetRangeUser(0, 20)
hnew_1.Write("zres_all")
示例#22
0
def featureSizePlots(optunf="Bayes",
                     leff=True,
                     optfun="exp",
                     opttfun="",
                     loufl=False,
                     gmean=-1.0,
                     nrebin=4):

    if opttfun == "":
        opttfun = optfun

    if optfun == "blobel":
        gmean = 0.0

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

    global hReco, hMeas, hTrue, hPulls, canv, histos
    histos = []
    canv = TCanvas("canv", "feature size plots", 600, 800)
    canv.Divide(1, 3)

    if optunf == "BasisSplines":
        bininfo = BinInfo(nrebin)
        unfoldtester = UnfoldTester(optunf, nrebin)
    else:
        bininfo = BinInfo()
        unfoldtester = UnfoldTester(optunf)
    trainer = Trainer(bininfo, opttfun, optfun)
    tester = Tester(bininfo, optfun)
    hbininfo = bininfo.create(optfun)
    dx = hbininfo["mhi"]
    for sigma, ipad in [[0.01 * dx, 1], [0.03 * dx, 2], [0.1 * dx, 3]]:
        measurement = createMeasurement(gmean, sigma, leff, optfun)
        response = trainer.train(measurement, loufl=loufl)
        unfold, hTrue, hMeas = unfoldtester.rununfoldtest(
            tester, measurement, response)
        hReco = unfold.Hreco(2)

        hRecoMeasured = unfold.HrecoMeasured()

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

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

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

    return
示例#23
0
文件: etaDistro.py 项目: adeyta/RPC
def eta_plot(X0W,Y0W,X1W,Y1W,X2W,Y2W,X3W, Y3W, X4W, Y4W, X5W, Y5W, X6W, Y6W,
             X7W,Y7W,X8W,Y8W,X9W,Y9W,X10W,Y10W,X11W,Y11W,X12W,Y12W,X13W,Y13W,
             X0E,Y0E,X1E,Y1E,X2E,Y2E,X3E, Y3E, X4E, Y4E, X5E, Y5E, X6E, Y6E,
             X7E,Y7E,X8E,Y8E,X9E,Y9E,X10E,Y10E,X11E,Y11E,X12E,Y12E,X13E,Y13E):
  print "------ Setting Up Format ----------"
  tdrstyle.setTDRStyle()
  #change the CMS_lumi variables (see CMS_lumi.py)
  CMS_lumi.writeExtraText = 1
  CMS_lumi.extraText  = "Preliminary"
  CMS_lumi.extraText2 = "2018 pp data"
  CMS_lumi.lumi_sqrtS = "13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)
  CMS_lumi.writeTitle = 1
  CMS_lumi.textTitle = 'title'

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

  H_ref = 600;
  W_ref = 800;
  W = W_ref  
  H = H_ref
  iPeriod = 0
  # references for T, B, L, R  
  T = 0.08*H_ref
  B = 0.12*H_ref
  L = 0.12*W_ref
  R = 0.04*W_ref

  
  print "------ Creating Wheel TGraph ----------"
  n0W = len(X0W)
  gr0W = TGraph(n0W,X0W,Y0W)
  gr0W.SetMarkerColor( kRed )
  gr0W.SetMarkerStyle( 20 )
  gr0W.SetMarkerSize( 1.5 )
  gr0W.SetTitle( 'RB1 in' )
  gr0W.GetXaxis().SetTitle( '#eta' )
  gr0W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n1W = len(X1W)
  gr1W = TGraph(n1W,X1W,Y1W)
  gr1W.SetLineColor( 2 )
  gr1W.SetLineWidth( 4 )
  gr1W.SetMarkerColor( kBlue )
  gr1W.SetMarkerStyle( 29 )
  gr1W.SetMarkerSize( 1.7 )
  gr1W.SetTitle( 'Layer 1 Wheel' )
  gr1W.GetXaxis().SetTitle( '#eta' )
  gr1W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n2W = len(X2W)
  gr2W = TGraph(n2W,X2W,Y2W)
  gr2W.SetLineColor( 3 )
  gr2W.SetLineWidth( 5 )
  gr2W.SetMarkerColor( kRed+2 )
  gr2W.SetMarkerStyle( 21 )
  gr2W.SetMarkerSize( 1.5 )
  gr2W.SetTitle( 'Layer 2 Wheel') 
  gr2W.GetXaxis().SetTitle( '#eta' )
  gr2W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n3W = len(X3W)
  gr3W = TGraph(n3W,X3W,Y3W)
  gr3W.SetLineColor( 4 )
  gr3W.SetLineWidth( 6 )
  gr3W.SetMarkerColor( kRed )
  gr3W.SetMarkerStyle( 21 )
  gr3W.SetMarkerSize( 1.5 )
  gr3W.SetTitle( 'Layer 3 Wheel' )
  gr3W.GetXaxis().SetTitle( '#eta' )
  gr3W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n4W = len(X4W)
  gr4W = TGraph(n4W,X4W,Y4W)
  gr4W.SetLineColor( 5 )
  gr4W.SetLineWidth( 7 )
  gr4W.SetMarkerColor( kBlue )
  gr4W.SetMarkerStyle( 23 )
  gr4W.SetMarkerSize( 1.5 )
  gr4W.SetTitle( 'Layer 4 Wheel' )
  gr4W.GetXaxis().SetTitle( '#eta' )
  gr4W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  print "------ Creating Endcap TGraph ----------"
  n0E = len(X0E)
  gr0E = TGraph(n0E,X0E,Y0E)
  gr0E.SetLineColor( 2 )
  gr0E.SetLineWidth( 4 )
  gr0E.SetMarkerColor( kRed )
  gr0E.SetMarkerStyle( 24 )
  gr0E.SetMarkerSize( 1.5 )
  gr0E.SetTitle( 'Layer 1 Endcap' )
  gr0E.GetXaxis().SetTitle( '#eta' )
  gr0E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n1E = len(X1E)
  gr1E = TGraph(n1E,X1E,Y1E)
  gr1E.SetLineColor( 2 )
  gr1E.SetLineWidth( 4 )
  gr1E.SetMarkerColor( kBlue )
  gr1E.SetMarkerStyle( 30 )
  gr1E.SetMarkerSize( 1.5 )
  gr1E.SetTitle( 'Layer 1 Endcap' )
  gr1E.GetXaxis().SetTitle( '#eta' )
  gr1E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n2E = len(X2E)
  gr2E = TGraph(n2E,X2E,Y2E)
  gr2E.SetLineColor( 3 )
  gr2E.SetLineWidth( 5 )
  gr2E.SetMarkerColor( kRed+2 )
  gr2E.SetMarkerStyle( 25 )
  gr2E.SetMarkerSize( 1.5 )
  gr2E.SetTitle( 'Layer 2 Endcap')
  gr2E.GetXaxis().SetTitle( '#eta' )
  gr2E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n3E = len(X3E)
  gr3E = TGraph(n3E,X3E,Y3E)
  gr3E.SetLineColor( 4 )
  gr3E.SetLineWidth( 6 )
  gr3E.SetMarkerColor( kRed )
  gr3E.SetMarkerStyle( 25 )
  gr3E.SetMarkerSize( 1.5 )
  gr3E.SetTitle( 'Layer 3 Endcap' )
  gr3E.GetXaxis().SetTitle( '#eta' )
  gr3E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n4E = len(X4E)
  gr4E = TGraph(n4E,X4E,Y4E)
  gr4E.SetLineColor( 5 )
  gr4E.SetLineWidth( 7 )
  gr4E.SetMarkerColor( kBlue )
  gr4E.SetMarkerStyle( 32 )
  gr4E.SetMarkerSize( 1.5 )
  gr4E.SetTitle( 'Layer 4 Endcap' )
  gr4E.GetXaxis().SetTitle( '#eta' )
  gr4E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  print "------ Creating Wheel TGraph ----------"
  n5W = len(X5W)
  gr5W = TGraph(n5W,X5W,Y5W)
  gr5W.SetLineColor( 2 )
  gr5W.SetLineWidth( 4 )
  gr5W.SetMarkerColor( 6 )
  gr5W.SetMarkerStyle( 22 )
  gr5W.SetMarkerSize( 1.5 )
  gr5W.SetTitle( 'Layer 1 Wheel' )
  gr5W.GetXaxis().SetTitle( '#eta' )
  gr5W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n6W = len(X6W)
  gr6W = TGraph(n6W,X6W,Y6W)
  gr6W.SetLineColor( 3 )
  gr6W.SetLineWidth( 5 )
  gr6W.SetMarkerColor( 28 )
  gr6W.SetMarkerStyle( 23 )
  gr6W.SetMarkerSize( 1.7 )
  gr6W.SetTitle( 'Layer 2 Wheel')
  gr6W.GetXaxis().SetTitle( '#eta' )
  gr6W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n7W = len(X7W)
  gr7W = TGraph(n7W,X7W,Y7W)
  gr7W.SetLineColor( 4 )
  gr7W.SetLineWidth( 6 )
  gr7W.SetMarkerColor( kRed )
  gr7W.SetMarkerStyle( 20 )
  gr7W.SetMarkerSize( 1.5 )
  gr7W.SetTitle( 'Layer 3 Wheel' )
  gr7W.GetXaxis().SetTitle( '#eta' )
  gr7W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n8W = len(X8W)
  gr8W = TGraph(n8W,X8W,Y8W)
  gr8W.SetLineColor( 5 )
  gr8W.SetLineWidth( 7 )
  gr8W.SetMarkerColor( kBlue )
  gr8W.SetMarkerStyle( 29 )
  gr8W.SetMarkerSize( 1.5 )
  gr8W.SetTitle( 'Layer 4 Wheel' )
  gr8W.GetXaxis().SetTitle( '#eta' )
  gr8W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n9W = len(X9W)
  gr9W = TGraph(n9W,X9W,Y9W)
  gr9W.SetLineColor( 5 )
  gr9W.SetLineWidth( 7 )
  gr9W.SetMarkerColor( kRed+2 )
  gr9W.SetMarkerStyle( 21 )
  gr9W.SetMarkerSize( 1.5 )
  gr9W.SetTitle( 'Layer 4 Wheel' )
  gr9W.GetXaxis().SetTitle( '#eta' )
  gr9W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n10W = len(X10W)
  gr10W = TGraph(n10W,X10W,Y10W)
  gr10W.SetLineColor( 5 )
  gr10W.SetLineWidth( 7 )
  gr10W.SetMarkerColor( kRed )
  gr10W.SetMarkerStyle( 21 )
  gr10W.SetMarkerSize( 1.5 )
  gr10W.SetTitle( 'Layer 4 Wheel' )
  gr10W.GetXaxis().SetTitle( '#eta' )
  gr10W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n11W = len(X11W)
  gr11W = TGraph(n11W,X11W,Y11W)
  gr11W.SetLineColor( 5 )
  gr11W.SetLineWidth( 7 )
  gr11W.SetMarkerColor( kBlue )
  gr11W.SetMarkerStyle( 23 )
  gr11W.SetMarkerSize( 1.5 )
  gr11W.SetTitle( 'Layer 4 Wheel' )
  gr11W.GetXaxis().SetTitle( '#eta' )
  gr11W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n12W = len(X12W)
  gr12W = TGraph(n12W,X12W,Y12W)
  gr12W.SetLineColor( 5 )
  gr12W.SetLineWidth( 7 )
  gr12W.SetMarkerColor( 6 )
  gr12W.SetMarkerStyle( 22 )
  gr12W.SetMarkerSize( 1.5 )
  gr12W.SetTitle( 'Layer 4 Wheel' )
  gr12W.GetXaxis().SetTitle( '#eta' )
  gr12W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n13W = len(X13W)
  gr13W = TGraph(n13W,X13W,Y13W)
  gr13W.SetLineColor( 5 )
  gr13W.SetLineWidth( 7 )
  gr13W.SetMarkerColor( 28 )
  gr13W.SetMarkerStyle( 23 )
  gr13W.SetMarkerSize( 1.5 )
  gr13W.SetTitle( 'Layer 4 Wheel' )
  gr13W.GetXaxis().SetTitle( '#eta' )
  gr13W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )


  print "------ Creating Endcap TGraph ----------"
  n5E = len(X5E)
  gr5E = TGraph(n5E,X5E,Y5E)
  gr5E.SetLineColor( 2 )
  gr5E.SetLineWidth( 4 )
  gr5E.SetMarkerColor( 6 )
  gr5E.SetMarkerStyle( 26 )
  gr5E.SetMarkerSize( 1.5 )
  gr5E.SetTitle( 'Layer 1 Endcap' )
  gr5E.GetXaxis().SetTitle( '#eta' )
  gr5E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n6E = len(X6E)
  gr6E = TGraph(n6E,X6E,Y6E)
  gr6E.SetLineColor( 3 )
  gr6E.SetLineWidth( 5 )
  gr6E.SetMarkerColor( 28 )
  gr6E.SetMarkerStyle( 32 )
  gr6E.SetMarkerSize( 1.5 )
  gr6E.SetTitle( 'Layer 2 Endcap')
  gr6E.GetXaxis().SetTitle( '#eta' )
  gr6E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n7E = len(X7E)
  gr7E = TGraph(n7E,X7E,Y7E)
  gr7E.SetLineColor( 4 )
  gr7E.SetLineWidth( 6 )
  gr7E.SetMarkerColor( kRed )
  gr7E.SetMarkerStyle( 24 )
  gr7E.SetMarkerSize( 1.5 )
  gr7E.SetTitle( 'Layer 3 Endcap' )
  gr7E.GetXaxis().SetTitle( '#eta' )
  gr7E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n8E = len(X8E)
  gr8E = TGraph(n8E,X8E,Y8E)
  gr8E.SetLineColor( 5 )
  gr8E.SetLineWidth( 7 )
  gr8E.SetMarkerColor( kBlue )
  gr8E.SetMarkerStyle( 30 )
  gr8E.SetMarkerSize( 1.5 )
  gr8E.SetTitle( 'Layer 4 Endcap' )
  gr8E.GetXaxis().SetTitle( '#eta' )
  gr8E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n9E = len(X9E)
  gr9E = TGraph(n9E,X9E,Y9E)
  gr9E.SetLineColor( 5 )
  gr9E.SetLineWidth( 7 )
  gr9E.SetMarkerColor( kRed+2 )
  gr9E.SetMarkerStyle( 25 )
  gr9E.SetMarkerSize( 1.5 )
  gr9E.SetTitle( 'Layer 4 Endcap' )
  gr9E.GetXaxis().SetTitle( '#eta' )
  gr9E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n10E = len(X10E)
  gr10E = TGraph(n10E,X10E,Y10E)
  gr10E.SetLineColor( 5 )
  gr10E.SetLineWidth( 7 )
  gr10E.SetMarkerColor( kRed )
  gr10E.SetMarkerStyle( 25 )
  gr10E.SetMarkerSize( 1.5 )
  gr10E.SetTitle( 'Layer 4 Endcap' )
  gr10E.GetXaxis().SetTitle( '#eta' )
  gr10E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n11E = len(X11E)
  gr11E = TGraph(n11E,X11E,Y11E)
  gr11E.SetLineColor( 5 )
  gr11E.SetLineWidth( 7 )
  gr11E.SetMarkerColor( kBlue )
  gr11E.SetMarkerStyle( 32 )
  gr11E.SetMarkerSize( 1.5 )
  gr11E.SetTitle( 'Layer 4 Endcap' )
  gr11E.GetXaxis().SetTitle( '#eta' )
  gr11E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n12E = len(X12E)
  gr12E = TGraph(n12E,X12E,Y12E)
  gr12E.SetLineColor( 5 )
  gr12E.SetLineWidth( 7 )
  gr12E.SetMarkerColor( 6 )
  gr12E.SetMarkerStyle( 26 )
  gr12E.SetMarkerSize( 1.5 )
  gr12E.SetTitle( 'Layer 4 Endcap' )
  gr12E.GetXaxis().SetTitle( '#eta' )
  gr12E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  n13E = len(X13E)
  gr13E = TGraph(n13E,X13E,Y13E)
  gr13E.SetLineColor( 5 )
  gr13E.SetLineWidth( 7 )
  gr13E.SetMarkerColor( 28 )
  gr13E.SetMarkerStyle( 32 )
  gr13E.SetMarkerSize( 1.5 )
  gr13E.SetTitle( 'Layer 4 Endcap' )
  gr13E.GetXaxis().SetTitle( '#eta' )
  gr13E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )

  print "----- Creating TCanvas -----"
  H = 800
  W = 1600
  canv = TCanvas("c1", "Canvas",50,50,W,H)
  canv.SetFillColor(0)
  canv.SetBorderMode(0)
  canv.SetFrameFillStyle(0)
  canv.SetFrameBorderMode(0)
  canv.SetLeftMargin( L/W )
  canv.SetRightMargin( R/W )
  canv.SetTopMargin( T/H )
  canv.SetBottomMargin( B/H )
  canv.SetTickx(0)
  canv.SetTicky(0)
  canv.Divide(3,2,0.001,0.001)
  CMS_lumi.CMS_lumi(canv, iPeriod, iPos)
  canv.cd()
  canv.Update()
  maxY = 1000

  canv.cd(1)
  gPad.SetLogy()
  print " ------------ Creating TMultiGraph -----------"
  mg1 = TMultiGraph()
  #graphAxis(mg1)
  mg1.Add(gr0E,"AP")
  mg1.Add(gr0W,"AP")
  mg1.Add(gr7E,"AP")
  mg1.Add(gr7W,"AP")
  mg1.Draw("a")
  mg1.SetTitle( 'RB1in')
  mg1.GetXaxis().SetTitle( '#eta' )
  mg1.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )
  mg1.SetMaximum(maxY)
  mg1.GetXaxis().SetLabelFont(42)
  mg1.GetXaxis().SetLabelOffset(0.007)
  mg1.GetXaxis().SetLabelSize(0.043)
  mg1.GetXaxis().SetTitleSize(0.05)
  mg1.GetXaxis().SetTitleOffset(1.06)
  mg1.GetXaxis().SetTitleFont(42)
  mg1.GetYaxis().SetLabelFont(42)
  mg1.GetYaxis().SetLabelOffset(0.008)
  mg1.GetYaxis().SetLabelSize(0.05)
  mg1.GetYaxis().SetTitleSize(0.06)
  mg1.GetYaxis().SetTitleOffset(0.87)
  mg1.GetYaxis().SetTitleFont(42)

  pvtxt = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73)
  pvtxt.AddText('CMS Preliminary')
  pvtxt.SetFillStyle(0)
  pvtxt.SetBorderSize(0)
  pvtxt.SetTextSize(0.03)
  pvtxt.Draw()
  pvtxt100 = TPaveText(.7,0.97,.9,0.97,"NDC")
  pvtxt100.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
  pvtxt100.SetFillStyle(0)
  pvtxt100.SetBorderSize(0)
  pvtxt100.SetTextSize(0.03)
  pvtxt100.Draw()

  canv.cd(2)
  gPad.SetLogy()
  gr00 = TGraph()
  gr00.SetMarkerColor( kBlack )
  gr00.SetMarkerStyle( 20 )
  gr00.SetMarkerSize( 1.5 )
  gr01 = TGraph()
  gr01.SetMarkerColor( kBlack )
  gr01.SetMarkerStyle( 24 )
  gr01.SetMarkerSize( 1.5 )

  legend0 = TLegend(0.2, 0.7, .8, .9)
  legend0.SetNColumns(1)
  legend0.AddEntry(gr00, "Barrel", "p")
  legend0.AddEntry(gr01, "Endcaps", "p")
  legend0.Draw("a same")

  legendi = TLegend(0.2, 0.2, .8, .6)
  legendi.SetNColumns(1)
  legendi.AddEntry(gr7W,  "RB1in  + RE1" , "p")
  legendi.AddEntry(gr8W,  "RB1out + RE1" , "p")
  legendi.AddEntry(gr9W,  "RB2 + RE2"    , "p")
#  legendi.AddEntry(gr10W, "RB2in  + RE2" , "p")
#  legendi.AddEntry(gr11W, "RB2out + RE2" , "p")
  legendi.AddEntry(gr12W, "RB3 + RE3"    , "p")
  legendi.AddEntry(gr13W, "RB4 + RE4"    , "p")
  legendi.SetTextSize(0.05)
  legendi.Draw("a");

  canv.cd(3)
  gPad.SetLogy()
  mg2 = TMultiGraph()
  mg2.Add(gr1E,"AP")
  mg2.Add(gr1W,"AP")
  mg2.Add(gr8E,"AP")
  mg2.Add(gr8W,"AP")
  mg2.Draw("a")
  mg2.SetTitle( 'RB1out')
  mg2.GetXaxis().SetTitle( '#eta' )
  mg2.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )
  mg2.SetMaximum(maxY)
  mg2.GetXaxis().SetLabelFont(42)
  mg2.GetXaxis().SetLabelOffset(0.007)
  mg2.GetXaxis().SetLabelSize(0.043)
  mg2.GetXaxis().SetTitleSize(0.05)
  mg2.GetXaxis().SetTitleOffset(1.06)
  mg2.GetXaxis().SetTitleFont(42)
  mg2.GetYaxis().SetLabelFont(42)
  mg2.GetYaxis().SetLabelOffset(0.008)
  mg2.GetYaxis().SetLabelSize(0.05)
  mg2.GetYaxis().SetTitleSize(0.06)
  mg2.GetYaxis().SetTitleOffset(0.87)
  mg2.GetYaxis().SetTitleFont(42)

  pvtxt3 = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73)
  pvtxt3.AddText('CMS Preliminary')
  pvtxt3.SetFillStyle(0)
  pvtxt3.SetBorderSize(0)
  pvtxt3.SetTextSize(0.03)
  pvtxt3.Draw()
  pvtxt4 = TPaveText(.7,0.97,.9,0.97,"NDC")
  pvtxt4.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
  pvtxt4.SetFillStyle(0)
  pvtxt4.SetBorderSize(0)
  pvtxt4.SetTextSize(0.03)
  pvtxt4.Draw()

  canv.cd(4)
  gPad.SetLogy()
  mg3 = TMultiGraph()
  #graphAxis(mg3)
  mg3.Add(gr2E,"AP")
  mg3.Add(gr2W,"AP")
  mg3.Add(gr9E,"AP")
  mg3.Add(gr9W,"AP")
  mg3.Draw("a")
  mg3.SetTitle( 'RB2')
  mg3.GetXaxis().SetTitle( '#eta' )
  mg3.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )
  mg3.SetMaximum(maxY)
  mg3.GetXaxis().SetLabelFont(42)
  mg3.GetXaxis().SetLabelOffset(0.007)
  mg3.GetXaxis().SetLabelSize(0.043)
  mg3.GetXaxis().SetTitleSize(0.05)
  mg3.GetXaxis().SetTitleOffset(1.06)
  mg3.GetXaxis().SetTitleFont(42)
  mg3.GetYaxis().SetLabelFont(42)
  mg3.GetYaxis().SetLabelOffset(0.008)
  mg3.GetYaxis().SetLabelSize(0.05)
  mg3.GetYaxis().SetTitleSize(0.06)
  mg3.GetYaxis().SetTitleOffset(0.87)
  mg3.GetYaxis().SetTitleFont(42)

  pvtxt5 = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73)
  pvtxt5.AddText('CMS Preliminary')
  pvtxt5.SetFillStyle(0)
  pvtxt5.SetBorderSize(0)
  pvtxt5.SetTextSize(0.03)
  pvtxt5.Draw()
  pvtxt6 = TPaveText(.7,0.97,.9,0.97,"NDC")
  pvtxt6.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
  pvtxt6.SetFillStyle(0)
  pvtxt6.SetBorderSize(0)
  pvtxt6.SetTextSize(0.03)
  pvtxt6.Draw()

  canv.cd(5)
  gPad.SetLogy()
  mg4 = TMultiGraph()
  #graphAxis(mg4)
  mg4.Add(gr5E,"AP")
  mg4.Add(gr5W,"AP")
  mg4.Add(gr12E,"AP")
  mg4.Add(gr12W,"AP")
  mg4.Draw("a")
  mg4.SetTitle( 'RB3')
  mg4.GetXaxis().SetTitle( '#eta' )
  mg4.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )
  mg4.SetMaximum(maxY)
  mg4.GetXaxis().SetLabelFont(42)
  mg4.GetXaxis().SetLabelOffset(0.007)
  mg4.GetXaxis().SetLabelSize(0.043)
  mg4.GetXaxis().SetTitleSize(0.05)
  mg4.GetXaxis().SetTitleOffset(1.06)
  mg4.GetXaxis().SetTitleFont(42)
  mg4.GetYaxis().SetLabelFont(42)
  mg4.GetYaxis().SetLabelOffset(0.008)
  mg4.GetYaxis().SetLabelSize(0.05)
  mg4.GetYaxis().SetTitleSize(0.06)
  mg4.GetYaxis().SetTitleOffset(0.87)
  mg4.GetYaxis().SetTitleFont(42)

  pvtxt7 = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73)
  pvtxt7.AddText('CMS Preliminary')
  pvtxt7.SetFillStyle(0)
  pvtxt7.SetBorderSize(0)
  pvtxt7.SetTextSize(0.03)
  pvtxt7.Draw()
  pvtxt8 = TPaveText(.7,0.97,.9,0.97,"NDC")
  pvtxt8.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
  pvtxt8.SetFillStyle(0)
  pvtxt8.SetBorderSize(0)
  pvtxt8.SetTextSize(0.03)
  pvtxt8.Draw()

  canv.cd(6)
  gPad.SetLogy()
  mg5 = TMultiGraph()
  #graphAxis(mg5)
  mg5.Add(gr6E,"AP")
  mg5.Add(gr6W,"AP")
  mg5.Add(gr13E,"AP")
  mg5.Add(gr13W,"AP")
  mg5.Draw("a")
  mg5.SetTitle( 'RB4')
  mg5.GetXaxis().SetTitle( '#eta' )
  mg5.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )
  mg5.SetMaximum(maxY)
  mg5.GetXaxis().SetLabelFont(42)
  mg5.GetXaxis().SetLabelOffset(0.007)
  mg5.GetXaxis().SetLabelSize(0.043)
  mg5.GetXaxis().SetTitleSize(0.05)
  mg5.GetXaxis().SetTitleOffset(1.06)
  mg5.GetXaxis().SetTitleFont(42)
  mg5.GetYaxis().SetLabelFont(42)
  mg5.GetYaxis().SetLabelOffset(0.008)
  mg5.GetYaxis().SetLabelSize(0.05)
  mg5.GetYaxis().SetTitleSize(0.06)
  mg5.GetYaxis().SetTitleOffset(0.87)
  mg5.GetYaxis().SetTitleFont(42)

  pvtxt10 = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73)
  pvtxt10.AddText('CMS Preliminary')
  pvtxt10.SetFillStyle(0)
  pvtxt10.SetBorderSize(0)
  pvtxt10.SetTextSize(0.03)
  pvtxt10.Draw()
  pvtxt9 = TPaveText(.7,0.97,.9,0.97,"NDC")
  pvtxt9.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
  pvtxt9.SetFillStyle(0)
  pvtxt9.SetBorderSize(0)
  pvtxt9.SetTextSize(0.03)
  pvtxt9.Draw()

  canv.SaveAs("etaDistro.gif")
  canv.Close()

  print "----- Creating Second TCanvas -----"
  H = 800
  W = 800
  c = TCanvas("c1", "Canvas",50,50,W,H)
  c.SetFillColor(0)
  c.SetBorderMode(0)
  c.SetFrameFillStyle(0)
  c.SetFrameBorderMode(0)
  c.SetLeftMargin( L/W )
  c.SetRightMargin( R/W )
  c.SetTopMargin( T/H )
  c.SetBottomMargin( B/H )
  c.SetTickx(0)
  c.SetTicky(0) 
  gPad.SetLogy()

  print " ------------ Creating TMultiGraph -----------"
  mg = TMultiGraph()
  mg.Add(gr0E,"AP")
  mg.Add(gr0W,"AP")
  mg.Add(gr7E,"AP")
  mg.Add(gr7W,"AP")
  mg.Add(gr1W,"AP")
  mg.Add(gr8W,"AP")
  mg.Draw("a")
  mg.SetTitle( 'RB1in')
  mg.GetXaxis().SetTitle( '#eta' )
  mg.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )
  mg.SetMaximum(maxY)
  mg.GetXaxis().SetLabelFont(42)
  mg.GetXaxis().SetLabelOffset(0.007)
  mg.GetXaxis().SetLabelSize(0.043)
  mg.GetXaxis().SetTitleSize(0.05)
  mg.GetXaxis().SetTitleOffset(1.06)
  mg.GetXaxis().SetTitleFont(42)
  mg.GetYaxis().SetLabelFont(42)
  mg.GetYaxis().SetLabelOffset(0.008)
  mg.GetYaxis().SetLabelSize(0.05)
  mg.GetYaxis().SetTitleSize(0.06)
  mg.GetYaxis().SetTitleOffset(0.87)
  mg.GetYaxis().SetTitleFont(42)

  pvt = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73)
  pvt.AddText('CMS Preliminary')
  pvt.SetFillStyle(0)
  pvt.SetBorderSize(0)
  pvt.SetTextSize(0.03)
  pvt.Draw()
  pvt1 = TPaveText(.7,0.97,.9,0.97,"NDC")
  pvt1.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
  pvt1.SetFillStyle(0)
  pvt1.SetBorderSize(0)
  pvt1.SetTextSize(0.03)
  pvt1.Draw()

  legenda = TLegend(0.4, 0.7, .7, .9)
  legenda.SetNColumns(1)
  legenda.AddEntry(gr0E, "RE1", "p")
  legenda.AddEntry(gr0W, "RB1in", "p")
  legenda.AddEntry(gr1W, "RB1out", "p")
  legenda.SetTextSize(0.05)
  legenda.Draw("a");

  c.SaveAs("etaDistroDetailRB1.png")
  c.Close()

  print "----- Creating Second TCanvas -----"
  c1 = TCanvas("c1", "Canvas",50,50,W,H)
  c1.SetFillColor(0)
  c1.SetBorderMode(0)
  c1.SetFrameFillStyle(0)
  c1.SetFrameBorderMode(0)
  c1.SetLeftMargin( L/W )
  c1.SetRightMargin( R/W )
  c1.SetTopMargin( T/H )
  c1.SetBottomMargin( B/H )
  c1.SetTickx(0)
  c1.SetTicky(0)
  gPad.SetLogy()

  print " ------------ Creating TMultiGraph -----------"
  mgd2 = TMultiGraph()
  mgd2.Add(gr3E,"AP")
  mgd2.Add(gr3W,"AP")
  mgd2.Add(gr10E,"AP")
  mgd2.Add(gr10W,"AP")
  mgd2.Add(gr4W,"AP")
  mgd2.Add(gr11W,"AP")
  mgd2.Draw("a")
  mgd2.SetTitle( 'RB1in')
  mgd2.GetXaxis().SetTitle( '#eta' )
  mgd2.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' )
  mgd2.SetMaximum(maxY)
  mgd2.GetXaxis().SetLabelFont(42)
  mgd2.GetXaxis().SetLabelOffset(0.007)
  mgd2.GetXaxis().SetLabelSize(0.043)
  mgd2.GetXaxis().SetTitleSize(0.05)
  mgd2.GetXaxis().SetTitleOffset(1.06)
  mgd2.GetXaxis().SetTitleFont(42)
  mgd2.GetYaxis().SetLabelFont(42)
  mgd2.GetYaxis().SetLabelOffset(0.008)
  mgd2.GetYaxis().SetLabelSize(0.05)
  mgd2.GetYaxis().SetTitleSize(0.06)
  mgd2.GetYaxis().SetTitleOffset(0.87)
  mgd2.GetYaxis().SetTitleFont(42)

  pv = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73)
  pv.AddText('CMS Preliminary')
  pv.SetFillStyle(0)
  pv.SetBorderSize(0)
  pv.SetTextSize(0.03)
  pv.Draw()
  pv1 = TPaveText(.7,0.97,.9,0.97,"NDC")
  pv1.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
  pv1.SetFillStyle(0)
  pv1.SetBorderSize(0)
  pv1.SetTextSize(0.03)
  pv1.Draw()

  legendd2 = TLegend(0.4, 0.6, .7, .8)
  legendd2.SetNColumns(1)
  legendd2.AddEntry(gr3E, "RE2", "p")
  legendd2.AddEntry(gr3W, "RB2in", "p")
  legendd2.AddEntry(gr4W, "RB2out", "p")
  legendd2.SetTextSize(0.05)
  legendd2.Draw("a");

  c1.SaveAs("etaDistroDetailRB2.png")
  c1.Close() 
  
  print "is there an error here?"
  return
示例#24
0
gStyle.SetTitleOffset(0.8, "y")
gStyle.SetTitleOffset(1, "z")
gStyle.SetOptStat(0)

# User Options
listFiles = [
    "/afs/cern.ch/user/s/siborghi/cmtuser/Brunel_v37r1/Alignment/Escher/options/RunKalmSens61/Iter9/xml/Conditions/Velo/Alignment/Modules.xml"
]
compare2 = "Metrology"
fnamein2 = "/afs/cern.ch/user/s/siborghi/cmtuser/Alignment_v4r6/Alignment/Escher/scripts/AlignXml/ModulesMetrology.xml"

psfile = "ModConstDiff_wrt" + compare2 + ".ps"
ps = TPostScript(psfile, 112)
c1 = TCanvas('c1', '', 10, 10, 1200, 900)
c2 = TCanvas('c2', '', 10, 10, 1200, 900)
c1.Divide(1, 3)
c2.Divide(2, 3)
#ps.NewPage()
counter = 0
for fnamein in listFiles:
    counter += 1
    vlabel = '_' + str(counter)
    inputname = compare2 + vlabel

    pl01 = TLatex()
    pl01.SetTextSize(0.06)
    pl01.SetTextColor(16)

    c1.cd(1)
    c1_1.SetGrid()
示例#25
0
qfXaxis.SetTitleSize(0.07)
qfXaxis.SetTitleOffset(0.55)
qfYaxis.SetTitle("x")
qfYaxis.SetTitleSize(0.07)
qfYaxis.SetTitleOffset(0.55)

# Set sigma to 1 and mean to zero of survival function of quantile of normal
# distribution, and set color to green and title to none.
cqfunc.SetParameter(0, 1.0)
cqfunc.SetTitle("")
cqfunc.SetLineColor(kGreen)
cqfunc.SetNpx(1000)

# Create canvas and divide in three parts
c1 = TCanvas("c1", "Normal Distributions", 100, 10, 600, 800)
c1.Divide(1, 3)
c1.cd(1)

# Draw the normal distribution
pdfunc.Draw()
legend1 = TLegend(0.583893, 0.601973, 0.885221, 0.854151)
legend1.AddEntry(pdfunc, "normal_pdf", "l")
legend1.Draw()

# Draw the cumulative normal distribution
c1.cd(2)
cdfunc.Draw()
ccdfunc.Draw("same")
legend2 = TLegend(0.585605, 0.462794, 0.886933, 0.710837)
legend2.AddEntry(cdfunc, "normal_cdf", "l")
legend2.AddEntry(ccdfunc, "normal_cdf_c", "l")
示例#26
0
文件: plot.py 项目: amodakgit/VLQAna
                                        integralError)
print '\hline'
print '{0:<5} & {1:<5.0f} \\\\ '.format(h_data.GetName().split('_')[0],
                                        h_data.Integral())
print '\end{tabular}'
#print 'bkg : ', h_bkg.Integral(ibin,bin2), 'tot : ', h_tot.Integral(ibin,bin2)

hs = THStack("", "")

for ihist in reversed(templates[0:5]):
    hs.Add(ihist)
    print 'histo added', ihist.GetName()

# Canvas
c1 = TCanvas('c1', 'c1', 800, 600)
c1.Divide(1, 2)
scale = (1.0 - 0.3) / 0.35

# prepare top pad for original plot
pad = c1.cd(1)
pad.SetPad(0, 0.3, 1, 1)
pad.SetTopMargin(0.1)
pad.SetBottomMargin(0.005)
t = pad.GetTopMargin()

# prepare the 2nd pad
pad = c1.cd(2)
pad.SetPad(0, 0.0, 1, 0.3)
pad.SetTopMargin(0.06)
pad.SetBottomMargin(0.4)
pad.SetTickx(1)
示例#27
0
def SaveHisto1D(HIST,
                suffix,
                output,
                snorm=1,
                ratio=0,
                poisson=True,
                logy=False,
                isVal=False):

    # only data and mc
    # SUFFIX = 2016_ss_lep1_pt

    bkgsum = 'BkgSum_%s' % (suffix)
    HIST[bkgsum] = HIST['DATA_%s' % (suffix)].Clone("BkgSum") if 'DATA_%s' % (
        suffix) in HIST else HIST['MC_%s' % (suffix)].Clone("BkgSum")
    HIST[bkgsum].Reset("MICES")
    HIST[bkgsum].SetFillStyle(3003)
    HIST[bkgsum].SetFillColor(1)
    HIST[bkgsum].SetMarkerStyle(0)

    HIST[bkgsum].Add(HIST['MC_%s' % (suffix)])

    HIST['DATA_%s' % (suffix)].SetMarkerStyle(20)
    HIST['DATA_%s' % (suffix)].SetMarkerSize(1.25)
    HIST['DATA_%s' % (suffix)].SetFillColor(418)
    HIST['DATA_%s' % (suffix)].SetFillStyle(1001)
    HIST['DATA_%s' % (suffix)].SetLineColor(1)
    HIST['DATA_%s' % (suffix)].SetLineStyle(1)
    HIST['DATA_%s' % (suffix)].SetLineWidth(2)

    HIST['MC_%s' % (suffix)].SetFillColor(418)
    HIST['MC_%s' % (suffix)].SetFillStyle(1001)
    HIST['MC_%s' % (suffix)].SetLineColor(418)
    HIST['MC_%s' % (suffix)].SetLineStyle(1)
    HIST['MC_%s' % (suffix)].SetLineWidth(2)

    for i, s in enumerate(HIST):
        addOverflow(HIST[s], False)  # Add overflow

    #Stack
    bkg = THStack(
        'bkg', ";" + HIST[bkgsum].GetXaxis().GetTitle() + ";" +
        HIST[bkgsum].GetYaxis().GetTitle())

    bkg.Add(HIST['MC_%s' % (suffix)])  # ADD ALL BKG

    #Legend
    n = len(HIST)
    leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetTextSize(0.03)
    leg.AddEntry(HIST['DATA_%s' % (suffix)],
                 'Data [%.1f]' % (HIST['DATA_%s' % (suffix)].Integral()), "pl")
    leg.AddEntry(HIST['MC_%s' % (suffix)],
                 'DY [%.1f]' % (HIST['MC_%s' % (suffix)].Integral()), "f")

    #if isFake: leg.AddEntry(HIST['FAKE_%s' %(suffix)], 'Fake [%.1f]' %(HIST['FAKE_%s' %(suffix)].Integral()), "f")

    leg.AddEntry(HIST[bkgsum], 'BkgSum [%.1f]' % (HIST[bkgsum].Integral()),
                 "f")
    c1 = TCanvas("c1",
                 HIST.values()[-1].GetXaxis().GetTitle(), 800,
                 800 if ratio else 600)

    #Ratio pad
    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)

    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.06)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if logy:
        c1.GetPad(bool(ratio)).SetLogy()

    #Draw
    bkg.Draw("HIST")  # stack
    HIST[bkgsum].Draw("SAME, E2")  # sum of bkg
    HIST['DATA_%s' % (suffix)].Draw("SAME, PE")  # data

    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1)  #1.075

    bkg.SetMaximum((6.0 if logy else 1.5) * max(
        bkg.GetMaximum(),
        HIST['DATA_%s' %
             (suffix)].GetBinContent(HIST['DATA_%s' %
                                          (suffix)].GetMaximumBin()) +
        HIST['DATA_%s' %
             (suffix)].GetBinError(HIST['DATA_%s' %
                                        (suffix)].GetMaximumBin())))
    bkg.SetMinimum(
        max(
            min(HIST[bkgsum].GetBinContent(HIST[bkgsum].GetMinimumBin(
            )), HIST['DATA_%s' %
                     (suffix)].GetMinimum()), 5.e-1) if logy else 0.)

    #bkg.SetMinimum(1.0)

    leg.Draw()

    setHistStyle(bkg, 1.2 if ratio else 1.1)
    setHistStyle(HIST[bkgsum], 1.2 if ratio else 1.1)

    ##########################
    if ratio:
        c1.cd(2)
        err = HIST[bkgsum].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if HIST[bkgsum].GetBinContent(i) > 0:
                err.SetBinError(
                    i, HIST[bkgsum].GetBinError(i) /
                    HIST[bkgsum].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        errLine.SetLineColor(1)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")

        if 'DATA_%s' % (suffix) in HIST:
            res = HIST['DATA_%s' % (suffix)].Clone("Residues")
            for i in range(0, res.GetNbinsX() + 1):
                if HIST[bkgsum].GetBinContent(i) > 0:
                    res.SetBinContent(
                        i,
                        res.GetBinContent(i) / HIST[bkgsum].GetBinContent(i))
                    res.SetBinError(
                        i,
                        res.GetBinError(i) / HIST[bkgsum].GetBinContent(i))
            setBotStyle(res)
            res.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(HIST['DATA_%s' % (suffix)], HIST[bkgsum])
                drawKolmogorov(HIST['DATA_%s' % (suffix)], HIST[bkgsum])
                #drawRelativeYield(HIST['DATA_%s' %(suffix)], HIST[bkgsum])
        else:
            res = None
    c1.cd(1)
    if '2016' in output:
        drawCMS("35.87", "Object Study")
    elif '2017' in output:
        drawCMS("41.53", "Object Study")
    elif '2018' in output:
        drawCMS("59.74", "Object Study")

    if 'os' in suffix:
        drawRegion('Opposite Sign')
    elif 'ss' in suffix:
        drawRegion('Same Sign')

    c1.Update()

    c1.Print('%s/hstack_%s.png' % (output, suffix))
示例#28
0
def signal(channel, stype):
    if 'VBF' in channel:
        stype = 'XZHVBF'
    else:
        stype = 'XZH'
    # HVT model
    if stype.startswith('X'):
        signalType = 'HVT'
        genPoints = [800, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000, 3500, 4000, 4500, 5000]
        massPoints = [x for x in range(800, 5000+1, 100)]
        interPar = True
    else:
        print "Signal type", stype, "not recognized"
        return
    
    n = len(genPoints)  
    
    category = channel
    cColor = color[category] if category in color else 1

    nElec = channel.count('e')
    nMuon = channel.count('m')
    nLept = nElec + nMuon
    nBtag = channel.count('b')
    if '0b' in channel:
        nBtag = 0

    X_name = "VH_mass"

    if not os.path.exists(PLOTDIR+stype+category): os.makedirs(PLOTDIR+stype+category)

    #*******************************************************#
    #                                                       #
    #              Variables and selections                 #
    #                                                       #
    #*******************************************************#
    X_mass = RooRealVar(  "X_mass",    "m_{ZH}",       XBINMIN, XBINMAX, "GeV")
    J_mass = RooRealVar(  "H_mass",   "jet mass",        LOWMIN, HIGMAX, "GeV")
    V_mass = RooRealVar(  "V_mass", "V jet mass",           -9.,  1.e6, "GeV")
    CSV1    = RooRealVar( "H_csv1",           "",         -999.,     2.     )
    CSV2    = RooRealVar( "H_csv2",           "",         -999.,     2.     )
    DeepCSV1= RooRealVar( "H_deepcsv1",       "",         -999.,     2.     )
    DeepCSV2= RooRealVar( "H_deepcsv2",       "",         -999.,     2.     )
    H_ntag  = RooRealVar( "H_ntag",           "",           -9.,     9.     )
    H_dbt   = RooRealVar( "H_dbt",            "",           -2.,     2.     )
    H_tau21 = RooRealVar( "H_tau21",          "",           -9.,     2.     )
    H_eta = RooRealVar( "H_eta",              "",           -9.,     9.     )
    H_tau21_ddt = RooRealVar( "H_ddt",  "",           -9.,     2.     )
    MaxBTag = RooRealVar( "MaxBTag",          "",          -10.,     2.     )
    H_chf   = RooRealVar( "H_chf",            "",           -1.,     2.     )
    MinDPhi = RooRealVar( "MinDPhi",          "",           -1.,    99.     )
    DPhi    = RooRealVar( "DPhi",             "",           -1.,    99.     )
    DEta    = RooRealVar( "DEta",             "",           -1.,    99.     )
    Mu1_relIso = RooRealVar( "Mu1_relIso",    "",           -1.,    99.     )
    Mu2_relIso = RooRealVar( "Mu2_relIso",    "",           -1.,    99.     )
    nTaus   = RooRealVar( "nTaus",            "",           -1.,    99.     )
    Vpt     = RooRealVar( "V.Pt()",           "",           -1.,   1.e6     )
    V_pt     = RooRealVar( "V_pt",            "",           -1.,   1.e6     )
    H_pt     = RooRealVar( "H_pt",            "",           -1.,   1.e6     )
    VH_deltaR=RooRealVar( "VH_deltaR",        "",           -1.,    99.     )
    isZtoNN = RooRealVar( "isZtoNN",          "",            0.,     2.     )
    isZtoEE = RooRealVar( "isZtoEE",          "",            0.,     2.     )
    isZtoMM = RooRealVar( "isZtoMM",          "",            0.,     2.     )
    isHtobb = RooRealVar( "isHtobb",          "",            0.,     2.     )
    isVBF   = RooRealVar( "isVBF",            "",            0.,     2.     )
    isMaxBTag_loose = RooRealVar( "isMaxBTag_loose", "",     0.,     2.     )
    weight  = RooRealVar( "eventWeightLumi",  "",         -1.e9,   1.e9     )

    Xmin = XBINMIN
    Xmax = XBINMAX

    # Define the RooArgSet which will include all the variables defined before
    # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add'
    variables = RooArgSet(X_mass, J_mass, V_mass, CSV1, CSV2, H_ntag, H_dbt, H_tau21)
    variables.add(RooArgSet(DEta, DPhi, MaxBTag, MinDPhi, nTaus, Vpt))
    variables.add(RooArgSet(DeepCSV1, DeepCSV2,VH_deltaR, H_tau21_ddt))
    variables.add(RooArgSet(isZtoNN, isZtoEE, isZtoMM, isHtobb, isMaxBTag_loose, weight))
    variables.add(RooArgSet(isVBF, Mu1_relIso, Mu2_relIso, H_chf, H_pt, V_pt,H_eta))
    #X_mass.setRange("X_extended_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_integration_range", Xmin, Xmax)
    X_mass.setBins(int((X_mass.getMax() - X_mass.getMin())/100))
    binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax())
    X_mass.setBinning(binsXmass, "PLOT")
    massArg = RooArgSet(X_mass)

    # Cuts
    SRcut = selection[category]+selection['SR']
    print "  Cut:\t", SRcut
    #*******************************************************#
    #                                                       #
    #                    Signal fits                        #
    #                                                       #
    #*******************************************************#

    treeSign = {}
    setSignal = {}

    vmean  = {}
    vsigma = {}
    valpha1 = {}
    vslope1 = {}
    smean  = {}
    ssigma = {}
    salpha1 = {}
    sslope1 = {}
    salpha2 = {}
    sslope2 = {}
    a1 = {}
    a2 = {}
    sbrwig = {}
    signal = {}
    signalExt = {}
    signalYield = {}
    signalIntegral = {}
    signalNorm = {}
    signalXS = {}
    frSignal = {}
    frSignal1 = {}
    frSignal2 = {}
    frSignal3 = {}

    # Signal shape uncertainties (common amongst all mass points)
    xmean_fit = RooRealVar("sig_p1_fit", "Variation of the resonance position with the fit uncertainty", 0.005, -1., 1.)
    smean_fit = RooRealVar("CMSRunII_sig_p1_fit", "Change of the resonance position with the fit uncertainty", 0., -10, 10)
    xmean_jes = RooRealVar("sig_p1_scale_jes", "Variation of the resonance position with the jet energy scale", 0.010, -1., 1.) #0.001
    smean_jes = RooRealVar("CMSRunII_sig_p1_jes", "Change of the resonance position with the jet energy scale", 0., -10, 10)
    xmean_e = RooRealVar("sig_p1_scale_e", "Variation of the resonance position with the electron energy scale", 0.001, -1., 1.)
    smean_e = RooRealVar("CMSRunII_sig_p1_scale_e", "Change of the resonance position with the electron energy scale", 0., -10, 10)
    xmean_m = RooRealVar("sig_p1_scale_m", "Variation of the resonance position with the muon energy scale", 0.001, -1., 1.)
    smean_m = RooRealVar("CMSRunII_sig_p1_scale_m", "Change of the resonance position with the muon energy scale", 0., -10, 10)

    xsigma_fit = RooRealVar("sig_p2_fit", "Variation of the resonance width with the fit uncertainty", 0.02, -1., 1.)
    ssigma_fit = RooRealVar("CMSRunII_sig_p2_fit", "Change of the resonance width with the fit uncertainty", 0., -10, 10)
    xsigma_jes = RooRealVar("sig_p2_scale_jes", "Variation of the resonance width with the jet energy scale", 0.010, -1., 1.) #0.001
    ssigma_jes = RooRealVar("CMSRunII_sig_p2_jes", "Change of the resonance width with the jet energy scale", 0., -10, 10)
    xsigma_jer = RooRealVar("sig_p2_scale_jer", "Variation of the resonance width with the jet energy resolution", 0.020, -1., 1.)
    ssigma_jer = RooRealVar("CMSRunII_sig_p2_jer", "Change of the resonance width with the jet energy resolution", 0., -10, 10)
    xsigma_e = RooRealVar("sig_p2_scale_e", "Variation of the resonance width with the electron energy scale", 0.001, -1., 1.)
    ssigma_e = RooRealVar("CMSRunII_sig_p2_scale_e", "Change of the resonance width with the electron energy scale", 0., -10, 10)
    xsigma_m = RooRealVar("sig_p2_scale_m", "Variation of the resonance width with the muon energy scale", 0.040, -1., 1.)
    ssigma_m = RooRealVar("CMSRunII_sig_p2_scale_m", "Change of the resonance width with the muon energy scale", 0., -10, 10)
    
    xalpha1_fit = RooRealVar("sig_p3_fit", "Variation of the resonance alpha with the fit uncertainty", 0.03, -1., 1.)
    salpha1_fit = RooRealVar("CMSRunII_sig_p3_fit", "Change of the resonance alpha with the fit uncertainty", 0., -10, 10)
    
    xslope1_fit = RooRealVar("sig_p4_fit", "Variation of the resonance slope with the fit uncertainty", 0.10, -1., 1.)
    sslope1_fit = RooRealVar("CMSRunII_sig_p4_fit", "Change of the resonance slope with the fit uncertainty", 0., -10, 10)

    xmean_fit.setConstant(True)
    smean_fit.setConstant(True)
    xmean_jes.setConstant(True)
    smean_jes.setConstant(True)
    xmean_e.setConstant(True)
    smean_e.setConstant(True)
    xmean_m.setConstant(True)
    smean_m.setConstant(True)
    
    xsigma_fit.setConstant(True)
    ssigma_fit.setConstant(True)
    xsigma_jes.setConstant(True)
    ssigma_jes.setConstant(True)
    xsigma_jer.setConstant(True)
    ssigma_jer.setConstant(True)
    xsigma_e.setConstant(True)
    ssigma_e.setConstant(True)
    xsigma_m.setConstant(True)
    ssigma_m.setConstant(True)
    
    xalpha1_fit.setConstant(True)
    salpha1_fit.setConstant(True)
    xslope1_fit.setConstant(True)
    sslope1_fit.setConstant(True)

    # the alpha method is now done.
    for m in massPoints:
        signalString = "M%d" % m
        signalMass = "%s_M%d" % (stype, m)
        signalName = "%s%s_M%d" % (stype, category, m)
        signalColor = sample[signalMass]['linecolor'] if signalName in sample else 1

        # define the signal PDF
        vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m, m*0.5, m*1.25)
        smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)", RooArgList(vmean[m], xmean_e, smean_e, xmean_m, smean_m, xmean_jes, smean_jes, xmean_fit, smean_fit))

        vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma", m*0.035, m*0.01, m*0.4)
        sigmaList = RooArgList(vsigma[m], xsigma_e, ssigma_e, xsigma_m, ssigma_m, xsigma_jes, ssigma_jes, xsigma_jer, ssigma_jer)
        sigmaList.add(RooArgList(xsigma_fit, ssigma_fit))
        ssigma[m] = RooFormulaVar(signalName + "_sigma", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)*(1+@9*@10)", sigmaList)
        
        valpha1[m] = RooRealVar(signalName + "_valpha1", "Crystal Ball alpha", 1.,  0., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0*(1+@1*@2)", RooArgList(valpha1[m], xalpha1_fit, salpha1_fit))

        vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope", 10., 1., 60.) # slope of the power tail   #10 1 60
        sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0*(1+@1*@2)", RooArgList(vslope1[m], xslope1_fit, sslope1_fit))

        salpha2[m] = RooRealVar(signalName + "_alpha2", "Crystal Ball alpha", 2,  1., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        sslope2[m] = RooRealVar(signalName + "_slope2", "Crystal Ball slope", 10, 1.e-1, 115.) # slope of the power tail
        #define polynomial
        #a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", m, 0.5*m, 2*m)
        a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", 0.001*m, 0.0005*m, 0.01*m)
        a2[m] = RooRealVar(signalName + "_a2", "par 2 for polynomial", 0.05, -1.,1.)
        #if channel=='nnbbVBF' or channel=='nn0bVBF':
        #    signal[m] = RooPolynomial(signalName,"m_{%s'} = %d GeV" % (stype[1], m) , X_mass, RooArgList(a1[m],a2[m]))
        #else:
        #    signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel
        signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel
        # extend the PDF with the yield to perform an extended likelihood fit
        signalYield[m] = RooRealVar(signalName+"_yield", "signalYield", 100, 0., 1.e6)
        signalNorm[m] = RooRealVar(signalName+"_norm", "signalNorm", 1., 0., 1.e6)
        signalXS[m] = RooRealVar(signalName+"_xs", "signalXS", 1., 0., 1.e6)
        signalExt[m] = RooExtendPdf(signalName+"_ext", "extended p.d.f", signal[m], signalYield[m])
        
        vslope1[m].setMax(50.)
        vslope1[m].setVal(20.)
        #valpha1[m].setVal(1.0)
        #valpha1[m].setConstant(True)
        
        if 'bb' in channel and 'VBF' not in channel:
            if 'nn' in channel:
                valpha1[m].setVal(0.5)
        elif '0b' in channel and 'VBF' not in channel:
            if 'nn' in channel:
                if m==800:
                    valpha1[m].setVal(2.)
                    vsigma[m].setVal(m*0.04)
            elif 'ee' in channel:
                valpha1[m].setVal(0.8)
                if m==800:
                    #valpha1[m].setVal(1.2)
                    valpha1[m].setVal(2.5)
                    vslope1[m].setVal(50.)
            elif 'mm' in channel:
                if m==800:
                    valpha1[m].setVal(2.)
                    vsigma[m].setVal(m*0.03)
                else:
                    vmean[m].setVal(m*0.9)
                    vsigma[m].setVal(m*0.08)
        elif 'bb' in channel and 'VBF' in channel:
            if 'nn' in channel:
                if m!=1800:
                    vmean[m].setVal(m*0.8)
                vsigma[m].setVal(m*0.08)
                valpha1[m].setMin(1.)
            elif 'ee' in channel:
                valpha1[m].setVal(0.7)
            elif 'mm' in channel:
                if m==800:
                    vslope1[m].setVal(50.)
                valpha1[m].setVal(0.7)
        elif '0b' in channel and 'VBF' in channel:
            if 'nn' in channel:
                valpha1[m].setVal(3.) 
                vmean[m].setVal(m*0.8)
                vsigma[m].setVal(m*0.08)
                valpha1[m].setMin(1.)
            elif 'ee' in channel:
                if m<2500:
                    valpha1[m].setVal(2.)
                if m==800:
                    vsigma[m].setVal(m*0.05)
                elif m==1000:
                    vsigma[m].setVal(m*0.03)
                elif m>1000 and m<1800:
                    vsigma[m].setVal(m*0.04)
            elif 'mm' in channel:
                if m<2000:
                    valpha1[m].setVal(2.)
                if m==1000 or m==1800:
                    vsigma[m].setVal(m*0.03)
                elif m==1200 or m==1600:
                    vsigma[m].setVal(m*0.04)

            
        #if m < 1000: vsigma[m].setVal(m*0.06)

        # If it's not the proper channel, make it a gaussian
        #if nLept==0 and 'VBF' in channel:
        #    valpha1[m].setVal(5)
        #    valpha1[m].setConstant(True)
        #    vslope1[m].setConstant(True)
        #    salpha2[m].setConstant(True)
        #    sslope2[m].setConstant(True)

        
        # ---------- if there is no simulated signal, skip this mass point ----------
        if m in genPoints:
            if VERBOSE: print " - Mass point", m

            # define the dataset for the signal applying the SR cuts
            treeSign[m] = TChain("tree")
            for j, ss in enumerate(sample[signalMass]['files']):
                treeSign[m].Add(NTUPLEDIR + ss + ".root")
            
            if treeSign[m].GetEntries() <= 0.:
                if VERBOSE: print " - 0 events available for mass", m, "skipping mass point..."
                signalNorm[m].setVal(-1)
                vmean[m].setConstant(True)
                vsigma[m].setConstant(True)
                salpha1[m].setConstant(True)
                sslope1[m].setConstant(True)
                salpha2[m].setConstant(True)
                sslope2[m].setConstant(True)
                signalNorm[m].setConstant(True)
                signalXS[m].setConstant(True)
                continue
            
            setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar(weight), RooFit.Import(treeSign[m]))
            if VERBOSE: print " - Dataset with", setSignal[m].sumEntries(), "events loaded"
            
            # FIT
            signalYield[m].setVal(setSignal[m].sumEntries())
            
            if treeSign[m].GetEntries(SRcut) > 5:
                if VERBOSE: print " - Running fit"
 
                frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1), RooFit.Extended(True), RooFit.SumW2Error(True), RooFit.PrintLevel(-1))
                if VERBOSE: print "********** Fit result [", m, "] **", category, "*"*40, "\n", frSignal[m].Print(), "\n", "*"*80
                if VERBOSE: frSignal[m].correlationMatrix().Print()
                drawPlot(signalMass, stype+channel, X_mass, signal[m], setSignal[m], frSignal[m])
            
            else:
                print "  WARNING: signal", stype, "and mass point", m, "in channel", channel, "has 0 entries or does not exist"          
            # Remove HVT cross section (which is the same for Zlep and Zinv)
            if stype == "XZHVBF":
                sample_name = 'Zprime_VBF_Zh_Zlephinc_narrow_M-%d' % m
            else:
                sample_name = 'ZprimeToZHToZlepHinc_narrow_M%d' % m

            xs = xsection[sample_name]['xsec']
            
            signalXS[m].setVal(xs * 1000.)
            
            signalIntegral[m] = signalExt[m].createIntegral(massArg, RooFit.NormSet(massArg), RooFit.Range("X_integration_range"))
            boundaryFactor = signalIntegral[m].getVal()
            if VERBOSE: 
                print " - Fit normalization vs integral:", signalYield[m].getVal(), "/", boundaryFactor, "events"
            if channel=='nnbb' and m==5000:
                signalNorm[m].setVal(2.5)
            elif channel=='nn0b' and m==5000:
                signalNorm[m].setVal(6.7)
            else:
                signalNorm[m].setVal( boundaryFactor * signalYield[m].getVal() / signalXS[m].getVal()) # here normalize to sigma(X) x Br(X->VH) = 1 [fb]
            
            
        a1[m].setConstant(True)
        a2[m].setConstant(True)
        vmean[m].setConstant(True)
        vsigma[m].setConstant(True)
        valpha1[m].setConstant(True)
        vslope1[m].setConstant(True)
        salpha2[m].setConstant(True)
        sslope2[m].setConstant(True)
        signalNorm[m].setConstant(True)
        signalXS[m].setConstant(True)

    #*******************************************************#
    #                                                       #
    #                 Signal interpolation                  #
    #                                                       #
    #*******************************************************#


    # ====== CONTROL PLOT ======
    c_signal = TCanvas("c_signal", "c_signal", 800, 600)
    c_signal.cd()
    frame_signal = X_mass.frame()
    for m in genPoints[:-2]:
        if m in signalExt.keys():
            signal[m].plotOn(frame_signal, RooFit.LineColor(sample["%s_M%d" % (stype, m)]['linecolor']), RooFit.Normalization(signalNorm[m].getVal(), RooAbsReal.NumEvent), RooFit.Range("X_reasonable_range"))
    frame_signal.GetXaxis().SetRangeUser(0, 6500)
    frame_signal.Draw()
    drawCMS(-1, YEAR, "Simulation")
    drawAnalysis(channel)
    drawRegion(channel)
    c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.pdf")
    c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.png")
    #if VERBOSE: raw_input("Press Enter to continue...")
    # ====== CONTROL PLOT ======

    # Normalization
    gnorm = TGraphErrors()
    gnorm.SetTitle(";m_{X} (GeV);integral (GeV)")
    gnorm.SetMarkerStyle(20)
    gnorm.SetMarkerColor(1)
    gnorm.SetMaximum(0)
    inorm = TGraphErrors()
    inorm.SetMarkerStyle(24)
    fnorm = TF1("fnorm", "pol9", 800, 5000) #"pol5" if not channel=="XZHnnbb" else "pol6" #pol5*TMath::Floor(x-1800) + ([5]*x + [6]*x*x)*(1-TMath::Floor(x-1800))
    fnorm.SetLineColor(920)
    fnorm.SetLineStyle(7)
    fnorm.SetFillColor(2)
    fnorm.SetLineColor(cColor)

    # Mean
    gmean = TGraphErrors()
    gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)")
    gmean.SetMarkerStyle(20)
    gmean.SetMarkerColor(cColor)
    gmean.SetLineColor(cColor)
    imean = TGraphErrors()
    imean.SetMarkerStyle(24)
    fmean = TF1("fmean", "pol1", 0, 5000)
    fmean.SetLineColor(2)
    fmean.SetFillColor(2)

    # Width
    gsigma = TGraphErrors()
    gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)")
    gsigma.SetMarkerStyle(20)
    gsigma.SetMarkerColor(cColor)
    gsigma.SetLineColor(cColor)
    isigma = TGraphErrors()
    isigma.SetMarkerStyle(24)
    fsigma = TF1("fsigma", "pol1", 0, 5000)
    fsigma.SetLineColor(2)
    fsigma.SetFillColor(2)

    # Alpha1
    galpha1 = TGraphErrors()
    galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha")
    galpha1.SetMarkerStyle(20)
    galpha1.SetMarkerColor(cColor)
    galpha1.SetLineColor(cColor)
    ialpha1 = TGraphErrors()
    ialpha1.SetMarkerStyle(24)
    falpha1 = TF1("falpha", "pol0", 0, 5000)
    falpha1.SetLineColor(2)
    falpha1.SetFillColor(2)

    # Slope1
    gslope1 = TGraphErrors()
    gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)")
    gslope1.SetMarkerStyle(20)
    gslope1.SetMarkerColor(cColor)
    gslope1.SetLineColor(cColor)
    islope1 = TGraphErrors()
    islope1.SetMarkerStyle(24)
    fslope1 = TF1("fslope", "pol0", 0, 5000)
    fslope1.SetLineColor(2)
    fslope1.SetFillColor(2)

    # Alpha2
    galpha2 = TGraphErrors()
    galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha")
    galpha2.SetMarkerStyle(20)
    galpha2.SetMarkerColor(cColor)
    galpha2.SetLineColor(cColor)
    ialpha2 = TGraphErrors()
    ialpha2.SetMarkerStyle(24)
    falpha2 = TF1("falpha", "pol0", 0, 5000)
    falpha2.SetLineColor(2)
    falpha2.SetFillColor(2)

    # Slope2
    gslope2 = TGraphErrors()
    gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)")
    gslope2.SetMarkerStyle(20)
    gslope2.SetMarkerColor(cColor)
    gslope2.SetLineColor(cColor)
    islope2 = TGraphErrors()
    islope2.SetMarkerStyle(24)
    fslope2 = TF1("fslope", "pol0", 0, 5000)
    fslope2.SetLineColor(2)
    fslope2.SetFillColor(2)



    n = 0
    for i, m in enumerate(genPoints):
        if not m in signalNorm.keys(): continue
        if signalNorm[m].getVal() < 1.e-6: continue
        signalString = "M%d" % m
        signalName = "%s_M%d" % (stype, m)

        if gnorm.GetMaximum() < signalNorm[m].getVal(): gnorm.SetMaximum(signalNorm[m].getVal())
        gnorm.SetPoint(n, m, signalNorm[m].getVal())
        gmean.SetPoint(n, m, vmean[m].getVal())
        gmean.SetPointError(n, 0, min(vmean[m].getError(), vmean[m].getVal()*0.02))
        gsigma.SetPoint(n, m, vsigma[m].getVal())
        gsigma.SetPointError(n, 0, min(vsigma[m].getError(), vsigma[m].getVal()*0.05))
        galpha1.SetPoint(n, m, valpha1[m].getVal())
        galpha1.SetPointError(n, 0, min(valpha1[m].getError(), valpha1[m].getVal()*0.10))
        gslope1.SetPoint(n, m, vslope1[m].getVal())
        gslope1.SetPointError(n, 0, min(vslope1[m].getError(), vslope1[m].getVal()*0.10))
        galpha2.SetPoint(n, m, salpha2[m].getVal())
        galpha2.SetPointError(n, 0, min(salpha2[m].getError(), salpha2[m].getVal()*0.10))
        gslope2.SetPoint(n, m, sslope2[m].getVal())
        gslope2.SetPointError(n, 0, min(sslope2[m].getError(), sslope2[m].getVal()*0.10))
        n = n + 1
    print "fit on gmean:"
    gmean.Fit(fmean, "Q0", "SAME")
    print "fit on gsigma:"
    gsigma.Fit(fsigma, "Q0", "SAME")
    print "fit on galpha:"
    galpha1.Fit(falpha1, "Q0", "SAME")
    print "fit on gslope:"
    gslope1.Fit(fslope1, "Q0", "SAME")
    galpha2.Fit(falpha2, "Q0", "SAME")
    gslope2.Fit(fslope2, "Q0", "SAME")
    #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S"))
    gnorm.Fit(fnorm, "Q", "SAME", 700, 5000)

    for m in massPoints:
        signalName = "%s_M%d" % (stype, m)
        
        if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.)

        # Interpolation method
        syield = gnorm.Eval(m)
        spline = gnorm.Eval(m, 0, "S")
        sfunct = fnorm.Eval(m)
        
        #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield))
        delta = abs(1.-spline/sfunct) if sfunct > 0 else 0
        syield = spline
               
        if interPar:
            jmean = gmean.Eval(m)
            jsigma = gsigma.Eval(m)
            jalpha1 = galpha1.Eval(m)
            jslope1 = gslope1.Eval(m)
        else:
            jmean = fmean.GetParameter(0) + fmean.GetParameter(1)*m + fmean.GetParameter(2)*m*m
            jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(1)*m + fsigma.GetParameter(2)*m*m
            jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(1)*m + falpha1.GetParameter(2)*m*m
            jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(1)*m + fslope1.GetParameter(2)*m*m

        inorm.SetPoint(inorm.GetN(), m, syield)
        signalNorm[m].setVal(syield)

        imean.SetPoint(imean.GetN(), m, jmean)
        if jmean > 0: vmean[m].setVal(jmean)

        isigma.SetPoint(isigma.GetN(), m, jsigma)
        if jsigma > 0: vsigma[m].setVal(jsigma)

        ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1)
        if not jalpha1==0: valpha1[m].setVal(jalpha1)

        islope1.SetPoint(islope1.GetN(), m, jslope1)
        if jslope1 > 0: vslope1[m].setVal(jslope1)
    

    c1 = TCanvas("c1", "Crystal Ball", 1200, 800)
    c1.Divide(2, 2)
    c1.cd(1)
    gmean.SetMinimum(0.)
    gmean.Draw("APL")
    imean.Draw("P, SAME")
    drawRegion(channel)
    c1.cd(2)
    gsigma.SetMinimum(0.)
    gsigma.Draw("APL")
    isigma.Draw("P, SAME")
    drawRegion(channel)
    c1.cd(3)
    galpha1.Draw("APL")
    ialpha1.Draw("P, SAME")
    drawRegion(channel)
    galpha1.GetYaxis().SetRangeUser(0., 5.)
    c1.cd(4)
    gslope1.Draw("APL")
    islope1.Draw("P, SAME")
    drawRegion(channel)
    gslope1.GetYaxis().SetRangeUser(0., 125.)
    if False:
        c1.cd(5)
        galpha2.Draw("APL")
        ialpha2.Draw("P, SAME")
        drawRegion(channel)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(channel)
        gslope2.GetYaxis().SetRangeUser(0., 10.)


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


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





    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    # create workspace
    w = RooWorkspace("ZH_RunII", "workspace")
    for m in massPoints:
        getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName()))
        getattr(w, "import")(signalNorm[m], RooFit.Rename(signalNorm[m].GetName()))
        getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName()))
    w.writeToFile("%s%s.root" % (WORKDIR, stype+channel), True)
    print "Workspace", "%s%s.root" % (WORKDIR, stype+channel), "saved successfully"
    sys.exit()
示例#29
0
#s = THStack("hs","")
#s.Add(h_ttbar_m3Hist)
#s.Add(h_wjets_m3Hist)
#s.Add(h_singletop_t_m3Hist)
#s.Add(h_zjets_m3Hist)
#s.Draw()
#s.SetMaximum(65)
#s.GetXaxis().SetTitle("M3 (GeV)")
#s.GetYaxis().SetTitle("Number of Events")

#h_data_m3Hist.Draw("sameP")
#h_data_m3Hist.SetMarkerStyle(20)
#h_data_m3Hist.SetMarkerSize(0.9)

c = TCanvas("c", "c", 900, 600)
c.Divide(3, 2)
c.cd(1)
h_ttbar_m3Hist.Draw()
c.cd(2)
h_wjets_m3Hist.Draw()
c.cd(3)
h_singletop_t_m3Hist.Draw()
c.cd(4)
h_zjets_m3Hist.Draw()
c.cd(5)
h_qcd_data_m3Hist.Draw()
c.cd(6)
h_data_m3Hist.Draw()

AminX = h_data_m3Hist.GetXaxis().FindBin(20) + 1
AmaxX = h_data_m3Hist.GetXaxis().FindBin(150)
示例#30
0
def plot_fits(canvas,
              histos,
              x_range,
              x_bin_step,
              title_formatter,
              save_name,
              label,
              y_fit_range,
              y_range=None,
              title=None,
              xtitle=None,
              ytitle=None,
              hline=None):

    canvas.Clear()
    canvas.Divide(2, 3)

    root_is_dumb = []
    for i in range(1, 7):
        canvas.cd(i)

        title = title_formatter.format(i)
        graph, slices, fits = fit_slices(histos.get(title, default_histo2d),
                                         x_range,
                                         x_bin_step,
                                         y_fit_range=y_fit_range)
        graph.SetMarkerStyle(8)
        graph.SetMarkerSize(1)

        if y_range:
            graph.GetHistogram().SetMinimum(y_range[0])
            graph.GetHistogram().SetMaximum(y_range[1])
            graph.Draw('AP')
            root_is_dumb.append(graph)
        else:
            graph.Draw('AP')
            root_is_dumb.append(graph)

        if hline:
            line = TLine(x_range[0], hline, x_range[1], hline)
            line.SetLineStyle(8)
            line.SetLineWidth(1)
            line.Draw()
            root_is_dumb.append(line)

        if title:
            label.DrawLatex(0.1, 0.925, title)

        if xtitle:
            label.DrawLatex(0.5, 0.015, xtitle)

        if ytitle:
            label.SetTextAngle(90)
            label.DrawLatex(0.035, 0.5, ytitle)
            label.SetTextAngle(0)

    canvas.Print(save_name)

    # For the slices
    slice_can = TCanvas('slice_can', 'slice_can', 1200, 1600)
    slice_pdfname = title_formatter.split('_{}')[0] + '_slices.pdf'
    slice_can.Print(slice_pdfname + '[')
    for i in range(1, 7):
        title = title_formatter.format(i)
        graph, slices, fits = fit_slices(histos.get(title, default_histo2d),
                                         x_range, x_bin_step, y_fit_range)

        # Size of slices page
        nrows = 5
        ncols = int(np.ceil(len(slices) / nrows) + 1)
        slice_can.Clear()
        slice_can.Divide(ncols, nrows)
        for j, (s, f) in enumerate(zip(slices, fits)):
            slice_can.cd(j + 1)
            s.Draw()
            lab.DrawLatex(
                0.15, 0.88, '#mu = {0:6.4f}, #sigma = {1:6.4f}'.format(
                    f.GetParameter(1), f.GetParameter(2)))

        slice_can.Print(slice_pdfname)
    slice_can.Print(slice_pdfname + ']')