1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, 1900.0, 2000.0,
    2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0, 2800.0, 2900.0,
    3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0, 3700.0, 3800.0,
    3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0, 4600.0, 4700.0,
    4800.0, 4900.0, 5000.0, 5100.0, 5200.0
])
significances = array('d', [
    0.0, 0.0, 0.0, 0.0, 0.0, 1.4301, 2.35386, 2.02192, 0.911242, 0.0, 0.0,
    0.0366119, 0.422815, 0.404487, 0.0, 0.0, 0.0, 0.0, 0.0, 0.360739, 0.296693,
    0.206474, 0.717595, 1.39978, 1.65206, 1.39911, 0.912702, 0.328027, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
])

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

graph_sig = TGraph(len(masses), masses, significances)
graph_sig.GetXaxis().SetTitle("qq resonance mass [GeV]")
graph_sig.GetYaxis().SetTitle("Significance")
graph_sig.SetLineWidth(2)
graph_sig.SetLineColor(kRed)
graph_sig.SetMarkerStyle(21)
graph_sig.SetMarkerSize(1)
graph_sig.SetMarkerColor(kBlue)
#graph_sig.GetYaxis().SetRangraph_sig.SetMarkerStyle(20)geUser(1e-03,2e+02)
graph_sig.GetXaxis().SetNdivisions(1005)

gStyle.SetOptTitle(0)
c = TCanvas("c", "", 800, 800)
c.cd()

graph_sig.Draw("ALP")
Ejemplo n.º 2
0
from array import array

n = count
x, y = array('d'), array('d')

#for i in range( n ):
coutn = 0
for i in fileIn:
    j = i.split()
    print j
    x.append(float(j[0]))
    y.append(float(j[1]))
    print(' i %f %f %f ' % (coutn, x[coutn], y[coutn]))
    coutn += 1
fileIn.close()
gr = TGraph(n, x, y)
gr.SetLineColor(2)
gr.SetLineWidth(4)
gr.SetMarkerColor(4)
gr.SetMarkerStyle(21)
gr.SetTitle('a simple graph')
gr.GetXaxis().SetTitle('X title')
gr.GetYaxis().SetTitle('Y title')
#gr.Draw( 'ACP' )
#c1.SaveAs("test.png")

fileIn = open("cutoffscale.dat", "read")
xx, yy = array('d'), array('d')
coutn = 0
for i in fileIn:
    j = i.split()
Ejemplo n.º 3
0
def makeLimitPlot(output,obs,exp,chan,printStats=False):

	fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")

	obsLimits = {}
	
	for obsFile in obs:
		if 'width' in obsFile:
			width = obsFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'
		obsLimits[width] = createObsGraph(obsFile)	

        if  SMOOTH:
		for width,obsGraph in obsLimits.iteritems():
                	smooth_obs=TGraphSmooth("normal")
                	GraphObs_nonSmooth=obsGraph
                	obsLimits[width]=copy.deepcopy(smooth_obs.SmoothSuper(GraphObs_nonSmooth,"linear",0,0.005))
                	obsLimits[width].SetLineWidth(3)


	expLimits = {}
	
	for expFile in exp:
		if 'width' in expFile:
			width = expFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'	
		expLimits[width] = createExpGraph(expFile)	

    	cCL=TCanvas("cCL", "cCL",0,0,600,450)
    	gStyle.SetOptStat(0)
	gStyle.SetPadRightMargin(0.063)
	gStyle.SetPadLeftMargin(0.14)
	gStyle.SetPadBottomMargin(0.12)
	
    	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
    	plotPad.Draw()	
    	plotPad.cd()


     	smoother=TGraphSmooth("normal")
    	smoother2=TGraphSmooth("normal")
	   

    
    	zprimeX=[]
    	zprimeY=[]
    	fileZPrime=open('tools/xsec_ssm.txt','r')
    	for entries in fileZPrime:
        	entry=entries.split()
        	zprimeX.append(float(entry[0]))
        	zprimeY.append(float(entry[1])/1928)
    	zpX=numpy.array(zprimeX)
    	zpY=numpy.array(zprimeY)
    	GraphZPrime=TGraph(len(zprimeX),zpX,zpY)
    	GraphZPrimeSmooth=smoother2.SmoothSuper(GraphZPrime,"linear")
    	GraphZPrimeSmooth.SetLineWidth(3)
    	GraphZPrimeSmooth.SetLineColor(ROOT.kGreen+3)
    	GraphZPrimeSmooth.SetLineStyle(2)

    	zprimePsiX=[]
    	zprimePsiY=[]
    	fileZPrimePsi=open('tools/xsec_psi.txt','r')
    	for entries in fileZPrimePsi:
        	entry=entries.split()
        	zprimePsiX.append(float(entry[0]))
        	zprimePsiY.append(float(entry[1])/1928)

   	zpPsiX=numpy.array(zprimePsiX)
	zpPsiY=numpy.array(zprimePsiY)
    	GraphZPrimePsi=TGraph(len(zprimePsiX),zpPsiX,zpPsiY)
    	GraphZPrimePsiSmooth=smoother.SmoothSuper(GraphZPrimePsi,"linear")
   	GraphZPrimePsiSmooth.SetLineWidth(3)
    	GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

#Draw the graphs:
    	plotPad.SetLogy()
    	DummyGraph=TH1F("DummyGraph","",100,200,5500)
    	DummyGraph.GetXaxis().SetTitle("M [GeV]")
	if SPIN2:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] G_{KK} / #sigma#upoint#font[12]{B}] Z")
	else:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")



    	gStyle.SetOptStat(0)
    	DummyGraph.GetXaxis().SetRangeUser(200,5500)

    	DummyGraph.SetMinimum(1e-8)
    	DummyGraph.SetMaximum(3e-4)
    	DummyGraph.GetXaxis().SetLabelSize(0.055)
    	DummyGraph.GetXaxis().SetTitleSize(0.055)
   	DummyGraph.GetXaxis().SetTitleOffset(1.05)
    	DummyGraph.GetYaxis().SetLabelSize(0.055)
    	DummyGraph.GetYaxis().SetTitleSize(0.055)
    	DummyGraph.GetYaxis().SetTitleOffset(1.3)

    	DummyGraph.Draw()

    	plCMS=TPaveLabel(.16,.76,.27,.83,"CMS","NBNDC")
#plCMS.SetTextSize(0.8)
    	plCMS.SetTextAlign(12)
    	plCMS.SetTextFont(62)
    	plCMS.SetFillColor(0)
    	plCMS.SetBorderSize(0)
    
    	plCMS.Draw()

    	plPrelim=TPaveLabel(.16,.76,.27,.82,"Preliminary","NBNDC")
    	plPrelim.SetTextSize(0.6)
    	plPrelim.SetTextAlign(12)
    	plPrelim.SetTextFont(52)
    	plPrelim.SetFillColor(0)
    	plPrelim.SetBorderSize(0)
#    	plPrelim.Draw()

    	leg=TLegend(0.420517,0.7,0.85,0.878644,"","brNDC")   
    	legWidth=TLegend(0.625,0.5,0.9,0.7,"width","brNDC")   
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")   
    	leg.SetTextSize(0.0425)
    	legWidth.SetTextSize(0.0425)
	colors = {'01':ROOT.kBlue,'03':ROOT.kRed,'05':ROOT.kGreen+3,'10':ROOT.kOrange}
