def addDataToRootFile(data, name):
        global flag
	global h_buf
	#f = open('workfile_tmp.txt', 'a')
        #f.write(data)
        lines = data.split('\n')
#        print lines[0]
        x = TVector(len(lines)-1)
        y = TVector(len(lines)-1)
	h = TH1F("h","h",BINS,MIN_BIN,MAX_BIN)
        for i in range(0,len(lines)-1):
                if(i > 4):
                        pair = lines[i].split(' ')
                        #
			h.SetBinContent(i,float(pair[1]));
                        #x[i] = float(pair[0])
                        #y[i] = float(pair[1])
#			print 'x='+pair[0]+" y="+pair[1]
        #g = TGraph(x,y)
        if (flag == 0):
		h_buf = h
		flag = 1
	else:
		c = TCanvas()
		c.cd()
		h.Draw()
		h_buf.Draw("same")
		flag = 0
		c.Write()	
	#h.Write(str(name))
        print 'write graph'
Ejemplo n.º 2
0
def make_spectral_plot(image_name,
                       stack,
                       legend):
    """
    :param image_name: name of output image (ext. ".png" will be added)
    :type image_name: str
    :param stack: stack of histograms to plot
    :type stack: THStack
    :param legend: legend to accompany histograms in stack
    :type legend: TLegend
    """
    ROOT.gROOT.SetStyle("Plain")
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetPadBorderMode(0)
    gStyle.SetPadColor(0)
    gStyle.SetCanvasColor(0)
    gStyle.SetOptTitle(0)
    gStyle.SetLabelSize(0.06, "xyz")
    gStyle.SetTitleSize(0.06, "xyz")
    gStyle.SetOptStat("")
    c1 = TCanvas("canvas", "canvas", 1200, 900)
    c1.cd()
    p1 = TPad("p1", "Region of Interest", 0.0, 0.5, 0.7, 1.0, 0)
    p1.SetBottomMargin(0.15)
    p1.SetLeftMargin(0.15)
    p1.Draw()
    p2 = TPad("p2", "Key", 0.7, 0.5, 1.0, 1.0, 0)
    p2.SetBottomMargin(0.15)
    p2.SetTopMargin(0.15)
    p2.SetLeftMargin(0.05)
    p2.SetRightMargin(0.05)
    p2.Draw()
    p3 = TPad("p3", "Full Spectrum", 0.0, 0.0, 1.0, 0.5, 0)
    p3.SetBottomMargin(0.15)
    p3.SetLeftMargin(0.15)
    p3.Draw()
    p3.cd()
    gStyle.SetOptStat(0)
    p3.SetLogy()
    stack.Draw("nostack")
    stack.GetXaxis().SetTitle("E (MeV)")
    stack.GetYaxis().SetTitle("Events/(0.02 MeV)")
    stack.SetMinimum(0.1)
    p1.cd()
    gStyle.SetOptStat(0)
    p1.SetLogy()
    stack_zoomed = stack.Clone()
    x_axis = stack_zoomed.GetXaxis()
    bin_width = x_axis.GetBinWidth(0) # assume uniform
    e_lo = 2.0 # MeV
    e_hi = 3.5 # MeV
    x_axis.SetRange(int(e_lo/bin_width), int(e_hi/bin_width))
    stack_zoomed.SetMaximum(5e3)
    stack_zoomed.Draw("nostack")
    p2.cd()
    legend.Draw()
    c1.Draw()
    image_path = image_name + ".png"
    c1.Print(image_path)
    raw_input("RETURN to exit")
Ejemplo n.º 3
0
	def plotAverageEnergyAroundL1(self):
		canvas = TCanvas('canvasAverageEnergy','Average energy',900,800)
		canvas.cd().SetLogz()
		canvas.cd().SetRightMargin(.15)

		hSum = self.fileHandler.getHistogram('averageEnergy/averageEnergyAroundPoint' + self.key + '_SummedEnergy')
		hCounter = self.fileHandler.getHistogram('averageEnergy/averageEnergyAroundPoint' + self.key + '_Counter')
	
		for i in range(0,hSum.GetNbinsX()):
			for j in range(0,hSum.GetNbinsY()):
				if hCounter.GetBinContent(hCounter.GetBin(i,j)) != 0:
					hSum.SetBinContent(hSum.GetBin(i,j),hSum.GetBinContent(hSum.GetBin(i,j))/hCounter.GetBinContent(hCounter.GetBin(i,j)))
					pass
		hSum.GetXaxis().SetRangeUser(-0.6,0.6)
		hSum.GetYaxis().SetRangeUser(-0.6,0.6)
		hSum.GetZaxis().SetTitle('Reconstructed Energy / GeV')
		hSum.SetTitle(';#Delta#eta;#Delta#phi;Reconstructed Energy / GeV')#'Average Energy in HO tiles around L1 direction
		hSum.Draw('colz')
						
		canvas.Update()
		
		#Setup plot style
		setupAxes(hSum)	
		setStatBoxOptions(hSum,1100)
		setStatBoxPosition(hSum,x1=.65,x2=.85)
		setupPalette(hSum,x2ndc=.87)
	
		canvas.Update()
		self.storeCanvas(canvas,'averageEnergy',marginRight=.15)
		return canvas,hSum,hCounter,drawHoBoxes(canvas)
Ejemplo n.º 4
0
	def plotHoDigiMatchesPerDetId(self):
		canvas = TCanvas('canvasDigiMatchesMultiplicity')
		digiMatches = self.fileHandler.getHistogram('hoDigiMatchesPerDetId_Multiplicity')
		setupAxes(digiMatches)
		digiMatches.SetTitle('Number of matches between RecHit and Digi for a given DetId')
		digiMatches.GetXaxis().SetRangeUser(0,5)
		digiMatches.GetXaxis().SetTitle('Number of matches per DetId')
		digiMatches.GetYaxis().SetTitle('#')
		canvas.cd().SetLogy()
		digiMatches.SetLineWidth(3)
		digiMatches.SetLineColor(colorRwthDarkBlue)
		digiMatches.Draw()
		
		label = drawLabelCmsPrivateSimulation()
		
		canvas.Update()
		
		stats = digiMatches.GetListOfFunctions().FindObject("stats")
		stats.SetX1NDC(.7)
		stats.SetX2NDC(.9)
		stats.SetY1NDC(.75)
		stats.SetY2NDC(.9)
		
		canvas.Update()
		self.storeCanvas(canvas,"digiMatchesPerDetId")
		return canvas,digiMatches,label
Ejemplo n.º 5
0
	def plot1DEnergyAroundL1(self):	
		'''
			eta[P,M][2,1,0]phi[P,M][2,1,0]_averageEnergyAroundPoint
			Central tile is central
		'''
		histList = []
		fitList = []
		labelList = []
		canvas = TCanvas('canvas1DEnergy','1D energy',1200,1200)
		for p in reversed(range(-2,3)):
			for e in range(-2,3):
				if e == 0 and p == 0:
					histList.append(self.fileHandler.getHistogram('etaPhi/energy1D/central_averageEnergyAroundPoint' + self.key))
				else:
					histName = ('etaPhi/energy1D/eta%s%dPhi%s%d_averageEnergyAroundPoint' + self.key) % ('P' if e >= 0 else 'M',abs(e),'P' if p >= 0 else 'M',abs(p))
					histList.append(self.fileHandler.getHistogram(histName))
		canvas.Divide(5,5)
		for i,hist in enumerate(histList):
			canvas.cd(i+1).SetLogy()
			hist.GetXaxis().SetRangeUser(-0.5,4)
			hist.SetLineWidth(3)
			setupAxes(hist)
			hist.Draw()
			fit = TF1('fit%d' % (i),'landau',0.5,2)
			hist.Fit(fit,'RQ')
			label = TPaveText(0.6,0.7,0.9,0.9,"NDC")
			label.AddText('MPV: %5.2f' % (fit.GetParameter(1)))
			label.Draw()
			labelList.append(label)
			fitList.append(fit)
		canvas.Update()
		self.storeCanvas(canvas, '1DPlots')
		return histList,canvas,fitList,labelList
Ejemplo n.º 6
0
def main():
    gROOT.SetStyle("DStyle")
    c1     = TCanvas("c1","c1")
    module = TH2D("mod",";x #rightarrow;y #rightarrow",64,0,64,4,0,4)
    
    pins_to_pixels   =  pins("pins.csv")
    pixels_to_fibers =  mapit()
    pins_to_count    =  struck("vics_list.txt",sys.argv[1])
    rows             =  rowmaker()
    
    
    module = fillhisto(module,
                       pins_to_pixels,
                       pixels_to_fibers,
                       pins_to_count,
                       rows)
    c1.cd()
    title=GetTitle("Raw FEB Data")
    module.GetYaxis().SetNdivisions(4)
    module.GetXaxis().SetNdivisions(8)
    module.GetYaxis().CenterTitle()
    module.GetXaxis().CenterTitle()
    gStyle.SetOptStat(0)
    module.Draw("COLZ")
    title.Draw("SAMES")
    c1.Update()
    c1.Modified()
    sys.stdin.readline()
Ejemplo n.º 7
0
    def __TDrawAll2D(self):
        """
        Root implementation of 2D  
        """

        self.mxz.SetMarkerColor(TColor.kRed)
        self.hxz.SetMarkerColor(TColor.kBlue)
        self.myz.SetMarkerColor(TColor.kRed)
        self.hyz.SetMarkerColor(TColor.kBlue)
        self.mxz.SetMarkerStyle(6)
        #self.mxz.SetMarkerSize(1)
        self.hxz.SetMarkerStyle(7)
        #self.hxz.SetMarkerSize(2)
        self.myz.SetMarkerStyle(6)
        self.hyz.SetMarkerStyle(7)
        #self.hyz.SetMarkerSize(2)
        c1 = TCanvas( 'c1', 'Meas & Hits 2D', 200, 10, 600, 800 )
        c1.Divide(1,2)
        c1.cd(1)
        self.mxz.Draw("")
        self.hxz.Draw("same")
        c1.cd(2)
        self.myz.Draw("")
        self.hyz.Draw("same")

        s=raw_input("return to continue")
Ejemplo n.º 8
0
def doPlotEtaPtOfSuccessfulMatches():
	file = TFile.Open('L1MuonHistogram.root')
	#Prepare canvas
	canvas = TCanvas("canvasPtEtaHoMatch","PtEtaHoMatch",1200,1200)
	canvas.cd().Draw()
	#prepare histogram
	hist = file.Get("hoMuonAnalyzer/etaPhi/3D/NoTrgTdmiAboveThr_EtaPhiPt")

	stack = THStack(hist,"zx","2dStack","",-1,-1,-1,-1,"zx","")

	#Create new histogram and add the histograms from the stack
	histNew = TH2D("histPtEtaHoMatch","p_{T} vs. #eta distribution;#eta;p_{T} / 5 GeV;#",40,-1.6,1.6,40,0,200)
	histNew.GetYaxis().SetTitleOffset(1.2)
	for i in stack.GetHists():
		histNew.Add(i)

	gStyle.SetPalette(1)
	histNew.SetStats(0)
	histNew.Draw('COLZ')
	canvas.Update()

	palette = histNew.FindObject("palette")
	palette.SetX1NDC(0.9)
	palette.SetX2NDC(0.92)
	#add label
	label = PlotStyle.getLabelCmsPrivateSimulation()
	label.Draw()
	
	canvas.Update()
	canvas.SaveAs('plots/NoL1HoMatchPtEta.pdf')
	canvas.SaveAs('plots/NoL1HoMatchPtEta.png')
	return canvas,hist,stack,histNew,label,palette,file
Ejemplo n.º 9
0
	def plotMatchedAndNotMatchedPerWheel(self):
		resHo = self.plotEnergyPerWheel('horeco')
		resHoMatched = self.plotEnergyPerWheel('L1MuonWithHoMatchAboveThr')
		
		cTogether = TCanvas('cTogether','Matched and not Matched',1800,500)
		cTogether.Divide(4,1)
		
		plotTitles = [
					'Wheel -1',
					'Wheel 0 (-)',
					'Wheel 0 (+)',
					'Wheel +1',
					]
		
		for i in range(0,4):
			cTogether.cd(i+1).SetLogy()
			resHo[i].SetTitle(plotTitles[i] + ';E_{Rec} / GeV;fraction of MIP peak')
			#resHo[i].GetXaxis().SetRangeUser(-1,6)
			maxBin = resHoMatched[i].GetMaximumBin()#resHo[i].FindBin()
			resHo[i].Scale(1/resHo[i].GetBinContent(maxBin))
			resHo[i].SetStats(0)
			resHo[i].Draw()
			setupAxes(resHo[i])
			#resHo[i].GetYaxis().SetRangeUser(4e-3,2)
			resHoMatched[i].Scale(1/resHoMatched[i].GetBinContent(maxBin))
			resHoMatched[i].Draw('same')
		cTogether.Update()
		cTogether.SaveAs('plots/energyPerWheelTogether.root')

		return cTogether,resHo, resHoMatched
Ejemplo n.º 10
0
def plotGroomed( obs="grthrust", filenames=[ "sjm136_test.root" ], ecm="136", logy=1, canv=None ):
    thplotoptions= { "xmin": 0.0, "xmax": 0.5, "ymin": 0.005, "ymax": 50.0, "markerStyle": 20, "markerSize": 0.5, "title": "groomed Thrust", "xlabel": "1-T_{gr}", "ylabel": "1/\sigma d\sigma/d(1-T_{gr})", "logy":logy }
    cpplotoptions= { "xmin": 0.0, "xmax": 1.0, "ymin": 0.03, "ymax": 30.0, "markerStyle": 20, "markerSize": 0.5, "title": "groomed C-parameter", "xlabel": "C_{gr}", "ylabel": "1/\sigma d\sigma/d(C_{gr})", "logy":logy }
    plotopts= { "grthrust": thplotoptions, "grcpar": cpplotoptions }
    if canv == None:
        canv= TCanvas( "canv", obs+" "+ecm, 1200, 800 )
    icanv= 0
    for beta in [ "0.0", "1.0" ]:
        for zcut in [ "0.05", "0.10", "0.15" ]:
            icanv= icanv+1
            canv.cd( icanv )
            gPad.SetLeftMargin( 0.15 )
            gPad.SetRightMargin( 0.025 )
            key= obs + "_" + beta + "_" + zcut
            print key
            aogr= createCombineAnalysisObservables( filenames, key )
            aogr.plot( plotopts[obs] )
            tl= TLegend( 0.4, 0.8, 0.85, 0.85 )
            tl.SetTextSize( 0.05 )
            tl.SetBorderSize( 0 )
            tl.AddEntry( key, "OPAL "+ecm+" GeV", "ep" )
            tl.Draw( "same" )
            txt= TLatex( 0.6, 0.7, "#beta="+beta+ " z_{cut}="+zcut )
            txt.SetNDC( True )
            txt.SetTextSize( 0.035 )
            txt.Draw()            
    return
Ejemplo n.º 11
0
def plotMM():
	NMM=4
	hmms=[[],[]]

	for idt in range(DTYPS):
		# hmms[idt].append(f[idt].top.hmmppippimVw.ProjectionY("0",0,-1,"e"))
		# hmms[idt].append(f[idt].top.hmmppimVw.ProjectionY("1",0,-1,"e"))
		# hmms[idt].append(f[idt].top.hmmppipVw.ProjectionY("2",0,-1,"e"))
		# hmms[idt].append(f[idt].top.hmmpippimVw.ProjectionY("3",0,-1,"e"))
		# hmms[idt].append(f[idt].Get("/top/hmmppippimVw"))#.ProjectionY())
		# hmms[idt].append(f[idt].Get("/top/hmmppimVw"))#.ProjectionY())
		# hmms[idt].append(f[idt].Get("/top/hmmppipVw"))#.ProjectionY())
		# hmms[idt].append(f[idt].Get("/top/hmmpippimVw"))#.ProjectionY())
		hmms[idt].append(f[idt].Get("/top/hmmppippimVw").ProjectionY('hmmppippim_%s'%DTYPS_NAME[idt]))
		hmms[idt].append(f[idt].Get("/top/hmmppimVw").ProjectionY('hmmppim_%s'%DTYPS_NAME[idt]))
		hmms[idt].append(f[idt].Get("/top/hmmppipVw").ProjectionY('hmmppip_%s'%DTYPS_NAME[idt]))
		hmms[idt].append(f[idt].Get("/top/hmmpippimVw").ProjectionY('hmmpippim_%s'%DTYPS_NAME[idt]))

	cmm = TCanvas()
	cmm.Divide(2,2)
	for imm in range(NMM):
		cmm.cd(imm+1)
		# hmms[EXP][imm].SetLineColor(gROOT.ProcessLine("kBlue"))
		# hmms[EXP][imm].DrawNormalized("",10000)
		hmms[SIM][imm].SetLineColor(gROOT.ProcessLine("kRed"))
		hmms[SIM][imm].DrawNormalized("",10000)
		hmms[EXP][imm].SetLineColor(gROOT.ProcessLine("kBlue"))
		hmms[EXP][imm].DrawNormalized("sames",10000)
def compareShapes(histograms=[], histogramlables=[], styles=[], maxfactor = 1.3):
    leg = TLegend(0.6, 0.7, 0.94, 0.92);
    leg.SetBorderSize(0);
    leg.SetLineStyle(0);
    leg.SetTextFont(42);
    leg.SetFillStyle(0);
    AddLegendEntry = leg.AddEntry 
    
    c = TCanvas("compareShapes", 'compareShapes', defaultCanvasWidth, defaultCanvasHeight)
    c.cd()

    for hist, label, style in zip(histograms,histogramlables,styles):
        hist.Sumw2()
        hist = normalise(hist)
        hist.SetLineColor(style['color'])
        hist.SetLineWidth(4)
        
        AddLegendEntry(hist, label, "f")
        
    index = 0
    maximum = getMax(histograms)
    for hist in histograms:
        if index == 0:
            hist.GetYaxis().SetRangeUser(0, maximum*maxfactor)
            hist.Draw('histe')
        else:
            hist.Draw('histe same')
        index += 1
    
    return c, leg
    def GetContour(self, histo):
        ctemp = TCanvas('temp' , 'tmp canvas' , 800 , 600 )
        ctemp.cd()
        
        histo.Draw('CONT Z LIST')
        ctemp.Update()
        conts = gROOT.GetListOfSpecials().FindObject("contours")

        ret = TMultiGraph()

        if conts.GetSize() == 0: 
            ctemp.Close()
            return ret
        if conts.At(0).GetSize() == 0:
            ctemp.Close()
            return ret

        for ggid in range(0,conts.At(0).GetSize()) :
            graph = conts.At(0).At(ggid).Clone( histo.GetName() + "_Con1Graph_%d" % (ggid) )
            graph.SetTitle( histo.GetTitle() )

            graph.SetLineWidth( histo.GetLineWidth() )
            graph.SetLineColor( histo.GetLineColor() )
            graph.SetLineStyle( histo.GetLineStyle() )

            graph.Write()
            ret.Add(graph)

        ctemp.Close()
        return ret
Ejemplo n.º 14
0
class MyHistograms:
    def __init__(self, name, title, bins = 100, min = 0, max = 1000):
        self.name = name
        self.h1 = TH1F('h1_'+name, title, bins,min,max)
        self.h2 = TH1F('h2_'+name, title, bins,min,max)
        self.h2 = TH1F('h3_'+name, title, bins,min,max)
        self.canMet = TCanvas('canMet'+name, 'canMet'+name)
        self.canEff = TCanvas('canEff'+name, 'canEff'+name)
        self.canMet.SetLogy()
        self.canEff.SetLogy()
        self.h1.SetLineWidth(2)        
    def computeEff(self):
        self.eff = self.h2.Clone( 'eff_'+ self.name)
        self.eff.GetYaxis().SetTitle('efficiency')
        self.eff.Divide( self.h1 )
        return self.eff
    def setUpLegend(self, caption):
        self.legend = TLegend(0.5,0.5,0.85,0.8)
        self.legend.AddEntry(histos.h1,'all events')
        self.legend.AddEntry(histos.h2,caption)
    def draw(self):
        self.canMet.cd()
        self.h1.Draw()
        self.h2.Draw('same')
        if self.legend != None:
            self.legend.Draw()
        self.canMet.SaveAs(self.canMet.GetName()+'.png')
        self.canEff.cd()
        self.eff.Draw()
        self.canEff.SaveAs(self.canEff.GetName()+'.png')
