def draw_nse_mean(self): cent_bin1 = [0, 4, 7] cent_bin2 = [3, 6, 8] p_bin1 = [ 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5 ] p_bin2 = [ 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 ] gr_mean = TGraphErrors() gr_width = TGraphErrors() gr_eff = TGraphErrors() for i in range(0, len(p_bin1)): f_gaus = self.draw_nse(cent_bin1[1], cent_bin2[1], p_bin1[i], p_bin2[i], -1, 2) mean = f_gaus.GetParameter(1) mean_err = f_gaus.GetParError(1) width = f_gaus.GetParameter(2) width_err = f_gaus.GetParError(2) gr_mean.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, mean) gr_mean.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, mean_err) gr_width.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, width) gr_width.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, width_err) p = 0.5 * (p_bin1[i] + p_bin2[i]) if p < 1: nse_low = 0.5 * p - 1.5 else: nse_low = -1 m = f_gaus.Integral(nse_low, 2.0) N = f_gaus.Integral(-10.0, 10.0) gr_eff.SetPoint(i, p, m / N) gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, eff_err(m, N)) gr_mean.SetMarkerStyle(20) gr_mean.SetMarkerSize(1.5) gr_mean.SetMarkerColor(632) gr_width.SetMarkerStyle(20) gr_width.SetMarkerSize(1.5) gr_width.SetMarkerColor(600) gr_eff.SetMarkerStyle(20) gr_eff.SetMarkerSize(1.5) gr_eff.SetMarkerColor(600) hx = histo(0, 10, -0.2, 1.2, "p_{T}(GeV/c)", "Mean/Width") canvas_file = self.__canvas__ canvas_file.cd() c1 = TCanvas("c1", "c1", 1000, 800) hx.Draw() gr_width.Draw("psame") gr_mean.Draw("psame") c1.Write("nse") c1.SaveAs("nse.png") c2 = TCanvas("c2", "c2", 1000, 800) hx.GetYaxis().SetTitle("n#sigma_{e} cut efficiency") hx.Draw() gr_eff.Draw("psame") c2.Write("nse_eff") c2.SaveAs("nse_eff.png")
def testIthr(): lines = get_lines('DAC_scan_ithr_0x40to0xf0.dat') gr1 = TGraphErrors() gr2 = TGraphErrors() fUnit = 1000. / 0.7 yUnit = 'e^{-}' for line in lines: if len(line) == 0: continue if line[0] in ['#', '\n']: continue fs = line.rstrip().split() ix = int(fs[0]) gr1.SetPoint(ix, float(fs[1]), float(fs[2]) * fUnit) gr1.SetPointError(ix, 0, float(fs[3]) * fUnit) gr2.SetPoint(ix, float(fs[1]), float(fs[4]) * fUnit) gr2.SetPointError(ix, 0, float(fs[5]) * fUnit) useAtlasStyle() gStyle.SetMarkerStyle(20) gr1.SetMarkerStyle(20) gr1.Draw('AP') h1 = gr1.GetHistogram() h1.GetYaxis().SetTitle("Threshold [" + yUnit + "]") h1.GetXaxis().SetTitle("I_{Thre} code") # h1.GetYaxis().SetRangeUser(0,0.2) gPad.SetTicks(1, 0) gPad.SetRightMargin(0.16) y1b = 0 y2b = 15 x1 = h1.GetXaxis().GetXmax() y1 = h1.GetYaxis().GetXmin() y2 = h1.GetYaxis().GetXmax() raxis = TGaxis(x1, y1, x1, y2, y1b, y2b, 506, "+L") raxis.SetLineColor(2) raxis.SetLabelColor(2) raxis.SetTitleColor(2) raxis.SetTitle("ENC [" + yUnit + "]") raxis.Draw() nP = gr2.GetN() Ys = gr2.GetY() EYs = gr2.GetEY() Y = array( 'd', [y1 + (y2 - y1) / (y2b - y1b) * (Ys[i] - y1b) for i in range(nP)]) EY = array('d', [(y2 - y1) / (y2b - y1b) * EYs[i] for i in range(nP)]) gr2x = TGraphErrors(nP, gr2.GetX(), Y, gr2.GetEX(), EY) gr2x.SetMarkerStyle(24) gr2x.SetLineColor(2) gr2x.SetMarkerColor(2) gr2x.Draw('Psame') waitRootCmdX()
def plotGainSummary(self, strDetName): #Create the Plot - Average gDet_AvgEffGain = TGraphErrors(len(self.GAIN_AVG_POINTS)) gDet_AvgEffGain.SetName("g_{0}_EffGainAvg".format(strDetName)) #Create the Plot - Max Gain gDet_MaxEffGain = TGraphErrors(len(self.GAIN_MAX_POINTS)) gDet_MaxEffGain.SetName("g_{0}_EffGainMax".format(strDetName)) #Create the Plot - Min Gain gDet_MinEffGain = TGraphErrors(len(self.GAIN_MIN_POINTS)) gDet_MinEffGain.SetName("g_{0}_EffGainMin".format(strDetName)) #Set and print the points #print "===============Printing Gain Data===============" #print "[BEGIN_DATA]" #print "\tVAR_INDEP,VAR_DEP,VAR_DEP_ERR" for i in range(0, len(self.GAIN_AVG_POINTS)): #Average gDet_AvgEffGain.SetPoint(i, self.DET_IMON_POINTS[i], self.GAIN_AVG_POINTS[i]) gDet_AvgEffGain.SetPointError(i, 0, self.GAIN_STDDEV_POINTS[i]) #print "\t%f,%f,%f"%(self.DET_IMON_POINTS[i],self.GAIN_AVG_POINTS[i],self.GAIN_STDDEV_POINTS[i]) #Max gDet_MaxEffGain.SetPoint(i, self.DET_IMON_POINTS[i], self.GAIN_MAX_POINTS[i]) #Min gDet_MinEffGain.SetPoint(i, self.DET_IMON_POINTS[i], self.GAIN_MIN_POINTS[i]) pass #print "[END_DATA]" #print "" #Draw canv_AvgEffGain = TCanvas( "canv_{0}_EffGainAvg".format(strDetName), "{0} Average Effective Gain".format(strDetName), 600, 600) canv_AvgEffGain.cd() canv_AvgEffGain.cd().SetLogy() gDet_AvgEffGain.GetXaxis().SetTitle("HV") gDet_AvgEffGain.GetYaxis().SetTitle("#LT Effective Gain #GT") gDet_AvgEffGain.GetYaxis().SetRangeUser(1e2, 1e6) gDet_AvgEffGain.SetMarkerStyle(21) gDet_AvgEffGain.Draw("AP") gDet_MaxEffGain.Draw("sameL") gDet_MinEffGain.Draw("sameL") #Write dir_Summary = self.FILE_OUT.mkdir("Summary") dir_Summary.cd() canv_AvgEffGain.Write() gDet_AvgEffGain.Write() gDet_MaxEffGain.Write() gDet_MinEffGain.Write() return
def draw_tof_cut_eff(self, cent_low, cent_high): cent_bin1 = [0, 4, 7] cent_bin2 = [3, 6, 8] p_bin1 = [ 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5 ] p_bin2 = [ 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 ] gr_mean = TGraphErrors() gr_width = TGraphErrors() gr_eff = TGraphErrors() for i in range(0, len(p_bin1)): f_gaus = self.draw_tof_cut(cent_bin1[1], cent_bin2[1], p_bin1[i], p_bin2[i]) mean = f_gaus.GetParameter(1) mean_err = f_gaus.GetParError(1) width = f_gaus.GetParameter(2) width_err = f_gaus.GetParError(2) gr_mean.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, mean) gr_mean.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, mean_err) gr_width.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, width) gr_width.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, width_err) m = f_gaus.Integral(0.97, 1.03) N = f_gaus.GetParameter(0) * math.sqrt( 2 * math.pi) * f_gaus.GetParameter(2) print m, N gr_eff.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N) gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, eff_err(m, N)) gr_mean.SetMarkerStyle(20) gr_mean.SetMarkerSize(1.5) gr_mean.SetMarkerColor(632) gr_width.SetMarkerStyle(20) gr_width.SetMarkerSize(1.5) gr_width.SetMarkerColor(600) gr_eff.SetMarkerStyle(20) gr_eff.SetMarkerSize(1.5) gr_eff.SetMarkerColor(600) hx = histo(0, 10, -0.2, 1.2, "p_{T}(GeV/c)", "Mean/Width") canvas_file = self.__canvas__ canvas_file.cd() c1 = TCanvas("c1", "c1", 1000, 800) hx.GetYaxis().SetTitle("1/#beta cut efficency") hx.Draw() gr_width.Draw("psame") gr_mean.Draw("psame") c1.Write("tof") c1.SaveAs("tof.png") c2 = TCanvas("c2", "c2", 1000, 800) hx.Draw() gr_eff.Draw("psame") c2.Write("tof_cut_eff") c2.SaveAs("tof_cut.png")
def plotPDSummary(self, strDetName): #Create the Plot - Average gDet_AvgPD = TGraphErrors(len(self.PD_AVG_POINTS)) gDet_AvgPD.SetName("g_{0}_PDAvg".format(strDetName)) #Create the Plot - Max Gain gDet_MaxPD = TGraphErrors(len(self.PD_MAX_POINTS)) gDet_MaxPD.SetName("g_{0}_PDMax".format(strDetName)) #Create the Plot - Min Gain gDet_MinPD = TGraphErrors(len(self.PD_MIN_POINTS)) gDet_MinPD.SetName("g_" + strDetName + "_PDMin") gDet_MinPD.SetName("g_{0}_PDMin".format(strDetName)) #Set the points for i in range(0, len(self.PD_AVG_POINTS)): #Average gDet_AvgPD.SetPoint(i, self.GAIN_AVG_POINTS[i], self.PD_AVG_POINTS[i]) gDet_AvgPD.SetPointError(i, self.GAIN_STDDEV_POINTS[i], self.PD_STDDEV_POINTS[i]) #Max gDet_MaxPD.SetPoint(i, self.GAIN_AVG_POINTS[i], self.PD_MAX_POINTS[i]) #Min gDet_MinPD.SetPoint(i, self.GAIN_AVG_POINTS[i], self.PD_MIN_POINTS[i]) #Draw canv_AvgPD = TCanvas("canv_{0}_PDAvg".format(strDetName), "{0} Discharge Probability".format(strDetName), 600, 600) canv_AvgPD.cd() canv_AvgPD.cd().SetLogx() canv_AvgPD.cd().SetLogy() gDet_AvgPD.GetXaxis().SetTitle("#LT Effective Gain #GT") gDet_AvgPD.GetYaxis().SetTitle("Discharge Probability P_{D}") gDet_AvgPD.GetYaxis().SetRangeUser(1e-11, 1e-6) gDet_AvgPD.SetMarkerStyle(21) gDet_AvgPD.Draw("AP") gDet_MaxPD.Draw("sameL") gDet_MinPD.Draw("sameL") #Write dir_Summary = self.FILE_OUT.GetDirectory("Summary") dir_Summary.cd() canv_AvgPD.Write() gDet_AvgPD.Write() gDet_MaxPD.Write() gDet_MinPD.Write() return
def plotGainSummary(self, strDetName): #Create the Plot - Average gDet_AvgEffGain = TGraphErrors( len(self.GAIN_AVG_POINTS) ) #gDet_AvgEffGain.SetName("g_" + strDetName + "_EffGainAvg") gDet_AvgEffGain.SetName("g_{0}_EffGainAvg".format(strDetName)) #Create the Plot - Max Gain gDet_MaxEffGain = TGraphErrors( len(self.GAIN_MAX_POINTS) ) #gDet_MaxEffGain.SetName("g_" + strDetName + "_EffGainMax") gDet_MaxEffGain.SetName("g_{0}_EffGainMax".format(strDetName)) #Create the Plot - Min Gain gDet_MinEffGain = TGraphErrors( len(self.GAIN_MIN_POINTS) ) #gDet_MinEffGain.SetName("g_" + strDetName + "_EffGainMin") gDet_MinEffGain.SetName("g_{0}_EffGainMin".format(strDetName)) #Set the points for i in range(0, len(self.GAIN_AVG_POINTS) ): #Average gDet_AvgEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_AVG_POINTS[i]) gDet_AvgEffGain.SetPointError(i,0,self.GAIN_STDDEV_POINTS[i]) #Max gDet_MaxEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_MAX_POINTS[i]) #Min gDet_MinEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_MIN_POINTS[i]) #Draw #canv_AvgEffGain = TCanvas("canv_" + strDetName + "_EffGainAvg",strDetName + " Average Effective Gain",600,600) canv_AvgEffGain = TCanvas("canv_{0}_EffGainAvg".format(strDetName),"{0} Average Effective Gain".format(strDetName),600,600) canv_AvgEffGain.cd() canv_AvgEffGain.cd().SetLogy() gDet_AvgEffGain.GetXaxis().SetTitle("HV") gDet_AvgEffGain.GetYaxis().SetTitle("#LT Effective Gain #GT") gDet_AvgEffGain.GetYaxis().SetRangeUser(1e2,1e6) gDet_AvgEffGain.SetMarkerStyle(21) gDet_AvgEffGain.Draw("AP") gDet_MaxEffGain.Draw("sameL") gDet_MinEffGain.Draw("sameL") #Write dir_Summary = self.FILE_OUT.mkdir("Summary") dir_Summary.cd() canv_AvgEffGain.Write() gDet_AvgEffGain.Write() gDet_MaxEffGain.Write() gDet_MinEffGain.Write() return
def create_resolutiongraph(n, energies, sigmasmeans, energieserrors, sigmasmeanserrors, graphname): """Function to perform ROOT graphs of resolutions""" #How many points n = int(n) TGraphresolution = TGraphErrors(n, energies, sigmasmeans, energieserrors, sigmasmeanserrors) #Draw + DrawOptions, Fit + parameter estimation Style = gStyle Style.SetOptFit() XAxis = TGraphresolution.GetXaxis() #TGraphresolution TGraphresolution.SetMarkerColor(4) TGraphresolution.SetMarkerStyle(20) TGraphresolution.SetMarkerSize(2) XAxis.SetTitle("Energy (GeV)") YAxis = TGraphresolution.GetYaxis() YAxis.SetTitle("Sigma/Mean") resolutionfit = TF1("resolutionfit", '([0]/((x)**0.5))+[1]', 0, max(energies)) #somma non quadratura TGraphresolution.Fit("resolutionfit") a = resolutionfit.GetParameter(0) b = resolutionfit.GetParameter(1) TGraphresolution.Draw("AP") gPad.SaveAs(graphname) gPad.Close() return a, b
def compareEEC( filename="sjm91_all.root", datafilename="../EECMC/share/OPAL/data.dat" ): f= TFile( filename ) ao= createAnalysisObservable( f, "EEC" ) tokens= datafilename.split( "/" ) exp= tokens[3] plotoptions= { "xmin": 0.0, "xmax": 3.14159, "ymin": 0.05, "ymax": 5.0, "markerStyle": 20, "markerSize": 0.5, "drawas": "3", "fillcolor": 6, "title": "EEC "+exp, "xlabel": "\chi\ [rad.]", "ylabel": "1/\sigma d\Sigma/d\chi", "logy": 1 } tgest, tgesy= ao.plot( plotoptions ) lines= [ line.rstrip( '\n' ) for line in open( datafilename ) ] n= len( lines ) points= TVectorD( n ) values= TVectorD( n ) errors= TVectorD( n ) perrs= TVectorD(n) grad2rad= 3.14159/180.0 for i in range( n ): line= (lines[i]).split() points[i]= float(line[0])*grad2rad values[i]= float(line[3]) errors[i]= float(line[4]) perrs[i]= 0.0 datatge= TGraphErrors( points, values, perrs, errors ) datatge.SetMarkerStyle( 20 ) datatge.SetMarkerSize( 0.5 ) datatge.Draw( "psame" ) legend= TLegend( 0.2, 0.7, 0.5, 0.85 ) datatge.SetName( "datatge" ); tgesy.SetName( "tgesy" ) legend.AddEntry( "datatge", exp+" data", "pe" ) legend.AddEntry( "tgesy", "OPAL "+filename, "f" ) legend.Draw() return
def test1a(fname='data/fpgaLin/dp02a_Mar04C1a_data_0.root'): add_fit_menu() t1 = TChain('reco') t1.Add(fname) t1.Show(0) V = 200 gr1 = TGraphErrors() for i in range(19): c1.cd(i+1) lt.DrawLatexNDC(0.2,0.4,'Ch={0:d}'.format(i)) t1.Draw('Q[{0:d}]>>hx{0:d}'.format(i),'tID!=7') hx = gPad.GetPrimitive('hx{0:d}'.format(i)) hx.Fit('gaus') fun1 = hx.GetFunction('gaus') encN = 7.40*V*fun1.GetParameter(2)/fun1.GetParameter(1) encE = 7.40*V*fun1.GetParError(2)/fun1.GetParameter(1) gr1.SetPoint(i,i,encN) gr1.SetPointError(i,0,encE) c1.cd(20) gr1.Draw('AP') c1.cd() waitRootCmdX()
def write(self, setup): #Rescaling to efficiency normalisation = 1/self.histogram.GetBinContent(1) #Rescaling everything to have rates self.histogram.Scale(normalisation) efficiencyPlot = TGraphErrors(self.histogram) efficiencyPlot.SetName(self.cfg_ana.plot_name+"_errors") efficiencyPlot.SetTitle(self.cfg_ana.plot_title) for index in xrange(0, len(efficiencyPlot.GetX())): efficiencyPlot.SetPointError(index, efficiencyPlot.GetEX()[index], sqrt(efficiencyPlot.GetY()[index] * normalisation) ) c1 = TCanvas ("canvas_" + self.cfg_ana.plot_name, self.cfg_ana.plot_title, 600, 600) c1.SetGridx() c1.SetGridy() efficiencyPlot.Draw("AP") c1.Update() c1.Write() c1.Print(self.cfg_ana.plot_name + ".svg", "svg") efficiencyPlot.Write()
class CorrezioneAreaLunghezza(LettoreFileDebye): """Legge il file con Volt, corrente, Rt, Rd e restituisce temperature, resistenze ed errori per l'analisi della temperatura di Debye. Inserita correzione al primo ordine per la dipendenza della sezione e lunghezza del filo dalla temperatura""" def __init__(self, *args, **kwargs): super(CorrezioneAreaLunghezza, self).__init__(*args, **kwargs) def draw(self, output_file): self.output_filename = output_file with open(output_file, "w") as out_file: for T, sigma_T, R, sigma_R in zip( self.T_i, self.sigma_Ti, self.R_i, self.sigma_i): out_line = [T, R * (1 + coefficiente_correttivo(T)), sigma_T, sigma_R, "\n"] out_line = [str(x) for x in out_line] out_line = " ".join(out_line) out_file.write(out_line) style.cd() self.canvas = TCanvas("temperatura_resistenza_can", "temperatura_resistenza_can") self.graph = TGraphErrors(output_file) self.graph.SetTitle("Resistenza del campione;T#[]{K};R#[]{#Omega}") self.graph.Draw("ap")
def CompareToys(MwValuemT, MwValuemTStat): print(len(MwValuemT), len(MwValuemTStat)) n = len(MwValuemT) x, y = array('d'), array('d') ex, ey = array('d'), array('d') for i in range(0, n): x.append(i + 1) ex.append(0) y.append(MwValuemT[i]) ey.append(MwValuemTStat[i]) gr = TGraphErrors(n, x, y, ex, ey) gr.Draw("P") gr.SetLineWidth(0) gr.SetMarkerStyle(20) gr.SetMarkerSize(1) xax = gr.GetXaxis() for i in range(0, n): binIndex = xax.FindBin(i) xax.SetBinLabel(binIndex, "toys") Output = ROOT.TFile.Open("Matrix.root", "RECREATE") gr.Write("gr")
def make1DSummaryPlot(binned_mw, bins, channel, variable, treeSuffix): nBins = len(bins) xValues, yValues = array('d'), array('d') xErrors, yErrors = array('d'), array('d') for bin in bins: mW = binned_mw[bin] lowBinEdge = bins[bin][0] highBinEdge = bins[bin][1] binWidth = (bins[bin][1] - bins[bin][0]) / 2 binCentre = bins[bin][1] - binWidth if bin.split('_')[-1] == 'inf': binCentre = lowBinEdge * 1.1 binWidth = lowBinEdge * 0.1 # print binCentre # print bin,bins[bin],mW.getVal(),mW.getError() xValues.append(binCentre) yValues.append(mW.getVal()) xErrors.append(binWidth) yErrors.append(mW.getError()) c = TCanvas('c1', 'A Simple Graph Example', 200, 10, 700, 500) gr = TGraphErrors(nBins, xValues, yValues, xErrors, yErrors) gr.SetMarkerColor(4) gr.SetMarkerStyle(3) gr.GetXaxis().SetTitle('X title') gr.GetYaxis().SetTitle('Y title') gr.SetMinimum(75) gr.SetMaximum(85) gr.Draw('AP') c.Update() outputDir = 'plots/WStudies/%s%s/%s' % (channel, treeSuffix, variable) c.Print('%s/Summary.pdf' % outputDir)
def draw_neta_cut_eff(self, cent_low, cent_high): cent_bin1 = [0, 4, 7] cent_bin2 = [3, 6, 8] p_bin1 = [ 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5 ] p_bin2 = [ 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 ] gr_eff = TGraphErrors() for i in range(0, len(p_bin1)): mn = self.draw_neta_cut(cent_low, cent_high, p_bin1[i], p_bin2[i]) m = mn[0] N = mn[1] gr_eff.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N) gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, eff_err(m, N)) gr_eff.SetMarkerStyle(20) gr_eff.SetMarkerSize(1.5) gr_eff.SetMarkerColor(600) hx = histo(0, 8, -0.2, 1.2, "p_{T}(GeV/c)", "n#eta cut efficiency") canvas_file = self.__canvas__ canvas_file.cd() c2 = TCanvas("c2", "c2", 1000, 800) hx.Draw() gr_eff.Draw("psame") c2.Write("neta_cut_eff") c2.SaveAs("neta_cut.png")
def Ratio(histo1,histo2, recorded, title): #gSystem.Exec("mkdir -p ZPlots") can1 = makeCMSCanvas(str(random.random()),"mult vs lumi ",900,700) lumi = [] lumi_err = [] ratio = [] ratio_err = [] sumLumi = 0. for i in range(0,len(recorded)): sumLumi += float(recorded[i]) lumi.append(sumLumi - float(recorded[i])/2) lumi_err.append(float(recorded[i])/2) ratio.append(histo1[i].GetEntries()/histo2[i].GetEntries()) ratio_err.append(0) graph1 = TGraphErrors(len(recorded),array('d',lumi),array('d',ratio),array('d',lumi_err),array('d',ratio_err)) can1.cd() graph1.SetTitle("") graph1.GetXaxis().SetTitle("Lumi [fb^{-1}]") graph1.GetYaxis().SetTitle("e^{+}e^{-}/#mu^{+}#mu^{-}") graph1.SetMarkerStyle(20) graph1.SetMarkerSize(1) graph1.Draw("AP") printLumiPrelOut(can1) can1.SaveAs("ZPlots/Z_ratio_"+title+".pdf") can1.SaveAs("ZPlots/Z_ratio_"+title+".png") return;
def ZMultVsLumi(histo, recorded, outputDir, title): #gSystem.Exec("mkdir -p ZPlots") can1 = makeCMSCanvas(str(random.random()),"mult vs lumi ",900,700) lumi = [] lumi_err = [] mult = [] mult_err = [] sumLumi = 0. for i in range(0,len(recorded)): sumLumi += float(recorded[i]) lumi.append(sumLumi - float(recorded[i])/2) lumi_err.append(float(recorded[i])/2) mult.append(histo[i].GetEntries()/float(recorded[i])) mult_err.append(math.sqrt(histo[i].GetEntries()/float(recorded[i]))) graph1 = TGraphErrors(len(lumi),array('d',lumi),array('d',mult),array('d',lumi_err),array('d',mult_err)) can1.cd() graph1.SetTitle("") graph1.GetXaxis().SetTitle("Lumi [fb^{-1}]") graph1.GetYaxis().SetTitle("#Z / fb^{-1}") graph1.SetMarkerStyle(20) graph1.SetMarkerSize(1) graph1.Draw("AP") printLumiPrelOut(can1) can1.SaveAs(str(outputDir) + "/Z_multiplicity_"+title+".pdf") can1.SaveAs(str(outputDir) + "/Z_multiplicity_"+title+".png") return graph1;
class GraphicsObject: def __init__(self, data, name): self._data = data self._graphics = None self._style = Style(kBlack, 20) self._plotrange = {"Min": None, "Max": None} self._name = name def SetPlotRange(self, min, max): self._plotrange[min] = min self._plotrange[max] = max def SetStyle(self, style): self._style = style def SetName(self, name): self._name = name def GetData(self): return self._data def GetGraphics(self): return self._graphics def GetStyle(self): return self._style def Draw(self): if not self._graphics: self._graphics = TGraphErrors() np = 0 for bin in range(1, self._data.GetXaxis().GetNbins() + 1): if self._plotrange["Min"] and self._data.GetXaxis( ).GetBinLowEdge(bin) < self._plotrange["Min"]: continue if self._plotrange["Max"] and self._data.GetXaxis( ).GetBinUpEdge(bin) > self._plotrange["Max"]: break self._graphics.SetPoint( np, self._data.GetXaxis().GetBinCenter(bin), self._data.GetBinContent(bin)) self._graphics.SetPointError( np, self._data.GetXaxis().GetBinWidth(bin) / 2., self._data.GetBinError(bin)) np = np + 1 self._graphics.SetMarkerColor(self._style.GetColor()) self._graphics.SetLineColor(self._style.GetColor()) self._graphics.SetMarkerStyle(self._style.GetMarker()) self._graphics.Draw("epsame") def AddToLegend(self, legend, title=None): if self._graphics: tit = self._name if title: tit = title legend.AddEntry(self._graphics, tit, "lep")
class LettoreFileDebye(object): """Legge il file con Volt, corrente, Rt, Rd e restituisce temperature, resistenze ed errori per l'analisi della temperatura di Debye""" def __init__(self, file_name): super(LettoreFileDebye, self).__init__() self.T_i = [] self.sigma_Ti = [] self.R_i = [] self.sigma_i = [] with open(file_name) as input_file: for line in input_file: if "//" in line: continue V, I, p_t, p_d = [float(x) for x in line.split()] PT = PotenziometroTemperatura(calibrazione_potenziometro_T, tabella_temperatura, p_t) PD = PotenziometroResistenza(calibrazione_potenziometro_D, p_d) self.T_i.append(PT.T) self.sigma_Ti.append(PT.sigma_T) self.R_i.append(PD.R) self.sigma_i.append(PD.sigma_R) def draw(self, output_file): self.output_filename = output_file with open(output_file, "w") as out_file: for T, sigma_T, R, sigma_R in zip(self.T_i, self.sigma_Ti, self.R_i, self.sigma_i): out_line = [T, R, sigma_T, sigma_R, "\n"] out_line = [str(x) for x in out_line] out_line = " ".join(out_line) out_file.write(out_line) style.cd() self.canvas = TCanvas("temperatura_resistenza_can", "temperatura_resistenza_can") self.graph = TGraphErrors(output_file) self.graph.SetTitle("Resistenza del campione;T#[]{K};R#[]{#Omega}") self.graph.Draw("ap") def tabella_latex(self, output_file): with open(output_file, "w") as out_file: out_file.write("\\begin{tabular}{r@{ $\\pm$ }lr@{ $\\pm$ }l|cc}\n") out_file.write( "\\multicolumn{2}{c}{$\\unit[T]{[K]}$} &\\multicolumn{2}{c}{$\\unit[R]{[\\ohm]}$} & $\\sigma_R/ R$ [\%] & $\\Delta_D / D$ [\%] \\\\\n " ) out_file.write("\\hline\n") for T, sigma_T, R, sigma_R in zip(self.T_i, self.sigma_Ti, self.R_i, self.sigma_i): line = [ T, sigma_T, R, sigma_R, sigma_R / R * 1e2, alpha * (T0 - T) * 1e2 ] out_file.write( "{0[0]:.1f} & {0[1]:.1f} & {0[2]:.2f} & {0[3]:.2f} & {0[4]:.2f} & {0[5]:.2f} \\\\ \n " .format(line)) out_file.write("\\end{tabular}") def save_as(self, name): self.canvas.SaveAs(name)
def plot( self, plotoptions, opt="?" ): vx= array( "d", self.aostand.getPointsCenter() ) values= self.values sterrs= self.sterrs if "m" in opt: print "AnalysisObservable::plot: use errors from error matrix" sterrs= array( "d", self.aostand.getErrors( "m" ) ) syerrs= self.syerrs npoints= len(vx) if "xshift" in plotoptions: for i in range(npoints): vx[i]+= plotoptions["xshift"] vex= array( "d", npoints*[0.0] ) tgest= TGraphErrors( npoints, vx, values, vex, sterrs ) toterrs= np.sqrt( np.add( np.square( sterrs ), np.square( syerrs ) ) ) tgesy= TGraphErrors( npoints, vx, values, vex, toterrs ) tgesy.SetMarkerStyle( plotoptions["markerStyle"] ) tgesy.SetMarkerSize( plotoptions["markerSize"] ) drawas= plotoptions["drawas"] if "drawas" in plotoptions else "p" tgesy.SetName( self.obs ) if "fillcolor" in plotoptions: tgesy.SetFillColor(plotoptions["fillcolor"]) tgest.SetFillColor(plotoptions["fillcolor"]) if "s" in opt: tgesy.Draw( "psame" ) else: if "title" in plotoptions: tgesy.SetTitle( plotoptions["title"] ) else: tgesy.SetTitle( self.obs ) tgesy.SetMinimum( plotoptions["ymin"] ) tgesy.SetMaximum( plotoptions["ymax"] ) xaxis= tgesy.GetXaxis() xaxis.SetLimits( plotoptions["xmin"], plotoptions["xmax"] ) if "xlabel" in plotoptions: xaxis.SetTitle( plotoptions["xlabel"] ) if "ylabel" in plotoptions: tgesy.GetYaxis().SetTitle( plotoptions["ylabel"] ) tgesy.Draw( "a"+drawas ) optlogx= plotoptions["logx"] if "logx" in plotoptions else 0 gPad.SetLogx( optlogx ) optlogy= plotoptions["logy"] if "logy" in plotoptions else 0 gPad.SetLogy( optlogy ) tgest.Draw( "same"+drawas ) return tgest, tgesy
def GraphVsLumi(result, outputDir, title): #gSystem.Exec("mkdir -p ZPlots") can1 = makeCMSCanvas(str(random.random()), "mean vs lumi ", 900, 700) can2 = makeCMSCanvas(str(random.random()), "width vs lumi ", 900, 700) lumi = [] lumi_err = [] mean = [] mean_err = [] width = [] width_err = [] sumLumi = 0. for i in range(0, len(result)): sumLumi += float(result[i].lumi) lumi.append(sumLumi - float(result[i].lumi) / 2) lumi_err.append(float(result[i].lumi) / 2) mean.append(result[i].mean) mean_err.append(result[i].mean_err) width.append(result[i].width) width_err.append(result[i].width_err) graph1 = TGraphErrors(len(result), array('d', lumi), array('d', mean), array('d', lumi_err), array('d', mean_err)) graph2 = TGraphErrors(len(result), array('d', lumi), array('d', width), array('d', lumi_err), array('d', width_err)) can1.cd() graph1.SetTitle("") graph1.GetXaxis().SetTitle("Lumi [fb^{-1}]") graph1.GetYaxis().SetTitle("Mass [GeV]") graph1.SetMarkerStyle(20) graph1.SetMarkerSize(1) graph1.Draw("AP") printLumiPrelOut(can1) can1.SaveAs(str(outputDir) + "/" + title + "_mean.pdf") can1.SaveAs(str(outputDir) + "/" + title + "_mean.png") can2.cd() graph2.SetTitle("") graph2.GetXaxis().SetTitle("Lumi [fb^{-1}]") graph2.GetYaxis().SetTitle("Width [GeV]") graph2.SetMarkerStyle(20) graph2.SetMarkerSize(1) graph2.Draw("AP") printLumiPrelOut(can2) can2.SaveAs(str(outputDir) + "/" + title + "_width.pdf") can2.SaveAs(str(outputDir) + "/" + title + "_width.png") return graph1, graph2
def MeanRMSVsLumi(histo, recorded, outputDir, title): can1 = makeCMSCanvas(str(random.random()), "mean vs lumi ", 900, 700) can2 = makeCMSCanvas(str(random.random()), "RMS vs lumi ", 900, 700) lumi = [] lumi_err = [] mean = [] mean_err = [] RMS = [] RMS_err = [] sumLumi = 0. for i in range(0, len(recorded)): sumLumi += float(recorded[i]) lumi.append(sumLumi - float(recorded[i]) / 2) lumi_err.append(float(recorded[i]) / 2) mean.append(histo[i].GetMean()) mean_err.append(0.) #dont put error on ISO and SIP histo[i].GetRMS() RMS.append(histo[i].GetRMS()) RMS_err.append(0.) graph1 = TGraphErrors(len(recorded), array('d', lumi), array('d', mean), array('d', lumi_err), array('d', mean_err)) graph2 = TGraphErrors(len(recorded), array('d', lumi), array('d', RMS), array('d', lumi_err), array('d', RMS_err)) can1.cd() graph1.SetTitle("") graph1.GetXaxis().SetTitle("Lumi [fb^{-1}]") graph1.GetYaxis().SetTitle(" ") graph1.SetMarkerStyle(20) graph1.SetMarkerSize(1) graph1.Draw("AP") printLumiPrelOut(can1) can1.SaveAs(str(outputDir) + "/" + title + "_mean.pdf") can1.SaveAs(str(outputDir) + "/" + title + "_mean.png") can2.cd() graph2.SetTitle("") graph2.GetXaxis().SetTitle(" ") graph2.GetYaxis().SetTitle("Width [GeV]") graph2.SetMarkerStyle(20) graph2.SetMarkerSize(1) graph2.Draw("AP") printLumiPrelOut(can2) can2.SaveAs(str(outputDir) + "/" + title + "_width.pdf") can2.SaveAs(str(outputDir) + "/" + title + "_width.png") return graph1, graph2
def plotGraph(self, x='vv', y='acc'): ''' Plot a graph with specified quantities on x and y axes , and saves the graph ''' if (x not in self.quantities.keys()) or (y not in self.quantities.keys()): raise RuntimeError('selected quantities not available, available quantities are: \n{}'.format(self.quantities.keys())) xq = self.quantities[x] yq = self.quantities[y] #graph = TGraphAsymmErrors() #graph = TGraph() graph = TGraphErrors() for i,s in enumerate(self.samples): graph.SetPoint(i,getattr(s, xq.name), getattr(s, yq.name) ) #if xq.err: # graph.SetPointEXhigh(i, getattr(s, xq.name+'_errup')) # errup errdn # graph.SetPointEXlow (i, getattr(s, xq.name+'_errdn')) if yq.err: graph.SetPointError(i, 0, getattr(s, yq.name+'_errup')) # graph.SetPointEYhigh(i, getattr(s, yq.name+'_errup')) # graph.SetPointEYlow (i, getattr(s, yq.name+'_errdn')) c = TCanvas() graph.SetLineWidth(2) graph.SetMarkerStyle(22) graph.SetTitle(';{x};{y}'.format(y=yq.title,x=xq.title)) graph.Draw('APLE') if yq.forceRange: graph.SetMinimum(yq.Range[0]) graph.SetMaximum(yq.Range[1]) gPad.Modified() gPad.Update() if yq.name=='expNevts': line = TLine(gPad.GetUxmin(),3,gPad.GetUxmax(),3) line.SetLineColor(ROOT.kBlue) line.Draw('same') #graph.SetMinimum(0.01) #graph.SetMaximum(1E06) if xq.log: c.SetLogx() if yq.log: c.SetLogy() c.SetGridx() c.SetGridy() c.SaveAs('./plots/{}{}/{}_{}VS{}.pdf'.format(self.label,suffix,self.name,yq.name,xq.name)) c.SaveAs('./plots/{}{}/{}_{}VS{}.C'.format(self.label,suffix,self.name,yq.name,xq.name)) c.SaveAs('./plots/{}{}/{}_{}VS{}.png'.format(self.label,suffix,self.name,yq.name,xq.name)) self.graphs['{}VS{}'.format(yq.name,xq.name)] = graph # add the graph container for memory? graph_saver.append(graph)
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig, lower1sig, upper2sig, lower2sig): channel = np.array( [3. * nchannels - 1.5 - 3. * i for i in range(0, nchannels)]) ey = np.array([0.8 for i in range(0, nchannels)]) zero = np.zeros(nchannels) gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig, upper1sig, ey, ey) gexpect1sig.SetFillColor(kGreen) gexpect1sig.SetLineWidth(2) gexpect1sig.SetLineStyle(2) gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig, upper2sig, ey, ey) gexpect2sig.SetFillColor(kYellow) gexpect2sig.SetLineWidth(2) gexpect2sig.SetLineStyle(2) gexpect2sig.Draw("2") gexpect1sig.Draw("2") gobs = TGraphErrors(nchannels, obs, channel, zero, ey) gobs.SetMarkerStyle(21) gobs.SetMarkerSize(1.5) gobs.SetLineWidth(2) gobs.Draw("pz") # dashed line at median expected limits l = TLine() l.SetLineStyle(2) l.SetLineWidth(2) for bin in range(nchannels): l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin], channel[bin] + ey[bin]) # line to separate individual and combined limits l.SetLineStyle(1) l.SetLineWidth(1) l.DrawLine(xmin, 0, xmax, 0) # legend x1 = gStyle.GetPadLeftMargin() + 0.01 y2 = 1 - gStyle.GetPadTopMargin() - 0.01 leg = TLegend(x1, y2 - 0.17, x1 + 0.25, y2) leg.SetFillColor(4000) leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL") leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL") leg.AddEntry(gobs, "Observed", "pl") leg.Draw() return gobs, gexpect1sig, gexpect2sig, leg
def compareY23d( filename="sjm91_all.root", mtffilename=None, opt="m" ): if mtffilename == None: ecm= ecmFromFilename( filename ) mtffilename= "mtford-y23d"+ecm+".txt" arrays= ascii2arrays( mtffilename ) mtfordpointsl= arrays[0] mtfordpointsr= arrays[1] mtfordpoints= np.divide( np.add( arrays[0], arrays[1] ), 2.0 ) mtfordvalues= arrays[2] mtfordsterrs= arrays[3] mtfordsyerrs= arrays[4] mtforderrs= np.sqrt( np.add( np.square( mtfordsterrs ), np.square( mtfordsyerrs ) ) ) if filename=="sjm133.root": f1= TFile( "sjm130.root" ) ao1= createAnalysisObservable( f1, "durhamymerge23" ) f2= TFile( "sjm136.root" ) ao2= createAnalysisObservable( f2, "durhamymerge23" ) ao= combineAnalysisObservables( [ ao1, ao2 ] ) else: f= TFile( filename ) ao= createAnalysisObservable( f, "durhamymerge23" ) npoints= len( mtfordpoints ) vex= array( "d", npoints*[0.0] ) tgest= TGraphErrors( npoints, mtfordpoints, mtfordvalues, vex, mtfordsterrs ) tgetot= TGraphErrors( npoints, mtfordpoints, mtfordvalues, vex, mtforderrs ) plotoptions= { "xmin": 0.0003, "xmax": 0.5, "ymin": 0.5, "ymax": 500.0, "markerStyle": 20, "markerSize": 0.75, "title": "Durham y23 "+filename, "xlabel": "y_{23}", "ylabel": "1/\sigma d\sigma/dy_{23}", "logx":1, "logy":1 } ao.plot( plotoptions, opt ) tgetot.SetMarkerStyle( 24 ) tgetot.SetMarkerSize( 1.25 ) tgetot.SetName( "mtford" ) tgetot.Draw( "psame" ) tgest.Draw( "psame" ) tl= TLegend( 0.7, 0.9, 0.7, 0.9 ) tl.AddEntry( "mtford", "M.T. Ford thesis", "ep" ) tl.AddEntry( "durhamymerge23", "sjmanalysis", "ep" ) tl.Draw() return
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig, lower1sig, upper2sig, lower2sig): channel = np.array( [nchannels - 1.5 - float(i) for i in range(0, nchannels)]) ey = np.full(nchannels, 0.494) zero = np.zeros(nchannels) gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig, upper1sig, ey, ey) gexpect1sig.SetFillColor(kGreen) gexpect1sig.SetLineWidth(2) gexpect1sig.SetLineStyle(2) gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig, upper2sig, ey, ey) gexpect2sig.SetFillColor(kYellow) gexpect2sig.SetLineWidth(2) gexpect2sig.SetLineStyle(2) gexpect2sig.Draw("2") gexpect1sig.Draw("2") gobs = TGraphErrors(nchannels, obs, channel, zero, ey) gobs.SetMarkerStyle(21) gobs.SetMarkerSize(1.5) gobs.SetLineWidth(2) gobs.Draw("pz") # dashed line at median expected limits l = TLine() l.SetLineStyle(2) l.SetLineWidth(2) for bin in range(nchannels): l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin], channel[bin] + ey[bin]) # line to separate individual and combined limits l.SetLineStyle(1) l.SetLineWidth(1) l.DrawLine(xmin, 0, xmax, 0) # legend leg = TLegend(0.32, 0.73, 0.55, 0.9) leg.SetFillColor(4000) leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL") leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL") leg.AddEntry(gobs, "Observed", "pl") leg.Draw() return gobs, gexpect1sig, gexpect2sig, leg
def plot_correction( h2, slope, offset, x_points, y_points, error_points, outname, xlabel='', etBinIdx=None, etaBinIdx=None, etBins=None, etaBins=None, label='Internal', ref_value=None, pd_value=None, palette=kBlackBody): def toStrBin(etlist = None, etalist = None, etidx = None, etaidx = None): if etlist and etidx is not None: etlist=copy(etlist) if etlist[-1]>9999: etlist[-1]='#infty' binEt = (str(etlist[etidx]) + ' < E_{T} [GeV] < ' + str(etlist[etidx+1]) if etidx+1 < len(etlist) else 'E_{T} > ' + str(etlist[etidx]) + ' GeV') return binEt if etalist and etaidx is not None: binEta = (str(etalist[etaidx]) + ' < |#eta| < ' + str(etalist[etaidx+1]) if etaidx+1 < len(etalist) else str(etalist[etaidx]) + ' <|#eta| < 2.47') return binEta canvas = TCanvas("canvas","canvas",500,500) rpl.set_figure(canvas) gStyle.SetPalette(palette) canvas.SetRightMargin(0.15) canvas.SetTopMargin(0.15) canvas.SetLogz() h2.GetXaxis().SetTitle('Neural Network output (Discriminant)') h2.GetYaxis().SetTitle(xlabel) h2.GetZaxis().SetTitle('Count') h2.Draw('colz') g = TGraphErrors(len(x_points), array.array('d',x_points), array.array('d',y_points), array.array('d',error_points), array.array('d',[0]*len(x_points))) g.SetMarkerColor(kBlue) g.SetMarkerStyle(8) g.SetMarkerSize(1) g.Draw("P same") line = TLine(slope*h2.GetYaxis().GetXmin()+offset,h2.GetYaxis().GetXmin(), slope*h2.GetYaxis().GetXmax()+offset, h2.GetYaxis().GetXmax()) line.SetLineColor(kBlack) line.SetLineWidth(2) line.Draw() # Add text labels into the canvas text = toStrBin(etlist=etBins, etidx=etBinIdx) text+= ', '+toStrBin(etalist=etaBins, etaidx=etaBinIdx) if ref_value and pd_value: text+=', P_{D} = %1.2f (%1.2f) [%%]'%(pd_value*100, ref_value*100) rpl.add_text(0.15, 0.885, text, textsize=.03) rpl.set_atlas_label(0.15, 0.94, label) rpl.format_canvas_axes(XLabelSize=16, YLabelSize=16, XTitleOffset=0.87, ZLabelSize=16,ZTitleSize=16, YTitleOffset=0.87, ZTitleOffset=1.1) canvas.SaveAs(outname)
def compareThrust( filename="sjm91_all.root", mtffilename=None ): if mtffilename == None: ecm= ecmFromFilename( filename ) mtffilename= "mtford-thrust"+ecm+".txt" arrays= ascii2arrays( mtffilename ) mtfordvalues= arrays[2] mtfordsterrs= arrays[3] mtfordsyerrs= arrays[4] mtforderrs= np.sqrt( np.add( np.square( mtfordsterrs ), np.square( mtfordsyerrs ) ) ) if filename=="sjm133.root": # f1= TFile( "sjm130.root" ) # aothrust1= createAnalysisObservable( f1, "thrust" ) # f2= TFile( "sjm136.root" ) # aothrust2= createAnalysisObservable( f2, "thrust" ) # aothrust= combineAnalysisObservables( [ aothrust1, aothrust2 ] ) aothrust= createCombineAnalysisObservables( ( "sjm130.root", "sjm136.root" ), "lepthrust" ) else: f= TFile( filename ) aothrust= createAnalysisObservable( f, "lepthrust" ) vx= array( "d", aothrust.aostand.getPointsCenter() ) npoints= len(vx)-1 vex= array( "d", npoints*[0.0] ) tgethrustst= TGraphErrors( npoints, vx, mtfordvalues, vex, mtfordsterrs ) tgethrusttot= TGraphErrors( npoints, vx, mtfordvalues, vex, mtforderrs ) plotoptions= { "xmin": 0.0, "xmax": 0.5, "ymin": 0.2, "ymax": 30, "markerStyle": 20, "markerSize": 0.8, "title": "Thrust "+filename, "logy": 1, "xlabel": "1-T", "ylabel": "1/\sigma d\sigma/d(1-T)" } aothrust.plot( plotoptions ) tgethrusttot.SetMarkerStyle( 24 ) tgethrusttot.SetMarkerSize( 1.25 ) tgethrusttot.SetName( "mtford" ) tgethrusttot.Draw( "psame" ) tgethrustst.Draw( "psame" ) tl= TLegend( 0.6, 0.75, 0.85, 0.9 ) tl.AddEntry( "mtford", "M.T. Ford thesis", "ep" ) tl.AddEntry( "thrust", "sjmanalysis", "ep" ) tl.Draw() return
def draw(mode, patch): if mode == 'DDPIPI' or mode == 'psipp' or mode == 'total': # N = 19 + 6 + 6 + 6 + 6# 19: 703p01, 6: 705, 4: 705 above 4600 N = 37 if mode == 'D1_2420': # N = 19 + 6 + 6 + 6# 18: 703p01, 6: 705, 4: 705 above 4600 N = 23 sys_err = array('f', N * [0]) ecms = array('f', N * [0]) ecms_err = array('f', N * [0]) xs = array('f', N * [0]) xs_err = array('f', N * [0]) path = './txts/xs_' + mode + '_' + patch + '_plot.txt' mbc = TCanvas('mbc', 'mbc', 800, 600) set_canvas_style(mbc) f = open(path, 'r') lines = f.readlines() count = 0 for line in lines: rs = line.rstrip('\n') rs = filter(None, rs.split(' ')) ecms[count] = ECMS(int(float(rs[0]) * 1000)) ecms_err[count] = 0.0022 xs[count] = float(rs[1]) xs_err[count] = float(rs[2]) count += 1 grerr = TGraphErrors(N, ecms, xs, ecms_err, xs_err) xtitle = '#sqrt{s}(GeV)' if mode == 'D1_2420': ytitle = '#sigma(e^{+}e^{-}#rightarrowD_{1}(2420)D)(pb)' if mode == 'psipp': ytitle = '#sigma(e^{+}e^{-}#rightarrow#psi(3770)#pi^{+}#pi^{-})(pb)' if mode == 'DDPIPI': ytitle = '#sigma(e^{+}e^{-}#rightarrowD^{+}D^{-}#pi^{+}#pi^{-})(PHSP)(pb)' if mode == 'total': ytitle = '#sigma(e^{+}e^{-}#rightarrow#pi^{+}#pi^{-}D^{+}D^{-})(pb)' set_graph_style(grerr, xtitle, ytitle) grerr.Draw('AP') mbc.Update() if not os.path.exists('./figs/'): os.makedirs('./figs/') mbc.SaveAs('./figs/xs_' + mode + '_' + patch + '.pdf') raw_input('Enter anything to end...')
def Plot2DHist( th2, slope, offset, x_points, y_points, error_points, outname, xlabel='', etBinIdx=None, etaBinIdx=None, etBins=None,etaBins=None): from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack,TLine,kBird, kOrange,kGray from ROOT import TGraphErrors,TF1,TColor import array def AddTopLabels(can, etlist = None, etalist = None, etidx = None, etaidx = None, logger=None): extraText = [GetAtlasInternalText()] if etlist and etidx is not None: etlist=copy(etlist) if etlist[-1]>9999: etlist[-1]='#infty' binEt = (str(etlist[etidx]) + ' < E_{T} [GeV] < ' + str(etlist[etidx+1]) if etidx+1 < len(etlist) else 'E_{T} > ' + str(etlist[etidx]) + ' GeV') extraText.append(binEt) if etalist and etaidx is not None: binEta = (str(etalist[etaidx]) + ' < #eta < ' + str(etalist[etaidx+1]) if etaidx+1 < len(etalist) else str(etalist[etaidx]) + ' < #eta < 2.47') extraText.append(binEta) DrawText(can,extraText,.14,.68,.35,.93,totalentries=4) gStyle.SetPalette(kBird) drawopt='lpE2' canvas = TCanvas('canvas','canvas',500, 500) canvas.SetRightMargin(0.15) th2.GetXaxis().SetTitle('Neural Network output (Discriminant)') th2.GetYaxis().SetTitle(xlabel) th2.GetZaxis().SetTitle('Count') th2.Draw('colz') canvas.SetLogz() g = TGraphErrors(len(x_points), array.array('d',x_points), array.array('d',y_points), array.array('d',error_points), array.array('d',[0]*len(x_points))) g.SetLineWidth(1) g.SetLineColor(kBlue) g.SetMarkerColor(kBlue) g.Draw("P same") line = TLine(slope*th2.GetYaxis().GetXmin()+offset,th2.GetYaxis().GetXmin(), slope*th2.GetYaxis().GetXmax()+offset, th2.GetYaxis().GetXmax()) line.SetLineColor(kBlack) line.SetLineWidth(2) line.Draw() AddTopLabels( canvas, etlist=etBins,etalist=etaBins,etidx=etBinIdx,etaidx=etaBinIdx) FormatCanvasAxes(canvas, XLabelSize=16, YLabelSize=16, XTitleOffset=0.87, ZLabelSize=14,ZTitleSize=14, YTitleOffset=0.87, ZTitleOffset=1.1) SetAxisLabels(canvas,'Neural Network output (Discriminant)',xlabel) canvas.SaveAs(outname+'.pdf') canvas.SaveAs(outname+'.C') return outname+'.pdf'
def DrawScat(all_, wrong_, DCAs_, title, fname): c = TCanvas("c2", "", 800, 600) # Normal arrays don't work for whatever reason, must be a ROOT thing x, y, ex, ey = array('d'), array('d'), array('d'), array('d') n = len(all_) # if(n != len(wrongHist)): # print("*** Error, hist arrays different length ***") # return for i in range(0, n): frac = wrong_[i].GetEntries() / all_[i].GetEntries() x.append(DCAs_[i]) ex.append(0) y.append(frac) ey.append(0) print( str(DCAs_[i]) + " * " + str(frac) + " * " + str(wrong_[i].GetEntries()) + " * " + str(all_[i].GetEntries())) scat = TGraphErrors(n, x, y, ex, ey) scat.SetTitle(title) scat.GetXaxis().SetTitleSize(.04) scat.GetYaxis().SetTitleSize(.04) scat.GetXaxis().SetTitleOffset(1.1) scat.GetYaxis().SetTitleOffset(1.25) scat.GetXaxis().CenterTitle(1) scat.GetYaxis().CenterTitle(1) # scat.GetYaxis().SetRangeUser(0.086,0.106) scat.GetXaxis().SetRangeUser(-5, 505) scat.GetYaxis().SetMaxDigits(4) #scat.SetMarkerSize(3) #scat.SetLineWidth(3) scat.SetMarkerStyle(20) # Full circle #scat.SetMarkerColor(4) #scat.SetLineColor(4) scat.Draw("AP") c.SaveAs(fname) return