#	for width in sorted(obsLimits):
#		obsGraph = obsLimits[width]
#		if colors.has_key(width):
#			obsGraph.SetLineColor(colors[width])
#		obsGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(obsGraph,"Observed 95% CL limit width 0.6%","l")
#		else:	
#			leg.AddEntry(obsGraph,"Observed 95%% CL limit width %d%%"%int(width),"l")
#
#	for width  in sorted(expLimits):
#		expGraph = expLimits[width]
#		if colors.has_key(width):
#			expGraph.SetLineColor(colors[width])
#		expGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(expGraph,"Expected 95% CL limit width 0.6%, median","l")
#		else:	
#			leg.AddEntry(expGraph,"Expected 95%% CL limit width %d%%, median"%(int(width)),"l")

	
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		obsGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(obsGraph,"Obs. 95% CL limit","l")

	for width  in sorted(expLimits):
		expGraph = expLimits[width]
		if colors.has_key(width):
			expGraph.SetLineColor(colors[width])
		expGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(expGraph,"Exp. 95% CL limit, median","l")
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		if width == '0.006':
			legWidth.AddEntry(obsGraph,"0.6%","l")
		else:	
			legWidth.AddEntry(obsGraph,"%d%%"%int(width),"l")


    	if not SPIN2:
        	GraphZPrimeSmooth.Draw("lsame")
        	GraphZPrimePsiSmooth.Draw("lsame")

	leg1=TLegend(0.625,0.35,0.825,0.5,"","brNDC")
	leg1.SetTextSize(0.0375)
	leg1.AddEntry(GraphZPrimeSmooth,"Z'_{SSM} (width 2.97%)","l")	
	leg1.AddEntry(GraphZPrimePsiSmooth,"Z'_{#Psi} (width 0.53%)","l")	
	
    	leg1.SetLineWidth(0)
    	leg1.SetLineStyle(0)
    	leg1.SetLineColor(0)
    	leg1.SetFillStyle(0)
    	leg1.SetBorderSize(0)

	leg1.Draw()

    	cCL.SetTickx(1)
    	cCL.SetTicky(1)
    	cCL.RedrawAxis()
    	cCL.Update()
    
    	#plCMS.Draw()
  	plotPad.SetTicks(1,1)
	plotPad.RedrawAxis()	

	

    	leg.SetLineWidth(0)
    	leg.SetLineStyle(0)
    	leg.SetLineColor(0)
    	leg.Draw("hist")
    	legWidth.SetLineWidth(0)
    	legWidth.SetLineStyle(0)
    	legWidth.SetLineColor(0)
    	legWidth.SetFillStyle(0)
	legWidth.SetNColumns(2)
    	legWidth.Draw("hist")


	if "Moriond" in output:
         	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.885,.9,.99,"36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.27,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
	else:
 	      	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.905,.9,.99,"13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.905,.9,.99,"2.7 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.4,.905,.9,.99,"12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")

    	plLumi.SetTextSize(0.5)
    	plLumi.SetTextFont(42)
    	plLumi.SetFillColor(0)
    	plLumi.SetBorderSize(0)
    	plLumi.Draw()
    

	plotPad.RedrawAxis()
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		obsGraph.SetName("graphObs%s"%width)
		obsGraph.Write("graphObs%s"%width)
	for width in sorted(expLimits):
		expGraph = expLimits[width]
		expGraph.SetName("graphExp%s"%width)
		expGraph.Write("graphExp%s"%width)


   	fileForHEPData.Write()
	fileForHEPData.Close() 


    
    	cCL.Update()
    	printPlots(cCL,output)
Ejemplo n.º 4
0
def plot_graph_yield(yield_signal, yield_signal_err, binmin, binmax):
    gr = TGraph(0)
    _ = gr.GetN()
    print(yield_signal, yield_signal_err, binmin, binmax)
Ejemplo n.º 5
0
    # Fill program use arrays with data
    Z.append(Data[0] / 1000.)
    Bx.append(Data[1])
    By.append(Data[2])
    Bz.append(Data[3])

# Close file
fIN.close()

# Get the max and mins in the field
[MaxListInd, MaxListBy] = FindMaxAndMins(Z, By)
[MaxByZ, MaxBy] = FindMinMaxFromFit(MaxListInd, Z, By, None)

# Save a graph of the points found
gMaxBy = TGraph(len(MaxByZ), array('d', MaxByZ), array('d', MaxBy))
gMaxBy.SetName('MaxBy')
gMaxBy.SetTitle('Calculated Max By')
gMaxBy.GetXaxis().SetTitle('Position [m]')
gMaxBy.GetYaxis().SetTitle('B_{Y} [T]')
gMaxBy.Write()

# TGraphs for measured Bx By and Bz vs Z
gBx = TGraph(len(Z), Z, Bx)
gBy = TGraph(len(Z), Z, By)
gBz = TGraph(len(Z), Z, Bz)

gBx.SetTitle('Measured magnetic field B_{X}')
gBx.GetXaxis().SetTitle('Position [m]')
gBx.GetYaxis().SetTitle('#B_{x} [T]')
gBx.SetName("Bx")
Ejemplo n.º 6
0
            if threshold[1] < halfMax:
                thrArrayFallingEdge.append(threshold[0])
                break  # Only one threshold is needed, leave loop

    trimFallingEdge.append(thrArrayFallingEdge)

# Turn array of trimming value arrays with pixels in the sub array into transposed array ( Pix1(trimDac[0-31]), Pix2(),.,,,Pix48(trimDac[0-31]))
pxlTrimFallingEdge = [list(trim) for trim in zip(*trimFallingEdge)]

# Draw graphs on canvas
c1 = TCanvas("graph", "graph", 1024, 768)

graphs = []
for pxl in pxlTrimFallingEdge:
    graphs.append(
        TGraph(32, array('d', range(32)), array('d', pxl))
    )  # Generate graph with trimDACs on x-axis and falling edge position (in threshold-steps) on y-axis

for i, graph in enumerate(graphs):
    graph.SetLineColor(i)
    if i == 0:
        graph.SetTitle('Trim Scan;Trim (DAC);Falling Edge (Threshold)')
        #graph.GetYaxis().SetRangeUser(0,max(maxHitsPerPixTrim[trim])*1.1)
        graph.Draw("APL")
    else:
        graph.Draw("PL")

pickle.dump(pxlTrimFallingEdge,
            open(str(sys.path[0]) + "/trimDacFallingEdge.pickle", "w"))

raw_input("Press any key to exit")
Ejemplo n.º 7
0
for n in range(0, stepNum + 1):

    currentFreq = startFreq + n * stepSize
    frequencies.append(currentFreq)

    f = TFile('Freq' + str(currentFreq) + '.root')
    t = f.Get('neutronend')
    hist = TH1D('hist', "", 400, -1, 1)

    t.Draw("Szend>>hist", "stopID==-1")

    print("Mean Szend: ")
    print(hist.GetMean())
    meanSzend.append(hist.GetMean())

x = array("d", frequencies)
y = array("d", meanSzend)

#f1 = TF1("f1", "-.5 - .5*cos((100*(pi)+8)*(29.16469-x))",29.16, 29.17)

graph = TGraph(stepNum + 1, x, y)
graph.SetTitle("Szend Of Ramsey Cycles in Frequency Range from " +
               str(startFreq) + " to " + str(endFreq))
graph.GetXaxis().SetTitle("BField Frequency")
graph.GetYaxis().SetTitle("Mean Szend")
canvas = TCanvas("canvas", "canvas", 700, 500)
graph.Draw()
#f1.Draw("same")

raw_input("Press Enter to Finish")
Ejemplo n.º 8
0
    hhh = TH2D("hhh","hhh",modmax-modmin+1,modmin-0.5,modmax+0.5,chanmax-chanmin+1,chanmin-0.5,chanmax+0.5)

if vsbin: tree.Draw(data,cut_cond,"goff",15)
else: tree.Draw(data,cut_cond,"goff")

if (not opt2d and tree.GetSelectedRows() <= 1) or tree.GetSelectedRows() <= 0:
    print "Not enough points to plot"
    sys.exit(2)

if vsbin:
    if tree.GetSelectedRows() >= 15:
        print "Maximum number of bins is 15"


if line or noline:
    gr = TGraph(tree.GetSelectedRows(),tree.GetV2(),tree.GetV1())
    gr.SetTitle(modulename +" " + " Channel "+ str(chan_n) +" " + gainvalue + titsuff)
    gr.SetMarkerStyle(20)
    gr.SetMarkerSize(1.3)
    gr.SetMarkerColor(2)
    gr.SetLineColor(2)
    gr.GetXaxis().SetNoExponent(kTRUE)
    if one_run: gr.GetXaxis().SetTitle("Lumi")
    else: gr.GetXaxis().SetTitle("Runs")
    if noline: gr.Draw("ap")
    else: gr.Draw("apl")

elif opt2d:
    nentries = tree.GetEntries()
    hhh.SetName(modulename)
    hhh.SetTitle(partname +" " + gainvalue + titsuff)
def Make_TDC_Energy(Fname1,Fname2,Title, XaxisT,low,high,freq,RootName):
    
    f_fc=TFile(Fname1)
    f_tdc=TFile(Fname2)
    gr_Inregral_fc=f_fc.Get("Graph_Integral")
    gr_Inregral_tdc=f_tdc.Get("Graph_Integral")

    FNumber=int((high-low)/freq)
    
    xpoint=array("d",xrange(0,FNumber))
    ypoint=array("d",xrange(0,FNumber))




        
        
    num=-1
    for iAmp in range(low,high,freq):
        num+=1
        xpoint[num]=gr_Inregral_fc.Eval(iAmp)/3800;print xpoint[num]
        ypoint[num]= gr_Inregral_tdc.Eval(iAmp); print ypoint[num]

    TwoDGraph=TGraph(len(xpoint), xpoint,ypoint)
    canvas_Integral = MakeCanvas("can1","can1",800,800)
    TwoDGraph.SetTitle("Time [ns] vs. Energy [GeV]  ")
    TwoDGraph.SetMarkerStyle(22)
    TwoDGraph.SetMarkerColor(3)
    TwoDGraph.SetMarkerSize(2)
    TwoDGraph.GetXaxis().SetTitle("Energy [GeV]")
    TwoDGraph.GetYaxis().SetTitle("Time [ns]")
    TwoDGraph.GetYaxis().SetRangeUser(TMath.MinElement(len(xpoint),TwoDGraph.GetY())/1.3, TMath.MaxElement(len(xpoint),TwoDGraph.GetY()) * 1.2)
    TwoDGraph.Draw()
    canvas_Integral.SaveAs("Final_Time_Energy.pdf")