Ejemplo n.º 15
0
def makeTwoScalesGraph(file):
    print(file)
    ch1 = OPData.fromPath('../data/part3/%s' % file, 1)
    ch2 = OPData.fromPath('../data/part3/%s' % file, 2)

    print('make canvas + pad')
    c = TCanvas('c-%s' % file, '', 1280, 720)
    pad = TPad('pad-%s' % file, '', 0, 0, 1, 1)
    pad.Draw()
    pad.cd()

    print('frame')
    frame = pad.DrawFrame(0, min(ch1.getY()) * 1.1, 0.051, max(ch1.getY()) * 1.1)
    frame.SetXTitle('Zeit t / s')
    frame.GetXaxis().CenterTitle()
    frame.SetYTitle('Spannung Spule 2: U_{2} / V')
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetLabelColor(4)
    frame.GetYaxis().SetTitleColor(4)

    print('g1')
    g1 = ch1.makeGraph('g1-%s' % file)
    prepareGraph(g1)
    g1.Draw('PX')

    print('overlay')
    c.cd()
    overlay = TPad('overlay-%s' % file, '', 0, 0, 1, 1)
    overlay.SetFillStyle(4000)  # transparent
    overlay.SetFillColor(0)  # white
    overlay.SetFrameFillStyle(4000)  # transparent
    overlay.Draw()
    overlay.cd()

    print('g2')
    g2 = ch2.makeGraph('g2-%s' % file)
    prepareGraph(g2, 2)
    g2ymin = min(ch2.getY())
    xmin = pad.GetUxmin()
    xmax = pad.GetUxmax()
    ymin = 1.1 * g2ymin
    ymax = abs(ymin)
    if file == '07.tab':  # same scale like 06.tab
        ymin, ymax = -0.07128, 0.07128
    oframe = overlay.DrawFrame(xmin, ymin, xmax, ymax)
    oframe.GetXaxis().SetLabelOffset(99)
    oframe.GetYaxis().SetLabelOffset(99)
    oframe.GetYaxis().SetTickLength(0)
    g2.Draw('PX')

    print('axis')
    axis = TGaxis(xmax, ymin, xmax, ymax, ymin, ymax, 510, "+L")
    axis.SetTitle('Spannung Photodiode: U_{ph} / V')
    axis.CenterTitle()
    axis.SetTitleOffset(1.2)
    axis.Draw()

    print('print')
    c.Update()
    c.Print('../img/part3/%s.pdf' % file[:-4], 'pdf')
