def legend4Plot(plot, left = False): if left: theLeg = TLegend(0.2, 0.62, 0.55, 0.92, "", "NDC") else: theLeg = TLegend(0.60, 0.62, 0.92, 0.92, "", "NDC") theLeg.SetName('theLegend') theLeg.SetBorderSize(0) theLeg.SetLineColor(0) theLeg.SetFillColor(0) theLeg.SetFillStyle(0) theLeg.SetLineWidth(0) theLeg.SetLineStyle(0) theLeg.SetTextFont(42) theLeg.SetTextSize(.045) entryCnt = 0 for obj in range(0, int(plot.numItems())): objName = plot.nameOf(obj) if (not plot.getInvisible(objName)): theObj = plot.getObject(obj) objTitle = theObj.GetTitle() if len(objTitle) < 1: objTitle = objName dopts = plot.getDrawOptions(objName).Data() # print 'obj:',theObj,'title:',objTitle,'opts:',dopts,'type:',type(dopts) if theObj.IsA().InheritsFrom('TNamed'): theLeg.AddEntry(theObj, objTitle, dopts) entryCnt += 1 theLeg.SetY1NDC(0.9 - 0.05*entryCnt - 0.005) theLeg.SetY1(theLeg.GetY1NDC()) return theLeg
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 create_legend(x0=0.696, y0 = 0.95, x1=0.94, y1=0.55): # legend = TLegend(0.6, 0.7, 0.94, 0.92); legend = TLegend(x0, y0, x1, y1) legend.SetBorderSize(0); legend.SetLineStyle(0); legend.SetTextFont(42); legend.SetFillStyle(0); return legend
def getLegend(): legend = TLegend(0.55010112, 0.7183362, 0.70202143, 0.919833) legend.SetTextSize(0.032) legend.SetLineColor(0) legend.SetShadowColor(0) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetMargin(0.35) return legend
def getLegend(x1=0.70010112,y1=0.123362,x2=0.90202143,y2=0.279833): legend = TLegend(x1,y1,x2,y2) legend.SetTextSize(0.032) legend.SetLineColor(0) legend.SetShadowColor(0) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetMargin(0.35) return legend
def legend(title=''): lg = TLegend(0.65, 0.55, 0.95, 0.90, title) lg.SetFillColor(0) lg.SetFillStyle(0) lg.SetLineColor(0) lg.SetLineStyle(0) lg.SetBorderSize(0) lg.SetShadowColor(0) lg.SetTextFont(42) lg.SetTextSize(0.06) return lg
def myLegend(coordinate=[0.48, 0.55, 0.97, 0.87], ncol=1): co = coordinate leg = TLegend(co[0], co[1], co[2], co[3]) leg.SetNColumns(ncol) leg.SetBorderSize(0) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.035) return leg
def SetLegend(coordinate_=[.15, .7, .47, .87], ncol=1): c_ = coordinate_ legend = TLegend(c_[0], c_[1], c_[2], c_[3]) legend.SetBorderSize(0) legend.SetNColumns(ncol) legend.SetLineColor(1) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) legend.SetTextSize(0.05) return legend
def loadlegend(top, bottom, left, right): relPosX = 0.001 relPosY = 0.005 posX = 1 - right - relPosX*(1-left-right) posY = 1 - top - relPosY*(1-top-bottom) legendOffsetX = 0.0 legendOffsetY = - 0.05 textSize = 0.05 textFont = 60 legendSizeX = 0.4 legendSizeY = 0.2 legend = TLegend(posX-legendSizeX+legendOffsetX,posY-legendSizeY+legendOffsetY,posX+legendOffsetX,posY+legendOffsetY) legend.SetTextSize(textSize) legend.SetLineStyle(0) legend.SetBorderSize(0) return legend
pad1.SetBorderSize(0) pad1.SetFrameBorderSize(0) pad2.SetBorderSize(0) pad2.SetFrameBorderSize(0) pad2.SetBottomMargin(0.3) pad2.SetBorderMode(0) pad1.Draw() pad2.Draw() pad1.cd() legend_years = TLegend(0.15, 0.7, 0.3, 0.95) legend_years.SetHeader(" ") legend_years.SetFillColor(0) legend_years.SetBorderSize(0) legend_years.SetLineColor(1) legend_years.SetLineStyle(1) legend_years.SetLineWidth(1) legend_years.SetFillStyle(0) legend_years.SetTextSize(0.03) legend_years.AddEntry(h_signal_2016, "2016", "lep") legend_years.AddEntry(h_signal_2017, "2017", "lep") legend_years.AddEntry(h_signal_2018, "2018", "lep") scaling_factor_2016_2018 = (h_signal_2018.Integral()) / ( h_signal_2016.Integral()) scaling_factor_2017_2018 = (h_signal_2018.Integral()) / ( h_signal_2017.Integral()) h_signal_2016.Scale(scaling_factor_2016_2018) h_signal_2016.SetMarkerStyle(20) h_signal_2016.SetMarkerColor(3) h_signal_2017.Scale(scaling_factor_2017_2018)
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(1.9,"X"); gStyle.SetLineWidth(3) gStyle.SetFrameLineWidth(3) i = 0 histList_ = [] histList = [] histList1 = [] maximum = [] minimum = [] ## Legend leg = TLegend(0.1, 0.80, 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(42) leg.SetTextSize(0.05) c = TCanvas("c1", "c1", 0, 0, 500, 500) c.SetBottomMargin(0.15) c.SetLogy(logstatus[1]) c.SetLogx(logstatus[0]) print("you have provided " + str(len(fileVec)) + " files and " + str(len(histVec)) + " histograms to make a overlapping plot") print "opening rootfiles" c.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()) minimum.append(histList[ii].GetMinimum()) maximum.sort() ii = ii + 1 print histList print maximum, " ", max(maximum) print minimum, " ", min(minimum) for ih in range(len(histList)): tt = type(histList[ih]) if logstatus[1] is 1: histList[ih].SetMaximum(1.5) #1.4 for log histList[ih].SetMinimum(0.1) #1.4 for log if logstatus[1] is 0: maxi = max(maximum) mini = min(minimum) if maxi == 0.0: maxi = 0.001 if mini == 0.0: mini = -0.001 histList[ih].SetMaximum(maxi * 3) #1.4 for log histList[ih].SetMinimum(mini * 3) #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("P 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("P hist same") if tt is TGraphAsymmErrors: histList[ih].SetMaximum(100) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetLineWidth(2) 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].SetMarkerColor(colors[ih]) histList[ih].SetMarkerStyle(20) histList[ih].SetMarkerSize(1.0) histList[ih].SetLineWidth(3) leg.AddEntry(histList[ih], legendtext[ih], "P") histList[ih].GetYaxis().SetTitle(titleVec[1]) histList[ih].GetYaxis().SetTitleSize(0.052) histList[ih].GetYaxis().SetTitleOffset(0.98) histList[ih].GetYaxis().SetTitleFont(42) histList[ih].GetYaxis().SetLabelFont(42) 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.14) histList[ih].GetXaxis().SetTitleFont(42) histList[ih].GetXaxis().SetLabelFont(42) histList[ih].GetYaxis().SetLabelFont(42) histList[ih].GetXaxis().SetNdivisions(507) #histList[ih].GetXaxis().SetMoreLogLabels(); #histList[ih].GetXaxis().SetNoExponent(); #histList[ih].GetTGaxis().SetMaxDigits(3); i = i + 1 pt = TPaveText(0.01, 0.92, 0.95, 0.96, "brNDC") pt.SetBorderSize(0) pt.SetTextAlign(12) pt.SetFillStyle(0) pt.SetTextFont(42) pt.SetTextSize(0.046) #text = pt.AddText(0.12,0.35,"CMS Internal 36 fb^{-1} (2016) ") text = pt.AddText(0.12, 0.35, "CMS Internal 41.5 fb^{-1} (2017) ") #text = pt.AddText(0.12,0.35,"CMS Internal 59.6 fb^{-1} (2018) ") #text = pt.AddText(0.6,0.5,"41.5 fb^{-1} (2017) ") pt.Draw() leg.Draw() outputdirname = 'UncPlots/' histname = outputdirname + pngname c.SaveAs(histname + '.png') c.SaveAs(histname + '.pdf')
def makeBiasPlot(output, muFile, chan, interference, printStats=False, obs2="", ratioLabel=""): mu = open(muFile, 'r') limits = {} mux = [] muy = [] mu1SigLow = [] mu1SigHigh = [] mu2SigLow = [] mu2SigHigh = [] for entry in mu: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: mux.append(massPoint) print massPoint, limits[massPoint][medianNr] muy.append(limits[massPoint][medianNr]) mu1SigLow.append(limits[massPoint][lower1Sig]) mu1SigHigh.append(limits[massPoint][upper1Sig]) mu2SigLow.append(limits[massPoint][lower2Sig]) mu2SigHigh.append(limits[massPoint][upper2Sig]) muX = numpy.array(mux) muY = numpy.array(muy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] if printStats: print "length of mux: ", len(mux) if printStats: print "length of mu1SigLow: ", len(mu1SigLow) if printStats: print "length of mu1SigHigh: ", len(mu1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(mux)): values2.append(mu2SigLow[x]) xPointsForValues2.append(mux[x]) for x in range(len(mux) - 1, 0 - 1, -1): values2.append(mu2SigHigh[x]) xPointsForValues2.append(mux[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(mux)): values.append(mu1SigLow[x]) xPointsForValues.append(mux[x]) for x in range(len(mux) - 1, 0 - 1, -1): values.append(mu1SigHigh[x]) xPointsForValues.append(mux[x]) if printStats: print "length of values: ", len(values) mu2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) mu1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) if printStats: print "xPoints2: ", xPoints2 if printStats: print "mu2Sig: ", mu2Sig if printStats: print "xPoints: ", xPoints if printStats: print "mu1Sig: ", mu1Sig GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, mu2Sig) GraphErr2Sig.SetFillColor(ROOT.kYellow + 1) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, mu1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen) cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500) gStyle.SetOptStat(0) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() muX = numpy.array(mux) muY = numpy.array(muy) GraphMU = TGraph(len(muX), muX, muY) GraphMU.SetLineWidth(3) GraphMU.SetLineStyle(2) GraphMU.SetLineColor(ROOT.kBlue) #Draw the graphs: DummyGraph = TH1F("DummyGraph", "", 100, 10, 40) DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]") DummyGraph.GetYaxis().SetTitle("#hat{#mu}") gStyle.SetOptStat(0) if "Des" in output: DummyGraph.GetXaxis().SetRangeUser(10, 28) else: DummyGraph.GetXaxis().SetRangeUser(10, 40) DummyGraph.SetMinimum(-2) DummyGraph.SetMaximum(10) DummyGraph.GetXaxis().SetLabelSize(0.04) DummyGraph.GetXaxis().SetTitleSize(0.045) DummyGraph.GetXaxis().SetTitleOffset(1.) DummyGraph.GetYaxis().SetLabelSize(0.04) DummyGraph.GetYaxis().SetTitleSize(0.045) DummyGraph.GetYaxis().SetTitleOffset(1.) DummyGraph.Draw() DummyGraph.SetLineColor(ROOT.kWhite) if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphMU.Draw("lpsame") else: GraphMU.Draw("lp") plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetFillStyle(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetFillStyle(0) plPrelim.SetBorderSize(0) plPrelim.Draw() cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.032) leg.AddEntry(GraphMU, "median value", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "1#sigma quantile", "f") leg.AddEntry(GraphErr2Sig, "2#sigma quantile", "f") leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetFillStyle(0) leg.SetLineColor(0) leg.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "35.9 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .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() maxX = 40 if "Des" in output: maxX = 28 line = ROOT.TLine(10, 0, maxX, 0) if "mu1" in output: line = ROOT.TLine(10, 1, maxX, 1) line.SetLineStyle(ROOT.kDashed) line.Draw("same") plotPad.RedrawAxis() cCL.Update() printPlots(cCL, output)
def makeLimitPlot(output, obs, exp, chan, interference, printStats=False, obs2="", ratioLabel=""): fileObs = open(obs, 'r') fileExp = open(exp, 'r') observedx = [] observedy = [] obsLimits = {} xSecs = getFittedXSecCurve("CI_%s" % interference, 1.3) for entry in fileObs: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) * xSecs.Eval( int(float(entry.split()[0]))) if massPoint not in obsLimits: obsLimits[massPoint] = [] obsLimits[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits) for massPoint in sorted(obsLimits): observedx.append(massPoint) observedy.append(numpy.mean(obsLimits[massPoint])) if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits[massPoint]), " std dev: ", numpy.std( obsLimits[massPoint]), " from: ", obsLimits[massPoint] if not obs2 == "": fileObs2 = open(obs2, 'r') observedx2 = [] observedy2 = [] obsLimits2 = {} for entry in fileObs2: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) * xSecs.Eval( int(float(entry.split()[0]))) if massPoint not in obsLimits2: obsLimits2[massPoint] = [] obsLimits2[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits2) for massPoint in sorted(obsLimits2): observedx2.append(massPoint) observedy2.append(numpy.mean(obsLimits2[massPoint])) if (numpy.std(obsLimits2[massPoint]) / numpy.mean(obsLimits2[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits2[massPoint]), " std dev: ", numpy.std( obsLimits2[massPoint] ), " from: ", obsLimits2[massPoint] limits = {} expectedx = [] expectedy = [] expected1SigLow = [] expected1SigHigh = [] expected2SigLow = [] expected2SigHigh = [] for entry in fileExp: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) * xSecs.Eval( int(float(entry.split()[0]))) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: expectedx.append(massPoint) print massPoint, limits[massPoint][medianNr] expectedy.append(limits[massPoint][medianNr]) expected1SigLow.append(limits[massPoint][lower1Sig]) expected1SigHigh.append(limits[massPoint][upper1Sig]) expected2SigLow.append(limits[massPoint][lower2Sig]) expected2SigHigh.append(limits[massPoint][upper2Sig]) expX = numpy.array(expectedx) expY = numpy.array(expectedy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] if printStats: print "length of expectedx: ", len(expectedx) if printStats: print "length of expected1SigLow: ", len(expected1SigLow) if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(expectedx)): values2.append(expected2SigLow[x]) xPointsForValues2.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values2.append(expected2SigHigh[x]) xPointsForValues2.append(expectedx[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(expectedx)): values.append(expected1SigLow[x]) xPointsForValues.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values.append(expected1SigHigh[x]) xPointsForValues.append(expectedx[x]) if printStats: print "length of values: ", len(values) exp2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) exp1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) if printStats: print "xPoints2: ", xPoints2 if printStats: print "exp2Sig: ", exp2Sig if printStats: print "xPoints: ", xPoints if printStats: print "exp1Sig: ", exp1Sig GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig) GraphErr2Sig.SetFillColor(ROOT.kOrange) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen + 1) cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500) gStyle.SetOptStat(0) if not obs2 == "": plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() expX = numpy.array(expectedx) expY = numpy.array(expectedy) GraphExp = TGraph(len(expX), expX, expY) GraphExp.SetLineWidth(3) GraphExp.SetLineStyle(2) GraphExp.SetLineColor(ROOT.kBlue) obsX = numpy.array(observedx) obsY = numpy.array(observedy) if printStats: print "obsX: ", obsX if printStats: print "obsY: ", obsY if SMOOTH: smooth_obs = TGraphSmooth("normal") GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY) GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005) else: GraphObs = TGraph(len(obsX), obsX, obsY) GraphObs.SetLineWidth(3) if not obs2 == "": ratio = [] ratiox = [] for index, val in enumerate(observedy): mass = observedx[index] foundIndex = -1 for index2, mass2 in enumerate(observedx2): if mass == mass2: foundIndex = index2 if foundIndex > 0: ratio.append(observedy2[foundIndex] / val) ratiox.append(mass) ratioA = numpy.array(ratio) ratioX = numpy.array(ratiox) obsX2 = numpy.array(observedx2) obsY2 = numpy.array(observedy2) ratioGraph = TGraph(len(ratioX), ratioX, ratioA) if printStats: print "obsX2: ", obsX2 if printStats: print "obsY2: ", obsY2 if SMOOTH: smooth_obs2 = TGraphSmooth("normal") GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2) GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear", 0, 0.005) else: GraphObs2 = TGraph(len(obsX2), obsX2, obsY2) GraphObs2.SetLineWidth(3) xSecCurves = [] xSecCurves.append(getFittedXSecCurve("CI_%s" % interference, 1.3)) #Draw the graphs: plotPad.SetLogy() DummyGraph = TH1F("DummyGraph", "", 100, 10, 46) DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]") if chan == "mumu": DummyGraph.GetYaxis().SetTitle( "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#mu#mu +X) [pb]" ) elif chan == "elel": DummyGraph.GetYaxis().SetTitle( "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrowee +X) [pb]") elif chan == "elmu": DummyGraph.GetYaxis().SetTitle( "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#font[12]{ll}) [pb]" ) gStyle.SetOptStat(0) DummyGraph.GetXaxis().SetRangeUser(10, 46) DummyGraph.SetMinimum(5e-4) DummyGraph.SetMaximum(1) DummyGraph.GetXaxis().SetLabelSize(0.04) DummyGraph.GetXaxis().SetTitleSize(0.045) DummyGraph.GetXaxis().SetTitleOffset(1.) DummyGraph.GetYaxis().SetLabelSize(0.04) DummyGraph.GetYaxis().SetTitleSize(0.045) DummyGraph.GetYaxis().SetTitleOffset(1.) DummyGraph.Draw() if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphExp.Draw("lpsame") else: if obs2 == "": GraphExp.Draw("lp") if not EXPONLY: GraphObs.Draw("plsame") if not obs2 == "": GraphObs2.SetLineColor(ROOT.kRed) GraphObs2.SetLineStyle(ROOT.kDashed) GraphObs2.Draw("plsame") for curve in xSecCurves: print curve.Eval(28) #curve.Draw() curve.Draw("sameR") plCMS = TPaveLabel(.15, .81, .25, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetFillStyle(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.15, .76, .275, .82, "Supplementary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetFillStyle(0) plPrelim.SetBorderSize(0) #plPrelim.Draw() cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") leg = TLegend(0.440517, 0.523051, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.032) if not obs2 == "": if ratioLabel == "": ratioLabel = "Variant/Default" ratioLabels = ratioLabel.split("/") print ratioLabels leg.AddEntry(GraphObs, "%s Observed 95%% CL limit" % ratioLabels[1], "l") leg.AddEntry(GraphObs2, "%s Observed 95%% CL limit" % ratioLabels[0], "l") else: if not EXPONLY: leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l") leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f") leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f") leg.AddEntry(xSecCurves[0], labels[interference], "l") leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetFillStyle(0) leg.SetLineColor(0) leg.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "35.9 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif "2017" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "42.1 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "41.5 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "41.5 fb^{-1} (13 TeV, ee) + 42.1 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() if not obs2 == "": ratioPad.cd() line = ROOT.TLine(200, 1, 5500, 1) line.SetLineStyle(ROOT.kDashed) ROOT.gStyle.SetTitleSize(0.12, "Y") ROOT.gStyle.SetTitleYOffset(0.35) ROOT.gStyle.SetNdivisions(000, "Y") ROOT.gStyle.SetNdivisions(408, "Y") ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel) line.Draw("same") ratioGraph.Draw("sameP") cCL.Update() printPlots(cCL, output)
def drawPlots(plots, plotopts, rootopts, output, optzero, optmean, opth, optw): from ROOT import TPostScript, TCanvas, TLegend from ROOT import gROOT, gStyle, gPad gROOT.Reset() gROOT.SetStyle("Plain") gStyle.SetOptStat(0) gStyle.SetPalette(1) leg = TLegend(0.54, 0.71, 0.9, 0.9) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetBorderSize(0) if output != "DISPLAY": ps = TPostScript(output, 111) ps.NewPage() canv = TCanvas('c1', "Validation Plot Viewer", 600, 800) canv.Divide(opth, optw) maxperlist = opth * optw #current pad num = 0 #for stupid drawing system legends = [] #drawing hists for plotopt in plotopts: print "Drawing", plotopt.display_name num += 1 if (num > maxperlist and output != "DISPLAY"): #end of a current PS page ps.NewPage() print "new page" num = 1 canv.cd(num) gPad.SetLogy(plotopt.logy) leg.Clear() entries = {} valuemax = -999999.9 valuemin = 999999.9 entryZ = 0 for rootopt in rootopts: #get the max entries entries[rootopt] = plots[plotopt][rootopt].GetEntries() if (plots[plotopt][rootopt].GetEntries() > entryZ): entryZ = plots[plotopt][rootopt].GetEntries() for rootopt in rootopts: #get the max entries plot = plots[plotopt][rootopt] if (plotopt.profile): print rootopt.legendname, "is a profile: no need to scale" else: if not (entries[rootopt] == 0): print "scaling", rootopt.legendname, "to", entryZ / entries[ rootopt] plot.Scale(entryZ / entries[rootopt]) else: print rootopt.legendname, "is an empty hist, no scale" for rootopt in rootopts: #get the highest peak if (plots[plotopt][rootopt].GetMaximum() > valuemax): valuemax = plots[plotopt][rootopt].GetMaximum() entryZ = plots[plotopt][rootopt].GetEntries() sameDrawOpt = "" #now we plot all fillers, as otherwise they will render invisible everything behind them for rootopt in rootopts: if (rootopt.markerstyle > 0): #not filler continue plot = plots[plotopt][rootopt] print "Drawing filler from", rootopt.legendname if optzero: if (plotopt.logy == 1): plot.SetMinimum(1.0) else: plot.SetMinimum(0.0) plot.SetMaximum(valuemax * 1.1) plot.GetXaxis().SetTitle( plotopt.axis_captions[plotopt.vars_to_draw[0].lstrip("+")]) if len(plotopt.vars_to_draw) > 1: plot.GetYaxis().SetTitle( plotopt.axis_captions[plotopt.vars_to_draw[1].lstrip("+")]) if (plotopt.i2d): plot.Draw("CONT4Z " + sameDrawOpt) else: plot.Draw(rootopt.drawopt + sameDrawOpt) sameDrawOpt = " SAME" #plot the rest & fill the legend in the normal order for rootopt in rootopts: plot = plots[plotopt][rootopt] prname = rootopt.legendname if optmean and (not plotopt.profile): prname += " (mean: " + ("%.4f" % plot.GetMean()) + ")" leg.AddEntry(plot, prname, "L") if (rootopt.markerstyle == 0): #filler continue #fillers are already drawn print "Drawing plot from", rootopt.legendname if optzero: if (plotopt.logy == 1): plot.SetMinimum(1.0) else: plot.SetMinimum(0.0) plot.SetMaximum(valuemax * 1.1) plot.GetXaxis().SetTitle( plotopt.axis_captions[plotopt.vars_to_draw[0].lstrip("+")]) if len(plotopt.vars_to_draw) > 1: plot.GetYaxis().SetTitle( plotopt.axis_captions[plotopt.vars_to_draw[1].lstrip("+")]) if (plotopt.i2d): plot.Draw("CONT4Z " + sameDrawOpt) else: plot.Draw(rootopt.drawopt + sameDrawOpt) sameDrawOpt = " SAME" if not plotopt.i2d: legends.append(leg.Clone()) legends[len(legends) - 1].Draw() canv.Update() if output != "DISPLAY": canv.Close() ps.Close() return canv, legends
def train_and_apply(): np.random.seed(1) ROOT.gROOT.SetBatch() #Extract data from root file tree = uproot.open("out_all.root")["outA/Tevts"] branch_mc = [ "MC_B_P", "MC_B_eta", "MC_B_phi", "MC_B_pt", "MC_D0_P", "MC_D0_eta", "MC_D0_phi", "MC_D0_pt", "MC_Dst_P", "MC_Dst_eta", "MC_Dst_phi", "MC_Dst_pt", "MC_Est_mu", "MC_M2_miss", "MC_mu_P", "MC_mu_eta", "MC_mu_phi", "MC_mu_pt", "MC_pis_P", "MC_pis_eta", "MC_pis_phi", "MC_pis_pt", "MC_q2" ] branch_rec = [ "B_P", "B_eta", "B_phi", "B_pt", "D0_P", "D0_eta", "D0_phi", "D0_pt", "Dst_P", "Dst_eta", "Dst_phi", "Dst_pt", "Est_mu", "M2_miss", "mu_P", "mu_eta", "mu_phi", "mu_pt", "pis_P", "pis_eta", "pis_phi", "pis_pt", "q2" ] nvariable = len(branch_mc) x_train = tree.array(branch_mc[0], entrystop=options.maxevents) for i in range(1, nvariable): x_train = np.vstack( (x_train, tree.array(branch_mc[i], entrystop=options.maxevents))) x_test = tree.array(branch_rec[0], entrystop=options.maxevents) for i in range(1, nvariable): x_test = np.vstack( (x_test, tree.array(branch_rec[i], entrystop=options.maxevents))) x_train = x_train.T x_test = x_test.T x_test = array2D_float(x_test) #Different type of reconstruction variables #BN normalization gamma = 0 beta = 0.2 ar = np.array(x_train) a = K.constant(ar[:, 0]) mean = K.mean(a) var = K.var(a) x_train = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) for i in range(1, nvariable): a = K.constant(ar[:, i]) mean = K.mean(a) var = K.var(a) a = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) x_train = np.vstack((x_train, a)) x_train = x_train.T ar = np.array(x_test) a = K.constant(ar[:, 0]) mean = K.mean(a) var = K.var(a) x_test = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) for i in range(1, nvariable): a = K.constant(ar[:, i]) mean = K.mean(a) var = K.var(a) a = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) x_test = np.vstack((x_test, a)) x_test = x_test.T #Add noise, remain to be improved noise = np.random.normal(loc=0.0, scale=0.01, size=x_train.shape) x_train_noisy = x_train + noise noise = np.random.normal(loc=0.0, scale=0.01, size=x_test.shape) x_test_noisy = x_test + noise x_train = np.clip(x_train, -1., 1.) x_test = np.clip(x_test, -1., 1.) x_train_noisy = np.clip(x_train_noisy, -1., 1.) x_test_noisy = np.clip(x_test_noisy, -1., 1.) # Network parameters input_shape = (x_train.shape[1], ) batch_size = 128 latent_dim = 2 # Build the Autoencoder Model # First build the Encoder Model inputs = Input(shape=input_shape, name='encoder_input') x = inputs # Shape info needed to build Decoder Model shape = K.int_shape(x) # Generate the latent vector latent = Dense(latent_dim, name='latent_vector')(x) # Instantiate Encoder Model encoder = Model(inputs, latent, name='encoder') encoder.summary() # Build the Decoder Model latent_inputs = Input(shape=(latent_dim, ), name='decoder_input') x = Dense(shape[1])(latent_inputs) x = Reshape((shape[1], ))(x) outputs = Activation('tanh', name='decoder_output')(x) # Instantiate Decoder Model decoder = Model(latent_inputs, outputs, name='decoder') decoder.summary() # Autoencoder = Encoder + Decoder # Instantiate Autoencoder Model autoencoder = Model(inputs, decoder(encoder(inputs)), name='autoencoder') autoencoder.summary() autoencoder.compile(loss='mse', optimizer='adam') # Train the autoencoder autoencoder.fit(x_train_noisy, x_train, validation_data=(x_test_noisy, x_test), epochs=options.epochs, batch_size=batch_size) # Predict the Autoencoder output from corrupted test imformation x_decoded = autoencoder.predict(x_test_noisy) # Draw Comparision Plots c = TCanvas("c", "c", 700, 700) fPads1 = TPad("pad1", "Run2", 0.0, 0.29, 1.00, 1.00) fPads2 = TPad("pad2", "", 0.00, 0.00, 1.00, 0.29) fPads1.SetBottomMargin(0.007) fPads1.SetLeftMargin(0.10) fPads1.SetRightMargin(0.03) fPads2.SetLeftMargin(0.10) fPads2.SetRightMargin(0.03) fPads2.SetBottomMargin(0.25) fPads1.Draw() fPads2.Draw() fPads1.cd() nbin = 50 min = -1. max = 1. variable = "P^{B}" lbin = (max - min) / nbin lbin = str(float((max - min) / nbin)) xtitle = branch_rec[options.branch - 1] ytitle = "Events/" + lbin + "GeV" h_rec = TH1D("h_rec", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max) h_rec.Sumw2() h_pre = TH1D("h_pre", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max) h_pre.Sumw2() for i in range(x_test_noisy.shape[0]): h_rec.Fill(x_test_noisy[i][options.branch - 1]) h_pre.Fill(x_decoded[i][options.branch - 1]) h_rec = UnderOverFlow1D(h_rec) h_pre = UnderOverFlow1D(h_pre) maxY = TMath.Max(h_rec.GetMaximum(), h_pre.GetMaximum()) h_rec.SetLineColor(2) h_rec.SetFillStyle(0) h_rec.SetLineWidth(2) h_rec.SetLineStyle(1) h_pre.SetLineColor(3) h_pre.SetFillStyle(0) h_pre.SetLineWidth(2) h_pre.SetLineStyle(1) h_rec.SetStats(0) h_pre.SetStats(0) h_rec.GetYaxis().SetRangeUser(0, maxY * 1.1) h_rec.Draw("HIST") h_pre.Draw("same HIST") h_rec.GetYaxis().SetTitleSize(0.06) h_rec.GetYaxis().SetTitleOffset(0.78) theLeg = TLegend(0.5, 0.45, 0.95, 0.82, "", "NDC") theLeg.SetName("theLegend") theLeg.SetBorderSize(0) theLeg.SetLineColor(0) theLeg.SetFillColor(0) theLeg.SetFillStyle(0) theLeg.SetLineWidth(0) theLeg.SetLineStyle(0) theLeg.SetTextFont(42) theLeg.SetTextSize(.05) theLeg.AddEntry(h_rec, "Reconstruction", "L") theLeg.AddEntry(h_pre, "Prediction", "L") theLeg.SetY1NDC(0.9 - 0.05 * 6 - 0.005) theLeg.SetY1(theLeg.GetY1NDC()) fPads1.cd() theLeg.Draw() title = TLatex( 0.91, 0.93, "AE prediction compare with reconstruction, epochs=" + str(options.epochs)) title.SetNDC() title.SetTextSize(0.05) title.SetTextFont(42) title.SetTextAlign(31) title.SetLineWidth(2) title.Draw() fPads2.cd() h_Ratio = h_pre.Clone("h_Ratio") h_Ratio.Divide(h_rec) h_Ratio.SetLineColor(1) h_Ratio.SetLineWidth(2) h_Ratio.SetMarkerStyle(8) h_Ratio.SetMarkerSize(0.7) h_Ratio.GetYaxis().SetRangeUser(0, 2) h_Ratio.GetYaxis().SetNdivisions(504, 0) h_Ratio.GetYaxis().SetTitle("Pre/Rec") h_Ratio.GetYaxis().SetTitleOffset(0.35) h_Ratio.GetYaxis().SetTitleSize(0.13) h_Ratio.GetYaxis().SetTitleSize(0.13) h_Ratio.GetYaxis().SetLabelSize(0.11) h_Ratio.GetXaxis().SetLabelSize(0.1) h_Ratio.GetXaxis().SetTitleOffset(0.8) h_Ratio.GetXaxis().SetTitleSize(0.14) h_Ratio.SetStats(0) axis1 = TGaxis(min, 1, max, 1, 0, 0, 0, "L") axis1.SetLineColor(1) axis1.SetLineWidth(1) for i in range(1, h_Ratio.GetNbinsX() + 1, 1): D = h_rec.GetBinContent(i) eD = h_rec.GetBinError(i) if D == 0: eD = 0.92 B = h_pre.GetBinContent(i) eB = h_pre.GetBinError(i) if B < 0.1 and eB >= B: eB = 0.92 Err = 0. if B != 0.: Err = TMath.Sqrt((eD * eD) / (B * B) + (D * D * eB * eB) / (B * B * B * B)) h_Ratio.SetBinContent(i, D / B) h_Ratio.SetBinError(i, Err) if B == 0.: Err = TMath.Sqrt((eD * eD) / (eB * eB) + (D * D * eB * eB) / (eB * eB * eB * eB)) h_Ratio.SetBinContent(i, D / 0.92) h_Ratio.SetBinError(i, Err) if D == 0 and B == 0: h_Ratio.SetBinContent(i, -1) h_Ratio.SetBinError(i, 0) h_Ratio.Draw("e0") axis1.Draw() c.SaveAs(branch_rec[options.branch - 1] + "_comparision.png")
wjets_color = ROOT.TColor.GetColor(0.717, 0.815, 0.749) zvv_color = (kAzure + 3) syst_color = ROOT.TColor.GetColor(0.960, 0.925, 0.6) color = [ qcd_color, vh_color, diboson_color, singletop_color, ttbar_color, zll_color, wjets_color, zvv_color ] print color legend = TLegend(0.65, 0.7, 0.92, 0.89) legend.SetTextSize(0.046) legend.SetBorderSize(0) legend.SetLineColor(1) legend.SetLineStyle(1) legend.SetLineWidth(1) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) legend.SetNColumns(2) i = 0 for iprocess in processes: hist_met_ = fin.Get('h_summary_' + iprocess) hist_met_.Sumw2() hist_met_.SetDirectory(0) TH1.AddDirectory(0) # gStyle.SetPalette(53) hist_met_.SetFillColor(color[i]) #hist_met_.SetLineColor(color[i]) bkgStack.Add(hist_met_, 'hist')
def makeLimitPlot(output, obs, exp, chan, printStats=False, obs2="", ratioLabel=""): fileObs = open(obs, 'r') fileExp = open(exp, 'r') observedx = [] observedy = [] obsLimits = {} for entry in fileObs: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits: obsLimits[massPoint] = [] obsLimits[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits) for massPoint in sorted(obsLimits): observedx.append(massPoint) observedy.append(numpy.mean(obsLimits[massPoint])) if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits[massPoint]), " std dev: ", numpy.std( obsLimits[massPoint]), " from: ", obsLimits[massPoint] if not obs2 == "": fileObs2 = open(obs2, 'r') observedx2 = [] observedy2 = [] obsLimits2 = {} for entry in fileObs2: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits2: obsLimits2[massPoint] = [] obsLimits2[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits2) for massPoint in sorted(obsLimits2): observedx2.append(massPoint) observedy2.append(numpy.mean(obsLimits2[massPoint])) if (numpy.std(obsLimits2[massPoint]) / numpy.mean(obsLimits2[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits2[massPoint]), " std dev: ", numpy.std( obsLimits2[massPoint] ), " from: ", obsLimits2[massPoint] limits = {} expectedx = [] expectedy = [] expected1SigLow = [] expected1SigHigh = [] expected2SigLow = [] expected2SigHigh = [] for entry in fileExp: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: expectedx.append(massPoint) expectedy.append(limits[massPoint][medianNr]) expected1SigLow.append(limits[massPoint][lower1Sig]) expected1SigHigh.append(limits[massPoint][upper1Sig]) expected2SigLow.append(limits[massPoint][lower2Sig]) expected2SigHigh.append(limits[massPoint][upper2Sig]) expX = numpy.array(expectedx) expY = numpy.array(expectedy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] if printStats: print "length of expectedx: ", len(expectedx) if printStats: print "length of expected1SigLow: ", len(expected1SigLow) if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(expectedx)): values2.append(expected2SigLow[x]) xPointsForValues2.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values2.append(expected2SigHigh[x]) xPointsForValues2.append(expectedx[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(expectedx)): values.append(expected1SigLow[x]) xPointsForValues.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values.append(expected1SigHigh[x]) xPointsForValues.append(expectedx[x]) if printStats: print "length of values: ", len(values) exp2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) exp1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) if printStats: print "xPoints2: ", xPoints2 if printStats: print "exp2Sig: ", exp2Sig if printStats: print "xPoints: ", xPoints if printStats: print "exp1Sig: ", exp1Sig GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig) GraphErr2Sig.SetFillColor(ROOT.kYellow + 1) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen) cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500) gStyle.SetOptStat(0) if not obs2 == "": plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() expX = numpy.array(expectedx) expY = numpy.array(expectedy) GraphExp = TGraph(len(expX), expX, expY) GraphExp.SetLineWidth(3) GraphExp.SetLineStyle(2) GraphExp.SetLineColor(ROOT.kBlue) obsX = numpy.array(observedx) obsY = numpy.array(observedy) if printStats: print "obsX: ", obsX if printStats: print "obsY: ", obsY if SMOOTH: smooth_obs = TGraphSmooth("normal") GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY) GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005) else: GraphObs = TGraph(len(obsX), obsX, obsY) GraphObs.SetLineWidth(3) if not obs2 == "": ratio = [] ratiox = [] for index, val in enumerate(observedy): mass = observedx[index] foundIndex = -1 for index2, mass2 in enumerate(observedx2): if mass == mass2: foundIndex = index2 if foundIndex > 0: ratio.append(observedy2[foundIndex] / val) ratiox.append(mass) ratioA = numpy.array(ratio) ratioX = numpy.array(ratiox) obsX2 = numpy.array(observedx2) obsY2 = numpy.array(observedy2) ratioGraph = TGraph(len(ratioX), ratioX, ratioA) if printStats: print "obsX2: ", obsX2 if printStats: print "obsY2: ", obsY2 if SMOOTH: smooth_obs2 = TGraphSmooth("normal") GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2) GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear", 0, 0.005) else: GraphObs2 = TGraph(len(obsX2), obsX2, obsY2) GraphObs2.SetLineWidth(3) 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]) * 1.3 / 1928) zpX = numpy.array(zprimeX) zpY = numpy.array(zprimeY) GraphZPrime = TGraph(481, 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]) * 1.3 / 1928) zpPsiX = numpy.array(zprimePsiX) zpPsiY = numpy.array(zprimePsiY) GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY) GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear") GraphZPrimePsiSmooth.SetLineWidth(3) GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue) #Draw the graphs: plotPad.SetLogy() if "Moriond" in output: DummyGraph = TH1F("DummyGraph", "", 100, 120, 4500) else: DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500) DummyGraph.GetXaxis().SetTitle("M [GeV]") 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) if "Moriond" in output: DummyGraph.GetXaxis().SetRangeUser(120, 4500) else: DummyGraph.GetXaxis().SetRangeUser(400, 4500) DummyGraph.SetMinimum(1e-8) DummyGraph.SetMaximum(4e-4) DummyGraph.GetXaxis().SetLabelSize(0.04) DummyGraph.GetXaxis().SetTitleSize(0.045) DummyGraph.GetXaxis().SetTitleOffset(1.) DummyGraph.GetYaxis().SetLabelSize(0.04) DummyGraph.GetYaxis().SetTitleSize(0.045) DummyGraph.GetYaxis().SetTitleOffset(1.) DummyGraph.Draw() if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphExp.Draw("lpsame") else: if obs2 == "": GraphExp.Draw("lp") GraphObs.Draw("plsame") if not obs2 == "": GraphObs2.SetLineColor(ROOT.kRed) GraphObs2.SetLineStyle(ROOT.kDashed) GraphObs2.Draw("plsame") if not SPIN2: GraphZPrimeSmooth.Draw("lsame") GraphZPrimePsiSmooth.Draw("lsame") cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.032) if not obs2 == "": if ratioLabel == "": ratioLabel = "Variant/Default" ratioLabels = ratioLabel.split("/") leg.AddEntry(GraphObs, "% Observed 95% CL limit" % ratioLabel[1], "l") leg.AddEntry(GraphObs2, "%s Observed 95% CL limit" % ratioLabel[0], "l") else: leg.AddEntry(GraphObs, "Observed 95% CL limit", "l") leg.AddEntry(GraphExp, "Expected 95% CL limit, median", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "Expected 95% CL limit, 1 s.d.", "f") leg.AddEntry(GraphErr2Sig, "Expected 95% CL limit, 2 s.d.", "f") leg1 = TLegend(0.665517, 0.483051, 0.834885, 0.623051, "", "brNDC") leg1.SetTextSize(0.032) if not SPIN2: leg1.AddEntry(GraphZPrimePsiSmooth, "Z'_{#Psi} (LOx1.3)", "l") leg1.AddEntry(GraphZPrimeSmooth, "Z'_{SSM} (LOx1.3)", "l") leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetLineColor(0) leg.Draw("hist") leg1.SetLineWidth(0) leg1.SetLineStyle(0) leg1.SetLineColor(0) leg1.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "36.3 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") 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() plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetBorderSize(0) plPrelim.Draw() if not obs2 == "": ratioPad.cd() line = ROOT.TLine(400, 1, 4500, 1) line.SetLineStyle(ROOT.kDashed) ROOT.gStyle.SetTitleSize(0.12, "Y") ROOT.gStyle.SetTitleYOffset(0.35) ROOT.gStyle.SetNdivisions(000, "Y") ROOT.gStyle.SetNdivisions(408, "Y") ratioPad.DrawFrame(400, 0.9, 4500, 1.1, "; ; %s" % ratioLabel) line.Draw("same") ratioGraph.Draw("sameP") cCL.Update() printPlots(cCL, output)
if drawObs: graph_limit_vs_mass__obs_limit.Draw("Lsame") graph_limit_vs_mass__exp_limit.Draw("Lsame") graph_limit_vs_mass__Th_limit.Draw("Lsame") drawCMS3(myC, 13, lumi_this) leg_limit_vs_mass_ = TLegend(0.38, 0.66, 0.81, 0.92) leg_limit_vs_mass_.SetHeader(label_this + ", c#tau_{#tilde{#chi}_{1}^{0}} = " + ctau_this_str + " cm") leg_limit_vs_mass_.SetBorderSize(0) leg_limit_vs_mass_.SetTextSize(0.03) leg_limit_vs_mass_.SetLineColor(1) leg_limit_vs_mass_.SetLineStyle(1) leg_limit_vs_mass_.SetLineWidth(1) leg_limit_vs_mass_.SetFillColor(0) leg_limit_vs_mass_.SetFillStyle(1001) leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__Th_limit, "Theoretical cross section", "L") if drawObs: leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__obs_limit, "Observed 95% CL upper limit", "L") leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__exp_limit, "Expected 95% CL upper limit", "L") leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__exp1sigma_limit, "#pm 1 #sigma Expected", "F") leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__exp2sigma_limit, "#pm 2 #sigma Expected", "F")
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.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(name_list[i] + '_' + str(i))) #print(histo_list) 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')
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)
class plotTogether: tfiles = {} lgx = 0.65 lgy = 0.4 def __init__(self): self.unctitle = '' self.MCplots = [] self.DAplots = [] self.NOplots = [] self.Otherplots = [] self.DIVplots = [] self.Canvases = [] self.Pads = [] self.unc = False ROOT.gStyle.SetOptFit(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetPadTickX(0) ROOT.gStyle.SetPadTickY(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetPadTopMargin(0.05) ROOT.gStyle.SetPadRightMargin(0.05) ROOT.gStyle.SetPadBottomMargin(0.15) ROOT.gStyle.SetPadLeftMargin(0.15) ROOT.gStyle.SetLabelFont(43, "x") ROOT.gStyle.SetLabelFont(43, "y") ROOT.gStyle.SetLabelFont(43, "z") ROOT.gStyle.SetLabelOffset(0.01, "x") ROOT.gStyle.SetLabelOffset(0.01, "y") ROOT.gStyle.SetLabelOffset(0.01, "z") ROOT.gStyle.SetLabelSize(25, "x") ROOT.gStyle.SetLabelSize(25, "y") ROOT.gStyle.SetLabelSize(25, "z") ROOT.gStyle.SetTitleFont(43, "x") ROOT.gStyle.SetTitleFont(43, "y") ROOT.gStyle.SetTitleFont(43, "z") ROOT.gStyle.SetTitleOffset(1.2, "x") ROOT.gStyle.SetTitleOffset(1.5, "y") ROOT.gStyle.SetTitleOffset(1.1, "z") ROOT.gStyle.SetTitleSize(30, "x") ROOT.gStyle.SetTitleSize(30, "y") ROOT.gStyle.SetTitleSize(30, "z") def legend(self, legtitle): xpos = 1. - ROOT.gPad.GetRightMargin() ypos = 1. - ROOT.gPad.GetTopMargin() #self.lg = TLegend(0.55, 0.4, xpos-0.02, ypos-0.02) self.lg = TLegend(self.lgx, self.lgy, xpos - 0.02, ypos - 0.02) if len(legtitle) != 0: self.lg.SetHeader(legtitle) self.lg.SetFillColor(0) self.lg.SetFillStyle(0) self.lg.SetLineColor(0) self.lg.SetLineStyle(0) self.lg.SetBorderSize(0) self.lg.SetShadowColor(0) self.lg.SetTextFont(42) self.lg.SetTextSize(0.07) def printLatexYieldTable(self, fname='yield_table.tex'): ''' This function will print a table based on how the addMCplot and addDAplot functions were called. It will sum over all files that have no title, and assing them to the previous title. So for example: plot[p].addMCplot(DYfile, p, 'V+Jets', DYscale, ROOT.kGreen+2, projection = pro) plot[p].addMCplot(Wfile, p, '', Wscale, ROOT.kGreen+2, projection = pro) will create a category 'V+Jets' that includes DY and W+jets events stored in DYfile and Wfile. A call to this function should be added just after a call to drawAddWithRatio for that particular histogram, and then, for example: can = plot[p].drawAddWithRatio( ....... if (p == "RECO/all_njets"): plot[p].printLatexYieldTable('totyield_table.tex' ''' MCtot = 0. MCtot_err = 0. category_yield = [] category_err = [] category_title = [] cat_yield = 0. cat_err = 0. for index, hist in enumerate(self.MCplots): if hist.GetTitle() != '': category_title.append(hist.GetTitle()) cat_yield = 0. cat_err = 0. err = ROOT.Double(0) # Make sure you run this over a histogram with known under- and overflows! # For example number of jets, or MET, anything that hasn't been initialized to -9 events = hist.IntegralAndError(0, hist.GetNbinsX() + 1, err) #events = hist.Integral() cat_yield += events cat_err = math.sqrt(cat_err * cat_err + err * err) if len(self.MCplots ) == index + 1 or self.MCplots[index + 1].GetTitle() != '': category_yield.append(cat_yield) category_err.append(cat_err) MCtot += events MCtot_err = math.sqrt(MCtot_err * MCtot_err + err * err) # Ready to print the numbers, first open the latex file: latexfile = open(fname, "w") latexfile.write( "\\begin{tabular}{l|r@{$\\pm$}l} \\hline \n") # r@{$\pm$}l latexfile.write("%-12s & %20s \\\\ \\hline \n" % ('Source', '\multicolumn{2}{c}{Yield}')) for i in range(len(category_title)): print "%-12s %5.1f +- %4.1f" % (category_title[i], category_yield[i], category_err[i]) latexfile.write( "%-12s & %5.1f & %4.1f \\\\ \n" % (category_title[i], category_yield[i], category_err[i])) print "%-12s %5.1f +- %4.1f" % ('BKG SUM ', MCtot, MCtot_err) latexfile.write("%-12s & %5.1f & %4.1f\\\\ \\hline \n" % ('BKG SUM ', MCtot, MCtot_err)) DAtot = 0. for hist in self.DAplots: DAtot += hist.Integral() print "%-12s %5i" % ('Data ', DAtot) latexfile.write("%-12s & \multicolumn{2}{c}{%5i} \\\\ \n" % ('Data ', DAtot)) latexfile.write("\\end{tabular} \n") latexfile.close() print "Wrote LaTeX table with yields in: ", fname print "The errors are obtained from ROOT::TH1::IntegralAndError() and added in quadrature per category" return [DAtot, MCtot, MCtot_err] def addMCplot(self, filename, histpath, title, scale, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.MCplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.MCplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) elif projection.startswith('Xbin:'): bins = projection.split('Xbin:')[-1].split('-') self.MCplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX( histpath.split('/')[-1] + '_myproX', int(bins[0]), int(bins[1])))) elif projection.startswith('Ybin:'): bins = projection.split('Ybin:')[-1].split('-') self.MCplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX( histpath.split('/')[-1] + '_myproY', int(bins[0]), int(bins[1])))) else: self.MCplots.append(TH1D(self.tfiles[filename].Get(histpath))) self.MCplots[-1].SetFillColor(color) self.MCplots[-1].SetLineColor(color) #self.MCplots[-1].Scale(scale, 'width') self.MCplots[-1].Scale(scale) self.MCplots[-1].SetTitle(title) def setUncTitle(self, unctitle): self.unctitle = unctitle def addUncerHist(self, fcentral, ferrdown, ferrup, hist, projection=''): if self.unc == False: self.herr = TH1D(self.DAplots[-1]) self.herr.Reset() self.herr.SetName('err') self.unc = True if fcentral not in self.tfiles: self.tfiles[fcentral] = TFile(fcentral, 'read') if ferrdown not in self.tfiles: self.tfiles[ferrdown] = TFile(ferrdown, 'read') if ferrup not in self.tfiles: self.tfiles[ferrup] = TFile(ferrup, 'read') hcen = self.tfiles[fcentral].Get(hist) hdown = self.tfiles[ferrdown].Get(hist) hup = self.tfiles[ferrup].Get(hist) if projection == 'Y': hcen = TH1D(hcen.ProjectionY()) hdown = TH1D(hdown.ProjectionY()) hup = TH1D(hup.ProjectionY()) if projection == 'X': hcen = TH1D(hcen.ProjectionX()) hdown = TH1D(hdown.ProjectionX()) hup = TH1D(hup.ProjectionX()) elif projection.startswith('Xbin:'): bins = projection.split('Xbin:')[-1].split('-') hcen = TH1D( hcen.ProjectionX( hist.split('/')[-1] + '_myproX', int(bins[0]), int(bins[1]))) hdown = TH1D( hdown.ProjectionX( hist.split('/')[-1] + '_myproX', int(bins[0]), int(bins[1]))) hup = TH1D( hup.ProjectionX( hist.split('/')[-1] + '_myproX', int(bins[0]), int(bins[1]))) elif projection.startswith('Ybin:'): bins = projection.split('Ybin:')[-1].split('-') hcen = TH1D( hcen.ProjectionY( hist.split('/')[-1] + '_myproY', int(bins[0]), int(bins[1]))) hdown = TH1D( hdown.ProjectionY( hist.split('/')[-1] + '_myproY', int(bins[0]), int(bins[1]))) hup = TH1D( hup.ProjectionY( hist.split('/')[-1] + '_myproY', int(bins[0]), int(bins[1]))) for b in range(1, 1 + self.herr.GetNbinsX()): cen = hcen.GetBinContent(b) if cen == 0: continue up = hup.GetBinContent(b) down = hdown.GetBinContent(b) old = self.herr.GetBinContent(b) errA = (up - cen) / cen errB = (down - cen) / cen err = math.sqrt((errA**2 + errB**2) / 2.) #err = max(abs(errA), abs(errB)) self.herr.SetBinContent(b, math.sqrt(old**2 + err**2)) def addUncerVal(self, val): if self.unc == False: self.herr = TH1D(self.DAplots[-1]) self.herr.Reset() self.herr.SetName('err') self.unc = True for b in range(1, 1 + self.herr.GetNbinsX()): old = self.herr.GetBinContent(b) self.herr.SetBinContent(b, math.sqrt(old**2 + val**2)) def addDAplot(self, filename, histpath, title, projection='', scale=1.): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.DAplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.DAplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) elif projection.startswith('Xbin:'): bins = projection.split('Xbin:')[-1].split('-') self.DAplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX( histpath.split('/')[-1] + '_myproX', int(bins[0]), int(bins[1])))) elif projection.startswith('Ybin:'): bins = projection.split('Ybin:')[-1].split('-') self.DAplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX( histpath.split('/')[-1] + '_myproY', int(bins[0]), int(bins[1])))) else: self.DAplots.append(TH1D(self.tfiles[filename].Get(histpath))) self.DAplots[-1].SetTitle(title) self.DAplots[-1].Scale(scale) #self.DAplots[-1].Scale(1., 'width') self.DAplots[-1].Scale(1.) def addOtherplot(self, filename, histpath, title, scale, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.Otherplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.Otherplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.Otherplots.append(TH1D(self.tfiles[filename].Get(histpath))) #self.NOplots[-1].SetFillColor(color) self.Otherplots[-1].SetLineColor(color) self.Otherplots[-1].SetTitle(title) self.Otherplots[-1].Scale(scale) def addNormplot(self, filename, histpath, title, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.NOplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.NOplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.NOplots.append(TH1D(self.tfiles[filename].Get(histpath))) #self.NOplots[-1].SetFillColor(color) self.NOplots[-1].SetLineColor(color) self.NOplots[-1].SetTitle(title) def drawAddWithRatio(self, options='hist', rebin=1, legtitle='', title='DEFAULT', ratio=False, rangemin=0., rangemax=0., printbinwidth=True, xtitle='', ytitle='', logy=False, xlabels=[]): self.cumaddhist = [] self.cumaddhist.append(TH1D(self.MCplots[0])) for hist in self.MCplots[1:]: self.cumaddhist.append(TH1D(self.cumaddhist[-1])) self.cumaddhist[-1].Add(hist) self.cumaddhist[-1].SetFillColor(hist.GetFillColor()) self.cumaddhist[-1].SetLineColor(hist.GetLineColor()) self.cumaddhist[-1].SetTitle(hist.GetTitle()) totalevents = 0. for hist in self.MCplots: if rangemin != rangemax: hist.GetXaxis().SetRangeUser(rangemin, rangemax) totalevents += hist.Integral() print 'Total MC events: ', totalevents totalevents = 0. for hist in self.DAplots: if rangemin != rangemax: hist.GetXaxis().SetRangeUser(rangemin, rangemax) totalevents += hist.Integral() print 'Total DA events: ', totalevents mymax = 0. self.Canvases.append( TCanvas('CanvasAdd_' + self.cumaddhist[-1].GetName(), 'CanvasAdd_' + self.cumaddhist[-1].GetName(), 800, 600)) if ratio == True: split = 0.3 spaceleft = 0.15 spaceright = 0.05 self.Pads.append(TPad("histpad", "histpad", 0, split, 1., 1.)) self.Pads[-1].SetTopMargin(0.05) self.Pads[-1].SetBottomMargin(0.022) self.Pads[-1].SetLeftMargin(spaceleft) self.Pads[-1].SetRightMargin(spaceright) self.Pads[-1].Draw() self.Canvases[-1].cd() self.Pads.append(TPad("divpad", "divpad", 0, 0, 1., split)) self.Pads[-1].SetTopMargin(0.0) self.Pads[-1].SetBottomMargin(0.4) self.Pads[-1].SetLeftMargin(spaceleft) self.Pads[-1].SetRightMargin(spaceright) self.Pads[-1].Draw() self.Pads[-2].cd() if len(title) > 0: ROOT.gPad.SetTopMargin(0.1) self.legend(legtitle) if len(xlabels) != 0: b = 0 for label in xlabels: b += 1 self.cumaddhist[-1].GetXaxis().SetBinLabel(b, label) if ratio == True: self.cumaddhist[-1].GetXaxis().SetTitleOffset(5.) self.cumaddhist[-1].GetXaxis().SetLabelOffset(5.) for hist in reversed(self.cumaddhist): hist.Rebin(rebin) hist.Draw(options) mymax = max(mymax, hist.GetMaximum()) if rangemin != 0 or rangemax != 0: hist.GetXaxis().SetRangeUser(rangemin, rangemax) if 'same' not in options: if self.unc: self.herr.Rebin(rebin) self.herr.Scale(1. / rebin) self.errprint = TH1D(hist) self.errprint.SetName('errprint') for b in range(1, self.errprint.GetNbinsX() + 1): self.errprint.SetBinError( b, self.herr.GetBinContent(b) * hist.GetBinContent(b)) self.errprint.SetFillColor(1) self.errprint.SetLineColor(1) self.errprint.SetFillStyle(3354) self.errprint.Draw('E2same') units = re.findall('\[.*\]', hist.GetXaxis().GetTitle()) unit = '' if len(units) == 1: unit = units[0][1:-1] if ytitle == '': if len(hist.GetYaxis().GetTitle()) == 0: ytitle = 'Events' else: ytitle = hist.GetYaxis().GetTitle() #ytitle = ytitle.lower() if printbinwidth == True: hist.GetYaxis().SetTitle( ytitle + ' / {0:g}'.format(hist.GetXaxis().GetBinWidth(1)) + ' ' + unit) else: hist.GetYaxis().SetTitle(ytitle) if (xtitle != ''): hist.GetXaxis().SetTitle(xtitle) options += ' same' for np in self.NOplots: np.Rebin(rebin) np.Scale(self.DAplots[0].Integral() / np.Integral()) np.SetLineWidth(2) np.Draw('sameE0') mymax = max(mymax, np.GetMaximum()) for op in self.Otherplots: op.Rebin(rebin) op.SetLineWidth(2) op.Draw('sameE0') mymax = max(mymax, op.GetMaximum()) if len(self.DAplots) == 1: self.DAplots[0].Rebin(rebin) self.DAplots[0].SetMarkerStyle(20) self.DAplots[0].SetMarkerSize(1.1) self.DAplots[0].SetLineWidth(2) self.DAplots[0].Draw('E1X0same') mymax = max(mymax, self.DAplots[0].GetMaximum()) if len(self.DAplots) == 1: self.lg.AddEntry(self.DAplots[0], self.DAplots[0].GetTitle(), 'p') for hist in reversed(self.cumaddhist): if len(hist.GetTitle()) != 0: self.lg.AddEntry(hist, hist.GetTitle(), 'f') for np in self.NOplots: self.lg.AddEntry(np, np.GetTitle() + ' (Scaled)', 'l') for op in self.Otherplots: self.lg.AddEntry(op, op.GetTitle(), 'l') if len(self.unctitle) != 0: self.lg.AddEntry(self.errprint, self.unctitle, 'f') self.lg.Draw() #self.settitle(title) settitle(title) setchannel() cmstext() if logy == False: self.cumaddhist[-1].GetYaxis().SetRangeUser(0, mymax * 1.5) if logy == True: self.cumaddhist[-1].GetYaxis().SetRangeUser(10, mymax * 50) self.Pads[-2].SetLogy(True) self.Pads[-2].RedrawAxis() if ratio == True: self.Pads[-1].cd() self.Pads[-1].SetGridy() self.DIVplots.append(TH1D(self.DAplots[0])) if (xtitle != ''): self.DIVplots[-1].GetXaxis().SetTitle(xtitle) self.DIVplots[-1].GetXaxis().SetTitle( self.DIVplots[-1].GetXaxis().GetTitle().replace( 'additional', 'Additional')) #self.DIVplots[-1].Divide(self.cumaddhist[-1]) for b in range(1, self.DIVplots[-1].GetNbinsX() + 1): if (self.cumaddhist[-1].GetBinContent(b) > 0.): divval = self.DIVplots[-1].GetBinContent( b) / self.cumaddhist[-1].GetBinContent(b) divvalerr = self.DIVplots[-1].GetBinError( b) / self.cumaddhist[-1].GetBinContent(b) self.DIVplots[-1].SetBinContent(b, divval) #self.DIVplots[-1].SetBinError(b, divvalerr) self.DIVplots[-1].SetBinError( b, math.sqrt(divvalerr**2 + (self.cumaddhist[-1].GetBinError(b) / self.cumaddhist[-1].GetBinContent(b))**2)) else: self.DIVplots[-1].SetBinContent(b, 0.) self.DIVplots[-1].SetBinError(b, 0.) self.DIVplots[-1].SetMarkerSize(1.1) if len(xlabels) != 0: b = 0 for label in xlabels: b += 1 self.DIVplots[-1].GetXaxis().SetBinLabel(b, label) self.DIVplots[-1].Draw('E1X0same') self.DIVplots[-1].GetXaxis().SetTitleOffset(3) self.DIVplots[-1].GetYaxis().SetTitle('#frac{Data}{Simulation} ') self.DIVplots[-1].GetYaxis().SetTitleOffset(1.3) self.DIVplots[-1].GetYaxis().SetRangeUser(0.5, 1.5) self.DIVplots[-1].GetYaxis().SetNdivisions(105) if rangemin != 0 or rangemax != 0: self.DIVplots[-1].GetXaxis().SetRangeUser(rangemin, rangemax) if self.unc: self.errprintratio = TH1D(self.herr) for b in range(1, self.errprintratio.GetNbinsX() + 1): self.errprintratio.SetBinError(b, self.herr.GetBinContent(b)) self.errprintratio.SetBinContent(b, 1.) self.errprintratio.SetFillColor(1) self.errprintratio.SetFillStyle(3354) self.errprintratio.Draw('E2same') self.DIVplots[-1].Draw('E1X0same') self.Pads[-1].RedrawAxis() return (self.Canvases[-1])
class plotUnc: tfiles = {} lgx = 0.65 lgy = 0.4 def __init__(self): self.MCplots = [] self.MCplotsUp = [] self.MCplotsDown = [] self.DAplots = [] self.Otherplots = [] self.DIVplots = [] self.Canvases = [] self.Pads = [] self.unc = False ROOT.gStyle.SetOptFit(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetPadTickX(0) ROOT.gStyle.SetPadTickY(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetPadTopMargin(0.05) ROOT.gStyle.SetPadRightMargin(0.05) ROOT.gStyle.SetPadBottomMargin(0.15) ROOT.gStyle.SetPadLeftMargin(0.15) ROOT.gStyle.SetLabelFont(43, "x") ROOT.gStyle.SetLabelFont(43, "y") ROOT.gStyle.SetLabelFont(43, "z") ROOT.gStyle.SetLabelOffset(0.01, "x") ROOT.gStyle.SetLabelOffset(0.01, "y") ROOT.gStyle.SetLabelOffset(0.01, "z") ROOT.gStyle.SetLabelSize(25, "x") ROOT.gStyle.SetLabelSize(25, "y") ROOT.gStyle.SetLabelSize(25, "z") ROOT.gStyle.SetTitleFont(43, "x") ROOT.gStyle.SetTitleFont(43, "y") ROOT.gStyle.SetTitleFont(43, "z") ROOT.gStyle.SetTitleOffset(1.2, "x") ROOT.gStyle.SetTitleOffset(1.5, "y") ROOT.gStyle.SetTitleOffset(1.1, "z") ROOT.gStyle.SetTitleSize(30, "x") ROOT.gStyle.SetTitleSize(30, "y") ROOT.gStyle.SetTitleSize(30, "z") def legend(self, legtitle): xpos = 1. - ROOT.gPad.GetRightMargin() ypos = 1. - ROOT.gPad.GetTopMargin() #self.lg = TLegend(0.55, 0.4, xpos-0.02, ypos-0.02) self.lg = TLegend(self.lgx, self.lgy, xpos - 0.02, ypos - 0.02) if len(legtitle) != 0: self.lg.SetHeader(legtitle) self.lg.SetFillColor(0) self.lg.SetFillStyle(0) self.lg.SetLineColor(0) self.lg.SetLineStyle(0) self.lg.SetBorderSize(0) self.lg.SetShadowColor(0) self.lg.SetTextFont(42) self.lg.SetTextSize(0.07) def setchannel(self, title='#splitline{l+jets parton}{%s}' % njets): xpos = 1. - ROOT.gPad.GetRightMargin() ypos = 1. - ROOT.gPad.GetTopMargin() lxtitle = TLatex(0., 0., 'Z') lxtitle.SetNDC(True) lxtitle.SetTextFont(63) lxtitle.SetTextSize(25) lxtitle.SetTextAlign(13) lxtitle.DrawLatex(0.35, ypos - 0.03, title) def cmstext(self, add=''): xpos = ROOT.gPad.GetLeftMargin() ypos = 1. - ROOT.gPad.GetTopMargin() self.lx = TLatex(0., 0., 'Z') self.lx.SetNDC(True) self.lx.SetTextFont(62) self.lx.SetTextSize(0.07) self.lx.SetTextAlign(13) self.lx.DrawLatex(xpos + 0.04, ypos - 0.02, 'CMS') self.lx2 = TLatex(0., 0., 'Z') self.lx2.SetNDC(True) self.lx2.SetTextFont(52) self.lx2.SetTextSize(0.07) self.lx2.SetTextAlign(13) self.lx2.DrawLatex(xpos + 0.04, ypos - 0.08, add) def settitle(self, title): xpos = 1. - ROOT.gPad.GetRightMargin() ypos = 1. - ROOT.gPad.GetTopMargin() self.lxtitle = TLatex(0., 0., 'Z') self.lxtitle.SetNDC(True) self.lxtitle.SetTextFont(42) self.lxtitle.SetTextSize(0.07) self.lxtitle.SetTextAlign(31) self.lxtitle.DrawLatex(xpos, ypos + 0.02, title) def addCentralplot(self, filename, histpath, title, scale, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.MCplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.MCplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.MCplots.append(TH1D(self.tfiles[filename].Get(histpath))) #self.MCplots[-1].SetFillColor(color) self.MCplots[-1].SetLineColor(color) #self.MCplots[-1].Scale(scale, 'width') self.MCplots[-1].Scale(scale) self.MCplots[-1].SetTitle(title) return self.MCplots def addTplotUp(self, filename, histpath, title, scale, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.MCplotsUp.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.MCplotsUp.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.MCplotsUp.append(TH1D(self.tfiles[filename].Get(histpath))) self.MCplotsUp[-1].SetLineColor(color) self.MCplotsUp[-1].SetTitle(title) self.MCplotsUp[-1].Scale(scale) #self.MCplotsUp[-1].Scale(1., 'width') #self.MCplotsUp[-1].Scale(1.)//close box return self.MCplotsUp def addTplotDown(self, filename, histpath, title, scale, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.MCplotsDown.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.MCplotsDown.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.MCplotsDown.append(TH1D(self.tfiles[filename].Get(histpath))) self.MCplotsDown[-1].SetLineColor(color) self.MCplotsDown[-1].SetTitle(title) self.MCplotsDown[-1].Scale(scale) #self.MCplots[-1].Scale(1., 'width') #self.MCplots[-1].Scale(1.)//close box return self.MCplotsDown def addOtherplot(self, filename, histpath, title, scale, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.Otherplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.Otherplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.Otherplots.append(TH1D(self.tfiles[filename].Get(histpath))) self.Otherplots[-1].SetLineColor(color) self.Otherplots[-1].SetTitle(title) self.Otherplots[-1].Scale(scale) return self.Otherplots def drawAddWithRelUnc(self, options='hist', rebin=1, legtitle='', title='', ratio=False, rangemin=0., rangemax=0., printbinwidth=True, xtitle='', ytitle='', logy=False): self.cumaddhist = [] self.cumaddhist.append(TH1D(self.MCplots[0])) self.cumaddhist.append(TH1D(self.Otherplots[0])) self.cumaddhist.append(TH1D(self.Otherplots[1])) for hist in self.MCplots[1:]: self.cumaddhist.append(TH1D(self.cumaddhist[-1])) self.cumaddhist[-1].Add(hist) self.cumaddhist[-1].SetFillColor(hist.GetFillColor()) self.cumaddhist[-1].SetLineColor(hist.GetLineColor()) self.cumaddhist[-1].SetTitle(hist.GetTitle()) totalevents = 0. for hist in self.MCplots: if rangemin != rangemax: hist.GetXaxis().SetRangeUser(rangemin, rangemax) totalevents += hist.Integral() print 'Total MC events: ', totalevents totalevents = 0. for hist in self.DAplots: if rangemin != rangemax: hist.GetXaxis().SetRangeUser(rangemin, rangemax) totalevents += hist.Integral() print 'Total DA events: ', totalevents mymax = 0. self.Canvases.append( TCanvas('CanvasAdd_' + self.cumaddhist[-1].GetName(), 'CanvasAdd_' + self.cumaddhist[-1].GetName(), 800, 600)) if ratio == True: split = 0.3 spaceleft = 0.15 spaceright = 0.05 self.Pads.append(TPad("histpad", "histpad", 0, split, 1., 1.)) self.Pads[-1].SetTopMargin(0.05) self.Pads[-1].SetBottomMargin(0.022) self.Pads[-1].SetLeftMargin(spaceleft) self.Pads[-1].SetRightMargin(spaceright) self.Pads[-1].Draw() self.Canvases[-1].cd() self.Pads.append(TPad("divpad", "divpad", 0, 0, 1., split)) self.Pads[-1].SetTopMargin(0.0) self.Pads[-1].SetBottomMargin(0.4) self.Pads[-1].SetLeftMargin(spaceleft) self.Pads[-1].SetRightMargin(spaceright) self.Pads[-1].Draw() self.Pads[-2].cd() if len(title) > 0: ROOT.gPad.SetTopMargin(0.1) self.legend(legtitle) if ratio == True: self.cumaddhist[-1].GetXaxis().SetTitleOffset(5.) self.cumaddhist[-1].GetXaxis().SetLabelOffset(5.) for hist in reversed(self.cumaddhist): hist.Rebin(rebin) hist.Draw(options) mymax = max(mymax, hist.GetMaximum()) if rangemin != 0 or rangemax != 0: hist.GetXaxis().SetRangeUser(rangemin, rangemax) if 'same' not in options: units = re.findall('\[.*\]', hist.GetXaxis().GetTitle()) unit = '' if len(units) == 1: unit = units[0][1:-1] if ytitle == '': if len(hist.GetYaxis().GetTitle()) == 0: ytitle = 'Events' else: ytitle = hist.GetYaxis().GetTitle() #ytitle = ytitle.lower() if printbinwidth == True: hist.GetYaxis().SetTitle( ytitle + ' / {0:g}'.format(hist.GetXaxis().GetBinWidth(1)) + ' ' + unit) else: hist.GetYaxis().SetTitle(ytitle) if (xtitle != ''): hist.GetXaxis().SetTitle(xtitle) options += ' same' for op in self.Otherplots: op.Rebin(rebin) op.SetLineWidth(2) #op.Draw('sameE0')//close box mymax = max(mymax, op.GetMaximum()) if len(self.DAplots) == 1: self.DAplots[0].Rebin(rebin) self.DAplots[0].SetMarkerStyle(20) self.DAplots[0].SetMarkerSize(1.1) self.DAplots[0].SetLineWidth(2) self.DAplots[0].Draw('E1X0same') mymax = max(mymax, self.DAplots[0].GetMaximum()) if len(self.DAplots) == 1: self.lg.AddEntry(self.DAplots[0], self.DAplots[0].GetTitle(), 'p') for hist in reversed(self.cumaddhist): if len(hist.GetTitle()) != 0: self.lg.AddEntry(hist, hist.GetTitle(), 'f') for op in self.Otherplots: self.lg.AddEntry(op, op.GetTitle(), 'l') self.lg.Draw() self.settitle(title) self.setchannel() self.cmstext() if logy == False: self.cumaddhist[-1].GetYaxis().SetRangeUser(0, mymax * 1.5) if logy == True: self.cumaddhist[-1].GetYaxis().SetRangeUser(10, mymax * 50) self.Pads[-2].SetLogy(True) self.Pads[-2].RedrawAxis() if ratio == True: self.Pads[-1].cd() self.Pads[-1].SetGridy() self.DIVplots.append(TH1D(self.Otherplots[0])) self.DIVplots.append(TH1D(self.Otherplots[1])) if (xtitle != ''): self.DIVplots[-1].GetXaxis().SetTitle(xtitle) #self.DIVplots[-1].Divide(self.cumaddhist[-1]) for b in range(1, self.DIVplots[-1].GetNbinsX() + 1): if (self.cumaddhist[-1].GetBinContent(b) > 0.): divval = self.DIVplots[-1].GetBinContent( b) / self.cumaddhist[-1].GetBinContent(b) divvalerr = self.DIVplots[-1].GetBinError( b) / self.cumaddhist[-1].GetBinContent(b) self.DIVplots[-1].SetBinContent(b, divval) #self.DIVplots[-1].SetBinError(b, divvalerr) self.DIVplots[-1].SetBinError( b, math.sqrt(divvalerr**2 + (self.cumaddhist[-1].GetBinError(b) / self.cumaddhist[-1].GetBinContent(b))**2)) else: self.DIVplots[-1].SetBinContent(b, 0.) self.DIVplots[-1].SetBinError(b, 0.) self.DIVplots[-1].SetMarkerSize(1.1) self.DIVplots[-1].Draw('E1X0same') self.DIVplots[-1].GetXaxis().SetTitleOffset(3) self.DIVplots[-1].GetYaxis().SetTitle('relative unc') self.DIVplots[-1].GetYaxis().SetTitleOffset(1.3) self.DIVplots[-1].GetYaxis().SetRangeUser(0.5, 1.5) self.DIVplots[-1].GetYaxis().SetNdivisions(105) if rangemin != 0 or rangemax != 0: self.DIVplots[-1].GetXaxis().SetRangeUser(rangemin, rangemax) self.DIVplots[-1].Draw('E1X0same') self.Pads[-1].RedrawAxis() return (self.Canvases[-1])
if drawObs: graph_limit_vs_mass_v1_obs_limit.Draw("Lsame") graph_limit_vs_mass_v1_exp_limit.Draw("Lsame") graph_limit_vs_mass_v1_Th_limit.Draw("Lsame") drawCMS2(myC, 13, lumi) leg_limit_vs_mass_v1 = TLegend(0.25, 0.62, 0.9, 0.89) leg_limit_vs_mass_v1.SetHeader( "c#tau_{#tilde{#chi}_{1}^{0}} = " + str(ctau_this) + " cm, #tilde{#chi}^{0}_{1} #rightarrow #gamma #tilde{G}") leg_limit_vs_mass_v1.SetBorderSize(0) leg_limit_vs_mass_v1.SetTextSize(0.03) leg_limit_vs_mass_v1.SetLineColor(1) leg_limit_vs_mass_v1.SetLineStyle(1) leg_limit_vs_mass_v1.SetLineWidth(1) leg_limit_vs_mass_v1.SetFillColor(0) leg_limit_vs_mass_v1.SetFillStyle(1001) leg_limit_vs_mass_v1.AddEntry(graph_limit_vs_mass_v1_Th_limit, "Theoretical cross-section", "L") if drawObs: leg_limit_vs_mass_v1.AddEntry(graph_limit_vs_mass_v1_obs_limit, "Observed 95% CL upper limit", "L") leg_limit_vs_mass_v1.AddEntry(graph_limit_vs_mass_v1_exp_limit, "Expected 95% CL upper limit", "L") leg_limit_vs_mass_v1.AddEntry(graph_limit_vs_mass_v1_exp1sigma_limit, "#pm 1 #sigma Expected", "F") leg_limit_vs_mass_v1.AddEntry(graph_limit_vs_mass_v1_exp2sigma_limit, "#pm 2 #sigma Expected", "F")
if drawObs: graph_limit_vs_mass__obs_limit.Draw("Lsame") graph_limit_vs_mass__exp_limit.Draw("Lsame") graph_limit_vs_mass__Th_limit.Draw("Lsame") drawCMS2(myC, 13, lumi_this) leg_limit_vs_mass_ = TLegend(0.25, 0.62, 0.9, 0.89) leg_limit_vs_mass_.SetHeader( "c#tau_{#tilde{#chi}_{1}^{0}} = " + str(ctau_this) + " cm, #tilde{#chi}^{0}_{1} #rightarrow #gamma #tilde{G}") leg_limit_vs_mass_.SetBorderSize(0) leg_limit_vs_mass_.SetTextSize(0.03) leg_limit_vs_mass_.SetLineColor(1) leg_limit_vs_mass_.SetLineStyle(1) leg_limit_vs_mass_.SetLineWidth(1) leg_limit_vs_mass_.SetFillColor(0) leg_limit_vs_mass_.SetFillStyle(1001) leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__Th_limit, "Theoretical cross-section", "L") if drawObs: leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__obs_limit, "Observed 95% CL upper limit", "L") leg_limit_vs_mass_.AddEntry(graph_limit_vs_mass__exp_limit, "Expected 95% CL upper limit", "L") leg_limit_vs_mass_.Draw() myC.SaveAs(outputDir + "/limits" + "/limit_vs_mass_" + year_this + "_ctau" + ctau_this_str + plot_tag + ".pdf")
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.4, 0.70, 0.939, 0.89) #,NULL,"brNDC"); legendtitle = legendtext[-1] leg.SetHeader(legendtitle) leg.SetBorderSize(0) leg.SetNColumns(2) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(22) leg.SetTextSize(0.045) c = TCanvas("c1", "c1", 0, 0, 500, 500) #c.SetBottomMargin(0.15) #c.SetLeftMargin(0.15) #c.SetLogy(0) #c.SetLogx(0) c1_2 = TPad("c1_2", "newpad", 0.04, 0.05, 1, 0.994) c1_2.Draw() print("you have provided " + str(len(fileVec)) + " files and " + str(len(histVec)) + " histograms to make a overlapping plot") print "opening rootfiles" c.cd() #c1_2.SetBottomMargin(0.13) c1_2.SetLogy(logstatus[1]) c1_2.SetLogx(logstatus[0]) c1_2.cd() ii = 0 inputfile = {} print str(fileVec[(len(fileVec) - 1)]) for ifile_ in range(len(fileVec)): print("opening file " + fileVec[ifile_]) inputfile[ifile_] = TFile(fileVec[ifile_]) print "fetching histograms" for ihisto_ in range(len(histVec)): print("printing histo " + str(histVec[ihisto_])) histo = inputfile[ifile_].Get(histVec[ihisto_]) #status_ = type(histo) is TGraphAsymmErrors histList.append(histo) # for ratio plot as they should nt be normalize histList1.append(histo) print histList[ii].Integral() #histList[ii].Rebin(xRange[2]) type_obj = type(histList[ii]) if (type_obj is TH1D) or (type_obj is TH1F) or ( type_obj is TH1) or (type_obj is TH1I): histList[ii].Rebin(1) 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]) # print "graph_status =" ,(tt is TGraphAsymmErrors) # print "hist status =", (tt is TH1D) or (tt is TH1F) if ih == 0: if (tt is TGraphAsymmErrors) | (tt is TGraph): histList[ih].Draw("A3P") 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) | (tt is TGraph): histList[ih].Draw("3P same") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("HISTsame") if (tt is TGraphAsymmErrors) | (tt is TGraph): # histList[ih].SetMaximum(0.06) # histList[ih].SetMinimum(0.02) # histList[ih].SetMaximum(maximum+0.3) histList[ih].SetMinimum(0.02) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetLineWidth(3) histList[ih].SetLineStyle(linestyle[ih]) histList[ih].SetMarkerStyle(markerStyle[ih]) histList[ih].SetMarkerSize(1) leg.AddEntry(histList[ih], legendtext[ih], "P") 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) histList[ih].SetMaximum(maximum[0] + 0.3) histList[ih].SetMinimum(0) leg.AddEntry(histList[ih], legendtext[ih], "L") histList[ih].GetYaxis().SetTitle(titleVec[1]) histList[ih].GetYaxis().SetTitleSize(0.045) histList[ih].GetYaxis().SetTitleOffset(1.1000998) histList[ih].GetYaxis().SetTitleFont(22) histList[ih].GetYaxis().SetLabelFont(22) histList[ih].GetYaxis().SetLabelSize(.045) histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1]) histList[ih].GetXaxis().SetLabelSize(0.0000) histList[ih].GetXaxis().SetTitle(titleVec[0]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitleSize(0.052) histList[ih].GetXaxis().SetTitleOffset(1.04) histList[ih].GetXaxis().SetTitleFont(22) histList[ih].GetXaxis().SetTickLength(0.07) histList[ih].GetXaxis().SetLabelFont(22) histList[ih].GetYaxis().SetLabelFont(22) # histList[ih].GetXaxis().SetNdivisions(508) # i = i + 1 pt = TPaveText(0.0877181, 0.9, 0.9580537, 0.96, "brNDC") pt.SetBorderSize(0) pt.SetTextAlign(12) pt.SetFillStyle(0) pt.SetTextFont(22) pt.SetTextSize(0.046) text = pt.AddText(0.05, 0.5, "CMS Preliminary") #text = pt.AddText(0.5,0.5,"12.9 fb^{-1} (13 TeV)") # text = pt.AddText(0.8,0.5," (13 TeV)") # text = pt.AddText(0.65,0.5," AK8") pt.Draw() # t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC") # t2a.SetBorderSize(0) # t2a.SetFillStyle(0) # t2a.SetTextSize(0.040) # t2a.SetTextAlign(12) # t2a.SetTextFont(62) # histolabel1= str(fileVec[(len(fileVec)-1)]) # text1 = t2a.AddText(0.06,0.5,"CMS Internal") # t2a.Draw() leg.Draw() # # c.cd() outputdirname = 'HGCAL/' histname = outputdirname + pngname c.SaveAs(histname + '.png') c.SaveAs(histname + '.pdf')
def DrawOverlap(histList, titleVec, legendtext, pngname, logstatus=[0, 0], xRange=[-99999, 99999, 1], cat='2b'): gStyle.SetOptTitle(0) gStyle.SetOptStat(0) gStyle.SetTitleOffset(1.1, "Y") #gStyle.SetTitleOffset(1.9,"X"); gStyle.SetLineWidth(3) gStyle.SetFrameLineWidth(3) gStyle.SetTickLength(0.0, "x") i = 0 # histList_=[] # histList=[] # histList1=[] # maximum=[] ## Legend leg = TLegend(0.2, 0.80, 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(42) leg.SetTextSize(0.05) c = TCanvas("c1", "c1", 0, 0, 500, 500) c.SetBottomMargin(0.15) c.SetLeftMargin(0.15) c.SetLogy(logstatus[1]) c.SetLogx(logstatus[0]) # print ("you have provided "+str(len(fileVec))+" files and "+str(len(histVec))+" histograms to make a overlapping plot" ) # print "opening rootfiles" c.cd() print "provided hists", histList for ih in range(len(histList)): tt = type(histList[ih]) if logstatus[1] is 1: histList[ih].SetMaximum(1.5) #1.4 for log histList[ih].SetMinimum(0.1) #1.4 for log if logstatus[1] is 0: maxi = histList[ih].GetMaximum() histList[ih].SetMaximum(maxi * 2) #1.4 for log histList[ih].SetMinimum(0) #1.4 for log # print "graph_status =" ,(tt is TGraphAsymmErrors) # print "hist status =", (tt is TH1D) or (tt is TH1F) if ih == 0: if tt is TGraphAsymmErrors: histList[ih].Draw("APL") if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I): histList[ih].Draw("PE2 ") 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("PE0 same") if tt is TGraphAsymmErrors: histList[ih].SetMaximum(100) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetLineWidth(0) 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): print "setting style for hist" print "color code", colors[ih] # histList[ih].SetLineStyle(linestyle[ih]) histList[ih].SetLineColor(colors[ih]) histList[ih].SetMarkerColor(colors[ih]) histList[ih].SetFillColor(colors[ih]) histList[ih].SetMarkerStyle(20) histList[ih].SetMarkerSize(1.0) histList[ih].SetLineWidth(1) #invert legend between first and second if ih == 0: leg.AddEntry(histList[ih + 1], legendtext[ih + 1], "PEL") #"f") if ih == 1: leg.AddEntry(histList[ih - 1], legendtext[ih - 1], 'f') #"PEL") histList[ih].GetYaxis().SetTitle(titleVec[1]) histList[ih].GetYaxis().SetTitleSize(0.052) histList[ih].GetYaxis().SetTitleOffset(1.4) histList[ih].GetYaxis().SetTitleFont(42) histList[ih].GetYaxis().SetLabelFont(42) 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.14) histList[ih].GetXaxis().SetTitleFont(42) histList[ih].GetXaxis().SetLabelFont(42) histList[ih].GetYaxis().SetLabelFont(42) histList[ih].GetXaxis().SetNdivisions(507) #histList[ih].GetXaxis().SetMoreLogLabels(); #histList[ih].GetXaxis().SetNoExponent(); #histList[ih].GetTGaxis().SetMaxDigits(3); # histList[ih].GetXaxis().SetTickSize(0.00) i = i + 1 pt = TPaveText(0.01, 0.92, 0.95, 0.96, "brNDC") pt.SetBorderSize(0) pt.SetTextAlign(12) pt.SetFillStyle(0) pt.SetTextFont(42) pt.SetTextSize(0.046) #text = pt.AddText(0.12,0.35,"CMS Internal 36 fb^{-1} (2016) ") text = pt.AddText(0.12, 0.35, "CMS Internal 41.5 fb^{-1} (2017) ") #text = pt.AddText(0.12,0.35,"CMS Internal 59.6 fb^{-1} (2018) ") #text = pt.AddText(0.6,0.5,"41.5 fb^{-1} (2017) ") cattxt = TLatex(0.20, 0.75, cat + ' ' + "category") cattxt.SetTextSize(0.06) cattxt.SetTextAlign(12) cattxt.SetNDC(1) cattxt.SetTextFont(42) pt.Draw() cattxt.Draw() leg.Draw() outputdirname = 'TFplots/' histname = outputdirname + pngname c.SaveAs(histname + '.png') c.SaveAs(histname + '.pdf')
def makeLimitPlot(output, obs, exp, chan, printStats=False, obs2="", ratioLabel=""): #fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE") fileObs = open(obs, 'r') fileExp = open(exp, 'r') observedx = [] observedy = [] obsLimits = {} for entry in fileObs: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits: obsLimits[massPoint] = [] obsLimits[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits) for massPoint in sorted(obsLimits): observedx.append(massPoint) observedy.append(numpy.mean(obsLimits[massPoint])) if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits[massPoint]), " std dev: ", numpy.std( obsLimits[massPoint]), " from: ", obsLimits[massPoint] if not obs2 == "": fileObs2 = open(obs2, 'r') observedx2 = [] observedy2 = [] obsLimits2 = {} for entry in fileObs2: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits2: obsLimits2[massPoint] = [] obsLimits2[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits2) for massPoint in sorted(obsLimits2): observedx2.append(massPoint) observedy2.append(numpy.mean(obsLimits2[massPoint])) if (numpy.std(obsLimits2[massPoint]) / numpy.mean(obsLimits2[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits2[massPoint]), " std dev: ", numpy.std( obsLimits2[massPoint] ), " from: ", obsLimits2[massPoint] limits = {} expectedx = [] expectedy = [] expected1SigLow = [] expected1SigHigh = [] expected2SigLow = [] expected2SigHigh = [] for entry in fileExp: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: expectedx.append(massPoint) print massPoint, limits[massPoint][medianNr] expectedy.append(limits[massPoint][medianNr]) expected1SigLow.append(limits[massPoint][lower1Sig]) expected1SigHigh.append(limits[massPoint][upper1Sig]) expected2SigLow.append(limits[massPoint][lower2Sig]) expected2SigHigh.append(limits[massPoint][upper2Sig]) expX = numpy.array(expectedx) expY = numpy.array(expectedy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] xPointsForErrors = [] if printStats: print "length of expectedx: ", len(expectedx) if printStats: print "length of expected1SigLow: ", len(expected1SigLow) if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(expectedx)): values2.append(expected2SigLow[x]) xPointsForValues2.append(expectedx[x]) xPointsForErrors.append(0) for x in range(len(expectedx) - 1, 0 - 1, -1): values2.append(expected2SigHigh[x]) xPointsForValues2.append(expectedx[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(expectedx)): values.append(expected1SigLow[x]) xPointsForValues.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values.append(expected1SigHigh[x]) xPointsForValues.append(expectedx[x]) if printStats: print "length of values: ", len(values) exp2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) exp1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) xPointsErrors = numpy.array(xPointsForErrors) if printStats: print "xPoints2: ", xPoints2 if printStats: print "exp2Sig: ", exp2Sig if printStats: print "xPoints: ", xPoints if printStats: print "exp1Sig: ", exp1Sig GraphErr2SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY, numpy.array(xPointsErrors), numpy.array(xPointsErrors), numpy.array(expected2SigLow), numpy.array(expected2SigHigh)) GraphErr1SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY, numpy.array(xPointsErrors), numpy.array(xPointsErrors), numpy.array(expected1SigLow), numpy.array(expected1SigHigh)) GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig) GraphErr2Sig.SetFillColor(ROOT.kOrange) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen + 1) #cCL=TCanvas("cCL", "cCL",0,0,567,384) cCL = TCanvas("cCL", "cCL", 0, 0, 600, 450) gStyle.SetOptStat(0) gStyle.SetPadRightMargin(0.063) gStyle.SetPadLeftMargin(0.14) gStyle.SetPadBottomMargin(0.12) if not obs2 == "": plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() expX = numpy.array(expectedx) expY = numpy.array(expectedy) GraphExp = TGraph(len(expX), expX, expY) GraphExp.SetLineWidth(3) GraphExp.SetLineStyle(2) GraphExp.SetLineColor(ROOT.kBlue) obsX = numpy.array(observedx) obsY = numpy.array(observedy) if printStats: print "obsX: ", obsX if printStats: print "obsY: ", obsY if SMOOTH: smooth_obs = TGraphSmooth("normal") GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY) GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005) else: GraphObs = TGraph(len(obsX), obsX, obsY) GraphObs.SetLineWidth(3) if not obs2 == "": ratio = [] ratiox = [] for index, val in enumerate(observedy): mass = observedx[index] foundIndex = -1 for index2, mass2 in enumerate(observedx2): if mass == mass2: foundIndex = index2 if foundIndex > 0: ratio.append(observedy2[foundIndex] / val) ratiox.append(mass) ratioA = numpy.array(ratio) ratioX = numpy.array(ratiox) obsX2 = numpy.array(observedx2) obsY2 = numpy.array(observedy2) ratioGraph = TGraph(len(ratioX), ratioX, ratioA) if printStats: print "obsX2: ", obsX2 if printStats: print "obsY2: ", obsY2 if SMOOTH: smooth_obs2 = TGraphSmooth("normal") GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2) GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear", 0, 0.005) else: GraphObs2 = TGraph(len(obsX2), obsX2, obsY2) GraphObs2.SetLineWidth(3) if SPIN2: signals = ["RS_kMpl01", "RS_kMpl005", "RS_kMpl001"] elif GUT: signals = ["ssm", "psi", "kai", "eta", "I", "S", "N"] else: signals = ["ssm", "psi"] xSecCurves = [] for signal in signals: xSecCurves.append(getXSecCurve(signal, kFacs[signal])) #xSecCurves.append(getXSecCurve(signal,kFacs[signal],massDependent=True)) #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(1e-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() if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphExp.Draw("lpsame") else: if obs2 == "": GraphExp.Draw("lp") if not EXPONLY: GraphObs.Draw("plsame") if not obs2 == "": GraphObs2.SetLineColor(ROOT.kRed) GraphObs2.SetLineStyle(ROOT.kDashed) GraphObs2.Draw("plsame") for curve in xSecCurves: curve.Draw("lsame") plCMS = TPaveLabel(.16, .81, .27, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetFillStyle(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.SetFillStyle(0) plPrelim.SetBorderSize(0) if "2017" in output or "Combination" in output: plPrelim.Draw() cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") #leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC") Default leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC") if SPIN2: leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.0425) if not obs2 == "": if ratioLabel == "": ratioLabel = "Variant/Default" ratioLabels = ratioLabel.split("/") print ratioLabels leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit" % ratioLabels[1], "l") leg.AddEntry(GraphObs2, "%s Obs. 95%% CL limit" % ratioLabels[0], "l") else: if not EXPONLY: leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l") leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f") leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f") leg1 = TLegend(0.7, 0.4, 0.9, 0.55, "", "brNDC") leg1.SetTextSize(0.05) if GUT: leg1 = TLegend(0.6, 0.35, 0.75, 0.623051, "", "brNDC") if SPIN2: leg1 = TLegend(0.7, 0.35, 0.9, 0.58, "G_{KK} (LO x 1.6)", "brNDC") leg1.SetTextSize(0.045) for index, signal in enumerate(signals): xSecCurves[index].SetName(labels[signal]) xSecCurves[index].Write(labels[signal]) leg1.AddEntry(xSecCurves[index], labels[signal], "l") leg1.SetBorderSize(0) leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetFillStyle(0) leg.SetLineColor(0) leg.Draw("hist") leg1.SetLineWidth(0) leg1.SetLineStyle(0) leg1.SetFillStyle(0) leg1.SetLineColor(0) leg1.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") elif "2017" in output or "Combination" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .885, .9, .99, "42.4 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .885, .9, .99, "41.4 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .27, .885, .9, .99, "77.3 fb^{-1} (13 TeV, ee) + 78.7 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.SetTicks(1, 1) plotPad.RedrawAxis() if not obs2 == "": ratioPad.cd() line = ROOT.TLine(200, 1, 5500, 1) line.SetLineStyle(ROOT.kDashed) ROOT.gStyle.SetTitleSize(0.12, "Y") ROOT.gStyle.SetTitleYOffset(0.35) ROOT.gStyle.SetNdivisions(000, "Y") ROOT.gStyle.SetNdivisions(408, "Y") ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel) line.Draw("same") ratioGraph.Draw("sameP") #GraphErr2SigForHEPData.SetName("graph2Sig") #GraphErr2SigForHEPData.Write("graph2Sig") #GraphErr1SigForHEPData.SetName("graph1Sig") #GraphErr1SigForHEPData.Write("graph1Sig") #GraphExp.SetName("graphExp") #GraphExp.Write("graphExp") #GraphObs.SetName("graphObs") #GraphObs.Write("graphObs") #fileForHEPData.Write() #fileForHEPData.Close() cCL.Update() printPlots(cCL, output)
def makeLimitPlot(output, obs, exp, chan, printStats=False): 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, 800, 500) gStyle.SetOptStat(0) 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]) * 1.3 / 1928) zpX = numpy.array(zprimeX) zpY = numpy.array(zprimeY) GraphZPrime = TGraph(481, 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]) * 1.3 / 1928) zpPsiX = numpy.array(zprimePsiX) zpPsiY = numpy.array(zprimePsiY) GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY) GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear") GraphZPrimePsiSmooth.SetLineWidth(3) GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue) #Draw the graphs: plotPad.SetLogy() if "Moriond" in output: DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500) else: DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500) DummyGraph.GetXaxis().SetTitle("M [GeV]") 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) if "Moriond" in output: DummyGraph.GetXaxis().SetRangeUser(200, 5500) else: DummyGraph.GetXaxis().SetRangeUser(400, 4500) DummyGraph.SetMinimum(1e-8) DummyGraph.SetMaximum(4e-4) DummyGraph.GetXaxis().SetLabelSize(0.04) DummyGraph.GetXaxis().SetTitleSize(0.045) DummyGraph.GetXaxis().SetTitleOffset(1.) DummyGraph.GetYaxis().SetLabelSize(0.04) DummyGraph.GetYaxis().SetTitleSize(0.045) DummyGraph.GetYaxis().SetTitleOffset(1.) DummyGraph.Draw() plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetBorderSize(0) plPrelim.Draw() leg = TLegend(0.430517, 0.623051, 0.734885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.032) 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") # if not SPIN2: # GraphZPrimeSmooth.Draw("lsame") # GraphZPrimePsiSmooth.Draw("lsame") cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetLineColor(0) leg.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "35.9 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .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() cCL.Update() printPlots(cCL, output)
def DrawOverlap(fileVec, histVec, titleVec, legendtext, pngname, logstatus=[0, 0], xRange=[-99999, 99999, 1], text_="", x_=0.5, y_=0.5, legendloc=[0.53, 0.13, 0.93, 0.39]): 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 legpos = legendloc leg = TLegend(legpos[0], legpos[1], legpos[2], legpos[3]) leg.SetBorderSize(0) leg.SetNColumns(2) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.049) from PlotTemplates import myCanvas1D c = myCanvas1D() c.SetLogy(logstatus[1]) c.SetLogx(logstatus[0]) #c.SetBottomMargin(0.15) #c.SetLeftMargin(0.15) #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.00001) #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(10) 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(1.08) histList[ih].GetYaxis().SetLabelSize(.052) histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitle(titleVec[0]) histList[ih].GetXaxis().SetLabelSize(0.052) histList[ih].GetXaxis().SetTitleSize(0.052) histList[ih].GetXaxis().SetTitleOffset(1.14) #histList[ih].GetXaxis().SetTickLength(0.07) histList[ih].GetXaxis().SetNdivisions(508) from PlotTemplates import SetCMSAxis histList[ih] = SetCMSAxis(histList[ih], 1.0, 1.15) #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") ''' from PlotTemplates import drawenergy1D pt_ = drawenergy1D(False) for ipt in pt_: ipt.Draw() ''' if len(text_) >0: ltx = TLatex() ltx.SetTextFont(42) ltx.SetTextSize(0.049) #text_f = "#font[42]{Phase Scan}" ltx.DrawTextNDC(x_,y_,text_) ''' from PlotTemplates import ExtraText text_ex = ExtraText(text_, x_, y_) text_ex.Draw() ExtraText("ECAL Endcaps", 0.4, 0.85) ltx_ = TLatex() ltx_.SetTextFont(42) ltx_.SetTextSize(0.049) ltx_.DrawLatexNDC(0.32, 0.81, "L1 e-#gamma object p_{T} > 10 GeV") #text_ex.Draw() #pt = TPaveText(0.0877181,0.9,0.9580537,0.96,"brNDC") #text = pt.AddText(0.65,0.5,"Phase Scan data #sqrt{s} = 13 TeV (2018)") #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.SetHeader("Matched TP energy") leg.Draw() # # c.cd() outputdirname = './' histname = outputdirname + pngname c.SaveAs(histname + '.png') c.SaveAs(histname + '.pdf')
class plotTogether: tfiles = {} lgx = 0.65 lgy = 0.4 def __init__(self): self.unctitle = '' self.MCplots = [] self.DAplots = [] self.NOplots = [] self.Otherplots = [] self.DIVplots = [] self.Canvases = [] self.Pads = [] self.unc = False ROOT.gStyle.SetOptFit(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetPadTickX(0) ROOT.gStyle.SetPadTickY(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetPadTopMargin(0.05) ROOT.gStyle.SetPadRightMargin(0.05) ROOT.gStyle.SetPadBottomMargin(0.15) ROOT.gStyle.SetPadLeftMargin(0.15) ROOT.gStyle.SetLabelFont(43, "x") ROOT.gStyle.SetLabelFont(43, "y") ROOT.gStyle.SetLabelFont(43, "z") ROOT.gStyle.SetLabelOffset(0.01, "x") ROOT.gStyle.SetLabelOffset(0.01, "y") ROOT.gStyle.SetLabelOffset(0.01, "z") ROOT.gStyle.SetLabelSize(25, "x") ROOT.gStyle.SetLabelSize(25, "y") ROOT.gStyle.SetLabelSize(25, "z") ROOT.gStyle.SetTitleFont(43, "x") ROOT.gStyle.SetTitleFont(43, "y") ROOT.gStyle.SetTitleFont(43, "z") ROOT.gStyle.SetTitleOffset(1.2, "x") ROOT.gStyle.SetTitleOffset(1.5, "y") ROOT.gStyle.SetTitleOffset(1.1, "z") ROOT.gStyle.SetTitleSize(30, "x") ROOT.gStyle.SetTitleSize(30, "y") ROOT.gStyle.SetTitleSize(30, "z") def legend(self, legtitle): xpos = 1. - ROOT.gPad.GetRightMargin() ypos = 1. - ROOT.gPad.GetTopMargin() #self.lg = TLegend(0.55, 0.4, xpos-0.02, ypos-0.02) self.lg = TLegend(self.lgx, self.lgy, xpos - 0.02, ypos - 0.02) if len(legtitle) != 0: self.lg.SetHeader(legtitle) self.lg.SetFillColor(0) self.lg.SetFillStyle(0) self.lg.SetLineColor(0) self.lg.SetLineStyle(0) self.lg.SetBorderSize(0) self.lg.SetShadowColor(0) self.lg.SetTextFont(42) self.lg.SetTextSize(0.07) njetstr = sys.argv[3][0] + ' jets' if '6' not in sys.argv[ 3] and 'up' not in sys.argv[3] else '#geq' + sys.argv[3][0] + ' jets' def setchannel(self, title='e/#mu+jets, ' + njetstr): #def setchannel(self, title = 'e/#mu+jets, %s jets' %njets[0]): #def setchannel(self, title = 'e/#mu+jets, #geq%s jets' %njets[0]): #def setchannel(self, title = 'e/#mu+jets, #geq%s jets in SB' %njets[0]): #def setchannel(self, title = 'l+jets'): xpos = 1. - ROOT.gPad.GetRightMargin() ypos = 1. - ROOT.gPad.GetTopMargin() lxtitle = TLatex(0., 0., 'Z') lxtitle.SetNDC(True) lxtitle.SetTextFont(63) lxtitle.SetTextSize(25) lxtitle.SetTextAlign(13) lxtitle.DrawLatex(0.35, ypos - 0.03, title) def cmstext(self, add=''): xpos = ROOT.gPad.GetLeftMargin() ypos = 1. - ROOT.gPad.GetTopMargin() self.lx = TLatex(0., 0., 'Z') self.lx.SetNDC(True) self.lx.SetTextFont(62) self.lx.SetTextSize(0.07) self.lx.SetTextAlign(13) self.lx.DrawLatex(xpos + 0.04, ypos - 0.03, 'CMS') self.lx2 = TLatex(0., 0., 'Z') self.lx2.SetNDC(True) self.lx2.SetTextFont(52) self.lx2.SetTextSize(0.05) self.lx2.SetTextAlign(13) self.lx2.DrawLatex(xpos + 0.04, ypos - 0.10, 'Preliminary') def settitle(self, title): xpos = 1. - ROOT.gPad.GetRightMargin() ypos = 1. - ROOT.gPad.GetTopMargin() self.lxtitle = TLatex(0., 0., 'Z') self.lxtitle.SetNDC(True) self.lxtitle.SetTextFont(42) self.lxtitle.SetTextSize(0.07) self.lxtitle.SetTextAlign(31) self.lxtitle.DrawLatex(xpos, ypos + 0.02, title) def printLatexYieldTable(self, fname='yield_table.tex'): ''' This function will print a table based on how the addMCplot and addDAplot functions were called. It will sum over all files that have no title, and assing them to the previous title. So for example: plot[p].addMCplot(DYfile, p, 'V+Jets', DYscale, ROOT.kGreen+2, projection = pro) plot[p].addMCplot(Wfile, p, '', Wscale, ROOT.kGreen+2, projection = pro) will create a category 'V+Jets' that includes DY and W+jets events stored in DYfile and Wfile. A call to this function should be added just after a call to drawAddWithRatio for that particular histogram, and then, for example: can = plot[p].drawAddWithRatio( ....... if (p == "RECO/all_njets"): plot[p].printLatexYieldTable('totyield_table.tex' ''' MCtot = 0. MCtot_err = 0. category_yield = [] category_err = [] category_title = [] cat_yield = 0. cat_err = 0. for index, hist in enumerate(self.MCplots): if hist.GetTitle() != '': category_title.append(hist.GetTitle()) cat_yield = 0. cat_err = 0. err = ROOT.Double(0) # Make sure you run this over a histogram with known under- and overflows! # For example number of jets, or MET, anything that hasn't been initialized to -9 events = hist.IntegralAndError(0, hist.GetNbinsX() + 1, err) #events = hist.Integral() cat_yield += events cat_err = math.sqrt(cat_err * cat_err + err * err) if len(self.MCplots ) == index + 1 or self.MCplots[index + 1].GetTitle() != '': category_yield.append(cat_yield) category_err.append(cat_err) MCtot += events MCtot_err = math.sqrt(MCtot_err * MCtot_err + err * err) # Ready to print the numbers, first open the latex file: latexfile = open(fname, "w") latexfile.write( "\\begin{tabular}{l|r@{$\\pm$}l} \\hline \n") # r@{$\pm$}l latexfile.write("%-12s & %20s \\\\ \\hline \n" % ('Source', '\multicolumn{2}{c}{Yield}')) for i in range(len(category_title)): print "%-12s %5.1f +- %4.1f" % (category_title[i], category_yield[i], category_err[i]) latexfile.write( "%-12s & %5.1f & %4.1f \\\\ \n" % (category_title[i], category_yield[i], category_err[i])) print "%-12s %5.1f +- %4.1f" % ('BKG SUM ', MCtot, MCtot_err) latexfile.write("%-12s & %5.1f & %4.1f\\\\ \\hline \n" % ('BKG SUM ', MCtot, MCtot_err)) DAtot = 0. for hist in self.DAplots: DAtot += hist.Integral() print "%-12s %5i" % ('Data ', DAtot) latexfile.write("%-12s & \multicolumn{2}{c}{%5i} \\\\ \n" % ('Data ', DAtot)) latexfile.write("\\end{tabular} \n") latexfile.close() print "Wrote LaTeX table with yields in: ", fname print "The errors are obtained from ROOT::TH1::IntegralAndError() and added in quadrature per category" return [DAtot, MCtot, MCtot_err] def addMCplot(self, filename, histpath, title, scale, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') print "little fox", self.tfiles[filename], histpath if projection == 'Y': self.MCplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.MCplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.MCplots.append(TH1D(self.tfiles[filename].Get(histpath))) print "fox" self.MCplots[-1].SetFillColor(color) self.MCplots[-1].SetLineColor(color) #self.MCplots[-1].Scale(scale, 'width') self.MCplots[-1].Scale(scale) self.MCplots[-1].SetTitle(title) def setUncTitle(self, unctitle): self.unctitle = unctitle def addUncerHist(self, fcentral, datascale, datascaledw, datascaleup, ferrdown, ferrup, hist, scaleUnc, projection='', Norm=False, AsymmetricError=False): if self.unc == False: self.herr = TH1D(self.DAplots[-1]) self.herr.Reset() self.herr.SetName('err') if AsymmetricError: self.herrup = TH1D(self.DAplots[-1]) self.herrup.Reset() self.herrup.SetName('errup') self.herrdw = TH1D(self.DAplots[-1]) self.herrdw.Reset() self.herrdw.SetName('errdw') self.unc = True if fcentral not in self.tfiles: self.tfiles[fcentral] = TFile(fcentral, 'read') if ferrdown not in self.tfiles: self.tfiles[ferrdown] = TFile(ferrdown, 'read') if ferrup not in self.tfiles: self.tfiles[ferrup] = TFile(ferrup, 'read') hcen = self.tfiles[fcentral].Get(hist) hdown = self.tfiles[ferrdown].Get(hist) hup = self.tfiles[ferrup].Get(hist) print "normalization precheck:", hcen.Integral(), hdown.Integral( ), hup.Integral(), datascale, datascaleup, datascaledw if Norm and (hup.Integral() != 0. and hdown.Integral() != 0.): hcen.Scale(datascale) hup.Scale(datascaleup) hdown.Scale(datascaledw) hup.Scale(hcen.Integral() / hup.Integral()) hdown.Scale(hcen.Integral() / hdown.Integral()) else: hcen.Scale(datascale) hup.Scale(datascaleup) hdown.Scale(datascaledw) print "normalization check:", hcen.Integral(), hdown.Integral( ), hup.Integral() if projection == 'Y': hcen = TH1D(hcen.ProjectionY()) hdown = TH1D(hdown.ProjectionY()) hup = TH1D(hup.ProjectionY()) if projection == 'X': hcen = TH1D(hcen.ProjectionX()) hdown = TH1D(hdown.ProjectionX()) hup = TH1D(hup.ProjectionX()) self.cumaddhist = [] self.cumaddhist.append(TH1D(self.MCplots[0])) for hist in self.MCplots[1:]: self.cumaddhist.append(TH1D(self.cumaddhist[-1])) self.cumaddhist[-1].Add(hist) for b in range(1, 1 + self.herr.GetNbinsX()): cen = hcen.GetBinContent(b) tot = self.cumaddhist[-1].GetBinContent(b) if cen == 0 or tot == 0: continue up = hup.GetBinContent(b) down = hdown.GetBinContent(b) old = self.herr.GetBinContent(b) errA = (up - cen) * scaleUnc / cen errB = (down - cen) * scaleUnc / cen err = (abs(errA) + abs(errB)) / 2. #err = max(abs(errA), abs(errB)) compWeight = cen / tot self.herr.SetBinContent(b, math.sqrt(old**2 + err**2 * compWeight**2)) #self.herr.SetBinContent(b, math.sqrt(old**2 + err**2)) #print scaleUnc if AsymmetricError: old = self.herrup.GetBinContent(b) self.herrup.SetBinContent( b, math.sqrt(old**2 + errA**2 * compWeight**2)) old = self.herrdw.GetBinContent(b) self.herrdw.SetBinContent( b, math.sqrt(old**2 + errB**2 * compWeight**2)) #Those are important !!! hcen.Scale(1 / datascale) hup.Scale(1 / datascaleup) hdown.Scale(1 / datascaledw) if Norm and (hup.Integral() != 0 and hdown.Integral() != 0): hup.Scale(1 / (hcen.Integral() / hup.Integral())) hdown.Scale(1 / (hcen.Integral() / hdown.Integral())) def addUncerVal(self, val): if self.unc == False: self.herr = TH1D(self.DAplots[-1]) self.herr.Reset() self.herr.SetName('err') self.unc = True for b in range(1, 1 + self.herr.GetNbinsX()): old = self.herr.GetBinContent(b) self.herr.SetBinContent(b, math.sqrt(old**2 + val**2)) def addUncerValBins(self, valist): if self.unc == False: self.herr = TH1D(self.DAplots[-1]) self.herr.Reset() self.herr.SetName('err') self.unc = True for b in range(len(valist)): old = self.herr.GetBinContent(b + 4) print old, valist[b], math.sqrt(old**2 + valist[b]**2), b + 1 self.herr.SetBinContent(b + 4, math.sqrt(old**2 + valist[b]**2)) #def addDAplot(self, filename, histpath, title, projection = '', scale = 1.):#close box def addDAplot(self, filename, histpath, title, scale, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.DAplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.DAplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.DAplots.append(TH1D(self.tfiles[filename].Get(histpath))) self.DAplots[-1].SetTitle(title) self.DAplots[-1].Scale(scale) #self.DAplots[-1].Scale(1., 'width') self.DAplots[-1].Scale(1.) #//close box def addOtherplot(self, filename, histpath, title, scale, color, style=1, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.Otherplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.Otherplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.Otherplots.append(TH1D(self.tfiles[filename].Get(histpath))) #self.NOplots[-1].SetFillColor(color) self.Otherplots[-1].SetLineColor(color) self.Otherplots[-1].SetLineStyle(style) self.Otherplots[-1].SetTitle(title) self.Otherplots[-1].Scale(scale) def addNormplot(self, filename, histpath, title, color, projection=''): if filename not in self.tfiles: self.tfiles[filename] = TFile(filename, 'read') if projection == 'Y': self.NOplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionY())) elif projection == 'X': self.NOplots.append( TH1D(self.tfiles[filename].Get(histpath).ProjectionX())) else: self.NOplots.append(TH1D(self.tfiles[filename].Get(histpath))) #self.NOplots[-1].SetFillColor(color) self.NOplots[-1].SetLineColor(color) self.NOplots[-1].SetTitle(title) def drawAddWithRatio(self, options='hist', rebin=1, legtitle='', title='', ratio=False, rangemin=0., rangemax=0., printbinwidth=True, xtitle='', ytitle='', logy=False, xlabels=[], AsymmetricError=False): self.cumaddhist = [] self.cumaddhist.append(TH1D(self.MCplots[0])) for hist in self.MCplots[1:]: self.cumaddhist.append(TH1D(self.cumaddhist[-1])) self.cumaddhist[-1].Add(hist) self.cumaddhist[-1].SetFillColor(hist.GetFillColor()) self.cumaddhist[-1].SetLineColor(hist.GetLineColor()) self.cumaddhist[-1].SetTitle(hist.GetTitle()) totalevents = 0. for hist in self.MCplots: if rangemin != rangemax: hist.GetXaxis().SetRangeUser(rangemin, rangemax) totalevents += hist.Integral() print 'Total MC events: ', totalevents totalevents = 0. for hist in self.DAplots: if rangemin != rangemax: hist.GetXaxis().SetRangeUser(rangemin, rangemax) totalevents += hist.Integral() print 'Total DA events: ', totalevents mymax = 0. self.Canvases.append( TCanvas('CanvasAdd_' + self.cumaddhist[-1].GetName(), 'CanvasAdd_' + self.cumaddhist[-1].GetName(), 800, 600)) if ratio == True: split = 0.3 spaceleft = 0.15 spaceright = 0.05 self.Pads.append(TPad("histpad", "histpad", 0, split, 1., 1.)) self.Pads[-1].SetTopMargin(0.05) self.Pads[-1].SetBottomMargin(0.022) self.Pads[-1].SetLeftMargin(spaceleft) self.Pads[-1].SetRightMargin(spaceright) self.Pads[-1].Draw() self.Canvases[-1].cd() self.Pads.append(TPad("divpad", "divpad", 0, 0, 1., split)) self.Pads[-1].SetTopMargin(0.0) self.Pads[-1].SetBottomMargin(0.4) self.Pads[-1].SetLeftMargin(spaceleft) self.Pads[-1].SetRightMargin(spaceright) self.Pads[-1].Draw() self.Pads[-2].cd() if len(title) > 0: ROOT.gPad.SetTopMargin(0.1) self.legend(legtitle) if len(xlabels) != 0: b = 0 for label in xlabels: b += 1 self.cumaddhist[-1].GetXaxis().SetBinLabel(b, label) if ratio == True: self.cumaddhist[-1].GetXaxis().SetTitleOffset(5.) self.cumaddhist[-1].GetXaxis().SetLabelOffset(5.) xList, yList = array('d'), array('d') errleftList, errightList = array('d'), array('d') errupList, errdwList = array('d'), array('d') relupList, reldwList = array('d'), array('d') for hist in reversed(self.cumaddhist): hist.Rebin(rebin) hist.Draw(options) mymax = max(mymax, hist.GetMaximum()) if rangemin != 0 or rangemax != 0: hist.GetXaxis().SetRangeUser(rangemin, rangemax) if 'same' not in options: if self.unc: self.herr.Rebin(rebin) self.herr.Scale(1. / rebin) self.errprint = TH1D(hist) self.errprint.SetName('errprint') for b in range(1, self.errprint.GetNbinsX() + 1): self.errprint.SetBinError( b, self.herr.GetBinContent(b) * hist.GetBinContent(b)) self.errprint.SetFillColor(1) self.errprint.SetLineColor(1) self.errprint.SetLineWidth(0) self.errprint.SetFillStyle(3354) #self.errprint.SetFillStyle(3344) self.errprint.Draw('E2same') #//close box if AsymmetricError: self.herrup.Rebin(rebin) self.herrup.Scale(1. / rebin) self.herrdw.Rebin(rebin) self.herrdw.Scale(1. / rebin) #self.DAplots[0].Rebin(rebin) for b in range(1, 1 + self.herr.GetNbinsX()): xList.append(self.cumaddhist[-1].GetBinCenter(b)) yList.append(self.cumaddhist[-1].GetBinContent(b)) #yList.append(self.DAplots[0].GetBinContent(b)) errleftList.append(self.cumaddhist[-1].GetXaxis( ).GetBinCenter(b) - self.cumaddhist[-1].GetXaxis(). GetBinLowEdge(b)) errightList.append( self.cumaddhist[-1].GetXaxis().GetBinUpEdge( b) - self.cumaddhist[-1].GetXaxis().GetBinCenter(b)) #errupList.append(self.herrup.GetBinContent(b)*self.cumaddhist[-1].GetBinContent(b)) #errdwList.append(self.herrdw.GetBinContent(b)*self.cumaddhist[-1].GetBinContent(b)) errupList.append( self.herrup.GetBinContent(b) * self.DAplots[0].GetBinContent(b)) errdwList.append( self.herrdw.GetBinContent(b) * self.DAplots[0].GetBinContent(b)) relupList.append(self.herrup.GetBinContent(b)) reldwList.append(self.herrdw.GetBinContent(b)) self.gerr = TGraphAsymmErrors(len(xList), xList, yList, errleftList, errightList, errdwList, errupList) self.gerr.SetName('gerr') self.gerr.SetFillColor(1) self.gerr.SetLineColor(1) self.gerr.SetLineWidth(0) self.gerr.SetFillStyle(3354) self.gerr.Draw('E2same') #//close box #else: #self.errprint.Draw('E2same')#//close box units = re.findall('\[.*\]', hist.GetXaxis().GetTitle()) unit = '' if len(units) == 1: unit = units[0][1:-1] if ytitle == '': if len(hist.GetYaxis().GetTitle()) == 0: ytitle = 'Events' else: ytitle = hist.GetYaxis().GetTitle() #ytitle = ytitle.lower() if printbinwidth == True: hist.GetYaxis().SetTitle( ytitle + ' / {0:g}'.format(hist.GetXaxis().GetBinWidth(1)) + ' ' + unit) else: hist.GetYaxis().SetTitle(ytitle) if (xtitle != ''): hist.GetXaxis().SetTitle(xtitle) options += ' same' #if not AsymmetricError: # self.errprint.Draw('E2same')#//close box for np in self.NOplots: np.Rebin(rebin) np.Scale(self.DAplots[0].Integral() / np.Integral()) np.SetLineWidth(2) np.Draw('sameE0') #//close box mymax = max(mymax, np.GetMaximum()) for op in self.Otherplots: op.Rebin(rebin) op.SetLineWidth(2) op.Draw('sameE0') #//close box mymax = max(mymax, op.GetMaximum()) if len(self.DAplots) == 1: self.DAplots[0].Rebin(rebin) self.DAplots[0].SetMarkerStyle(20) self.DAplots[0].SetMarkerSize(1.1) self.DAplots[0].SetLineWidth(2) self.DAplots[0].Draw('E1X0same') mymax = max(mymax, self.DAplots[0].GetMaximum()) if len(self.DAplots) == 1: self.lg.AddEntry(self.DAplots[0], self.DAplots[0].GetTitle(), 'p') for hist in reversed(self.cumaddhist): if len(hist.GetTitle()) != 0: self.lg.AddEntry(hist, hist.GetTitle(), 'f') for np in self.NOplots: self.lg.AddEntry(np, np.GetTitle() + ' (Scaled)', 'l') for op in self.Otherplots: self.lg.AddEntry(op, op.GetTitle(), 'l') if len(self.unctitle) != 0: self.lg.AddEntry(self.errprint, self.unctitle, 'f') self.lg.Draw() self.settitle(title) self.setchannel() self.cmstext() if logy == False: self.cumaddhist[-1].GetYaxis().SetRangeUser(0, mymax * 1.5) if logy == True: self.cumaddhist[-1].GetYaxis().SetRangeUser(10, mymax * 50) self.Pads[-2].SetLogy(True) self.Pads[-2].RedrawAxis() if ratio == True: self.Pads[-1].cd() self.Pads[-1].SetGridy() self.DIVplots.append(TH1D(self.DAplots[0])) if (xtitle != ''): self.DIVplots[-1].GetXaxis().SetTitle(xtitle) #self.DIVplots[-1].Divide(self.cumaddhist[-1]) printList = [] for b in range(1, self.DIVplots[-1].GetNbinsX() + 1): if (self.cumaddhist[-1].GetBinContent(b) > 0.): divval = self.DIVplots[-1].GetBinContent( b) / self.cumaddhist[-1].GetBinContent(b) divvalerr = self.DIVplots[-1].GetBinError( b) / self.cumaddhist[-1].GetBinContent(b) printList.append(divval) self.DIVplots[-1].SetBinContent(b, divval) #self.DIVplots[-1].SetBinError(b, divvalerr) self.DIVplots[-1].SetBinError( b, math.sqrt(divvalerr**2 + (self.cumaddhist[-1].GetBinError(b) / self.cumaddhist[-1].GetBinContent(b))**2)) else: printList.append(0) self.DIVplots[-1].SetBinContent(b, 0.) self.DIVplots[-1].SetBinError(b, 0.) print printList self.DIVplots[-1].SetMarkerSize(1.1) if len(xlabels) != 0: b = 0 for label in xlabels: b += 1 self.DIVplots[-1].GetXaxis().SetBinLabel(b, label) self.DIVplots[-1].Draw('E1X0same') self.DIVplots[-1].GetXaxis().SetTitleOffset(3) self.DIVplots[-1].GetYaxis().SetTitle('#frac{Data}{MC}') self.DIVplots[-1].GetYaxis().SetTitleOffset(1.3) self.DIVplots[-1].GetYaxis().SetRangeUser(0.5, 1.5) self.DIVplots[-1].GetYaxis().SetNdivisions(105) if rangemin != 0 or rangemax != 0: self.DIVplots[-1].GetXaxis().SetRangeUser(rangemin, rangemax) if self.unc: self.errprintratio = TH1D(self.herr) for b in range(1, self.errprintratio.GetNbinsX() + 1): self.errprintratio.SetBinError(b, self.herr.GetBinContent(b)) self.errprintratio.SetBinContent(b, 1.) self.errprintratio.SetFillColor(1) #self.errprintratio.SetFillStyle(3002) self.errprintratio.SetFillStyle(3354) #self.errprintratio.Draw('E2same')#//close box if AsymmetricError: self.gerratio = TGraphAsymmErrors( len(xList), xList, array('d', [1] * len(xList)), errleftList, errightList, reldwList, relupList) self.gerratio.SetFillColor(1) self.gerratio.SetFillStyle(3354) self.gerratio.Draw('E2same') else: self.errprintratio.Draw('E2same') #//close box self.DIVplots[-1].Draw('E1X0same') self.Pads[-1].RedrawAxis() return (self.Canvases[-1])