Ejemplo n.º 10
0
def btag_efficiency(cut, year, pT_range=None):
    ### Preliminary Operations ###
    from root_numpy import hist2array
    from sklearn.metrics import roc_curve
    import numpy as np
    genPoints = [
        1600, 1800, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 7000,
        8000
    ]
    signal = ['ZpBB_M' + str(x) for x in genPoints]
    btag_vars = BTAGGEFFVARS
    nbins = 100
    min_, max_ = 0., 1.

    treeRead = True
    channel = cut
    isAH = False
    for k in sorted(alias.keys(), key=len, reverse=True):
        if k in cut:
            cut = cut.replace(k, aliasSM[k])

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

    ### Create and fill MC histograms ###
    for i, s in enumerate(back + signal):
        tree[s] = TChain("tree")
        for j, ss in enumerate(sample[s]['files']):
            if year == "run2" or year in ss:
                ### to run on big ntuples:
                #k = 0
                #while True:
                #    if os.path.exists("/eos/user/m/msommerh/Zprime_to_bb_analysis/" + ss + "/" + ss+ "_flatTuple_{}.root".format(k)):
                #        tree[s].Add("/eos/user/m/msommerh/Zprime_to_bb_analysis/" + ss + "/" + ss + "_flatTuple_{}.root".format(k))
                #        k += 1
                #    else:
                #        print "found {} files for sample:".format(k), ss
                #        break
                #if k == 0:
                #    print '  WARNING: files for sample', ss , 'do not exist, continuing'
                #    return True
                ### end big ntuples
                tree[s].Add(NTUPLEDIR + ss +
                            ".root")  ## to run on skimmed ntuples
        for var in btag_vars:
            hist[s + "_" + var] = TH1F(s + "_" + var,
                                       ";efficiency; mistag rate", nbins, min_,
                                       max_)
            for suf in ["_1", "_2"]:
                temp_hist = TH1F(s + "_" + var + suf,
                                 ";efficiency; mistag rate", nbins, min_, max_)
                temp_hist.Sumw2()
                if pT_range is not None:
                    pT_cut = " && jpt" + suf + ">=" + str(
                        pT_range[0]) + " && jpt" + suf + "<" + str(pT_range[1])
                else:
                    pT_cut = ""
                if s in signal:
                    flavourcut = " && abs(jflavour" + suf + ")==5"
                else:
                    flavourcut = " && (abs(jflavour" + suf + ")<4 || abs(jflavour" + suf + ")==9 || abs(jflavour" + suf + ")==21)"  ## FIXME this currently excludes charms
                if len(cut) == 0: flavourcut = flavourcut[4:]
                cutstring = "(eventWeightLumi)" + "*(" + cut + flavourcut + pT_cut + ")"
                tree[s].Project(s + "_" + var + suf, var + suf, cutstring)
                if not tree[s].GetTree() == None:
                    hist[s + "_" + var].SetOption(
                        "%s" % tree[s].GetTree().GetEntriesFast())
                #hist[s][var+suf].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0)
                hist[s + "_" + var].Add(temp_hist)
                temp_hist.Delete()

    fpr = {}
    tpr = {}
    thr = {}
    for var in btag_vars:
        hist_sig = TH1F(var + "_sig", ";efficiency; mistag rate", nbins, min_,
                        max_)
        hist_bkg = TH1F(var + "_bkg", ";efficiency; mistag rate", nbins, min_,
                        max_)
        for i, s in enumerate(signal):
            hist_sig.Add(hist[s + "_" + var])
        for i, s in enumerate(back):
            hist_bkg.Add(hist[s + "_" + var])
        sig_arr, sig_edges = hist2array(hist_sig, return_edges=True)
        bkg_arr, bkg_edges = hist2array(hist_bkg, return_edges=True)
        assert len(sig_edges[0]) == len(bkg_edges[0])
        vals = []
        sig_weights = []
        bkg_weights = []
        for j, entry in enumerate(sig_edges[0][:-1]):
            vals.append(0.5 * (sig_edges[0][j] + sig_edges[0][j + 1]))
            sig_weights.append(sig_arr[j])
            bkg_weights.append(bkg_arr[j])
        sig_labels = np.ones(len(sig_weights))
        bkg_labels = np.zeros(len(bkg_weights))
        fpr[var], tpr[var], thr[var] = roc_curve(np.concatenate(
            (sig_labels, bkg_labels)),
                                                 np.array(vals + vals),
                                                 sample_weight=np.concatenate(
                                                     (sig_weights,
                                                      bkg_weights)))

    canv = TCanvas('c', 'c', 500, 650)
    canv.SetGrid()

    graphs = {}
    for j, var in enumerate(btag_vars):
        graphs[var] = TGraph(len(tpr[var]), tpr[var], fpr[var])
        graphs[var].SetLineColor(btag_colors[var])
        graphs[var].SetMarkerStyle(1)
        graphs[var].SetMarkerColor(btag_colors[var])
        graphs[var].SetLineWidth(2)

        graphs[var].SetTitle(";b tagging efficiency;mistag rate (udsg jets)")
        graphs[var].GetXaxis().SetLimits(0., 1.)
        graphs[var].GetHistogram().SetMinimum(1e-4)
        graphs[var].GetHistogram().SetMaximum(1.)
        graphs[var].GetYaxis().SetTitleOffset(1.4)
    leg = TLegend(0.65, 0.15, 0.9, 0.35)
    for j, var in enumerate(btag_vars):
        leg.AddEntry(graphs[var], btag_titles[var])
        if j == 0:
            graphs[var].Draw("APL")
        else:
            graphs[var].Draw("PL SAME")

    latex = TLatex(0.05, 0.5,
                   str(pT_range[0]) + '<p_{T}<' + str(pT_range[1]) + ' GeV')
    latex.SetTextSize(0.043)
    latex.Draw()

    leg.Draw()
    canv.SetLogy()

    if pT_range is not None:
        pt_suff = "pT{}to{}".format(pT_range[0], pT_range[1])
    else:
        pt_suff = "incl_pT"
    canv.Print("plots/btag_eff/ROC_{}_{}.png".format(year, pt_suff))
    canv.Print("plots/btag_eff/ROC_{}_{}.pdf".format(year, pt_suff))