Ejemplo n.º 16
0
 def plotHistNorm2(self,fname,name1,name2,logy=False):
    cnv = TCanvas(name1,"",600,600)
    cnv.Draw()
    cnv.cd()
    if(logy): cnv.SetLogy()
    self.histos[name1].SetMinimum(0)
    self.histos[name2].SetMinimum(0)
    int1 = self.histos[name1].Integral()
    max1 = self.histos[name1].GetMaximum()
    int2 = self.histos[name2].Integral()
    max2 = self.histos[name2].GetMaximum()
    if(max2/int2>max1/int1):
       self.histos[name2].DrawNormalized()
       self.histos[name1].DrawNormalized("same")
    else:
       self.histos[name1].DrawNormalized()
       self.histos[name2].DrawNormalized("same")
    leg = TLegend(0.5,0.60,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 (OTF)", "");
    leg.AddEntry(0, "#it{pp}#rightarrow#it{t}#bar{#it{t}}#rightarrow#mu+jets", "");
    leg.AddEntry(0, "Resolved selection", "");
    leg.AddEntry(self.histos[name1],"gg production","ple");
    leg.AddEntry(self.histos[name2],"q#bar{q} production","ple");
    leg.Draw("same")
    cnv.Update()
    cnv.RedrawAxis()
    cnv.SaveAs(fname)
Ejemplo n.º 17
0
 def plotHist2(self,fname,name1,name2,logy=False):
    cnv = TCanvas(name1,"",600,600)
    cnv.Draw()
    cnv.cd()
    if(logy): cnv.SetLogy()
    self.histos[name1].SetMinimum(0)
    self.histos[name2].SetMinimum(0)
    if(self.histos[name2].GetMaximum()>self.histos[name1].GetMaximum()): self.histos[name1].SetMaximum(self.histos[name2].GetMaximum()*1.2)
    else:                                                      self.histos[name1].SetMaximum(self.histos[name1].GetMaximum()*1.2)
    self.histos[name1].Draw()
    self.histos[name2].Draw("same")
    leg = TLegend(0.5,0.60,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 (OTF)", "");
    leg.AddEntry(0, "#it{gg}#rightarrow#it{t}#bar{#it{t}}#rightarrow#mu+jets", "");
    leg.AddEntry(0, "Resolved selection", "");
    leg.AddEntry(self.histos[name2],"Hard Process tops","ple");
    leg.AddEntry(self.histos[name1],"Reconstructed tops","ple");
    leg.Draw("same")
    cnv.Update()
    cnv.RedrawAxis()
    cnv.SaveAs(fname)
Ejemplo n.º 18
0
def makePlot(tasks):
    da = TDatime(2011,01,01,12,00,00);
    gStyle.SetTimeOffset(da.Convert());
  
    ct = TCanvas("ct","Time on axis");

    ndays = 390
    toodledo = TH1F("toodledo","toodledo",ndays,0.,ndays*86400);
    for i in range(1,toodledo.GetNbinsX()+1):
        try:
            num = tasks[i]
        except:
            num = 0
        toodledo.SetBinContent(i,num);
        
    ct.cd(2);
    toodledo.SetStats(0)
    toodledo.GetXaxis().SetLabelSize(0.04);
    toodledo.GetXaxis().SetTimeDisplay(1);
    toodledo.GetXaxis().SetNdivisions(5);
    toodledo.GetXaxis().SetTimeFormat("%d\/%m\/%y");
    toodledo.Draw();
    ct.Modified()
    ct.Update()
    return ct, toodledo
Ejemplo n.º 19
0
class PadService:
    def __init__(self, name, title, nPlots):
        if nPlots == 1:
            self.nPadsX = 1
            self.nPadsY = 1
            self.width = 600
            self.height = 1.0 * self.width
        elif nPlots == 2:
            self.nPadsX = 1
            self.nPadsY = 2
            self.height = 600
            self.width = 0.55*self.height;
        elif nPlots > 2 and nPlots < 5:
            self.nPadsX = 2
            self.nPadsY = 2
            self.width = 600
            self.height = 0.8 * self.width;
        elif nPlots > 4 and nPlots < 7:
            self.nPadsX = 2
            self.nPadsY = 3
            self.height = 800
            self.width = 0.7 *  self.height;
        elif nPlots > 6 and nPlots < 9:
            self.nPadsX = 2
            self.nPadsY = 4
            self.height = 800
            self.width = 0.6 *  self.height;
        else:
            self.nPadsX = 3
            self.nPadsY = 4
            self.height = 800
            self.width = 0.8 *  self.height;
            
            
        self.last = None
        self.index = 0
        self.count = 0
        self.name = name
        self.title = title
 
    def Next(self):
        if not self.last:
            self.count += 1
            name = '%s_%d' % (self.name, self.count)
            self.last = TCanvas(name.__str__(), self.title.__str__(), int(self.width), int(self.height))
            self.last.SetBorderSize(2);
            self.last.SetFrameFillColor(0);
            self.last.SetHighLightColor(0);
            self.last.Divide(self.nPadsX, self.nPadsY);
            self.index = 0;
            self.count+=1
        self.index += 1
        self.last.cd(self.index);
        #prevent override
        if self.index > self.nPadsX * self.nPadsY:
            print "EERER"
            self.last = None
        else:
            pad = self.last.GetPad(self.index)
            return pad
Ejemplo n.º 20
0
	def plotAverageEMaxAroundL1(self):
		canvas = TCanvas('canvasAverageEMax','Average EMax',1200,1200)
		canvas.cd().SetLogz()
		
		hSum = self.fileHandler.getHistogram('hoMuonAnalyzer/deltaEtaDeltaPhiEnergy/averageEMaxAroundPoint' + self.key + '_2dSummedWeights')
		hCounter = self.fileHandler.getHistogram('hoMuonAnalyzer/deltaEtaDeltaPhiEnergy/averageEMaxAroundPoint' + self.key + '_2dCounter')
		
		hSum = setupEAvplot(hSum, hCounter,same=True,limitForAll=0.3)
		hSum.SetTitle('Mean E_{Max} in HO tiles around L1 direction')
		hSum.SetMaximum(2)
		hSum.Draw('colz')
		setupEAvplot(hCounter,same=True,limitForAll=0.3).Draw('same,text')
	
		label = getLabelCmsPrivateSimulation()
		label.Draw()
		
		canvas.Update()		
				
		setupPalette(hSum)
		
		canvas.Update()
		self.storeCanvas(canvas, 'averageEmax')
		hCounter.SaveAs('histogramEMaxCounter.root')
		
		return canvas,hSum,label,hCounter
Ejemplo n.º 21
0
def make_page(drawables, name="plots", title="plots", landscape=False, dpi=96, margin=2, split=(2,3), format="pdf", log=False):
    inch_per_cm = 0.3937
    wx, wy = (21 - 2*margin)*inch_per_cm*dpi, (29.7 - 2*margin)*inch_per_cm*dpi
    sx, sy = split
    if landscape:
        wx, wy = wy, wx
        sx, sy = sy, sx
    wx, wy = int(wx), int(wy)

    saver = []
    n_per_page = sx*sy
    pages = int(ceil(len(drawables)*1.0/n_per_page))
    for page in range(1, pages+1):
        on_page = drawables[(page-1)*n_per_page:page*n_per_page]
        c = TCanvas("%s_p%i" % (name, page), "%s (Page %i/%i)" % (title, page, pages), wx, wy)

        c.SetRightMargin(wx/2.0)
        c.Divide(sx, sy)
        for i in range(len(on_page)):
            c.cd(i+1)
            if log:
                c.SetLogy(i+1)
            saver.append(on_page[i]())
            if log:
                gPad.SetLogy(True)
                c.SetLogy(i+1)
        c.cd()
        c.SaveAs("%s_%i.%s" % (name, page, format)) 
Ejemplo n.º 22
0
def draw_hist(BCALhist):
	
	c1 = TCanvas('c1','c1',600,900) # Creates the canvas to draw the histogram to.
	c1.Divide(1,2)		# separates the canvas into two for two plots
	c1.SetGrid()		# Adds grid lines to canvas.

	#hithist.LabelsDeflate("X") 	# Trim the number of bins to match the number of active labels - Took ages to find this, didn't work without.
	c1.cd(1)						# selects first canvas
	BCALhist.Draw("COLZ") 			# Draws the histogram to the canvas, sets draw style.
	BCALhist.SetStats(0)			# removes stats legend
	BCALhist.SetXTitle("X")			# X axis label
	BCALhist.SetYTitle("Y")			# Y axis label
	c1.Update()					# Makes the canvas show the histogram.

	c1.cd(2)						# selects second canvas
	BCALhist.Draw("SURF1") 			# Draws the histogram to the canvas.
	BCALhist.SetStats(0)
	BCALhist.SetXTitle("X")
	BCALhist.SetYTitle("Y")
	c1.Update()					# Makes the canvas show the histogram.
    
	img = ROOT.TImage.Create()				# creates image
	img.FromPad(c1)							# takes it from canvas
	img.WriteImage("BCALsurf-z.png")	# Saves it as png file with this name the the input file directory.

	return c1 # returns the canvas with histograms drawn to it
Ejemplo n.º 23
0
    def drawGraph(self,g,figDir="",SetLogx=False,SetLogy=False,option='APL'):
        '''
        output graph to file
        '''
        title = g.GetTitle()
        name  = g.GetName()
        if SetLogx: name += '_logx'
        if SetLogy: name += '_logy'

        pdf   = os.path.join( figDir,  name + '.pdf')
    
        xsize,ysize = 1100,850 # landscape style
        noPopUp = True
        if noPopUp : gROOT.ProcessLine("gROOT->SetBatch()")
        canvas = TCanvas(pdf,title,xsize,ysize)

        
        g.Draw(option)

        if SetLogy: canvas.SetLogy(1)
        if SetLogx: canvas.SetLogx(1)
    
        canvas.Draw()
        canvas.SetGrid(1)
        canvas.SetTicks(1)
        canvas.cd()
        canvas.Modified()
        canvas.Update()
        canvas.Print(pdf,'pdf')
        return
Ejemplo n.º 24
0
    def drawFit(self,h,figdir='',SetLogy=False,SetLogx=False,extraName=None):
        '''
        draw histogram with fit parameters
        '''
        name = h.GetName()
        if extraName is not None: name += '_' + extraName
        title = h.GetTitle()
        if SetLogx: name += '_logx'
        if SetLogy: name += '_logy'
        pdf = os.path.join( figdir ,  name + '.pdf' )
        ps  = os.path.join( figdir , name + '.ps' )
        xsize,ysize = 1100,850 # landscape style
        noPopUp = True
        if noPopUp : gROOT.ProcessLine("gROOT->SetBatch()")
        canvas = TCanvas(pdf,title,xsize,ysize)
        
        gStyle.SetOptFit(1111)
        h.Draw()
        if SetLogy: canvas.SetLogy(1)
        if SetLogx: canvas.SetLogx(1)
        
        canvas.Draw()
        canvas.SetGrid(1)
        canvas.SetTicks(1)
        canvas.cd()
        canvas.Modified()
        canvas.Update()
        
        canvas.Print(ps,'Landscape')
        os.system('ps2pdf ' + ps + ' ' + pdf)
        if os.path.exists(pdf): os.system('rm ' + ps)

        return
Ejemplo n.º 25
0
	def plotPtAndPhiOfWrongBxId(self):
		#Prepare canvas
		canvas = TCanvas("canvasPtPhiBxWrong","PtPhiBxWrong",1200,1200)
		canvas.cd().Draw()
		#prepare histogram
		hist = self.fileHandler.getHistogram("etaPhi/3D/BxWrongGen_EtaPhiPt")
	
		stack = THStack(hist,"zy","2dStack","",-1,-1,-1,-1,"zy","")
	
		#Create new histogram and add the histograms from the stack
		histNew = TH2D("histPtPhiBxWrong","p_{T} vs. #phi distribution for wrong BX ID;#phi;p_{T} / 5 GeV;#",80,-3.2,3.2,40,0,200)
		histNew.GetYaxis().SetTitleOffset(1.2)
		for i in stack.GetHists():
			histNew.Add(i)
	
		gStyle.SetPalette(1)
		histNew.SetStats(0)
		setupAxes(histNew)
		histNew.Draw('COLZ')
		canvas.Update()
	
		palette = histNew.FindObject("palette")
		palette.SetX1NDC(0.9)
		palette.SetX2NDC(0.92)
		#add label
		label = getLabelCmsPrivateSimulation()
		label.Draw()
		
		canvas.Update()
		self.storeCanvas(canvas,"bxWrongPtPhi")
		return canvas,hist,stack,histNew,label
def drawMCMass( tree, list ):
	'''
	draws different simulated mass distributions
	list: list containing integers from 0-18

	returns: void ( histgram will be saved )
	'''
	masses = weightToMass()
	from ROOT import TCanvas,TLegend
	can = TCanvas()
	can.cd()
	can.SetCanvasSize(1400, 800)
	leg = TLegend(.8,.6,.95,.9)
	leg.SetBorderSize(0)
	leg.SetFillColor(0)
	leg.SetShadowColor(0)
	histlist = []
	niceColors = [1,2,4,6,9,12,46]
	for colorindex, massindex in enumerate( list ):
		histo = createHistoFromTree(tree, "mc_w_m", "weight[{}]".format(massindex), 100, 75, 85)
		histo.SetTitle(";M_{W} [GeV];Eintr#ddot{a}ge")
		histo.SetLineColor( niceColors[colorindex] )
		histo.SetLineWidth(3)
		if histlist == []:
			histo.Draw("hist")
		else:
			histo.Draw("hist,same")
		histlist.append( histo )
		leg.AddEntry(histo, "{0} GeV".format(masses[massindex]), "l")
	leg.Draw()
	can.SaveAs('diffenentMcMasses.pdf')
	can.Close()
Ejemplo n.º 27
0
def splot( pdf, sdata ) :
    # switch off all yields, except current one
    from contextlib import contextmanager
    @contextmanager
    def __select_component( i, yields ):
        orig = dict( (j,j.getVal()) for j in yields )
        [ j.setVal(0) for j in orig.iterkeys() if j!=i ]
        try     : yield
        finally : [ j.setVal(v) for (j,v) in orig.iteritems() ]
    from ROOT import TCanvas, kDashed, kRed, kGreen, kBlue, kBlack
    canvas = TCanvas(pdf.GetName() + '_splot')
    obs = [ o for o in pdf.Observables() if hasattr(o,'frame') and o not in sdata.usedObservables() ]
    for (p,o) in zip( canvas.pads(len(obs)), obs ) :
        # select yields
        _yields = [ y for y in pdf.Parameters() if y.getAttribute('Yield') ]
        # loop over components
        for (pp,i) in zip( p.pads(1,len(_yields)), _yields ) :
            # switch off all yields, except current one
            with __select_component( i, _yields ) :
                # plot both weighed data and PDF
                # TODO: add the same color coding as above...
                c_name = i.GetName()[2:]
                c_opts = { 'signal'             : dict( LineColor = kGreen )
                         , 'psi_background'     : dict( LineColor = kRed )
                         , 'cmb_background'     : dict( LineColor = kBlue )
                         }
                from P2VV.Utilities.Plotting import plot
                plot( pp, o, sdata.data( c_name ), pdf, pdfOpts = c_opts[c_name] if c_name in c_opts else {})
    return canvas
Ejemplo n.º 28
0
def plotHitTruthPositions(topPlotPath,topPlotTitle,bottomPlotPath,bottomPlotTitle) :

  #Create a fresh canvas
  c = TCanvas("c","",1200,800)
  c.Divide(1,2)

  #First hit plot
  h_primaryPositronHits = rh.getFromFile(rootFile,topPlotPath)
  c.cd(1)
  h_primaryPositronHits.SetTitle(topPlotTitle)
  #h_primaryPositronHits.GetYaxis().SetTitleOffset(1.5)
  h_primaryPositronHits.SetStats(False)
  h_primaryPositronHits.GetYaxis().SetRangeUser(-200.,400.)
  h_primaryPositronHits.Draw("COLZ")

  #Second hit plot
  h_secondaryHits = rh.getFromFile(rootFile,bottomPlotPath)
  c.cd(2)
  h_secondaryHits.SetTitle(bottomPlotTitle)
  #h_secondaryHits.GetYaxis().SetTitleOffset(1.5)
  h_secondaryHits.SetStats(False)
  h_secondaryHits.GetYaxis().SetRangeUser(-200.,400.)
  h_secondaryHits.Draw("COLZ")

  raw_input("Press Enter to continue...")
Ejemplo n.º 29
0
	def plotEMaxCounts(self):
		canvas = TCanvas('canvasEmaxcounts','E max counts',1200,1200)
		canvas.cd().SetLogz()
			
		hCounter = self.fileHandler.getHistogram('hoMuonAnalyzer/deltaEtaDeltaPhiEnergy/averageEMaxAroundPointL1MuonPresent_2dCounter')
		#hSum = setupEAvplot(hSum, hCounter,same=True,limitForAll=0.3)
		hCounter.SetTitle('# of E_{Max} in HO tiles around L1 direction;#Delta#eta;#Delta#phi;# Entries')
		hCounter.SetStats(0)
		hCounter.GetXaxis().SetRangeUser(-.5,.5)
		hCounter.GetYaxis().SetRangeUser(-.5,.5)
		hCounter.Draw('colz')
		label = self.drawLabel()
		canvas.Update()		
		setupPalette(hCounter)
		canvas.Update()
		#boxes = drawHoBoxes(canvas)
		self.storeCanvas(canvas,'eMaxCounts')
		
		#Calculate fraction in 3x3 grid
		integralCentral = hCounter.Integral(hCounter.GetXaxis().FindBin(-.0435),hCounter.GetXaxis().FindBin(.0435),
									hCounter.GetYaxis().FindBin(-.0435),hCounter.GetYaxis().FindBin(.0435))
		integral3x3 = hCounter.Integral(hCounter.GetXaxis().FindBin(-.1305),hCounter.GetXaxis().FindBin(.1305),
									hCounter.GetYaxis().FindBin(-.1305),hCounter.GetYaxis().FindBin(.1305))
		integralTotal = hCounter.Integral()
		
		self.output(80*'#')
		self.output('%20s:%5.2f%% +/- %5.2f%%' % ('Central Fraction',calcPercent(integralCentral,integralTotal),
												calcSigma(integralCentral,integralTotal)*100))
		self.output('%20s:%5.2f%% +/- %5.2f%%' % ('3x3 Fraction',calcPercent(integral3x3,integralTotal),
												calcSigma(integral3x3,integralTotal)*100))
		
		self.output(80*'#')
		return canvas,label,hCounter
Ejemplo n.º 30
0
def plotQualityCodesStacked(gridSize):
	gridString = gridSizeDict.get(gridSize)
	c = TCanvas('cQualityCodes' + gridString + 'Stacked','Stacked QC ' + gridString,600,0,800,600)
	c.SetLogy()
	c.cd().SetBottomMargin(0.15)
	c.cd().SetRightMargin(0.20)
	qualityCodes = fileHandler.getHistogram('hoMuonAnalyzer/multiplicity/L1MuonQualityCodes' + gridString + '_Multiplicity')
	qualityCodesFail = fileHandler.getHistogram('hoMuonAnalyzer/multiplicity/L1MuonQualityCodes' + gridString + 'Fail_Multiplicity')
	
	countQualityCodes = fileHandler.getHistogram('hoMuonAnalyzer/multiplicity/L1MuonAllQualityCodes_Multiplicity')
	countQualityCodesTruth = fileHandler.getHistogram('hoMuonAnalyzer/multiplicity/L1MuonTruthAllQualityCodes_Multiplicity')
	
	print
	cli.output('Sanity check for quality code counts')
	for i in range(1,8):
		nTotalHistogram = countQualityCodes.GetBinContent(countQualityCodes.FindBin(i))
		nFail = qualityCodesFail.GetBinContent(qualityCodesFail.FindBin(i))
		nPass = qualityCodes.GetBinContent(qualityCodes.FindBin(i))
		nSummed = nFail + nPass
		print
		cli.output('NTotal: %d\t\tNSummed: %d' % (nTotalHistogram,nSummed))
		cli.output('Sanity check: %s'% (CliColors.OKBLUE + 'OK' + CliColors.ENDC if nTotalHistogram == nSummed else CliColors.FAIL + 'FAIL' + CliColors.ENDC) )
		print
		if nTotalHistogram:
			qualityCodes.SetBinContent(qualityCodes.FindBin(i),nPass/float(nTotalHistogram))
			qualityCodesFail.SetBinContent(qualityCodesFail.FindBin(i),nFail/float(nTotalHistogram))
	
	stack = THStack("hstack","Quality Codes in matching to HO (" + gridString + ");;rel. fraction")
	
	qualityCodes.SetLineColor(colorRwthDarkBlue)
	qualityCodes.SetFillColor(colorRwthDarkBlue)
	qualityCodes.SetFillStyle(3002)

	qualityCodesFail.SetFillColor(colorRwthMagenta)
	qualityCodesFail.SetLineColor(colorRwthMagenta)
	qualityCodesFail.SetFillStyle(3002)

	stack.Add(qualityCodes)
	stack.Add(qualityCodesFail)
	
	stack.Draw()
	stack.GetXaxis().SetRangeUser(0,8)
		#Label the bins with the meaning of the quality code
	for i in range(1,8):
		stack.GetXaxis().SetBinLabel(stack.GetXaxis().FindBin(i),qualityCodeDict.get(i))
		
	legend = TLegend(0.82,0.75,0.99,0.9)
	legend.AddEntry(qualityCodes,"Passed","f")
	legend.AddEntry(qualityCodesFail,"Failed","f")
	legend.Draw()
	
	label = drawLabelCmsPrivateSimulation(x1ndc=0.5,y1ndc=0.9,x2ndc=0.8,y2ndc=0.93)
	
	setupAxes(stack)
		
	c.Update()
	
	c.SaveAs('plots/efficiency/qualityCodesStacked' + gridString + '.pdf')
	
	return stack,c,qualityCodes,qualityCodesFail,legend,label
Ejemplo n.º 31
0
        h_El_dataSS_a = ScaleHisto(h_El_dataSS_a, 1)
        h_q2_dataSS_a = ScaleHisto(h_q2_dataSS_a, 1)
        h_mmiss_dataSS_a = ScaleHisto(h_mmiss_dataSS_a, 1)
        h_LbM_dataSS_a = ScaleHisto(h_LbM_dataSS_a, 1)

    h_El_dataSS_b = ScaleHisto(h_El_dataSS_b, 1)
    h_q2_dataSS_b = ScaleHisto(h_q2_dataSS_b, 1)
    h_mmiss_dataSS_b = ScaleHisto(h_mmiss_dataSS_b, 1)

    h_El_dataSS_f = ScaleHisto(h_El_dataSS_f, 1)
    h_q2_dataSS_f = ScaleHisto(h_q2_dataSS_f, 1)
    h_mmiss_dataSS_f = ScaleHisto(h_mmiss_dataSS_f, 1)
    h_LbM_dataSS_f = ScaleHisto(h_LbM_dataSS_f, 1)

    #plot the full range kinematical templates superimposed
    c0 = TCanvas('c0', 'full range', 1500, 500)
    c0.Divide(3, 1)
    c0.cd(1)
    h_El_data_f.SetMarkerStyle(20)
    h_El_data_f.SetMarkerSize(1)
    h_El_data_f.Draw('PE0')
    h_El_dataSS_f.SetLineColor(r.kRed)
    h_El_dataSS_f.Draw('hist sames')
    legend = r.TLegend(0.6, 0.75, 0.9, 0.9)
    legend.AddEntry(h_El_dataSS_f, 'Data SS', "l")
    legend.AddEntry(h_El_data_f, 'Data OS', "pl")
    legend.Draw()
    c0.cd(2)
    h_q2_data_f.SetMarkerStyle(20)
    h_q2_data_f.SetMarkerSize(1)
    h_q2_data_f.Draw('PE0')
Ejemplo n.º 32
0
def SignificanceOpt(Lumi_scalefactor = 1.00, plot = "n",speak="") :
	if speak!='mute': print("------- Significance Optimization -------")
	
	# Prepare histograms
	if speak!='mute': print(" Info: Mass distribution in the 4 lepton channel")
	
	h_sig = GetMassDistribution(125, Lumi_scalefactor)
	h_bgr = GetMassDistribution(1, Lumi_scalefactor)
	h_data = GetMassDistribution(2, Lumi_scalefactor)


	# Compute significance for various mass windows
	# Define histograms for mass windows to try
	h_masswindow = TH1D("h_masswindow", "", 250, 0.,25.) #full width \in [0,25]
	h_masswindow_exp = TH1D("h_masswindow_expected", "", 250, 0.,25.)
	h_masswindow_obs = TH1D("h_masswindow_observed", "", 250, 0.,25.)	

	# Loop over various mass windows
	for i in range( 0,h_masswindow.GetNbinsX() ):
		masswindow_fullwidth = h_masswindow.GetBinCenter(i)

		if speak!='mute': print("	Trying as mass window: ",masswindow_fullwidth," GeV\n")
		
		# determine events in the mass window for each event type
		Ndata = h_data.Integral( h_data.FindBin(125-0.5*masswindow_fullwidth),h_data.FindBin(125+0.5*masswindow_fullwidth) )
		Nbgr =  h_bgr.Integral( h_bgr.FindBin(125-0.5*masswindow_fullwidth),h_bgr.FindBin(125+0.5*masswindow_fullwidth) )
		Nsig = h_sig.Integral( h_sig.FindBin(125-0.5*masswindow_fullwidth),h_sig.FindBin(125+0.5*masswindow_fullwidth) )

		if speak!='mute': print("Number of events: ", Nsig, "\n")
		
		if( (Nbgr+Nsig)<1 ): continue 

		# Computing EXPECTED significance
		pvalue_exp = IntegratePoissonFromRight(Nbgr, Nsig+Nbgr)
		significance_exp = ROOT.Math.gaussian_quantile_c(pvalue_exp,1)
		h_masswindow_exp.SetBinContent(i, significance_exp)

		# Computing OBSERVED significance
		pvalue_obs = IntegratePoissonFromRight(Nbgr, Ndata)
		significance_obs = ROOT.Math.gaussian_quantile_c(pvalue_obs,1)
		h_masswindow_obs.SetBinContent(i, significance_obs)
		if(pvalue_obs<0): continue

		
	# Getting maximum
	MaxBin_exp = h_masswindow_exp.GetMaximumBin()
	OptimumSign_exp = h_masswindow_exp.GetBinContent(MaxBin_exp)
	OptMassWindow_exp = h_masswindow_exp.GetXaxis().GetBinCenter(MaxBin_exp)

	if speak!='mute':
		print("Luminosity factor: ", Lumi_scalefactor,"\n")
		print("EXPECTED significance - Optimal mass window\n")
		print("	Expected significance: ",OptimumSign_exp,"\n")
		print("	Mass window: ", OptMassWindow_exp, "\n")
		
	if( abs(Lumi_scalefactor-1.0)<0.01 ):
	
		MaxBin_obs = h_masswindow_obs.GetMaximumBin()
		OptimumSign_obs = h_masswindow_obs.GetBinContent(MaxBin_obs)
		OptMassWindow_obs = h_masswindow_obs.GetXaxis().GetBinCenter(MaxBin_obs)

		if speak!='mute':
			print("Luminosity factor: ", Lumi_scalefactor,"\n")
			print("OBSERVED significance - Optimal mass window\n")
			print("	Observed significance: ",OptimumSign_obs,"\n")
			print("	Mass window: ", OptMassWindow_obs, "\n")

	# plot and save histograms
	if(plot == "y"):
		canvas1 = TCanvas( "canvas1","Standard Canvas",600,400);  
		canvas1.SetLeftMargin(0.125);
		canvas1.SetBottomMargin(0.125); 
		canvas1.cd(); 
	
		h_masswindow_exp.SetLineColor(1);
		h_masswindow_exp.SetLineWidth(2);
		h_masswindow_obs.SetLineColor(4);
		h_masswindow_obs.SetLineWidth(2);

		h_masswindow_exp.SetAxisRange(-1.,6.,"Y");
		h_masswindow_exp.SetStats(kFALSE)

		h_masswindow_exp.SetTitle("OPTIMAL MASS WINDOW")

		h_masswindow_exp.GetXaxis().SetTitle("mass window [GeV]")
		h_masswindow_exp.GetYaxis().SetTitle("significance Z")

		leg1 = TLegend(0.70,0.70,0.90,0.85)
		leg1.SetBorderSize(1); leg1.SetFillColor(0); #leg1.SetO
		leg1a = leg1.AddEntry(h_masswindow_exp, "expected", "l"); leg1a.SetTextSize(0.04);




		h_masswindow_exp.Draw("l");
		if( abs(Lumi_scalefactor-1.00)<0.01 ):
			h_masswindow_obs.Draw("l same");
			leg1b = leg1.AddEntry(h_masswindow_obs, "observed", "l"); leg1b.SetTextSize(0.04);

		leg1.Draw()                        

		canvas1.Print("Plots/Significance_Optimization_lumiscalefactor"+str(Lumi_scalefactor)+".pdf");

	return OptimumSign_exp;
Ejemplo n.º 33
0
    inputReconFile = TFile(str(reconFiles[i]))  #tuple files after cuts
    inputTruthFile = TFile(str(reconFiles[i + nMass]))  #truth files
    inputReconFile.Get("cut").Draw(
        "triEndZ>>histoRecon({0},{1},{2})".format(nBins, targZ, maxZ),
        "triP>0.8*{0}".format(eBeam))
    histoRecon = ROOT.gROOT.FindObject("histoRecon")
    inputTruthFile.Get("ntuple").Draw(
        "triEndZ>>histoTruth({0},{1},{2})".format(nBins, targZ, maxZ),
        "triP>0.8*{0}".format(eBeam))
    histoTruth = ROOT.gROOT.FindObject("histoTruth")
    #Write the efficiency for a given mass (row) as function of z
    for j in range(nBins):
        if (histoTruth.GetBinContent(j + 1) == 0): textfile.write(str(0))
        else:
            textfile.write(
                str(
                    histoRecon.GetBinContent(j + 1) /
                    histoTruth.GetBinContent(j + 1)) + " ")
    textfile.write("\n")

textfile.close()

#Make test plots if desired
if (makeTestPlots):
    c = TCanvas("c", "c", 1200, 900)
    c.Print(outfile + ".pdf[")

    for i in range(1, nMass - 1):
        plotTest(i, outfile + ".eff", outfile, targZ, maxZ)

    c.Print(outfile + ".pdf]")
Ejemplo n.º 34
0
def PoissonError(nObs, ErrorType, plot=""):

	# Prepare histograms
	LambdaMin = 0.
	LambdaMax = nObs + 6*np.sqrt(nObs)
	Nsteps = 1000

	h_likelihood = TH1D( "h_likelihood","",Nsteps,LambdaMin,LambdaMax )
	h_2loglik = TH1D( "h_2loglik","",Nsteps,LambdaMin,LambdaMax )
	h_pdf_full = TH1D( "h_pdf_full","",Nsteps,LambdaMin,LambdaMax )

	IntFraction =ROOT.Math.gaussian_cdf(-1,1,0)

	# loop over possible Lambda values
	for iBin in  range(1,Nsteps+1):
		Lambda=h_likelihood.GetBinCenter(iBin)

		PoissonProb = TMath.Poisson(nObs,Lambda)
		LogLikelihood = -2.*TMath.Log(PoissonProb)

		h_likelihood.Fill( Lambda,PoissonProb )
		h_2loglik.Fill( Lambda, LogLikelihood )
		h_pdf_full.Fill( Lambda, PoissonProb*1. )

	# get characteristic values
	bin_central = h_2loglik.GetMinimumBin()
	LoglikMin = h_2loglik.GetBinContent(bin_central)
	Lambda_central = h_2loglik.GetBinCenter(bin_central)

	LambdaLow = -1.
	LambdaUp = -1.


	if ErrorType=="ClassicalCentral": # Frequentist
		NobsMax = nObs+100

		for iBin in range(1,h_pdf_full.GetNbinsX()+1):
			Lambda = h_pdf_full.GetBinCenter(iBin)
			PoissonSumLow = 0.
			PoissonSumUp = 0.

			for i in range(nObs,NobsMax+1):
				PoissonSumLow += TMath.Poisson(i,Lambda)
			
			if( PoissonSumLow>IntFraction and LambdaLow<0 ):
				LambdaLow = Lambda

			for i in range(0,nObs+1):
				PoissonSumUp += TMath.Poisson(i,Lambda)

			if( PoissonSumUp<IntFraction and LambdaUp<0 ):
				LambdaUp = Lambda

		cvs = TCanvas("Standard Canvas","",600,600)

	
		cvs.Divide(1,2)

		cvs.cd(1)

		hLow = TH1D("hLow","CLASSICAL CENTRAL",1000,0,17)
		for i in range(1,hLow.GetNbinsX()+1):
			hLow.SetBinContent(i, TMath.Poisson( hLow.GetBinCenter(i),LambdaLow ))
		hLow.SetLineColor(1)
		hLow.GetXaxis().SetTitle(r"#mu")

		h_conf = hLow.Clone("h_conf")
		for i in range(1,h_conf.GetNbinsX()+1):
			if(h_conf.GetBinCenter(i)<=nObs): h_conf.SetBinContent(i, 0)
		h_conf.SetFillColorAlpha(9,0.5)
		h_conf.SetLineWidth(1)
		h_conf.SetLineColor(1)


		LowLine = TLine(LambdaLow,0,LambdaLow,hLow.GetBinContent(hLow.FindBin(LambdaLow)))

		hLow.SetStats(kFALSE)


		hLow.Draw("l")
		h_conf.Draw("l same")
		LowLine.Draw()

		text = TLatex()
		text.SetTextSize(0.5)
		text.SetTextColor(1)
		text.DrawLatex(0.5,0.8, "LOL")

		cvs.cd(2)

		hUp = TH1D("hUp","",1000,0,17)
		for i in range(1,hUp.GetNbinsX()+1):
			hUp.SetBinContent(i, TMath.Poisson( hLow.GetBinCenter(i),LambdaUp ))
		hUp.SetLineColor(1)
		hUp.GetXaxis().SetTitle(r"#mu")

		h_conf1 = hUp.Clone("h_conf")
		for i in range(1,h_conf.GetNbinsX()+1):
			if(h_conf.GetBinCenter(i)>=nObs): h_conf1.SetBinContent(i, 0)
		h_conf1.SetFillColorAlpha(9,0.5)
		h_conf1.SetLineWidth(1)
		h_conf1.SetLineColor(1)

		UpLine = TLine(LambdaUp,0,LambdaUp,hUp.GetBinContent(hUp.FindBin(LambdaUp)))

		hUp.SetStats(kFALSE)


		hUp.Draw("l")
		h_conf1.Draw("l same")
		UpLine.Draw()

		cvs.cd()

		leg1 = TLegend(0.35,0.70,0.90,0.85)
		leg1.SetBorderSize(1); leg1.SetFillColor(0);
		h_conf.SetMarkerColor(0)
		leg1a = leg1.AddEntry(h_conf, r"(#mu_{low}, #mu_{up}) = ("+str(round(LambdaLow,2))+","+str(round(LambdaUp,2))+")","p"); leg1a.SetTextSize(0.04);
		leg1.Draw()

		cvs.Print("Plots/Errors_"+ErrorType+".eps")



	if ErrorType=="LikelihoodRatio":
		for i in range(1,h_2loglik.GetNbinsX()+1):
			if (h_2loglik.GetBinCenter(i)<LoglikMin and h_2loglik.GetBinContent(i)-LoglikMin>=1.):  LambdaLow=h_2loglik.GetBinCenter(i)
			if (h_2loglik.GetBinCenter(i)>LoglikMin and h_2loglik.GetBinContent(i)-LoglikMin<=1.):  LambdaUp=h_2loglik.GetBinCenter(i)

		cvs = TCanvas("Standard Canvas","",600,400)
		cvs.cd()

		LowLine = TLine(LambdaLow,2,LambdaLow,h_2loglik.GetBinContent(h_2loglik.FindBin(LambdaLow))); LowLine.SetLineWidth(1)
		UpLine = TLine(LambdaUp,2,LambdaUp,h_2loglik.GetBinContent(h_2loglik.FindBin(LambdaUp))); UpLine.SetLineWidth(1)
		ObsLine = TLine(nObs,2,nObs,h_2loglik.GetBinContent(h_2loglik.FindBin(nObs))); ObsLine.SetLineWidth(1); ObsLine.SetLineColor(2); ObsLine.SetLineStyle(7)

		h_2loglik.SetFillColor(0)
		h_2loglik.SetStats(kFALSE)
		h_2loglik.SetTitle("LIKELIHOOD RATIO")
		h_2loglik.SetAxisRange(0.8,8,"X")
		h_2loglik.SetAxisRange(2,7,"Y")
		h_2loglik.Draw("hist lp")
		h_2loglik.GetXaxis().SetTitle(r"#mu")

		h_conf = h_2loglik.Clone("h_conf")
		for i in range(1,h_conf.GetNbinsX()+1):
			if(h_conf.GetBinCenter(i)>LambdaLow and h_conf.GetBinCenter(i)<LambdaUp): h_conf.SetBinContent(i,0)

		h_conf.SetFillColor(9)
		h_conf.Draw("hist same")

		leg1 = TLegend(0.55,0.70,0.90,0.85)
		leg1.SetBorderSize(1); leg1.SetFillColor(0);
		h_conf.SetMarkerColor(0)
		leg1a = leg1.AddEntry(h_conf, r"(#mu_{low}, #mu_{up}) = ("+str(round(LambdaLow,2))+","+str(round(LambdaUp,2))+")","p"); leg1a.SetTextSize(0.04);
		leg1.Draw()

		LowLine.Draw()
		UpLine.Draw()
		ObsLine.Draw()
		

		cvs.Print("Plots/Errors_"+ErrorType+".eps")




	if ErrorType=="BayesCentral": 
		# Work on likelihood as PDF
		Integral = h_likelihood.Integral()
		for i in range(1,h_likelihood.GetNbinsX()+1):
			h_likelihood.SetBinContent(i,h_likelihood.GetBinContent(i)/Integral)

		# Sum over bins until reached CL
		Sum_low = 0.
		Sum_up = 0.
		for i in range(1,bin_central+1):
			if Sum_low<=IntFraction:
				Sum_low += h_likelihood.GetBinContent(i)
				LambdaLow = h_likelihood.GetBinCenter(i)
		for i in range(h_likelihood.GetNbinsX(),bin_central,-1):
			if Sum_up<=IntFraction:
				Sum_up += h_likelihood.GetBinContent(i)
				LambdaUp = h_likelihood.GetBinCenter(i)

		cvs = TCanvas("Standard Canvas","",600,400)
		cvs.cd()

		LowLine = TLine(LambdaLow,0,LambdaLow,h_likelihood.GetBinContent(h_likelihood.FindBin(LambdaLow))); LowLine.SetLineWidth(1)
		UpLine = TLine(LambdaUp,0,LambdaUp,h_likelihood.GetBinContent(h_likelihood.FindBin(LambdaUp))); UpLine.SetLineWidth(1)
		ObsLine = TLine(nObs,0,nObs,h_likelihood.GetBinContent(h_2loglik.FindBin(nObs))); ObsLine.SetLineWidth(1); ObsLine.SetLineColor(2); ObsLine.SetLineStyle(7)


		h_likelihood.SetFillColor(0)
		h_likelihood.SetStats(kFALSE)
		h_likelihood.SetTitle("BAYES CENTRAL")
		#h_likelihood.SetAxisRange(0.8,8,"X")
		#h_likelihood.SetAxisRange(2,7,"Y")
		h_likelihood.Draw("hist lp")
		h_likelihood.GetXaxis().SetTitle(r"#mu")

		h_conf = h_likelihood.Clone("h_conf")
		for i in range(1,h_conf.GetNbinsX()+1):
			if(h_conf.GetBinCenter(i)>LambdaLow and h_conf.GetBinCenter(i)<LambdaUp): h_conf.SetBinContent(i,0)

		h_conf.SetFillColor(9)
		h_conf.Draw("hist same")

		leg1 = TLegend(0.55,0.70,0.90,0.85)
		leg1.SetBorderSize(1); leg1.SetFillColor(0);
		h_conf.SetMarkerColor(0)
		leg1a = leg1.AddEntry(h_conf, r"(#mu_{low}, #mu_{up}) = ("+str(round(LambdaLow,2))+","+str(round(LambdaUp,2))+")","p"); leg1a.SetTextSize(0.04);
		leg1.Draw()

		LowLine.Draw()
		UpLine.Draw()
		ObsLine.Draw()
		

		cvs.Print("Plots/Errors_"+ErrorType+".eps")


	if ErrorType=="BayesHDI":
		# Work on likelihood as PDF
		Integral = h_likelihood.Integral()
		for i in range(1,h_likelihood.GetNbinsX()+1):
			h_likelihood.SetBinContent(i,h_likelihood.GetBinContent(i)/Integral)

		Area = 0.	
		RightIndex=bin_central
		while Area<=(1-2*IntFraction):
			RightIndex+=1
			# find corresponding bin on left side
			for i in range(1,bin_central):
				if h_likelihood.GetBinContent(i)<=h_likelihood.GetBinContent(RightIndex): 
					LeftIndex=i
			Area = h_likelihood.Integral( LeftIndex,RightIndex )

		LambdaLow = h_likelihood.GetBinCenter(LeftIndex)
		LambdaUp = h_likelihood.GetBinCenter(RightIndex)

		cvs = TCanvas("Standard Canvas","",600,400)
		cvs.cd()

		LowLine = TLine(LambdaLow,0,LambdaLow,h_likelihood.GetBinContent(h_likelihood.FindBin(LambdaLow))); LowLine.SetLineWidth(1)
		UpLine = TLine(LambdaUp,0,LambdaUp,h_likelihood.GetBinContent(h_likelihood.FindBin(LambdaUp))); UpLine.SetLineWidth(1)
		ObsLine = TLine(nObs,0,nObs,h_likelihood.GetBinContent(h_2loglik.FindBin(nObs))); ObsLine.SetLineWidth(1); ObsLine.SetLineColor(2); ObsLine.SetLineStyle(7)

		h_likelihood.SetFillColor(0)
		h_likelihood.SetStats(kFALSE)
		h_likelihood.SetTitle("BAYES SHORTEST")
		h_likelihood.Draw("hist lp")
		h_likelihood.GetXaxis().SetTitle(r"#mu")

		h_conf = h_likelihood.Clone("h_conf")
		for i in range(1,h_conf.GetNbinsX()+1):
			if(h_conf.GetBinCenter(i)>LambdaLow and h_conf.GetBinCenter(i)<LambdaUp): h_conf.SetBinContent(i,0)

		h_conf.SetFillColor(9)
		h_conf.Draw("hist same")

		leg1 = TLegend(0.55,0.70,0.90,0.85)
		leg1.SetBorderSize(1); leg1.SetFillColor(0);
		h_conf.SetMarkerColor(0)
		leg1a = leg1.AddEntry(h_conf, r"(#mu_{low}, #mu_{up}) = ("+str(round(LambdaLow,2))+","+str(round(LambdaUp,2))+")","p"); leg1a.SetTextSize(0.04);
		leg1.Draw()

		LowLine.Draw()
		UpLine.Draw()
		ObsLine.Draw()
		

		cvs.Print("Plots/Errors_"+ErrorType+".eps")


	return [LambdaLow, LambdaUp]









	return
Ejemplo n.º 35
0
def MuFit(Nbins,irebin=1.):
	# Get histrograms
	h_bgr = GetMassDistribution(1)
	h_data = GetMassDistribution(2)
	h_sig = GetMassDistribution(125)

	h_bgr.Rebin(irebin)
	h_data.Rebin(irebin)
	h_sig.Rebin(irebin)

	h_sf = TH2D("scalefactor","title",Nbins,0.5,2.,Nbins,0.,5.)

	for i in range(1,h_sf.GetNbinsX()+1):
		for j in range(1,h_sf.GetNbinsY()+1):

			sf_bgr = h_sf.GetXaxis().GetBinCenter(i)
			sf_sig = h_sf.GetYaxis().GetBinCenter(j)

			# Loop over bins, compute likelihood
			loglik = 0.

			for iDataBin in range(1,h_data.GetNbinsX()+1):

				m4lepBin = h_data.GetBinCenter(iDataBin)
				NObsBin = h_data.GetBinContent(iDataBin)

				MeanBin = sf_bgr*h_bgr.GetBinContent(iDataBin) + sf_sig*h_sig.GetBinContent(iDataBin)

				if (MeanBin>0): loglik += TMath.Log( TMath.Poisson(NObsBin,MeanBin) )

			h_sf.SetBinContent(i,j,-2.*loglik)

	# Get best SF parameters

	x=ctypes.c_int(0)
	y=ctypes.c_int(0)
	z=ctypes.c_int(0)
	h_sf.GetBinXYZ(h_sf.GetMinimumBin(),x,y,z)
	Minimum = h_sf.GetBinContent(x.value,y.value)
	best_alpha = h_sf.GetXaxis().GetBinCenter(x.value)
	best_mu = h_sf.GetYaxis().GetBinCenter(y.value)
	print(Minimum,best_alpha,best_mu)
	

	# Rescale histogram
	for i in range(1,h_sf.GetNbinsX()+1):
		for j in range(1,h_sf.GetNbinsY()+1):
			h_sf.SetBinContent( i,j, h_sf.GetBinContent(i,j)-Minimum )


	canvas = TCanvas("canvas","Standard Canvas",600,400)
	canvas.cd()
	Min = TMarker(best_alpha,best_mu,29)
	Min.SetMarkerSize(2)
	h_sf.SetStats(kFALSE)
	h_sf.SetTitle("HIGGS PRODUCTION CROSS SECTION - PARAMETERS")
	h_sf.GetXaxis().SetTitle(r"#alpha")
	h_sf.GetYaxis().SetTitle(r"#mu")
	h_sf.Draw("COLZ")

	h_sigma = h_sf.Clone("h_sigma")
	h_sigma.Reset()
	for i in range(1,h_sigma.GetNbinsX()+1):
		for j in range(1,h_sigma.GetNbinsY()+1):
			if( h_sf.GetBinContent(i,j)<=1.): h_sigma.SetBinContent(i,j, 1.)
	h_sigma.SetMarkerColorAlpha(kRed,0.40)

	h_sigma.SetMarkerSize(10)
	h_sigma.Draw("same L")
	Min.Draw()
	leg1 = TLegend(0.65,0.85,0.85,0.75)
	leg1.SetBorderSize(1); leg1.SetFillColor(0);
	leg1a = leg1.AddEntry(Min, r"optimal (#alpha,#mu)", "p"); leg1a.SetTextSize(0.04);
	leg1.Draw()
	canvas.Print("Plots/MuFit.pdf")
Ejemplo n.º 36
0
def MassPlot(Irebin):
	gROOT.Clear()
	gROOT.Delete()

	# Prepare canvas
	c1 = TCanvas("c1","Standard Canvas",600,400)
	c1.SetLeftMargin(0.125)
	c1.SetBottomMargin(0.125)
	#c1.SetLogy()
	c1.cd()

	# Prepare histograms
	# get from file and rebin
	h_sig = GetMassDistribution(125)
	h_sig.Rebin(Irebin)
	h_bgr = GetMassDistribution(1)
	h_bgr.Rebin(Irebin)
	h_data = GetMassDistribution(2)
	h_data.Rebin(Irebin)

	# cumulative S+B
	h_SB = h_bgr.Clone("h_SB")
	h_SB.Reset()
	for i in range(1,h_bgr.GetNbinsX()+1):
		h_SB.SetBinContent(i, h_sig.GetBinContent(i)+h_bgr.GetBinContent(i) )

		print(" REBINNED HISTOGRAM: bin", i, "Ndata = ",h_data.GetBinContent(i),"\n")



	h_fit = h_SB.Clone("h_fit")
	h_fit.Reset()

	for i in range( 0,h_bgr.GetNbinsX() ):
		if( h_SB.GetBinCenter(i)>=150 and h_fit.GetBinCenter(i)>=400 ):	h_fit.SetBinContent(i, h_SB.GetBinContent(i) )



	# prepare and plot histograms
	Data_max = h_data.GetBinContent(h_data.GetMaximumBin())
	Ymax_plot = 1.20*(Data_max + 0.1*(Data_max))
	h_SB.SetFillColor(7)
	h_SB.SetAxisRange(1,Ymax_plot,"Y")
	h_SB.SetAxisRange(0,400.,"X")
	h_bgr.SetFillColor(2)

	h_SB.SetTitle("4-LEPTON INVARIANT MASS DISTRIBUTION")


	h_SB.GetXaxis().SetTitle("m [GeV]")
	h_SB.SetTitleSize(0.05,"X")
	h_SB.SetTitleOffset(0.9,"X")


	h_SB.GetYaxis().SetTitle("counts")
	h_SB.SetTitleSize(0.05,"Y")
	h_SB.SetTitleOffset(0.7,"Y")
	

	h_SB.Draw("hist")
	h_bgr.Draw("same")
	h_bgr.Draw("axis same")
	h_data.Draw("e same")

	# image format
	#AddText(0.900,0.035,"4-lepton invariant mass [GeV]",0.060,0.,"right")
	#AddText(0.040,0.900, "Number of events / "+str(h_bgr.GetBinWidth(1))+" GeV", 0.060, 90., "right")
	leg1 = TLegend(0.70,0.70,0.90,0.85)
	leg1.SetBorderSize(1); leg1.SetFillColor(0); #leg1.SetO
	leg1a = leg1.AddEntry(h_bgr, "SM(ZZ)", "f"); leg1a.SetTextSize(0.04);
	leg1b = leg1.AddEntry(h_SB, "Higgs", "f"); leg1b.SetTextSize(0.04);
	leg1.Draw()

	# save image
	c1.Print("Plots/MassPlot_rebin"+str(Irebin)+".pdf")

	h_fit = h_SB.Clone("h_fit")
	h_fit.Reset()

	for i in range( 0,h_bgr.GetNbinsX() ):
		if( h_SB.GetBinCenter(i)>=150 and h_fit.GetBinCenter(i)<=400 ):	h_fit.SetBinContent(i, h_SB.GetBinContent(i) )

	# printing plot for sidebandfit

	c2 = TCanvas("c2","Standard Canvas",600,400)
	c2.SetLeftMargin(0.125)
	c2.SetBottomMargin(0.125)
	c2.cd()

	h_SB.SetAxisRange(1,20,"Y")
	h_fit.SetAxisRange(0,400.,"X")

	h_fit.SetFillColor(8);

	h_SB.SetFillColor(0); h_SB.SetLineColor(9); h_SB.SetTitle("SIDE-BAND FIT REGION")
	h_bgr.SetFillColor(0); h_bgr.SetLineColor(1)

	h_SB.Draw("hist")
	h_bgr.Draw("hist same")
	h_fit.Draw("hist same")
	h_data.Draw("e same")
	leg1.Draw()

	c2.Print("Plots/Sideband_region.pdf")

	return
Ejemplo n.º 37
0
def Pvalues(signal=1.0):

	h_data = GetMassDistribution(2)
	h_bgr = GetMassDistribution(1)
	h_sig = GetMassDistribution(125)


	dir = ROOT.gDirectory
	file = ROOT.TFile("toy_"+str(signal)+".root","READ")
	dir.cd()

	h_test_bgr = file.Get("test_bgr").Clone("h_test_bgr")
	h_test_sb = file.Get("test_sb").Clone("h_test_sb")



	TestStat_data = GetTestStatistics(h_data,h_bgr,h_sig)
	print("--------------------")
	print("Test Statistics value for real data: ",TestStat_data)
	print("--------------------")

	# Computing p-values

	# DISCOVERY - CLb (b-only hypothesis) 
	Nbins = h_test_bgr.GetNbinsX()
	# Median b-only
	Median_bgr = Quantiles(h_test_bgr)[2]
	CLb_bgr = h_test_bgr.Integral(h_test_bgr.FindBin(Median_bgr),Nbins)/h_test_bgr.Integral()
	
	# Median s+b
	Median_sb = Quantiles(h_test_sb)[2]
	CLb_sb = h_test_bgr.Integral(h_test_bgr.FindBin(Median_sb),Nbins)/h_test_bgr.Integral()

	# Data
	CLb_data = h_test_bgr.Integral(h_test_bgr.FindBin(TestStat_data),h_test_bgr.GetNbinsX())/h_test_bgr.Integral()

	# Print a log
	print("==============================")
	print("b-only hypothesis")
	print("-----------------------------------------")
	print("	CLb 		pvalue 		significance 	")
	print("bgr:	",CLb_bgr,"	",1-CLb_bgr,"	",ROOT.Math.gaussian_quantile_c(1-CLb_bgr,1))
	print("S+B:	",CLb_sb,"	",1-CLb_sb,"	",ROOT.Math.gaussian_quantile_c(1-CLb_sb,1))
	print("Data:	",CLb_data,"	",1-CLb_data,"	",ROOT.Math.gaussian_quantile_c(1-CLb_data,1))
	print("-----------------------------------------")


	# CCL_{s+b} (S+B hypothesis)

	CLsb_bgr = h_test_sb.Integral(h_test_bgr.FindBin(Median_bgr),h_test_sb.GetNbinsX())/h_test_sb.Integral()
	
	# # Median s+b
	CLsb_sb = h_test_sb.Integral(h_test_sb.FindBin(Median_sb),h_test_sb.GetNbinsX())/h_test_sb.Integral()

	# # Data
	CLsb_data = h_test_sb.Integral(h_test_sb.FindBin(TestStat_data),h_test_sb.GetNbinsX())/h_test_sb.Integral()

	print("\ns+b hypothesis")
	print("-----------------------------------------")
	print("	CL_sb 		pvalue 		CL_s 	")
	print("bgr:	",CLsb_bgr,"	",1-CLsb_bgr,"	",CLsb_bgr/CLb_bgr )
	print("S+B:	",CLsb_sb,"	",1-CLsb_sb,"	",CLsb_sb/CLb_sb )
	print("Data:	",CLsb_data,"	",1-CLsb_data,"	",CLsb_data/CLb_data )
	print("-----------------------------------------")

	if signal!=1.: 
		cvs = TCanvas("cvs","Standard Canvas",600,400)
		Data_max = h_test_bgr.GetBinContent(h_test_bgr.GetMaximumBin())
		Ymax_plot = Data_max + np.sqrt(Data_max)
		h_test_bgr.SetAxisRange(0.,Ymax_plot,"Y")
		line = TLine(TestStat_data,0,TestStat_data,Ymax_plot)

		cvs.cd()
		h_test_bgr.SetTitle("TEST STATISTIC DISTRIBUTION")
		h_test_bgr.SetLineColor(9)
		h_test_sb.SetLineColor(8)
		line.SetLineColor(2)
		h_test_bgr.GetXaxis().SetTitle("test statistic values")
		h_test_bgr.GetYaxis().SetTitle("# toy experiments")
		h_test_bgr.SetStats(kFALSE)

		h_test_bgr.Draw("L")
		h_test_sb.Draw("same L")
		line.Draw("same")
		leg1 = TLegend(0.70,0.70,0.90,0.85)
		leg1.SetBorderSize(1); leg1.SetFillColor(0);
		leg1a = leg1.AddEntry(h_test_bgr, "b- only", "l"); leg1a.SetTextSize(0.04);
		leg1b = leg1.AddEntry(h_test_sb, "s+b", "l"); leg1b.SetTextSize(0.04);
		leg1.Draw()
		cvs.Print("Plots/TestStat"+str(signal)+".pdf")

	file.Close()

	return CLsb_data, CLsb_data/CLb_data
Ejemplo n.º 38
0
def SideBandFit(irebin=1):

	print("\n Side-band fit \n\n")

	# prepare histograms
	h_bgr = GetMassDistribution(1)
	h_data = GetMassDistribution(2)

	# rebin
	h_bgr.Rebin(irebin)
	h_data.Rebin(irebin)
	print("INFO: Rebinning histograms with factor",irebin,". Binwidth: ",h_data.GetBinWidth(1))

	# Loop over scalefactor (alpha_bgr)
	h_sf_bgr = TH1D("h_sf_bgr","",100,0.8,1.5)

	for i in range(1,h_sf_bgr.GetNbinsX()+1): 
		sf_bgr = h_sf_bgr.GetBinCenter(i)

		# Loop over bins, compute loglikelihood, save in histogram
		loglik = 0.
		for j in range(1,h_data.GetNbinsX()+1):

			# Signal-free region
			m4lepBin = h_data.GetBinCenter(j)
			NObsBin = h_data.GetBinContent(j)

			if ( m4lepBin>=150. and m4lepBin<=400.): 
				MeanBgdBin = sf_bgr * h_bgr.GetBinContent(j)

				if MeanBgdBin>0.: loglik += TMath.Log( TMath.Poisson(NObsBin,MeanBgdBin) )

		h_sf_bgr.SetBinContent(i,-2.*loglik)


	# Interpret the likelihood distribution

	h_sf_bgr_rescaled = h_sf_bgr.Clone("h_sf_bgr_rescaled")


	# find minimum
	
	MinBin = h_sf_bgr.GetMinimumBin()
	Minimum = h_sf_bgr.GetBinContent(MinBin)
	BestSF_bgd = h_sf_bgr.GetBinCenter(MinBin)

	# Rescale and find \pm 1\sigma errors
	for i in range(1,h_sf_bgr.GetNbinsX()+1):
		h_sf_bgr_rescaled.SetBinContent(i,Minimum-h_sf_bgr.GetBinContent(i))

	LeftLim = h_sf_bgr.GetBinCenter( h_sf_bgr_rescaled.FindFirstBinAbove(-1)-1 )
	RightLim = h_sf_bgr.GetBinCenter( h_sf_bgr_rescaled.FindLastBinAbove(-1)+1 )

	LeftError = BestSF_bgd - LeftLim
	RightError = RightLim - BestSF_bgd

	# Print summary
	print("   ----------\n","   Result fit: \n","   ----------","Background scale factor from sideband fit: ",BestSF_bgd," - ",LeftError," + ",RightError)

	# Plot histogram
	canvas1 = TCanvas("canvas1","Standard Canvas",600,400)
	canvas1.SetLeftMargin(0.175)
	canvas1.SetBottomMargin(0.125)
	canvas1.cd()
	h_sf_bgr_rescaled.SetStats(kFALSE)

	h_sf_bgr_rescaled.SetTitle("Background scale factor")

	h_sf_bgr_rescaled.GetXaxis().SetTitle("scale factor")
	h_sf_bgr_rescaled.GetYaxis().SetTitle("2 log L")
	#h_sf_bgr_rescaled.SetAxisRange(1,-1	,"Y")
	h_sf_bgr_rescaled.Draw("C")

	CenterLine = TLine(BestSF_bgd,0,BestSF_bgd,-31)
	CenterLine.SetLineColor(2)
	LeftLine = TLine(LeftLim,Minimum-h_sf_bgr.GetBinContent( h_sf_bgr_rescaled.FindFirstBinAbove(-1)-1 ),LeftLim,-31)
	LeftLine.SetLineColor(40)
	RightLine = TLine(RightLim,Minimum-h_sf_bgr.GetBinContent( h_sf_bgr_rescaled.FindLastBinAbove(-1)+1 ),RightLim,-31)
	RightLine.SetLineColor(40)

	CenterLine.Draw("same axis")
	LeftLine.Draw("same axis")
	RightLine.Draw("same axis")

	canvas1.Print("Plots/SideBandFit.pdf")


	# Find expected background
	bgr = h_bgr.Integral(h_bgr.FindBin(125.-0.5*7.15),h_bgr.FindBin(125+0.5*7.15))
	sig = GetMassDistribution(125).Integral(h_bgr.FindBin(125.-0.5*7.15),h_bgr.FindBin(125+0.5*7.15))
	obs = h_data.Integral(h_bgr.FindBin(125.-0.5*7.15),h_bgr.FindBin(125+0.5*7.15))
	print("BACKGROUND - without rescaling	: ", bgr)
	print("Best scalefactor: ",BestSF_bgd)
	print("BACKGROUND - with rescaling	: ", BestSF_bgd*bgr," - ",LeftError*bgr,' + ',RightError*bgr)
	print("SIGNAL EVENTS:	",sig)
	print("OBSERVED EVENTS:	",obs)

	return
Ejemplo n.º 39
0
def compare(name,file_list,name_list,legend_list,normalize=False,drawoption='hE',xtitle='',ytitle='',minx=0,maxx=0,rebin=1,miny=0,maxy=0,textsizefactor=1,logy=False,fit='',fitlow=0,fithigh=0,colors=[]):
  c=TCanvas(name,'',600,600)
  # c.SetLeftMargin(0.15)#
  # c.SetRightMargin(0.05)#
  # # c.SetTopMargin(0.05)#
  # c.SetBottomMargin(0.10)
  # # if not useOutfile:
  # # legend=TLegend(0.7,0.7,0.95,0.95)
  # # else:
  # c.SetTopMargin(0.15)
  # legend=TLegend(0.0,0.85,0.99,0.99)
  # #legend=TLegend(0.35,0.2,0.85,0.5)



  c.SetLeftMargin(0.15)#
  c.SetRightMargin(0.05)#
  c.SetBottomMargin(0.11)
  c.SetTopMargin(0.25)
  legend=TLegend(0.0,0.76,0.99,1.04)


  legend.SetHeader('')
  #legend.SetTextSize(0.03)
  legend.SetBorderSize(0)
  legend.SetTextFont(42)
  legend.SetLineColor(1)
  legend.SetLineStyle(1)
  legend.SetLineWidth(1)
  legend.SetFillColor(0)
  legend.SetFillStyle(0)
  histo_list=[]
  # tfile_list=[]
  the_maxy=0
  widths=[]
  for i in range(len(name_list)):
    # tfile_list.append(TFile(file_list[i],'READ'))
    histo_list.append(file_list[i].Get(name_list[i]).Clone())
    print(legend_list[i],histo_list[-1].Integral())
    if normalize:
      histo_list[-1].Scale(1.0/(histo_list[-1].Integral()+0.00000001))
    if not histo_list[-1].ClassName()=='TGraphAsymmErrors':
      histo_list[-1].SetStats(0)
    histo_list[-1].SetLineWidth(3)
    if colors==[]:
      histo_list[-1].SetLineColor(i+1)
      if i>6:
        histo_list[-1].SetLineColor(i+4)
    else:
      histo_list[-1].SetLineColor(colors[i])
    histo_list[-1].SetTitle('')
    
    if rebin!=1:
      histo_list[-1].Rebin(rebin)
    if not histo_list[-1].ClassName()=='TGraphAsymmErrors':
      the_maxy=max(the_maxy,histo_list[-1].GetBinContent(histo_list[-1].GetMaximumBin())*1.05)
    if fit!='':
      if fitlow==0 and fithigh==0:
        histo_list[-1].Fit(fit)
      else:
        histo_list[-1].Fit(fit,'','',fitlow[i],fithigh[i])
      histo_list[-1].GetFunction("gaus").SetLineColor(i+1)
      gaus=histo_list[-1].GetFunction("gaus")
      print(i,gaus.GetParameter(0),gaus.GetParameter(1),gaus.GetParameter(2))
      widths.append(gaus.GetParameter(2))
    if fit=='':
      legend.AddEntry(histo_list[-1],legend_list[i],'l')
    else:
      legend.AddEntry(histo_list[-1],legend_list[i]+' FWHM='+ "%.2f [GeV]" % (2.354*widths[i]),'l')
  for i in range(len(name_list)):
    if i==0:
      if not histo_list[-1].ClassName()=='TGraphAsymmErrors':
        if miny!=0 or maxy!=0:
          histo_list[i].SetMaximum(maxy)
          histo_list[i].SetMinimum(miny)
        else:
          histo_list[i].SetMaximum(the_maxy)
          histo_list[i].SetMinimum(0.0001)
      else:
        histo_list[i].SetMaximum(1.05)
        histo_list[i].SetMinimum(0.0001)
      histo_list[i].Draw(drawoption)
      charsize=0.05*textsizefactor
      histo_list[i].GetYaxis().SetLabelSize(charsize)
      histo_list[i].GetYaxis().SetTitleSize(charsize)
      histo_list[i].GetYaxis().SetTitleOffset(1.6)
      histo_list[i].GetXaxis().SetLabelSize(charsize)
      histo_list[i].GetXaxis().SetTitleSize(charsize)
      histo_list[i].GetXaxis().SetTitleOffset(0.95)
      # if useOutfile:
      if xtitle!='':
        histo_list[i].GetXaxis().SetTitle(xtitle)
      if ytitle!='':  
        histo_list[i].GetYaxis().SetTitle(ytitle)
      if maxx!=0 or minx!=0:
        histo_list[i].GetXaxis().SetRangeUser(minx,maxx)
      #   histo_list[i].GetYaxis().SetTitle('Efficiency')
    else:
      if histo_list[-1].ClassName()=='TGraphAsymmErrors':
        drawoption= drawoption.replace("A", "")
      histo_list[i].Draw(drawoption+'SAME')
  if logy:
    c.SetLogy()
  legend.Draw()
  # outfile.cd()
  c.Write(name)
  c.SaveAs('pdf/'+name+'.pdf')
Ejemplo n.º 40
0
#!/usr/bin/env python
import ROOT
from ROOT import TH1I, TChain, TCanvas

chGabriel = TChain("evt2l")
chEGamma = TChain("ZeeCandidate")

c = TCanvas("c", "Canvas", 1)
hGabriel = TH1I("hGabriel", "Compare", 10, 0, 10)
hGabriel.Fill(1)
hGabriel.Draw()
c.Print("try.pdf")
Ejemplo n.º 41
0
    elif opt == '-s':
        signal_strength = float(arg)
    elif opt == '-j':
        junk_strength = float(arg)
    elif opt == '-h':
        print_usage()
        sys.exit(0)

if (len(remainder) != 1):
    print_usage()
    sys.exit()

print "{0} events, signal fraction {1}, junk fraction {2}".format(
    n, signal_strength, junk_strength)

c = TCanvas("c", "c", 800, 600)
c.Print(remainder[0] + ".pdf[")
w = ROOT.RooWorkspace("w")

w.factory("Exponential::bkg(x[0,100],{0})".format(-1.0 / bkg_lambda))
#w.factory("Gaussian::bkg(x[-50,50],0,3)")
w.factory("Exponential::junk(x,{0})".format(-1.0 / junk_lambda))

w.factory("Exponential::signal(x,{0})".format(-1.0 / sig_lambda))
#w.factory("EXPR::signal_step('x>0?1:0',x)")
#w.factory("Gaussian::signal_res(x,0,3)")
#w.factory("PROD::signal(signal_decay,signal_step)")
#w.factory("FCONV::signal(x,signal_truth,signal_res)")
w.factory("SUM::source(strength[{0},0,0.005]*signal,{1}*junk,bkg)".format(
    signal_strength, junk_strength))
w.factory("SUM::model(strength*signal,bkg)")
Ejemplo n.º 42
0
#!/usr/bin/env python
from ROOT import TTree, TFile, gROOT, gStyle, TCanvas, TGraph, TLegend
from array import array

f = TFile('mleak_chk.root')
tr = f.Get('tr')

gROOT.SetStyle('Plain')

c = TCanvas('c', 'c', 640, 480)
c.SetTopMargin(0.05)
c.SetRightMargin(0.05)

gStyle.SetGridStyle(1)
gStyle.SetGridColor(16)
c.SetGrid()
h = c.DrawFrame(0, 0, 8000, 1200)
N = tr.GetEntries()

tr.Draw('committed_AS/1000:Entry$', '', 'goff')
g1 = TGraph(tr.GetSelectedRows(), tr.GetV2(), tr.GetV1())
g1.SetLineWidth(2)
g1.Draw('')

tr.Draw('memFree/1000:Entry$', '', 'goff')
g2 = TGraph(tr.GetSelectedRows(), tr.GetV2(), tr.GetV1())
g2.SetLineWidth(2)
g2.SetLineStyle(2)
g2.Draw('')

tr.Draw('swapFree/1000:Entry$', '', 'goff')
     cut_name_index].Clone(histogram_name + '_' + cut_name +
                           '_DoverMC_Add')
 added_histo_DoverMC.Divide(added_histo)
 cut_sublist.append(added_histo)
 cut_sublist_signal.append(added_histo_signal)
 cut_sublist_background.append(added_histo_background)
 cut_sublist_SoverB.append(added_histo_SoverB)
 cut_sublist_DoverMC.append(added_histo_DoverMC)
 if histogram_name == 'Nevts' and cut_name in [
         "heptoptag_masscut_hists", "NOheptoptag_NOmasscut_hists",
         "NOheptoptag_masscut_hists", "heptoptag_NOmasscut_hists",
         "heptoptag_NOmasscut__NOheptoptag_masscut_hists"
 ]:
     added_histo_SoverB.Write()
     added_histo_DoverMC.Write()
     canvas = TCanvas(histogram_name + '_' + cut_name + '_Info')
     SoverBvalue = added_histo_SoverB.GetBinContent(1)
     SoverBerror = added_histo_SoverB.GetBinError(1)
     DoverMCvalue = added_histo_DoverMC.GetBinContent(1)
     DoverMCerror = added_histo_DoverMC.GetBinError(1)
     latex = TLatex()
     #latex.DrawLatex(0.1,0.8,"#frac{S}{B}="+('%.3f' % SoverBvalue)+'#pm'+('%.3f' % SoverBerror))
     #latex.DrawLatex(0.1,0.6,"#frac{DATA}{MC}="+('%.3f' % DoverMCvalue)+'#pm'+('%.3f' % DoverMCerror))
     latex.DrawLatex(
         0.1, 0.8,
         "#frac{S}{B}=" + str(SoverBvalue) + '#pm' + str(SoverBerror))
     latex.DrawLatex(
         0.1, 0.6, "#frac{DATA}{MC}=" + str(DoverMCvalue) + '#pm' +
         str(DoverMCerror))
     latex.Draw()
     canvas.Write()
Ejemplo n.º 44
0
def make_ratioplot(name, ttbar_file=0, qcd_file=0, signal_files=[], histo=0,rebin=1,minx=0,maxx=0,miny=0,maxy=0,logy=False,
                    xtitle='',ytitle='',textsizefactor=1,signal_legend=[],outfile=0,signal_colors=[], signal_zoom=1, qcd_zoom=1, ttbar_zoom=1,
                    ttbar_legend='t#bar{t}',qcd_legend='QCD from MC',dosys=False,docms=True,legendtitle=''):
  
  ###canvas setting up
  canvas=0
  canvas=TCanvas(name,'',0,0,600,600)
  canvas.SetLeftMargin(0.15)
  canvas.SetRightMargin(0.05)
  canvas.SetTopMargin(0.10)
  canvas.SetBottomMargin(0.10)
  charsize=0.04
  offset=1.9

  ###latex label
  latex=0
  latex=TLatex(0.6,0.7,'13 TeV, 2.69 fb^{-1}')
  latex.SetTextSize(charsize)
  latex.SetNDC(1)
  latex.SetTextFont(42)

  ###legend setting up
  #legend=TLegend(0.0,0.75,0.99,1.04)
  legend=TLegend(0.4,0.6,0.94,0.95)
  legend.SetNColumns(2)
  legend.SetHeader('')
  legend.SetFillStyle(0)
  legend.SetBorderSize(0)


  ###mc stack
  stack=THStack(name+'_stack','')
  
  qcd_histo=qcd_file.Get(histo).Clone(name+'_make_plot')
  qcd_histo.Rebin(rebin)
  ttbar_histo=ttbar_file.Get(histo).Clone()
  ttbar_histo.Rebin(rebin)
  ttbar_histo.SetFillColor(kRed-9)
  ttbar_histo.SetLineColor(kRed-9)
  ttbar_histo.SetMarkerColor(kRed-9)
  if ttbar_zoom!=1:
    ttbar_histo.Scale(ttbar_zoom)  
  legend.AddEntry(ttbar_histo,ttbar_legend,'f')
  qcd_histo.SetFillColor(kOrange-5)
  qcd_histo.SetLineColor(kOrange-5)
  qcd_histo.SetMarkerColor(kOrange-5)
  if qcd_zoom!=1:
      qcd_histo.Scale(qcd_zoom)
  legend.AddEntry(qcd_histo,qcd_legend,'f')

  sum_mc=qcd_histo.Clone(histo+'tmp')
  sum_mc.Add(ttbar_histo)
  stack.Add(ttbar_histo)
  stack.Add(qcd_histo)
  
  sum_mc.SetLineColor(kBlack)
  sum_mc.SetFillStyle(0)
  err=TGraphAsymmErrors(sum_mc)
  legend.AddEntry(err,'Total uncertainty','f')

  if legendtitle=='':
    legend.AddEntry(0,"",'')
    legend.AddEntry(0,"g_{RS} #rightarrow t#bar{t} (2pb)",'')
  else:
    legend.AddEntry(0,"",'')
    legend.AddEntry(0,legendtitle,'')

  ###signal setting up
  signal_histos=[]
  colors=[kBlack,kRed,kOrange,kBlue,kGreen+3,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]
  styles=[1,3,5,7,7,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
  if signal_colors!=[]:
    colors=signal_colors
  for i in range(len(signal_files)):
    signal_histos.append(signal_files[i].Get(histo).Clone())
    signal_histos[i].SetLineWidth(3)
    signal_histos[i].SetLineStyle(styles[i])
    signal_histos[i].SetLineColor(colors[i])
    signal_histos[i].SetMarkerColor(colors[i])
    signal_histos[i].Rebin(rebin)
    if signal_zoom!=1:
      signal_histos[i].Scale(signal_zoom)
    legend.AddEntry(signal_histos[i],signal_legend[i],'l')

  ###mc shape line
  ttbar_line=0
  ttbar_line=ttbar_histo.Clone()
  ttbar_line.SetLineColor(kBlack)
  ttbar_line.SetFillStyle(0)

  ###mc errors
  if dosys:
    sys_diff_qcd=[]
    sys_diff_ttbar=[]
    for imtt in range(1,ttbar_histo.GetNbinsX()+1):
      sys_diff_qcd.append([])
      sys_diff_ttbar.append([])

    #adding stat uncertainties <--removed
    # for imtt in range(1,ttbar_histo.GetNbinsX()+1):
    #   sys_diff_ttbar[imtt-1].append(ttbar_histo.GetBinError(imtt))
    #   sys_diff_ttbar[imtt-1].append(-ttbar_histo.GetBinError(imtt))
    #   sys_diff_qcd[imtt-1].append(qcd_histo.GetBinError(imtt))
    #   sys_diff_qcd[imtt-1].append(-qcd_histo.GetBinError(imtt))
    #adding flat uncertainties
    for imtt in range(1,ttbar_histo.GetNbinsX()+1):
      #ttbar
      for i in [2.4,#pdf
                10.0,#mu
                3.0,#xsec
                6.0,#toppt
                1.0,#lumi
                3.5,#jec
                3.0,#jer
                10.0,#btag
                #3.0,#trig
                10.0,#toptag
                3.0]:#pileup
         sys_diff_ttbar[imtt-1].append(i/100.0*ttbar_histo.GetBinContent(imtt))
         sys_diff_ttbar[imtt-1].append(-i/100.0*ttbar_histo.GetBinContent(imtt))
      closureunc=5.0
      # if '1b' in histo:
      #   closureunc=5.0
      # elif '2b' in histo:
      #   closureunc=10.0
      for i in [2.0,#modmass
                closureunc]:#closure
         sys_diff_qcd[imtt-1].append(i/100.0*qcd_histo.GetBinContent(imtt))
         sys_diff_qcd[imtt-1].append(-i/100.0*qcd_histo.GetBinContent(imtt))
      # #3% trigger
      # sys_diff_ttbar[imtt-1].append(0.03*ttbar_histo.GetBinContent(imtt))
      # sys_diff_ttbar[imtt-1].append(-0.03*ttbar_histo.GetBinContent(imtt))
      # #2.7% lumi
      # sys_diff_ttbar[imtt-1].append(0.023*ttbar_histo.GetBinContent(imtt))
      # sys_diff_ttbar[imtt-1].append(-0.023*ttbar_histo.GetBinContent(imtt))
      # #15% ttbar
      # #sys_diff_ttbar[imtt-1].append(0.15*ttbar_histo.GetBinContent(imtt))
      # #sys_diff_ttbar[imtt-1].append(-0.15*ttbar_histo.GetBinContent(imtt))
      # #2.8% QCD
      # sys_diff_qcd[imtt-1].append(0.028*qcd_histo.GetBinContent(imtt))
      # sys_diff_qcd[imtt-1].append(-0.028*qcd_histo.GetBinContent(imtt))
    #combining uncertainties
    sys_tot_ttbar=[]
    sys_tot_qcd=[]
    sys_tot=[]
    sys_global_ttbar=[0.0,0.0]
    sys_global_qcd=[0.0,0.0]
    nevt_global=[0.0,0.0,0.0]
    for imtt in range(1,ttbar_histo.GetNbinsX()+1):
      uperr_qcd=0
      downerr_qcd=0
      uperr_ttbar=0
      downerr_ttbar=0
      for error in sys_diff_ttbar[imtt-1]:
        if error<0:
          downerr_ttbar=downerr_ttbar+error*error
        else:
          uperr_ttbar=uperr_ttbar+error*error
      for error in sys_diff_qcd[imtt-1]:
        if error<0:
          downerr_qcd=downerr_qcd+error*error
        else:
          uperr_qcd=uperr_qcd+error*error
      sys_tot_ttbar.append([math.sqrt(downerr_ttbar),math.sqrt(uperr_ttbar)])
      sys_tot_qcd.append([math.sqrt(downerr_qcd),math.sqrt(uperr_qcd)])
      sys_tot.append([math.sqrt(downerr_qcd+downerr_ttbar),math.sqrt(uperr_qcd+uperr_ttbar)])
      sys_global_qcd[0]=sys_global_qcd[0]+downerr_qcd
      sys_global_qcd[1]=sys_global_qcd[1]+uperr_qcd
      sys_global_ttbar[0]=sys_global_ttbar[0]+downerr_ttbar
      sys_global_ttbar[1]=sys_global_ttbar[1]+uperr_ttbar
      # nevt_global[0]=nevt_global[0]+data_histo.GetBinContent(imtt)
      nevt_global[1]=nevt_global[1]+qcd_histo.GetBinContent(imtt)
      nevt_global[2]=nevt_global[2]+ttbar_histo.GetBinContent(imtt)
      #print 'ttbar+qcd',math.sqrt(uperr_qcd+uperr_ttbar),math.sqrt(downerr_qcd+downerr_ttbar)
      #print 'qcd',math.sqrt(uperr_qcd),math.sqrt(downerr_qcd)
      #print 'ttbar',math.sqrt(uperr_ttbar),math.sqrt(downerr_ttbar)
      err.SetPointEYhigh(imtt-1,math.sqrt(uperr_qcd+uperr_ttbar))
      err.SetPointEYlow(imtt-1,math.sqrt(downerr_qcd+downerr_ttbar))
    sys_global=[0.0,0.0]
    sys_global[0]=math.sqrt(sys_global_qcd[0]+sys_global_ttbar[0])
    sys_global[1]=math.sqrt(sys_global_qcd[1]+sys_global_ttbar[1])
    sys_global_qcd[0]=math.sqrt(sys_global_qcd[0])
    sys_global_qcd[1]=math.sqrt(sys_global_qcd[1])
    sys_global_ttbar[0]=math.sqrt(sys_global_ttbar[0])
    sys_global_ttbar[1]=math.sqrt(sys_global_ttbar[1])
    # print name
    # print "\hline"
    # print "Multijet QCD & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1],sys_global_qcd[1],sys_global_qcd[0])
    # print "SM ttbar & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[2],sys_global_ttbar[1],sys_global_ttbar[0])
    # print "\hline"
    # print "Total background & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1]+nevt_global[2],sys_global[1],sys_global[0])
    # print 'DATA & %.0f' %nevt_global[0]


  err.SetFillStyle(3145)
  err.SetFillColor(kGray+1)

  ###drawing top
  canvas.cd()
  stack.Draw('hist')
  stack.GetXaxis().SetTitle(ttbar_histo.GetXaxis().GetTitle())
  stack.GetYaxis().SetTitle(ttbar_histo.GetYaxis().GetTitle())
  stack.GetXaxis().SetLabelSize(charsize)
  stack.GetXaxis().SetTitleSize(charsize)
  stack.GetYaxis().SetLabelSize(charsize)
  stack.GetYaxis().SetTitleSize(charsize)
  stack.GetYaxis().SetTitleOffset(offset)
  if minx!=0 or maxx!=0:
    stack.GetXaxis().SetRangeUser(minx,maxx)
  #else:
  #  stack.GetXaxis().SetRangeUser(0,4000)
  if miny!=0 or maxy!=0:
    stack.SetMaximum(maxy)
    stack.SetMinimum(miny)
  else:
    if logy:
      stack.SetMaximum(stack.GetMaximum()*10)
      stack.SetMinimum(0.2)
    else:
      stack.SetMaximum(stack.GetMaximum()*2.0)
      stack.SetMinimum(0.001)
  err.Draw('2')
  sum_mc.Draw('samehist')
  if ttbar_file!=0:
    ttbar_line.Draw('samehist')
  for i in signal_histos:
    i.Draw('samehist')
  if logy:
    canvas.SetLogy()
  legend.Draw()

  latex2text=''
  if   'ldy_0b' in name:
    latex2text='#Deltay < 1; 0 b tag'
  elif 'ldy_1b' in name:
    latex2text='#Deltay < 1; 1 b tag'
  elif 'ldy_2b' in name:
    latex2text='#Deltay < 1; 2 b tag'
  elif 'hdy_0b' in name:
    latex2text='#Deltay > 1; 0 b tag'
  elif 'hdy_1b' in name:
    latex2text='#Deltay > 1; 1 b tag'
  elif 'hdy_2b' in name:
    latex2text='#Deltay > 1; 2 b tag'
  latex2=TLatex(0.19,0.7,latex2text)
  latex2.SetTextSize(0.03)
  latex2.SetNDC(1)
  latex2.SetTextFont(42)
  latex2.Draw()

  if docms:
    if '3000' in name:
       CMS_lumi.CMS_lumi(canvas, 3, 11)
    elif '1000' in name:
       CMS_lumi.CMS_lumi(canvas, 2, 11)
    elif '300' in name:
       CMS_lumi.CMS_lumi(canvas, 1, 11)
    elif '36' in name:
       CMS_lumi.CMS_lumi(canvas, 0, 11)

  ###saving
  canvas.SaveAs('pdf/'+name+'.pdf')
  if outfile!=0:
      canvas.Write()
Ejemplo n.º 45
0
def plot(var, cut, year, norm=False, nm1=False):
    from root_numpy import root2array, fill_hist, array2root
    import numpy.lib.recfunctions as rfn
    ### Preliminary Operations ###
    treeRead = not cut in [
        "nnqq", "en", "enqq", "mn", "mnqq", "ee", "eeqq", "mm", "mmqq", "em",
        "emqq", "qqqq"
    ]  # Read from tree
    channel = cut
    unit = ''
    if "GeV" in variable[var]['title']: unit = ' GeV'
    isBlind = BLIND and 'SR' in channel
    isAH = False  #'qqqq' in channel or 'hp' in channel or 'lp' in channel
    showSignal = False if 'SB' in cut or 'TR' in cut else True  #'SR' in channel or channel=='qqqq'#or len(channel)==5
    stype = "HVT model B"
    if len(sign) > 0 and 'AZh' in sign[0]: stype = "2HDM"
    elif len(sign) > 0 and 'monoH' in sign[0]: stype = "Z'-2HDM m_{A}=300 GeV"
    if treeRead:
        for k in sorted(alias.keys(), key=len, reverse=True):
            if BTAGGING == 'semimedium':
                if k in cut:
                    cut = cut.replace(k, aliasSM[k])

            else:
                if k in cut:
                    cut = cut.replace(
                        k, alias[k].format(WP=working_points[BTAGGING]))

    print "Plotting from", ("tree" if treeRead else
                            "file"), var, "in", channel, "channel with:"
    print "  cut    :", cut

    if var == 'jj_deltaEta_widejet':
        if "jj_deltaEta_widejet<1.1 && " in cut:
            print
            print "omitting jj_deltaEta_widejet<1.1 cut to draw the deltaEta distribution"
            print
            cut = cut.replace("jj_deltaEta_widejet<1.1 && ", "")
        else:
            print
            print "no 'jj_deltaEta_widejet<1.1 && ' in the cut string detected, so it cannot be ommited explicitly"
            print

    ### Create and fill MC histograms ###
    # Create dict
    file = {}
    tree = {}
    hist = {}

    ### Create and fill MC histograms ###
    for i, s in enumerate(back + sign):
        if True:  #FIXME

            if variable[var]['nbins'] > 0:
                hist[s] = TH1F(
                    s, ";" + variable[var]['title'] + ";Events / ( " + str(
                        (variable[var]['max'] - variable[var]['min']) /
                        variable[var]['nbins']) + unit + " );" +
                    ('log' if variable[var]['log'] else ''),
                    variable[var]['nbins'], variable[var]['min'],
                    variable[var]['max'])
            else:
                hist[s] = TH1F(
                    s, ";" + variable[var]['title'] + ";Events" +
                    ('log' if variable[var]['log'] else ''),
                    len(variable[var]['bins']) - 1,
                    array('f', variable[var]['bins']))
            hist[s].Sumw2()

            for j, ss in enumerate(sample[s]['files']):
                if not 'data' in s:
                    if year == "run2" or year in ss:
                        arr = root2array(
                            NTUPLEDIR + ss + ".root",
                            branches=[
                                var, "jpt_1", "jpt_2", "eventWeightLumi",
                                "TMath::Abs(jflavour_1)==5 && TMath::Abs(jflavour_2)==5",
                                "TMath::Abs(jflavour_1)==5 && TMath::Abs(jflavour_2)!=5",
                                "TMath::Abs(jflavour_1)!=5 && TMath::Abs(jflavour_2)==5",
                                "TMath::Abs(jflavour_1)!=5 && TMath::Abs(jflavour_2)!=5"
                            ],
                            selection=cut if len(cut) > 0 else "")
                        print "imported " + NTUPLEDIR + ss + ".root"
                        arr.dtype.names = [
                            var, "jpt_1", "jpt_2", "eventWeightLumi", "bb",
                            "bq", "qb", "qq"
                        ]
                        MANtag_eff1 = np.array(map(MANtag_eff, arr["jpt_1"]))
                        MANtag_eff2 = np.array(map(MANtag_eff, arr["jpt_2"]))
                        MANtag_mis1 = np.array(map(MANtag_mis, arr["jpt_1"]))
                        MANtag_mis2 = np.array(map(MANtag_mis, arr["jpt_2"]))
                        MANtag_weight = np.multiply(
                            arr["eventWeightLumi"],
                            np.multiply(arr['bb'],
                                        np.multiply(MANtag_eff1, MANtag_eff2))
                            + np.multiply(
                                arr['bq'], np.multiply(MANtag_eff1,
                                                       MANtag_mis2)) +
                            np.multiply(arr['qb'],
                                        np.multiply(MANtag_mis1,
                                                    MANtag_eff2)) +
                            np.multiply(arr['qq'],
                                        np.multiply(MANtag_mis1, MANtag_mis2)))
                        fill_hist(hist[s], arr[var], weights=MANtag_weight)
                        deepCSV_eff1 = np.array(map(deepCSV_eff, arr["jpt_1"]))
                        deepCSV_eff2 = np.array(map(deepCSV_eff, arr["jpt_2"]))
                        deepCSV_mis1 = np.array(map(deepCSV_mis, arr["jpt_1"]))
                        deepCSV_mis2 = np.array(map(deepCSV_mis, arr["jpt_2"]))
                        deepCSV_weight = np.multiply(
                            arr["eventWeightLumi"],
                            np.multiply(
                                arr['bb'],
                                np.multiply(deepCSV_eff1, deepCSV_eff2)) +
                            np.multiply(
                                arr['bq'],
                                np.multiply(deepCSV_eff1, deepCSV_mis2)) +
                            np.multiply(
                                arr['qb'],
                                np.multiply(deepCSV_mis1, deepCSV_eff2)) +
                            np.multiply(
                                arr['qq'],
                                np.multiply(deepCSV_mis1, deepCSV_mis2)))

                        if var == "jj_mass_widejet" and options.save and not "data" in ss:
                            arr = rfn.append_fields(arr,
                                                    "MANtag_weight",
                                                    MANtag_weight,
                                                    usemask=False)
                            arr = rfn.append_fields(arr,
                                                    "deepCSV_weight",
                                                    deepCSV_weight,
                                                    usemask=False)
                            array2root(arr,
                                       NTUPLEDIR + "MANtag/" + ss + "_" +
                                       BTAGGING + ".root",
                                       treename="tree",
                                       mode='recreate')
                            print "saved as", NTUPLEDIR + "MANtag/" + ss + "_" + BTAGGING + ".root"
                        arr = None

            #tree[s] = TChain("tree")
            #for j, ss in enumerate(sample[s]['files']):
            #    if not 'data' in s or ('data' in s and ss in pd):
            #        if year=="run2" or year in ss:
            #            tree[s].Add(NTUPLEDIR + ss + ".root")
            #if variable[var]['nbins']>0: hist[s] = TH1F(s, ";"+variable[var]['title']+";Events / ( "+str((variable[var]['max']-variable[var]['min'])/variable[var]['nbins'])+unit+" );"+('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max'])
            #else: hist[s] = TH1F(s, ";"+variable[var]['title']+";Events"+('log' if variable[var]['log'] else ''), len(variable[var]['bins'])-1, array('f', variable[var]['bins']))
            #hist[s].Sumw2()
            #cutstring = "(eventWeightLumi)" + ("*("+cut+")" if len(cut)>0 else "")
            #tree[s].Project(s, var, cutstring)
            #if not tree[s].GetTree()==None: hist[s].SetOption("%s" % tree[s].GetTree().GetEntriesFast())

        #else: # Histogram written to file
        #    for j, ss in enumerate(sample[s]['files']):
        #        if not 'data' in s or ('data' in s and ss in pd):
        #            file[ss] = TFile(NTUPLEDIR + ss + ".root", "R")
        #            if file[ss].IsZombie():
        #                print "WARNING: file", NTUPLEDIR + ss + ".root", "does not exist"
        #                continue
        #            tmphist = file[ss].Get(cut+"/"+var)
        #            if tmphist==None: continue
        #            if not s in hist.keys(): hist[s] = tmphist
        #            else: hist[s].Add(tmphist)
        hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0)
        hist[s].SetFillColor(sample[s]['fillcolor'])
        hist[s].SetFillStyle(sample[s]['fillstyle'])
        hist[s].SetLineColor(sample[s]['linecolor'])
        hist[s].SetLineStyle(sample[s]['linestyle'])

    if channel.endswith('TR') and channel.replace('TR', '') in topSF:
        hist['TTbarSL'].Scale(topSF[channel.replace('TR', '')][0])
        hist['ST'].Scale(topSF[channel.replace('TR', '')][0])

    hist['BkgSum'] = hist['data_obs'].Clone(
        "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
    hist['BkgSum'].Reset("MICES")
    hist['BkgSum'].SetFillStyle(3003)
    hist['BkgSum'].SetFillColor(1)
    for i, s in enumerate(back):
        hist['BkgSum'].Add(hist[s])

    #if options.norm:
    #    for i, s in enumerate(back + ['BkgSum']): hist[s].Scale(hist[data[0]].Integral()/hist['BkgSum'].Integral())

    # Create data and Bkg sum histograms
    if options.blind or 'SR' in channel:
        hist['data_obs'] = hist['BkgSum'].Clone("data_obs")
        hist['data_obs'].Reset("MICES")
    # Set histogram style
    hist['data_obs'].SetMarkerStyle(20)
    hist['data_obs'].SetMarkerSize(1.25)

    for i, s in enumerate(back + sign + ['BkgSum']):
        addOverflow(hist[s], False)  # Add overflow
    for i, s in enumerate(sign):
        hist[s].SetLineWidth(3)
    for i, s in enumerate(sign):
        sample[s][
            'plot'] = True  #sample[s]['plot'] and s.startswith(channel[:2])

    if isAH:
        for i, s in enumerate(back):
            hist[s].SetFillStyle(3005)
            hist[s].SetLineWidth(2)
        #for i, s in enumerate(sign):
        #    hist[s].SetFillStyle(0)
        if not var == "Events":
            sfnorm = hist[data[0]].Integral() / hist['BkgSum'].Integral()
            print "Applying SF:", sfnorm
            for i, s in enumerate(back + ['BkgSum']):
                hist[s].Scale(sfnorm)
        if BLIND and var.endswith("Mass"):
            for i, s in enumerate(data + back + ['BkgSum']):
                first, last = hist[s].FindBin(65), hist[s].FindBin(135)
                for j in range(first, last):
                    hist[s].SetBinContent(j, -1.e-4)
        if BLIND and var.endswith("Tau21"):
            for i, s in enumerate(data):
                first, last = hist[s].FindBin(0), hist[s].FindBin(0.6)
                for j in range(first, last):
                    hist[s].SetBinContent(j, -1.e-4)

    # Create stack
    if variable[var]['nbins'] > 0:
        bkg = THStack(
            "Bkg",
            ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events / ( " + str(
                (variable[var]['max'] - variable[var]['min']) /
                variable[var]['nbins']) + unit + " )")
    else:
        bkg = THStack("Bkg",
                      ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events; ")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    leg = TLegend(0.65, 0.6, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    if showSignal:
        for i, s in enumerate(sign):
            if sample[s]['plot']:
                leg.AddEntry(hist[s], sample[s]['label'], "fl")

    leg.SetY1(0.9 - leg.GetNRows() * 0.05)

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

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

    log = variable[var]['log']  #"log" in hist['BkgSum'].GetZaxis().GetTitle()
    if log: c1.GetPad(bool(RATIO)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    if not isBlind and len(data) > 0: hist['data_obs'].Draw("SAME, PE")  # data
    if 'sync' in hist: hist['sync'].Draw("SAME, PE")
    #data_graph.Draw("SAME, PE")
    if showSignal:
        smagn = 1.  #if treeRead else 1.e2 #if log else 1.e2
        for i, s in enumerate(sign):
            #        if sample[s]['plot']:
            hist[s].Scale(smagn)
            hist[s].Draw(
                "SAME, HIST"
            )  # signals Normalized, hist[s].Integral()*sample[s]['weight']
        textS = drawText(0.80, 0.9 - leg.GetNRows() * 0.05 - 0.02,
                         stype + " (x%d)" % smagn, True)
    #bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075)
    bkg.GetYaxis().SetTitleOffset(0.9)
    #bkg.GetYaxis().SetTitleOffset(2.)
    bkg.SetMaximum((5. if log else 1.25) * max(
        bkg.GetMaximum(),
        hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25)
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        #bkg.GetYaxis().SetMoreLogLabels(True)
    bkg.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max'])

    #if log: bkg.SetMinimum(1)
    leg.Draw()
    #drawCMS(LUMI[year], "Preliminary")
    drawCMS(LUMI[year], "Work in Progress", suppressCMS=True)
    drawRegion('XVH' + channel, True)
    drawAnalysis(channel)

    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 / MC")
        err.GetYaxis().SetTitleOffset(0.9)

        err.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max'])
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        res = hist['data_obs'].Clone("Residues")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                res.SetBinContent(
                    i,
                    res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                res.SetBinError(
                    i,
                    res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
        if 'sync' in hist:
            res.SetMarkerColor(2)
            res.SetMarkerStyle(31)
            res.Reset()
            for i in range(0, res.GetNbinsX() + 1):
                x = hist['data_obs'].GetXaxis().GetBinCenter(i)
                if hist['sync'].GetBinContent(hist['sync'].FindBin(x)) > 0:
                    res.SetBinContent(
                        i, hist['data_obs'].GetBinContent(
                            hist['data_obs'].FindBin(x)) /
                        hist['sync'].GetBinContent(hist['sync'].FindBin(x)))
                    res.SetBinError(
                        i, hist['data_obs'].GetBinError(
                            hist['data_obs'].FindBin(x)) /
                        hist['sync'].GetBinContent(hist['sync'].FindBin(x)))
        setBotStyle(res)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if not isBlind and len(data) > 0:
            res.Draw("SAME, PE0")
            #res_graph.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(hist['data_obs'], hist['BkgSum'])
                drawStat(hist['data_obs'], hist['BkgSum'])

    c1.Update()

    if gROOT.IsBatch():
        if channel == "": channel = "nocut"
        varname = var.replace('.', '_').replace('()', '')
        if not os.path.exists("plots/" + channel):
            os.makedirs("plots/" + channel)
        suffix = ''
        if "b" in channel or 'mu' in channel: suffix += "_" + BTAGGING
        c1.Print("plots/MANtag_study/" + channel + "/" + varname + "_" + year +
                 suffix + ".png")
        c1.Print("plots/MANtag_study/" + channel + "/" + varname + "_" + year +
                 suffix + ".pdf")

    # Print table
    printTable(hist, sign)

    #    if True:
    #        sFile = TFile("sync/data_2016.root", "RECREATE")
    #        sFile.cd()
    #        hist['data_obs'].

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Ejemplo n.º 46
0
def DrawOverlap(fileVec,
                histVec,
                titleVec,
                legendtext,
                pngname,
                logstatus=[0, 0],
                xRange=[-99999, 99999, 1]):

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

    i = 0

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

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

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

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

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

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

    print histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
        if logstatus[1] is 1:
            histList[ih].SetMaximum(100)  #1.4 for log
            histList[ih].SetMinimum(0.01)  #1.4 for log
        if logstatus[1] is 0:
            histList[ih].SetMaximum(1.4)  #1.4 for log
            histList[ih].SetMinimum(0.001)  #1.4 for log
#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0:
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("APL")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("hist")
        if ih > 0:
            #histList[ih].SetLineWidth(2)
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("PL same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("hist same")

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

        i = i + 1
    pt = TPaveText(0.0877181, 0.9, 0.9580537, 0.96, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(22)
    pt.SetTextSize(0.046)
    text = pt.AddText(0.2, 0.5, "CMS Internal")
    text = pt.AddText(0.65, 0.5, "#sqrt{s} = 13 TeV(2016) ")
    pt.Draw()

    #    t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC")
    #    t2a.SetBorderSize(0)
    #    t2a.SetFillStyle(0)
    #    t2a.SetTextSize(0.040)
    #    t2a.SetTextAlign(12)
    #    t2a.SetTextFont(62)
    #    histolabel1= str(fileVec[(len(fileVec)-1)])
    #    text1 = t2a.AddText(0.06,0.5,"CMS Internal")
    #    t2a.Draw()
    leg.Draw()
    #
    #    c.cd()
    outputdirname = 'plots/'
    histname = outputdirname + pngname
    c.SaveAs(histname + '.png')
    c.SaveAs(histname + '.pdf')
Ejemplo n.º 47
0
                      [0.6, 0.15, 0.85, 0.4], [0.6, 0.15, 0.85, 0.4]]

    outRootDir = "out/"
    if not os.path.exists(outRootDir):
        os.makedirs(outRootDir)
    outRootFile = ROOT.TFile.Open(outRootDir + "outFile.root", "RECREATE")

    #  for jj in range(1,2):
    #          for ii in {0,3,4,5,6,7,8,9,10}:
    for jj in range(0, 1):
        for ii in {0, 1, 2, 10}:
            #  for ii in range(0,9):
            graphs = createGraphs(
                globalArr, ii + 2
            )  # +2 is needed since two first elements in the array correspond to the truth information
            c1 = TCanvas('c1', 'A Simple Graph Example', 0, 0, 800, 600)
            c1.cd()
            leg = TLegend(legendPosition[ii][0], legendPosition[ii][1],
                          legendPosition[ii][2], legendPosition[ii][3])
            leg.SetBorderSize(0)
            leg.SetTextSize(0.03)

            for kk in range(0, len(graphs[jj])):
                iGr = graphs[jj][kk]
                styleGraph(iGr, kk + 1)
                leg.AddEntry(iGr, iGr.GetTitle(), "p")
                if kk == 0:
                    iGr.SetTitle("")
                    iGr.GetYaxis().SetTitle(yAxisTitle[ii])
                    iGr.GetXaxis().SetTitle(xAxisTitle[jj])
                    iGr.GetYaxis().SetTitleOffset(1.3)
def efficiencytracking(var):
    # plots the efficiency vs pT, eta and phi for all the species(it extracts the
    # Efficiency from qa - tracking - efficiency if you have ran with-- make - eff)
    hadron_list = ["pion", "proton", "kaon", "electron", "muon"]
    color_list = [1, 2, 4, 6, 8]
    marker_list = [20, 21, 22, 34, 45]
    fileo2 = TFile("../codeHF/AnalysisResults_O2.root")

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

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

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

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

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

        gr.SetLineColor(color_list[i])
        gr.SetMarkerColor(color_list[i])
        gr.SetMarkerStyle(marker_list[i])
        eff_list.append(gr)
        gr.Draw(" same p")
        leg.AddEntry(eff_list[i], had, "p")
    leg.Draw()
    saveCanvas(c1, "efficiency_tracking_%s" % var)
Ejemplo n.º 49
0
    "module_L6t_halfmodule_axial_hole_sensor0 - Occupancy")
L6t_axial_slot_nom = inFile2.Get(
    "module_L6t_halfmodule_axial_slot_sensor0 - Occupancy")
L6t_stereo_hole_nom = inFile2.Get(
    "module_L6t_halfmodule_stereo_hole_sensor0 - Occupancy")
L6t_stereo_slot_nom = inFile2.Get(
    "module_L6t_halfmodule_stereo_slot_sensor0 - Occupancy")


def plot(histo, outName):
    histo.Draw("")
    histo.SetTitle(histo.GetTitle())
    c.Print(outName + ".pdf", "Title:histoTitle")


c = TCanvas("c", "c", 800, 600)

outnameL0 = outname + "L0"
outnamenom = outname + "nom"

c.Print(outnameL0 + ".pdf[", "Title:histoTitle")

plot(L0b_axial_hole_L0, outnameL0)
plot(L0b_axial_slot_L0, outnameL0)
plot(L0b_stereo_hole_L0, outnameL0)
plot(L0b_stereo_slot_L0, outnameL0)
plot(L0t_axial_hole_L0, outnameL0)
plot(L0t_axial_slot_L0, outnameL0)
plot(L0t_stereo_hole_L0, outnameL0)
plot(L0t_stereo_slot_L0, outnameL0)
 ratiograph.SetMinimum(0.976)
 ratiograph.SetMaximum(1.024)
 ratiograph.GetXaxis().SetLimits(0.0, 155.0)
 ratiograph.SetTitle("")
 ratiograph.GetXaxis().SetLabelSize(.105)
 ratiograph.GetYaxis().SetLabelSize(0.105)
 ratiograph.GetXaxis().SetNdivisions(520)
 ratiograph.GetYaxis().SetNdivisions(504)
 lingraph.SetTitle("")
 lingraph.SetMinimum(0.0)
 lingraph.SetMaximum(155.0)
 lingraph.GetXaxis().SetLimits(0.0, 155.0)
 lingraph.GetXaxis().SetLabelSize(0.)
 lingraph.GetXaxis().SetNdivisions(520)
 lingraph.GetYaxis().SetNdivisions(520)
 c = TCanvas("c", "canvas", 800, 800)
 # Upper histogram plot is pad1
 pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
 pad1.SetBottomMargin(0.02)  # joins upper and lower plot
 pad1.SetLeftMargin(0.1)
 pad1.SetRightMargin(0.1)
 pad1.Draw()
 # Lower ratio plot is pad2
 c.cd()  # returns to main canvas before defining pad2
 pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
 pad2.SetTopMargin(0.05)  # joins upper and lower plot
 pad2.SetBottomMargin(0.3)
 pad2.SetLeftMargin(0.1)
 pad2.SetRightMargin(0.1)
 pad2.Draw()
 pad1.cd()
Ejemplo n.º 51
0
def fitSloChannelsFast(dsNum):

    # Just get the 95% upper value from the peak.
    # NOTE: the slowness model might not be good at the 238 peak (S/N too high ??)
    # Ben is shaking his head in disapproval.

    ds = dsNum
    chCal = {}
    chCal[0] = [640, 644, 646, 656, 662, 664, 674, 688, 690, 692, 696, 576, 592, 594, 598, 600, 608, 610, 624, 626]
    chCal[1] = [672, 640, 610, 580, 578, 582, 648, 600, 626, 592, 664, 594, 692, 598, 690, 632, 608]
    chCal[3] = [608, 624, 610, 580, 614, 582, 648, 664, 694, 578, 678, 592, 600, 626, 692, 598, 690, 632, 640, 672]
    chCal[4] = [1232, 1236, 1332, 1298, 1330, 1170, 1296, 1136, 1176, 1106, 1204, 1174, 1144, 1172]
    chCal[5] = [640, 1302, 648, 1170, 1172, 662, 1176, 672, 678, 680, 1330, 688, 690, 1332, 694, 1208, 1204, 1110, 1174, 608, 584, 1298, 592, 1106, 598, 1120, 610, 1124, 614, 1128, 658, 624, 626, 628, 632, 660]

    f1 = TFile("~/project/lat/latSkimDS%d_0_0.root"%ds)
    theCut = f1.Get("theCut").GetTitle()
    calib = TChain("skimTree")
    calib.Add("~/project/cal-lat/latSkimDS%d*.root"%ds)

    c = TCanvas("c","c",1600,600)
    c.Divide(3,1,0.00001,0.00001)

    # ch = 626 # the golden detector
    for ch in chCal[ds]:

        var = "fitSlo"
        eb, elo, ehi = 10,237,240
        vb, vlo, vhi = 200,0,30
        d2Draw = "fitSlo:trapENFCal>>b(%d,%d,%d,%d,%d,%d)"%(eb,elo,ehi,vb,vlo,vhi)
        d2Cut = theCut + " && channel==%d" % ch
        d1Cut = theCut + " && trapENFCal > %d && trapENFCal < %d && channel==%d" % (elo,ehi,ch)

        c.cd(2)
        gPad.SetLogy(0)
        h1 = TH1D("h1","h1",vb,vlo,vhi)
        calib.Project("h1",var,d1Cut)
        h1.Scale(1/h1.Integral())
        h1.Draw("hist")

        c.cd(1)
        gPad.SetLogy(0)
        calib.Draw(d2Draw,d2Cut)
        pk99,pk95,pk01,pk05 = GetIntegralPoints(h1)
        line99 = TLine()
        line99.SetLineColor(ROOT.kGreen)
        line95 = TLine()
        line95.SetLineColor(ROOT.kRed)
        line99.DrawLine(elo, pk99, ehi, pk99)
        line95.DrawLine(elo, pk95, ehi, pk95)
        line95.DrawLine(elo, pk05, ehi, pk05)
        line99.DrawLine(elo, pk01, ehi, pk01)

        c.cd(3)
        x_h1, y_h1 = npTH1D(h1)
        int_h1 = integFunc(y_h1)
        g2 = TGraph(len(x_h1), x_h1, int_h1)
        g2.Draw("ACP")
        line99.DrawLine(pk99, 0, pk99, 1)
        line95.DrawLine(pk95, 0, pk95, 1)
        line99.DrawLine(pk01, 0, pk01, 1)
        line95.DrawLine(pk05, 0, pk05, 1)

        c.Print("./plots/fitSlo/fast_ds%d_ch%d.png" % (ds,ch))
        print "DS-%d  Ch %d  fitSlo95 %.2f " % (ds,ch,pk95)
Ejemplo n.º 52
0
def provideQuadCanvas(title="Same Sign Dilepton SUSY analysis"):
    # window settings
    theCanvasSizeX = 1400
    theCanvasSizeY = 920
    theScreenSizeX = 1680
    theScreenSizeY = 1050
    theOffsetX = -80
    theOffsetY = -60

    # canvas
    posX = (theScreenSizeX - theCanvasSizeX) / 2 + theOffsetX
    posY = (theScreenSizeY - theCanvasSizeY) / 2 + theOffsetY
    c1 = TCanvas('c1', title, posX, posY, theCanvasSizeX, theCanvasSizeY)
    c1.Divide(2, 2)

    c1.cd(1)
    pad1 = TPad('pad1', 'Pad for top left histogram', 0.03, 0.03, 0.97, 0.97,
                0)
    pad1.Draw()
    c1.cd(2)
    pad2 = TPad('pad2', 'Pad for top right histogram', 0.03, 0.03, 0.97, 0.97,
                0)
    pad2.Draw()
    c1.cd(3)
    pad3 = TPad('pad1', 'Pad for bottom left histogram', 0.03, 0.03, 0.97,
                0.97, 0)
    pad3.Draw()
    c1.cd(4)
    pad4 = TPad('pad2', 'Pad for bottom right histogram', 0.03, 0.03, 0.97,
                0.97, 0)
    pad4.Draw()

    return [c1, pad1, pad2, pad3, pad4]
Ejemplo n.º 53
0
def fitArb10(tree,theCut):
    # fit an arbitrary low-energy cut

    print theCut

    theCut += " && !isEnr"
    checkCut = ""
    thisVar = "bandTime"
    fileName = "./plots/lat-max.pdf"
    parLim = [0,20000]

    # scatter plot
    h0 = wl.H2D(tree,"h0",100,0,20,500,parLim[0],parLim[1],thisVar+":trapENFCal",theCut)

    # -- 10 peak --
    fitModel10 = "[0] + [1]*x + [2]*x**2 + [3] * exp(-1.0 * ((x-[4])**2 / (2 * [5]**2)) )"

    h1 = wl.H1D(tree,"h1",20,9.5,11.5,"trapENFCal",theCut)
    h2 = wl.H1D(tree,"h2",20,9.5,11.5,"trapENFCal",theCut+checkCut)

    f0 = TF1("f0","gaus",10,11)
    h1.Fit("f0","Lq")
    [norm,mu,sig] = wl.GetPars(f0)

    f1 = TF1("f1", fitModel10, 9.5,11)
    wl.SetPars(f1,[-209, 41, -2, norm, mu, sig])
    f1.SetLineColor(4)
    h1.Fit("f1","Lq")
    [p0,p1,p2,norm1,mu,sig] = wl.GetPars(f1)

    f2 = TF1("f2", fitModel10, 9.5,11)
    wl.SetPars(f2,[-209, 41, -2, norm1, mu, sig])
    f2.SetLineColor(2)
    h2.Fit("f2","Lq")
    [p0,p1,p2,norm2,mu,sig] = wl.GetPars(f2)

    retention = 100*norm2/norm1
    print "Retention:",retention," Cut used:",checkCut

    # -- Energy Spectrum --
    h3 = wl.H1D(tree,"h3",250,0,50,"trapENFCal",theCut)
    h4 = wl.H1D(tree,"h4",250,0,50,"trapENFCal",theCut+checkCut)

    cts3 = h3.Integral( *wl.Get1DBins(h3,0,20))
    cts4 = h4.Integral( *wl.Get1DBins(h4,0,20))
    cts5 = h3.Integral( *wl.Get1DBins(h3,20,40))
    cts6 = h4.Integral( *wl.Get1DBins(h4,20,40))

    print "Cts. 0-20 %d before  %d after.  20-40 %d before %d after" % (cts3,cts4,cts5,cts6)

    h3.GetXaxis().SetRangeUser(0,20)
    h4.GetXaxis().SetRangeUser(0,20)


    # -- Plots --
    c1 = TCanvas("c1","Bob Ross's Canvas",1800,600)

    c1.Divide(3,1,0.00001) # TPad::Divide
    c1.cd(1)
    gPad.SetLogz()
    h0.SetMinimum(1)
    h0.Draw("COLZ")

    c1.cd(2)
    gPad.SetLogy()
    h3.SetLineColor(4)
    h3.Draw()
    h4.SetLineColor(2)
    h4.Draw("same")
    l1 = TLegend(0.4,0.7,0.87,0.92)
    l1.AddEntry(h1,"basic","l")
    l1.AddEntry(h2,thisVar,"l")
    l1.Draw("same")

    c1.cd(3)
    h1.SetLineColor(4) # blue
    h1.Draw()
    h2.SetLineColor(2) # red
    h2.Draw("same")

    l2 = TLegend(0.6,0.6,0.87,0.92)
    l2.AddEntry(h1,"basic","l")
    l2.AddEntry(h2,thisVar,"l")
    l2.AddEntry(h2,"Retention: %.3f" % retention,"")
    l2.Draw("same")

    c1.Print(fileName)
Ejemplo n.º 54
0
def fitSlo238(tree,theCut):

    # for calibration data, keep 99% of the fast events in the 238 peak.
    # this is practice for doing this with the 10 kev peak in natural bg data.

    # scatter plot
    h1 = wl.H2D(tree,"h1",500,0,250,500,0,200,"fitSlo:trapENFCal",theCut)
    cts1 = h1.Integral( *wl.Get2DBins(h1,0,250,0,200) )

    # -- 238 peak --

    h2 = wl.H1D(tree,"h2",50,237,240,"trapENFCal",theCut)
    cts2 = h2.Integral( *wl.Get1DBins(h2,237,240) )
    h2.SetLineColor(4)

    f0 = TF1("f0","gaus",237,240)
    h2.Fit("f0","Lq") # use to set initial guesses

    f1 = TF1("f1", "[0] * x  + [1] * exp(-1.0 * (TMath::Power((x-[2]),2) / (2 * TMath::Power([3],2)) ))", 237, 240)
    wl.SetPars(f1,[1,418,238,0.381])
    f1.SetLineColor(4)
    h2.Fit("f1","q")
    [flat, norm1, mu, sig] = wl.GetPars(f1)

    h3 = wl.H1D(tree,"h3",50,237,240,"trapENFCal",theCut+" && fitSlo < 20")
    cts3 = h3.Integral( *wl.Get1DBins(h3,237,240) )

    f2 = TF1("f2", "[0] * x  + [1] * exp(-1.0 * (TMath::Power((x-[2]),2) / (2 * TMath::Power([3],2)) ))", 237, 240)
    wl.SetPars(f2,[1,418,238,0.381])
    f2.SetLineColor(2)
    h3.Fit("f2","q")
    [flat, norm2, mu, sig] = wl.GetPars(f2)

    retention = 100*norm2/norm1
    print "norm1 %.2f  norm2 %.2f  retention: %.2f" % (norm1, norm2, retention)


    # -- Plots --
    c1 = TCanvas("c1","Bob Ross's Canvas",1200,600)

    c1.Divide(2,1) # x, y
    c1.cd(1)
    gPad.SetLogz()
    h1.Draw("COLZ")

    c1.cd(2)
    h2.Draw()
    h3.SetLineColor(2) # red
    h3.Draw("same")

    l1 = TLegend(0.6,0.7,0.87,0.92)
    l1.AddEntry(h2,"basic","l")
    l1.AddEntry(f1,"basic fit:","l")
    # l1.AddEntry(f1,"flat %.2f  norm %.2f" % (flat,norm1) ,"")
    # l1.AddEntry(f1,"mu %.2f  sig %.2f" % (mu,sig) ,"")
    l1.AddEntry(h3,"+fitSlo < 20","l")
    l1.AddEntry(h3,"Retention: %.3f" % retention,"")

    l1.Draw("same")
    c1.Update()

    c1.Print("./plots/cal-fitSlo.pdf")
Ejemplo n.º 55
0
def PlotProfiles(hists,
                 xlabel,
                 these_colors,
                 these_transcolors,
                 these_markers,
                 drawopt='pE1',
                 rlabel='Trigger/Ref.',
                 ylabel='Trigger Efficiency',
                 doRatioCanvas=False,
                 y_axes_maximum=1.1,
                 y_axes_minimum=0.0,
                 pad_top_y_axes_maximum=1.1,
                 pad_top_y_axes_minimum=0.0,
                 pad_bot_y_axes_maximum=1.1,
                 pad_bot_y_axes_minimum=0.9):

    from ROOT import TCanvas
    from Gaugi.monet import RatioCanvas, AddHistogram, FormatCanvasAxes, SetAxisLabels
    doRatio = True if (doRatioCanvas and (len(hists) > 1)) else False
    collect = []
    canvas = RatioCanvas('canvas', "", 700, 500) if doRatio else TCanvas(
        'canvas', "", 700, 500)
    if doRatio:
        pad_top = canvas.GetPrimitive('pad_top')
        pad_bot = canvas.GetPrimitive('pad_bot')

    refHist = hists[0]
    for idx, hist in enumerate(hists):
        if doRatio:
            if idx < 1:
                refHist.SetLineColor(these_colors[idx])
                refHist.SetMarkerColor(these_colors[idx])
                refHist.SetMaximum(pad_top_y_axes_maximum)
                refHist.SetMinimum(pad_top_y_axes_minimum)
                AddHistogram(pad_top,
                             refHist,
                             drawopt=drawopt,
                             markerStyle=these_markers[idx])
            else:
                h_hist = hist.Clone()
                h_hist.Divide(h_hist, refHist, 1., 1., 'B')
                h_hist.SetMinimum(pad_bot_y_axes_minimum)
                h_hist.SetMaximum(pad_bot_y_axes_maximum)
                collect.append(h_hist)
                hist.SetLineColor(these_colors[idx])
                hist.SetMarkerColor(these_colors[idx])
                hist.SetMaximum(pad_top_y_axes_maximum)
                AddHistogram(pad_top,
                             hist,
                             drawopt,
                             markerStyle=these_markers[idx])
                AddHistogram(pad_bot,
                             h_hist,
                             'P',
                             markerStyle=these_markers[idx])
        else:
            hist.SetLineColor(these_colors[idx])
            hist.SetMarkerColor(these_colors[idx])
            hist.SetMaximum(y_axes_maximum)
            hist.SetMinimum(y_axes_minimum)
            AddHistogram(canvas,
                         hist,
                         drawopt=drawopt,
                         markerStyle=these_markers[idx])

    FormatCanvasAxes(canvas,
                     XLabelSize=18,
                     YLabelSize=18,
                     XTitleOffset=0.87,
                     YTitleOffset=1.5)
    SetAxisLabels(canvas, xlabel, ylabel, rlabel)
    return canvas
Ejemplo n.º 56
0
def fitSloChannels():
    ds = 1

    f1 = TFile("~/project/lat/latSkimDS%d_0_0.root"%ds)
    theCut = f1.Get("theCut").GetTitle()
    calib = TChain("skimTree")
    calib.Add("~/project/cal-lat/latSkimDS%d*.root"%ds)

    c = TCanvas("c","c",1600,1200)
    c.Divide(3,2,0.00001,0.00001)

    # ch = 626 # the golden detector

    for ch in chCalDS1:

        # 10-200 spectrum
        var = "fitSlo"
        eb, elo, ehi = 10,10,200
        vb, vlo, vhi = 200,0,30
        d2Draw = "fitSlo:trapENFCal>>a(%d,%d,%d,%d,%d,%d)"%(eb,elo,ehi,vb,vlo,vhi)
        d2Cut = theCut + " && channel==%d" % ch
        d1Cut = theCut + " && trapENFCal > 5 && channel==%d" % ch

        c.cd(2)
        gPad.SetLogy(0)
        h0 = TH1D("h0","h0",vb,vlo,vhi)
        calib.Project("h0",var,d1Cut)
        h0.Scale(1/h0.Integral())
        h0.Draw("hist")

        c.cd(1)
        gPad.SetLogy(1)
        calib.Draw(d2Draw,d2Cut)
        sp99,sp95,sp01,sp05 = GetIntegralPoints(h0)
        line99 = TLine()
        line99.SetLineColor(ROOT.kGreen)
        line95 = TLine()
        line95.SetLineColor(ROOT.kRed)
        line99.DrawLine(elo, sp99, ehi, sp99)
        line95.DrawLine(elo, sp95, ehi, sp95)
        line95.DrawLine(elo, sp05, ehi, sp05)
        line99.DrawLine(elo, sp01, ehi, sp01)

        c.cd(3)
        x_h0, y_h0 = npTH1D(h0)
        int_h0 = integFunc(y_h0)
        g1 = TGraph(len(x_h0), x_h0, int_h0)
        g1.Draw("ACP")
        line99.DrawLine(sp99, 0, sp99, 1)
        line95.DrawLine(sp95, 0, sp95, 1)
        line99.DrawLine(sp01, 0, sp01, 1)
        line95.DrawLine(sp05, 0, sp05, 1)


        # 238 peak spectrum
        eb, elo, ehi = 10,237,240
        d2Draw = "fitSlo:trapENFCal>>b(%d,%d,%d,%d,%d,%d)"%(eb,elo,ehi,vb,vlo,vhi)
        d2Cut = theCut + " && channel==%d" % ch
        d1Cut = theCut + " && trapENFCal > %d && trapENFCal < %d && channel==%d" % (elo,ehi,ch)

        c.cd(5)
        gPad.SetLogy(0)
        h1 = TH1D("h1","h1",vb,vlo,vhi)
        calib.Project("h1",var,d1Cut)
        h1.Scale(1/h1.Integral())
        h1.Draw("hist")

        c.cd(4)
        gPad.SetLogy(0)
        calib.Draw(d2Draw,d2Cut)
        pk99,pk95,pk01,pk05 = GetIntegralPoints(h1)
        line99 = TLine()
        line99.SetLineColor(ROOT.kGreen)
        line95 = TLine()
        line95.SetLineColor(ROOT.kRed)
        line99.DrawLine(elo, pk99, ehi, pk99)
        line95.DrawLine(elo, pk95, ehi, pk95)
        line95.DrawLine(elo, pk05, ehi, pk05)
        line99.DrawLine(elo, pk01, ehi, pk01)

        c.cd(6)
        x_h1, y_h1 = npTH1D(h1)
        int_h1 = integFunc(y_h1)
        g2 = TGraph(len(x_h1), x_h1, int_h1)
        g2.Draw("ACP")
        line99.DrawLine(pk99, 0, pk99, 1)
        line95.DrawLine(pk95, 0, pk95, 1)
        line99.DrawLine(pk01, 0, pk01, 1)
        line95.DrawLine(pk05, 0, pk05, 1)

        c.Print("./plots/fitSlo/ds%d_ch%d.png" % (ds,ch))

        print "DS-%d  Channel %d:" % (ds,ch)
        print "  Peak - 99: %.2f  95: %.2f  5: %.2f  1: %.2f" % (sp99,sp95,sp05,sp01)
        print "  Spec - 99: %.2f  95: %.2f  5: %.2f  1: %.2f" % (pk99,pk95,pk05,pk01)
Ejemplo n.º 57
0
def report():
    global freed_file
    print '    HeapMonReport.report(): heapmon_file=', freed_file

    #findStaticHoles()

    tfile = TFile(freed_file, "READ")
    print "   root compression factor = ", tfile.GetCompressionFactor()

    mem_canvas = TCanvas("HeapMon_report", "Memory Holes Statistics", 10, 10,
                         800, 1034)
    mem_canvas.SetFillColor(17)
    mem_canvas.cd()

    pad1 = TPad("pad1", "pad1", 0.01, 0.57, 0.50, 0.93, 33)
    pad2 = TPad("pad2", "pad2", 0.51, 0.57, 0.99, 0.93, 33)
    pad3 = TPad("pad3", "pad3", 0.01, 0.01, 0.99, 0.50, 33)
    pad3.SetPhi(210)
    pad3.SetTheta(25)

    pad1.Draw()
    pad2.Draw()
    pad3.Draw()
    memTree = tfile.Get("holeTree")
    infoTree = tfile.Get("infoTree")
    mallocTree = tfile.Get("mallocTree")
    #holesm_th1i =   TH1I('holesm_th1i', 'Holes size evolution', fcount, 0, fcount)
    #holesn_th1i =   TH1I('holesn_th1i', 'Holes number evolution', fcount, 0, fcount)
    #total_th1i  =   TH1I('total_th1i', 'Total memory size evolution', fcount, 0, fcount)

    max_hole_size = memTree.GetMaximum("hole_size")
    print "    max_hole_size=", max_hole_size, "    min_hole_size", memTree.GetMinimum(
        "hole_size")
    max_scan_number = memTree.GetMaximum("scan_number")
    print "     max_scan_number=", max_scan_number

    memHist1 = TH2I("mem2d", "Hole-sizes distribution evolution", 128, -0.5,
                    max_hole_size - 0.5, 50, 0, max_scan_number)
    memTree.Project("mem2d", "scan_number:hole_size")

    multiGraph1 = TMultiGraph()
    multiGraph2 = TMultiGraph()

    print " memHist.GetMaximum() = ", memHist1.GetMaximum()

    # Working on a Report
    gStyle.SetOptStat(0)
    gStyle.SetPalette(1)
    gStyle.SetCanvasColor(33)
    gStyle.SetFrameFillColor(18)

    memHist1.SetFillColor(30)
    memHist1.SetFillStyle(0)
    memHist1.GetXaxis().SetTitle("Size of holes, kb")
    memHist1.GetXaxis().SetLabelOffset(0.02)
    memHist1.GetXaxis().SetLabelSize(0.02)
    memHist1.GetXaxis().SetTitleSize(0.04)
    memHist1.GetXaxis().SetTitleColor(2)
    memHist1.GetYaxis().SetTitle("Event number")
    memHist1.GetYaxis().SetLabelSize(0.04)
    memHist1.GetXaxis().SetLabelOffset(0.04)
    memHist1.GetYaxis().SetTitleSize(0.04)
    memHist1.GetYaxis().SetTitleColor(2)
    memHist1.GetZaxis().SetTitle("Number of holes")
    memHist1.GetZaxis().SetLabelSize(0.02)
    memHist1.GetZaxis().SetTitleSize(0.04)
    memHist1.GetZaxis().SetTitleColor(2)

    title = TPaveLabel(0.1, 0.95, 0.9, 0.99, "Job Memory Usage Plots")
    title.SetFillColor(42)
    title.SetTextFont(42)
    title.Draw()

    text_box = TPaveText(0.1, 0.51, 0.9, 0.54)
    text_box.AddText("Malloc freed ('marked') Heap Memory Profile")
    text_box.SetFillColor(42)
    text_box.SetTextAlign(12)
    text_box.SetTextFont(42)
    text_box.Draw()

    x1 = 0.2
    y1 = 0.91
    x2 = 0.8
    y2 = 0.98

    #Drawing upper-left corner Pad1 of the report
    pad1.cd()
    pad1.SetGridx()
    pad1.SetGridy()
    infoTree.Draw("total_maps_memory:scan_number", "", "goff")
    mapsGraph = TGraph(int(infoTree.GetSelectedRows()), infoTree.GetV2(),
                       infoTree.GetV1())
    mapsGraph.SetLineColor(1)
    mapsGraph.SetLineWidth(1)
    #mapsGraph.SetFillStyle(3001); mapsGraph.SetFillColor(2);
    mapsGraph.SetName("total_maps_memory")
    #VmSize, VmLck, VmRSS, VmData, VmStk, VmExe, VmLib;
    infoTree.Draw("VmSize:scan_number", "", "goff")
    vmsizeGraph = TGraph(int(infoTree.GetSelectedRows()), infoTree.GetV2(),
                         infoTree.GetV1())
    vmsizeGraph.SetLineColor(2)
    vmsizeGraph.SetLineWidth(1)
    #vmsizeGraph.SetFillStyle(3002); vmsizeGraph.SetFillColor(3);
    vmsizeGraph.SetName("VmSize")

    infoTree.Draw("VmRSS:scan_number", "", "goff")
    vmrssGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(),
                        infoTree.GetV1())
    vmrssGraph.SetLineColor(3)
    vmrssGraph.SetLineWidth(1)
    #vmrssGraph.SetFillStyle(3003); vmrssGraph.SetFillColor(4);
    vmrssGraph.SetName("VmRSS")

    infoTree.Draw("VmData:scan_number", "", "goff")
    vmdataGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(),
                         infoTree.GetV1())
    vmdataGraph.SetLineColor(4)
    vmdataGraph.SetLineWidth(1)
    #vmdataGraph.SetFillStyle(3004); vmdataGraph.SetFillColor(4);
    vmdataGraph.SetName("VmData")

    infoTree.Draw("VmStk:scan_number", "", "goff")
    vmstkGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(),
                        infoTree.GetV1())
    vmstkGraph.SetLineColor(5)
    vmstkGraph.SetLineWidth(1)
    #vmstkGraph.SetFillStyle(3005); vmstkGraph.SetFillColor(4);
    vmstkGraph.SetName("VmStk")

    infoTree.Draw("VmExe:scan_number", "", "goff")
    vmexeGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(),
                        infoTree.GetV1())
    vmexeGraph.SetLineColor(6)
    vmexeGraph.SetLineWidth(1)
    #vmexeGraph.SetFillStyle(3003); vmexeGraph.SetFillColor(4);
    vmexeGraph.SetName("VmExe")

    infoTree.Draw("VmLib:scan_number", "", "goff")
    vmlibGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(),
                        infoTree.GetV1())
    vmlibGraph.SetLineColor(7)
    vmlibGraph.SetLineWidth(1)
    #vmlibGraph.SetFillStyle(3003); vmlibGraph.SetFillColor(4);
    vmlibGraph.SetName("VmLib")

    infoTree.Draw("VmLck:scan_number", "", "goff")
    vmlckGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(),
                        infoTree.GetV1())
    vmlckGraph.SetLineColor(8)
    vmlckGraph.SetLineWidth(1)
    #vmlckGraph.SetFillStyle(3003); vmlckGraph.SetFillColor(4);
    vmlckGraph.SetName("VmLck")

    infoTree.Draw("total_hole_memory:scan_number", "", "goff")
    holeGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(),
                       infoTree.GetV1())
    holeGraph.SetLineColor(9)
    holeGraph.SetLineWidth(1)
    #holeGraph.SetFillStyle(3004); holeGraph.SetFillColor(5);
    holeGraph.SetName("HolesSize")

    mallocTree.Draw("malloc_free:scan_number", "", "goff")
    freeGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(),
                       mallocTree.GetV1())
    freeGraph.SetLineColor(11)
    freeGraph.SetLineWidth(1)
    freeGraph.SetFillStyle(3003)
    freeGraph.SetFillColor(4)
    freeGraph.SetName("malloc_free")

    mallocTree.Draw("malloc_inuse:scan_number", "", "goff")
    inuseGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(),
                        mallocTree.GetV1())
    inuseGraph.SetLineColor(21)
    inuseGraph.SetLineWidth(1)
    inuseGraph.SetFillStyle(3003)
    inuseGraph.SetFillColor(4)
    inuseGraph.SetName("malloc_inuse")

    mallocTree.Draw("malloc_sbrk:scan_number", "", "goff")
    sbrkGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(),
                       mallocTree.GetV1())
    sbrkGraph.SetLineColor(31)
    sbrkGraph.SetLineWidth(1)
    sbrkGraph.SetFillStyle(3003)
    sbrkGraph.SetFillColor(4)
    sbrkGraph.SetName("malloc_sbrk")

    mallocTree.Draw("malloc_mmap:scan_number", "", "goff")
    mmapGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(),
                       mallocTree.GetV1())
    mmapGraph.SetLineColor(41)
    mmapGraph.SetLineWidth(1)
    mmapGraph.SetFillStyle(3003)
    mmapGraph.SetFillColor(4)
    mmapGraph.SetName("malloc_mmap")

    pad1.cd()
    multiGraph1.Add(mapsGraph)
    multiGraph1.Add(vmsizeGraph)
    multiGraph1.Add(vmrssGraph)
    multiGraph1.Add(vmdataGraph)
    multiGraph1.Add(vmlckGraph)
    multiGraph1.Add(vmexeGraph)
    multiGraph1.Add(vmstkGraph)
    #multiGraph1.Add(vmlibGraph);
    multiGraph1.Add(inuseGraph)
    multiGraph1.Add(sbrkGraph)
    multiGraph1.Add(mmapGraph)
    multiGraph1.Add(holeGraph)
    multiGraph1.Add(freeGraph)

    #multiGraph1.SetTitle("PROCESS VM and Malloc MEMORY USAGE");
    title.DrawPaveLabel(x1, y1, x2, y2, "PROCESS VM and Malloc MEMORY USAGE",
                        "brNDC")

    multiGraph1.Draw("ALg")
    hist = multiGraph1.GetHistogram()
    hist.SetXTitle("Event Number")
    hist.SetYTitle("Memory, kb")
    legend1 = TLegend(0.84, 0.20, 0.99, 0.90)
    legend1.AddEntry(mapsGraph, "Maps", "l")
    legend1.AddEntry(vmsizeGraph, "VmSize", "l")
    legend1.AddEntry(vmrssGraph, "VmRSS", "l")
    legend1.AddEntry(vmdataGraph, "VmData", "l")

    legend1.AddEntry(sbrkGraph, "MallocSbrk", "l")
    legend1.AddEntry(inuseGraph, "MallocInuse", "l")
    #legend1.AddEntry(vmlibGraph, "VmLib",          "l");
    legend1.AddEntry(mmapGraph, "MallocMmap", "l")
    legend1.AddEntry(freeGraph, "MallocFree", "l")
    legend1.AddEntry(holeGraph, "Freed-Holes", "l")
    legend1.AddEntry(vmstkGraph, "VmStk", "l")
    legend1.AddEntry(vmexeGraph, "VmExe", "l")
    legend1.AddEntry(vmlckGraph, "VmLck", "l")
    legend1.Draw()

    #multiGraph1.Draw("ALg")
    #title.DrawPaveLabel(x1,y1,x2,y2,"Process Memory Usage Charts","brNDC");

    #Drawing upper-left corner Pad1 of the report
    pad2.cd()
    pad2.SetGridx()
    pad2.SetGridy()

    infoTree.Draw("total_hole_memory:scan_number", "", "goff")
    holeGraph = TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(),
                       infoTree.GetV1())
    holeGraph.SetLineColor(9)
    holeGraph.SetLineWidth(1)
    holeGraph.SetFillStyle(3004)
    holeGraph.SetFillColor(5)
    holeGraph.SetName("total_hole_memory")

    mallocTree.Draw("malloc_free:scan_number", "", "goff")
    freeGraph = TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(),
                       mallocTree.GetV1())
    freeGraph.SetLineColor(11)
    freeGraph.SetLineWidth(1)
    freeGraph.SetFillStyle(3004)
    freeGraph.SetFillColor(5)
    freeGraph.SetName("malloc_free")

    pad2.cd()
    multiGraph2.Add(holeGraph)
    multiGraph2.Add(freeGraph)
    #multiGraph2.Add(sbrkGraph);
    #multiGraph2.Add(mmapGraph);

    #multiGraph2.SetTitle("Free and Marked Holes Memory Graph");
    title.DrawPaveLabel(x1, y1, x2, y2, "Malloc Free and Marked Holes Memory",
                        "brNDC")

    multiGraph2.Draw("ALg")
    hist = multiGraph2.GetHistogram()
    hist.SetXTitle("Event Number")
    hist.SetYTitle("Memory, kb")

    legend2 = TLegend(0.9, 0.30, 0.99, 0.90)
    legend2.AddEntry(freeGraph, "Free", "l")
    legend2.AddEntry(holeGraph, "Holes", "l")
    #legend2.AddEntry(inuseGraph, "Inuse",  "l");
    #legend2.AddEntry(mmapGraph,  "Mmap",  "l");
    #legend2.AddEntry(sbrkGraph,  "Sbrk",  "l");

    legend2.Draw()
    #multiGraph2.Draw("ALg")
    #title.DrawPaveLabel(x1,y1,x2,y2,"Malloc Memory Usage and Deallocation Charts","brNDC");

    #PAD3
    pad3.cd()
    pad3.SetLogz()
    memHist1.Draw("lego2")
    #title.DrawPaveLabel(x1,y1,x2,y2,"TH2I-LEGO2","brNDC");

    mem_canvas.SetBorderSize(1)
    #mem_canvas.Modified()
    mem_canvas.Update()
    mem_canvas.Print(".pdf")
    mem_canvas.Print(".C")
