def readHists(SystName): inputfile = read_rootfile() # assuming TTH_hww is always there gROOT.cd() histName = "TTH_hww" h0 = inputfile.Get(histName) h_nominal = h0.Clone("h_nominal") h_nominal.SetDirectory(0) h_nominal.Reset() h_nominal.SetMarkerStyle(1) hists = {} legends = {} Samples.reverse() for sample in Samples: legend = TLegend(0.4, 0.6, 0.9, 0.88) #legend.SetHeader("2017 "+fit_type+", 2lss l^{#pm}l^{#pm} #mu(ttH)=#hat#mu") legend.SetHeader("2017 prefit, " + header_postfix) #legend.SetNColumns(3) legend.SetBorderSize(0) hist = h_nominal.Clone(sample) hist.SetStats(0) hist.Reset() hist.SetTitle( "#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary} 41.53 fb^{-1}(13TeV)}" ) hist_up = h_nominal.Clone(sample + "_" + SystName + "Up") hist_up.SetStats(0) hist_up.Reset() hist_down = h_nominal.Clone(sample + "_" + SystName + "Down") hist_down.SetStats(0) hist_down.Reset() for p in Process[sample]: rootfile = read_rootfile() if rootfile.IsZombie(): continue gROOT.cd() if not rootfile.GetListOfKeys().Contains(p + "_" + SystName + "Up"): continue h1 = rootfile.Get(p) h1_up = rootfile.Get(p + "_" + SystName + "Up") #print ( " get "+p+"_"+SystName+"Up " ) h1_down = rootfile.Get(p + "_" + SystName + "Down") hist.Add(h1) hist_up.Add(h1_up) hist_down.Add(h1_down) rootfile.Close() hist.SetFillColor(0) hist.SetLineColor(Color["Nominal"]) hist.SetMarkerColor(Color["Nominal"]) hist_up.SetFillColor(0) hist_up.SetLineColor(Color["SystUp"]) hist_up.SetMarkerColor(Color["SystUp"]) hist_down.SetFillColor(0) hist_down.SetLineColor(Color["SystDown"]) hist_down.SetMarkerColor(Color["SystDown"]) if WIDTH == 1: hist = YDivideWidth(hist) hist_up = YDivideWidth(hist_up) hist_down = YDivideWidth(hist_down) h_list = [] h_list.append(hist) h_list.append(hist_up) h_list.append(hist_down) hists[sample] = h_list legend.AddEntry(hist, sample, "l") legend.AddEntry(hist_up, sample + "_" + SystName + "Up", "l") legend.AddEntry(hist_down, sample + "_" + SystName + "Down", "l") legends[sample] = legend inputfile.Close() # hists = {"sampleName":[h_nominal, h_up, h_down]} return hists, legends
"g_uu_eff", "Flavor efficiency tagging @{}".format(detector) + " " + mode) g_cc_eff = TGraph() g_cc_eff.SetNameTitle( "g_cc_eff", "Flavor efficiency tagging @{}".format(detector) + " " + mode) g_bb_eff = TGraph() g_bb_eff.SetNameTitle( "g_bb_eff", "Flavor efficiency tagging @{}".format(detector) + " " + mode) g_bb_pur = TGraph() g_bb_pur.SetNameTitle( "g_bb_pur", "Flavor efficiency tagging @{}".format(detector) + " " + mode) leg_eff = TLegend(0.2, 0.6, 0.6, 0.8) leg_eff.AddEntry(g_uu_eff, "u, d, s jets efficiency", "p") leg_eff.AddEntry(g_cc_eff, "c jets efficiency", "p") leg_eff.AddEntry(g_bb_eff, "b jets efficiency", "p") leg_eff.AddEntry(g_bb_pur, "b jets purity", "p") # canvases c_roc = TCanvas("c_roc_{}_".format(detector) + mode, "ROC curve for b jets @{}".format(detector), 800, 600) c_roc_b_eff_c_eff = TCanvas( "c_roc_b_eff_c_eff_{}_".format(detector) + mode, "Product efficiency x purity for b-jets @{}".format(detector), 800, 600) c_eff = TCanvas("c_eff_{}_".format(detector) + mode, "Jets b-tagging efficiency @{}".format(detector), 800, 600) canvases = [c_roc, c_roc_b_eff_c_eff, c_eff]
def getGraph(self): from array import array from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors n = len(self.__x) if n != len(self.__y) or n != len(self.__yErrLow) or n != len( self.__yErrHigh): raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match" % ( len(self.__x), len(self.__y), len( self.__yErrLow), len(self.__yErrHigh)) result = TMultiGraph() legendPosition = [ float(i) for i in self.__getStyleOption("legendPosition").split() ] legend = TLegend(*legendPosition) legend.SetFillColor(0) result.SetTitle("%s;%s;%s" % (self.__title, self.__xTitle, self.__yTitle)) #(refArrays, refLabel) = self.__getRefernceGraphArrays() #refGraph = TGraphAsymmErrors(*refArrays) #refGraph.SetLineWidth(2) #refGraph.SetLineColor(int(self.__config.get("reference","lineColor"))) #refGraph.SetFillColor(int(self.__config.get("reference","fillColor"))) #result.Add(refGraph,"L3") #legend.AddEntry(refGraph,self.__config.get("reference","name")) xErr = array("d", [0 for i in range(n)]) print "__x = ", self.__x print "__y = ", self.__y lst = [] for inc in range(0, n): d = {} d['run'] = self.__runs[inc] d['x'] = self.__x[inc] d['y'] = self.__y[inc] d['yErr'] = self.__yErrLow[inc] d['yTitle'] = self.__yTitle if self.__config.has_option(self.__section, "hTitle"): d['hTitle'] = self.__config.get(self.__section, "hTitle") else: d['hTitle'] = self.__yTitle if self.__config.has_option(self.__section, "yMin") and self.__config.has_option( self.__section, "yMax"): d['ymin'] = float(self.__config.get(self.__section, "yMin")) d['ymax'] = float(self.__config.get(self.__section, "yMax")) else: d['ymin'] = 0 d['ymax'] = 0 lst.append(d) obj = {} obj[self.__title] = lst #finalObj[self.__title]=lst #finalList.append(finalObj) # save_path = './JSON/' #completeName = os.path.join(save_path, self.__title+".json") if not os.path.exists("./JSON"): os.makedirs("./JSON") with open("./JSON/" + self.__title + ".json", 'w') as outfile: json.dump(obj, outfile, indent=4) print json.dumps(obj, indent=2) graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__yErrLow, self.__yErrHigh) graph.SetLineWidth(2) graph.SetFillColor(0) graph.SetLineColor(int(self.__getStyleOption("lineColor"))) graph.SetMarkerColor(int(self.__getStyleOption("markerColor"))) graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle"))) graph.SetMarkerSize(float(self.__getStyleOption("markerSize"))) sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__ySysErrLow, self.__ySysErrHigh) sysGraph.SetLineWidth(1) sysGraph.SetFillColor(0) sysGraph.SetLineColor(int(self.__getStyleOption("lineColor"))) sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor"))) sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle"))) sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize"))) #TOMAS removed sys error from the plot #result.Add(sysGraph,"[]") result.Add(graph, "P") # result.SetName("MultiPlots") # result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle)) result.SetName("MG_%s" % (self.__title)) legend.AddEntry(graph, self.__getStyleOption("name")) #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)): # self.__addAnnotaion("hallo",x,y,yErr) return (result, legend)
hs.Draw("histo") ZMass_DATA[i].Draw("sameEP") hs.GetXaxis().SetTitle("Mass [GeV/c^{2}]") hs.GetXaxis().SetLabelFont(43) hs.GetXaxis().SetLabelSize(15) hs.GetYaxis().SetTitleSize(20) hs.GetYaxis().SetTitleFont(43) hs.GetYaxis().SetTitleOffset(1.8) hs.GetYaxis().SetLabelFont(43) hs.GetYaxis().SetLabelSize(15) hs.GetYaxis().SetTitle("Events") # legend legend = TLegend(0.74, 0.68, 0.94, 0.87) legend.AddEntry(ZMass_DATA[i], "Data", "p") legend.AddEntry(ZMass_MC_DY[i], "Drell-Yan", "f") legend.AddEntry(ZMass_MC_TTJets[i], "t#bar{t}", "f") legend.SetFillColor(kWhite) legend.SetLineColor(kBlack) legend.SetTextFont(43) legend.SetTextSize(20) legend.Draw() # box with fit results pv = TPaveText(0.64, 0.35, 0.94, 0.65, "brNDC") pv.AddText("DATA:") pv.AddText("Z DCBmean = " + str(round(massFitDATA_dict[key], 2)) + " GeV") pv.AddText("Z DCBwidth = " + str(round(widthFitDATA_dict[key], 2)) + " GeV") pv.AddText("MC:")
def plotUpperLimits(masses, limit, ALP_xs, name): N = len(masses) print str(N) + ' mass points' yellow = TGraph(2 * N) # yellow band green = TGraph(2 * N) # green band median = TGraph(N) # median line print 'limit = ', limit for i in range(N): print 'ALP mass: ' + str(masses[i]) + ' GeV' x_mass = masses[i] yellow.SetPoint(i, x_mass, limit[x_mass][4] * ALP_xs) # + 2 sigma green.SetPoint(i, x_mass, limit[x_mass][3] * ALP_xs) # + 1 sigma median.SetPoint(i, x_mass, limit[x_mass][2] * ALP_xs) # median green.SetPoint(2 * N - 1 - i, x_mass, limit[x_mass][1] * ALP_xs) # - 1 sigma yellow.SetPoint(2 * N - 1 - i, x_mass, limit[x_mass][0] * ALP_xs) # - 2 sigma W = 800 H = 600 T = 0.08 * H B = 0.12 * H L = 0.12 * W R = 0.04 * W c = TCanvas("c", "c", 100, 100, W, H) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) c.SetLeftMargin(L / W) c.SetRightMargin(R / W) c.SetTopMargin(T / H) c.SetBottomMargin(B / H) c.SetTickx(0) c.SetTicky(0) c.SetGrid() c.cd() frame = c.DrawFrame(1.4, 0.001, 4.1, 10) frame.GetYaxis().CenterTitle() frame.GetYaxis().SetTitleSize(0.04) frame.GetXaxis().SetTitleSize(0.05) frame.GetXaxis().SetLabelSize(0.04) frame.GetYaxis().SetLabelSize(0.04) frame.GetYaxis().SetTitleOffset(1.3) frame.GetXaxis().SetNdivisions(508) frame.GetYaxis().CenterTitle(True) frame.GetXaxis().SetTitle("m_{a} [GeV]") if (args.pb): frame.GetYaxis().SetTitle( "95% CL limits on #sigma(gg#rightarrow H)#times B(X#rightarrow HH) [pb]" ) elif (args.fb): if name == 'coeff': frame.GetYaxis().SetTitle( "95% CL limits on |C_{Zh}^{eff}| [#frac{#Lambda}{1 TeV}]") frame.SetMinimum(0.01) # need Minimum > 0 for log scale frame.SetMaximum(1.) # CMS HH elif name == 'Br': #frame.GetYaxis().SetTitle("95% CL limits on #sigma(gg#rightarrow H#rightarrow Za#rightarrow 2l + 2#gamma)(fb)") frame.GetYaxis().SetTitle( "95% CL limits on Br(pp#rightarrow H#rightarrow Za#rightarrow 2l + 2#gamma)" ) frame.SetMinimum(0.000001) # need Minimum > 0 for log scale frame.SetMaximum(1.) # CMS HH else: frame.GetYaxis().SetTitle( "95% CL limits on #sigma(pp#rightarrow H#rightarrow Za#rightarrow 2l + 2#gamma)(fb)" ) frame.SetMinimum(0.1) # need Minimum > 0 for log scale frame.SetMaximum(8 * 1e4) # CMS HH frame.GetXaxis().SetLimits(0, 32) yellow.SetFillColor(ROOT.kOrange) yellow.SetLineColor(ROOT.kOrange) yellow.SetFillStyle(1001) yellow.Draw('F') green.SetFillColor(ROOT.kGreen + 1) green.SetLineColor(ROOT.kGreen + 1) green.SetFillStyle(1001) green.Draw('Fsame') median.SetLineColor(1) median.SetLineWidth(2) median.SetLineStyle(2) median.Draw('Lsame') CMS_lumi.CMS_lumi(c, 4, 11) ROOT.gPad.SetTicks(1, 1) frame.Draw('sameaxis') # yboost = 0.075 yboost = -0.2 x1 = 0.15 x2 = x1 + 0.24 y2 = 0.88 + yboost y1 = 0.80 + yboost legend = TLegend(x1, y1, x2, y2) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextSize(0.035) legend.SetTextFont(42) legend.AddEntry(median, "AsymptoticLimits CL_{s} expected", 'L') legend.AddEntry(green, "#pm 1 std. deviation", 'f') # legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 1 std. deviation",'f') legend.AddEntry(yellow, "#pm 2 std. deviation", 'f') # legend.AddEntry("","STAT Only","") # legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 2 std. deviation",'f') legend.Draw() label = TLatex() label.SetNDC() label.SetTextAngle(0) label.SetTextColor(kBlack) label.SetTextFont(42) label.SetTextSize(0.045) label.SetLineWidth(2) label.DrawLatex(0.7, 0.7 + yboost, "STAT only") print " " # c.SaveAs("UpperLimit.png") outFile = "ALP_" if args.SM_Radion: outFile += "SM_" c.SaveAs(outFile + name + "_UpperLimit.pdf") c.SaveAs(outFile + name + "_UpperLimit.C") c.Close()
def makeRatioPlot(hNum, hDen, hDen2="", nameNum="num", nameDen="den", nameDen2="", xtitle="pt",ytitle="Entries", ratiotitle="Ratio", norm=False, log=True, plotName="ratio", outDir='out'): TH1.SetDefaultSumw2() # prepare settings of histos hNum.SetLineColor(kBlack) hNum.SetLineWidth(2) hNum.SetMarkerStyle(20) #hNum.SetMarkerStyle(1) hNum.SetMarkerColor(kBlack) hNum.GetYaxis().SetTitle(ytitle) hDen.SetLineColor(kRed+1) hDen.SetMarkerColor(kRed+1) hDen.SetLineWidth(2) hDen.SetMarkerStyle(21) #hDen.SetMarkerStyle(1) if nameDen2 != "": hDen2.SetLineColor(kBlue) hDen2.SetMarkerColor(kBlue) hDen2.SetLineWidth(2) hDen2.SetMarkerStyle(22) #hDen2.SetMarkerStyle(1) makeHistSettings(hDen2)# makeHistSettings(hNum) makeHistSettings(hDen) # prepare canva canvas=TCanvas(plotName, plotName, 600, 600) ROOT.SetOwnership(canvas, False) # Crucial to avoid crashes due to the way python deletes the objects canvas.cd() yMinP1=0.305; bottomMarginP1=0.005; pad1 = TPad('pad1','pad1',0,yMinP1,0.99,1) if log: pad1.SetLogy() pad1.SetBottomMargin(bottomMarginP1) pad1.SetFillColor(kWhite) pad1.SetTickx() pad1.SetTicky() pad2 = TPad('pad2','pad2',0.,0.01,.99,0.300) pad2.SetTopMargin(0.010) pad2.SetBottomMargin(0.40) pad2.SetFillColor(kWhite) pad2.SetGridy() pad1.SetNumber(1) pad2.SetNumber(2) pad1.Draw() pad2.Draw() # prepare legend leg = TLegend(0.75,0.68,0.82,0.88,'') leg.SetBorderSize(0) leg.SetTextSize(0.05) # Draw pad1.cd() histo_saver = [] #hNumNorm = hNum.Clone() if norm: hNumNorm = hNum.DrawNormalized('LP') histo_saver.append(hNumNorm) else: hNum.Draw('PE') if log: hNum.SetMaximum(hNum.GetMaximum()*4) if norm: hNumNorm.SetMaximum(hNumNorm.GetMaximum()*4) else: hNum.SetMaximum(hNum.GetMaximum()*2) if norm: hNumNorm.SetMaximum(hNumNorm.GetMaximum()*2) #leg.Draw('same') #hDenNorm = hDen.Clone() if norm: hDenNorm = hDen.DrawNormalized('samePE') histo_saver.append(hDenNorm) else: hDen.Draw('samePE') #hDenNorm2 = hDen2.Clone() if nameDen2 != "": if norm: hDenNorm2 = hDen2.DrawNormalized('samePE') histo_saver.append(hDenNorm2) else: hDen2.Draw('samePE') leg.AddEntry(hDen2, nameDen2, 'PE') leg.AddEntry(hDen, nameDen, 'PE') leg.AddEntry(hNum, nameNum, 'PE') leg.Draw('same') #print hNumNorm.Integral(), hDenNorm.Integral(), hDenNorm2.Integral() #print hNum.Integral(), hDen.Integral(), hDen2.Integral() ####################################################### ### RATIO PAD ####################################################### pad2.cd() hRatio = hNum.Clone() if nameDen2 != "": hRatio2 = hNum.Clone() if norm: hRatio = hNumNorm.Clone() hRatio2 = hNumNorm.Clone() #print 'Ratio integral before division' #print hRatio.Integral(), hRatio2.Integral() hRatio.Divide(hDenNorm) if nameDen2 != "": hRatio2.Divide(hDenNorm2) #print 'Ratio integral after division' #print hRatio.Integral(), hRatio2.Integral() else: hRatio.Divide(hDen) if nameDen2 != "": hRatio2.Divide(hDen2) #hRatio.SetLineColor(kRed+2) if nameDen2 != "": hRatio2.SetLineColor(kBlue) #print hRatio.Integral() makeRatioSettings(hRatio) if nameDen2 != "": makeRatioSettings(hRatio2) hRatio.GetXaxis().SetTitle(xtitle) hRatio.GetYaxis().SetTitle(ratiotitle) hRatio.SetTitle('') hRatio.Draw('PE') if nameDen2 != "": hRatio2.Draw('PEsame') #hRatio.GetXaxis().SetRangeUser(200.,2000.) canvas.SaveAs('{d}/{name}.pdf'.format(d=outDir, name = plotName)) canvas.SaveAs('{d}/{name}.png'.format(d=outDir, name = plotName))
gFDFracFcVsCut[iPt].SetPoint(iCutSet, iCutSet+1, fFDFc[0]) gFDFracFcVsCut[iPt].SetPointError(iCutSet, 0.5, 0.5, fFDFc[0]-fFDFc[1], fFDFc[2]-fFDFc[0]) if compareToNb: fPromptNb = GetFractionNb(rawY, effP, effF, crossSecFD, ptMax-ptMin, 1., BR, hEv[iCutSet].GetBinContent(1), sigmaMB) fFDNb = [1-fPromptNb[0], 1-fPromptNb[2], 1-fPromptNb[1]] #inverse Nb method not reliable gPromptFracNbVsCut[iPt].SetPoint(iCutSet, iCutSet+1, fPromptNb[0]) gPromptFracNbVsCut[iPt].SetPointError(iCutSet, 0.5, 0.5, fPromptNb[0]-fPromptNb[1], fPromptNb[2]-fPromptNb[0]) gFDFracNbVsCut[iPt].SetPoint(iCutSet, iCutSet+1, fFDNb[0]) gFDFracNbVsCut[iPt].SetPointError(iCutSet, 0.5, 0.5, fFDNb[0]-fFDNb[1], fFDNb[2]-fFDNb[0]) if iPt == 0: legDistr.AddEntry(hRawYieldsVsCut[iPt], 'Measured raw yield', 'lpe') legDistr.AddEntry(hRawYieldPromptVsCut[iPt], 'Prompt', 'f') legDistr.AddEntry(hRawYieldFDVsCut[iPt], 'Non-prompt', 'f') legDistr.AddEntry(hRawYieldsVsCutReSum[iPt], 'Prompt + non-prompt', 'l') legEff.AddEntry(hEffPromptVsCut[iPt], 'Prompt', 'lpe') legEff.AddEntry(hEffFDVsCut[iPt], 'Non-prompt', 'lpe') legFrac.AddEntry(hPromptFracVsCut[iPt], 'Prompt', 'lpe') legFrac.AddEntry(hFDFracVsCut[iPt], 'Non-prompt', 'lpe') deltaY = 0. if compareToFc: legFrac.AddEntry(gPromptFracFcVsCut[iPt], 'Prompt #it{f}_{c}', 'lpe') legFrac.AddEntry(gFDFracFcVsCut[iPt], 'Non-prompt #it{f}_{c}', 'lpe') deltaY += 0.1
def createPlots_(plot): """Cumulative material budget from simulation. Internal function that will produce a cumulative profile of the material budget inferred from the simulation starting from the single detectors that compose the tracker. It will iterate over all existing detectors contained in the DETECTORS dictionary. The function will automatically skip non-existent detectors. """ IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"] theDirname = "Figures" hist_X0_detectors = OrderedDict() if plot not in plots.keys(): print("Error: chosen plot name not known %s" % plot) return hist_X0_IB = None # We need to keep the file content alive for the lifetime of the # full function.... subDetectorFiles = [] hist_X0_elements = OrderedDict() prof_X0_elements = OrderedDict() for subDetector, color in DETECTORS.iteritems(): subDetectorFilename = "matbdg_%s.root" % subDetector if not checkFile_(subDetectorFilename): print("Error opening file: %s" % subDetectorFilename) continue subDetectorFiles.append(TFile(subDetectorFilename)) subDetectorFile = subDetectorFiles[-1] print("Opening file: %s" % subDetectorFilename) prof_X0_XXX = subDetectorFile.Get("%d" % plots[plot].plotNumber) # Merge together the "inner barrel detectors". if subDetector in IBs: hist_X0_IB = assignOrAddIfExists_(hist_X0_IB, prof_X0_XXX) hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionX() # category profiles for label, [num, color, leg] in hist_label_to_num.iteritems(): prof_X0_elements[label] = subDetectorFile.Get( "%d" % (num + plots[plot].plotNumber)) hist_X0_elements[label] = assignOrAddIfExists_( hist_X0_elements.setdefault(label, None), prof_X0_elements[label]) cumulative_matbdg = TH1D("CumulativeSimulMatBdg", "CumulativeSimulMatBdg", hist_X0_IB.GetNbinsX(), hist_X0_IB.GetXaxis().GetXmin(), hist_X0_IB.GetXaxis().GetXmax()) cumulative_matbdg.SetDirectory(0) # colors for det, color in DETECTORS.iteritems(): setColorIfExists_(hist_X0_detectors, det, color) for label, [num, color, leg] in hist_label_to_num.iteritems(): hist_X0_elements[label].SetFillColor(color) # First Plot: BeamPipe + Pixel + TIB/TID + TOB + TEC + Outside # stack stackTitle_SubDetectors = "Tracker Material Budget;%s;%s" % ( plots[plot].abscissa, plots[plot].ordinate) stack_X0_SubDetectors = THStack("stack_X0", stackTitle_SubDetectors) for det, histo in hist_X0_detectors.iteritems(): stack_X0_SubDetectors.Add(histo) cumulative_matbdg.Add(histo, 1) # canvas can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors", 800, 800) can_SubDetectors.Range(0, 0, 25, 25) can_SubDetectors.SetFillColor(kWhite) # Draw stack_X0_SubDetectors.SetMinimum(plots[plot].ymin) stack_X0_SubDetectors.SetMaximum(plots[plot].ymax) stack_X0_SubDetectors.Draw("HIST") stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax) # Legenda theLegend_SubDetectors = TLegend(0.180, 0.8, 0.98, 0.92) theLegend_SubDetectors.SetNColumns(3) theLegend_SubDetectors.SetFillColor(0) theLegend_SubDetectors.SetFillStyle(0) theLegend_SubDetectors.SetBorderSize(0) for det, histo in hist_X0_detectors.iteritems(): theLegend_SubDetectors.AddEntry(histo, det, "f") theLegend_SubDetectors.Draw() # text text_SubDetectors = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC") text_SubDetectors.SetFillColor(0) text_SubDetectors.SetBorderSize(0) text_SubDetectors.AddText("CMS Simulation") text_SubDetectors.SetTextAlign(11) text_SubDetectors.Draw() # Store can_SubDetectors.Update() if not checkFile_(theDirname): os.mkdir(theDirname) can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.pdf" % (theDirname, plot)) can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.root" % (theDirname, plot)) # Second Plot: BeamPipe + SEN + ELE + CAB + COL + SUP + OTH/AIR + # Outside stack stackTitle_Materials = "Tracker Material Budget;%s;%s" % ( plots[plot].abscissa, plots[plot].ordinate) stack_X0_Materials = THStack("stack_X0", stackTitle_Materials) stack_X0_Materials.Add(hist_X0_detectors["BeamPipe"]) for label, [num, color, leg] in hist_label_to_num.iteritems(): stack_X0_Materials.Add(hist_X0_elements[label]) # canvas can_Materials = TCanvas("can_Materials", "can_Materials", 800, 800) can_Materials.Range(0, 0, 25, 25) can_Materials.SetFillColor(kWhite) # Draw stack_X0_Materials.SetMinimum(plots[plot].ymin) stack_X0_Materials.SetMaximum(plots[plot].ymax) stack_X0_Materials.Draw("HIST") stack_X0_Materials.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax) # Legenda theLegend_Materials = TLegend(0.180, 0.8, 0.95, 0.92) theLegend_Materials.SetNColumns(3) theLegend_Materials.SetFillColor(0) theLegend_Materials.SetBorderSize(0) theLegend_Materials.AddEntry(hist_X0_detectors["BeamPipe"], "Beam Pipe", "f") for label, [num, color, leg] in hist_label_to_num.iteritems(): theLegend_Materials.AddEntry(hist_X0_elements[label], leg, "f") theLegend_Materials.Draw() # text text_Materials = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC") text_Materials.SetFillColor(0) text_Materials.SetBorderSize(0) text_Materials.AddText("CMS Simulation") text_Materials.SetTextAlign(11) text_Materials.Draw() # Store can_Materials.Update() can_Materials.SaveAs("%s/Tracker_Materials_%s.pdf" % (theDirname, plot)) can_Materials.SaveAs("%s/Tracker_Materials_%s.root" % (theDirname, plot)) return cumulative_matbdg
drawCMS2(myC, 13, lumi_2016) leg_limit_vs_mass_2016 = TLegend(0.25, 0.62, 0.9, 0.89) leg_limit_vs_mass_2016.SetHeader( "c#tau_{#tilde{#chi}_{1}^{0}} = " + str(ctau_this) + " cm, #tilde{#chi}^{0}_{1} #rightarrow #gamma #tilde{G}") leg_limit_vs_mass_2016.SetBorderSize(0) leg_limit_vs_mass_2016.SetTextSize(0.03) leg_limit_vs_mass_2016.SetLineColor(1) leg_limit_vs_mass_2016.SetLineStyle(1) leg_limit_vs_mass_2016.SetLineWidth(1) leg_limit_vs_mass_2016.SetFillColor(0) leg_limit_vs_mass_2016.SetFillStyle(1001) leg_limit_vs_mass_2016.AddEntry(graph_limit_vs_mass_2016_Th_limit, "Theoretical cross-section", "L") if drawObs: leg_limit_vs_mass_2016.AddEntry(graph_limit_vs_mass_2016_obs_limit, "Observed 95% CL upper limit", "L") leg_limit_vs_mass_2016.AddEntry(graph_limit_vs_mass_2016_exp_limit, "Expected 95% CL upper limit", "L") leg_limit_vs_mass_2016.AddEntry(graph_limit_vs_mass_2016_exp1sigma_limit, "#pm 1 #sigma Expected", "F") leg_limit_vs_mass_2016.AddEntry(graph_limit_vs_mass_2016_exp2sigma_limit, "#pm 2 #sigma Expected", "F") leg_limit_vs_mass_2016.Draw() myC.SaveAs(outputDir + "/limits" + "/limit_vs_mass_2016_ctau" + ctau_this_str + "_2016Only_" + plot_tag + ".pdf") myC.SaveAs(outputDir + "/limits" + "/limit_vs_mass_2016_ctau" + ctau_this_str + "_2016Only_" + plot_tag + ".png")
def __main__(ifile): with open(ifile) as ifile: data = ifile.read().split('\n') stat_histo = TH1F('stat_histo', ';Sort Time (Clock Cycles);Count', 128, 0, 128) dyn_histo = TH1F('dyn_histo', ';Sort Time (Clock Cycles);Count', 128, 0, 128) asym_histo = TH1F('Sort_asym', ';Sort Time Differance (semiStat - Dyn);count', 100, 0, 100) asym_histo2 = TH2F( 'Sort_asym2', ';SPP / BCID;Dynamic Sorting Time Saved [25ns Clock Cycle]', 64, 0, 64, 64, 0, 64) asym_histo2.SetStats(0) for each in data: if each != '': stat = int(each.split(',')[0]) dyn = int(each.split(',')[1]) if stat > 64: continue if stat < dyn: dyn_histo.Fill(stat) asym_histo.Fill(0) asym_histo2.Fill(stat, 0) else: dyn_histo.Fill(dyn) asym_histo.Fill(stat - dyn) asym_histo2.Fill(stat, stat - dyn) stat_histo.Fill(stat) Canvas = TCanvas('Dynamic_vs_Static_Sorttime_Comparison', 'Dynamic vs Static Sorttime Comparison', 900, 600) # (fold) Canvas.Divide(2, 0) stat_max = stat_histo.GetMaximum() dyn_max = dyn_histo.GetMaximum() Canvas.cd(1) stat_histo.Draw('') stat_histo.SetLineColor(4) stat_histo.SetStats(0) stat_histo.GetYaxis().SetRangeUser(0, max([stat_max, dyn_max]) * 1.1) stat_histo.GetXaxis().SetRangeUser(0, 70) dyn_histo.Draw('same') dyn_histo.SetLineColor(2) leg = TLegend(0.4, 0.7, 0.89, 0.89) leg.SetHeader('Max Sort Acceptance = 64 SPP/BCID') leg.SetLineColor(0) leg.AddEntry(stat_histo, 'Semi Static Sort Time', 'l') leg.AddEntry(dyn_histo, 'Dynamic Sort Time', 'l') leg.Draw() Canvas.cd(2) stat_histo.Draw('') stat_histo.SetLineColor(4) stat_histo.SetStats(0) stat_histo.GetYaxis().SetRangeUser(0.9, max([stat_max, dyn_max]) * 1.1) stat_histo.GetXaxis().SetRangeUser(0, 70) dyn_histo.Draw('same') dyn_histo.SetLineColor(2) leg2 = TLegend(0.2, 0.2, 0.7, 0.4) leg2.SetHeader('Max Sort Acceptance = 64 SPP/BCID') leg2.SetLineColor(0) leg2.AddEntry(stat_histo, 'Semi Static Sort Time', 'l') leg2.AddEntry(dyn_histo, 'Dynamic Sort Time', 'l') leg2.Draw() gPad.SetLogy() Canvas.SaveAs('semiStat_dyn_sort_time.pdf') #(unfold) Canvas = TCanvas('time_saved_by_sort_1d', 'Time Saves by Sort 1D', 900, 600) #(fold) asym_histo.SetLineColor(4) asym_histo.SetStats(0) asym_histo.GetXaxis().SetRangeUser(0, 30) asym_histo.Draw() leg = TLegend(0.55, 0.75, 0.89, 0.89) leg.SetHeader('Max Sort Acceptance = 64 SPP/BCID') leg.SetLineColor(0) leg.AddEntry(asym_histo, 'Time Saved by Dynamic Sorting', 'l') leg.Draw() Canvas.SaveAs('time_saved_by_dynamic_sort_1d.pdf') #(unfold) Canvas = TCanvas('time_saved_by_sort_1d', 'Time Saves by Sort 1D', 900, 600) #(fold) asym_histo2.SetStats(0) asym_histo2.GetYaxis().SetRangeUser(0, 30) asym_histo2.Draw('COLZ') Canvas.SetLogz() Canvas.SaveAs('time_saved_by_dynamic_sort_2d.pdf') #(unfold) rfile = TFile('fix_dyn_analysis.root', 'RECREATE') stat_histo.Write() dyn_histo.Write() asym_histo.Write() asym_histo2.Write()
def MakeOneDHist(pathToDir, distribution): numFittingSamples = 0 HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right, header_y_top, HeaderText, "NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right, topLeft_y_top, LumiText, "NDC") LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) NormLabel = TPaveLabel() NormLabel.SetDrawOption("NDC") NormLabel.SetX1NDC(topLeft_x_left) NormLabel.SetX2NDC(topLeft_x_right) NormLabel.SetBorderSize(0) NormLabel.SetFillColor(0) NormLabel.SetFillStyle(0) NormText = "" if arguments.normalizeToUnitArea: NormText = "Scaled to unit area" elif arguments.normalizeToData: NormText = "MC scaled to data" NormLabel.SetLabel(NormText) YieldsLabel = TPaveText(0.39, 0.7, 0.59, 0.9, "NDC") YieldsLabel.SetBorderSize(0) YieldsLabel.SetFillColor(0) YieldsLabel.SetFillStyle(0) YieldsLabel.SetTextAlign(12) RatiosLabel = TPaveText() RatiosLabel.SetDrawOption("NDC") RatiosLabel.SetBorderSize(0) RatiosLabel.SetFillColor(0) RatiosLabel.SetFillStyle(0) RatiosLabel.SetTextAlign(32) Legend = TLegend() Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) fittingIntegral = 0 scaleFactor = 1 HistogramsToFit = [] TargetDataset = distribution['target_dataset'] FittingLegendEntries = [] DataLegendEntries = [] FittingHistogramDatasets = [] Stack_list = [] Stack_list.append(THStack("stack_before", distribution['name'])) Stack_list.append(THStack("stack_after", distribution['name'])) fileName = condor_dir + "/" + distribution['target_dataset'] + ".root" if not os.path.exists(fileName): return inputFile = TFile(fileName) if inputFile.IsZombie() or not inputFile.GetNkeys(): return Target = inputFile.Get("OSUAnalysis/" + distribution['channel'] + "/" + distribution['name']).Clone() Target.SetDirectory(0) inputFile.Close() Target.SetMarkerStyle(20) Target.SetMarkerSize(0.8) Target.SetFillStyle(0) Target.SetLineColor(colors[TargetDataset]) Target.SetLineStyle(1) Target.SetLineWidth(2) targetIntegral = Target.Integral() if (arguments.normalizeToUnitArea and Target.Integral() > 0): Target.Scale(1. / Target.Integral()) if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Target.GetNbinsX() >= RebinFactor * 5 and Target.GetName().find( "GenMatch") is -1: Target.Rebin(RebinFactor) ### formatting target histogram and adding to legend legendIndex = 0 Legend.AddEntry(Target, labels[TargetDataset], "LEP") legendIndex = legendIndex + 1 if not outputFile.Get("OSUAnalysis"): outputFile.mkdir("OSUAnalysis") if not outputFile.Get("OSUAnalysis/" + distribution['channel']): outputFile.Get("OSUAnalysis").mkdir(distribution['channel']) for sample in distribution[ 'datasets']: # loop over different samples requested to be fit dataset_file = "%s/%s.root" % (condor_dir, sample) inputFile = TFile(dataset_file) HistogramObj = inputFile.Get(pathToDir + "/" + distribution['channel'] + "/" + distribution['name']) if not HistogramObj: print "WARNING: Could not find histogram " + pathToDir + "/" + distribution[ 'channel'] + "/" + distribution[ 'name'] + " in file " + dataset_file + ". Will skip it and continue." continue Histogram = HistogramObj.Clone() Histogram.SetDirectory(0) inputFile.Close() if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetName( ).find("GenMatch") is -1: Histogram.Rebin(RebinFactor) xAxisLabel = Histogram.GetXaxis().GetTitle() unitBeginIndex = xAxisLabel.find("[") unitEndIndex = xAxisLabel.find("]") if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth( 1)) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex] else: yAxisLabel = "Entries per bin (" + str( Histogram.GetXaxis().GetBinWidth(1)) + " width)" if not arguments.makeFancy: histoTitle = Histogram.GetTitle() else: histoTitle = "" legLabel = labels[sample] if (arguments.printYields): yieldHist = Histogram.Integral() legLabel = legLabel + " (%.1f)" % yieldHist FittingLegendEntries.append(legLabel) if (types[sample] == "bgMC"): numFittingSamples += 1 fittingIntegral += Histogram.Integral() Histogram.SetLineStyle(1) if (arguments.noStack): Histogram.SetFillStyle(0) Histogram.SetLineColor(colors[sample]) Histogram.SetLineWidth(2) else: Histogram.SetFillStyle(1001) Histogram.SetFillColor(colors[sample]) Histogram.SetLineColor(1) Histogram.SetLineWidth(1) elif (types[sample] == "signalMC"): numFittingSamples += 1 Histogram.SetFillStyle(0) Histogram.SetLineColor(colors[sample]) Histogram.SetLineStyle(1) Histogram.SetLineWidth(2) if (arguments.normalizeToUnitArea and Histogram.Integral() > 0): Histogram.Scale(1. / Histogram.Integral()) HistogramsToFit.append(Histogram) FittingHistogramDatasets.append(sample) #scaling histograms as per user's specifications if targetIntegral > 0 and fittingIntegral > 0: scaleFactor = targetIntegral / fittingIntegral for fittingHist in HistogramsToFit: if arguments.normalizeToData: fittingHist.Scale(scaleFactor) if arguments.normalizeToUnitArea and not arguments.noStack and fittingIntegral > 0: fittingHist.Scale(1. / fittingIntegral) elif arguments.normalizeToUnitArea and arguments.noStack and fittingHist.Integral( ) > 0: fittingHist.Scale(1. / fittingHist.Integral()) def fitf(x, par): xBin = HistogramsToFit[0].FindBin(x[0]) value = 0.0 for i in range(0, len(HistogramsToFit)): value += par[i] * HistogramsToFit[i].GetBinContent(xBin) + par[ i + len(HistogramsToFit)] * HistogramsToFit[i].GetBinError(xBin) return value lowerLimit = Target.GetBinLowEdge(1) upperLimit = Target.GetBinLowEdge(Target.GetNbinsX()) + Target.GetBinWidth( Target.GetNbinsX()) if 'lowerLimit' in distribution: lowerLimit = distribution['lowerLimit'] if 'upperLimit' in distribution: upperLimit = distribution['upperLimit'] func = TF1("fit", fitf, lowerLimit, upperLimit, 2 * len(HistogramsToFit)) for i in range(0, len(HistogramsToFit)): if 'fixed_datasets' in distribution and distribution['datasets'][ i] in distribution['fixed_datasets']: func.FixParameter(i, 1.0) else: func.SetParameter(i, 1.0) # func.SetParLimits (i, 0.0, 1.0e2) # comment this out so we don't have to pre-normalize the QCD input sample func.SetParName(i, labels[FittingHistogramDatasets[i]]) shiftedScaleFactors = [] if arguments.parametricErrors: # loop over all input histograms and shift them +- 1 sigma for i in range(0, len(HistogramsToFit)): sfs = [] # -1 => -1 sigma, +1 => +1 sigma for j in [-1, 1]: # loop over the parameters holding the errors for each dataset, fixing all to 0 for k in range(len(HistogramsToFit), 2 * len(HistogramsToFit)): func.FixParameter(k, 0) # fix the error of the dataset of interest to +-1 func.FixParameter(i + len(HistogramsToFit), j) # perform new fit for k in range(0, distribution['iterations'] - 1): if j == -1: print "Scale down " + labels[FittingHistogramDatasets[ i]] + " iteration " + str(k + 1) + "..." if j == 1: print "Scale up " + labels[FittingHistogramDatasets[ i]] + " iteration " + str(k + 1) + "..." Target.Fit("fit", "QEMR0") Target.Fit("fit", "VEMR0") # save the new scale factors for each dataset for k in range(0, len(HistogramsToFit)): sfs.append(func.GetParameter(k)) shiftedScaleFactors.append(sfs) # reset the parameters with the errors of each dataset to 0 for i in range(len(HistogramsToFit), 2 * len(HistogramsToFit)): func.FixParameter(i, 0) # do the fit to get the central values for i in range(0, distribution['iterations'] - 1): print "Iteration " + str(i + 1) + "..." Target.Fit("fit", "QEMR0") Target.Fit("fit", "VEMR0") if arguments.parametricErrors: # make a list of the largest errors on each contribution by shifting any other contribution parErrors = [] # loop over all the datasets for i in range(0, len(HistogramsToFit)): centralValue = func.GetParameter(i) maxError = 0 # find the maximum deviation from the central value and save that for shiftedScaleFactor in shiftedScaleFactors[i]: currentError = abs(shiftedScaleFactor - centralValue) if currentError > maxError: maxError = currentError parErrors.append(maxError) finalMax = 0 if not arguments.noStack: for fittingHist in HistogramsToFit: finalMax += fittingHist.GetMaximum() else: for fittingHist in HistogramsToFit: if (fittingHist.GetMaximum() > finalMax): finalMax = fittingHist.GetMaximum() if (Target.GetMaximum() > finalMax): finalMax = Target.GetMaximum() Target.SetMaximum(1.1 * finalMax) Target.SetMinimum(0.0001) Canvas = TCanvas(distribution['name'] + "_FitFunction") Canvas.cd(1) Target.Draw() func.Draw("same") outputFile.cd("OSUAnalysis/" + distribution['channel']) Canvas.Write() if arguments.savePDFs: if histogram == input_histograms[0]: Canvas.Print(pdfFileName + "(", "pdf") else: Canvas.Print(pdfFileName, "pdf") Target.SetStats(0) ### formatting bgMC histograms and adding to legend legendIndex = numFittingSamples - 1 for Histogram in reversed(HistogramsToFit): if (arguments.noStack): Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "L") else: Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "F") legendIndex = legendIndex - 1 ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots yAxisMin = 0.0001 if arguments.setYMin: yAxisMin = float(arguments.setYMin) ### Draw everything to the canvases !!!! for i in range(0, 2): # 0 => before, 1 => after integrals = [] ratios = [] errors = [] if i == 1: # loop over each dataset, saving it's yield and the errors on it for j in range(0, len(HistogramsToFit)): integrals.append(HistogramsToFit[j].Integral()) HistogramsToFit[j].Scale(func.GetParameter(j)) ratios.append(func.GetParameter(j)) errors.append(func.GetParError(j)) for fittingHist in HistogramsToFit: if not arguments.noStack: Stack_list[i].Add(fittingHist) #creating the histogram to represent the statistical errors on the stack if not arguments.noStack: ErrorHisto = HistogramsToFit[0].Clone("errors") ErrorHisto.SetFillStyle(3001) ErrorHisto.SetFillColor(13) ErrorHisto.SetLineWidth(0) if i == 1: Legend.AddEntry(ErrorHisto, "Stat. Errors", "F") for Histogram in HistogramsToFit: if Histogram is not HistogramsToFit[0]: ErrorHisto.Add(Histogram) if i == 0: Canvas = TCanvas(distribution['name'] + "_Before") if i == 1: Canvas = TCanvas(distribution['name'] + "_After") if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1, 2) Canvas.cd(1) gPad.SetPad(0, 0.25, 1, 1) gPad.SetMargin(0.15, 0.05, 0.01, 0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() if arguments.setLogY: gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0, 0, 1, 0.25) # format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15, 0.05, 0.4, 0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 0 if numFittingSamples is not 0 and not arguments.noStack: finalMax = ErrorHisto.GetMaximum() + ErrorHisto.GetBinError( ErrorHisto.GetMaximumBin()) else: for bgMCHist in HistogramsToFit: if (bgMCHist.GetMaximum() > finalMax): finalMax = bgMCHist.GetMaximum() if (Target.GetMaximum() > finalMax): finalMax = Target.GetMaximum() + Target.GetBinError( Target.GetMaximumBin()) finalMax = 1.15 * finalMax if arguments.setYMax: finalMax = float(arguments.setYMax) if not arguments.noStack: # draw stacked background samples Stack_list[i].SetTitle(histoTitle) Stack_list[i].Draw("HIST") Stack_list[i].GetXaxis().SetTitle(xAxisLabel) Stack_list[i].GetYaxis().SetTitle(yAxisLabel) Stack_list[i].SetMaximum(finalMax) Stack_list[i].SetMinimum(yAxisMin) if makeRatioPlots or makeDiffPlots: Stack_list[i].GetHistogram().GetXaxis().SetLabelSize(0) #draw shaded error bands ErrorHisto.Draw("A E2 SAME") else: #draw the unstacked backgrounds HistogramsToFit[0].SetTitle(histoTitle) HistogramsToFit[0].Draw("HIST") HistogramsToFit[0].GetXaxis().SetTitle(xAxisLabel) HistogramsToFit[0].GetYaxis().SetTitle(yAxisLabel) HistogramsToFit[0].SetMaximum(finalMax) HistogramsToFit[0].SetMinimum(yAxisMin) for bgMCHist in HistogramsToFit: bgMCHist.Draw("A HIST SAME") Target.Draw("A E X0 SAME") #legend coordinates, empirically determined :-) x_left = 0.6761745 x_right = 0.9328859 x_width = x_right - x_left y_max = 0.9 entry_height = 0.05 if (numFittingSamples is not 0): #then draw the data & bgMC legend numExtraEntries = 2 # count the target and (lack of) title Legend.SetX1NDC(x_left) numExtraEntries = numExtraEntries + 1 # count the stat. errors entry Legend.SetY1NDC(y_max - entry_height * (numExtraEntries + numFittingSamples)) Legend.SetX2NDC(x_right) Legend.SetY2NDC(y_max) Legend.Draw() RatiosLabel.SetX1NDC(x_left - 0.1) RatiosLabel.SetX2NDC(x_right) RatiosLabel.SetY2NDC(Legend.GetY1NDC() - 0.1) RatiosLabel.SetY1NDC(RatiosLabel.GetY2NDC() - entry_height * (numFittingSamples)) # Deciding which text labels to draw and drawing them drawLumiLabel = False drawNormLabel = False offsetNormLabel = False drawHeaderLabel = False if not arguments.normalizeToUnitArea: #don't draw the lumi label if there's no data and it's scaled to unit area drawLumiLabel = True # move the normalization label down before drawing if we drew the lumi. label offsetNormLabel = True if arguments.normalizeToUnitArea or arguments.normalizeToData: drawNormLabel = True if arguments.makeFancy: drawHeaderLabel = True drawLumiLabel = False # now that flags are set, draw the appropriate labels if drawLumiLabel: LumiLabel.Draw() if drawNormLabel: if offsetNormLabel: NormLabel.SetY1NDC(topLeft_y_bottom - topLeft_y_offset) NormLabel.SetY2NDC(topLeft_y_top - topLeft_y_offset) else: NormLabel.SetY1NDC(topLeft_y_bottom) NormLabel.SetY2NDC(topLeft_y_top) NormLabel.Draw() if drawHeaderLabel: HeaderLabel.Draw() YieldsLabel.Clear() mcYield = Stack_list[i].GetStack().Last().Integral() dataYield = Target.Integral() if i == 0: YieldsLabel.AddText("Before Fit to Data") if i == 1: YieldsLabel.AddText("After Fit to Data") YieldsLabel.AddText("data yield: " + '%.1f' % dataYield) YieldsLabel.AddText("bkgd yield: " + '%.1f' % mcYield) YieldsLabel.AddText("data/bkgd: " + '%.2f' % (dataYield / mcYield)) if i == 1: for j in range(0, len(FittingLegendEntries)): if abs(ratios[j] - 1) < 0.001 and abs( errors[j] ) < 0.001: #then it probably was held fixed continue if arguments.showFittedYields: yield_ = ratios[j] * integrals[j] yielderror_ = errors[j] * yield_ text = FittingLegendEntries[ j] + " yield: " + '%.0f' % yield_ + ' #pm %.0f' % yielderror_ else: text = FittingLegendEntries[ j] + " ratio: " + '%.2f' % ratios[ j] + ' #pm %.2f' % errors[j] text = text + " (fit)" if arguments.parametricErrors: yield_ = ratios[j] * integrals[j] yieldParError_ = parErrors[j] * yield_ if arguments.showFittedYields: text += ' #pm %.2f' % yieldParError_ else: text += ' #pm %.2f' % parErrors[j] text = text + " (sys)" RatiosLabel.AddText(text) YieldsLabel.Draw() RatiosLabel.Draw() # drawing the ratio or difference plot if requested if (makeRatioPlots or makeDiffPlots): Canvas.cd(2) BgSum = Stack_list[i].GetStack().Last() if makeRatioPlots: if arguments.ratioRelErrMax: Comparison = ratioHistogram(Target, BgSum, arguments.ratioRelErrMax) else: Comparison = ratioHistogram(Target, BgSum) elif makeDiffPlots: Comparison = Target.Clone("diff") Comparison.Add(BgSum, -1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("Data-Bkgd") Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange, RatioYRange) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser( -1.2 * YMax, 1.2 * YMax) else: Comparison.GetYaxis().SetRangeUser( -1.2 * YMin, 1.2 * YMin) Comparison.GetYaxis().SetNdivisions(205) Comparison.Draw("E0") if i == 0: Canvas.Write(distribution['name'] + "_Before") if arguments.savePDFs: pathToDirString = plainTextString(pathToDir) Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" + pathToDirString + "/" + distribution['name'] + "_Before.pdf") if i == 1: Canvas.Write(distribution['name'] + "_After") if arguments.savePDFs: pathToDirString = plainTextString(pathToDir) Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" + pathToDirString + "/" + distribution['name'] + "_After.pdf")
c1.cd() # returns to main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0.0, 0.0, 1, 0.28) pad2.SetBottomMargin(0.3) pad2.SetTopMargin(0.02) pad2.SetLeftMargin(0.12) pad2.SetGridx() pad2.SetGridy() pad2.Draw() l = TLegend(0.15, 0.77, 0.89, 0.87) l.SetNColumns(5) l.SetTextFont(62) l.SetTextSize(0.05) l.SetLineColor(0) l.SetFillColor(0) l.AddEntry(bdt_ttbb, 'ttbb', 'F') l.AddEntry(bdt_ttbj, 'ttbj', 'F') l.AddEntry(bdt_ttcc, 'ttcc', 'F') l.AddEntry(bdt_ttLF, 'ttLF', 'F') l.AddEntry(bdt_singletop, 'ST', 'F') l.AddEntry(bdt_others, 'Others', 'F') if not gen: l.AddEntry(0, "", "") l.AddEntry(bdt_sig, "Sig", "F") if gen: l.AddEntry(bdt_sig_gen, "Gen", "F") l.AddEntry(bdt_data, 'Data', 'P') label = TPaveText() label.SetX1NDC(gStyle.GetPadLeftMargin()) label.SetY1NDC(1.0 - gStyle.GetPadTopMargin())
def CSCCLCTPattern(plotter): toPlot = "pt" for st in range(0, len(cscStations)): topTitle = "" xTitle = "Generated p_{T} GeV" yTitle = "Efficiency" title = "%s;%s;%s" % (topTitle, xTitle, yTitle) h_bins = "(20,0,20)" nBins = int(h_bins[1:-1].split(',')[0]) minBin = float(h_bins[1:-1].split(',')[1]) maxBin = float(h_bins[1:-1].split(',')[2]) c = newCanvas() base = TH1F("base", title, nBins, minBin, maxBin) base.SetMinimum(0.0) base.SetMaximum(1.1) base.GetXaxis().SetLabelSize(0.05) base.GetYaxis().SetLabelSize(0.05) base.GetXaxis().SetTitleSize(0.05) base.GetYaxis().SetTitleSize(0.05) base.Draw("") CMS_lumi.CMS_lumi(c, iPeriod, iPos) def ok_csc_clct_pattern(st, p1, p2): return AND(ok_csc_clct(st), OR(ok_pattern(st, p1), ok_pattern(st, p2))) h2 = draw_geff(plotter.tree, title, h_bins, toPlot, ok_csc_sh(st), ok_csc_clct_pattern(st, 2, 3), "same", kBlack) h3 = draw_geff(plotter.tree, title, h_bins, toPlot, ok_csc_sh(st), ok_csc_clct_pattern(st, 4, 5), "same", kRed) h4 = draw_geff(plotter.tree, title, h_bins, toPlot, ok_csc_sh(st), ok_csc_clct_pattern(st, 6, 7), "same", kBlue) h5 = draw_geff(plotter.tree, title, h_bins, toPlot, ok_csc_sh(st), ok_csc_clct_pattern(st, 8, 9), "same", kOrange) h6 = draw_geff(plotter.tree, title, h_bins, toPlot, ok_csc_sh(st), ok_csc_clct_pattern(st, 10, 10), "same", kGreen + 2) leg = TLegend(0.7, 0.15, .95, 0.45, "", "brNDC") leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetTextSize(0.05) leg.SetHeader("PID") leg.AddEntry(h2, "#geq 2", "pl") leg.AddEntry(h3, "#geq 4", "pl") leg.AddEntry(h4, "#geq 6", "pl") leg.AddEntry(h5, "#geq 8", "pl") leg.AddEntry(h6, "#geq 10", "pl") leg.Draw("same") csc = drawCSCLabel(cscStations[st].label, 0.85, 0.85, 0.05) c.Print("%sEff_CSCCLCT_pattern_%s%s" % (plotter.targetDir + subdirectory, cscStations[st].labelc, plotter.ext)) del c, base, h2, leg, csc, h3, h4, h5, h6
def DrawQA_Calo(qa): CaloQA = {} for trig in TRIGGER_CLASSES: CaloQA[trig] = {} CaloQA[trig]['NEvent'] = 0 CaloQA[trig]['E'] = None CaloQA[trig]['RF'] = None CaloQA[trig]['Eth'] = 11.0 if trig.count('1') else 6.0 # Event numbers evQA = qa.FindObject('Event_afterCuts') # TList evQA.SetOwner(True) hTrig = evQA.FindObject('FiredTag') # TH1D for i in range(1, hTrig.GetNbinsX() + 1): tag = hTrig.GetXaxis().GetBinLabel(i) if(tag == ''): break tag = tag.replace('INT7', 'MB') for trig in tag.split('_'): CaloQA[trig]['NEvent'] += hTrig.GetBinContent(i) # End - read with fired tags padQA.Clear() padQA.SetWindowSize(1600, 600) padQA.Divide(2) lgdE = TLegend(0.5, 0.7, 0.8, 0.85, "", "brNDC") lgdE.SetBorderSize(0) lgdE.SetNColumns(2) lgdRF = TLegend(0.5, 0.12, 0.88, 0.45, "", "brNDC") lgdRF.SetTextSize(0.02) lgdRF.SetBorderSize(0) lgdRF.SetNColumns(1) COLOR = SelectColor() # Reset for trig in TRIGGER_CLASSES: # Cluster energy calo = qa.FindObject('Cluster_' + trig) # TList calo.SetOwner(True) caloE = calo.FindObject('E').Clone('hClusterE_' + trig) HistNorm(caloE, CaloQA[trig]['NEvent']) caloE.SetTitle('EMCal/DCal cluster energy distribution') caloE.GetXaxis().SetRangeUser(0, 40) caloE.GetYaxis().SetRangeUser(1e-8, 100.) caloE.GetYaxis().SetTitle('#frac{1}{N_{ev}} #frac{dN_{cls}}{dE}') padQA.cd(1) colorHist = next(COLOR) caloE.SetLineColor(colorHist) caloE.SetMarkerColor(colorHist) caloE.SetMarkerStyle(kRound) caloE.Draw("same PE") lgdE.AddEntry(caloE, trig) gPad.SetLogy() # Rejection factor if(CaloQA['MB']['E']): caloRF = caloE.Clone('hClusterRF_' + trig) caloRF.SetTitle('Rejection factor of EMCal by ratio of cluster energy') caloRF.GetXaxis().SetRangeUser(0, 40) caloRF.GetYaxis().SetRangeUser(1e-2, 1e4) caloRF.GetYaxis().SetTitle('R_{trig}') caloRF.Divide(CaloQA['MB']['E']) padQA.cd(2) caloRF.Draw("same PE") gPad.SetLogy() caloRF.Write() CaloQA[trig]['RF'] = caloRF lgdRF.AddEntry(caloRF, trig + '/MB: ' + FitRF(caloRF, trig, CaloQA[trig]['Eth'])) CaloQA[trig]['E'] = caloE calo.Delete() # End - trigger loop padQA.cd(1) lgdE.Draw("same") # RF - EG1/EG2 caloRF_NEW = CaloQA['EG1']['E'].Clone('hClusterRF_EG12') caloRF_NEW.SetTitle('Rejection factor EMCal/DCal by ratio of cluster energy') caloRF_NEW.Divide(CaloQA['EG2']['E']) caloRF_NEW.SetMarkerStyle(kRoundHollow) padQA.cd(2) caloRF_NEW.Draw("same PE") caloRF_NEW.Write() lgdRF.AddEntry(caloRF_NEW, 'EG1/EG2: ' + FitRF(caloRF_NEW, 'EG12')) # RF -DG1/DG2 caloRF = CaloQA['DG1']['E'].Clone('hClusterRF_DG12') caloRF.SetTitle('Rejection factor EMCal/DCal by ratio of cluster energy') caloRF.Divide(CaloQA['DG2']['E']) caloRF.SetMarkerStyle(kCrossHollow) caloRF.Draw("same PE") caloRF.Write() lgdRF.AddEntry(caloRF, 'DG1/DG2: ' + FitRF(caloRF, 'DG12')) lgdRF.Draw("same") # Output padQA.Print(args.print,'Title:ClusterQA') padQA.Write("cQA_Cluster")
[] for _ in range(7)) for iPt, (ptMin, ptMax) in enumerate(zip(cutVars['Pt']['min'], cutVars['Pt']['max'])): minMass = hMassSel[iPt].GetBinLowEdge(1) maxMass = hMassSel[iPt].GetXaxis().GetBinUpEdge(hMassSel[iPt].GetNbinsX()) hMassNoSelNorm = hMassNoSel[iPt].Clone() hMassSelNorm = hMassSel[iPt].Clone() hMassNoSelNorm.Scale(1. / hMassNoSelNorm.Integral()) hMassSelNorm.Scale(1. / hMassSelNorm.Integral()) lineNorm = line.Clone() lineNorm.SetY2( hMassSelNorm.GetBinContent(int(hMassSelNorm.GetNbinsX() / 2)) * 1.5) if iPt == 0: leg.AddEntry(hMassNoSel[iPt], 'no selection', 'lp') leg.AddEntry(hMassSel[iPt], 'ML selection', 'lp') leg.AddEntry(lineNorm, f'{particleTitle} mass', 'l') cMass.append(TCanvas(f'cMassPt{ptMin*10:.0f}_{ptMax*10:.0f}', '', 500, 500)) cMass[iPt].cd().DrawFrame(minMass, 0., maxMass, hMassSelNorm.GetMaximum() * 1.5, f';{massTitle}; Normalised counts') hMassNoSelNorm.DrawCopy('esame') hMassSelNorm.DrawCopy('esame') leg.Draw() lineNorm.Draw() cMass[iPt].Update() cMass[iPt].Modified()
def makePlot(resname): os.system("sort -k 1 pre_" + resname + " > sorted_pre_" + resname) os.system("sort -k 1 post_" + resname + " > sorted_post_" + resname) pre_fres = open("sorted_pre_" + resname, "r") post_fres = open("sorted_post_" + resname, "r") ll_pre = pre_fres.readlines() ll_post = post_fres.readlines() n = len(ll_pre) hres_pre = {} hres_post = {} for trigger in trigger_list: print " ... trigger = ", trigger hres_pre[trigger] = TH1F("hres_pre_" + trigger, " ;run number; pre-firing " + trigger, n, 0, n) hres_post[trigger] = TH1F("hres_post_" + trigger, " ;run number; post-firing " + trigger, n, 0, n) i = 0 for al in ll_pre: l = al.split() i = i + 1 run = l[0] for trigger in trigger_list: itrig = trigger_list.index(trigger) hres_pre[trigger].GetXaxis().SetBinLabel(i, "Run " + str(run)) hres_pre[trigger].SetBinContent(i, float(l[1 + 2 * itrig])) hres_pre[trigger].SetBinError(i, float(l[1 + 2 * itrig + 1])) i = 0 for al in ll_post: l = al.split() i = i + 1 run = l[0] for trigger in trigger_list: itrig = trigger_list.index(trigger) hres_post[trigger].GetXaxis().SetBinLabel(i, "Run " + str(run)) hres_post[trigger].SetBinContent(i, float(l[1 + 2 * itrig])) hres_post[trigger].SetBinError(i, float(l[1 + 2 * itrig + 1])) pre_fres.close() post_fres.close() # -- do the plots : gStyle.SetOptStat(0) leg = TLegend(0.6, 0.75, 0.95, 0.92, "", "brNDC") leg.SetBorderSize(0) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) tt = TText() tt.SetTextSize(0.06) for trigger in trigger_list: hres_pre[trigger].SetMinimum(0) hres_post[trigger].SetMinimum(0) hres_post[trigger].SetMarkerColor(2) hres_post[trigger].SetLineColor(2) c = TCanvas("c_" + trigger, "c_" + trigger) hres_pre[trigger].GetYaxis().SetTitle( "post/" + hres_pre[trigger].GetYaxis().GetTitle()) hres_pre[trigger].Draw("pe") hres_post[trigger].Draw("same,pe") if trigger_list.index(trigger) == 0: leg.AddEntry(hres_pre[trigger], "pre-firing", "pe") leg.AddEntry(hres_post[trigger], "post-firing", "pe") leg.Draw() tt.DrawTextNDC(0.25, 0.88, trigger) c.SaveAs(trigger + ".gif") # --- store the histograms hres = ROOT.TFile("all_hres.root", "update") for trigger in trigger_list: hres_pre[trigger].Write() hres_post[trigger].Write() hres.Close() return
def createCompoundPlots(detector, plot): """Produce the requested plot for the specified detector. Function that will plot the requested @plot for the specified @detector. The specified detector could either be a real detector or a compound one. The list of available plots are the keys of plots dictionary (imported from plot_utils. """ theDirname = 'Images' if not checkFile_(theDirname): os.mkdir(theDirname) goodToGo, theDetectorFilename = paramsGood_(detector, plot) if not goodToGo: return theDetectorFile = TFile(theDetectorFilename) # # get TProfiles prof_X0_elements = OrderedDict() hist_X0_elements = OrderedDict() for label, [num, color, leg] in hist_label_to_num.iteritems(): prof_X0_elements[label] = theDetectorFile.Get( "%d" % (num + plots[plot].plotNumber)) hist_X0_elements[label] = prof_X0_elements[label].ProjectionX() hist_X0_elements[label].SetFillColor(color) hist_X0_elements[label].SetLineColor(kBlack) files = [] if detector in COMPOUNDS.keys(): for subDetector in COMPOUNDS[detector][1:]: subDetectorFilename = "matbdg_%s.root" % subDetector # open file if not checkFile_(subDetectorFilename): continue subDetectorFile = TFile(subDetectorFilename) files.append(subDetectorFile) print("*** Open file... %s" % subDetectorFilename) # subdetector profiles for label, [num, color, leg] in hist_label_to_num.iteritems(): prof_X0_elements[label] = subDetectorFile.Get( "%d" % (num + plots[plot].plotNumber)) hist_X0_elements[label].Add( prof_X0_elements[label].ProjectionX( "B_%s" % prof_X0_elements[label].GetName()), +1.000) # stack stackTitle = "Material Budget %s;%s;%s" % (detector, plots[plot].abscissa, plots[plot].ordinate) stack_X0 = THStack("stack_X0", stackTitle) for label, [num, color, leg] in hist_label_to_num.iteritems(): stack_X0.Add(hist_X0_elements[label]) # canvas canname = "MBCan_1D_%s_%s" % (detector, plot) can = TCanvas(canname, canname, 800, 800) can.Range(0, 0, 25, 25) can.SetFillColor(kWhite) gStyle.SetOptStat(0) # Draw stack_X0.Draw("HIST") # Legenda theLegend = TLegend(0.70, 0.70, 0.89, 0.89) for label, [num, color, leg] in hist_label_to_num.iteritems(): theLegend.AddEntry(hist_X0_elements[label], leg, "f") theLegend.Draw() # Store can.Update() can.SaveAs("%s/%s_%s.pdf" % (theDirname, detector, plot)) can.SaveAs("%s/%s_%s.png" % (theDirname, detector, plot))