Ejemplo n.º 11
0
def trigger_efficiency(year, separate=False):
    from root_numpy import root2array, fill_hist
    from aliases import triggers, triggers_PFHT, triggers_Jet, triggers_BTag
    import numpy as np
    #spec_triggers = {"PFHT": triggers_PFHT, "Jet": triggers_Jet, "BTag": triggers_BTag}
    spec_triggers = {
        "HT/Jet": "(" + triggers_PFHT + " || " + triggers_Jet + ")",
        "BTag": triggers_BTag
    }
    spec_triggers_colors = {
        "PFHT": 418,
        "Jet": 4,
        "BTag": 6,
        "HT/Jet": 4,
        "total": 2
    }

    hist_pass = TH1F("pass", "pass", 100, 0., 10000.)
    if separate:
        hist_pass_spec = {}
        for trig in spec_triggers.keys():
            hist_pass_spec[trig] = TH1F("pass_" + trig, "pass_" + trig, 100,
                                        0., 10000.)
    hist_all = TH1F("all", "all", 100, 0., 10000.)

    file_list = []

    data_2016_letters = ["B", "C", "D", "E", "F", "G", "H"]
    data_2017_letters = ["B", "C", "D", "E", "F"]
    data_2018_letters = ["A", "B", "C", "D"]

    sample_names = []
    if year == '2016':
        letters = data_2016_letters
    elif year == '2017':
        letters = data_2017_letters
    elif year == '2018':
        letters = data_2018_letters
    else:
        print "unknown year"
        sys.exit()
    for letter in letters:
        #dir_content =  os.listdir(TRIGGERDIR+"/SingleMuon_{}_{}/".format(year, letter)) ## intended to run directly on ntuples
        #for entry in dir_content:
        #    if "_flatTuple" in entry: file_list.append(TRIGGERDIR+"/SingleMuon_{}_{}/".format(year, letter)+entry)
        file_list.append(TRIGGERDIR +
                         "/SingleMuon_{}_{}.root".format(year, letter))
        print "appending:", TRIGGERDIR + "/SingleMuon_{}_{}.root".format(
            year, letter)

    for file_name in file_list:
        temp_array = root2array(file_name,
                                treename='tree',
                                branches='jj_mass_widejet',
                                selection="jj_deltaEta_widejet<1.1")
        fill_hist(hist_all, temp_array)
        temp_array = root2array(file_name,
                                treename='tree',
                                branches='jj_mass_widejet',
                                selection="jj_deltaEta_widejet<1.1 && " +
                                triggers)
        fill_hist(hist_pass, temp_array)
        if separate:
            for trig in spec_triggers.keys():
                temp_array = root2array(
                    file_name,
                    treename='tree',
                    branches='jj_mass_widejet',
                    selection="jj_deltaEta_widejet<1.1 && " +
                    spec_triggers[trig])
                fill_hist(hist_pass_spec[trig], temp_array)
        temp_array = None

    import array
    from aliases import dijet_bins
    binning = []
    for num in dijet_bins:
        if num <= 10000: binning.append(num)
    #binning = range(0,1500,100)+range(1500,2000,100)+range(2000,3100,150)+range(3100,10000,300)
    binning_ = array.array('d', binning)
    hist_pass2 = hist_pass.Rebin(
        len(binning_) - 1, "hist_pass_rebinned", binning_)
    hist_all2 = hist_all.Rebin(
        len(binning_) - 1, "hist_all_rebinned", binning_)

    if separate:
        hist_pass_spec2 = {}
        for trig in spec_triggers.keys():
            hist_pass_spec2[trig] = hist_pass_spec[trig].Rebin(
                len(binning_) - 1, "hist_pass_" + trig + "_rebinned", binning_)

    hist_pass2.Sumw2()
    hist_all2.Sumw2()
    eff = TGraphAsymmErrors()
    eff.Divide(hist_pass2, hist_all2)

    eff.SetMarkerColor(spec_triggers_colors["total"])
    if separate:
        eff.SetMarkerStyle(5)
    else:
        eff.SetMarkerStyle(1)
    eff.SetLineColor(spec_triggers_colors["total"])
    eff.SetLineWidth(2)

    if separate:
        eff_spec = {}
        for trig in spec_triggers.keys():
            hist_pass_spec2[trig].Sumw2()
            eff_spec[trig] = TGraphAsymmErrors()
            eff_spec[trig].Divide(hist_pass_spec2[trig], hist_all2)
            eff_spec[trig].SetMarkerColor(spec_triggers_colors[trig])
            eff_spec[trig].SetMarkerStyle(1)
            eff_spec[trig].SetLineColor(spec_triggers_colors[trig])
            eff_spec[trig].SetLineWidth(2)

    one_line = TGraph()
    one_line.SetPoint(0, 0., 1.)
    one_line.SetPoint(1, 10000., 1.)
    one_line.SetLineStyle(2)

    c1 = TCanvas("c1", "Trigger Efficiency", 800, 800)
    c1.cd(1)
    eff.Draw("AP")
    one_line.Draw("L")
    eff.SetTitle(";m_{jj} (GeV);trigger efficiency")
    eff.SetMinimum(0.)
    eff.SetMaximum(1.4)  #0.65

    ## new
    dijet_bin_centers = []
    for b, lthr in enumerate(dijet_bins[:-1]):
        if lthr < 1200 or lthr > 2500: continue
        dijet_bin_centers.append(0.5 * (dijet_bins[b] + dijet_bins[b + 1]))
    print "total trigger efficiency:"
    for cval in dijet_bin_centers:
        print cval, ":", eff.Eval(cval)
    ## end new

    if separate:
        leg = TLegend(0.65, 0.75, 0.9, 0.95)
        leg.AddEntry(eff, "total")
        for trig in spec_triggers.keys():
            leg.AddEntry(eff_spec[trig], trig + "-based")
            eff_spec[trig].Draw("P SAME")
            ## new
            print trig, "trigger efficiency"
            for cval in dijet_bin_centers:
                print cval, ":", eff_spec[trig].Eval(cval)
            ## end new
        leg.Draw()

    eff.GetXaxis().SetTitleSize(0.045)
    eff.GetYaxis().SetTitleSize(0.045)
    eff.GetYaxis().SetTitleOffset(1.1)
    eff.GetXaxis().SetTitleOffset(1.05)
    eff.GetXaxis().SetLimits(700., 5000.)
    c1.SetTopMargin(0.05)
    #drawCMS(-1, "Preliminary", year=year) #Preliminary
    #drawCMS(-1, "Work in Progress", year=year, suppressCMS=True)
    drawCMS(-1, "", year=year, suppressCMS=True)
    drawAnalysis("")

    suffix = ""
    if separate: suffix = "_sep"

    c1.Print("plots/Efficiency/trigger_" + year + suffix + ".pdf")
    c1.Print("plots/Efficiency/trigger_" + year + suffix + ".png")
def main():
    filename = read_file_name("LA_OUTPUT.txt")
    can = TCanvas("can", "can")
    can.SetGrid()
    mg = TMultiGraph()
    nn = 9

    GR = []
    NAME = []
    px, py = array('d'), array('d')
    f = open(filename[2], 'r')
    indicator = 0

    for line in f:
        if (indicator == 0):
            indicator = indicator + 1
            continue

        Name, Total, Pos, Neg, TNum = line.split()
        name = Find_Loca(Name)
        name = Name.replace(Name[name:], "")
        #        print(name)

        px.append((indicator - 1) % 9)
        py.append(float(TNum))
        if ((indicator) % 9 == 0):
            NAME.append(name)
            gr = TGraph(nn, px, py)
            GR.append(gr)
            px, py = array('d'), array('d')
        indicator = indicator + 1


#    print(GR); print(len(GR))
    for i in range(len(GR)):
        GR[i].SetLineWidth(2)
        if "water" in NAME[i]:
            GR[i].SetLineWidth(5)
            GR[i].SetLineColor(1)
            GR[i].SetMarkerColor(1)
        if "wine" in NAME[i]:
            GR[i].SetMarkerColor(2)
            GR[i].SetLineColor(2)
        if "beer" in NAME[i]:
            GR[i].SetMarkerColor(5)
            GR[i].SetLineColor(5)
        if "tea" in NAME[i]:
            GR[i].SetMarkerColor(4)
            GR[i].SetLineColor(4)
        if "coffee" in NAME[i]:
            GR[i].SetMarkerColor(3)
            GR[i].SetLineColor(3)
        if "juice" in NAME[i]:
            GR[i].SetMarkerColor(7)
            GR[i].SetLineColor(7)
        if "COLA" in NAME[i]:
            GR[i].SetMarkerColor(6)
            GR[i].SetLineColor(6)
        GR[i].GetXaxis().SetTitle("days")
        GR[i].SetMarkerStyle(20)
        #        GR[i].Fit("pol4","q")
        mg.Add(GR[i])

    mg.Draw("ALP")

    leg = TLegend(0.65, 0.65, 0.9, 0.8)
    leg.SetBorderSize(0)
    leg.SetFillColor(10)
    for i in range(len(GR)):
        leg_entry = leg.AddEntry(GR[i], NAME[i], "l")
    leg.Draw()
    mg.SetTitle("Total tweets counts at LA")
    mg.GetHistogram().GetXaxis().SetTitle("days")
    mg.GetHistogram().GetXaxis().SetTitleOffset(1)
    mg.GetHistogram().GetXaxis().SetLabelSize(0.03)
    mg.GetHistogram().GetYaxis().SetTitle("Counts")
    mg.GetHistogram().GetYaxis().SetTitleOffset(1.3)
    mg.GetHistogram().GetYaxis().SetLabelSize(0.03)
    mg.GetHistogram().GetXaxis().SetBinLabel(5, "Mon")
    mg.GetHistogram().GetXaxis().SetBinLabel(16, "Tue")
    mg.GetHistogram().GetXaxis().SetBinLabel(28, "Wed")
    mg.GetHistogram().GetXaxis().SetBinLabel(40, "Thu")
    mg.GetHistogram().GetXaxis().SetBinLabel(51, "Fri")
    mg.GetHistogram().GetXaxis().SetBinLabel(63, "Sat")
    mg.GetHistogram().GetXaxis().SetBinLabel(73, "Sun")
    mg.GetHistogram().GetXaxis().SetBinLabel(84, "Mon")
    mg.GetHistogram().GetXaxis().SetBinLabel(96, "Tue")
    #    for i in range(len(GR)):
    #        mg.GetHistogram().GetXaxis().SetBinLabel(i,DAYS)
    #    mg.GetHistogram().GetXaxis().SetLabel("tt")

    can.Modified()
    can.Update()
    # can.GetFrame().SetBorderSize( 12 )
    can.Print("Total_tweet_LA.pdf")