Ejemplo n.º 58
0
def fitSlo10(tree,theCut):

    theCut += " && !isEnr"

    # scatter plot
    h0 = wl.H2D(tree,"h0",100,0,20,500,0,200,"fitSlo:trapENFCal",theCut)

    # -- 10 peak --
    fitModel10 = "[0] + [1]*x + [2]*x**2 + [3] * exp(-1.0 * ((x-[4])**2 / (2 * [5]**2)) )"

    h1 = wl.H1D(tree,"h1",20,9.5,11.5,"trapENFCal",theCut)
    h1.SetLineColor(4)

    # f1 = TF1("f1","gaus",10,11)
    # h1.Fit("f1","L") # use to set initial guesses

    f1 = TF1("f1", fitModel10, 9.5,11)
    wl.SetPars(f1,[-209, 41, -2, 28, 10.3, 0.135])
    f1.SetLineColor(4)
    h1.Fit("f1","Lq")
    [p0,p1,p2,norm1,mu,sig] = wl.GetPars(f1)
    # print wl.GetPars(f1)

    h2 = wl.H1D(tree,"h2",20,9.5,11.5,"trapENFCal",theCut+" && fitSlo < 18")
    f2 = TF1("f2", fitModel10, 9.5,11)
    wl.SetPars(f2,[-209, 41, -2, 28, 10.3, 0.135])
    f2.SetLineColor(2)
    h2.Fit("f2","Lq")
    [p0,p1,p2,norm2,mu,sig] = wl.GetPars(f2)

    retention1 = 100*norm2/norm1


    # -- 6.54 (Fe55) peak --
    # TODO: This doesn't work well.  wait till you're using RooFit.

    fitModel6 = "[0] * x + [1] * exp( -1.0 * ((x - [2])**2 / (2 * [3]**2)) )"
    # fitModel6 = "[0] * exp( -1.0 * ((x - [1])**2 / (2 * [2]**2)) )"

    h3 = wl.H1D(tree,"h3",20,5.5,7.5,"trapENFCal",theCut)

    # f3 = TF1("f3","gaus",6,7)
    # h3.Fit("f3","L") # use to set initial guesses

    # f3 = TF1("f3", fitModel6, 6,7)
    # wl.SetPars(f3,[-1, 19.4, 6.47, 0.631])
    # f3.SetLineColor(4)
    # h3.Fit("f3","Lq")
    # [lin,norm3,mu,sig] = wl.GetPars(f3)
    #
    # h4 = wl.H1D(tree,"h4",20,5.5,7.5,"trapENFCal",theCut+" && fitSlo < 18")
    # f4 = TF1("f4", fitModel6, 6,7)
    # wl.SetPars(f4,[-1, 19.4, 6.47, 0.631])
    # f4.SetLineColor(2)
    # h4.Fit("f4","Lq")
    # [lin,norm4,mu,sig] = wl.GetPars(f4)

    # retention2 = 100*norm4/norm3
    # print "norm3 %.2f  norm4 %.2f  retention2: %.2f" % (norm3, norm4, retention2)


    # -- Plots --
    c1 = TCanvas("c1","Bob Ross's Canvas",1200,600)

    # c1.Divide(3,1,0.00001) # TPad::Divide
    c1.Divide(2,1,0.00001)
    c1.cd(1)
    gPad.SetLogz()
    h0.SetMinimum(1)
    h0.Draw("COLZ")

    c1.cd(2)
    h1.SetLineColor(4) # blue
    h1.Draw()
    h2.SetLineColor(2) # red
    h2.Draw("same")

    l1 = TLegend(0.6,0.6,0.87,0.92)
    l1.AddEntry(h1,"basic","l")
    l1.AddEntry(h2,"+fitSlo < 20","l")
    l1.AddEntry(h2,"Retention: %.3f" % retention1,"")
    l1.Draw("same")

    # c1.cd(3)
    # h3.Draw()
    # h4.SetLineColor(2) # red
    # h4.Draw("same")
    #
    # l2 = TLegend(0.6,0.6,0.87,0.92)
    # l2.AddEntry(h3,"basic","l")
    # l2.AddEntry(h4,"+fitSlo < 20","l")
    # l2.AddEntry(h4,"Retention: %.3f" % retention2,"")
    # l2.Draw("same")

    c1.Print("./plots/ds1-fitSlo.pdf")