def DrawSplotHistograms(DataFileName, DataTreeName, SFileName, STreeName, noStack=True): fData = TFile(DataFileName) tData = fData.Get(DataTreeName) tData.AddFriend(STreeName, SFileName) histoListe = setupHistograms() HistDic = {} for i, h in enumerate(histoListe): legende = TLegend(0.75, 0.83, 0.97, 0.97) CanvasName = "c" + str(i) CanvasName = TCanvas(CanvasName, 'Defining histogram size') g = THStack("", "") #tMC.Draw(histoListe[i][3],CutMC) #hist_MC = tMC.GetHistogram().Clone("hist_MC") #hist_MC.SetLineColor(6) #hist_MC.SetLineWidth(1) ##hist_MC.SetMarkerStyle(21) #legende.AddEntry(hist_MC, "MC", "lp") #hist_MC.GetXaxis().SetTitle(h[1]) #hist_MC.GetYaxis().SetTitle(h[2]) #hist_MC.Scale(1/hist_MC.Integral()) #MaxMC = hist_MC.GetMaximum() #g.Add(hist_MC) tData.Draw(histoListe[i][3], "B_M>5300") hist_data = tData.GetHistogram().Clone("hist_data") hist_data.SetLineColor(5) hist_data.SetLineWidth(1) #hist_data.SetMarkerStyle(21) legende.AddEntry(hist_data, "Data", "lp") hist_data.GetXaxis().SetTitle(h[1]) hist_data.GetYaxis().SetTitle(h[2]) MaxData = hist_data.GetMaximum() g.Add(hist_data) tData.Draw(histoListe[i][3], "nsig_sw") hist_sw = tData.GetHistogram().Clone("hist_sw") hist_sw.SetLineColor(4) hist_sw.SetLineWidth(1) ##hist_RS.SetMarkerStyle(21) legende.AddEntry(hist_sw, "sweighted Data", "lp") MaxSW = hist_sw.GetMaximum() g.Add(hist_sw) if noStack: if (MaxSW > MaxData): g.SetMaximum(MaxSW * 1.2) else: g.SetMaximum(MaxData * 1.2) g.Draw("nostackhist") else: g.SetMaximum(g.GetMaximum() * 1.2) g.Draw("hist") legende.Draw() g.GetXaxis().SetTitle(h[1]) g.GetYaxis().SetTitle(h[2]) g.GetYaxis().SetTitleOffset(1.4) g.GetXaxis().SetTitleOffset(1.1) my_Latex = TLatex() my_Latex.SetTextSize(0.04) my_Latex.DrawLatexNDC(0.13, 0.85, "LHCb Data 2012") CanvasName.Update() outDir = '/sps/lhcb/volle/FitBMass/v1_Min5120' if not os.path.isdir(outDir): os.makedirs(outDir) CanvasName.SaveAs("{}/{}_both.pdf".format(outDir, histoListe[i][0])) #_both CanvasName.SaveAs("{}/{}_both.png".format(outDir, histoListe[i][0])) #_both
print 'Corrected chi2' #chi2 = ndf*1.0 chi2 = theFitter.computeChi2(ndf) print 'Raw chi2' #chi2Raw = ndf2*1.0 chi2Raw = theFitter.computeChi2(ndf2, False) mf = theFitter.stackedPlot() mf.SetName("Mjj_Stacked") ## sf = theFitter.residualPlot(mf, "h_background", "dibosonPdf", False) # pf = theFitter.residualPlot(mf, "h_total", "", True) pf = pulls.createPull(mf.getHist('theData'), mf.getCurve('h_total')) pf.SetName("Mjj_Pull") ## lf = theFitter.stackedPlot(True) l = TLatex() l.SetNDC() l.SetTextSize(0.035) l.SetTextFont(42) cs = TCanvas("cs", "stacked") mf.Draw() # l.DrawLatex(0.66, 0.55, # '#chi^{{2}}/dof = {0:0.3f}/{1}'.format(chi2, ndf) # ) pyroot_logon.cmsPrelim(cs, fitterPars.intLumi/1000) cs.Print('H{2}_Mjj_{0}_{1}jets_Stacked.pdf'.format(modeString, opts.Nj, opts.mH)) cs.Print('H{2}_Mjj_{0}_{1}jets_Stacked.png'.format(modeString, opts.Nj, opts.mH)) # if (fr.covQual() != 3): # print "Fit did not converge with a good error matrix. Bailing out."
def PlotHisto(hist, fitName, plotType): if debug: print "Fitting", fitName, "function" #get fitting params height = hist.GetMaximum() mean = hist.GetMean() rms = hist.GetRMS() #define fit range variables xmin = mean - 3 * rms xmax = mean + 3 * rms #make the required fit if fitName == "Gauss": fitfunc = TF1('Gauss', Gauss(), xmin, xmax, 3) fitfunc.SetParameters(height, mean, rms) elif fitName == "Bukin": fitfunc = TF1('Bukin', Bukin(), xmin, xmax, 6) fitfunc.SetParameters(height, mean, rms, -0.4, 0.01, 0.005) #create and draw legend and canvas c = TCanvas(histname, histname, 800, 400) legend = TLegend(0.13, 0.7, 0.45, 0.85) #histoStyle() gStyle.SetOptTitle(0) gStyle.SetOptStat(0) #fit and plot according to requirements if plotType == "hist": hist.Fit(fitfunc, "0") legend.AddEntry(hist, "Higgs Mass histo", "l") hist.Draw() elif plotType == "overlay": hist.Fit(fitfunc) legend.AddEntry(hist, "Higgs Mass histo", "l") legend.AddEntry(fitfunc, "Fitted function", "l") hist.Draw() elif plotType == "fit": hist.Fit(fitfunc) func = hist.GetFunction(fitName) legend.AddEntry(func, "Fitted function", "l") hist.Draw("FUNC") func = hist.GetFunction(fitName) fitresults = (func.GetParameter(0), func.GetParameter(1), func.GetParameter(2), func.GetParameter(3), func.GetParameter(4), func.GetParameter(5)) hist.SetXTitle("mbb [GeV]") hist.SetYTitle("Number of events") legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "") legend_text = "#bf{%-.3f/%-.3f/%-.3f}" % ( fitresults[1], fitresults[2], ratio(fitresults[2], fitresults[1])) legend.AddEntry(None, legend_text, "") legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.03) legend.Draw("same") t = TLatex() t.SetNDC() t.SetTextSize(10) t.SetTextFont(43) t.SetTextAlign(13) t.DrawLatex(0.65, 0.85, "#it{#bf{SUPAROOT} lab2 }") t.Draw("same") c.Print(outputfileName) return
def OverlayHistograms(fitName, plotType, histograms, outputfileName): if debug: print "Fitting", fit, "function" print "PlotType:", plotType #create and draw legend and canvas c = TCanvas("canvas", "canvas", 1600, 800) legend = TLegend(0.12, 0.47, 0.40, 0.87) legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "") legend.SetBorderSize(0) legend.SetFillStyle(0) legend.SetTextFont(42) legend.SetTextSize(0.03) gStyle.SetOptTitle(0) gStyle.SetOptStat(0) #make a template histo so that y axis has correct height #find max height for hist in histograms: heights = [] height = hist.GetMaximum() heights.append(height) maxheight = max(heights) + 100 template = histograms[0].Clone() template.SetMaximum(maxheight) template.Reset() template.Draw() template.SetXTitle("mbb [GeV]") template.SetYTitle("Number of events") col = 2 #loop over histos to overlay for hist in histograms: #get fitting params height = hist.GetMaximum() mean = hist.GetMean() rms = hist.GetRMS() #set line color hist.SetLineColor(col) #define fit range variables xmin = mean - 3 * rms xmax = mean + 3 * rms #make the required fit if fitName == "Gauss": fitfunc = TF1('Gauss', Gauss(), xmin, xmax, 3) fitfunc.SetParameters(height, mean, rms) elif fitName == "Bukin": fitfunc = TF1('Bukin', Bukin(), xmin, xmax, 6) fitfunc.SetParameters(height, mean, rms, -0.4, 0.01, 0.005) #fit and plot according to requirements if plotType == "hist": hist.Fit(fitfunc, "0") legend.AddEntry(hist, hist.GetName(), "l") hist.Draw("same") elif plotType == "overlay": hist.Fit(fitfunc, "0") func = hist.GetFunction(fitName) legend.AddEntry(hist, hist.GetName(), "l") hist.Draw("same") func.SetLineColor(col) func.Draw("SAME") elif plotType == "fit": hist.Fit(fitfunc, "0") func = hist.GetFunction(fitName) legend.AddEntry(hist, hist.GetName(), "l") func.Draw("SAME") func.SetLineColor(col) #show fit results in the legend func = hist.GetFunction(fitName) fitresults = (func.GetParameter(0), func.GetParameter(1), func.GetParameter(2), func.GetParameter(3), func.GetParameter(4), func.GetParameter(5)) legend_text = "#bf{%-.3f/%-.3f/%-.3f}" % ( fitresults[1], fitresults[2], ratio(fitresults[2], fitresults[1])) legend.AddEntry(None, legend_text, "") col += 1 #end for loop legend.Draw("same") #plot text t = TLatex() t.SetNDC() t.SetTextSize(14) t.SetTextFont(43) t.SetTextAlign(13) t.DrawLatex(0.8, 0.85, "#it{#bf{SUPAROOT} lab2 }") t.Draw("same") c.Print(outputfileName) return
def __init__(self): self.dataFiles = None self.bins = (50, 0, 1) self.Info = None self.lt = TLatex()
def FitRegion(REGION='SignalRegion'): gROOT.SetBatch(True) # cavn0=TCanvas('test','test',600,600) # SD_REGION='Signal' # REGION='SignalRegion' # REGION='SidebandRegion' #filename='/nfs/dust/cms/user/albrechs/CMSSW_8_1_0/src/DijetCombineLimitCode/input/ZZ_S0_16p00.root' # filename='/nfs/dust/cms/user/albrechs/UHH2_Output/'+REGION+'/backup/uhh2.AnalysisModuleRunner.Data.DATA.root' if ('Signal' in REGION): filename = '/nfs/dust/cms/user/albrechs/UHH2_Output/' + REGION + '/uhh2.AnalysisModuleRunner.MC.MC_QCD.root' else: filename = '/nfs/dust/cms/user/albrechs/UHH2_Output/' + REGION + '/uhh2.AnalysisModuleRunner.Data.DATA.root' # filename='/nfs/dust/cms/user/albrechs/UHH2_Output/'+REGION+'/uhh2.AnalysisModuleRunner.MC.MC_QCD.root' File = TFile(filename) # VVHist_1GeV= File.Get('qcd_invMass') # VBFHist_1GeV= File.Get('qcd_invMass_afterVBFsel') VVHist_1GeV = File.Get('VVRegion/M_jj_AK8_highbin') VBFHist_1GeV = File.Get('invMAk4sel_1p0/M_jj_AK8_highbin') # VVHist_1GeV.Draw('PE1') # raw_input('press enter to continue') VVHist_1GeV.Scale(1. / VVHist_1GeV.Integral(), 'width') VBFHist_1GeV.Scale(1. / VBFHist_1GeV.Integral(), 'width') # VVHist_1GeV.Draw('PE1') # raw_input('press enter to continue') equidistant = False fitbinning = array('d') if (equidistant): binwidth = 400 yTitle = 'Normalized # Events / (%.1f GeV)' % binwidth #NBins=(14000/binwidth) - ( (1040/binwidth) + 1 ) NBins = (14000 / binwidth) - ((1040 / binwidth) + 1) NBins = int(NBins) for i in range(NBins + 1): fitbinning.append(1050 + i * binwidth) # # print(fitbinning) else: yTitle = 'Normalized # Events' #not plotting bin before Mjj>1050GeV Cut nonequidistant_binning = [ 1058, 1118, 1181, 1246, 1313, 1383, 1455, 1530, 1607, 1687, 1770, 1856, 1945, 2037, 2132, 2231, 2332, 2438, 2546, 2659, 2775, 2895, 3019, 3147, 3279, 3416, 3558, 3704, 3854, 4010, 4171, 4337, 4509, 4686, 4869, 5058, 5253, 5455, 5663, 5877, 6099, 6328, 6564, 6808, 7060, 7320, 7589, 7866, 8152, 8447, 8752, 9067, 9391, 9726, 10072, 10430, 10798, 11179, 11571, 11977, 12395, 12827, 13272, 13732, 14000 ] # nonequidistant_binning=[1, 3, 6, 10, 16, 23, 31, 40, 50, 61, 74, 88, 103, 119, 137, 156, 176, 197, 220, 244, 270, 296, 325, 354, 386, 419, 453, 489, 526, 565, 606, 649, 693, 740, 788, 838, 890, 944, 1000, 1058, 1118, 1181, 1246, 1313, 1383, 1455, 1530, 1607, 1687, 1770, 1856, 1945, 2037, 2132, 2231, 2332, 2438, 2546, 2659, 2775, 2895, 3019, 3147, 3279, 3416, 3558, 3704, 3854, 4010, 4171, 4337, 4509, 4686, 4869, 5058, 5253, 5455, 5663, 5877, 6099, 6328, 6564, 6808, 7060, 7320, 7589, 7866, 8152, 8447, 8752, 9067, 9391, 9726, 10072, 10430, 10798, 11179, 11571, 11977, 12395, 12827, 13272, 13732, 14000] NBins = len(nonequidistant_binning) - 1 for b in nonequidistant_binning: fitbinning.append(b) VVHist_100GeV = VVHist_1GeV.Rebin(NBins, "fit parameter", fitbinning) VBFHist_100GeV = VBFHist_1GeV.Rebin(NBins, "fit parameter", fitbinning) # VVHist_100GeV.Scale(1./VVHist_100GeV.Integral(),'width') # VBFHist_100GeV.Scale(1./VBFHist_100GeV.Integral(),'width') # VVHist_100GeV.Draw('PE1') # raw_input('press enter to continue') gStyle.SetOptStat(0) gStyle.SetOptFit(0000) # gStyle.SetOptFit(1100) gStyle.SetOptTitle(0) RooFit.SumW2Error(kTRUE) VV_MAXIMUM = 0 for i in range(VVHist_100GeV.GetNbinsX()): if (VVHist_100GeV.GetBinContent(i) > 0): VV_MAXIMUM = VVHist_100GeV.GetBinCenter(i) VBF_MAXIMUM = 0 for i in range(VBFHist_100GeV.GetNbinsX()): if (VBFHist_100GeV.GetBinContent(i) > 0): VBF_MAXIMUM = VBFHist_100GeV.GetBinCenter(i) VVcanv = TCanvas('VV', 'VV', 700, 700) VVcanv.SetLogy() VVcanv.SetLeftMargin(0.20) VVcanv.cd() # fitOptions='R' # fitOptions='R' fitOptions = 'RSWLM' twopar = '[0]/TMath::Power(x/13000,[1])' threeparlog = '[0]/TMath::Power(x/13000,[1])+([2]*TMath::Log10(x/13000))' threepar = '[0]*TMath::Power((1-(x/13000)),[2])/TMath::Power(x/13000,[1])' # threepar='[0]*TMath::Power((1-x)/13000,[1])+(x/13000)*[2]' fourpar = '[0]*TMath::Power((1-(x/13000),[1])/TMath::Power(x/13000,[2]+[3]*TMath::Log10(x/13000))' if ('Signal' in REGION): NPar = 2 else: NPar = 3 if (NPar == 2): fitfunc = twopar functionTeX = 'p_{0}/(x/#sqrt{s})^{p_{1}}' elif (NPar == 3): # functionTeX='#frac{p_{0}}{(x/#sqrt{s})^{p_{1}}}+p_{2}*log_{10}(x/#sqrt{s})' # fitfunc=threeparlog functionTeX = '#frac{p_{0}*((1-(x/#sqrt{s}))^{p_{2}}}{(x/#sqrt{s})^{p_{1}}}' fitfunc = threepar elif (NPar == 4): fitfunc = fourpar functionTeX = '#frac{p_{0}*((1-x)/#sqrt{s})^{p_{1}}}{(x/#sqrt{s})^{p_{2}+p_{3}*log_{10}(x/#sqrt{s})}}' # for i in range(VVHist_100GeV.GetNbinsX()): # print i,':',VVHist_100GeV.GetBinCenter(i),'-',VVHist_100GeV.GetBinContent(i) # VVHist_100GeV.SetBinContent(19,0) # VVHist_100GeV.SetBinError(19,0) VVTF1 = TF1('VVTF1', fitfunc, 1058, VV_MAXIMUM) # VVTF1.SetParLimits(0,-10**(-6),10**(-6)) # VVTF1.SetParLimits(1,0,8) # VVTF1.SetParLimits(2,-100,0) # VVTF1.SetParameter(0,1.70473**(-7)) VVTF1.SetParameter(0, 1.70473 * 10**(-7)) VVTF1.SetParameter(1, 5.76351) # VVTF1.SetParameter(2,0) VVHist_100GeV.SetMarkerStyle(8) VVHist_100GeV.SetLineColor(1) VVHist_100GeV.GetYaxis().SetRangeUser(10**(-6), 10) VVHist_100GeV.GetXaxis().SetTitle('M_{jj-AK8} [GeV/c^{2}]') VVHist_100GeV.GetYaxis().SetTitle(yTitle) VVHist_100GeV.GetYaxis().SetTitleOffset(2) VVHist_100GeV.Draw('PE1') VVHist_100GeV.GetXaxis().SetRangeUser(1058, VV_MAXIMUM + 1000) VVHist_100GeV.Draw('PE1SAME') #raw_input('press enter to continue') VVHist_100GeV.Sumw2() VVHist_100GeV.Fit('VVTF1', fitOptions) # VVHist_100GeV.Fit('VVTF1','R') VVTF1.Draw('SAME') # VVTF1UP=TF1('VVTF1UP',fitfunc,1050,VV_MAXIMUM) # VVTF1UP.SetParameter(0,VVTF1.GetParameter(0)+VVTF1.GetParError(0)) # VVTF1UP.SetParameter(1,VVTF1.GetParameter(1)+VVTF1.GetParError(1)) # VVTF1UP.SetLineStyle(rt.kDashed) # VVTF1DOWN=TF1('VVTF1DOWN',fitfunc,1050,VV_MAXIMUM) # VVTF1DOWN.SetParameter(0,VVTF1.GetParameter(0)-VVTF1.GetParError(0)) # VVTF1DOWN.SetParameter(1,VVTF1.GetParameter(1)-VVTF1.GetParError(1)) # VVTF1DOWN.SetLineStyle(rt.kDashed) # VVTF1UP.Draw('SAME') # VVTF1DOWN.Draw('SAME') print('chi2/ndf:', VVTF1.GetChisquare(), '/', VVTF1.GetNDF()) latex = TLatex() latex.SetNDC(kTRUE) latex.SetTextSize(0.03) # latex.DrawLatex(0.52,0.953,"%.2f fb^{-1} (13 TeV)"%36.1) latex.DrawLatex( 0.45, 0.65, "#chi^{2}/ndof=%.2f/%.2f=%.2f" % (VVTF1.GetChisquare(), VVTF1.GetNDF(), VVTF1.GetChisquare() / VVTF1.GetNDF())) latex.Draw("SAME") VVleg = TLegend(0.45, 0.7, 0.9, 0.9) VVleg.SetBorderSize(0) VVleg.SetFillStyle(0) if ('Data' in filename): VVleg.AddEntry(VVHist_100GeV, 'Data-!VBF', 'p') VVleg.AddEntry(VVTF1, 'Data-!VBF Fit %s' % functionTeX, 'l') else: VVleg.AddEntry(VVHist_100GeV, 'QCD-!VBF', 'p') VVleg.AddEntry(VVTF1, 'QCD-!VBF Fit %s' % functionTeX, 'l') VVleg.SetTextSize(0.03) VVleg.Draw('SAME') VVcanv.Print(REGION + '_VVRegion.eps') VBFcanv = TCanvas('VBF', 'VBF', 700, 700) VBFcanv.SetLogy() VBFcanv.SetLeftMargin(0.20) VBFcanv.cd() VBFTF1 = TF1('VBFTF1', fitfunc, 1058, VBF_MAXIMUM) if (NPar > 2): VBFTF1.SetParameter(0, 2.85852 * 10**(-8)) VBFTF1.SetParameter(1, 6.49129) VBFTF1.SetParameter(2, -1) VBFTF1.SetLineColor(rt.kBlue) VBFTF1.SetLineWidth(2) # VBFTF1.SetLineStyle(2) VBFHist_100GeV.SetMarkerStyle(8) VBFHist_100GeV.SetLineColor(1) VBFHist_100GeV.GetYaxis().SetRangeUser(10**(-6), 10) VBFHist_100GeV.GetXaxis().SetTitle('M_{jj-AK8} [GeV/c^{2}]') VBFHist_100GeV.GetYaxis().SetTitle(yTitle) VBFHist_100GeV.GetYaxis().SetTitleOffset(2) VBFHist_100GeV.Draw('PE1') VBFHist_100GeV.GetXaxis().SetRangeUser(1058, VV_MAXIMUM + 1000) VBFHist_100GeV.Draw('PE1SAME') # raw_input('press enter to continue') # VBFHist_100GeV.Sumw2() VBFHist_100GeV.Fit('VBFTF1', fitOptions) VBFTF1.Draw('SAME') # VVTF1.SetLineStyle(2) VVTF1.Draw('SAME') # VVTF1UP.Draw('SAME') # VVTF1DOWN.Draw('SAME') # VBFTF1UP=TF1('VBFTF1UP',fitfunc,1050,VBF_MAXIMUM) # VBFTF1UP.SetParameter(0,VBFTF1.GetParameter(0)+VBFTF1.GetParError(0)) # VBFTF1UP.SetParameter(1,VBFTF1.GetParameter(1)+VBFTF1.GetParError(1)) # VBFTF1UP.SetLineColor(rt.kBlue) # VBFTF1UP.SetLineStyle(rt.kDashed) # VBFTF1DOWN=TF1('VBFTF1DOWN',fitfunc,1050,VBF_MAXIMUM) # VBFTF1DOWN.SetParameter(0,VBFTF1.GetParameter(0)-VBFTF1.GetParError(0)) # VBFTF1DOWN.SetParameter(1,VBFTF1.GetParameter(1)-VBFTF1.GetParError(1)) # VBFTF1DOWN.SetLineColor(rt.kBlue) # VBFTF1DOWN.SetLineStyle(rt.kDashed) # VBFTF1UP.Draw('SAME') # VBFTF1DOWN.Draw('SAME') print('chi2/ndf:', VBFTF1.GetChisquare(), '/', VBFTF1.GetNDF()) latexvbf = TLatex() latexvbf.SetNDC(kTRUE) latexvbf.SetTextSize(0.03) latexvbf.DrawLatex( 0.45, 0.65, "#chi^{2}/ndof=%.2f/%.2f=%.2f" % (VBFTF1.GetChisquare(), VBFTF1.GetNDF(), VBFTF1.GetChisquare() / VBFTF1.GetNDF())) VBFleg = TLegend(0.45, 0.7, 0.9, 0.9) VBFleg.SetBorderSize(0) VBFleg.SetFillStyle(0) if ('Data' in filename): VBFleg.AddEntry(VBFHist_100GeV, 'Data-VBF', 'p') VBFleg.AddEntry(VBFTF1, 'Data-VBF Fit %s' % functionTeX, 'l') VBFleg.AddEntry(TH1F(), '', '') VBFleg.AddEntry(VVTF1, 'Data-!VBF Fit %s' % functionTeX, 'l') else: VBFleg.AddEntry(VBFHist_100GeV, 'QCD-VBF', 'p') VBFleg.AddEntry(VBFTF1, 'QCD-VBF Fit %s' % functionTeX, 'l') if (NPar == 3): VBFleg.AddEntry(TH1F(), '', '') VBFleg.AddEntry(VVTF1, 'QCD-!VBF Fit %s' % functionTeX, 'l') VBFleg.SetTextSize(0.03) VBFleg.Draw('SAME') VBFcanv.Print(REGION + '_VBFRegion.eps')
def SAME3VsLumi(g1, g2, g3, title, ptype, lineMC1, lineDATA1, lineMC2, lineDATA2, lineMC3, lineDATA3, DoInclusive, dataPeriod): canvas = makeCMSCanvas(str(random.random()),"canvas",900,700) canvas.cd() graph2=copy.deepcopy(g2) graph3=copy.deepcopy(g3) graph2.SetMarkerColor(kBlue)#electrons graph3.SetMarkerColor(kRed)#muons multigraph = TMultiGraph() if(DoInclusive): graph1=copy.deepcopy(g1) multigraph.Add(graph1,"AP") multigraph.Add(graph2,"AP") multigraph.Add(graph3,"AP") multigraph.Draw("AP") TGaxis.SetMaxDigits(2) TGaxis.SetExponentOffset(-0.05, 0.02, "y") multigraph.GetXaxis().SetTitle("L [fb^{-1}]") multigraph.GetYaxis().SetTitleOffset(1.4) if(ptype == "Zmass"): multigraph.GetYaxis().SetTitle("M_{Z} [GeV]") # multigraph.GetYaxis().SetTitle("M_{l^{+}l^{-}} [GeV]") multigraph.SetMaximum(max(multigraph.GetHistogram().GetMaximum(),91.4)) multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(),89.6)) elif(ptype == "Zwidth"): multigraph.GetYaxis().SetTitle("#Gamma_{Z} [GeV]") elif(ptype == "Zmult"): multigraph.GetYaxis().SetTitle("#Z / fb^{-1}") if(not DoInclusive) : multigraph.SetMaximum(max(multigraph.GetHistogram().GetMaximum(),60000.)) # set y axis minimum at 60000. multigraph.SetMinimum(0.) # set y axis minimum at 0. # multigraph.SetMaximum(60000.) #second type: vs 2016 plots # multigraph.SetMinimum(25000.) printLumiPrelOut(canvas) # Draw legend legend = TLegend(0.93,0.84,0.99,0.93) if(DoInclusive): #legend.AddEntry(graph1,"inclusive","P") legend.AddEntry(graph1,"BB","P") legend.AddEntry(graph2,"BE","P") legend.AddEntry(graph3,"EE","P") else : legend.AddEntry(graph2,"e^{+}e^{-}","P") legend.AddEntry(graph3,"#mu^{+}#mu^{-}","P") legend.SetFillColor(kWhite) legend.SetLineColor(kBlack) legend.SetTextFont(43) legend.SetTextSize(20) legend.Draw() canvas.Update() # Draw letters for data-taking periods if(dataPeriod == "data2017"): textLetters = TLatex() textLetters.SetTextColor(kGray+1) textLetters.SetTextSize(0.03) if(ptype == "Zmass"): textLetters.DrawLatex(2., gPad.GetUymin()+0.2,"B") textLetters.DrawLatex(9.5, gPad.GetUymin()+0.2,"C") textLetters.DrawLatex(16., gPad.GetUymin()+0.2,"D") textLetters.DrawLatex(23., gPad.GetUymin()+0.2,"E") textLetters.DrawLatex(36., gPad.GetUymin()+0.2,"F") elif(ptype == "Zwidth"): textLetters.DrawLatex(2., gPad.GetUymin()+0.3,"B") textLetters.DrawLatex(9.5, gPad.GetUymin()+0.3,"C") textLetters.DrawLatex(16., gPad.GetUymin()+0.3,"D") textLetters.DrawLatex(23., gPad.GetUymin()+0.3,"E") textLetters.DrawLatex(36., gPad.GetUymin()+0.3,"F") elif(ptype == "Zmult") : textLetters.DrawLatex(2., 260000,"B") textLetters.DrawLatex(9.5, 260000,"C") textLetters.DrawLatex(16., 260000,"D") textLetters.DrawLatex(23., 260000,"E") textLetters.DrawLatex(36., 260000,"F") if(dataPeriod == "data2018"): textLetters = TLatex() textLetters.SetTextColor(kGray+1) textLetters.SetTextSize(0.03) if(ptype == "Zmass"): textLetters.DrawLatex(6., gPad.GetUymin() + 0.6,"A") textLetters.DrawLatex(16., gPad.GetUymin() + 0.6,"B") textLetters.DrawLatex(23., gPad.GetUymin() + 0.6,"C") textLetters.DrawLatex(43., gPad.GetUymin() + 0.6,"D") elif(ptype == "Zwidth"): textLetters.DrawLatex(6., gPad.GetUymin() +0.3,"A") textLetters.DrawLatex(16., gPad.GetUymin() +0.3,"B") textLetters.DrawLatex(23., gPad.GetUymin() +0.3,"C") textLetters.DrawLatex(43., gPad.GetUymin() +0.3,"D") elif(ptype == "Zmult") : textLetters.DrawLatex(6., 260000,"A") textLetters.DrawLatex(16., 260000,"B") textLetters.DrawLatex(23., 260000,"C") textLetters.DrawLatex(43., 260000,"D") # **** if(dataPeriod == "data2018"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineA = TLine(13.48, down, 13.48, up) # Run2018A up to 13.48 fb-1 lineA.SetLineColor(kBlack) lineA.SetLineStyle(2) lineA.Draw() lineB = TLine(20.265, down, 20.265, up) # Run2018B up to 20.265 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(26.877, down, 26.877, up) # Run2018C up to 26.877 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() if(dataPeriod == "data2017"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineB = TLine(4.793, down, 4.793, up) # Run2017B up to 4.793 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(14.549, down, 14.549, up) # Run2017C up to 14.549 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() lineD = TLine(18.868, down, 18.868, up) # Run2017D up to 18.868 fb-1 lineD.SetLineColor(kBlack) lineD.SetLineStyle(2) lineD.Draw() lineE = TLine(28.293, down, 28.293, up) # Run2017E up to 28.293 fb-1 lineE.SetLineColor(kBlack) lineE.SetLineStyle(2) lineE.Draw() if(dataPeriod == "data2016"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineB = TLine(5.789, down, 5.789, up) # Run2016B up to 5.789 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(8.366, down, 8.366, up) # Run2016C up to 8.366 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() lineD = TLine(12.616, down, 12.616, up) # Run2016D up to 12.616 fb-1 lineD.SetLineColor(kBlack) lineD.SetLineStyle(2) lineD.Draw() lineE = TLine(16.624, down, 16.624, up) # Run2016E up to 16.624 fb-1 lineE.SetLineColor(kBlack) lineE.SetLineStyle(2) lineE.Draw() lineF = TLine(19.725, down, 19.725, up) # Run2016F up to 19.725 fb-1 lineF.SetLineColor(kBlack) lineF.SetLineStyle(2) lineF.Draw() lineG = TLine(27.268, down, 27.268, up) # Run2016G up to 27.268 fb-1 lineG.SetLineColor(kBlack) lineG.SetLineStyle(2) lineG.Draw() # **** # draw orizontal lines for MC and DATA fit if(ptype == "Zmass" or ptype == "Zwidth") : leftEnd = gPad.GetUxmin() rightEnd = gPad.GetUxmax() if(DoInclusive): line1 = TLine(leftEnd,lineMC1,rightEnd,lineMC1) line1.SetLineColor(kBlack) line1.SetLineStyle(1) line1.Draw() line2 = TLine(leftEnd,lineDATA1,rightEnd,lineDATA1) line2.SetLineColor(kBlack) line2.SetLineStyle(2) line2.Draw() # line for graph 2: color blue line3 = TLine(leftEnd,lineMC2,rightEnd,lineMC2) line3.SetLineColor(kBlue) line3.SetLineStyle(1) line3.Draw() line4 = TLine(leftEnd,lineDATA2,rightEnd,lineDATA2) line4.SetLineColor(kBlue) line4.SetLineStyle(2) line4.Draw() # line for graph 3: color red line5 = TLine(leftEnd,lineMC3,rightEnd,lineMC3) line5.SetLineColor(kRed) line5.SetLineStyle(1) line5.Draw() line6 = TLine(leftEnd,lineDATA3,rightEnd,lineDATA3) line6.SetLineColor(kRed) line6.SetLineStyle(2) line6.Draw() # *** canvas.SaveAs(title + ".root") canvas.SaveAs(title + ".pdf") canvas.SaveAs(title + ".png") return;
lineVector = [ line1, line2, line3, line4, line5, line6, line7, line8, line9, line10, line11, line12, line13, line14, line15, line16, line17, line18, line19, line20, line21, line22, line23, line24, line25, line26, line27, line28, line29, line30, line31, line32, line33, line34, line35, line36, line37, line38, line39, line40, line41, line42, line43, line44, line45, line46, line47, line48, line49, line50, line51, line52, line53, line54, line55, line56, line57, line58, line59, line60, line61, line62, line63, line64 ] for line in lineVector: line.SetLineColor(ROOT.kBlack) line.SetLineWidth(3) line.Draw() leg = TLegend(.54, .78, .58, .82) leg.SetFillStyle(0) leg.SetLineWidth(4) leg.Draw() text = TLatex(.6, .78, "NA49 Coverage") text.SetTextColor(ROOT.kBlack) text.SetNDC() text.SetTextSize(1.4 / 30.) text.SetTextAlign(11) #text.DrawLatex(.48, .55, "#Square"); text.Draw() raw_input("Please press enter to exit.")
def GetAndDrawHistograms(DataFileName, DataTreeName, MCFileName, MCTreeName, noStack=True): fMC = TFile(MCFileName) tMC = fMC.Get(MCTreeName) fData = TFile(DataFileName) tData = fData.Get(DataTreeName) histoListe = setupHistograms() HistDic = {} for i, h in enumerate(histoListe): legende = TLegend(0.7, 0.7, 0.89, 0.89) CanvasName = "c" + str(i) CanvasName = TCanvas(CanvasName, 'Defining histogram size') g = THStack("", "") #tMC.Draw(histoListe[i][3],CutMC) #hist_MC = tMC.GetHistogram().Clone("hist_MC") #hist_MC.SetLineColor(6) #hist_MC.SetLineWidth(1) ##hist_MC.SetMarkerStyle(21) #legende.AddEntry(hist_MC, "MC", "lp") #hist_MC.GetXaxis().SetTitle(h[1]) #hist_MC.GetYaxis().SetTitle(h[2]) #hist_MC.Scale(1/hist_MC.Integral()) #MaxMC = hist_MC.GetMaximum() #g.Add(hist_MC) tData.Draw(histoListe[i][3], CutData) hist_data = tData.GetHistogram().Clone("hist_data") hist_data.SetLineColor(9) hist_data.SetLineWidth(1) #hist_data.SetMarkerStyle(21) legende.AddEntry(hist_data, "Data", "lp") hist_data.GetXaxis().SetTitle(h[1]) hist_data.GetYaxis().SetTitle(h[2]) #hist_data.Scale(1/hist_data.Integral()) MaxData = hist_data.GetMaximum() g.Add(hist_data) #tData.Draw(histoListe[i][3],CutData_RS) #hist_RS = tData.GetHistogram().Clone("hist_RS") #hist_RS.SetLineColor(4) #hist_RS.SetLineWidth(1) ##hist_RS.SetMarkerStyle(21) #legende.AddEntry(hist_RS, "Data RS", "lp") #hist_RS.Scale(1/hist_RS.Integral()) #MaxRS = hist_RS.GetMaximum() #g.Add(hist_RS) #if noStack: # if (MaxMC > MaxData): # g.SetMaximum(MaxMC*1.1) # else: # g.SetMaximum(MaxData*1.1) # g.Draw("nostackhist") #else: # g.SetMaximum(g.GetMaximum()*1.1) # g.Draw("hist") g.SetMaximum(MaxData * 1.1) g.Draw("hist") #legende.Draw() g.GetXaxis().SetTitle(h[1]) g.GetYaxis().SetTitle(h[2]) g.GetYaxis().SetTitleOffset(1.4) g.GetXaxis().SetTitleOffset(1.1) my_Latex = TLatex() my_Latex.SetTextSize(0.04) my_Latex.DrawLatexNDC(0.13, 0.85, "LHCb Data 2012") CanvasName.Update() outDir = '/sps/lhcb/volle/BMass' if not os.path.isdir(outDir): os.makedirs(outDir) CanvasName.SaveAs("{}/{}_{}.pdf".format(outDir, histoListe[i][0], comment)) CanvasName.SaveAs("{}/{}_{}.png".format(outDir, histoListe[i][0], comment))
def MakePlots(self): if not hasattr(self, "Numerator") or not hasattr(self, "Denominator"): print "Either Numerator or Denominator has not been defined. Not finding hot spots..." return circles = [] for spots in self._hotSpotsList: circle = TEllipse(float(spots[0]), float(spots[1]), 0.06) circle.SetLineColor(2) circle.SetLineWidth(1) circle.SetFillStyle(0) circles.append(circle) LumiText = str.format('{0:.1f}', self._luminosityInInvFb) + " fb^{-1} (13 TeV)" pasLumiLatex = TLatex() pasLumiLatex.SetNDC() pasLumiLatex.SetTextAngle(0) pasLumiLatex.SetTextFont(42) pasLumiLatex.SetTextAlign(32) pasLumiLatex.SetTextSize(0.04) pasCMSLatex = TLatex() pasCMSLatex.SetNDC() pasCMSLatex.SetTextAngle(0) pasCMSLatex.SetTextFont(62) pasCMSLatex.SetTextAlign(12) pasCMSLatex.SetTextSize(0.04) pasPrelimLatex = TLatex() pasPrelimLatex.SetNDC() pasPrelimLatex.SetTextAngle(0) pasPrelimLatex.SetTextFont(62) pasPrelimLatex.SetTextAlign(12) pasPrelimLatex.SetTextSize(0.04) self.Denominator["histogram"].Draw('colz') pasLumiLatex.DrawLatex(0.96, 0.93, LumiText) pasCMSLatex.DrawLatex(0.12, 0.925, "CMS Preliminary") self._canvas.SaveAs('fiducialMapCalc_beforeVeto_' + self.Denominator["sample"] + '.pdf') self.Numerator["histogram"].Draw('colz') pasLumiLatex.DrawLatex(0.96, 0.93, LumiText) pasCMSLatex.DrawLatex(0.12, 0.925, "CMS Preliminary") self._canvas.SaveAs('fiducialMapCalc_afterVeto_' + self.Numerator["sample"] + '.pdf') self._canvas.SetLogz(False) self.Numerator["histogram"].Divide(self.Denominator["histogram"]) self.Numerator["histogram"].Draw('colz') if 'SingleEle' in self.Numerator["sample"]: self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 0.5) elif 'SingleMu' in self.Numerator["sample"]: self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 0.05) self.Numerator["histogram"].GetZaxis().SetLabelSize(0.025) for circle in circles: circle.Draw("same") pasLumiLatex.DrawLatex(0.96, 0.93, LumiText) pasCMSLatex.DrawLatex(0.12, 0.925, "CMS Preliminary") self._canvas.SaveAs('fiducialMapCalc_efficiency_' + self.Numerator["sample"] + '.pdf') for xbin in range(1, self.Numerator["histogram"].GetXaxis().GetNbins()): for ybin in range( 1, self.Numerator["histogram"].GetYaxis().GetNbins()): thisInefficiency = self.Numerator["histogram"].GetBinContent( xbin, ybin) if thisInefficiency == 0: continue valueInSigma = (thisInefficiency - self._meanInefficiency ) / self._stdDevInefficiency if valueInSigma < 0: valueInSigma = 0 self.Numerator["histogram"].SetBinContent( xbin, ybin, valueInSigma) self._canvas.SetLogz(False) self.Numerator["histogram"].GetZaxis().SetLabelSize(0.04) self.Numerator["histogram"].Draw('colz') if 'SingleEle' in self.Numerator["sample"]: if '2017' in self.Numerator["sample"]: self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 7) self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 12) elif 'SingleMu' in self.Numerator["sample"]: self.Numerator["histogram"].GetZaxis().SetRangeUser(0, 23) self.Numerator["histogram"].GetZaxis().SetLabelSize(0.025) for circle in circles: circle.Draw("same") pasLumiLatex.DrawLatex(0.96, 0.93, LumiText) pasCMSLatex.DrawLatex(0.12, 0.925, "CMS Preliminary") self._canvas.SaveAs('fiducialMapCalc_efficiencyInSigma_' + self.Numerator["sample"] + '.pdf')
c4.SetBottomMargin(0.15) c4.SetRightMargin(0.06) #c4.SetLogy(1) #expected95.SetMinimum(0.0001); expected95.SetMaximum(0.0056) expected95.Draw("a3") expected95.GetXaxis().SetTitle("Diphoton Mass [GeV/c^{2}]") expected95.GetYaxis().SetTitle("#sigma(G_{RS} #rightarrow #gamma #gamma)[pb]") expected68.Draw("3same") expected_p.Draw("csame") observed_p.Draw("cpsame") theory.Draw("same") latex = TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.SetTextAlign(31) # align right latex.DrawLatex(0.45, 0.95, "CMS Preliminary") latex2 = TLatex() latex2.SetNDC() latex2.SetTextSize(0.04) latex2.SetTextAlign(31) # align right latex2.DrawLatex(0.87, 0.95, "19.37 fb^{-1} at #sqrt{s} = 8 TeV") latex4 = TLatex() latex4.SetNDC() latex4.SetTextSize(0.04) latex4.SetTextAlign(31) # align right
def main(): output = argv[1] rap = argv[2] flavour = argv[3] trackType = argv[4] f = argv[5] fit_min = int(argv[6]) fit_max = int(argv[7]) rebinFactor = int(argv[8]) i = int(argv[9]) if f == "CB": DOCRYSTALBALL = True DOCRUIJFF = False DODOUBLECB = False elif f == "cruijff": DOCRUIJFF = True DOCRYSTALBALL = False DODOUBLECB = False elif f == "doubleCB": DODOUBLECB = True DOCRYSTALBALL = False DOCRUIJFF = False print ("+++++++++++++++++++++++++++++++++++++++++") print ("Fitting histogram for %d < pt_{l} <%d" %(ptbins[i],ptbins[i+1])) print ("+++++++++++++++++++++++++++++++++++++++++\n") wsFile = TFile("tmpWorkspace.root") ws = wsFile.Get("tempWS") # fit with a gaussian if DOCRYSTALBALL: funct = TF1("crystal","crystalball",fit_min,fit_max) funct.SetLineColor(kRed) if ws.data("hist").sum(False) < 1500: nDOF = (fit_max-fit_min)*2/(rebinFactor)-3 else: nDOF = (fit_max-fit_min)*2/rebinFactor-3 ws.factory("RooCBShape::cb(mass, mean[0.0,-1.5,1.5], sigma[2,0,10], alphaL[3,-25,25], nL[5,-25,25])") ws.factory("BreitWigner::bw(mass,meanZ[91.187], width[2.495])") bw = ws.pdf("bw") cb = ws.pdf("cb") ws.var("mass").setBins(2000,"cache") ws.var("mass").setMin("cache",0) ws.var("mass").setMax("cache",1000); ## need to be adjusted to be higher than limit setting sigpdf = RooFFTConvPdf("sig","sig",ws.var("mass"),bw,cb) getattr(ws,'import')(sigpdf,RooCmdArg()) fitResult = ws.pdf("sig").fitTo(ws.data("hist"),RooFit.Save(), RooFit.SumW2Error(kFALSE), RooFit.Minos(kFALSE)) elif DOCRUIJFF: gSystem.Load("./RooCruijff_cxx.so") ws.factory("RooCruijff::cb(mass, mean[0.0,-1.5,1.5], sigma[2,0,20], sigma, alphaL[1,0,25], alphaR[1,0,25])") if ws.data("hist").sum(False) < 1500: nDOF = (fit_max-fit_min)*2/(1)-3 elif ws.data("hist").sum(False) < 2500: nDOF = (fit_max-fit_min)*2/(1)-3 else: nDOF = (fit_max-fit_min)*2/rebinFactor-3 ws.factory("BreitWigner::bw(mass,meanZ[91.187], width[2.495])") bw = ws.pdf("bw") cb = ws.pdf("cb") ws.var("mass").setBins(2000,"cache") ws.var("mass").setMin("cache",0) ws.var("mass").setMax("cache",1000); ## need to be adjusted to be higher than limit setting sigpdf = RooFFTConvPdf("sig","sig",ws.var("mass"),bw,cb) getattr(ws,'import')(sigpdf,RooCmdArg()) fitResult = ws.pdf("sig").fitTo(ws.data("hist"),RooFit.Save(), RooFit.SumW2Error(kFALSE), RooFit.Minos(kFALSE)) elif DODOUBLECB: gSystem.Load("./RooDCBShape_cxx.so") if i > 2: ws.factory("RooDCBShape::cb(mass, mean[0.0,-1.5,1.5], sigma[2,0,20], alphaL[2,0,25] , alphaR[2,0,25], nL[2.5,0,25], nR[0])") else: ws.factory("RooDCBShape::cb(mass, mean[0.0,-1.5,1.5], sigma[2,0,20], alphaL[2,0,25] , alphaR[2,0,25], nL[2.5,0,25], nR[2.5,0,25])") if i == 0: ws.var("nL").setVal(1) ws.var("nR").setVal(1) ws.factory("BreitWigner::bw(mass,meanZ[91.187], width[2.495])") bw = ws.pdf("bw") cb = ws.pdf("cb") ws.var("mass").setBins(2000,"cache") ws.var("mass").setMin("cache",0) ws.var("mass").setMax("cache",1000); ## need to be adjusted to be higher than limit setting sigpdf = RooFFTConvPdf("sig","sig",ws.var("mass"),bw,cb) getattr(ws,'import')(sigpdf,RooCmdArg()) fitResult = ws.pdf("sig").fitTo(ws.data("hist"),RooFit.Save(), RooFit.SumW2Error(kFALSE), RooFit.Minos(kFALSE)) chi2 = RooChi2Var("bla","blubb",ws.pdf("sig"),ws.data("hist")).getVal() if ws.data("hist").sum(False) < 1500: nDOF = (fit_max-fit_min)*2/(1)-5 elif ws.data("hist").sum(False) < 2500: nDOF = (fit_max-fit_min)*2/(1)-5 else: nDOF = (fit_max-fit_min)*2/rebinFactor-5 chi2 = RooChi2Var("bla","blubb",ws.pdf("sig"),ws.data("hist")).getVal() mean = RooRealVar('Mean','Mean',ws.var("meanZ").getVal() ) getattr(ws,'import')(mean,RooCmdArg()) meane = RooRealVar('Meane','Meane',ws.var("meanZ").getError() ) getattr(ws,'import')(meane,RooCmdArg()) sig = RooRealVar('Sig','Sig',ws.var("sigma").getVal() ) getattr(ws,'import')(sig,RooCmdArg()) sige = RooRealVar('Sige','Sige',ws.var("sigma").getError() ) getattr(ws,'import')(sige,RooCmdArg()) c1 = TCanvas("c1","c1",700,700) c1.cd() plotPad = TPad("plotPad","plotPad",0,0,1,1) style = setTDRStyle() gStyle.SetOptStat(0) gStyle.SetTitleXOffset(1.45) gStyle.SetPadLeftMargin(0.2) gStyle.SetTitleYOffset(2) plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() if DODOUBLECB or DOCRYSTALBALL or DOCRUIJFF: ws.var("mass").setBins(30) frame = ws.var('mass').frame(RooFit.Title('Invariant mass of dimuon pairs')) frame.GetXaxis().SetTitle('m_{#mu#mu} [GeV]') frame.GetYaxis().SetTitle("Events / 2 GeV") RooAbsData.plotOn(ws.data('hist'), frame,RooFit.Name("hist")) ws.pdf('sig').plotOn(frame,RooFit.Name("sig")) frame.Draw() chi2 = frame.chiSquare("sig","hist") else: h.GetXaxis().SetTitle("m_{ll} [GeV]") h.SetLineColor(kBlack) h.GetXaxis().SetRangeUser(fit_min,fit_max) h.SetMarkerStyle(20) h.SetMarkerSize(0.7) h.Draw("E") if DOCRYSTALBALL or DOCRUIJFF or DODOUBLECB: funct.Draw("SAME") else: gaus.Draw("SAME") nDOFforWS = RooRealVar('nDOF','nDOF',nDOF ) getattr(ws,'import')(nDOFforWS,RooCmdArg()) chi2forWS = RooRealVar('chi2','chi2',chi2*nDOF ) getattr(ws,'import')(chi2forWS,RooCmdArg()) latex = TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "(13 TeV)") cmsExtra = "Preliminary" latexCMS.DrawLatex(0.78,0.88,"CMS") yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.78,yLabelPos,"%s"%(cmsExtra)) latexFit1 = TLatex() latexFit1.SetTextFont(42) latexFit1.SetTextSize(0.035) latexFit1.SetNDC(True) latexFit1.DrawLatex(0.25, 0.84, "%d GeV < p_{T} < %d GeV" %(ptbins[i],ptbins[i+1])) latexFit = TLatex() latexFit.SetTextFont(42) latexFit.SetTextSize(0.030) latexFit.SetNDC(True) latexFit.DrawLatex(0.25, 0.74,"%s = %5.3g #pm %5.3g GeV"%("mean bias",ws.var("mean").getVal(),ws.var("mean").getError())) if f == "CB": latexFit.DrawLatex(0.25, 0.7,"%s = %5.3g #pm %5.3g GeV"%("#sigma",ws.var("sigma").getVal(),ws.var("sigma").getError())) latexFit.DrawLatex(0.25, 0.66,"%s = %5.3g #pm %5.3g"%("alphaL",ws.var("alphaL").getVal(),ws.var("alphaL").getError())) latexFit.DrawLatex(0.25, 0.62,"%s = %5.3g #pm %5.3g"%("nL",ws.var("nL").getVal(),ws.var("nL").getError())) elif f == "cruijff": latexFit.DrawLatex(0.25, 0.7,"%s = %5.3g #pm %5.3g GeV"%("#sigma",ws.var("sigma").getVal(),ws.var("sigma").getError())) latexFit.DrawLatex(0.25, 0.66,"%s = %5.3g #pm %5.3g"%("alphaL",ws.var("alphaL").getVal(),ws.var("alphaL").getError())) latexFit.DrawLatex(0.25, 0.62,"%s = %5.3g #pm %5.3g"%("alphaR",ws.var("alphaR").getVal(),ws.var("alphaR").getError())) elif f == "doubleCB": latexFit.DrawLatex(0.25, 0.7,"%s = %5.3g #pm %5.3g GeV"%("#sigma",ws.var("sigma").getVal(),ws.var("sigma").getError())) latexFit.DrawLatex(0.25, 0.66,"%s = %5.3g #pm %5.3g"%("alphaL",ws.var("alphaL").getVal(),ws.var("alphaL").getError())) latexFit.DrawLatex(0.25, 0.62,"%s = %5.3g #pm %5.3g"%("alphaR",ws.var("alphaR").getVal(),ws.var("alphaR").getError())) latexFit.DrawLatex(0.25, 0.58,"%s = %5.3g #pm %5.3g"%("nL",ws.var("nL").getVal(),ws.var("nL").getError())) latexFit.DrawLatex(0.25, 0.54,"%s = %5.3g #pm %5.3g"%("nR",ws.var("nR").getVal(),ws.var("nR").getError())) latexFit.DrawLatex(0.25, 0.5, "#chi^{2}/ndf = %5.3f / %2.0f = %4.2f" %(chi2*nDOF,nDOF,chi2)) saveas = "/MassRes_%s_%s_Pt%d_%d_%s" %(trackType,flavour,ptbins[i],ptbins[i+1],rap) c1.SaveAs(output+saveas+".root") c1.SaveAs(output+saveas+".C") c1.SaveAs(output+saveas+".png") c1.SaveAs(output+saveas+".pdf") print ("DONE Fitting...") ws.writeToFile("tmpWorkspaceReturn.root")
print "Max quarantined " + str( max([e.Q for j, e in histories[i].iteritems()])) print "Max deaths " + str( max([e.D for j, e in histories[i].iteritems()])) from ROOT import TH1F, TCanvas import math ###################### # Estimation part!!! # ###################### nbins = int(0.5 * math.sqrt(n_pseudo_exp)) if n_pseudo_exp > 10 else 3 from ROOT import TLatex latex = TLatex() latex.SetTextSize(0.03) latex.SetTextFont(42) # qpeak 30000, deaths 8000, total 60000 # # Peak of quarantined # qpeak = 35000 histos["q_peak"] = TH1F("q_peak", "", nbins, 0., 1e5) for i, h in histories.iteritems(): histos["q_peak"].Fill(max([e.Q for i, e in h.iteritems()])) canvases["q_peak"] = TCanvas("q_peak", "Peak of quarantines", 400, 400) histos["q_peak"].SetStats(0) histos["q_peak"].SetTitle("; Maximum of quarantined people; A.U.") histos["q_peak"].SetLineColor(1)
def fit(histo, outdir, file=0, Ecm=0): """Fit the transverse profile to gat the parametrization and save in root file""" canvas_fit = TCanvas("c_fit_{}_{}".format(histo, Ecm), "c_fit", 800, 600) if not file: infile = outdir + ".root" else: infile = file file_ = TFile(infile, "r") file_.cd() g_fit = gDirectory.Get(histo) g_fit.Draw() par = array('d', 13 * [0.]) f1 = TF1("f1", "gaus", -4, -3.5) g_fit.Fit(f1, "R0") par1 = f1.GetParameters() tail1 = TF1("tail1", "crystalball", -6, -3.5) tail1.SetParameters(par1[0], par1[1], par1[2], 1.0, 1.6) tail1.SetLineColor(3) g_fit.Fit(tail1, "R0+") par2 = tail1.GetParameters() tail2 = TF1("tail2", "crystalball", -4, -2) tail2.SetParameters(par1[0], par1[1], par1[2], -0.68, 1.85) tail2.SetLineColor(4) g_fit.Fit(tail2, "R0+") par3 = tail2.GetParameters() par[0], par[1], par[2] = par1[0], par1[1], par1[2] par[3], par[4], par[5], par[6], par[7] = par2[0], par1[1], par2[2], par2[ 3], par2[4] par[8], par[9], par[10], par[11], par[12] = par3[0], par1[1], par3[ 2], par3[3], par3[4] total = TF1("total", 'gaus(0)+crystalball(3)+crystalball(8)', -6, -2.3) total.SetParameters(par) total.SetLineColor(1) g_fit.Fit(total, "R+") # gStyle.SetOptFit(1) tot_param = total.GetParameters() sum_sigma = sqrt(tot_param[2] * tot_param[2] + tot_param[5] * tot_param[5] + tot_param[10] * tot_param[10]) print sum_sigma sum_sigma2 = sqrt(par1[2] * par1[2] + par2[2] * par2[2] + par3[2] * par3[2]) print "Verif = ", sum_sigma2 uncertainty = TLatex() uncertainty.DrawLatex(0, 0, "#sigma = {}".format(sum_sigma)) # write into the output file and close the file0 outFileName = "{}.root".format(outdir) outFile = TFile(outFileName, "UPDATE") raw_input("hit a key to exit") canvas_fit.Write("", TObject.kOverwrite) outFile.Write() outFile.Close()
def do_plot(categories): #this sets how tall the canvas is N_cats = len(plot_categories.keys()) #sets the number of divisions on the plot N_cuts = max(len(cuts) for cuts in plot_categories.itervalues()) canv = TCanvas('theorycomp','',500,500+200*N_cats) main_pad_ylow = 1-(500.0/(500+200*N_cats)) rat_pad_height = main_pad_ylow/N_cats canv.cd() max_cs = get_max_cs(categories) min_cs = get_min_cs(categories) scaffold = TH1F('scaf','',N_cuts,0,N_cuts) scaffold.GetYaxis().SetLimits(10*max_cs,min_cs/10.0) scaffold.GetYaxis().SetRangeUser(min_cs/10.0,10*max_cs) scaffold.SetNdivisions(100*N_cuts) scaffold.SetStats(False) scaffold.GetYaxis().SetTitle(y_axis_title) unshitify(scaffold) main_pad = TPad('main_plot','',0,main_pad_ylow,1,1,0,0,0) main_pad.SetLogy() main_pad.Draw() main_pad.cd() scaffold.Draw() cut_labels = TLatex() cut_labels.SetNDC() plot_start = 0.15 column_width = (0.945 - plot_start)/N_cuts cut_labels.SetTextSize(0.04) cut_labels.DrawLatex(0.15,0.96, "CMS %i, #sqrt{s} = %s"%(year,sqrts)) cut_labels.DrawLatex(0.18,0.86,luminosity) labels_drawn = 0 ratio_pads = [] cat_meass = [] cat_preds = [] cat_meas_rats = [] cat_pred_rats = [] legend = TLegend(0.5,0.65,0.93,0.93) legend.SetFillColor(0) legend.SetLineColor(0) legend.SetBorderSize(1) for j, (cat, cuts) in enumerate(plot_categories.iteritems()): canv.cd() ratio_pads.append(TPad(cat,'', 0,rat_pad_height*j+0.075, 1,rat_pad_height*(j+1)+rat_pad_height/4, 0,0,0)) ratio_pads[-1].Draw() ratio_pads[-1].cd() rat_scaf = scaffold.DrawCopy() rat_scaf.GetYaxis().SetLimits(-1,3) rat_scaf.GetYaxis().SetRangeUser(0,2) rat_scaf.GetYaxis().SetNdivisions(105) rat_scaf.GetYaxis().SetTitle("#frac{Data}{%s}"%(prediction_name)) rat_scaf.GetYaxis().SetTitleOffset(0.6) rat_scaf.GetYaxis().SetTitleSize(0.10) main_pad.cd() print j,cat cat_meass.append([]) cat_preds.append(TGraphErrors()) cat_meas_rats.append([]) cat_pred_rats.append(TGraphErrors()) cat_preds[-1].SetName("%s (%s)"%(prediction_name,cat)) added_channels = False for i,cut in enumerate(cuts): cut_name = cut.keys()[0] if len(cuts) == N_cuts and labels_drawn != len(cuts): canv.cd() cut_labels.DrawLatex(plot_start+column_width*(i+0.35), 0.05, cut_name) labels_drawn+=1 main_pad.cd() print '\t%i : %s'%(i,cut_name) realkeys = list(cut[cut_name].keys()) realkeys.remove('PREDICTION') nchan = len(realkeys) divsize = 1.0/(nchan) if not added_channels: cat_meass[-1] += [TGraphErrors() for l in range(nchan)] cat_meas_rats[-1] += [TGraphErrors() for l in range(nchan)] print cat_meass[-1] added_channels = True #graph entries for prediction pcs, perr = cut[cut_name]['PREDICTION'] cat_preds[-1].SetPoint(i,i+0.5,pcs) cat_preds[-1].SetPointError(i,0.5,perr) cat_pred_rats[-1].SetPoint(i,i+0.5,1.0) cat_pred_rats[-1].SetPointError(i,0.5,perr/pcs) #graph entries for data measurement for k, key in enumerate(realkeys): gidx = i print cut[cut_name][key] cs,stat,syst = cut[cut_name][key] err = hypot(stat,syst) cat_meass[-1][k].SetName("%s (%s)"%(key,cat)) cat_meass[-1][k].SetPoint(gidx, i + (k+0.5)*divsize, cs) cat_meass[-1][k].SetPointError(gidx, 0, err) cat_meas_rats[-1][k].SetPoint(gidx, i + (k+0.5)*divsize, cs/pcs) cat_meas_rats[-1][k].SetPointError(gidx, 0, err/pcs) main_pad.cd() cat_preds[-1].SetFillColor(fill_colors[j]-3) cat_preds[-1].Draw('2') legend.AddEntry(cat_preds[-1],cat_preds[-1].GetName(),'f') for i,gr in enumerate(cat_meass[-1]): gr.SetMarkerStyle(20+4*j+i) gr.Draw('pe1') legend.AddEntry(gr,gr.GetName(),'pl') ratio_pads[-1].cd() cat_pred_rats[-1].SetFillColor(fill_colors[j]-3) cat_pred_rats[-1].Draw('2') for i,gr in enumerate(cat_meas_rats[-1]): gr.SetMarkerStyle(20+4*j+i) gr.Draw('pe1') main_pad.cd() legend.Draw() canv.cd() cut_labels.DrawLatex(0.80,0.015,'E_{T}^{#gamma} (GeV)') canv.Print('vgamma_theory_comparison.pdf') canv.Print('vgamma_theory_comparison.eps') canv.Print('vgamma_theory_comparison.png')
def make_comparison_plot(outdir, var, groupname1, groupname2, category, weight = "PU_weight*MC_weight*bTagSF_weight*leptonSF_weight*triggerSF_weight*FR_weight", dataset = "ttH"): var_name = var[0] n_bins = var[3] range_low = var[4] range_high = var[5] histos = [] plot_name = "p" #segfault when using different names for each #"%s_%s_%s_%s_%s_vs_%s" % (outdir, var_name, dataset, category, groupname1, groupname2) name1 = "plot_%s_%s" % (groupname1, plot_name) plot1 = single_plot("%s/%s" % (groups[groupname1]["inputPath"], groups[groupname1]["inputFiles"][dataset]), name1, "%s_%s" % (groups[groupname1]["treePrefix"], category), var_name, weight, n_bins, range_low, range_high) name2 = "plot_%s_%s" % (groupname2, plot_name) plot2 = single_plot("%s/%s" % (groups[groupname2]["inputPath"], groups[groupname2]["inputFiles"][dataset]), name2, "%s_%s" % (groups[groupname2]["treePrefix"], category), var_name, weight, n_bins, range_low, range_high) histos.append(plot1) histos.append(plot2) leg_entry = [] leg_entry.append("%s:\t N=%d, mean=%.2f, RMS=%.2f" % (groupname1, plot1.GetEntries(), plot1.GetMean(), plot1.GetRMS())) leg_entry.append("%s:\t N=%d, mean=%.2f, RMS=%.2f" % (groupname2, plot2.GetEntries(), plot2.GetMean(), plot2.GetRMS())) leg=TLegend(0.45,0.74,0.85,0.89) leg.SetHeader(get_header(category)); leg.SetBorderSize(0) leg.SetTextSize(0.04) leg.SetFillColor(0) for i in range(len(histos)): normalize_histogram(histos[i]) leg.AddEntry(histos[i], leg_entry[i]) histos[0].SetLineColor(ROOT.kOrange-2) histos[0].SetFillColor(ROOT.kOrange-2) histos[0].SetStats(0) histos[0].SetTitle("") histos[1].SetLineColor(1) histos[1].SetLineWidth(2) c=TCanvas("c_%s" % plot_name,"c_%s" % plot_name, 800, 600) pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetLeftMargin(0.15) pad1.SetBottomMargin(0) # Upper and lower plot are joined pad1.Draw() # Draw the upper pad: pad1 pad1.cd() # pad1 becomes the current pad max_val = 0.1 min_val = 0 for i in range(len(histos)): max_val = max(histos[i].GetMaximum(), max_val) min_val = min(histos[i].GetMinimum(), min_val) for i in range(len(histos)): histos[i].SetMaximum(1.4*max_val) histos[i].SetMinimum(1.4*min_val) histos[i].GetXaxis().SetTitle(var_name) histos[i].GetYaxis().SetTitle("a.u.") histos[i].GetYaxis().SetTitleOffset(1.7) #histos[i].GetYaxis().SetTickLength(0) #histos[i].GetYaxis().SetLabelOffset(999) texl = TLatex(histos[0].GetBinLowEdge(1), 1.01*1.4*max_val, "CMS Preliminary, Simulation ttH #sqrt{s}=13 TeV") texl.SetTextSize(0.04) texl.Draw("same") histos[0].Draw("hist") histos[1].Draw("same") leg.Draw("same") texl.Draw("same") histos[0].GetYaxis().SetLabelSize(0.) axis = TGaxis(range_low, min_val, range_low, max_val, min_val, max_val, 510, "") axis.SetLabelFont(43) #Absolute font size in pixel (precision 3) axis.SetLabelSize(15) axis.Draw() # lower plot will be in pad c.cd() # Go back to the main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetLeftMargin(0.15) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.35) pad2.Draw() pad2.cd() h_ratio = make_ratio_histogram("h_ratio", histos[1], histos[0]) """ h_ratio = h[1].Clone("h_ratio") """ h_ratio.SetTitle("") h_ratio.Draw() #Draw the ratio plot # Y axis histo_emul plot settings histos[0].GetYaxis().SetTitleSize(20) histos[0].GetYaxis().SetTitleFont(43) histos[0].GetYaxis().SetTitleOffset(1.5) # Ratio plot (h_ratio) settings #h_ratio.SetTitle("") # Remove the ratio title h_ratio.GetYaxis().SetLabelSize(0.) axis2 = TGaxis( range_low, 0.01, range_low, 1.99, 0.01, 1.99, 505,"") axis2.SetLabelFont(43) # Absolute font size in pixel (precision 3) axis2.SetLabelSize(15) axis2.Draw() # Y axis ratio plot settings h_ratio.GetYaxis().SetTitle("%s/%s" % (groupname2, groupname1)) h_ratio.GetYaxis().SetNdivisions(505) h_ratio.GetYaxis().SetTitleSize(20) h_ratio.GetYaxis().SetTitleFont(43) h_ratio.GetYaxis().SetTitleOffset(1.5) #h_ratio.GetYaxis().SetLabelFont(43) # Absolute font size in pixel (precision 3) #h_ratio.GetYaxis().SetLabelSize(15) # X axis ratio plot settings h_ratio.GetXaxis().SetTitleSize(20) h_ratio.GetXaxis().SetTitleFont(43) h_ratio.GetXaxis().SetTitleOffset(4.) h_ratio.GetXaxis().SetLabelFont(43) # Absolute font size in pixel (precision 3) h_ratio.GetXaxis().SetLabelSize(15) line = TLine(range_low, 1., range_high,1.) line.Draw("same") plot_file_name="%s" % (var_name) dirname = ("%s_vs_%s/%s/%s" % (groupname1, groupname2, category, outdir)).replace(" ", "_") for file_format in ["png", "pdf"]: mkdir_p("plots_test/%s/%s" % (dirname, file_format)) c.SaveAs("plots_test/%s/%s/%s.%s" % (dirname, file_format, plot_file_name, file_format))
legend4.Draw("same") #legend2=TLegend(0.17,0.8,0.5,0.85,str(minpt)+" < p_{T} < "+str(maxpt)+" GeV") legend2 = TLegend(0.17, 0.8, 0.5, 0.85, "p_{T} > " + str(minpt) + " GeV, |#eta|<2.4") legend2.SetTextSize(0.03) legend2.SetFillStyle(0) legend2.Draw("same") legend2a = TLegend(0.17, 0.75, 0.5, 0.8, "massdrop < 0.4") legend2a.SetTextSize(0.03) legend2a.SetFillStyle(0) #legend2a.Draw("same") banner = TLatex( 0.27, 0.93, " CMS L = 2.3 fb^{-1} at #sqrt{s} = 13 TeV, dijets") banner.SetNDC() banner.SetTextSize(0.04) banner.Draw() legend3 = TLegend( 0.17, 0.7, 0.5, 0.75, str(cuts[max(0, cuts.index(cut) - 1)]) + "<#tau_{2}/#tau_{1}<" + str(cut)) legend3.SetTextSize(0.03) legend3.SetFillStyle(0) #legend3.Draw("same") legend3 = TLegend(
# Setup basic drawer gROOT.LoadMacro("tdrstyle.C") gROOT.ProcessLine("setTDRStyle();") #gROOT.SetBatch(True) gStyle.SetPadGridX(True) gStyle.SetPadGridY(True) #gStyle.SetPadRightMargin(0.05) #gStyle.SetTitleOffset(0.9, "Y") #gStyle.SetTitleOffset(1.2, "Y") gROOT.ForceStyle() tline = TLine() tline.SetLineColor(920 + 2) # kGray+2 tline.SetLineStyle(2) tlatexCMS1 = TLatex() tlatexCMS1.SetNDC() tlatexCMS1.SetTextFont(61) tlatexCMS1.SetTextSize(0.75 * 0.05) tlatexCMS2 = TLatex() tlatexCMS2.SetNDC() tlatexCMS2.SetTextFont(52) tlatexCMS2.SetTextSize(0.60 * 0.05) tlatexCMS3 = TLatex() tlatexCMS3.SetNDC() tlatexCMS3.SetTextFont(42) tlatexCMS3.SetTextSize(0.60 * 0.05) tlatexCMS3.SetTextAlign(11)
def main(): gStyle.SetOptStat(0) zplist = [600, 600, 1200, 1200, 2000, 2000] a0list = [300, 400, 300, 500, 300, 600] c1 = TCanvas('c1', 'c1', 3) gPad.SetTickx() gPad.SetTicky() c1.SetLeftMargin(0.12) h_frame = TH1F('frame', '', 60, 0, 1200) h_frame.SetXTitle('P^{miss}_{T} (GeV)') h_frame.SetYTitle('Arbitrary units') h_frame.SetMaximum(0.3) h_higgsPt = TH1F('h_higgsPt', 'h_higgsPt', 60, 0, 1200) h_higgsPtList = [] rootfilelist = [] for i in range(6): fName = 'rootFile/higgsPt_MZp' + str(zplist[i]) + '_MA0' + str( a0list[i]) + '.root' rootfile = TFile(fName) rootfilelist.append(rootfile) colorList = [61, 95, 65, 91, 69, 87] for i in range(6): hist = rootfilelist[i].Get('h_higgsPt') hist.SetName('h_higgsPt_MZp' + str(zplist[i]) + '_MA0' + str(a0list[i])) h_higgsPtList.append(hist) h_higgsPtList[i].SetLineWidth(2) h_higgsPtList[i].SetLineColor(colorList[i]) info_bar = TLatex(0, 0.305, 'CMS') info_bar_3 = TLatex(700, 0.15, '#font[42]{tan#beta=1.0}') info_bar_2 = TLatex(1200, 0.305, '35.9 fb^{-1} (13 TeV)') info_bar.SetTextSize(0.03) info_bar_2.SetTextSize(0.03) info_bar_3.SetTextSize(0.04) info_bar_2.SetTextAlign(31) leg = TLegend(0.32, 0.57, 0.87, 0.87) leg.SetBorderSize(0) for j in range(3): i = 2 * j text = 'M_{Z\'} = ' + str(zplist[i]) + ' GeV, M_{A} = ' + str( a0list[i]) + ' GeV' leg.AddEntry(h_higgsPtList[i], text) for j in range(3): i = 2 * j + 1 text = 'M_{Z\'} = ' + str(zplist[i]) + ' GeV, M_{A} = ' + str( a0list[i]) + ' GeV' leg.AddEntry(h_higgsPtList[i], text) h_frame.Draw('hist') for i in range(6): h_higgsPtList[i].DrawNormalized('histsame') leg.Draw() info_bar.Draw() info_bar_2.Draw() info_bar_3.Draw() c1.Print('Zp2HDM_higgsPt_new.pdf') '''
line6 = TLine(31, 1.55, 42, 1.55) line7 = TLine(42, 1.55, 42, 2) line8 = TLine(42, 2, 60, 2) line9 = TLine(60, 2, 90, 2) line10 = TLine(90, 2, 90, 0) line11 = TLine(90, 0, 20, 0) lineVector = [ line1, line2, line3, line4, line5, line6, line7, line8, line9, line10, line11 ] for line in lineVector: line.SetLineColor(ROOT.kBlack) line.SetLineWidth(3) line.Draw() leg = TLegend(.61, .55, .65, .59) leg.SetFillStyle(0) leg.SetLineWidth(4) leg.Draw() text = TLatex(.67, .55, "MIPP Coverage") text.SetTextColor(ROOT.kBlack) text.SetNDC() text.SetTextSize(1.4 / 30.) text.SetTextAlign(11) #text.DrawLatex(.48, .55, "#Square"); text.Draw() raw_input("Please press enter to exit.")
def SAME2VsLumi(g1, g2,title, ptype, dataPeriod): canvas = makeCMSCanvas(str(random.random()),"canvas",900,700) canvas.cd() graph1=copy.deepcopy(g1) graph2=copy.deepcopy(g2) graph1.SetMarkerColor(kBlue)#electrons graph2.SetMarkerColor(kRed)#muons multigraph = TMultiGraph() multigraph.Add(graph1,"AP") multigraph.Add(graph2,"AP") multigraph.Draw("AP") TGaxis.SetMaxDigits(2) TGaxis.SetExponentOffset(-0.06, 0.02, "y") multigraph.GetXaxis().SetTitle("L [fb^{-1}]") multigraph.GetYaxis().SetTitleOffset(1.4) if(ptype == "ISO"): multigraph.GetYaxis().SetTitle("Isolation") gPad.Modified() multigraph.SetMinimum(0.5*gPad.GetUymin()) multigraph.SetMaximum(1.5*gPad.GetUymax()) elif(ptype == "SIP"): multigraph.GetYaxis().SetTitle("SIP") multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(),1.)) multigraph.SetMaximum(max(multigraph.GetHistogram().GetMinimum(),2.2)) min(multigraph.GetHistogram().GetMinimum(),1.) printLumiPrelOut(canvas) # Draw legend legend = TLegend(0.93,0.84,0.99,0.93) legend.AddEntry(graph1,"e^{+}e^{-}","P") legend.AddEntry(graph2,"#mu^{+}#mu^{-}","P") legend.SetFillColor(kWhite) legend.SetLineColor(kBlack) legend.SetTextFont(43) legend.SetTextSize(20) legend.Draw() canvas.Update() # Draw letters for data-taking periods if(dataPeriod == "data2017"): textLetters = TLatex() textLetters.SetTextColor(kGray+1) textLetters.SetTextSize(0.03) if(ptype == "ISO"): textLetters.DrawLatex(2., 0.8*gPad.GetUymax(),"B") textLetters.DrawLatex(9.5, 0.8*gPad.GetUymax(),"C") textLetters.DrawLatex(16., 0.8*gPad.GetUymax(),"D") textLetters.DrawLatex(23., 0.8*gPad.GetUymax(),"E") textLetters.DrawLatex(36., 0.8*gPad.GetUymax(),"F") elif(ptype == "SIP"): textLetters.DrawLatex(2., 1.5,"B") textLetters.DrawLatex(9.5, 1.5,"C") textLetters.DrawLatex(16., 1.5,"D") textLetters.DrawLatex(23., 1.5,"E") textLetters.DrawLatex(36., 1.5,"F") if(dataPeriod == "data2018"): textLetters = TLatex() textLetters.SetTextColor(kGray+1) textLetters.SetTextSize(0.03) if(ptype == "ISO"): textLetters.DrawLatex(6., 0.8*gPad.GetUymax(), "A") textLetters.DrawLatex(16., 0.8*gPad.GetUymax(), "B") textLetters.DrawLatex(23., 0.8*gPad.GetUymax(), "C") textLetters.DrawLatex(43., 0.8*gPad.GetUymax(), "D") elif(ptype == "SIP"): textLetters.DrawLatex(6., 1.5, "A") textLetters.DrawLatex(16., 1.5, "B") textLetters.DrawLatex(23., 1.5, "C") textLetters.DrawLatex(43., 1.5, "D") # **** if(dataPeriod == "data2018"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineA = TLine(13.48, down, 13.48, up) # Run2018A up to 13.48 fb-1 lineA.SetLineColor(kBlack) lineA.SetLineStyle(2) lineA.Draw() lineB = TLine(20.265, down, 20.265, up) # Run2018B up to 20.265 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(26.877, down, 26.877, up) # Run2018C up to 26.877 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() # **** if(dataPeriod == "data2017"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineB = TLine(4.793, down, 4.793, up) # Run2017B up to 4.793 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(14.549, down, 14.549, up) # Run2017C up to 14.549 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() lineD = TLine(18.868, down, 18.868, up) # Run2017D up to 18.868 fb-1 lineD.SetLineColor(kBlack) lineD.SetLineStyle(2) lineD.Draw() lineE = TLine(28.293, down, 28.293, up) # Run2017E up to 28.293 fb-1 lineE.SetLineColor(kBlack) lineE.SetLineStyle(2) lineE.Draw() # **** if(dataPeriod == "data2016"): # draw vertical lines that divide different data taking periods down = gPad.GetUymin() up = gPad.GetUymax() lineB = TLine(5.789, down, 5.789, up) # Run2016B up to 5.789 fb-1 lineB.SetLineColor(kBlack) lineB.SetLineStyle(2) lineB.Draw() lineC = TLine(8.366, down, 8.366, up) # Run2016C up to 8.366 fb-1 lineC.SetLineColor(kBlack) lineC.SetLineStyle(2) lineC.Draw() lineD = TLine(12.616, down, 12.616, up) # Run2016D up to 12.616 fb-1 lineD.SetLineColor(kBlack) lineD.SetLineStyle(2) lineD.Draw() lineE = TLine(16.624, down, 16.624, up) # Run2016E up to 16.624 fb-1 lineE.SetLineColor(kBlack) lineE.SetLineStyle(2) lineE.Draw() lineF = TLine(19.725, down, 19.725, up) # Run2016F up to 19.725 fb-1 lineF.SetLineColor(kBlack) lineF.SetLineStyle(2) lineF.Draw() lineG = TLine(27.268, down, 27.268, up) # Run2016G up to 27.268 fb-1 lineG.SetLineColor(kBlack) lineG.SetLineStyle(2) lineG.Draw() # **** canvas.SaveAs(title + ".root") canvas.SaveAs(title + ".pdf") canvas.SaveAs(title + ".png") return;
def dijet(category): channel = 'bb' stype = channel isSB = True # relict from using Alberto's more complex script isData = not ISMC nTupleDir = NTUPLEDIR samples = data if isData else back pd = [] for sample_name in samples: if YEAR == 'run2': pd += sample[sample_name]['files'] else: pd += [x for x in sample[sample_name]['files'] if YEAR in x] print "datasets:", pd if not os.path.exists(PLOTDIR): os.makedirs(PLOTDIR) if BIAS: print "Running in BIAS mode" order = 0 RSS = {} X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV") weight = RooRealVar("MANtag_weight", "", -1.e9, 1.e9) variables = RooArgSet(X_mass) variables.add(RooArgSet(weight)) if VARBINS: binsXmass = RooBinning(len(abins) - 1, abins) X_mass.setBinning(RooBinning(len(abins_narrow) - 1, abins_narrow)) plot_binning = RooBinning( int((X_mass.getMax() - X_mass.getMin()) / 100), X_mass.getMin(), X_mass.getMax()) else: X_mass.setBins(int((X_mass.getMax() - X_mass.getMin()) / 10)) binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin()) / 100), X_mass.getMin(), X_mass.getMax()) plot_binning = binsXmass baseCut = "" print stype, "|", baseCut print " - Reading from Tree" treeBkg = TChain("tree") for ss in pd: if os.path.exists(nTupleDir + ss + "_" + BTAGGING + ".root"): treeBkg.Add(nTupleDir + ss + "_" + BTAGGING + ".root") else: print "found no file for sample:", ss setData = RooDataSet("setData", "Data (QCD+TTbar MC)", variables, RooFit.Cut(baseCut), RooFit.WeightVar(weight), RooFit.Import(treeBkg)) nevents = setData.sumEntries() dataMin, dataMax = array('d', [0.]), array('d', [0.]) setData.getRange(X_mass, dataMin, dataMax) xmin, xmax = dataMin[0], dataMax[0] lastBin = X_mass.getMax() if VARBINS: for b in narrow_bins: if b > xmax: lastBin = b break print "Imported", ( "data" if isData else "MC" ), "RooDataSet with", nevents, "events between [%.1f, %.1f]" % (xmin, xmax) #xmax = xmax+binsXmass.averageBinWidth() # start form next bin # 1 parameter print "fitting 1 parameter model" p1_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p1_1", "p1", 7.0, 0., 2000.) modelBkg1 = RooGenericPdf("Bkg1", "Bkg. fit (2 par.)", "1./pow(@0/13000, @1)", RooArgList(X_mass, p1_1)) normzBkg1 = RooRealVar( modelBkg1.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) #range dependent of actual number of events! modelExt1 = RooExtendPdf(modelBkg1.GetName() + "_ext", modelBkg1.GetTitle(), modelBkg1, normzBkg1) fitRes1 = modelExt1.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes1.Print() RSS[1] = drawFit("Bkg1", category, X_mass, modelBkg1, setData, binsXmass, [fitRes1], normzBkg1.getVal()) # 2 parameters print "fitting 2 parameter model" p2_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_1", "p1", 0., -100., 1000.) p2_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_2", "p2", p1_1.getVal(), -100., 600.) modelBkg2 = RooGenericPdf("Bkg2", "Bkg. fit (3 par.)", "pow(1-@0/13000, @1) / pow(@0/13000, @2)", RooArgList(X_mass, p2_1, p2_2)) normzBkg2 = RooRealVar(modelBkg2.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt2 = RooExtendPdf(modelBkg2.GetName() + "_ext", modelBkg2.GetTitle(), modelBkg2, normzBkg2) fitRes2 = modelExt2.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes2.Print() RSS[2] = drawFit("Bkg2", category, X_mass, modelBkg2, setData, binsXmass, [fitRes2], normzBkg2.getVal()) # 3 parameters print "fitting 3 parameter model" p3_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_1", "p1", p2_1.getVal(), -2000., 2000.) p3_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_2", "p2", p2_2.getVal(), -400., 2000.) p3_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_3", "p3", -2.5, -500., 500.) modelBkg3 = RooGenericPdf( "Bkg3", "Bkg. fit (4 par.)", "pow(1-@0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000))", RooArgList(X_mass, p3_1, p3_2, p3_3)) normzBkg3 = RooRealVar(modelBkg3.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt3 = RooExtendPdf(modelBkg3.GetName() + "_ext", modelBkg3.GetTitle(), modelBkg3, normzBkg3) fitRes3 = modelExt3.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes3.Print() RSS[3] = drawFit("Bkg3", category, X_mass, modelBkg3, setData, binsXmass, [fitRes3], normzBkg3.getVal()) # 4 parameters print "fitting 4 parameter model" p4_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_1", "p1", p3_1.getVal(), -2000., 2000.) p4_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_2", "p2", p3_2.getVal(), -2000., 2000.) p4_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_3", "p3", p3_3.getVal(), -50., 50.) p4_4 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_4", "p4", 0.1, -50., 50.) modelBkg4 = RooGenericPdf( "Bkg4", "Bkg. fit (5 par.)", "pow(1 - @0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000)+@4*pow(log(@0/13000), 2))", RooArgList(X_mass, p4_1, p4_2, p4_3, p4_4)) normzBkg4 = RooRealVar(modelBkg4.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt4 = RooExtendPdf(modelBkg4.GetName() + "_ext", modelBkg4.GetTitle(), modelBkg4, normzBkg4) fitRes4 = modelExt4.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes4.Print() RSS[4] = drawFit("Bkg4", category, X_mass, modelBkg4, setData, binsXmass, [fitRes4], normzBkg4.getVal()) # Normalization parameters are should be set constant, but shape ones should not # if BIAS: # p1_1.setConstant(True) # p2_1.setConstant(True) # p2_2.setConstant(True) # p3_1.setConstant(True) # p3_2.setConstant(True) # p3_3.setConstant(True) # p4_1.setConstant(True) # p4_2.setConstant(True) # p4_3.setConstant(True) # p4_4.setConstant(True) normzBkg1.setConstant(True) normzBkg2.setConstant(True) normzBkg3.setConstant(True) normzBkg4.setConstant(True) #*******************************************************# # # # Fisher # # # #*******************************************************# # Fisher test with open(PLOTDIR + "/Fisher_" + category + ".tex", 'w') as fout: fout.write(r"\begin{tabular}{c|c|c|c|c}") fout.write("\n") fout.write(r"function & $\chi^2$ & RSS & ndof & F-test \\") fout.write("\n") fout.write("\hline") fout.write("\n") CL_high = False for o1 in range(1, 5): o2 = min(o1 + 1, 5) fout.write("%d par & %.2f & %.2f & %d & " % (o1 + 1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"] - RSS[o1]["npar"])) if o2 > len(RSS): fout.write(r"\\") fout.write("\n") continue #order==0 and CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1 + 1., o2 + 1., RSS[o1]["nbins"]) fout.write("CL=%.3f " % (CL)) if CL > 0.10: # The function with less parameters is enough if not CL_high: order = o1 #fout.write( "%d par are sufficient " % (o1+1)) CL_high = True else: #fout.write( "%d par are needed " % (o2+1)) if not CL_high: order = o2 fout.write(r"\\") fout.write("\n") fout.write("\hline") fout.write("\n") fout.write(r"\end{tabular}") print "saved F-test table as", PLOTDIR + "/Fisher_" + category + ".tex" #print "-"*25 #print "function & $\\chi^2$ & RSS & ndof & F-test & result \\\\" #print "\\multicolumn{6}{c}{", "Zprime_to_bb", "} \\\\" #print "\\hline" #CL_high = False #for o1 in range(1, 5): # o2 = min(o1 + 1, 5) # print "%d par & %.2f & %.2f & %d & " % (o1+1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"]-RSS[o1]["npar"]), # if o2 > len(RSS): # print "\\\\" # continue #order==0 and # CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1+1., o2+1., RSS[o1]["nbins"]) # print "%d par vs %d par CL=%f & " % (o1+1, o2+1, CL), # if CL > 0.10: # The function with less parameters is enough # if not CL_high: # order = o1 # print "%d par are sufficient" % (o1+1), # CL_high=True # else: # print "%d par are needed" % (o2+1), # if not CL_high: # order = o2 # print "\\\\" #print "\\hline" #print "-"*25 #print "@ Order is", order, "("+category+")" #order = min(3, order) #order = 2 if order == 1: modelBkg = modelBkg1 #.Clone("Bkg") modelAlt = modelBkg2 #.Clone("BkgAlt") normzBkg = normzBkg1 #.Clone("Bkg_norm") fitRes = fitRes1 elif order == 2: modelBkg = modelBkg2 #.Clone("Bkg") modelAlt = modelBkg3 #.Clone("BkgAlt") normzBkg = normzBkg2 #.Clone("Bkg_norm") fitRes = fitRes2 elif order == 3: modelBkg = modelBkg3 #.Clone("Bkg") modelAlt = modelBkg4 #.Clone("BkgAlt") normzBkg = normzBkg3 #.Clone("Bkg_norm") fitRes = fitRes3 elif order == 4: modelBkg = modelBkg4 #.Clone("Bkg") modelAlt = modelBkg3 #.Clone("BkgAlt") normzBkg = normzBkg4 #.Clone("Bkg_norm") fitRes = fitRes4 else: print "Functions with", order + 1, "or more parameters are needed to fit the background" exit() modelBkg.SetName("Bkg_" + YEAR + "_" + category) modelAlt.SetName("Alt_" + YEAR + "_" + category) normzBkg.SetName("Bkg_" + YEAR + "_" + category + "_norm") print "-" * 25 # Generate pseudo data setToys = RooDataSet() setToys.SetName("data_toys") setToys.SetTitle("Data (toys)") if not isData: print " - Generating", nevents, "events for toy data" setToys = modelBkg.generate(RooArgSet(X_mass), nevents) #setToys = modelAlt.generate(RooArgSet(X_mass), nevents) print "toy data generated" if VERBOSE: raw_input("Press Enter to continue...") #*******************************************************# # # # Plot # # # #*******************************************************# print "starting to plot" c = TCanvas("c_" + category, category, 800, 800) c.Divide(1, 2) setTopPad(c.GetPad(1), RATIO) setBotPad(c.GetPad(2), RATIO) c.cd(1) frame = X_mass.frame() setPadStyle(frame, 1.25, True) if VARBINS: frame.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin) signal = getSignal( category, stype, 2000) #replacing Alberto's getSignal by own dummy function graphData = setData.plotOn(frame, RooFit.Binning(plot_binning), RooFit.Scaling(False), RooFit.Invisible()) modelBkg.plotOn(frame, RooFit.VisualizeError(fitRes, 1, False), RooFit.LineColor(602), RooFit.FillColor(590), RooFit.FillStyle(1001), RooFit.DrawOption("FL"), RooFit.Name("1sigma")) modelBkg.plotOn(frame, RooFit.LineColor(602), RooFit.FillColor(590), RooFit.FillStyle(1001), RooFit.DrawOption("L"), RooFit.Name(modelBkg.GetName())) modelAlt.plotOn(frame, RooFit.LineStyle(7), RooFit.LineColor(613), RooFit.FillColor(609), RooFit.FillStyle(1001), RooFit.DrawOption("L"), RooFit.Name(modelAlt.GetName())) if not isSB and signal[0] is not None: # FIXME remove /(2./3.) signal[0].plotOn( frame, RooFit.Normalization(signal[1] * signal[2], RooAbsReal.NumEvent), RooFit.LineStyle(3), RooFit.LineWidth(6), RooFit.LineColor(629), RooFit.DrawOption("L"), RooFit.Name("Signal")) graphData = setData.plotOn( frame, RooFit.Binning(plot_binning), RooFit.Scaling(False), RooFit.XErrorSize(0 if not VARBINS else 1), RooFit.DataError(RooAbsData.Poisson if isData else RooAbsData.SumW2), RooFit.DrawOption("PE0"), RooFit.Name(setData.GetName())) fixData(graphData.getHist(), True, True, not isData) pulls = frame.pullHist(setData.GetName(), modelBkg.GetName(), True) chi = frame.chiSquare(setData.GetName(), modelBkg.GetName(), True) #setToys.plotOn(frame, RooFit.DataError(RooAbsData.Poisson), RooFit.DrawOption("PE0"), RooFit.MarkerColor(2)) frame.GetYaxis().SetTitle("Events / ( 100 GeV )") frame.GetYaxis().SetTitleOffset(1.05) frame.Draw() #print "frame drawn" # Get Chi2 # chi2[1] = frame.chiSquare(modelBkg1.GetName(), setData.GetName()) # chi2[2] = frame.chiSquare(modelBkg2.GetName(), setData.GetName()) # chi2[3] = frame.chiSquare(modelBkg3.GetName(), setData.GetName()) # chi2[4] = frame.chiSquare(modelBkg4.GetName(), setData.GetName()) frame.SetMaximum(frame.GetMaximum() * 10) frame.SetMinimum(max(frame.GetMinimum(), 1.e-1)) c.GetPad(1).SetLogy() drawAnalysis(category) drawRegion(category, True) #drawCMS(LUMI, "Simulation Preliminary") drawCMS(LUMI, "Work in Progress", suppressCMS=True) leg = TLegend(0.575, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.AddEntry(setData.GetName(), setData.GetTitle() + " (%d events)" % nevents, "PEL") leg.AddEntry(modelBkg.GetName(), modelBkg.GetTitle(), "FL") #.SetTextColor(629) leg.AddEntry(modelAlt.GetName(), modelAlt.GetTitle(), "L") if not isSB and signal[0] is not None: leg.AddEntry("Signal", signal[0].GetTitle(), "L") leg.SetY1(0.9 - leg.GetNRows() * 0.05) leg.Draw() latex = TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.SetTextFont(42) if not isSB: latex.DrawLatex(leg.GetX1() * 1.16, leg.GetY1() - 0.04, "HVT model B (g_{V}=3)") # latex.DrawLatex(0.67, leg.GetY1()-0.045, "#sigma_{X} = 1.0 pb") c.cd(2) frame_res = X_mass.frame() setPadStyle(frame_res, 1.25) frame_res.addPlotable(pulls, "P") setBotStyle(frame_res, RATIO, False) if VARBINS: frame_res.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin) frame_res.GetYaxis().SetRangeUser(-5, 5) frame_res.GetYaxis().SetTitle("pulls(#sigma)") frame_res.GetYaxis().SetTitleOffset(0.3) frame_res.Draw() fixData(pulls, False, True, False) drawChi2(RSS[order]["chi2"], RSS[order]["nbins"] - (order + 1), True) line = drawLine(X_mass.getMin(), 0, lastBin, 0) if VARBINS: c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf") c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png") else: c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf") c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png") #*******************************************************# # # # Generate workspace # # # #*******************************************************# if BIAS: gSystem.Load("libHiggsAnalysisCombinedLimit.so") from ROOT import RooMultiPdf cat = RooCategory("pdf_index", "Index of Pdf which is active") pdfs = RooArgList(modelBkg, modelAlt) roomultipdf = RooMultiPdf("roomultipdf", "All Pdfs", cat, pdfs) normulti = RooRealVar("roomultipdf_norm", "Number of background events", nevents, 0., 1.e6) normzBkg.setConstant( False ) ## newly put here to ensure it's freely floating in the combine fit # create workspace w = RooWorkspace("Zprime_" + YEAR, "workspace") # Dataset if isData: getattr(w, "import")(setData, RooFit.Rename("data_obs")) else: getattr(w, "import")(setToys, RooFit.Rename("data_obs")) #getattr(w, "import")(setData, RooFit.Rename("data_obs")) if BIAS: getattr(w, "import")(cat, RooFit.Rename(cat.GetName())) getattr(w, "import")(normulti, RooFit.Rename(normulti.GetName())) getattr(w, "import")(roomultipdf, RooFit.Rename(roomultipdf.GetName())) getattr(w, "import")(modelBkg, RooFit.Rename(modelBkg.GetName())) getattr(w, "import")(modelAlt, RooFit.Rename(modelAlt.GetName())) getattr(w, "import")(normzBkg, RooFit.Rename(normzBkg.GetName())) w.writeToFile(WORKDIR + "%s_%s.root" % (DATA_TYPE + "_" + YEAR, category), True) print "Workspace", WORKDIR + "%s_%s.root" % ( DATA_TYPE + "_" + YEAR, category), "saved successfully" if VERBOSE: raw_input("Press Enter to continue...")
def createCompoundPlots(detector, plot, geometry): """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. """ setTDRStyle() theDirname = 'Images' if not checkFile_(theDirname): os.mkdir(theDirname) goodToGo, theDetectorFilename = paramsGood_(detector, plot, geometry) if not goodToGo: return hist_X0_elements = OrderedDict() # stack stackTitle = "%s;%s;%s" % (detector, plots[plot].abscissa, plots[plot].ordinate) stack_X0 = THStack("stack_X0", stackTitle) theLegend = TLegend(0.50, 0.70, 0.70, 0.90) def setRanges(h): legendSpace = 1. + 0.3 # 30% minY = h.GetYaxis().GetXmin() maxY = h.GetBinContent(h.GetMaximumBin()) * legendSpace h.GetYaxis().SetRangeUser(minY, maxY) for label, [num, color, leg] in six.iteritems(hist_label_to_num): # We don't want the sum to be added as part of the stack if label is 'SUM': continue hist_X0_elements[label] = get1DHisto_(detector, num + plots[plot].plotNumber, geometry) hist_X0_elements[label].SetFillColor(color) hist_X0_elements[label].SetLineColor(kBlack) stack_X0.Add(hist_X0_elements[label]) if hist_X0_elements[label].Integral() > 0.: theLegend.AddEntry(hist_X0_elements[label], leg, "f") # canvas canname = "MBCan_1D_%s_%s" % (detector, plot) can = TCanvas(canname, canname, 800, 800) can.Range(0, 0, 25, 25) gStyle.SetOptTitle(0) # Draw setRanges(stack_X0.GetStack().Last()) stack_X0.Draw("HIST") stack_X0.GetXaxis().SetLabelSize(0.035) stack_X0.GetYaxis().SetLabelSize(0.035) theLegend.Draw() cmsMark = TLatex() cmsMark.SetNDC() cmsMark.SetTextAngle(0) cmsMark.SetTextColor(kBlack) cmsMark.SetTextFont(61) cmsMark.SetTextSize(5e-2) cmsMark.SetTextAlign(11) cmsMark.DrawLatex(0.16, 0.86, "CMS") simuMark = TLatex() simuMark.SetNDC() simuMark.SetTextAngle(0) simuMark.SetTextColor(kBlack) simuMark.SetTextSize(3e-2) simuMark.SetTextAlign(11) simuMark.DrawLatex(0.16, 0.82, "#font[52]{Simulation Internal}") # Store can.Update() can.SaveAs("%s/%s_%s_%s.pdf" % (theDirname, detector, plot, geometry)) can.SaveAs("%s/%s_%s_%s.png" % (theDirname, detector, plot, geometry))
def get_text(x, y, f, s): t = TLatex(x, y, "#font[41]{{0:d} :} {1}".format(f(), s)) t.SetTextFont(f('root')) t.SetTextAlign(12) t.SetTextSize(0.048) return t
def showENC(): fname1 = '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat' tree1 = TTree() tree1.ReadFile( '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat', 'idX/i:vL/F:vH:A:D/i:R:W') tree1.ReadFile( '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan2_mod.dat' ) tree1.Show(500) p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', 50, 0.12, 0.2) tree1.Draw("D:(vH-vL)>>p1", "", "profE") ### change it to tgraph g1 = TGraphErrors() for i in range(p1.GetNbinsX() + 2): N = p1.GetBinEntries(i) if N > 0: print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent( i), p1.GetBinError(i) n = g1.GetN() g1.SetPoint(n, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i)) g1.SetPointError(n, 0, p1.GetBinError(i)) # g1.SetMarkerColor(3) # g1.SetLineColor(3) p1.Draw("axis") g1.Draw('Psame') fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))', 0.05, 0.3) fun1.SetParameter(0, 0.155) fun1.SetParameter(1, 0.005) g1.Fit(fun1) fun1a = g1.GetFunction('fun1') # p1.Fit(fun1) # fun1a = p1.GetFunction('fun1') fun1a.SetLineColor(2) # p1.Draw("Esame") v0 = fun1a.GetParameter(0) e0 = fun1a.GetParError(0) v1 = fun1a.GetParameter(1) e1 = fun1a.GetParError(1) print v0, v1 fUnit = 1000. lt = TLatex() lt.DrawLatexNDC( 0.185, 0.89, '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit)) lt.DrawLatexNDC( 0.185, 0.84, '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit)) print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1) fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)) fun2.SetLineColor(4) fun2.SetLineStyle(2) fun2.Draw('same') lg = TLegend(0.7, 0.4, 0.95, 0.5) lg.SetFillStyle(0) lg.AddEntry(p1, 'Measurement', 'p') lg.AddEntry(fun1a, 'Fit', 'l') lg.AddEntry(fun2, 'Gaus', 'l') lg.Draw() waitRootCmdX()
def write_rootgraph(vectorx, vectory, graphtitle, xtitle, ytitle, sectorscurrents, rootdirectory): """Function to perform ROOT graph""" arrayx = array('d') arrayy = array('d') for x in vectorx: arrayx.append(x) for y in vectory: arrayy.append(y) #How many graph points n = len(vectorx) MyTGraph = TGraph(n, arrayx, arrayy) MyTGraph.SetName(graphtitle) if ytitle == "i": ytitle = ytitle + " (uA)" color = 2 offset = 1. minimum = -0.5 maximum = int(np.max(vectory) + 1.5) lineup = TLine(float(np.min(vectorx)), 500, float(np.max(vectorx)), 500) lineup.SetLineColor(2) lineup.SetLineStyle(2) linedown = TLine(float(np.min(vectorx)), 500., float(np.max(vectorx)), 500.) linedown.SetLineColor(8) linedown.SetLineStyle(2) for entry in range(len(sectorscurrents)): if vectory[entry] > 0.01: latex = TLatex(MyTGraph.GetX()[entry], MyTGraph.GetY()[entry], sectorscurrents[entry]) latex.SetTextSize(0.02) MyTGraph.GetListOfFunctions().Add(latex) else: latex = TLatex(MyTGraph.GetX()[entry], MyTGraph.GetY()[entry], "") latex.SetTextSize(0.02) MyTGraph.GetListOfFunctions().Add(latex) if ytitle == "v": ytitle = ytitle + " (V)" color = 4 offset = 0.9 minimum = 400 maximum = 600 lineup = TLine(float(np.min(vectorx)), 580., float(np.max(vectorx)), 580.) lineup.SetLineColor(2) lineup.SetLineStyle(2) linedown = TLine(float(np.min(vectorx)), 530., float(np.max(vectorx)), 530.) linedown.SetLineColor(8) linedown.SetLineStyle(2) for entry in range(len(sectorscurrents)): if vectory[entry] > 569.0: latex = TLatex(MyTGraph.GetX()[entry], MyTGraph.GetY()[entry], "") else: latex = TLatex(MyTGraph.GetX()[entry], MyTGraph.GetY()[entry], sectorscurrents[entry]) latex.SetTextSize(0.02) MyTGraph.GetListOfFunctions().Add(latex) #Draw + DrawOptions Style = gStyle Style.SetPadLeftMargin(2.0) XAxis = MyTGraph.GetXaxis() #TGraphfasthescin #XAxis.SetTitleOffset(offset) XAxis.SetTitle(xtitle) MyTGraph.SetMarkerColor(color) MyTGraph.SetMarkerStyle(1) MyTGraph.SetMarkerSize(1) MyTGraph.SetLineColor(color) MyTGraph.SetTitle(graphtitle) #XAxis.SetTitle(xtitle) YAxis = MyTGraph.GetYaxis() YAxis.SetTitleOffset(offset) YAxis.SetTitle(ytitle) MyTGraph.GetHistogram().SetMinimum(minimum) MyTGraph.GetHistogram().SetMaximum(maximum) rootdirectory.WriteTObject(MyTGraph) c = TCanvas() c.SetName(graphtitle + "_canvas") MyTGraph.Draw("APL") lineup.Draw("") linedown.Draw("") rootdirectory.WriteTObject(c) #MyTGraph.Write(graphtitle) MyTGraph.Draw("APL") #gPad.SaveAs("current-"+graphtitle+".pdf") gPad.Close()
def main(options, args): from ROOT import gSystem, gROOT, gStyle gROOT.SetBatch() gSystem.Load("libRooFitCore") if options.doWebPage: from lip.Tools.rootutils import loadToolsLib, apply_modifs loadToolsLib() from ROOT import TFile, RooFit, RooArgSet, RooDataHist, RooKeysPdf, RooHistPdf, TCanvas, TLegend, TLatex, TArrow, TPaveText, RooAddPdf, RooArgList from ROOT import kWhite, kBlue, kOpenSquare if options.doWebPage: from ROOT import HtmlHelper, HtmlTag, HtmlTable, HtmlPlot rootglobestyle.setTDRStyle() gStyle.SetMarkerSize(1.5) gStyle.SetTitleYOffset(1.5) gStyle.SetPadLeftMargin(0.16) gStyle.SetPadRightMargin(0.05) gStyle.SetPadTopMargin(0.05) gStyle.SetPadBottomMargin(0.13) gStyle.SetLabelFont(42, "XYZ") gStyle.SetLabelOffset(0.007, "XYZ") gStyle.SetLabelSize(0.05, "XYZ") gStyle.SetTitleSize(0.06, "XYZ") gStyle.SetTitleXOffset(0.9) gStyle.SetTitleYOffset(1.24) gStyle.SetTitleFont(42, "XYZ") ## ## Read files ## options.outdir = "%s_m%1.0f" % (options.outdir, options.mH) if options.fp: options.outdir += "_fp" ncat = options.ncat cats = options.cats if cats is "": categories = ["_cat%d" % i for i in range(0, ncat)] else: categories = ["_cat%s" % i for i in cats.split(",")] if options.mva: clables = { "_cat0": ("MVA > 0.89", ""), "_cat1": ("0.74 #leq MVA", "MVA < 0.89"), "_cat2": ("0.545 #leq MVA", "MVA < 0.74"), "_cat3": ("0.05 #leq MVA", "MVA < 0.545"), "_cat4": ("Di-jet", "Tagged"), "_cat5": ("Di-jet", "Tagged"), "_combcat": ("All Classes", "Combined") } else: clables = { "_cat0": ("max(|#eta|<1.5", "min(R_{9})>0.94"), "_cat1": ("max(|#eta|<1.5", "min(R_{9})<0.94"), "_cat2": ("max(|#eta|>1.5", "min(R_{9})>0.94"), "_cat3": ("max(|#eta|>1.5", "min(R_{9})<0.94"), "_cat4": ("Di-jet", "Tagged"), "_cat5": ("Di-jet", "Tagged"), "_combcat": ("All Classes", "Combined") } helper = Helper() fin = TFile.Open(options.infile) helper.files.append(fin) ws = fin.Get("cms_hgg_workspace") mass = ws.var("CMS_hgg_mass") mass.SetTitle("m_{#gamma#gamma}") mass.setUnit("GeV") mass.setRange(100., 150.) mass.setBins(100, "plot") mass.setBins(5000) print ws aset = RooArgSet(mass) helper.objs.append(mass) helper.objs.append(aset) fitopt = (RooFit.Minimizer("Minuit2", ""), RooFit.Minos(False), RooFit.SumW2Error(False), RooFit.NumCPU(8)) if not options.binned and not options.refit: finpdf = TFile.Open(options.infilepdf) helper.files.append(finpdf) wspdf = finpdf.Get("wsig") else: wspdf = ws for c in categories: processes = ["ggh", "vbf", "wzh"] if options.fp: processes = ["vbf", "wzh"] ### elif clables[c][0] == "Di-jet": ### processes = [ "vbf", "ggh" ] dsname = "sig_mass_m%1.0f%s" % (options.mH, c) print dsname print ws ds = ws.data("sig_%s_mass_m%1.0f%s" % (processes[0], options.mH, c)).Clone(dsname) for proc in processes[1:]: ds.append(ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c))) helper.dsets.append(ds) if options.binned: binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname, aset, ds) pdf = RooKeysPdf("pdf_%s_%s" % (dsname, f), "pdf_%s" % dsname, mass, ds) plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds) helper.add(binned_ds, binned_ds.GetName()) else: if options.refit: if options.refitall and clables[c][0] != "Di-jet": rpdfs = [] for proc in processes: for ngaus in range(1, 4): pp = build_pdf(ws, "%s_%s" % (c, proc), ngaus, ngaus == 3) pp.fitTo( ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c)), RooFit.Strategy(0), *fitopt) rpdfs.append(pp) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*tuple(rpdfs))) else: if options.refitall and clables[c][0] == "Di-jet": for ngaus in range(1, 5): pdf = build_pdf(ws, c, ngaus, ngaus == 5) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt) else: for ngaus in range(1, 4): pdf = build_pdf(ws, c, ngaus, ngaus == 3) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt) else: pdfs = (wspdf.pdf("hggpdfrel%s_%s" % (c, p)) for p in processes) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*pdfs)) helper.add(pdf, pdf.GetName()) plot_pdf = pdf.Clone("pdf_%s" % dsname) plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot") plot_ds.add(ds) cdf = pdf.createCdf(aset) hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10., options.mH + 10.) wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10., options.mH + 10.) ### hmin, hmax, hm = get_FWHM( points ) helper.add(plot_ds, plot_ds.GetName()) helper.add(plot_pdf, plot_pdf.GetName()) helper.add((wmin, wmax), "eff_sigma%s" % c) helper.add((hmin, hmax, hm), "FWHM%s" % c) helper.add(ds.sumEntries(), "sumEntries%s" % c) # signal model integral # data integral for PAS tables data = ws.data("data_mass%s" % c) helper.add( data.sumEntries("CMS_hgg_mass>=%1.4f && CMS_hgg_mass<=%1.4f" % (options.mH - 10., options.mH + 10.)), "data_sumEntries%s" % c) del cdf del pdf dsname = "sig_mass_m%1.0f_combcat" % options.mH print dsname combined_ds = helper.dsets[0].Clone(dsname) for d in helper.dsets[1:]: combined_ds.append(d) if options.binned: binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname, aset, combined_ds) pdf = RooKeysPdf("pdf_%s" % (dsname), "pdf_%s" % dsname, mass, combined_ds) plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds) helper.add(binned_ds, binned_ds.GetName()) else: #### pdf = build_pdf(ws,"_combcat") #### pdf.fitTo(combined_ds, RooFit.Strategy(0), *fitopt ) #### plot_pdf = pdf.Clone( "pdf_%s" % dsname ) pdf = RooAddPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, RooArgList(*(helper.histos["hggpdfrel%s" % c] for c in categories))) plot_pdf = pdf cdf = pdf.createCdf(aset) plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot") plot_ds.add(combined_ds) wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10., options.mH + 10.) hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10., options.mH + 10.) helper.add(plot_ds, plot_ds.GetName()) helper.add(plot_pdf, plot_pdf.GetName()) helper.add((wmin, wmax), "eff_sigma_combcat") helper.add((hmin, hmax, hm), "FWHM_combcat") helper.add(plot_ds.sumEntries(), "sumEntries_combcat") mass.setRange("higgsrange", options.mH - 25., options.mH + 15.) del cdf del pdf del helper.dsets ### label = TLatex(0.1812081,0.8618881,"#scale[0.8]{#splitline{CMS preliminary}{Simulation}}") label = TLatex(0.7, 0.86, "#scale[0.65]{#splitline{CMS preliminary}{Simulation}}") label.SetNDC(1) ## ## Make web page with plots ## if options.doWebPage: hth = HtmlHelper(options.outdir) hth.navbar().cell(HtmlTag("a")).firstChild().txt("..").set( "href", "../?C=M;O=D") hth.navbar().cell(HtmlTag("a")).firstChild().txt("home").set( "href", "./") tab = hth.body().add(HtmlTable()) ip = 0 for c in ["_combcat"] + categories: ### for c in categories: if options.doWebPage and ip % 4 == 0: row = tab.row() ip = ip + 1 dsname = "sig_mass_m%1.0f%s" % (options.mH, c) canv = TCanvas(dsname, dsname, 600, 600) helper.objs.append(canv) ### leg = TLegend(0.4345638,0.6835664,0.9362416,0.9178322) leg = TLegend(0.2, 0.96, 0.5, 0.55) #apply_modifs( leg, [("SetLineColor",kWhite),("SetFillColor",kWhite),("SetFillStyle",0),("SetLineStyle",0)] ) hplotcompint = mass.frame(RooFit.Bins(250), RooFit.Range("higgsrange")) helper.objs.append(hplotcompint) helper.objs.append(leg) plot_ds = helper.histos["plot_%s" % dsname] plot_pdf = helper.histos["pdf_%s" % dsname] wmin, wmax = helper.histos["eff_sigma%s" % c] hmin, hmax, hm = helper.histos["FWHM%s" % c] print hmin, hmax, hm style = (RooFit.LineColor(kBlue), RooFit.LineWidth(2), RooFit.FillStyle(0)) style_seff = ( RooFit.LineWidth(2), RooFit.FillStyle(1001), RooFit.VLines(), RooFit.LineColor(15), ) style_ds = (RooFit.MarkerStyle(kOpenSquare), ) plot_ds.plotOn(hplotcompint, RooFit.Invisible()) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range(wmin, wmax), RooFit.FillColor(19), RooFit.DrawOption("F"), *style_seff) seffleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range(wmin, wmax), RooFit.LineColor(15), *style_seff) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range("higgsrange"), *style) pdfleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) plot_ds.plotOn(hplotcompint, *style_ds) pointsleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) iob = int(hplotcompint.numItems() - 1) leg.AddEntry(pointsleg, "Simulation", "pe") leg.AddEntry(pdfleg, "Parametric model", "l") leg.AddEntry(seffleg, "#sigma_{eff} = %1.2f GeV " % (0.5 * (wmax - wmin)), "fl") clabel = TLatex(0.74, 0.65, "#scale[0.65]{#splitline{%s}{%s}}" % clables[c]) clabel.SetNDC(1) helper.objs.append(clabel) hm = hplotcompint.GetMaximum() * 0.5 * 0.9 ### hm = pdfleg.GetMaximum()*0.5 fwhmarrow = TArrow(hmin, hm, hmax, hm) fwhmarrow.SetArrowSize(0.03) helper.objs.append(fwhmarrow) fwhmlabel = TPaveText(0.20, 0.58, 0.56, 0.48, "brNDC") fwhmlabel.SetFillStyle(0) fwhmlabel.SetLineColor(kWhite) reducedFWHM = (hmax - hmin) / 2.3548200 fwhmlabel.AddText("FWHM/2.35 = %1.2f GeV" % reducedFWHM) helper.objs.append(fwhmlabel) hplotcompint.SetTitle("") hplotcompint.GetXaxis().SetNoExponent(True) hplotcompint.GetXaxis().SetTitle("m_{#gamma#gamma} (GeV)") hplotcompint.GetXaxis().SetNdivisions(509) ## hplotcompint.GetYaxis().SetTitle("A.U."); ## hplotcompint.GetYaxis().SetRangeUser(0.,hplotcompint.GetMaximum()*1.4); hplotcompint.Draw() leg.Draw("same") label.Draw("same") clabel.Draw("same") fwhmarrow.Draw("<>") fwhmlabel.Draw("same") plot_ds.sumEntries() if options.doWebPage: hpl = HtmlPlot(canv, False, "", True, True, True) hpl.caption("<i>%s</i>" % canv.GetTitle()) row.cell(hpl) else: if os.path.isdir(options.outdir) is False: os.mkdir(options.outdir) for ext in "C", "png", "pdf": canv.SaveAs( os.path.join(options.outdir, "%s.%s" % (canv.GetName(), ext))) if "comb" in c: ip = 0 if options.doWebPage: print "Creating pages..." hth.dump() for f in helper.files: f.Close() gROOT.Reset() from pprint import pprint pprint(helper) print 'Summary statistics per event class' print 'Cat\tSignal\t\tData/GeV (in %3.1f+/-10)\tsigEff\tFWHM/2.35' % options.mH sigTotal = 0. dataTotal = 0. for c in categories: sigVal = helper.histos["sumEntries%s" % c] datVal = helper.histos["data_sumEntries%s" % c] sigTotal += sigVal dataTotal += datVal for c in categories: sigVal = helper.histos["sumEntries%s" % c] datVal = helper.histos["data_sumEntries%s" % c] effSig = 0.5 * (helper.histos["eff_sigma%s" % c][1] - helper.histos["eff_sigma%s" % c][0]) fwhm = (helper.histos["FWHM%s" % c][1] - helper.histos["FWHM%s" % c][0]) / 2.3548200 print c, '\t%3.1f (%3.1f%%)\t%3.1f (%3.1f%%)\t\t\t%2.2f\t%2.2f' % ( sigVal, 100. * sigVal / sigTotal, datVal / (10. + 10.), 100. * datVal / dataTotal, effSig, fwhm) print "Done."
ratePlot.GetYaxis().SetTitle("Rate [Hz]") leg.Draw() # Plot ranges ratePlot.GetYaxis().SetRangeUser(1e2, 1e10) ratePlot.GetXaxis().SetRangeUser(30, 370) # Lumi and energy info text = TPaveText(0.2, 0.84, 0.6, 0.9, "NDC") text.AddText("L_{inst} = 3 #times 10^{35} cm^{-2} s^{-1} #sqrt{s} = 100 TeV") text.Draw() # Adding a reference line at 1 MHz mhzLine = TLine(30, mySettings.yScale, 160, mySettings.yScale) mhzLine.SetLineColor(2) mhzLine.SetLineStyle(2) mhzLine.Draw() label_1MHz = TLatex(143, 1.1 * mySettings.yScale, "1 MHz") label_1MHz.SetTextSize(0.04) label_1MHz.Draw() canvas.Update() canvas.Draw() canvas.Print("ratePlot.png", "png") canvas.Print("ratePlot.svg", "svg") canvas.Print("ratePlot.pdf", "pdf") canvas.Print("ratePlot.C", "cxx")
def main(argv): VERBOSE = False # Read in command line args parser = OptionParser(usage=str( "\n" + "create_resource_correlation_plots.py [run period] [minversion] [version]\n" + "example: create_resource_correlation_plots.py 2015_03 15 20\n" + "\n" + "Input xml file should be created with\n" + "hdswif.py summary [workflow]")) parser.add_option("-V", "--verbose", dest="verbose", help="verbose output") (options, args) = parser.parse_args(argv) if (options.verbose): VERBOSE = True if len(args) != 3: print "Usage:" print "create_resource_correlation_plots.py [run period] [minversion] [version]" print "example: create_resource_correlation_plots.py 2015_03 15 20" exit() RUNPERIOD = "" VERSION = "" # RUNPERIOD is with underscore RUNPERIOD = args[0] RUNPERIOD = RUNPERIOD.replace('-', '_') RUNPERIOD_HYPHEN = RUNPERIOD.replace('_', '-') MINVERSION = int(args[1]) VERSION = int(args[2]) #assert MINVERSION < VERSION # List of all valid launch vers launchlist = [] # Only run over launches that had table created in DB # Create MySQL connection db_conn = MySQLdb.connect(host='hallddb', user='******', passwd='', db='farming') cursor = db_conn.cursor() for ver in range(MINVERSION, VERSION): formatted_vernum = "%02d" % ver tablename = 'cross_analysis_table_' + RUNPERIOD + '_ver' + formatted_vernum cursor.execute("SHOW TABLES LIKE '" + tablename + "'") results = cursor.fetchall() if len(results) == 0: print 'table ' + tablename + ' does NOT exist, skipping...' else: # print 'table ' + tablename + ' exists' launchlist.append(ver) print 'Launch vers to compare: ' + str(launchlist) # Dictionary between ver to be filled and TGraph dict_cpu_sec = {} dict_wall_sec = {} dict_mem_kb = {} dict_vmem_kb = {} dict_nevents = {} dict_input_copy_sec = {} dict_plugin_sec = {} # This one is a TH1F dict_nevents_diff = {} for ver in launchlist: dict_cpu_sec[ver] = TGraph() dict_wall_sec[ver] = TGraph() dict_mem_kb[ver] = TGraph() dict_vmem_kb[ver] = TGraph() dict_nevents[ver] = TGraph() dict_input_copy_sec[ver] = TGraph() dict_plugin_sec[ver] = TGraph() hname = 'dict_nevents_diff_' + format(ver, 2) dict_nevents_diff[ver] = TH1F( hname, ';#events ver' + str(VERSION) + ' - ver' + str(ver) + ';', 400, -200, 200) # Create MySQL connection db_conn = MySQLdb.connect(host='hallddb', user='******', passwd='', db='farming') cursor = db_conn.cursor() # Get all runs and files for the launch of interest (ver VERSION) formatted_mainvernum = "%02d" % VERSION tablename = 'cross_analysis_table_' + RUNPERIOD + '_ver' + formatted_mainvernum cursor.execute('SELECT run, file FROM ' + tablename) results = cursor.fetchall() # Keep the run/file combination in a set. The entries in the DB # should be unique, but this acts as a guard. set_run_file = Set() for row in results: run_file = format(row[0], 6) + '_' + format(row[1], 3) if run_file in set_run_file: print run_file + ' has already been accounted for, skipping' continue set_run_file.add(run_file) npoints = 0 for run_file in set_run_file: npoints += 1 if npoints % 500 == 0: print 'processing ' + format(npoints, 4) + ' / ' + str( len(set_run_file)) + '...' match = re.search(r"(\d\d\d\d\d\d)_(\d\d\d)", run_file) run_num = match.group(1) file_num = match.group(2) if VERBOSE: print '-------------------------------------------------------------------' print 'run = ' + str(run_num) + ' file = ' + str(file_num) # Grab results from DB for each version for this file, # fill into dicts # Dictionaries between [version] : [resources] cpu_sec = {} wall_sec = {} mem_kb = {} vmem_kb = {} nevents = {} input_copy_sec = {} plugin_sec = {} # Iterate over VERSION and launchlist. # Start with VERSION so that the condition for # filling the correlation plots gets satsified # for each of the vers in launchlist noValue = -999 for ver in [VERSION] + launchlist: cpu_sec[ver] = noValue wall_sec[ver] = noValue mem_kb[ver] = noValue vmem_kb[ver] = noValue nevents[ver] = noValue input_copy_sec[ver] = noValue plugin_sec[ver] = noValue formatted_vernum = "%02d" % ver tablename = 'cross_analysis_table_' + RUNPERIOD + '_ver' + formatted_vernum cursor.execute('SELECT cpu_sec, wall_sec, mem_kb, vmem_kb, nevents, input_copy_sec, plugin_sec FROM ' \ + tablename + ' WHERE run = ' + str(run_num) + ' AND file = ' + str(file_num)) results = cursor.fetchall() for row in results: cpu_sec[ver] = row[0] wall_sec[ver] = row[1] mem_kb[ver] = row[2] vmem_kb[ver] = row[3] nevents[ver] = row[4] input_copy_sec[ver] = row[5] plugin_sec[ver] = row[6] if ver == VERSION: # Nothing to fill for ver VERSION continue # Fill correlations plots if cpu_sec[VERSION] != noValue and cpu_sec[ver] != noValue: dict_cpu_sec[ver].SetPoint(dict_cpu_sec[ver].GetN(), float(cpu_sec[VERSION]) / 60, float(cpu_sec[ver]) / 60) if wall_sec[VERSION] != noValue and wall_sec[ver] != noValue: dict_wall_sec[ver].SetPoint(dict_wall_sec[ver].GetN(), float(wall_sec[VERSION]) / 60, float(wall_sec[ver]) / 60) if mem_kb[VERSION] != noValue and mem_kb[ver] != noValue: dict_mem_kb[ver].SetPoint(dict_mem_kb[ver].GetN(), float(mem_kb[VERSION]) / 1024 / 1024, float(mem_kb[ver]) / 1024 / 1024) if vmem_kb[VERSION] != noValue and vmem_kb[ver] != noValue: dict_vmem_kb[ver].SetPoint( dict_vmem_kb[ver].GetN(), float(vmem_kb[VERSION]) / 1024 / 1024, float(vmem_kb[ver]) / 1024 / 1024) if nevents[VERSION] != noValue and nevents[ver] != noValue: dict_nevents[ver].SetPoint(dict_nevents[ver].GetN(), float(nevents[VERSION]), float(nevents[ver])) dict_nevents_diff[ver].Fill( float(nevents[VERSION]) - float(nevents[ver])) if input_copy_sec[VERSION] != noValue and input_copy_sec[ ver] != noValue: dict_input_copy_sec[ver].SetPoint( dict_input_copy_sec[ver].GetN(), float(input_copy_sec[VERSION]) / 60, float(input_copy_sec[ver]) / 60) if plugin_sec[VERSION] != noValue and plugin_sec[ver] != noValue: dict_plugin_sec[ver].SetPoint(dict_plugin_sec[ver].GetN(), float(plugin_sec[VERSION]) / 60, float(plugin_sec[ver]) / 60) # end of loop over vers # end of loop over run and files # Create html page htmlDir = 'resource_use' if not os.path.exists(htmlDir): os.makedirs(htmlDir) htmlfilename = htmlDir + '/resource_use_' + RUNPERIOD + '_ver' + format( VERSION, 2) + '.html' htmlfile = open(htmlfilename, 'w') htmlfile.write('<!-- launch ver ' + format(VERSION, 2) + '-->\n') htmlfile.write('<html>\n') htmlfile.write('\n') htmlfile.write('<head>\n') htmlfile.write( '<link rel="stylesheet" type="text/css" href="mystyle.css">\n') htmlfile.write( '<meta http-equiv="content-style-type" content="text/css">\n') htmlfile.write('<title>Offline Monitoring Results 2015-03</title>\n') htmlfile.write('\n') htmlfile.write('<style>\n') htmlfile.write(' #content iframe{\n') htmlfile.write(' overflow: hidden;\n') htmlfile.write(' width:100%;\n') htmlfile.write(' border:none;\n') htmlfile.write(' margin: 0;\n') htmlfile.write(' padding: 0;\n') htmlfile.write(' }\n') htmlfile.write('</style>\n') htmlfile.write('\n') htmlfile.write('<script language="javascript" type="text/javascript">\n') htmlfile.write(' function resizeIframe(obj) {\n') htmlfile.write( " obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';\n" ) htmlfile.write(' }\n') htmlfile.write('</script>\n') htmlfile.write('\n') htmlfile.write('</head>\n') htmlfile.write('\n') htmlfile.write('<body>\n') htmlfile.write('<h2>Comparison of ver' + format(VERSION, 2) + ' and older</h2>\n') tablewidth = (VERSION - MINVERSION) * 20 htmlfile.write('<table style="width:' + str(tablewidth) + '%">\n') # cpu_sec htmlfile.write(' <tr>\n') htmlfile.write(' <td colspan="' + str(VERSION - MINVERSION) + '"> CPU time (min) </td>\n') htmlfile.write(' </tr>\n') htmlfile.write(' <tr>\n') for ver in launchlist: htmlfile.write(' <!-- 01___cpu_sec ver' + format(ver, 2) + '-->\n') htmlfile.write(' <td style="width:20%">\n') htmlfile.write(' <a href="./figures/SWIF/ver' + format(VERSION,2) + '/01___cpu_sec_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png">\n') htmlfile.write(' <img src="./figures/SWIF/ver' + format(VERSION,2) + '/01___cpu_sec_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png" width="100%">\n') htmlfile.write(' </a>\n') htmlfile.write(' </td>\n') htmlfile.write(' </tr>\n') # wall_sec htmlfile.write(' <tr>\n') htmlfile.write(' <td colspan="' + str(VERSION - MINVERSION) + '"> wall time (min) </td>\n') htmlfile.write(' </tr>\n') htmlfile.write(' <tr>\n') for ver in launchlist: htmlfile.write(' <!-- 02___wall_sec ver' + format(ver, 2) + '-->\n') htmlfile.write(' <td style="width:20%">\n') htmlfile.write(' <a href="./figures/SWIF/ver' + format(VERSION,2) + '/02___wall_sec_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png">\n') htmlfile.write(' <img src="./figures/SWIF/ver' + format(VERSION,2) + '/02___wall_sec_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png" width="100%">\n') htmlfile.write(' </a>\n') htmlfile.write(' </td>\n') htmlfile.write(' </tr>\n') # mem_kb htmlfile.write(' <tr>\n') htmlfile.write(' <td colspan="' + str(VERSION - MINVERSION) + '"> Memory (GB) </td>\n') htmlfile.write(' </tr>\n') htmlfile.write(' <tr>\n') for ver in launchlist: htmlfile.write(' <!-- 03___mem_kb ver' + format(ver, 2) + '-->\n') htmlfile.write(' <td style="width:20%">\n') htmlfile.write(' <a href="./figures/SWIF/ver' + format(VERSION,2) + '/03___mem_kb_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png">\n') htmlfile.write(' <img src="./figures/SWIF/ver' + format(VERSION,2) + '/03___mem_kb_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png" width="100%">\n') htmlfile.write(' </a>\n') htmlfile.write(' </td>\n') htmlfile.write(' </tr>\n') # vmem_kb htmlfile.write(' <tr>\n') htmlfile.write(' <td colspan="' + str(VERSION - MINVERSION) + '"> Virtual memory (GB) </td>\n') htmlfile.write(' </tr>\n') htmlfile.write(' <tr>\n') for ver in launchlist: htmlfile.write(' <!-- 04___vmem_kb ver' + format(ver, 2) + '-->\n') htmlfile.write(' <td style="width:20%">\n') htmlfile.write(' <a href="./figures/SWIF/ver' + format(VERSION,2) + '/04___vmem_kb_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png">\n') htmlfile.write(' <img src="./figures/SWIF/ver' + format(VERSION,2) + '/04___vmem_kb_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png" width="100%">\n') htmlfile.write(' </a>\n') htmlfile.write(' </td>\n') htmlfile.write(' </tr>\n') # nevents htmlfile.write(' <tr>\n') htmlfile.write(' <td colspan="' + str(VERSION - MINVERSION) + '"> #events </td>\n') htmlfile.write(' </tr>\n') htmlfile.write(' <tr>\n') for ver in launchlist: htmlfile.write(' <!-- 05___nevents ver' + format(ver, 2) + '-->\n') htmlfile.write(' <td style="width:20%">\n') htmlfile.write(' <a href="./figures/SWIF/ver' + format(VERSION,2) + '/05___nevents_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png">\n') htmlfile.write(' <img src="./figures/SWIF/ver' + format(VERSION,2) + '/05___nevents_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png" width="100%">\n') htmlfile.write(' </a>\n') htmlfile.write(' </td>\n') htmlfile.write(' </tr>\n') # nevents_diff htmlfile.write(' <tr>\n') htmlfile.write(' <td colspan="' + str(VERSION - MINVERSION) + '"> Δ events </td>\n') htmlfile.write(' </tr>\n') htmlfile.write(' <tr>\n') for ver in launchlist: htmlfile.write(' <!-- 06___nevents_diff ver' + format(ver, 2) + '-->\n') htmlfile.write(' <td style="width:20%">\n') htmlfile.write(' <a href="./figures/SWIF/ver' + format(VERSION,2) + '/06___nevents_diff_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png">\n') htmlfile.write(' <img src="./figures/SWIF/ver' + format(VERSION,2) + '/06___nevents_diff_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png" width="100%">\n') htmlfile.write(' </a>\n') htmlfile.write(' </td>\n') htmlfile.write(' </tr>\n') # input_copy_sec htmlfile.write(' <tr>\n') htmlfile.write(' <td colspan="' + str(VERSION - MINVERSION) + '"> input copy time (min) </td>\n') htmlfile.write(' </tr>\n') htmlfile.write(' <tr>\n') for ver in launchlist: htmlfile.write(' <!-- 07___input_copy_sec ver' + format(ver, 2) + '-->\n') htmlfile.write(' <td style="width:20%">\n') htmlfile.write(' <a href="./figures/SWIF/ver' + format(VERSION,2) + '/07___input_copy_sec_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png">\n') htmlfile.write(' <img src="./figures/SWIF/ver' + format(VERSION,2) + '/07___input_copy_sec_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png" width="100%">\n') htmlfile.write(' </a>\n') htmlfile.write(' </td>\n') htmlfile.write(' </tr>\n') # plugin_time htmlfile.write(' <tr>\n') htmlfile.write(' <td colspan="' + str(VERSION - MINVERSION) + '"> plugin time (min) </td>\n') htmlfile.write(' </tr>\n') htmlfile.write(' <tr>\n') for ver in launchlist: htmlfile.write(' <!-- 08___plugin_time ver' + format(ver, 2) + '-->\n') htmlfile.write(' <td style="width:20%">\n') htmlfile.write(' <a href="./figures/SWIF/ver' + format(VERSION,2) + '/08___plugin_time_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png">\n') htmlfile.write(' <img src="./figures/SWIF/ver' + format(VERSION,2) + '/08___plugin_time_ver' \ + format(VERSION,2) + '_ver' + format(ver,2) + '.png" width="100%">\n') htmlfile.write(' </a>\n') htmlfile.write(' </td>\n') htmlfile.write(' </tr>\n') htmlfile.write('</table>\n') htmlfile.write('</body>\n') htmlfile.write('</html>\n') htmlfile.close() line = TLine(0, 0, 0, 0) latex = TLatex() latex.SetTextColor(ROOT.kBlack) latex.SetTextSize(0.06) latex.SetTextAlign(12) latex.SetNDC(1) figureDir = htmlDir + '/figures/SWIF/ver' + format(VERSION, 2) if not os.path.exists(figureDir): os.makedirs(figureDir) for ver in launchlist: #-------------------------------------------------------------------- # cpu_sec #-------------------------------------------------------------------- c1 = TCanvas('c1', 'canvas', 0, 0, 1600, 1200) c1.SetTopMargin(0.02) c1.SetRightMargin(0.02) c1.SetLeftMargin(0.15) c1.SetBottomMargin(0.14) dict_cpu_sec[ver].GetXaxis().SetTitleSize(0.06) dict_cpu_sec[ver].GetXaxis().SetTitleOffset(0.900) dict_cpu_sec[ver].GetXaxis().SetLabelSize(0.05) dict_cpu_sec[ver].GetYaxis().SetTitleSize(0.06) dict_cpu_sec[ver].GetYaxis().SetTitleOffset(1.200) dict_cpu_sec[ver].GetYaxis().CenterTitle() dict_cpu_sec[ver].GetYaxis().SetLabelSize(0.05) dict_cpu_sec[ver].SetMarkerColor(ROOT.kRed) dict_cpu_sec[ver].SetMarkerStyle(20) dict_cpu_sec[ver].SetMarkerSize(1.2) dict_cpu_sec[ver].SetLineColor(ROOT.kRed) dict_cpu_sec[ver].SetLineStyle(1) dict_cpu_sec[ver].SetLineWidth(1) dict_cpu_sec[ver].GetXaxis().SetTitle('CPU time (min) for ver' + format(VERSION, 2)) dict_cpu_sec[ver].GetYaxis().SetTitle('CPU time (min) for ver' + format(ver, 2)) X = dict_cpu_sec[ver].GetXaxis().GetXmax() Y = dict_cpu_sec[ver].GetYaxis().GetXmax() larger = Y if X < Y else X # don't show negative values (should not exist) dict_cpu_sec[ver].GetXaxis().SetLimits(0, larger) dict_cpu_sec[ver].SetMinimum(0) dict_cpu_sec[ver].SetMaximum(larger) dict_cpu_sec[ver].Draw('AP') line.SetX1(0) line.SetY1(0) line.SetX2(larger) line.SetY2(larger) line.SetLineColor(ROOT.kMagenta) line.SetLineStyle(2) line.DrawClone("same") text = "total: " + str(dict_cpu_sec[ver].GetN()) latex.SetTextColor(ROOT.kBlue) latex.DrawLatex(0.75, 0.92, text) c1.SaveAs(figureDir + '/01___cpu_sec_ver' + format(VERSION, 2) + '_ver' + format(ver, 2) + '.png') c1.Close() #-------------------------------------------------------------------- # wall_sec #-------------------------------------------------------------------- c1 = TCanvas('c1', 'canvas', 0, 0, 1600, 1200) c1.SetTopMargin(0.02) c1.SetRightMargin(0.02) c1.SetLeftMargin(0.15) c1.SetBottomMargin(0.14) dict_wall_sec[ver].GetXaxis().SetTitleSize(0.06) dict_wall_sec[ver].GetXaxis().SetTitleOffset(0.900) dict_wall_sec[ver].GetXaxis().SetLabelSize(0.05) dict_wall_sec[ver].GetYaxis().SetTitleSize(0.06) dict_wall_sec[ver].GetYaxis().SetTitleOffset(1.200) dict_wall_sec[ver].GetYaxis().CenterTitle() dict_wall_sec[ver].GetYaxis().SetLabelSize(0.05) dict_wall_sec[ver].SetMarkerColor(ROOT.kRed) dict_wall_sec[ver].SetMarkerStyle(20) dict_wall_sec[ver].SetMarkerSize(1.2) dict_wall_sec[ver].SetLineColor(ROOT.kRed) dict_wall_sec[ver].SetLineStyle(1) dict_wall_sec[ver].SetLineWidth(1) dict_wall_sec[ver].GetXaxis().SetTitle('wall time (min) for ver' + format(VERSION, 2)) dict_wall_sec[ver].GetYaxis().SetTitle('wall time (min) for ver' + format(ver, 2)) X = dict_wall_sec[ver].GetXaxis().GetXmax() Y = dict_wall_sec[ver].GetYaxis().GetXmax() larger = Y if X < Y else X # don't show negative values (should not exist) dict_wall_sec[ver].GetXaxis().SetLimits(0, larger) dict_wall_sec[ver].SetMinimum(0) dict_wall_sec[ver].SetMaximum(larger) dict_wall_sec[ver].Draw('AP') line.SetX1(0) line.SetY1(0) line.SetX2(larger) line.SetY2(larger) line.SetLineColor(ROOT.kMagenta) line.SetLineStyle(2) line.DrawClone("same") text = "total: " + str(dict_wall_sec[ver].GetN()) latex.SetTextColor(ROOT.kBlue) latex.DrawLatex(0.75, 0.92, text) c1.SaveAs(figureDir + '/02___wall_sec_ver' + format(VERSION, 2) + '_ver' + format(ver, 2) + '.png') c1.Close() #-------------------------------------------------------------------- # mem_kb #-------------------------------------------------------------------- c1 = TCanvas('c1', 'canvas', 0, 0, 1600, 1200) c1.SetTopMargin(0.02) c1.SetRightMargin(0.02) c1.SetLeftMargin(0.15) c1.SetBottomMargin(0.14) dict_mem_kb[ver].GetXaxis().SetTitleSize(0.06) dict_mem_kb[ver].GetXaxis().SetTitleOffset(0.900) dict_mem_kb[ver].GetXaxis().SetLabelSize(0.05) dict_mem_kb[ver].GetYaxis().SetTitleSize(0.06) dict_mem_kb[ver].GetYaxis().SetTitleOffset(1.200) dict_mem_kb[ver].GetYaxis().CenterTitle() dict_mem_kb[ver].GetYaxis().SetLabelSize(0.05) dict_mem_kb[ver].SetMarkerColor(ROOT.kRed) dict_mem_kb[ver].SetMarkerStyle(20) dict_mem_kb[ver].SetMarkerSize(1.2) dict_mem_kb[ver].SetLineColor(ROOT.kRed) dict_mem_kb[ver].SetLineStyle(1) dict_mem_kb[ver].SetLineWidth(1) dict_mem_kb[ver].GetXaxis().SetTitle('mem (GB) for ver' + format(VERSION, 2)) dict_mem_kb[ver].GetYaxis().SetTitle('mem (GB) for ver' + format(ver, 2)) X = dict_mem_kb[ver].GetXaxis().GetXmax() Y = dict_mem_kb[ver].GetYaxis().GetXmax() larger = Y if X < Y else X # don't show negative values (should not exist) dict_mem_kb[ver].GetXaxis().SetLimits(0, larger) dict_mem_kb[ver].SetMinimum(0) dict_mem_kb[ver].SetMaximum(larger) dict_mem_kb[ver].Draw('AP') line.SetX1(0) line.SetY1(0) line.SetX2(larger) line.SetY2(larger) line.SetLineColor(ROOT.kMagenta) line.SetLineStyle(2) line.DrawClone("same") text = "total: " + str(dict_mem_kb[ver].GetN()) latex.SetTextColor(ROOT.kBlue) latex.DrawLatex(0.75, 0.92, text) c1.SaveAs(figureDir + '/03___mem_kb_ver' + format(VERSION, 2) + '_ver' + format(ver, 2) + '.png') c1.Close() #-------------------------------------------------------------------- # vmem_kb #-------------------------------------------------------------------- c1 = TCanvas('c1', 'canvas', 0, 0, 1600, 1200) c1.SetTopMargin(0.02) c1.SetRightMargin(0.02) c1.SetLeftMargin(0.15) c1.SetBottomMargin(0.14) dict_vmem_kb[ver].GetXaxis().SetTitleSize(0.06) dict_vmem_kb[ver].GetXaxis().SetTitleOffset(0.900) dict_vmem_kb[ver].GetXaxis().SetLabelSize(0.05) dict_vmem_kb[ver].GetYaxis().SetTitleSize(0.06) dict_vmem_kb[ver].GetYaxis().SetTitleOffset(1.200) dict_vmem_kb[ver].GetYaxis().CenterTitle() dict_vmem_kb[ver].GetYaxis().SetLabelSize(0.05) dict_vmem_kb[ver].SetMarkerColor(ROOT.kRed) dict_vmem_kb[ver].SetMarkerStyle(20) dict_vmem_kb[ver].SetMarkerSize(1.2) dict_vmem_kb[ver].SetLineColor(ROOT.kRed) dict_vmem_kb[ver].SetLineStyle(1) dict_vmem_kb[ver].SetLineWidth(1) dict_vmem_kb[ver].GetXaxis().SetTitle('vmem (GB) for ver' + format(VERSION, 2)) dict_vmem_kb[ver].GetYaxis().SetTitle('vmem (GB) for ver' + format(ver, 2)) X = dict_vmem_kb[ver].GetXaxis().GetXmax() Y = dict_vmem_kb[ver].GetYaxis().GetXmax() larger = Y if X < Y else X # don't show negative values (should not exist) dict_vmem_kb[ver].GetXaxis().SetLimits(0, larger) dict_vmem_kb[ver].SetMinimum(0) dict_vmem_kb[ver].SetMaximum(larger) dict_vmem_kb[ver].Draw('AP') line.SetX1(0) line.SetY1(0) line.SetX2(larger) line.SetY2(larger) line.SetLineColor(ROOT.kMagenta) line.SetLineStyle(2) line.DrawClone("same") text = "total: " + str(dict_vmem_kb[ver].GetN()) latex.SetTextColor(ROOT.kBlue) latex.DrawLatex(0.75, 0.92, text) c1.SaveAs(figureDir + '/04___vmem_kb_ver' + format(VERSION, 2) + '_ver' + format(ver, 2) + '.png') c1.Close() #-------------------------------------------------------------------- # nevents #-------------------------------------------------------------------- c1 = TCanvas('c1', 'canvas', 0, 0, 1600, 1200) c1.SetTopMargin(0.04) c1.SetRightMargin(0.04) c1.SetLeftMargin(0.15) c1.SetBottomMargin(0.14) dict_nevents[ver].GetXaxis().SetTitleSize(0.06) dict_nevents[ver].GetXaxis().SetTitleOffset(0.900) dict_nevents[ver].GetXaxis().SetLabelSize(0.05) dict_nevents[ver].GetYaxis().SetTitleSize(0.06) dict_nevents[ver].GetYaxis().SetTitleOffset(1.200) dict_nevents[ver].GetYaxis().CenterTitle() dict_nevents[ver].GetYaxis().SetLabelSize(0.05) dict_nevents[ver].SetMarkerColor(ROOT.kRed) dict_nevents[ver].SetMarkerStyle(20) dict_nevents[ver].SetMarkerSize(1.2) dict_nevents[ver].SetLineColor(ROOT.kRed) dict_nevents[ver].SetLineStyle(1) dict_nevents[ver].SetLineWidth(1) dict_nevents[ver].GetXaxis().SetTitle('#events for ver' + format(VERSION, 2)) dict_nevents[ver].GetYaxis().SetTitle('#events for ver' + format(ver, 2)) X = dict_nevents[ver].GetXaxis().GetXmax() Y = dict_nevents[ver].GetYaxis().GetXmax() larger = Y if X < Y else X # don't show negative values (should not exist) dict_nevents[ver].GetXaxis().SetLimits(0, larger) dict_nevents[ver].SetMinimum(0) dict_nevents[ver].SetMaximum(larger) dict_nevents[ver].Draw('AP') line.SetX1(0) line.SetY1(0) line.SetX2(larger) line.SetY2(larger) line.SetLineColor(ROOT.kMagenta) line.SetLineStyle(2) line.DrawClone("same") text = "total: " + str(dict_nevents[ver].GetN()) latex.SetTextColor(ROOT.kBlue) latex.DrawLatex(0.75, 0.92, text) c1.SaveAs(figureDir + '/05___nevents_ver' + format(VERSION, 2) + '_ver' + format(ver, 2) + '.png') c1.Close() #-------------------------------------------------------------------- # nevents_diff #-------------------------------------------------------------------- c1 = TCanvas('c1', 'canvas', 0, 0, 1600, 1200) c1.SetTopMargin(0.04) c1.SetRightMargin(0.04) c1.SetLeftMargin(0.15) c1.SetBottomMargin(0.14) dict_nevents_diff[ver].GetXaxis().SetTitleSize(0.06) dict_nevents_diff[ver].GetXaxis().SetTitleOffset(0.900) dict_nevents_diff[ver].GetXaxis().SetLabelSize(0.05) dict_nevents_diff[ver].GetYaxis().SetTitleSize(0.06) dict_nevents_diff[ver].GetYaxis().SetTitleOffset(1.200) dict_nevents_diff[ver].GetYaxis().CenterTitle() dict_nevents_diff[ver].GetYaxis().SetLabelSize(0.05) dict_nevents_diff[ver].SetLineColor(ROOT.kRed) dict_nevents_diff[ver].SetLineStyle(1) dict_nevents_diff[ver].SetLineWidth(1) c1.SetLogy(1) dict_nevents_diff[ver].Draw() text = "total: " + str(int(dict_nevents_diff[ver].GetEntries())) latex.SetTextColor(ROOT.kBlue) latex.DrawLatex(0.75, 0.92, text) c1.SaveAs(figureDir + '/06___nevents_diff_ver' + format(VERSION, 2) + '_ver' + format(ver, 2) + '.png') c1.Close() #-------------------------------------------------------------------- # input_copy_sec #-------------------------------------------------------------------- c1 = TCanvas('c1', 'canvas', 0, 0, 1600, 1200) c1.SetTopMargin(0.02) c1.SetRightMargin(0.02) c1.SetLeftMargin(0.15) c1.SetBottomMargin(0.14) dict_input_copy_sec[ver].GetXaxis().SetTitleSize(0.06) dict_input_copy_sec[ver].GetXaxis().SetTitleOffset(0.900) dict_input_copy_sec[ver].GetXaxis().SetLabelSize(0.05) dict_input_copy_sec[ver].GetYaxis().SetTitleSize(0.06) dict_input_copy_sec[ver].GetYaxis().SetTitleOffset(1.200) dict_input_copy_sec[ver].GetYaxis().CenterTitle() dict_input_copy_sec[ver].GetYaxis().SetLabelSize(0.05) dict_input_copy_sec[ver].SetMarkerColor(ROOT.kRed) dict_input_copy_sec[ver].SetMarkerStyle(20) dict_input_copy_sec[ver].SetMarkerSize(1.2) dict_input_copy_sec[ver].SetLineColor(ROOT.kRed) dict_input_copy_sec[ver].SetLineStyle(1) dict_input_copy_sec[ver].SetLineWidth(1) dict_input_copy_sec[ver].GetXaxis().SetTitle( 'input copy time (min) for ver' + format(VERSION, 2)) dict_input_copy_sec[ver].GetYaxis().SetTitle( 'input copy time (min) for ver' + format(ver, 2)) X = dict_input_copy_sec[ver].GetXaxis().GetXmax() Y = dict_input_copy_sec[ver].GetYaxis().GetXmax() larger = Y if X < Y else X # don't show negative values (should not exist) dict_input_copy_sec[ver].GetXaxis().SetLimits(0, larger) dict_input_copy_sec[ver].SetMinimum(0) dict_input_copy_sec[ver].SetMaximum(larger) dict_input_copy_sec[ver].Draw('AP') line.SetX1(0) line.SetY1(0) line.SetX2(larger) line.SetY2(larger) line.SetLineColor(ROOT.kMagenta) line.SetLineStyle(2) line.DrawClone("same") text = "total: " + str(dict_input_copy_sec[ver].GetN()) latex.SetTextColor(ROOT.kBlue) latex.DrawLatex(0.75, 0.92, text) c1.SaveAs(figureDir + '/07___input_copy_sec_ver' + format(VERSION, 2) + '_ver' + format(ver, 2) + '.png') c1.Close() #-------------------------------------------------------------------- # plugin_sec #-------------------------------------------------------------------- c1 = TCanvas('c1', 'canvas', 0, 0, 1600, 1200) c1.SetTopMargin(0.02) c1.SetRightMargin(0.02) c1.SetLeftMargin(0.15) c1.SetBottomMargin(0.14) dict_plugin_sec[ver].GetXaxis().SetTitleSize(0.06) dict_plugin_sec[ver].GetXaxis().SetTitleOffset(0.900) dict_plugin_sec[ver].GetXaxis().SetLabelSize(0.05) dict_plugin_sec[ver].GetYaxis().SetTitleSize(0.06) dict_plugin_sec[ver].GetYaxis().SetTitleOffset(1.200) dict_plugin_sec[ver].GetYaxis().CenterTitle() dict_plugin_sec[ver].GetYaxis().SetLabelSize(0.05) dict_plugin_sec[ver].SetMarkerColor(ROOT.kRed) dict_plugin_sec[ver].SetMarkerStyle(20) dict_plugin_sec[ver].SetMarkerSize(1.2) dict_plugin_sec[ver].SetLineColor(ROOT.kRed) dict_plugin_sec[ver].SetLineStyle(1) dict_plugin_sec[ver].SetLineWidth(1) dict_plugin_sec[ver].GetXaxis().SetTitle('plugin time (min) for ver' + format(VERSION, 2)) dict_plugin_sec[ver].GetYaxis().SetTitle('plugin time (min) for ver' + format(ver, 2)) X = dict_plugin_sec[ver].GetXaxis().GetXmax() Y = dict_plugin_sec[ver].GetYaxis().GetXmax() larger = Y if X < Y else X # don't show negative values (should not exist) dict_plugin_sec[ver].GetXaxis().SetLimits(0, larger) dict_plugin_sec[ver].SetMinimum(0) dict_plugin_sec[ver].SetMaximum(larger) dict_plugin_sec[ver].Draw('AP') line.SetX1(0) line.SetY1(0) line.SetX2(larger) line.SetY2(larger) line.SetLineColor(ROOT.kMagenta) line.SetLineStyle(2) line.DrawClone("same") text = "total: " + str(dict_plugin_sec[ver].GetN()) latex.SetTextColor(ROOT.kBlue) latex.DrawLatex(0.75, 0.92, text) c1.SaveAs(figureDir + '/08___plugin_time_ver' + format(VERSION, 2) + '_ver' + format(ver, 2) + '.png') c1.Close() # Copy all files to web-accessible directory outDir = '/group/halld/www/halldweb/html/data_monitoring/launch_analysis/' + RUNPERIOD + '/resource_use/' shutil.copy(htmlfilename, outDir) outputfigureDir = outDir + '/figures/SWIF/ver' + format(VERSION, 2) # delete directory if it already exists (necessary for shutil.copytree) if os.path.exists(outputfigureDir): shutil.rmtree(outputfigureDir) shutil.copytree(figureDir, outputfigureDir + '/') # Create link from main [RUNPERIOD].html file # Add the newest row into the html table using the hook # that is added at the end of each launch version. runperiodfilename = '/group/halld/www/halldweb/html/data_monitoring/launch_analysis/' + RUNPERIOD + '/' + RUNPERIOD + '.html' with open(runperiodfilename, 'r') as runperiodfile: alllines = runperiodfile.readlines() # Reverse the lines and find the first occurrence of the hook # this is the final (most recent hook) alllines.reverse() nlines = 0 pos = 0 old_hook = '' for line in alllines: nlines += 1 if re.search( '<!--20[1-3][0-9]_[0-1][0-9]_ver[0-9][0-9] resource_use-->', line): pos = nlines old_hook = line break if old_hook == '': print 'Did not find old hook, make sure that file' print runperiodfilename print 'has a line containing <!--[RUNPERIOD]_ver[VERSION] resource_use-->' exit() # position to seek is total number of lines in file minus pos + 1 pos = len(alllines) - pos + 1 # lines for link linklines = [] linklines.append(' <li style="color:blue;">\n') linklines.append(' <h3><a href = "resource_use/resource_use_' + RUNPERIOD + '_ver' + format(VERSION,2) + '.html">' \ + 'ver' + format(VERSION,2) + '</a></h3> <!--' + RUNPERIOD + '_ver' \ + format(VERSION,2) + ' resource_use-->\n') # Reopen stats html file and insert newlines into line pos with open(runperiodfilename, 'r+') as runperiodfile: alllines = runperiodfile.readlines() alllines[pos:pos] = linklines # Write the new file with open(runperiodfilename, 'w') as runperiodfile: for line in alllines: runperiodfile.write(line) exit()
def addCMSTitle(x=0.2, y=0.93): T1 = TLatex() T1.SetNDC() T1.DrawLatex(x, y, "#scale[0.9]{CMS Preliminary #sqrt{s} = 8 TeV}")