Ejemplo n.º 13
0
def MakeCutPlot(c, cal, var, eb, elo, ehi, vb, vlo, vhi, d2Cut, d1Cut, outPlot,
                fastMode):
    """ Creates a channel-specific energy calibration plot. """

    # Calculate cut vals (assumes plot range is correct)
    h1 = wl.H1D(cal, vb, vlo, vhi, var, d1Cut)
    h1Sum = h1.Integral()
    if h1Sum == 0:
        print(
            "Error: Failed %s, histogram sum is 0 so cannot normalize, setting to [0,0,0,0,0]"
            % (var))
        return 0, 0, 0, 0, 0
    h1.Scale(1 / h1Sum)
    try:
        cut99, cut95, cut01, cut05, cut90 = wl.GetIntegralPoints(h1)
    except:
        print("Error: Failed %s using cut %s, setting to [0,0,0,0,0]" %
              (var, d1Cut))
        return 0, 0, 0, 0, 0
    if fastMode:
        print("Returning fastMode output: ", cut99, cut95, cut01, cut05, cut90)
        return cut99, cut95, cut01, cut05, cut90

    # Generate the plot for inspection.
    c.cd(2)
    gPad.SetLogy(0)
    h1.GetXaxis().SetRangeUser(cut01 - abs(0.25 * cut01),
                               cut99 + abs(0.25 * cut99))
    h1.SetTitle("")
    h1.GetXaxis().SetTitle(var)
    h1.Draw("hist")

    c.cd(1)
    gPad.SetLogy(0)
    cal.Draw(
        "%s:trapENFCal>>b(%d,%d,%d,%d,%.3E,%.3E)" %
        (var, eb + 10, elo - 5, ehi + 5, vb, cut01 - abs(0.25 * cut01),
         cut99 + abs(0.25 * cut99)), d2Cut)

    l1, l2, l3 = TLine(), TLine(), TLine()
    l1.SetLineColor(ROOT.kGreen)
    l2.SetLineColor(ROOT.kRed)
    l3.SetLineColor(ROOT.kMagenta)

    l1.DrawLine(elo - 5, cut99, ehi + 5, cut99)
    l2.DrawLine(elo - 5, cut95, ehi + 5, cut95)
    l2.DrawLine(elo - 5, cut05, ehi + 5, cut05)
    l1.DrawLine(elo - 5, cut01, ehi + 5, cut01)

    c.cd(3)
    x_h1, y_h1 = wl.npTH1D(h1)
    int_h1 = wl.integFunc(y_h1)
    g2 = TGraph(len(x_h1), x_h1, int_h1)
    g2.GetXaxis().SetRangeUser(cut01 - abs(0.3 * cut01),
                               cut99 + abs(0.3 * cut99))
    g2.SetTitle("")
    g2.GetXaxis().SetTitle(var)
    g2.GetYaxis().SetTitle("Percentile")
    g2.Draw("ACP")
    l1.DrawLine(cut99, 0, cut99, 1)
    l2.DrawLine(cut95, 0, cut95, 1)
    l1.DrawLine(cut01, 0, cut01, 1)
    l2.DrawLine(cut05, 0, cut05, 1)

    c.Print(outPlot)
    return cut99, cut95, cut01, cut05, cut90
Ejemplo n.º 14
0
mg.Add(brazil_yellow)
mg.Add(brazil_green)
mg.Draw("a3")

yaxistitle = "#sigma #times A #times BR [pb]"
if particle == "qbh":
    yaxistitle = "#sigma #times A [pb]"

mg.GetXaxis().SetTitle("m_{%s} [GeV]" % particle_symbol)
mg.GetYaxis().SetTitle(yaxistitle)
mg.GetYaxis().SetRangeUser(*y_limits)
mg.GetYaxis().SetTitleOffset(1.35)
mg.GetXaxis().SetTitleOffset(1.2)
mg.GetXaxis().SetNdivisions(508)

brazil_line = TGraph(len(brazil_data), x, mean)
brazil_line.SetLineStyle(7)
brazil_line.SetLineColor(1)
brazil_line.Draw("same")

data_mass_limit_pairs = []
with open(data_cl_file, "r") as data_file:
    for line in data_file.readlines():
        data_mass_limit_pairs.append(tuple(map(float, line.split(":"))))

with open(op.join(args.output_dir, "b_{0}.txt".format(job_id)),
          "a") as out_file:
    for a, b in data_mass_limit_pairs:
        out_file.write("o:{0}:{1}\n".format(a, b / fb2))

data_x, data_y = zip(*sorted(data_mass_limit_pairs, key=itemgetter(0)))
Ejemplo n.º 15
0
avg = 0.0

mags = []

print "Scanning through files"

for f in files:
    for l in f:
        n += 1
        if( n >= 900):
            z += 1
            l.strip()
            avg += float(l)
    mags.append(avg/float(z))
    z   = 0
    avg = 0
    n   = 0

looks_minos()

c1 = TCanvas()
tg = TGraph()
for x in xrange(len(mags)):
    tg.SetPoint(x,temps[x],mags[x])


tg.SetMarkerStyle(6)
tg.Draw("AP")
c1.Update()
c1.Modified()
Ejemplo n.º 16
0
    5100.0, 5200.0, 5300.0, 5400.0, 5500.0, 5600.0, 5700.0, 5800.0, 5900.0,
    6000.0, 6100.0, 6200.0, 6300.0, 6400.0, 6500.0, 6600.0, 6700.0, 6800.0,
    6900.0, 7000.0, 7100.0, 7200.0
])
significances = array('d', [
    0.0, 0.361683, 1.17934, 0.937784, 0.20214, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.351713, 0.54517, 0.698591, 0.877327, 0.877771, 1.01375,
    1.27896, 1.35268, 1.12581, 1.1746, 1.46086, 1.41497, 0.872541, 0.00435573,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0856762, 0.433186, 0.542791,
    0.55899, 0.556067, 0.573986, 0.583046, 0.538931, 0.459697, 0.332036,
    0.152038, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
])

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

graph_sig = TGraph(len(masses), masses, significances)
graph_sig.GetXaxis().SetTitle("qg resonance mass [GeV]")
graph_sig.GetYaxis().SetTitle("Significance (local)")
graph_sig.GetYaxis().SetTitleOffset(1.2)
graph_sig.GetYaxis().SetRangeUser(0., 3.0)
graph_sig.SetLineWidth(2)
graph_sig.SetLineColor(kRed)
graph_sig.SetMarkerStyle(21)
graph_sig.SetMarkerSize(1)
graph_sig.SetMarkerColor(kBlue)
#graph_sig.GetXaxis().SetNdivisions(1005)

gStyle.SetOptTitle(0)
c = TCanvas("c", "", 800, 800)
c.cd()
Ejemplo n.º 17
0
print 'dt ', dt
print 'dx ', dx

print str(dt / (dx * dx)) + '<' + str(1 / D)

C = [Ct0]
X = [0]

for i in range(1, N - 1):
    C.append(random.gauss(Ct0, Ct0 * 0.001))
    X.append(X[-1] + dx)

C.append(C_L)
X.append(L)

FileOutRoot = TFile('Out.root', 'recreate')

for t in range(0, 10000):
    C_tp = [C_0]
    for i in range(1, N - 1):
        C_tp.append(evolution(dt, dx, D, C[i], C[i + 1], C[i - 1]))
    C_tp.append(C_L)

    g = TGraph(N, np.asarray(X), np.asarray(C_tp))
    g.Write('Ct_' + str(t))

    for i in range(0, N):
        C[i] = C_tp[i]

FileOutRoot.Close()
                histoVar2.GetBinContent(iBin) -
                hRefVar['var2'].GetBinContent(iBin)
            ])
relVar = np.array(relVar)
absVar = np.array(absVar)

if doRelVar and removeOutliersRel:
    radius = inputCfg['outputs']['variations']['relative']['outliers'][
        'DBSCAN']['radius']
    minsample = inputCfg['outputs']['variations']['relative']['outliers'][
        'DBSCAN']['minsample']
    _, clLabelsRel = dbscan(relVar,
                            eps=radius,
                            min_samples=minsample,
                            metric='euclidean')
    gRelVarOutliers = TGraph(0)
if doAbsVar and removeOutliersAbs:
    radius = inputCfg['outputs']['variations']['absolute']['outliers'][
        'DBSCAN']['radius']
    minsample = inputCfg['outputs']['variations']['absolute']['outliers'][
        'DBSCAN']['minsample']
    _, clLabelsAbs = dbscan(relVar,
                            eps=radius,
                            min_samples=minsample,
                            metric='euclidean')
    gAbsVarOutliers = TGraph(0)

iPointOutlier, iPointCore = 0, 0
gRelVar, gAbsVar = TGraph(0), TGraph(0)
if doRelVar:
    for iPoint, point in enumerate(relVar):
def CalculateTotalSelectionEfficiencies(self):
    print green('  --> Producing selection efficiencies.')
    gROOT.SetBatch(1)
    ROOT.gErrorIgnoreLevel = kError

    signalcategory = 'fromtau'
    backgroundcategories = ['fromhad', 'unmatched']
    histnametags_per_lepton = {
        'el': [''] + [signalcategory] + backgroundcategories,
        'mu': [''] + [signalcategory] + backgroundcategories
    }
    histclassname_per_lepton = {
        'el': ('Electrons', 'electron'),
        'mu': ('Muons', 'muon')
    }
    ids_per_lepton = {
        'mu': [
            'pteta', 'mvasoft', 'mvaloose', 'mvatight', 'cutsoft', 'cutloose',
            'cuttight'
        ],
        'el': [
            'pteta', 'cutveto', 'cutloose', 'cuttight', 'mvaisoloose',
            'mvanonisoloose', 'mvaiso90', 'mvanoniso90'
        ]
    }
    colors = [kRed + 4, kRed + 1, kAzure - 2, kOrange, kGreen - 2]
    tags_denominator = {
        'iddenominator': 'WrtAllReco',
        'pteta': 'WrtPtEta',
    }

    for lep in ids_per_lepton.keys():
        eff_sig_per_id = {}
        eff_bkg_per_id = {}
        eff_had_per_id = {}
        eff_unm_per_id = {}
        for id in ids_per_lepton[lep]:
            eff_sig_per_denomtag = {}
            eff_bkg_per_denomtag = {}
            eff_had_per_denomtag = {}
            eff_unm_per_denomtag = {}
            for denomtag in tags_denominator.keys():
                eff_sig_per_signal = {}
                eff_bkg_per_signal = {}
                eff_had_per_signal = {}
                eff_unm_per_signal = {}
                npass_sig_per_signal = {}
                npass_bkg_per_signal = {}
                npass_had_per_signal = {}
                npass_unm_per_signal = {}
                ntot_sig_per_signal = {}
                ntot_bkg_per_signal = {}
                ntot_had_per_signal = {}
                ntot_unm_per_signal = {}
                for signal in self.signals:
                    npass_sig_per_signal[signal] = 0
                    ntot_sig_per_signal[signal] = 0
                    npass_bkg_per_signal[signal] = 0
                    ntot_bkg_per_signal[signal] = 0
                    npass_had_per_signal[signal] = 0
                    ntot_had_per_signal[signal] = 0
                    npass_unm_per_signal[signal] = 0
                    ntot_unm_per_signal[signal] = 0
                for tag in histnametags_per_lepton[lep]:
                    is_signal = tag == signalcategory
                    is_background = tag in backgroundcategories
                    is_had = tag == 'fromhad'
                    is_unmatched = tag == 'unmatched'
                    hists_total = []
                    hists_pass = []
                    ratios = []
                    hists_n_total = []
                    hists_n_pass = []

                    for signal in self.signals:
                        infilename = os.path.join(self.inputpath,
                                                  'MC__' + signal + '.root')
                        infile = TFile(infilename, 'READ')

                        hfn_den = '_'.join(
                            [denomtag, histclassname_per_lepton[lep][0]])
                        hfn_num = '_'.join(
                            [lep, id, histclassname_per_lepton[lep][0]])

                        h_total = infile.Get('/'.join([
                            hfn_den, histclassname_per_lepton[lep][1] + tag +
                            'pt_rebin2'
                        ]))
                        h_total.SetDirectory(0)
                        hists_total.append(h_total)
                        h_pass = infile.Get('/'.join([
                            hfn_num, histclassname_per_lepton[lep][1] + tag +
                            'pt_rebin2'
                        ]))
                        h_pass.SetDirectory(0)
                        hists_pass.append(h_pass)
                        h_n_total = infile.Get('/'.join([
                            hfn_den,
                            'n' + histclassname_per_lepton[lep][1] + 's' + tag
                        ]))
                        h_n_total.SetDirectory(0)
                        hists_n_total.append(h_n_total)
                        h_n_pass = infile.Get('/'.join([
                            hfn_num,
                            'n' + histclassname_per_lepton[lep][1] + 's' + tag
                        ]))
                        h_n_pass.SetDirectory(0)
                        hists_n_pass.append(h_n_pass)
                        ratio = TGraphAsymmErrors(h_pass, h_total,
                                                  'cl=0.683 b(1,1) mode')
                        ratios.append(ratio)

                        c = tdrDiCanvas(
                            'c', hists_total[0].GetBinLowEdge(1),
                            hists_total[0].GetBinLowEdge(
                                hists_total[0].GetNbinsX() + 1), 1E-2, 1E8,
                            0.3, 1.7, hists_total[0].GetXaxis().GetTitle(),
                            hists_total[0].GetYaxis().GetTitle(), 'efficiency',
                            True, 0, 11)
                        leg = tdrLeg(0.25, 0.65, 0.85, 0.9, textSize=0.025)

                    len(self.signals)
                    for idx, signal in enumerate(self.signals):
                        mlq, mps, mch = get_mlq_mps_mch(signal)
                        c.cd(1).SetLogy()
                        tdrDraw(hists_total[idx],
                                "E",
                                marker=kOpenCircle,
                                mcolor=colors[idx],
                                lcolor=colors[idx],
                                fstyle=0)
                        tdrDraw(hists_pass[idx],
                                "E",
                                marker=kFullCircle,
                                mcolor=colors[idx],
                                lcolor=colors[idx],
                                fstyle=0)
                        npass = 0
                        ntotal = 0
                        for i in range(hists_n_pass[idx].GetNbinsX()):
                            npass += hists_n_pass[idx].GetBinContent(
                                i + 1) * hists_n_pass[idx].GetBinCenter(i + 1)
                            ntotal += hists_n_total[idx].GetBinContent(
                                i + 1) * hists_n_total[idx].GetBinCenter(i + 1)
                        total_eff = npass / ntotal
                        if is_signal:
                            npass_sig_per_signal[signal] += float(npass)
                            ntot_sig_per_signal[signal] += float(ntotal)
                        if is_background:
                            npass_bkg_per_signal[signal] += float(npass)
                            ntot_bkg_per_signal[signal] += float(ntotal)
                        if is_had:
                            npass_had_per_signal[signal] += float(npass)
                            ntot_had_per_signal[signal] += float(ntotal)
                        if is_unmatched:
                            npass_unm_per_signal[signal] += float(npass)
                            ntot_unm_per_signal[signal] += float(ntotal)

                        leg.AddEntry(
                            hists_pass[idx],
                            'M_{#psi} = %i GeV, M_{DM} = %i GeV (tot. eff: %.2f)'
                            % (mps, mch, total_eff), 'L')
                        c.cd(2)
                        tdrDraw(ratios[idx],
                                "P",
                                marker=kFullCircle,
                                mcolor=colors[idx],
                                lcolor=colors[idx],
                                fstyle=0)

                    tagstr = '' if tag == '' else '_' + tag
                    c.SaveAs(
                        os.path.join(
                            self.plotoutput_path,
                            'IDEfficiency_%s_%s_%s%s.pdf' %
                            (lep, tags_denominator[denomtag], id, tagstr)))

                for signal in self.signals:
                    eff_sig_per_signal[signal] = npass_sig_per_signal[
                        signal] / ntot_sig_per_signal[signal]
                    eff_bkg_per_signal[signal] = npass_bkg_per_signal[
                        signal] / ntot_bkg_per_signal[signal]
                    eff_had_per_signal[signal] = npass_had_per_signal[
                        signal] / ntot_had_per_signal[signal]
                    eff_unm_per_signal[signal] = npass_unm_per_signal[
                        signal] / ntot_unm_per_signal[signal]
                eff_sig_per_denomtag[denomtag] = eff_sig_per_signal
                eff_bkg_per_denomtag[denomtag] = eff_bkg_per_signal
                eff_had_per_denomtag[denomtag] = eff_had_per_signal
                eff_unm_per_denomtag[denomtag] = eff_unm_per_signal
            eff_sig_per_id[id] = eff_sig_per_denomtag
            eff_bkg_per_id[id] = eff_bkg_per_denomtag
            eff_had_per_id[id] = eff_had_per_denomtag
            eff_unm_per_id[id] = eff_unm_per_denomtag

        for signal in self.signals:
            for denomtag in tags_denominator.keys():
                graphs_bkg = []
                graphs_had = []
                graphs_unm = []
                legends_bkg = []
                legends_had = []
                legends_unm = []
                for id in ids_per_lepton[lep]:

                    graph_bkg = TGraph()
                    graph_bkg.SetPoint(0, eff_sig_per_id[id][denomtag][signal],
                                       eff_bkg_per_id[id][denomtag][signal])
                    legends_bkg.append(id)
                    graphs_bkg.append(graph_bkg)

                    graph_had = TGraph()
                    graph_had.SetPoint(0, eff_sig_per_id[id][denomtag][signal],
                                       eff_had_per_id[id][denomtag][signal])
                    legends_had.append(id)
                    graphs_had.append(graph_had)

                    graph_unm = TGraph()
                    graph_unm.SetPoint(0, eff_sig_per_id[id][denomtag][signal],
                                       eff_unm_per_id[id][denomtag][signal])
                    legends_unm.append(id)
                    graphs_unm.append(graph_unm)
                cgrbkg = tdrCanvas(
                    'cgrbkg', 0, 1, 1E-3, 1, '%s from #tau efficiency' %
                    (histclassname_per_lepton[lep][1]),
                    'other %s efficiency' % (histclassname_per_lepton[lep][1]),
                    True, 0, 11)
                legend_bkg = tdrLeg(0.25, 0.65, 0.85, 0.9, textSize=0.025)
                for i in range(len(graphs_bkg)):
                    g = graphs_bkg[i]
                    l = legends_bkg[i]
                    tdrDraw(g,
                            "P",
                            marker=kFullCircle,
                            mcolor=i + 1,
                            lcolor=i + 1,
                            fstyle=0)
                    legend_bkg.AddEntry(g, l, 'P')
                cgrbkg.SetLogy()
                cgrbkg.SaveAs(
                    os.path.join(
                        self.plotoutput_path,
                        'IDEfficiencyVsBackground_%s_%s_%s.pdf' %
                        (lep, signal, tags_denominator[denomtag])))

                cgrhad = tdrCanvas(
                    'cgrhad', 0, 1, 1E-3, 1, '%s from #tau efficiency' %
                    (histclassname_per_lepton[lep][1]),
                    '%s from had. efficiency' %
                    (histclassname_per_lepton[lep][1]), True, 0, 11)
                legend_had = tdrLeg(0.25, 0.65, 0.85, 0.9, textSize=0.025)
                for i in range(len(graphs_had)):
                    g = graphs_had[i]
                    l = legends_had[i]
                    tdrDraw(g,
                            "P",
                            marker=kFullCircle,
                            mcolor=i + 1,
                            lcolor=i + 1,
                            fstyle=0)
                    legend_had.AddEntry(g, l, 'P')
                cgrhad.SetLogy()
                cgrhad.SaveAs(
                    os.path.join(
                        self.plotoutput_path,
                        'IDEfficiencyVsHadronic_%s_%s_%s.pdf' %
                        (lep, signal, tags_denominator[denomtag])))

                cgrunm = tdrCanvas(
                    'cgrunm', 0, 1, 1E-3, 1, '%s from #tau efficiency' %
                    (histclassname_per_lepton[lep][1]),
                    'unmatched %s efficiency' %
                    (histclassname_per_lepton[lep][1]), True, 0, 11)
                legend_unm = tdrLeg(0.25, 0.65, 0.85, 0.9, textSize=0.025)
                for i in range(len(graphs_unm)):
                    g = graphs_unm[i]
                    l = legends_unm[i]
                    tdrDraw(g,
                            "P",
                            marker=kFullCircle,
                            mcolor=i + 1,
                            lcolor=i + 1,
                            fstyle=0)
                    legend_unm.AddEntry(g, l, 'P')
                cgrunm.SetLogy()
                # os.path.join(self.plotoutput_path, 'ReconstructionEfficiency_%s_%s_%s%s.pdf' % (lep, histfolders_denom[histfolder_denom], id, tagstr))
                cgrunm.SaveAs(
                    os.path.join(
                        self.plotoutput_path,
                        'IDEfficiencyVsUnmatched_%s_%s_%s.pdf' %
                        (lep, signal, tags_denominator[denomtag])))
Ejemplo n.º 20
0
    def __init__(self,
                 name,
                 title,
                 lenght,
                 time_min,
                 time_max,
                 helix,
                 n_points=100,
                 ip_algorithm='complex'):
        """
        Constructor providing:
        name: string used to identify ROOT objects
        title: string used as title of canvases and graphs
        lenght: half of the axis dimension
        time_min and time_max: defining the time interval for which the track is shown
        helix: helix object to be shown; having the ip attributes is mandatory
        n_points: number of points that show the track
        ip_algorithm: if 'complex' it shows also the distance of
        closest approach to the jet direction, and the linearized track at
        that point. It requires to have run the function compute_IP_wrt_direction
        on the helix object.
        """
        self.name = name
        self.title = title
        self.helix = helix
        self.ip_algorithm = ip_algorithm

        self.gr_transverse = TGraph()
        self.gr_transverse.SetNameTitle("g_tr_" + name, title)
        self.gr_transverse.SetPoint(0, 0., 0.)
        self.gr_transverse.SetPoint(1, 0., lenght)
        self.gr_transverse.SetPoint(2, 0., -lenght)
        self.gr_transverse.SetPoint(3, lenght, 0.)
        self.gr_transverse.SetPoint(4, -lenght, 0.)
        self.gr_transverse.SetMarkerStyle(22)
        self.gr_transverse.SetMarkerColor(3)
        self.gr_transverse.GetXaxis().SetTitle("X axis")
        self.gr_transverse.GetYaxis().SetTitle("Y axis")

        # Origin
        self.gr_transverse.SetPoint(5, helix.origin.X(), helix.origin.Y())

        # Track
        self.ell_transverse = TGraph()
        self.ell_transverse.SetNameTitle("g_ellipse_" + name, title)
        self.ell_transverse.SetMarkerStyle(7)
        self.ell_transverse.SetMarkerColor(1)

        for i in range(n_points):
            time_coord = time_min + i * (time_max - time_min) / n_points
            point = helix.point_at_time(time_coord)
            self.ell_transverse.SetPoint(i, point.X(), point.Y())

        # Jet direction
        jet_dir_x1 = self.helix.primary_vertex.X(
        ) - lenght * self.helix.jet_direction.X()
        jet_dir_x2 = self.helix.primary_vertex.X(
        ) + lenght * self.helix.jet_direction.X()
        jet_dir_y1 = self.helix.primary_vertex.Y(
        ) - lenght * self.helix.jet_direction.Y()
        jet_dir_y2 = self.helix.primary_vertex.Y(
        ) + lenght * self.helix.jet_direction.Y()

        self.jet_dir = TLine(jet_dir_x1, jet_dir_y1, jet_dir_x2, jet_dir_y2)
        self.jet_dir.SetLineColor(6)
        self.jet_dir.SetLineStyle(1)
        self.jet_dir.SetLineWidth(1)

        # Impact Parameter D
        impact_parameter_x1 = self.helix.primary_vertex.X()
        impact_parameter_y1 = self.helix.primary_vertex.Y()
        impact_parameter_x2 = self.helix.vector_impact_parameter.X()
        impact_parameter_y2 = self.helix.vector_impact_parameter.Y()

        self.impact_parameter = TLine(impact_parameter_x1, impact_parameter_y1,
                                      impact_parameter_x2, impact_parameter_y2)
        self.impact_parameter.SetLineColor(4)
        self.impact_parameter.SetLineStyle(6)
        self.impact_parameter.SetLineWidth(4)

        if self.ip_algorithm == 'complex':
            # Linearized_track
            lin_track_x1 = self.helix.linearized_track.origin.X() \
                         - lenght * self.helix.linearized_track.direction.X()
            lin_track_x2 = self.helix.linearized_track.origin.X() \
                         + lenght * self.helix.linearized_track.direction.X()
            lin_track_y1 = self.helix.linearized_track.origin.Y() \
                         - lenght * self.helix.linearized_track.direction.Y()
            lin_track_y2 = self.helix.linearized_track.origin.Y() \
                         + lenght * self.helix.linearized_track.direction.Y()

            self.lin_track = TLine(lin_track_x1, lin_track_y1, lin_track_x2,
                                   lin_track_y2)
            self.lin_track.SetLineColor(2)
            self.lin_track.SetLineStyle(9)
            self.lin_track.SetLineWidth(2)

            # Jet-track distance D_j: vector from S_j to S_t
            jet_track_distance_x1 = self.helix.jet_point_min_approach.X()
            jet_track_distance_y1 = self.helix.jet_point_min_approach.Y()
            jet_track_distance_x2 = self.helix.point_min_approach.X()
            jet_track_distance_y2 = self.helix.point_min_approach.Y()

            self.jet_track_distance = TLine(jet_track_distance_x1,
                                            jet_track_distance_y1,
                                            jet_track_distance_x2,
                                            jet_track_distance_y2)
            self.jet_track_distance.SetLineColor(3)
            self.jet_track_distance.SetLineStyle(3)
            self.jet_track_distance.SetLineWidth(4)
Ejemplo n.º 21
0
def uncertainty_interpolation(year, category, uncertainty_type="BTag"):

    uncerts = {'up': {}, 'down': {}}

    g_up = TGraph()
    g_up.SetTitle("uncert;m_{X} (GeV);uncert")
    g_up.SetMarkerStyle(20)
    g_up.SetMarkerColor(2)
    i_up = TGraph()
    i_up.SetMarkerStyle(24)
    i_up.SetMarkerColor(2)
    f_up = TF1("f_up", "pol0", 0, 1)
    g_down = TGraph()
    g_down.SetMarkerStyle(20)
    g_down.SetMarkerColor(4)
    i_down = TGraph()
    i_down.SetMarkerStyle(24)
    i_down.SetMarkerColor(4)
    f_down = TF1("f_down", "pol0", 0, 1)

    n = 0
    for i, m in enumerate(genPoints):
        if year == "run2":
            up_value = 0
            for yr in ['2016', '2017', '2018']:
                up_value += LUMI[yr] * sample['ZpBB_M{}'.format(m)][
                    uncertainty_type + '_uncertainties'][yr]['up'][category]
            up_value /= LUMI['run2']
        else:
            up_value = sample['ZpBB_M{}'.format(m)][
                uncertainty_type + '_uncertainties'][year]['up'][category]
        if up_value == -100: continue
        g_up.SetPoint(n, m, up_value)
        n = n + 1
    if n == 0:
        print "no valid uncertainties detected!!"
        sys.exit()
    n = 0
    for i, m in enumerate(genPoints):
        if year == "run2":
            down_value = 0
            for yr in ['2016', '2017', '2018']:
                down_value += LUMI[yr] * sample['ZpBB_M{}'.format(m)][
                    uncertainty_type + '_uncertainties'][yr]['down'][category]
            down_value /= LUMI['run2']
        else:
            down_value = sample['ZpBB_M{}'.format(m)][
                uncertainty_type + '_uncertainties'][year]['down'][category]
        if down_value == -100: continue
        g_down.SetPoint(n, m, down_value)
        n = n + 1
    if n == 0:
        print "no valid uncertainties detected!!"
        sys.exit()

    g_up.Fit(f_up, "Q0", "SAME")
    g_down.Fit(f_down, "Q0", "SAME")

    for m in massPoints:
        up_val = g_up.Eval(m)
        uncerts['up'][m] = up_val
        i_up.SetPoint(i_up.GetN(), m, up_val)
        down_val = g_down.Eval(m)
        uncerts['down'][m] = down_val
        i_down.SetPoint(i_down.GetN(), m, down_val)

    c = TCanvas("c2", "Signal Efficiency", 800, 600)
    g_up.Draw("APL")
    i_up.Draw("P, SAME")
    g_down.Draw("PL, SAME")
    i_down.Draw("P, SAME")
    g_up.GetYaxis().SetRangeUser(-1., 1.)
    g_up.GetXaxis().SetRangeUser(genPoints[0] - 100, genPoints[-1] + 100)

    leg = TLegend(0.7, 0.75, 0.9, 0.9)
    leg.AddEntry(g_up, "up")
    leg.AddEntry(g_down, "down")
    leg.Draw()
    c.Print(PLOTDIR + uncertainty_type +
            "_uncertainty_interpol_{}_{}.png".format(year, category))

    return uncerts
Ejemplo n.º 22
0
def makepTbinsPlots(w,
                    rfr,
                    is_prefit,
                    suffix,
                    plotdir,
                    yields=None,
                    save_hists=False):
    """ Plot VpT distributions in each tag region """

    logging.info("Plotting VpT Distributions")
    if is_prefit:
        w.loadSnapshot("vars_initial")
    else:
        w.loadSnapshot("vars_final")

    if not yields:
        logging.debug("Yields not provided. Compute them")
        getYields(w, rfr, True)
        yields = Config.yields

    os.system("mkdir -vp " + plotdir)

    ptbins_cut = array('d', [0, 90, 120, 160, 200, 250])
    hmodel_cut = TH1F("hmodel_cut", "hmodel_cut", 5, ptbins_cut)
    errmodel_x_cut = array('d', [
        0, 90, 90, 120, 120, 160, 160, 200, 200, 250, 250, 200, 200, 160, 160,
        120, 120, 90, 90, 0
    ])
    errmodel_y_cut = array('d', [0 for i in range(20)])
    errmodel_cut = TGraph(20, errmodel_x_cut, errmodel_y_cut)

    ptbins_mva = array('d', [0, 120, 250])
    hmodel_mva = TH1F("hmodel_mva", "hmodel_mva", 2, ptbins_mva)
    errmodel_x_mva = array('d', [0, 120, 120, 250, 250, 120, 120, 0])
    errmodel_y_mva = array('d', [0 for i in range(8)])
    errmodel_mva = TGraph(8, errmodel_x_mva, errmodel_y_mva)

    ptbins_cut_0lep = array('d', [0, 100, 120, 160, 200, 250])
    hmodel_cut_0lep = TH1F("hmodel_cut_0lep", "hmodel_cut_0lep", 5,
                           ptbins_cut_0lep)
    errmodel_x_cut_0lep = array('d', [
        0, 100, 100, 120, 120, 160, 160, 200, 200, 250, 250, 200, 200, 160,
        160, 120, 120, 100, 100, 0
    ])
    errmodel_y_cut_0lep = array('d', [0 for i in range(20)])
    errmodel_cut_0lep = TGraph(20, errmodel_x_cut_0lep, errmodel_y_cut_0lep)

    ptbins_mva_0lep = array('d', [0, 100, 120, 250])
    hmodel_mva_0lep = TH1F("hmodel_mva_0lep", "hmodel_mva_0lep", 3,
                           ptbins_mva_0lep)
    errmodel_x_mva_0lep = array(
        'd', [0, 100, 100, 120, 120, 250, 250, 120, 120, 100, 100, 0])
    errmodel_y_mva_0lep = array('d', [0 for i in range(12)])
    errmodel_mva_0lep = TGraph(12, errmodel_x_mva_0lep, errmodel_y_mva_0lep)

    histos = {}
    mass = None

    for k, y in yields.iteritems():
        parts = k.split('_')
        # k: Region_Y2012_isMVA1_B2_J2_T2_L2_distmva_TType
        # find the bin:
        pos1 = k.find("_B")
        pos2 = k.find("_", pos1 + 1)
        if pos2 - pos1 != 3:
            logging.error(
                "name of the region {} does not seem to be a standard one".
                format(k))
            logging.error("_B should match the bin name")
            return
        # TODO: horrible. Need to take care of 0 lepton low MET bin properly, especially in MVA case where lowMET is still CUT
        regname = k[:pos1 + 2] + '9' + k[pos2:]
        bin = int(k[pos1 + 2])
        pos1 = regname.find("_dist")
        pos2 = regname.find("_", pos1 + 1)
        regname = regname[:pos1 + 5] + "VpT" + regname[pos2:]
        pos1 = regname.find("_isMVA")
        isMVA = int(regname[pos1 + 6])
        pos1 = k.find("_L")
        pos2 = k.find("_", pos1 + 1)
        nlep = int(k[pos1 + 2])
        logging.info("Accumulating for region {}".format(regname))
        ibin = bin + 1
        if isMVA and nlep != 0 and ibin == 3:  # MVA has no B1
            ibin = 2
        if isMVA:
            if nlep == 0:
                hmodel = hmodel_mva_0lep
                errmodel = errmodel_mva_0lep
            else:
                hmodel = hmodel_mva
                errmodel = errmodel_mva
        else:
            if nlep == 0:
                hmodel = hmodel_cut_0lep
                errmodel = errmodel_cut_0lep
            else:
                hmodel = hmodel_cut
                errmodel = errmodel_cut
        if not regname in histos:
            histos[regname] = {}
            for s, v in y.iteritems():
                if s.startswith("L_x"):
                    sname = getCompName(s)
                    histos[regname][sname] = hmodel.Clone(sname)
                    if mass == None:
                        res = is_signal(sname)
                        if res:
                            mass = res
            histos[regname]["data"] = hmodel.Clone("data")
            histos[regname]["error"] = errmodel.Clone("error")
            histos[regname]["prefit"] = [hmodel.Clone("prefit"), ""]
        # now, fill the histos
        for s, v in y.iteritems():
            if s.startswith("L_x"):
                sname = getCompName(s)
                try:
                    histos[regname][getCompName(s)].SetBinContent(ibin, v[0])
                except KeyError:  # case when a given component is 0 in the first found VpT bin, but !=0 elsewhere
                    sname = getCompName(s)
                    histos[regname][sname] = hmodel.Clone(sname)
                    histos[regname][sname].SetBinContent(ibin, v[0])
        histos[regname]["data"].SetBinContent(ibin, y["data"])
        (mcval, mcerr) = y["MC"]
        if mcerr == -1:  # recompute case by case if not already computed somewhere
            mcerr = getMCerror(w, rfr, k)
            y["MC"] = [mcval, mcerr]
        X = Double()
        Y = Double()
        for i in [2 * ibin - 2, 2 * ibin - 1]:
            histos[regname]["error"].GetPoint(i, X, Y)
            histos[regname]["error"].SetPoint(i, X, mcval - mcerr)
        npoints = histos[regname]["error"].GetN()
        for i in [npoints + 1 - 2 * ibin, npoints - 2 * ibin]:
            histos[regname]["error"].GetPoint(i, X, Y)
            histos[regname]["error"].SetPoint(i, X, mcval + mcerr)
        # if doing postfit, add the prefit line
        if not is_prefit:
            histo, mulegend = getPrefitCurve(w, regname=k)
            histos[regname]["prefit"][0].SetBinContent(ibin, histo.Integral())
            print("PREFIT ", mulegend)
            logging.info("PREFIT {}".format(mulegend))
            histos[regname]["prefit"][1] = mulegend

    for reg, h in histos.iteritems():
        h["data"] = TGraphAsymmErrors(h["data"])  # TODO use Poisson errors ?
        sm = mkplots.SetupMaker(reg, mass, muhat=Config.muhat)
        for k, v in h.iteritems():
            sm.add(k, v)

        cname = reg + "_" + suffix
        can = sm.setup.make_complete_plot(cname, True, ybounds=(0.85, 1.15))
        plotname = "{0}/{1}".format(plotdir, can.GetName())
        can2 = sm.setup.make_complete_plot(cname + "_logy",
                                           True,
                                           True,
                                           ybounds=(0.85, 1.15))
        plotname2 = "{0}/{1}".format(plotdir, can2.GetName())
        for f in Config.formats:
            can.Print(plotname + '.' + f)
            can2.Print(plotname2 + '.' + f)

        # save histograms if requested
        if save_hists:
            afile = TFile.Open(plotname + ".root", "recreate")
            can.Write(can.GetName())
            can2.Write(can2.GetName())
            for k, v in h.iteritems():
                if isinstance(v, TObject):
                    v.Write(v.GetName())
                if k == "prefit":
                    v[0].Write(v[0].GetName())

        can.Close()
        can2.Close()
        # free memory for some objects used in the plotting...
        mkplots.purge()
        # TODO check for things not deleted
    Config.save_yields()