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 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 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 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()
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option("-i", "--inputfile", dest="inputfile") parser.add_option("", "--spline3", action="store_true", dest="spline3", default=False) (options, args) = parser.parse_args() from ROOT import TFile, TGraph, TGraphErrors, NULL import csv with open(options.inputfile) as f: reader = csv.reader(f, delimiter=" ", skipinitialspace=True) rows = list(reader) outfile = TFile("%s.root" % options.inputfile, "RECREATE") g = TGraphErrors(len(rows)) for i, row in enumerate(rows): g.SetPoint(i, float(row[1]) / 1000., float(row[2])) g.SetPointError(i, 0.0, float(row[3])) if options.spline3: g_spline3 = TGraph(10 * (g.GetN() - 1)) x = g.GetX() y = g.GetY() for i in range(g.GetN() - 1): step = (x[i + 1] - x[i]) / 10 for j in range(10): index = 10 * i + j x_ = x[i] + j * step y_ = g.Eval(x_, NULL, "S") g_spline3.SetPoint(index, x_, y_) g_spline3.SetName(options.inputfile) g_spline3.Write() else: g.SetName(options.inputfile) g.Write() outfile.Close()
purGraph = TGraphErrors(len(_NumberOfProtons), _NumberOfProtons, _Purity, _NumberOfProtonsErr, _PurityErr) purGraph.SetMarkerStyle(5) purGraph.SetLineColor(2) purGraph.SetMarkerColor(2) purGraph.SetMarkerSize(2) purGraph.GetXaxis().SetTitle("Mean N Proton") purGraph.GetYaxis().SetTitle("Purity") purGraph.SetTitle("Purity") MyFile = TFile( "effVsPurity_bs" + (str)(beamSpread) + "mrad_geo" + geoName + "_RestrictTracks" + (str)(restrictNTracks) + "_pitch" + (str)(pitch) + ".root", "RECREATE") mg = TMultiGraph() mg.SetTitle("Efficiency and Purity vs nProtons;Mean N Protons; (%)") mg.Add(effGraph, "lp") mg.Add(purGraph, "lp") mg.Draw("a") effGraph.Write() purGraph.Write() mg.Write() legend = TLegend(0.1, 0.7, 0.48, 0.9) legend.AddEntry(effGraph, "Efficiency", "lp") legend.AddEntry(purGraph, "Purity", "lp") legend.Draw("SAME") canvas1.Write("EffVsPurity")
c2.Update() c2.Print(voltage_pdf2) c2.Clear() graph3v = TGraphErrors(n_points, voltage_sq, peak3_array, voltage_error, error3_array) graph3v.SetTitle("peak 3") graph3v.GetXaxis().SetTitle("Voltage^2 (V^2)") graph3v.GetYaxis().SetTitle("Peaks Amp (mV)") graph3v.Draw() c2.Update() c2.Print(voltage_pdf3) # Save graphs to file outputFilev = '%speaks_voltage_plot_%s.root' % (OutputPath, scan) f2 = TFile(outputFilev, "RECREATE") graph1v.Write() graph2v.Write() graph3v.Write() f2.Close() # Temperature plots # Draw graphs temperature_pdf1 = '%sscan%s_peak1_temperature.pdf' % (PDFFilePath, scan) temperature_pdf22 = '%sscan%s_peak2_temperature.pdf' % (PDFFilePath, scan) temperature_pdf3 = '%sscan%s_peak3_temperature.pdf' % (PDFFilePath, scan) temperature_time = '%sscan%s_time_temperature.pdf' % (PDFFilePath, scan) c5 = TCanvas("c5", "Temperature", 200, 10, 700, 500) grapht = TGraphErrors(n_points, temperatures, peak1_array, temperature_error, error1_array) grapht.SetTitle("peak 1") grapht.GetXaxis().SetTitle("Temperature (degree Celsius)") grapht.GetYaxis().SetTitle("Peaks Amp (mV)")
def main(argv): #Usage controls from OptionParser parser_usage = "outputfile.root" parser = OptionParser(usage=parser_usage) (options, args) = parser.parse_args(argv) if (len(args) != 1): parser.print_help() return #Get files, add to another dictionary run_dict = get_run_dict() f_list = {} for runnum in run_dict: print "Run: " + str(runnum) filesmatching = glob.glob(base_directory + "*_" + str(runnum) + "*.root") if (len(filesmatching) != 1): print "ERROR FINDING FILE: " + base_directory + "hd_root_" + str( runnum) + "*.root" print "exiting..." return f = TFile.Open(filesmatching[0]) f_list[runnum] = f rocid_arr = array('i', [31, 32, 34, 35, 37, 38, 40, 41 ]) #These are the rocids associated with BCAL fADC250s slot_arr = array( 'i', [3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16 ]) #These are the slots used for BCAL fADC250s, common to all crates channel_arr = array( 'i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]) #These are the channels used on each slot, common to all slots if (year == "2015"): rocid_arr = array( 'i', [31, 32, 34, 35 ]) #These are the rocids associated with BCAL fADC250s h_layer1_US_RMS_arr = [] h_layer2_US_RMS_arr = [] h_layer3_US_RMS_arr = [] h_layer4_US_RMS_arr = [] h_global_US_RMS_arr = [] h_layer1_DS_RMS_arr = [] h_layer2_DS_RMS_arr = [] h_layer3_DS_RMS_arr = [] h_layer4_DS_RMS_arr = [] h_global_DS_RMS_arr = [] h_global_all_RMS_arr = [] #A whole big bunch of arrays for TGraphErrors mean_layer1_US_RMS = array('d', []) mean_layer2_US_RMS = array('d', []) mean_layer3_US_RMS = array('d', []) mean_layer4_US_RMS = array('d', []) mean_global_US_RMS = array('d', []) mean_layer1_DS_RMS = array('d', []) mean_layer2_DS_RMS = array('d', []) mean_layer3_DS_RMS = array('d', []) mean_layer4_DS_RMS = array('d', []) mean_global_DS_RMS = array('d', []) mean_global_all_RMS = array('d', []) mean_err_layer1_US_RMS = array('d', []) mean_err_layer2_US_RMS = array('d', []) mean_err_layer3_US_RMS = array('d', []) mean_err_layer4_US_RMS = array('d', []) mean_err_global_US_RMS = array('d', []) mean_err_layer1_DS_RMS = array('d', []) mean_err_layer2_DS_RMS = array('d', []) mean_err_layer3_DS_RMS = array('d', []) mean_err_layer4_DS_RMS = array('d', []) mean_err_global_DS_RMS = array('d', []) mean_err_global_all_RMS = array('d', []) bias_arr = array('d', []) bias_err_arr = array('d', []) mean_layer1_diff_RMS = array('d', []) mean_layer2_diff_RMS = array('d', []) mean_layer3_diff_RMS = array('d', []) mean_layer4_diff_RMS = array('d', []) mean_global_diff_RMS = array('d', []) mean_err_layer1_diff_RMS = array('d', []) mean_err_layer2_diff_RMS = array('d', []) mean_err_layer3_diff_RMS = array('d', []) mean_err_layer4_diff_RMS = array('d', []) mean_err_global_diff_RMS = array('d', []) #Loop over all files for curr_run in f_list: print "Runnum: " + str(curr_run) print "bias V: " + str(run_dict[curr_run]) curr_file = f_list[curr_run] curr_bias = run_dict[curr_run] #Create histograms hist_min = 0. hist_max = 4. h_layer1_US_RMS = TH1F("h_layer1_US_RMS_bias" + str(curr_bias), "RMS of US Layer 1 Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_layer2_US_RMS = TH1F("h_layer2_US_RMS_bias" + str(curr_bias), "RMS of US Layer 2 Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_layer3_US_RMS = TH1F("h_layer3_US_RMS_bias" + str(curr_bias), "RMS of US Layer 3 Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_layer4_US_RMS = TH1F("h_layer4_US_RMS_bias" + str(curr_bias), "RMS of US Layer 4 Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_global_US_RMS = TH1F("h_global_US_RMS_bias" + str(curr_bias), "RMS of All US BCAL Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_layer1_DS_RMS = TH1F("h_layer1_DS_RMS_bias" + str(curr_bias), "RMS of DS Layer 1 Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_layer2_DS_RMS = TH1F("h_layer2_DS_RMS_bias" + str(curr_bias), "RMS of DS Layer 2 Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_layer3_DS_RMS = TH1F("h_layer3_DS_RMS_bias" + str(curr_bias), "RMS of DS Layer 3 Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_layer4_DS_RMS = TH1F("h_layer4_DS_RMS_bias" + str(curr_bias), "RMS of DS Layer 4 Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_global_DS_RMS = TH1F("h_global_DS_RMS_bias" + str(curr_bias), "RMS of All DS BCAL Channels;RMS (ADC units)", 1000, hist_min, hist_max) h_global_all_RMS = TH1F("h_global_all_RMS_bias" + str(curr_bias), "RMS of All BCAL Channels;RMS (ADC units)", 1000, hist_min, hist_max) #Loop over all channels for rocid in rocid_arr: for slot in slot_arr: for channel in channel_arr: hist = get_hist_from_rocid_slot_channel( curr_file, rocid, slot, channel) quadrant = getquadrant(rocid) layer = getlayer(slot, channel) is_downstream = getend(slot, channel) # if(quadrant==3): continue #Skip quadrant 3, it has LEDs firing (in 2019 at least) if (quadrant == 3 or quadrant == 2 or quadrant == 4): continue #Skip quadrant 3, it has LEDs firing (in 2019 at least) #Fill appropriate histograms if (layer == 1 and is_downstream == 0): h_layer1_US_RMS.Fill(hist.GetRMS() / sqrt(layer)) if (layer == 2 and is_downstream == 0): h_layer2_US_RMS.Fill(hist.GetRMS() / sqrt(layer)) if (layer == 3 and is_downstream == 0): h_layer3_US_RMS.Fill(hist.GetRMS() / sqrt(layer)) if (layer == 4 and is_downstream == 0): h_layer4_US_RMS.Fill(hist.GetRMS() / sqrt(layer)) if (is_downstream == 0): h_global_US_RMS.Fill(hist.GetRMS()) if (layer == 1 and is_downstream == 1): h_layer1_DS_RMS.Fill(hist.GetRMS() / sqrt(layer)) if (layer == 2 and is_downstream == 1): h_layer2_DS_RMS.Fill(hist.GetRMS() / sqrt(layer)) if (layer == 3 and is_downstream == 1): h_layer3_DS_RMS.Fill(hist.GetRMS() / sqrt(layer)) if (layer == 4 and is_downstream == 1): h_layer4_DS_RMS.Fill(hist.GetRMS() / sqrt(layer)) if (is_downstream == 1): h_global_DS_RMS.Fill(hist.GetRMS()) h_global_all_RMS.Fill(hist.GetRMS()) #End of file: add histograms to list h_layer1_US_RMS_arr.append(h_layer1_US_RMS) h_layer2_US_RMS_arr.append(h_layer2_US_RMS) h_layer3_US_RMS_arr.append(h_layer3_US_RMS) h_layer4_US_RMS_arr.append(h_layer4_US_RMS) h_global_US_RMS_arr.append(h_global_US_RMS) h_layer1_DS_RMS_arr.append(h_layer1_DS_RMS) h_layer2_DS_RMS_arr.append(h_layer2_DS_RMS) h_layer3_DS_RMS_arr.append(h_layer3_DS_RMS) h_layer4_DS_RMS_arr.append(h_layer4_DS_RMS) h_global_DS_RMS_arr.append(h_global_DS_RMS) h_global_all_RMS_arr.append(h_global_all_RMS) mean_layer1_US_RMS.append(h_layer1_US_RMS.GetMean()) mean_layer2_US_RMS.append(h_layer2_US_RMS.GetMean()) mean_layer3_US_RMS.append(h_layer3_US_RMS.GetMean()) mean_layer4_US_RMS.append(h_layer4_US_RMS.GetMean()) mean_global_US_RMS.append(h_global_US_RMS.GetMean()) mean_layer1_DS_RMS.append(h_layer1_DS_RMS.GetMean()) mean_layer2_DS_RMS.append(h_layer2_DS_RMS.GetMean()) mean_layer3_DS_RMS.append(h_layer3_DS_RMS.GetMean()) mean_layer4_DS_RMS.append(h_layer4_DS_RMS.GetMean()) mean_global_DS_RMS.append(h_global_DS_RMS.GetMean()) mean_global_all_RMS.append(h_global_all_RMS.GetMean()) mean_err_layer1_US_RMS.append(h_layer1_US_RMS.GetRMS()) mean_err_layer2_US_RMS.append(h_layer2_US_RMS.GetRMS()) mean_err_layer3_US_RMS.append(h_layer3_US_RMS.GetRMS()) mean_err_layer4_US_RMS.append(h_layer4_US_RMS.GetRMS()) mean_err_global_US_RMS.append(h_global_US_RMS.GetRMS()) mean_err_layer1_DS_RMS.append(h_layer1_DS_RMS.GetRMS()) mean_err_layer2_DS_RMS.append(h_layer2_DS_RMS.GetRMS()) mean_err_layer3_DS_RMS.append(h_layer3_DS_RMS.GetRMS()) mean_err_layer4_DS_RMS.append(h_layer4_DS_RMS.GetRMS()) mean_err_global_DS_RMS.append(h_global_DS_RMS.GetRMS()) mean_err_global_all_RMS.append(h_global_all_RMS.GetRMS()) bias_arr.append(curr_bias) bias_err_arr.append(0) mean_layer1_diff_RMS.append(h_layer1_DS_RMS.GetMean() - h_layer1_US_RMS.GetMean()) mean_layer2_diff_RMS.append(h_layer2_DS_RMS.GetMean() - h_layer2_US_RMS.GetMean()) mean_layer3_diff_RMS.append(h_layer3_DS_RMS.GetMean() - h_layer3_US_RMS.GetMean()) mean_layer4_diff_RMS.append(h_layer4_DS_RMS.GetMean() - h_layer4_US_RMS.GetMean()) mean_global_diff_RMS.append(h_global_DS_RMS.GetMean() - h_global_US_RMS.GetMean()) mean_err_layer1_diff_RMS.append( sqrt(h_layer1_DS_RMS.GetRMS()**2 + h_layer1_US_RMS.GetRMS()**2)) mean_err_layer2_diff_RMS.append( sqrt(h_layer2_DS_RMS.GetRMS()**2 + h_layer2_US_RMS.GetRMS()**2)) mean_err_layer3_diff_RMS.append( sqrt(h_layer3_DS_RMS.GetRMS()**2 + h_layer3_US_RMS.GetRMS()**2)) mean_err_layer4_diff_RMS.append( sqrt(h_layer4_DS_RMS.GetRMS()**2 + h_layer4_US_RMS.GetRMS()**2)) mean_err_global_diff_RMS.append( sqrt(h_global_DS_RMS.GetRMS()**2 + h_global_US_RMS.GetRMS()**2)) gr_layer1_US_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer1_US_RMS, bias_err_arr, mean_err_layer1_US_RMS) gr_layer2_US_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer2_US_RMS, bias_err_arr, mean_err_layer2_US_RMS) gr_layer3_US_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer3_US_RMS, bias_err_arr, mean_err_layer3_US_RMS) gr_layer4_US_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer4_US_RMS, bias_err_arr, mean_err_layer4_US_RMS) gr_global_US_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_global_US_RMS, bias_err_arr, mean_err_global_US_RMS) gr_layer1_DS_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer1_DS_RMS, bias_err_arr, mean_err_layer1_DS_RMS) gr_layer2_DS_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer2_DS_RMS, bias_err_arr, mean_err_layer2_DS_RMS) gr_layer3_DS_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer3_DS_RMS, bias_err_arr, mean_err_layer3_DS_RMS) gr_layer4_DS_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer4_DS_RMS, bias_err_arr, mean_err_layer4_DS_RMS) gr_global_DS_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_global_DS_RMS, bias_err_arr, mean_err_global_DS_RMS) gr_global_all_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_global_all_RMS, bias_err_arr, mean_err_global_DS_RMS) gr_layer1_diff_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer1_diff_RMS, bias_err_arr, mean_err_layer1_diff_RMS) gr_layer2_diff_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer2_diff_RMS, bias_err_arr, mean_err_layer2_diff_RMS) gr_layer3_diff_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer3_diff_RMS, bias_err_arr, mean_err_layer3_diff_RMS) gr_layer4_diff_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_layer4_diff_RMS, bias_err_arr, mean_err_layer4_diff_RMS) gr_global_diff_RMS = TGraphErrors(len(bias_arr), bias_arr, mean_global_diff_RMS, bias_err_arr, mean_err_global_diff_RMS) if (subtract_floor_term): gr_layer1_US_RMS = remove_floor_term_from_gr(gr_layer1_US_RMS) gr_layer2_US_RMS = remove_floor_term_from_gr(gr_layer2_US_RMS) gr_layer3_US_RMS = remove_floor_term_from_gr(gr_layer3_US_RMS) gr_layer4_US_RMS = remove_floor_term_from_gr(gr_layer4_US_RMS) gr_global_US_RMS = remove_floor_term_from_gr(gr_global_US_RMS) gr_layer1_DS_RMS = remove_floor_term_from_gr(gr_layer1_DS_RMS) gr_layer2_DS_RMS = remove_floor_term_from_gr(gr_layer2_DS_RMS) gr_layer3_DS_RMS = remove_floor_term_from_gr(gr_layer3_DS_RMS) gr_layer4_DS_RMS = remove_floor_term_from_gr(gr_layer4_DS_RMS) gr_global_DS_RMS = remove_floor_term_from_gr(gr_global_DS_RMS) gr_global_all_RMS = remove_floor_term_from_gr(gr_global_all_RMS) gr_layer1_diff_RMS = remove_floor_term_from_gr_diff( gr_layer1_US_RMS, gr_layer1_DS_RMS) gr_layer2_diff_RMS = remove_floor_term_from_gr_diff( gr_layer2_US_RMS, gr_layer2_DS_RMS) gr_layer3_diff_RMS = remove_floor_term_from_gr_diff( gr_layer3_US_RMS, gr_layer3_DS_RMS) gr_layer4_diff_RMS = remove_floor_term_from_gr_diff( gr_layer4_US_RMS, gr_layer4_DS_RMS) gr_global_diff_RMS = remove_floor_term_from_gr_diff( gr_global_US_RMS, gr_global_DS_RMS) gr_layer1_US_RMS.SetNameTitle( "gr_layer1_US_RMS", "Layer 1 Upstream;Bias (V);Pedestal Width (ADC units)") gr_layer2_US_RMS.SetNameTitle( "gr_layer2_US_RMS", "Layer 2 Upstream;Bias (V);Pedestal Width (ADC units)") gr_layer3_US_RMS.SetNameTitle( "gr_layer3_US_RMS", "Layer 3 Upstream;Bias (V);Pedestal Width (ADC units)") gr_layer4_US_RMS.SetNameTitle( "gr_layer4_US_RMS", "Layer 4 Upstream;Bias (V);Pedestal Width (ADC units)") gr_global_US_RMS.SetNameTitle( "gr_global_US_RMS", "ALL Upstream;Bias (V);Pedestal Width (ADC units)") gr_layer1_DS_RMS.SetNameTitle( "gr_layer1_DS_RMS", "Layer 1 Downstream;Bias (V);Pedestal Width (ADC units)") gr_layer2_DS_RMS.SetNameTitle( "gr_layer2_DS_RMS", "Layer 2 Downstream;Bias (V);Pedestal Width (ADC units)") gr_layer3_DS_RMS.SetNameTitle( "gr_layer3_DS_RMS", "Layer 3 Downstream;Bias (V);Pedestal Width (ADC units)") gr_layer4_DS_RMS.SetNameTitle( "gr_layer4_DS_RMS", "Layer 4 Downstream;Bias (V);Pedestal Width (ADC units)") gr_global_DS_RMS.SetNameTitle( "gr_global_DS_RMS", "ALL Downstream;Bias (V);Pedestal Width (ADC units)") gr_global_all_RMS.SetNameTitle( "gr_global_all_RMS", "ALL Channels;Bias (V);Pedestal Width (ADC units)") gr_layer1_diff_RMS.SetNameTitle( "gr_layer1_diff_RMS", "Layer 1 Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)" ) gr_layer2_diff_RMS.SetNameTitle( "gr_layer2_diff_RMS", "Layer 2 Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)" ) gr_layer3_diff_RMS.SetNameTitle( "gr_layer3_diff_RMS", "Layer 3 Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)" ) gr_layer4_diff_RMS.SetNameTitle( "gr_layer4_diff_RMS", "Layer 4 Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)" ) gr_global_diff_RMS.SetNameTitle( "gr_global_diff_RMS", "ALL Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)" ) #Save results to file f_out = TFile(argv[0], "RECREATE") f_out.cd() gr_layer1_US_RMS.Write() gr_layer2_US_RMS.Write() gr_layer3_US_RMS.Write() gr_layer4_US_RMS.Write() gr_global_US_RMS.Write() gr_layer1_DS_RMS.Write() gr_layer2_DS_RMS.Write() gr_layer3_DS_RMS.Write() gr_layer4_DS_RMS.Write() gr_global_DS_RMS.Write() gr_global_all_RMS.Write() gr_layer1_diff_RMS.Write() gr_layer2_diff_RMS.Write() gr_layer3_diff_RMS.Write() gr_layer4_diff_RMS.Write() gr_global_diff_RMS.Write() for i in range(0, len(h_layer1_US_RMS_arr)): h_layer1_US_RMS_arr[i].Write() h_layer2_US_RMS_arr[i].Write() h_layer3_US_RMS_arr[i].Write() h_layer4_US_RMS_arr[i].Write() h_global_US_RMS_arr[i].Write() h_layer1_DS_RMS_arr[i].Write() h_layer2_DS_RMS_arr[i].Write() h_layer3_DS_RMS_arr[i].Write() h_layer4_DS_RMS_arr[i].Write() h_global_DS_RMS_arr[i].Write() h_global_all_RMS_arr[i].Write() f_out.Close() print("Done") return
comptonEdge = -0.5*par1/par2 err = comptonEdge*np.sqrt(((err1/par1)**2+(err2/par2)**2)) gComptonVsRun.SetPoint(i,15.0*i,comptonEdge) gComptonVsRun.SetPointError(i,0,err) gChi2VsRun.SetPoint(i,15.0*i,chi2/ndf) if 2000 < 15.0*i: hist_comptonedge.Fill(comptonEdge) print chi2 canvas = TCanvas() canvas.SetName("Results") canvas.Divide(1,2) canvas.cd(1) gComptonVsRun.SetName("ComptonEdge_vs_Time") gComptonVsRun.SetMarkerStyle(21); gComptonVsRun.GetXaxis().SetTitle("Time [min]") gComptonVsRun.GetYaxis().SetTitle("Channel number") gComptonVsRun.Draw("ACP") gComptonVsRun.Write() canvas.cd(2) gChi2VsRun.SetName("Fit_Chi2_NDF") gChi2VsRun.SetMarkerStyle(21); gChi2VsRun.GetXaxis().SetTitle("Time [min]") gChi2VsRun.GetYaxis().SetTitle("Chi2/NDF") gChi2VsRun.Draw("ACP") gChi2VsRun.Write() hist_comptonedge.GetXaxis().SetTitle("Compton edge (Channel number)") hist_comptonedge.GetYaxis().SetTitle("Counts") hist_comptonedge.Write() rootfile.Close()
def plotDistributionComparisonPlot(cfg): multiGraph = TMultiGraph() multiGraph.SetName("triggerRateMultiGraph") tfiles = [] histograms = [] canvas = TCanvas("canvas", "canvas", 800, 800) '''Contains the legend''' legend = TLegend(0.3, 0.7, 0.90, 0.9) '''Maximum value container, used to scale histograms''' maximumY = float("-inf") pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetBottomMargin(0.05) # Upper and lower plot are joined #pad1.SetBottomMargin(0) # Upper and lower plot are joined pad1.SetGridx() # Vertical grid pad1.Draw() # Draw the upper pad: pad1 pad1.cd() # pad1 becomes the current pad for histogramFileNameAndTitle in cfg.plots: tfile = TFile(histogramFileNameAndTitle[0]) tfiles.append(tfile) histogram = tfile.Get(histogramFileNameAndTitle[1]) histograms.append(histogram) if histogram.ClassName() == "TH1F": histogram.SetStats(0) # No statistics on upper plot maximumY = histogram.GetMaximum( ) if histogram.GetMaximum() > maximumY else maximumY legend.AddEntry(histogram, histogramFileNameAndTitle[2], "l") # histograms[0] settings histograms[0].SetMarkerColor(4) histograms[0].SetLineColor(4) histograms[0].SetLineWidth(1) # Y axis histograms[0] plot settings histograms[0].GetYaxis().SetTitleSize(20) histograms[0].GetYaxis().SetTitleFont(43) histograms[0].GetYaxis().SetTitleOffset(1.55) #histograms[0].Scale(1./histograms[0].GetEntries()) if histograms[0].ClassName() == "TH1F": histograms[0].Draw( "SAME HIST") # Draw histograms[1] on top of histograms[0] else: histograms[0].Draw( "SAME APE") # Draw histograms[1] on top of histograms[0] #multiGraph.Add(histograms[0]) if getattr(cfg, "xRange", None) is not None: histograms[0].GetXaxis().SetRangeUser(cfg.xRange[0], cfg.xRange[1]) gPad.RedrawAxis() if getattr(cfg, "xAxisLabel", None) is not None: histograms[0].GetXaxis().SetTitle(cfg.xAxisLabel) gPad.RedrawAxis() if getattr(cfg, "yAxisLabel", None) is not None: histograms[0].GetYaxis().SetTitle(cfg.yAxisLabel) gPad.RedrawAxis() if getattr(cfg, "yRange", None) is not None: histograms[0].GetYaxis().SetRangeUser(cfg.yRange[0], cfg.yRange[1]) gPad.RedrawAxis() else: maximumY *= 1.1 histograms[0].GetYaxis().SetRangeUser(1e-6, maximumY) if getattr(cfg, "logY", False): canvas.SetLogy() # histograms[1] settings histograms[1].SetMarkerColor(2) histograms[1].SetLineColor(2) histograms[1].SetLineWidth(1) #histograms[1].Scale(1./histograms[1].GetEntries()) if histograms[1].ClassName() == "TH1F": histograms[1].Draw( "SAME HIST") # Draw histograms[1] on top of histograms[0] else: histograms[1].Draw( "SAME PE") # Draw histograms[1] on top of histograms[0] #multiGraph.Add(histograms[1]) #if multiGraph.GetListOfGraphs() != None: # multiGraph.Draw("SAME PE") # Do not draw the Y axis label on the upper plot and redraw a small # axis instead, in order to avoid the first label (0) to be clipped. #histograms[0].GetYaxis().SetLabelSize(0.) #axis = TGaxis( 0, 20, 0, maximumY, 20, maximumY, 510,"") #axis.SetLabelFont(43) # Absolute font size in pixel (precision 3) #axis.SetLabelSize(15) #axis.Draw() # Adding a small text with the chi-squared chiSquared = 0 if (histograms[0].ClassName() == "TGraph") or (histograms[0].ClassName() == "TGraphErrors"): numberOfBins = histograms[0].GetN() numberOfDegreesOfFreedom = numberOfBins else: numberOfBins = histograms[0].GetNbinsX() numberOfDegreesOfFreedom = numberOfBins for x in xrange( 1, numberOfBins + 1 ): # numberOfBins contains last bin, numberOfBins+1 contains the overflow (latter excluded), underflow also excluded if (histograms[0].ClassName() == "TGraph") or (histograms[0].ClassName() == "TGraphErrors"): binContent0 = histograms[0].GetY()[x - 1] else: binContent0 = histograms[0].GetBinContent(x) if (histograms[1].ClassName() == "TGraph") or (histograms[1].ClassName() == "TGraphErrors"): binContent1 = histograms[1].GetY()[x - 1] else: binContent1 = histograms[1].GetBinContent(x) bin0ErrorSquared = binContent0 bin1ErrorSquared = binContent1 #bin1ErrorSquared = 0 if (binContent0 == 0) and (binContent1 == 0): numberOfDegreesOfFreedom -= 1 #No data means one less degree of freedom else: binDifferenceSquared = (binContent0 - binContent1)**2 chiSquaredTerm = binDifferenceSquared / (bin0ErrorSquared + bin1ErrorSquared) chiSquared += chiSquaredTerm if chiSquaredTerm > chiSquaredWarningThreshold: if (histograms[0].ClassName() == "TGraph") or (histograms[0].ClassName() == "TGraphErrors"): print "Bin", x, "-", histograms[0].GetX()[ x - 1], "has a CS=", chiSquaredTerm else: print "Bin", x, "-", histograms[0].GetBinCenter( x), "has a CS=", chiSquaredTerm chiSquareLabel = TPaveText(0.7, 0.6, 0.9, 0.4) chiSquareLabel.AddText("#chi^{2}/ndf = " + str(chiSquared) + "/" + str(numberOfDegreesOfFreedom) + " = " + str(chiSquared / numberOfDegreesOfFreedom)) chiSquareLabel.Draw() print "FINAL CS IS", format( chiSquared, ".2f") + "/" + str(numberOfDegreesOfFreedom) + " = " + format( chiSquared / numberOfDegreesOfFreedom, ".2f") legend.SetHeader( "#chi^{2}/ndf = " + format(chiSquared, ".2f") + "/" + str(numberOfDegreesOfFreedom) + " = " + format(chiSquared / numberOfDegreesOfFreedom, ".2f"), "C") legend.Draw() # lower plot will be in pad canvas.cd() # Go back to the main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.2) pad2.SetGridx() # vertical grid pad2.Draw() pad2.cd() # pad2 becomes the current pad pad2.SetGridy() # Define the ratio plot ratioPlot = TGraphErrors(histograms[0]) ratioPlot.SetName("ratioPlot") graph_histo0 = TGraphErrors(histograms[0]) graph_histo1 = TGraphErrors(histograms[1]) ratioPlot.SetLineColor(1) ratioPlot.SetMinimum(0.6) # Define Y .. ratioPlot.SetMaximum(1.5) # .. range #ratioPlot.Sumw2() #ratioPlot.SetStats(0) # No statistics on lower plot #Dividing point by point for index in xrange(0, ratioPlot.GetN()): if graph_histo1.GetY()[index] == 0: ratioPlot.GetY()[index] = 0 ratioPlot.GetEY()[index] = 0 else: ratioPlot.GetY()[index] /= graph_histo1.GetY()[index] ratioPlot.GetEY()[index] = sqrt( ((graph_histo1.GetY()[index])**2 * (graph_histo0.GetEY()[index])**2 + (graph_histo0.GetY()[index])**2 * (graph_histo1.GetEY()[index])**2) / (graph_histo1.GetY()[index])**4) ratioPlot.SetMarkerStyle(21) if getattr(cfg, "xRange", None) is not None: ratioPlot.GetXaxis().SetRangeUser(cfg.xRange[0], cfg.xRange[1]) gPad.RedrawAxis() if getattr(cfg, "yRangeRatio", None) is not None: ratioPlot.GetYaxis().SetRangeUser(cfg.yRangeRatio[0], cfg.yRangeRatio[1]) gPad.RedrawAxis() ratioPlot.Draw("APE") # Draw the ratio plot line0 = TLine(ratioPlot.GetXaxis().GetXmin(), 1, ratioPlot.GetXaxis().GetXmax(), 1) line0.SetLineColor(2) line0.SetLineWidth(2) line0.SetLineStyle(2) line0.Draw() # Ratio plot (ratioPlot) settings ratioPlot.SetTitle("") # Remove the ratio title # Y axis ratio plot settings ratioPlot.GetYaxis().SetTitle("Ratio #frac{blue}{red}") ratioPlot.GetYaxis().SetNdivisions(505) ratioPlot.GetYaxis().SetTitleSize(20) ratioPlot.GetYaxis().SetTitleFont(43) ratioPlot.GetYaxis().SetTitleOffset(1.55) ratioPlot.GetYaxis().SetLabelFont( 43) # Absolute font size in pixel (precision 3) ratioPlot.GetYaxis().SetLabelSize(15) # X axis ratio plot settings ratioPlot.GetXaxis().SetTitleSize(20) ratioPlot.GetXaxis().SetTitleFont(43) ratioPlot.GetXaxis().SetTitleOffset(4.) ratioPlot.GetXaxis().SetLabelFont( 43) # Absolute font size in pixel (precision 3) ratioPlot.GetXaxis().SetLabelSize(15) xRangeBinning = getattr(cfg, "simplifiedRatioPlotXRangeBinning", None) if xRangeBinning is not None: simplifiedRatioPlot = TGraphErrors(len(xRangeBinning) - 1) simplifiedRatioPlot.SetName("simplifiedRatioPlot") ratioPlotIndex = 0 for idx in xrange(0, simplifiedRatioPlot.GetN()): yAverage = 0. yMax = float("-inf") yMin = float("+inf") nPoints = 0. simplifiedRatioPlot.GetX()[idx] = (xRangeBinning[idx] + xRangeBinning[idx + 1]) / 2. simplifiedRatioPlot.GetEX()[idx] = (xRangeBinning[idx + 1] - xRangeBinning[idx]) / 2. while (ratioPlot.GetX()[ratioPlotIndex] < xRangeBinning[idx]): ratioPlotIndex += 1 while ((ratioPlotIndex < ratioPlot.GetN()) and (ratioPlot.GetX()[ratioPlotIndex] < xRangeBinning[idx + 1]) and (ratioPlot.GetX()[ratioPlotIndex] >= xRangeBinning[idx])): yAverage += ratioPlot.GetY()[ratioPlotIndex] if (yMax < ratioPlot.GetY()[ratioPlotIndex] + ratioPlot.GetEY()[ratioPlotIndex]): yMax = ratioPlot.GetY()[ratioPlotIndex] + ratioPlot.GetEY( )[ratioPlotIndex] if (yMin > ratioPlot.GetY()[ratioPlotIndex] - ratioPlot.GetEY()[ratioPlotIndex]): yMin = ratioPlot.GetY()[ratioPlotIndex] - ratioPlot.GetEY( )[ratioPlotIndex] nPoints += 1. ratioPlotIndex += 1 simplifiedRatioPlot.GetY()[idx] = yAverage / nPoints simplifiedRatioPlot.GetEY()[idx] = (yMax - yMin) / 2. saveFile = TFile(cfg.saveFileName, "RECREATE") saveFile.cd() canvas.Write() histograms[0].Write() histograms[1].Write() if multiGraph.GetListOfGraphs() != None: multiGraph.Write() ratioPlot.Write() if xRangeBinning is not None: simplifiedRatioPlot.Write() saveFile.Close() for tfile in tfiles: tfile.Close()
breakzErr.append(fit.Get().ParError(3)) lengthErr.append(fit.Get().ParError(4)) fit_params.Write("fit {0} GeV".format(mass)) c.Print(remainder[0] + ".pdf", "Title:mass_{0}".format(mass)) c.Clear() outfile.cd() gPad.SetLogy(0) graph = TGraphErrors(len(massarray), massarray, sigmaarray, zeroArr, sigmaErr) graph.Draw("A*") graph.SetTitle("Vertex Resolution") graph.GetXaxis().SetTitle("mass [GeV]") graph.GetYaxis().SetTitle("sigma [mm]") graph.Write("sigmaz") c.Print(remainder[0] + ".pdf", "Title:sigmaz") graph = TGraphErrors(len(massarray), massarray, breakzarray, zeroArr, breakzErr) graph.Draw("A*") graph.SetTitle("Tail Z") graph.GetXaxis().SetTitle("mass [GeV]") graph.GetYaxis().SetTitle("tail Z [mm]") graph.Write("breakz") c.Print(remainder[0] + ".pdf", "Title:tailz") graph = TGraphErrors(len(massarray), massarray, lengtharray, zeroArr, lengthErr) graph.Draw("A*") graph.SetTitle("Tail length")
def FitHistsGetEffic(hist_fname, fit_out_fname, MIN_E, MAX_E, E_STEP, scale_factor): E_arr = array('d', []) E_arr_err = array('d', []) effic_arr = array('d', []) effic_arr_err = array('d', []) norm_arr = array('d', []) curr_E_val = MIN_E while curr_E_val <= MAX_E + 0.0001: E_arr.append(curr_E_val) if (NORMALIZE_EXTERNAL): E_arr_err.append(0) if (not NORMALIZE_EXTERNAL): E_arr_err.append(E_STEP / 2.) curr_E_val += E_STEP c1 = TCanvas("c1", "c1", 1600, 900) c1.SetGridx(1) c1.SetGridy(1) #Get normalization from external files assuming matching directory scheme for embedded photon gun data if (NORMALIZE_EXTERNAL): #Get normalization curr_E_val = MIN_E while curr_E_val <= MAX_E + 0.0001: print "Getting normalization for energy value: " + str(curr_E_val) thisfile_string = NORM_BASE_DIR + str( curr_E_val) + "/" + NORM_FILENAME if (not os.path.isfile(thisfile_string)): print "file not found, normalization will be 0: " + thisfile_string norm_arr.append(0.) curr_E_val += E_STEP continue normfile = TFile.Open(thisfile_string, 'read') my_tr = TTree() my_tr.Print() my_tr = normfile.Get(NORM_TREENAME) norm_arr.append(my_tr.GetEntries()) curr_E_val += E_STEP #Done getting normalization # Get normalization from same root file f_in = TFile.Open(hist_fname) #Open rootfile if (not NORMALIZE_EXTERNAL): for i in range(0, len(E_arr)): E_cut_str = str(E_arr[i] - E_STEP / 2.) + "<ThrownE&&ThrownE<" + str( E_arr[i] + E_STEP / 2.) + "&&ThrownTheta<9&&ThrownTheta>4" h_curr = f_in.Get("h_EThrown_" + E_cut_str) norm_arr.append(h_curr.GetEntries() / scale_factor) #Fit stuff for i in range(0, len(E_arr)): h_curr = TH1F() E_cut_str = str(E_arr[i] - E_STEP / 2.) + "<ThrownE&&ThrownE<" + str( E_arr[i] + E_STEP / 2.) + "&&ThrownTheta<9&&ThrownTheta>4" if (NORMALIZE_EXTERNAL): h_curr = f_in.Get("h_EGammaPostCuts_" + str(E_arr[i])) if (not NORMALIZE_EXTERNAL): h_curr = f_in.Get("h_EGammaPostCuts_" + E_cut_str) curr_E_val = E_arr[i] norm_count = norm_arr[i] if (norm_count < MIN_EVENTS): effic_arr.append(-1) effic_arr_err.append(0) continue my_gaus_fit = TF1("my_gaus_fit", "gausn", 0.001, 3.) my_gaus_fit.SetParLimits(0, 0, 10000) my_gaus_fit.SetParLimits(1, curr_E_val - 0.2, curr_E_val + 0.1) my_gaus_fit.SetParLimits(2, 0.005, 0.4) my_gaus_fit.SetNpx(1000) h_curr.GetXaxis().SetRangeUser(curr_E_val - 1.2, curr_E_val + 0.5) h_curr.Fit(my_gaus_fit, "Q", "", curr_E_val - E_BELOWTHROWN_TOFIT, curr_E_val + E_ABOVETHROWN_TOFIT) h_curr.Fit(my_gaus_fit, "QL", "", curr_E_val - E_BELOWTHROWN_TOFIT, curr_E_val + E_ABOVETHROWN_TOFIT) if (POLY_ORDER >= 1): gaus_fit_amplitude = my_gaus_fit.GetParameter(0) gaus_fit_mean = my_gaus_fit.GetParameter(1) gaus_fit_sigma = my_gaus_fit.GetParameter(2) gaus_plus_poly_fit = TF1("gaus_plus_poly_fit", "gausn+pol" + str(POLY_ORDER) + "(3)", 0.001, 3.) gaus_plus_poly_fit.SetParameter(0, gaus_fit_amplitude) gaus_plus_poly_fit.SetParameter(1, gaus_fit_mean) gaus_plus_poly_fit.SetParameter(2, gaus_fit_sigma) gaus_plus_poly_fit.SetParLimits(0, 0, 10000) gaus_plus_poly_fit.SetParLimits(1, curr_E_val - 0.2, curr_E_val + 0.1) gaus_plus_poly_fit.SetParLimits(2, 0.005, 0.4) h_curr.Fit(gaus_plus_poly_fit, "Q", "", curr_E_val - E_BELOWTHROWN_TOFIT, curr_E_val + E_ABOVETHROWN_TOFIT) h_curr.Fit(gaus_plus_poly_fit, "QL", "", curr_E_val - E_BELOWTHROWN_TOFIT, curr_E_val + E_ABOVETHROWN_TOFIT) c1.SaveAs(".plots/FitE_" + str(curr_E_val) + ".png") effic_arr.append( (my_gaus_fit.GetParameter(0) / h_curr.GetBinWidth(0)) / norm_count) effic_arr_err.append( my_gaus_fit.GetParError(0) / h_curr.GetBinWidth(0) / norm_count) gr_gauscore_effic = TGraphErrors(len(E_arr), E_arr, effic_arr, E_arr_err, effic_arr_err) gr_gauscore_effic.SetMarkerStyle(15) gr_gauscore_effic.SetMarkerSize(1.2) gr_gauscore_effic.SetMarkerColor(kBlue) gr_gauscore_effic.SetName("gr_gauscore_effic") f_out = TFile(fit_out_fname, "RECREATE") f_out.cd() gr_gauscore_effic.Write() f_out.Close()
electron.append(nEstElectron[runPeriods.index(runPeriod)][0] / lumi["MET_2015" + runPeriod]) muon.append(nEstMuon[runPeriods.index(runPeriod)][0] / lumi["MET_2015" + runPeriod]) tau.append(nEstTau[runPeriods.index(runPeriod)][0] / lumi["MET_2015" + runPeriod]) fake.append(nEstFake[runPeriods.index(runPeriod)][0] / lumi["MET_2015" + runPeriod]) eElectron.append(nEstElectron[runPeriods.index(runPeriod)][1] / lumi["MET_2015" + runPeriod]) eMuon.append(nEstMuon[runPeriods.index(runPeriod)][1] / lumi["MET_2015" + runPeriod]) eTau.append(nEstTau[runPeriods.index(runPeriod)][1] / lumi["MET_2015" + runPeriod]) eFake.append(nEstFake[runPeriods.index(runPeriod)][1] / lumi["MET_2015" + runPeriod]) gElectron = TGraphErrors(len(x), x, electron, ex, eElectron) gMuon = TGraphErrors(len(x), x, muon, ex, eMuon) gTau = TGraphErrors(len(x), x, tau, ex, eTau) gFake = TGraphErrors(len(x), x, fake, ex, eFake) fout = TFile.Open("backgroundCrossSections_2015.root", "recreate") fout.cd() gElectron.Write("electron") gMuon.Write("muon") gTau.Write("tau") gFake.Write("fake") fout.Close()
def recenergy(particle, name, chivalue): outputfile = str(particle) + "_Femanalysis" + str(chivalue) + "_" + str( name) displayfile = TFile(outputfile + ".root", "RECREATE") ''' if name == "FTFPBERT": chi = 0.3 if name == "FTFPBERTTRV": chi = 0.3 if name == "QGSPBERT": chi = 0.3 if name == "QBBC": chi = 0.3 ''' MeanEnergyScin = array('d') MeanEnergyCher = array('d') Energy = array('d') Energyerror = array('d') energyfractionscin = array('d') energyfractionscinerror = array('d') energyfractioncher = array('d') energyfractionchererror = array('d') energyfraction = array('d') energyfractionerror = array('d') resolutionscin = array('d') resolutionscinerror = array('d') resolutioncher = array('d') resolutionchererror = array('d') resolution = array('d') resolutionerror = array('d') chiarray = array('d') chierrorarray = array('d') zeros = array('d') containment = array('d') containmenterror = array('d') femvalues = array('d') zvalues = array('d') femvalueserror = array('d') zvalueserror = array('d') znormvalues = array('d') znormvalueserror = array('d') t = [10, 30, 50, 70, 100, 120, 140, 150] sqrtenergies = array('d', [1 / (x**0.5) for x in t]) energies = array('d', t) #inputfiles = ["/home/software/Calo/results/energycont_2p0m/Pion_"+str(i)+".root" for i in t] #inputfiles = ["/home/software/Calo/results/pionenergyscan_QGSPBICHP/Pion_"+str(i)+".root" for i in t] #inputfiles = ["/home/lorenzo/Desktop/Calo/newresults/FTFPBERTTRV/Pion_"+str(i)+"_FTFPBERTTRV_office.root" for i in t] #inputfiles = ["/Users/lorenzo/Desktop/ToPC/newresults/"+str(name)+"/Pion_"+str(i)+".root" for i in t] if particle == "pion": inputfiles = [ "/home/lorenzo/Calo/results/Pion_25_3_2020/" + str(name) + "" + "/Pion_" + str(i) + ".root" for i in t ] #inputfiles = ["/home/lorenzo/Calo/results/geant4.10.4.p01/Pion_30_4_2020/"+str(name)+""+"/Pion_"+str(i)+".root" for i in t] if particle == "proton": inputfiles = [ "/home/lorenzo/Calo/results/Proton_25_3_2020/" + str(name) + "" + "/Proton_" + str(i) + ".root" for i in t ] if particle == "neutron": inputfiles = [ "/home/lorenzo/Calo/results/Neutron_25_3_2020/" + str(name) + "" + "/Neutron_" + str(i) + ".root" for i in t ] if particle == "kaon": inputfiles = [ "/home/lorenzo/Calo/results/Kaon_5_4_2020/" + str(name) + "" + "/Kaon_" + str(i) + ".root" for i in t ] for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: " + str(inputfile) + " \n" tree = TTree() inputfile.GetObject("B4", tree) ScinEnergyHist = TH1F("scinenergy_" + str(t[counter]), str(t[counter]) + "_scin", 400, 0., 200.) CherEnergyHist = TH1F("cherenergy_" + str(t[counter]), str(t[counter]) + "_cher", 400, 0., 200.) RecEnergyHist = TH1F("RecEnergy_" + str(t[counter]), str(t[counter]) + "_Energy", 400, 0., 200.) #Signalscinhist = TH1F("scintot_", str(counter+1)+"_scin", 3000, 0., 30000) EnergyHist = TH1F("Energy_" + str(t[counter]), str(t[counter]) + "_Energy", 400, 0., 200.) LeakageHist = TH1F("Leak_" + str(t[counter]), str(t[counter]) + "_Leak", 1000, 0., 100.) NeutrinoLeakageHist = TH1F("NeutrinoNeutrinoLeak_" + str(t[counter]), str(t[counter]) + "_Leak", 1000, 0., 100.) TotalLeakageHist = TH1F("TotalLeak_" + str(t[counter]), str(t[counter]) + "_Leak", 1000, 0., 100.) ChiHist = TH1F("Chi_" + str(t[counter]), str(t[counter]) + "_Chi", 200, 0., 2.) scatterplot = TH2F("scatterplot_" + str(t[counter]), str(t[counter]), int(400), 0., 200., int(400), 0., 200.) EnergyContHist = TH1F("EnergyCont_" + str(t[counter]), str(t[counter]) + "_EnergyCont", 400, 0., 200.) hesscatterplot = TH2F("H/E_S" + str(t[counter]), "H/E_S" + str(t[counter]), 200, 0., 1.1, 200, 0., 1.1) hecscatterplot = TH2F("H/E_C" + str(t[counter]), "H/E_C" + str(t[counter]), 200, 0., 1.1, 200, 0., 1.1) #fem and z histo femhisto = TH1F("fem_" + str(t[counter]), str(t[counter]) + "_fem", 100, 0., 1.) zhisto = TH1F("z" + str(t[counter]), str(t[counter]) + "_z", 100, 0., 1.) znormhisto = TH1F("z_norm" + str(t[counter]), str(t[counter]) + "_z_norm", 200, 0., 2.) zfemhisto = TH2F("z_fem_histo" + str(t[counter]), str(t[counter]) + "_z_fem_histo", 200, 0., 2., 200, 0., 2.) #loop over events entries = 50000 for Event in range(entries): tree.GetEntry(Event) if Event % 1000 == 0: print Event #Set values of the tree PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name PrimaryParticleEnergy = tree.PrimaryParticleEnergy EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter Energyem = tree.Energyem # Energy deposited by the em component EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected) EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected) NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected BarrelR_VectorSignals = tree.VectorSignalsR # Vector of energy deposited in Scin fibers (Birk corrected) BarrelL_VectorSignals = tree.VectorSignalsL # Vector of energy deposited in Scin fibers (Birk corrected) BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers BarrelL_VectorSignalsCher = tree.VectorSignalsCherL VectorR = tree.VectorR VectorL = tree.VectorL Leak = tree.leakage NeutrinoLeak = tree.neutrinoleakage #totalsignalscin = sum(BarrelR_VectorSignals)+sum(BarrelL_VectorSignals) #Signalscinhist.Fill(totalsignalscin) energytot = (sum(VectorR) + sum(VectorL)) / 1000 EnergyHist.Fill(energytot) LeakageHist.Fill(Leak / 1000.) NeutrinoLeakageHist.Fill(NeutrinoLeak / 1000.) TotalLeakageHist.Fill(Leak / 1000. + NeutrinoLeak / 1000.) if float(t[counter]) < 12.: cutleak = 0.5 if float(t[counter]) > 12. and float(t[counter]) < 50.: cutleak = 1.0 if float(t[counter]) > 50.: cutleak = 3.0 if (Leak / 1000. + NeutrinoLeak / 1000.) < cutleak: #apply calibrations Calib_BarrelL_VectorSignals = calibration.calibscin( BarrelL_VectorSignals) Calib_BarrelR_VectorSignals = calibration.calibscin( BarrelR_VectorSignals) Calib_BarrelL_VectorSignalsCher = calibration.calibcher( BarrelL_VectorSignalsCher) Calib_BarrelR_VectorSignalsCher = calibration.calibcher( BarrelR_VectorSignalsCher) #end of calibrations energyscin = sum(Calib_BarrelR_VectorSignals) + sum( Calib_BarrelL_VectorSignals) energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum( Calib_BarrelL_VectorSignalsCher) e_c = float(t[counter]) - (Leak / 1000. + NeutrinoLeak / 1000.) hesscatterplot.Fill(Energyem / 1000. / e_c, energyscin / e_c) hecscatterplot.Fill(Energyem / 1000. / e_c, energycher / e_c) femhisto.Fill(Energyem / 1000. / e_c) z = (1. - energycher / energyscin) / ( 1. - (chivalue * energycher / energyscin)) zhisto.Fill(z) znormhisto.Fill(z / (1 - (Energyem / 1000. / e_c))) zfemhisto.Fill(z, (1 - (Energyem / 1000. / e_c))) EnergyContHist.Fill(e_c) ScinEnergyHist.Fill(energyscin) CherEnergyHist.Fill(energycher) scatterplot.Fill(energyscin / float(t[counter]), energycher / float(t[counter])) chi = chivalue newchi = (energyscin - e_c) / (energycher - e_c) ChiHist.Fill(newchi) RecEnergyHist.Fill( 1. / 0.99 * (energyscin - chi * energycher) / (1. - chi)) print energies[counter], ScinEnergyHist.GetMean( ), CherEnergyHist.GetMean(), RecEnergyHist.GetMean() displayfile.cd() gStyle.SetOptStat(111) #ScinEnergyHist.Fit("gaus") #CherEnergyHist.Fit("gaus") #RecEnergyHist.Scale(1/RecEnergyHist.Integral()) #print RecEnergyHist.Integral() RecEnergyHist.Fit("gaus") RecEnergyHist.Write() ScinEnergyHist.Write() CherEnergyHist.Write() #Signalscinhist.Write() EnergyHist.Write() EnergyContHist.Write() e_cont = EnergyContHist.GetMean() e_cont_error = EnergyContHist.GetRMS() / float(entries)**0.5 scatterplot.Write() #cut1 = TCutG("cut1",4) #cut1.SetVarX("x") #cut1.SetVarY("y") #cut1.SetPoint(0,0.,0.) #cut1.SetPoint(1,1.,0.) #cut1.SetPoint(2,1.,1.) #cut1.SetPoint(3,0.,1.) #profile = scatterplot.ProfileX("",1,400,"[cut1]") #profile.GetYaxis().SetRangeUser(0.,1.5) #profile.Write() func2 = TF1("func2", '[0]+x*(1.-[0])', 0., 1.) pp = hesscatterplot.ProfileX() pp.Fit(func2) pp.Write() hesscatterplot.Write() hecscatterplot.Write() femhisto ppc = hecscatterplot.ProfileX() ppc.Fit(func2) ppc.Write() LeakageHist.Write() NeutrinoLeakageHist.Write() TotalLeakageHist.Write() ChiHist.Write() #scin_sqrtenergies.append(1./(ScinEnergyHist.GetFunction("gaus").GetParameter(1)**0.5)) #cher_sqrtenergies.append(1./(CherEnergyHist.GetFunction("gaus").GetParameter(1)**0.5)) Energy.append(RecEnergyHist.GetFunction("gaus").GetParameter(1)) Energyerror.append(3. * RecEnergyHist.GetFunction("gaus").GetParameter(2) / float(entries)**0.5) MeanEnergyScin.append(ScinEnergyHist.GetMean()) MeanEnergyCher.append(CherEnergyHist.GetMean()) resolution.append( RecEnergyHist.GetFunction("gaus").GetParameter(2) / RecEnergyHist.GetFunction("gaus").GetParameter(1)) sigma_energy_e = ( (RecEnergyHist.GetFunction("gaus").GetParameter(2) / (float(entries)**0.5)) / RecEnergyHist.GetFunction("gaus").GetParameter(1) + RecEnergyHist.GetFunction("gaus").GetParError(2) / RecEnergyHist.GetFunction("gaus").GetParameter(2)) * ( RecEnergyHist.GetFunction("gaus").GetParameter(2) / RecEnergyHist.GetFunction("gaus").GetParameter(1)) resolutionerror.append(sigma_energy_e) energyfractionscin.append(ScinEnergyHist.GetMean() / float(t[counter])) energyfractionscinerror.append( 3 * (ScinEnergyHist.GetRMS() / entries**0.5) / float(t[counter])) energyfractioncher.append(CherEnergyHist.GetMean() / float(t[counter])) energyfractionchererror.append( 3 * (CherEnergyHist.GetRMS() / entries**0.5) / float(t[counter])) energyfraction.append( RecEnergyHist.GetFunction("gaus").GetParameter(1) / float(t[counter])) energyfractionerror.append( 3 * (RecEnergyHist.GetFunction("gaus").GetParameter(2) / entries**0.5) / float(t[counter])) resolutionscin.append(ScinEnergyHist.GetRMS() / ScinEnergyHist.GetMean()) sigma_energy_e = ( ScinEnergyHist.GetMeanError() / ScinEnergyHist.GetMean() + ScinEnergyHist.GetRMSError() / ScinEnergyHist.GetRMS()) * ( ScinEnergyHist.GetRMS() / ScinEnergyHist.GetMean()) resolutionscinerror.append(sigma_energy_e) resolutioncher.append(CherEnergyHist.GetRMS() / CherEnergyHist.GetMean()) sigma_energy_e = ( CherEnergyHist.GetMeanError() / CherEnergyHist.GetMean() + CherEnergyHist.GetRMSError() / CherEnergyHist.GetRMS()) * ( CherEnergyHist.GetRMS() / CherEnergyHist.GetMean()) resolutionchererror.append(sigma_energy_e) chiarray.append(ChiHist.GetBinCenter(ChiHist.GetMaximumBin())) chierrorarray.append(3 * ChiHist.GetRMS() / (entries**0.5)) zeros.append(0.0) containment.append(e_cont / float(t[counter])) containmenterror.append(e_cont_error / float(t[counter])) femhisto.Write() zhisto.Write() zfemhisto.Write() znormhisto.Write() femvalues.append(femhisto.GetMean()) zvalues.append(zhisto.GetMean()) femvalueserror.append(femhisto.GetRMS() / (entries**0.5)) zvalueserror.append(zhisto.GetRMS() / (entries**0.5)) znormvalues.append(znormhisto.GetMean()) znormvalueserror.append(znormhisto.GetRMS() / (entries**0.5)) containmentgraph = TGraphErrors(len(energies), energies, containment, zeros, containmenterror) containmentgraph.SetName("containment") containmentgraph.Write() ChiGraph = TGraphErrors(len(energies), energies, chiarray, zeros, chierrorarray) ChiGraph.SetName("Chi") ChiGraph.Write() LinearityGraph2 = TGraphErrors(len(energies), energies, Energy, zeros, Energyerror) LinearityGraph2.SetName("LinearityGraph2") LinearityGraph2.Write() LinearityGraph = TGraphErrors(len(energies), energies, energyfraction, zeros, energyfractionerror) LinearityGraph.SetName("LinearityGraph") LinearityGraph.Write() LinearityGraphScin = TGraphErrors(len(energies), energies, energyfractionscin, zeros, energyfractionscinerror) LinearityGraphCher = TGraphErrors(len(energies), energies, energyfractioncher, zeros, energyfractionchererror) LinearityGraphCher.SetName("LinearityGraphCher") LinearityGraphCher.Write() LinearityGraphScin.SetName("LinearityGraphScin") LinearityGraphScin.Write() ResolutionGraphScin = TGraphErrors(len(energies), sqrtenergies, resolutionscin, zeros, resolutionscinerror) func = TF1("func", "[0]/(x**0.5)+[1]", 10., 150.) ResolutionGraphCher = TGraphErrors(len(energies), sqrtenergies, resolutioncher, zeros, resolutionchererror) #ResolutionGraphScin.Fit("func", "R") #ResolutionGraphCher.Fit("func", "R") ResolutionGraphScin.SetName("ResolutionGraphScin") ResolutionGraphScin.Write() ResolutionGraphCher.SetName("ResolutionGraphCher") ResolutionGraphCher.Write() ResolutionGraph = TGraphErrors(len(energies), sqrtenergies, resolution, zeros, resolutionerror) #ResolutionGraph.Fit("func", "R") ResolutionGraph.SetName("ResolutionGraph") ResolutionGraph.Write() LinearityGraph.SetMinimum(0.976) #0.976 LinearityGraph.SetMaximum(1.024) #1.024 LinearityGraph.GetXaxis().SetLimits(0.0, 155.0) LinearityGraph.SetTitle("") LinearityGraph.GetXaxis().SetLabelSize(.105) LinearityGraph.GetYaxis().SetLabelSize(0.105) LinearityGraph.GetXaxis().SetNdivisions(520) LinearityGraph.GetYaxis().SetNdivisions(504) LinearityGraph2.SetTitle("") LinearityGraph2.SetMinimum(0.0) LinearityGraph2.SetMaximum(155.0) LinearityGraph2.GetXaxis().SetLimits(0.0, 155.0) LinearityGraph2.GetXaxis().SetLabelSize(0.) LinearityGraph2.GetXaxis().SetNdivisions(520) LinearityGraph2.GetYaxis().SetNdivisions(520) c = TCanvas("c", "canvas", 800, 800) # Upper histogram plot is pad1 pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetBottomMargin(0.02) # joins upper and lower plot pad1.SetLeftMargin(0.1) pad1.SetRightMargin(0.1) pad1.Draw() # Lower ratio plot is pad2 c.cd() # returns to main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetTopMargin(0.05) # joins upper and lower plot pad2.SetBottomMargin(0.3) pad2.SetLeftMargin(0.1) pad2.SetRightMargin(0.1) pad2.Draw() pad1.cd() LinearityGraph2.Draw() pad2.cd() LinearityGraph.Draw("AP") ratioline = TF1("ratioline", str(np.mean(energyfraction)), 0., 160.) ratioline.SetLineColor(1) ratioline.SetLineWidth(1) ratioline.SetLineStyle(9) ratioline.Draw("same") ratioline.Write() c.Update() #c.SaveAs("MLratio.pdf") c.Write() femgraph = TGraphErrors(len(energies), energies, femvalues, zeros, femvalueserror) femgraph.SetName("fem_graph") femfit = TF1("femfit", "1.-(x/[0])**([1]-1.)", 10., 150.) femgraph.Fit("femfit", "R") femgraph.Write() zvalues = array('d', [math.log(x) for x in zvalues]) logenergies = array('d', [math.log(x) for x in energies]) zgraph = TGraphErrors(len(logenergies), logenergies, zvalues, zeros, zvalueserror) zgraph.SetName("z_graph") zfit = TF1("zfit", "pol1", 2.2, 5.1) zgraph.Fit("zfit", "R") zgraph.Write() znormgraph = TGraphErrors(len(energies), energies, znormvalues, zeros, znormvalueserror) znormgraph.SetName("znorm_graph") znormgraph.Write() ''' Resolutions = TMultiGraph() Resolutions.Add(ResolutionGraphScin) Resolutions.Add(ResolutionGraphCher) Resolutions.Add(ResolutionGraph) Resolutions.SetName("EMResolutions") Resolutions.Write() Linearities = TMultiGraph() Linearities.Add(LinearityGraph) Linearities.Add(LinearityGraphScin) Linearities.Add(LinearityGraphCher) Linearities.SetName("Linearities") Linearities.Write() ''' return RecEnergyHist.GetFunction("gaus").GetParameter( 2), RecEnergyHist.GetFunction("gaus").GetParameter( 1), RecEnergyHist.GetFunction("gaus").GetChisquare()
def main(argv): #Usage controls from OptionParser parser_usage = "outputfile.root filename1.root ... filenameN.root" parser = OptionParser(usage=parser_usage) (options, args) = parser.parse_args(argv) if (len(args) == 0): parser.print_help() return if (SCAN_OVER_ENERGY and SCAN_OVER_THETA): print "ERROR: both scan flags turned on! Please select either energy or theta to scan over..." return if (not SCAN_OVER_ENERGY and not SCAN_OVER_THETA): print "ERROR: neither scan flags turned on! Please select either energy or theta to scan over..." return gStyle.SetOptFit(11111) #Show fit results in panel c1 = TCanvas("c1", "c1", 1600, 900) BASE_FOLDER_STRING = "" if (IS_FCAL is True): BASE_FOLDER_STRING = "FCAL_photon_gun_hists" else: BASE_FOLDER_STRING = "BCAL_photon_gun_hists" file_list = [] curr_E_val = 0.1 for i in range(1, len(args)): file_list.append(TFile.Open(argv[i], 'read')) scan_val_arr = array('d', []) scan_val_arr_arr_err = array('d', []) effic_gauscore_arr = array('d', []) effic_gauscore_err_arr = array('d', []) effic_anyquality_arr = array('d', []) effic_anyquality_err_arr = array('d', []) effic_gauscore_1show_arr = array('d', []) effic_gauscore_1show_err_arr = array('d', []) effic_anyquality_1show_arr = array('d', []) effic_anyquality_1show_err_arr = array('d', []) avg_reconE_arr = array('d', []) # curr_E_val = 0.1 for i in range(0, len(file_list)): print "Current file: " + argv[i + 1] #For normalization if IS_FCAL: h_curr_showers = file_list[i].Get(BASE_FOLDER_STRING + "/h_NFCALShowers") else: h_curr_showers = file_list[i].Get(BASE_FOLDER_STRING + "/h_NBCALShowers") h_ThrownPhotonE_curr = TH1F() h_ThrownPhotonTheta_curr = TH1F() h_ThrownPhotonE_curr = file_list[i].Get(BASE_FOLDER_STRING + "/h_ThrownPhotonE") h_ThrownPhotonTheta_curr = file_list[i].Get(BASE_FOLDER_STRING + "/h_thrownTheta") norm_count = h_ThrownPhotonE_curr.GetEntries() print "Denominator: " + str(norm_count) # print "Norm count is: " + str(norm_count) for j in range(0, h_curr_showers.GetNbinsX()): if (h_curr_showers.GetBinCenter(j) > 1 and h_curr_showers.GetBinContent(j) > 0): # print "reducing norm count by " + str(h_curr_showers.GetBinContent(j)) if ZERO_OR_ONE_SHOWERS_ONLY: norm_count -= h_curr_showers.GetBinContent(j) # print "Now norm count is: " + str(norm_count) if (norm_count < MIN_EVENTS): continue atleast_one_shower = norm_count - h_curr_showers.GetBinContent( 1) #Bin 1 corresponds to 0 showers # curr_E_val = my_gaus_fit.GetParameter(1) # curr_E_val = h_ThrownPhotonE_curr.GetBinLowEdge( h_ThrownPhotonE_curr.GetMaximumBin()+1 ) curr_E_val = h_ThrownPhotonE_curr.GetMean() curr_theta_val = h_ThrownPhotonTheta_curr.GetMean() print "Current theta: " + str(curr_theta_val) # h_curr = file_list[i].Get("h_foundE_all_dist") h_curr = file_list[i].Get(BASE_FOLDER_STRING + "/" + shower_hist_name) #Fit once with pure gaussian fit_center = curr_E_val #Fiting around reconstructed energy. if (not USE_EDIST_FOR_FITTING): fit_center = 0 #Fitting DeltaPhi instead, should be centered around 0. my_gaus_fit = TF1("my_gaus_fit", "gausn+gausn(3)", 0.001, 3.) my_gaus_fit.SetParLimits(0, 0, 10000) my_gaus_fit.SetParLimits(1, fit_center - 0.2, fit_center + 0.1) my_gaus_fit.SetParLimits(2, 0.005, 0.4) my_gaus_fit.SetParLimits(0 + 3, 0, 10000) my_gaus_fit.SetParLimits(1 + 3, fit_center - 0.2, fit_center + 0.1) my_gaus_fit.SetParLimits(2 + 3, 0.005, 0.4) my_gaus_fit.SetNpx(1000) if (curr_E_val < 0.26 and not IS_FCAL): my_gaus_fit.FixParameter(3, 0) # One gaussian only h_curr.GetXaxis().SetRangeUser(fit_center - VAL_BELOWTHROWN_TOFIT * 2, fit_center + VAL_ABOVETHROWN_TOFIT * 2) h_curr.Fit(my_gaus_fit, "Q", "", fit_center - VAL_BELOWTHROWN_TOFIT, fit_center + VAL_ABOVETHROWN_TOFIT) h_curr.Fit(my_gaus_fit, "QL", "", fit_center - VAL_BELOWTHROWN_TOFIT, fit_center + VAL_ABOVETHROWN_TOFIT) if (POLY_ORDER >= 1): gaus_fit_amplitude = my_gaus_fit.GetParameter(0) gaus_fit_mean = my_gaus_fit.GetParameter(1) gaus_fit_sigma = my_gaus_fit.GetParameter(2) gaus_fit_amplitude2 = my_gaus_fit.GetParameter(0 + 3) gaus_fit_mean2 = my_gaus_fit.GetParameter(1 + 3) gaus_fit_sigma2 = my_gaus_fit.GetParameter(2 + 3) gaus_plus_poly_fit = TF1( "gaus_plus_poly_fit", "gausn+gausn(3)+pol" + str(POLY_ORDER) + "(6)", 0.001, 3.) gaus_plus_poly_fit.SetParameter(0, gaus_fit_amplitude) gaus_plus_poly_fit.SetParameter(1, gaus_fit_mean) gaus_plus_poly_fit.SetParameter(2, gaus_fit_sigma) gaus_plus_poly_fit.SetParameter(0 + 3, gaus_fit_amplitude2) gaus_plus_poly_fit.SetParameter(1 + 3, gaus_fit_mean2) gaus_plus_poly_fit.SetParameter(2 + 3, gaus_fit_sigma2) gaus_plus_poly_fit.SetParLimits(0, 0, 10000) gaus_plus_poly_fit.SetParLimits(1, fit_center - 0.2, fit_center + 0.1) gaus_plus_poly_fit.SetParLimits(2, 0.005, 0.7) gaus_plus_poly_fit.SetParNames("YieldUnnorm", "Mean", "#sigma", "YieldUnnorm2", "Mean2", "#sigma2", "pol0", "pol1", "pol2", "pol3") # Need different fitting routine for low energy BCAL showers if (curr_E_val < 0.26 and not IS_FCAL): my_gaus_fit.FixParameter(3, 0) # One gaussian only for i in range(0, POLY_ORDER + 1): my_gaus_fit.FixParameter(6 + i, 0) h_curr.Fit(gaus_plus_poly_fit, "Q", "", fit_center - VAL_BELOWTHROWN_TOFIT, fit_center + VAL_ABOVETHROWN_TOFIT) h_curr.Fit(gaus_plus_poly_fit, "QL", "", fit_center - VAL_BELOWTHROWN_TOFIT, fit_center + VAL_ABOVETHROWN_TOFIT) if SCAN_OVER_ENERGY: c1.SaveAs(".plots/FitE_" + str(curr_E_val) + "_" + PLOT_TAG + ".png") if SCAN_OVER_THETA: c1.SaveAs(".plots/FitTheta_" + str(curr_theta_val) + "_" + PLOT_TAG + ".png") if (curr_E_val > 0.28 or IS_FCAL): effic_gauscore_arr.append( ((my_gaus_fit.GetParameter(0) + my_gaus_fit.GetParameter(3)) / h_curr.GetBinWidth(0)) / norm_count) effic_gauscore_err_arr.append( sqrt( (my_gaus_fit.GetParameter(0) + my_gaus_fit.GetParameter(3)) // h_curr.GetBinWidth(0)) / norm_count) if (curr_E_val < 0.28 and not IS_FCAL): effic_gauscore_arr.append(h_curr.GetEntries() / norm_count) effic_gauscore_err_arr.append( sqrt(h_curr.GetEntries()) / norm_count) avg_reconE_arr.append(h_curr.GetMean()) effic_anyquality_arr.append(atleast_one_shower / norm_count) effic_anyquality_err_arr.append(0) if (SCAN_OVER_ENERGY): scan_val_arr.append(curr_E_val) if (SCAN_OVER_THETA): scan_val_arr.append(curr_theta_val) scan_val_arr_arr_err.append(0) # curr_E_val+=0.05 # curr_E_val = 0.1 # for i in range(0,len(file_list)): # print "Current file: " + argv[i] # h_curr = file_list[i].Get("h_foundE_1orless_all_dist") # my_gaus_fit = TF1("my_gaus_fit","gausn",0.001,3.) # my_gaus_fit.SetParLimits(0,0,100) # my_gaus_fit.SetNpx(1000); # h_curr.GetXaxis().SetRangeUser(0.01,3.5) # h_curr.Fit(my_gaus_fit,"Q") # curr_E_val = my_gaus_fit.GetParameter(1) # c1.SaveAs(".plots/FitE_1show_"+str(curr_E_val)+".png") # effic_gauscore_1show_arr.append((my_gaus_fit.GetParameter(0)/h_curr.GetBinWidth(0))/10000) # effic_gauscore_1show_err_arr.append(my_gaus_fit.GetParError(0)/h_curr.GetBinWidth(0)/10000) # effic_anyquality_1show_arr.append((10000.-h_curr.GetBinContent(1))/10000) # effic_anyquality_1show_err_arr.append(0) for i in range(0, len(scan_val_arr)): print "Value: " + str(scan_val_arr[i]) print "Efficiency: " + str(effic_gauscore_arr[i]) print "" gr_gauscore_effic = TGraphErrors(len(file_list), scan_val_arr, effic_gauscore_arr, scan_val_arr_arr_err, effic_gauscore_err_arr) gr_gauscore_effic.SetMarkerStyle(15) gr_gauscore_effic.SetMarkerSize(1.2) gr_gauscore_effic.SetMarkerColor(kBlue) gr_gauscore_effic.SetName("gr_gauscore_effic") gr_gauscore_effic.SetTitle("Efficiency at 1 GeV") if (SCAN_OVER_ENERGY): gr_gauscore_effic.GetXaxis().SetTitle("E_{#gamma} (GeV)") if (SCAN_OVER_THETA): gr_gauscore_effic.GetXaxis().SetTitle("Photon #theta (degrees)") gr_gauscore_effic.GetYaxis().SetTitle("Efficiency") # gr_gauscore_effic.GetXaxis().SetRangeUser(0,12.) gr_anyquality_effic = TGraphErrors(len(file_list), scan_val_arr, effic_anyquality_arr, scan_val_arr_arr_err, effic_anyquality_err_arr) gr_anyquality_effic.SetName("gr_anyquality_effic") gr_anyquality_effic.SetMarkerStyle(15) gr_anyquality_effic.SetMarkerSize(1.2) gr_anyquality_effic.SetMarkerColor(kBlue) # gr_gauscore_1show_effic = TGraphErrors( len(file_list), E_arr, effic_gauscore_1show_arr, E_arr_err, effic_gauscore_1show_err_arr) # gr_gauscore_1show_effic.SetMarkerStyle(15) # gr_gauscore_1show_effic.SetMarkerSize(1.2) # gr_gauscore_1show_effic.SetMarkerColor(kBlue) # gr_gauscore_1show_effic.SetName("gr_gauscore_1show_effic") # gr_anyquality_1show_effic = TGraphErrors( len(file_list), E_arr, effic_anyquality_1show_arr, E_arr_err, effic_anyquality_1show_err_arr) # gr_anyquality_1show_effic.SetName("gr_anyquality_1show_effic") # gr_anyquality_1show_effic.SetMarkerStyle(15) # gr_anyquality_1show_effic.SetMarkerSize(1.2) # gr_anyquality_1show_effic.SetMarkerColor(kBlue) gr_gauscore_effic.Draw("AP") c1.SaveAs("GaussianCoreEfficiency.png") gr_anyquality_effic.Draw("AP") c1.SaveAs("AnyQualityEfficiency.png") gr_avg_reconE = TGraph(len(file_list), scan_val_arr, avg_reconE_arr) gr_avg_reconE.SetName("gr_avg_reconE") f_out = TFile(argv[0], "RECREATE") f_out.cd() gr_gauscore_effic.Write() gr_anyquality_effic.Write() gr_avg_reconE.Write() # gr_gauscore_1show_effic.Write() # gr_anyquality_1show_effic.Write() f_out.Close() print("Done ")
def main(): gROOT.SetBatch(True) parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument("-add", "--add", action="store_true", dest="useADD", default=False, help="use ADD instead of CI.") parser.add_argument("-truncation", "--truncation", action="store_true", dest="truncation", default=False, help="use ADD instead of CI.") parser.add_argument("-s", "--suffix", dest="suffix", default='nominal', help="name of systematic to use") args = parser.parse_args() useADD = args.useADD histos = ["BB", "BE"] labels = [ "dielectron_2016", "dimuon_2016", "dimuon_2017", "dielectron_2017", "dimuon_2018", "dielectron_2018" ] suffixesMu = [ "nominal", "scaleup", "scaledown", "smeared", "muonid", "pdfWeightsUp", "pdfWeightsDown" ] suffixesEle = [ "nominal", "scaledown", "scaleup", "pileup", "piledown", "pdfWeightsUp", "pdfWeightsDown", 'prefireup', 'prefiredown' ] css = ["inc", "cspos", "csneg"] lambdas = [10, 16, 22, 28, 34, 40, 46] interferences = ["Con", "Des"] hels = ["LL", "RL", "LR", "RR"] massBins = [400, 500, 700, 1100, 1900, 3500] if useADD: labels = [ "dielectron_2016", "dimuon_2016", "dimuon_2017", "dielectron_2017", "dimuon_2018", "dielectron_2018" ] lambdas = [3500 + i * 500 for i in range(12)] lambdas.append(10000) interferences = [""] hels = [""] massBins = [1800, 2200, 2600, 3000, 3400] outDir = "parametrizations" if args.truncation: outDir = "parametrizationsTruncation" graphs = [] for label in labels: print(label) if "dimuon" in label: suffixes = suffixesMu else: suffixes = suffixesEle if not args.suffix in suffixes: continue suffix = args.suffix for cs in css: for histo in histos: for hel in hels: for interference in interferences: model = interference + hel addci = "CI" if useADD: addci = "ADD" if "dimuon" in label: name = "%sto2mu" % addci else: #~ print signalYields name = "%sto2e" % addci if useADD: if not "2016" in label: massBins = [1800, 2200, 2600, 3000, 3400] else: massBins = [1900, 2200, 2600, 3000, 3400] if "2016" in label: fitFile = TFile( outDir + "/%s_%s_%s_%s_parametrization_fixinf_2016.root" % (name, suffix, histo.lower(), cs), "READ") elif "2018" in label: fitFile = TFile( outDir + "/%s_%s_%s_%s_parametrization_fixinf_2018.root" % (name, suffix, histo.lower(), cs), "READ") else: fitFile = TFile( outDir + "/%s_%s_%s_%s_parametrization_fixinf.root" % (name, suffix, histo.lower(), cs), "READ") else: if "2016" in label: fitFile = TFile( outDir + "/%s_%s_%s_%s_parametrization_fixinf_limitp0_limitp1_limitp2_2016.root" % (name, suffix, histo.lower(), cs), "READ") elif "2018" in label: fitFile = TFile( outDir + "/%s_%s_%s_%s_parametrization_fixinf_limitp0_limitp1_limitp2_2018.root" % (name, suffix, histo.lower(), cs), "READ") else: fitFile = TFile( outDir + "/%s_%s_%s_%s_parametrization_fixinf_limitp0_limitp1_limitp2.root" % (name, suffix, histo.lower(), cs), "READ") # ~ print (fitFile.ls()) # ~ print ("%s_%s_%s_%s_parametrization_fixinf.root"%(name,suffix,histo.lower(),cs)) if "dimuon" in label: plotName = "Mu" + histo.lower() + suffix else: plotName = "Ele" + histo.lower() + suffix if not cs == "inc": plotName = plotName + cs plot = getPlot(plots[plotName]) eventCounts = totalNumberOfGeneratedEvents( path, plot.muon) negWeights = negWeightFractions(path, plot.muon) if "2016" in label: lumi = 35922.0 if plot.muon: lumi = 36294.6 elif "2018" in label: lumi = 59401.0 if plot.muon: lumi = 61298.775231718995 else: lumi = 41500.0 if plot.muon: lumi = 42079.880396 if "2016" in label: zScaleFac = zScale2016["muons"] if not plot.muon: if "bbbe" in plot.histName: zScaleFac = zScale2016["electrons"][0] elif "bb" in plot.histName: zScaleFac = zScale2016["electrons"][1] elif "be" in plot.histName: zScaleFac = zScale2016["electrons"][2] else: zScaleFac = zScale2016["electrons"][0] elif "2018" in label: zScaleFac = zScale2018["muons"] if not plot.muon: if "bbbe" in plot.histName: zScaleFac = zScale2018["electrons"][0] elif "bb" in plot.histName: zScaleFac = zScale2018["electrons"][1] elif "be" in plot.histName: zScaleFac = zScale2018["electrons"][2] else: zScaleFac = zScale2018["electrons"][0] else: zScaleFac = zScale["muons"] if not plot.muon: if "bbbe" in plot.histName: zScaleFac = zScale["electrons"][0] elif "bb" in plot.histName: zScaleFac = zScale["electrons"][1] elif "be" in plot.histName: zScaleFac = zScale["electrons"][2] else: zScaleFac = zScale["electrons"][0] background = "DrellYan" if "2016" in label: DY = Process(getattr(Backgrounds2016, background), eventCounts, negWeights) elif "2018" in label: DY = Process(getattr(Backgrounds2018, background), eventCounts, negWeights) else: DY = Process(getattr(Backgrounds, background), eventCounts, negWeights) backgroundHist = DY.loadHistogram( plot, lumi, zScaleFac) backgroundHist = backgroundHist.Rebin( len(massBins), name, array('d', massBins + [10000])) for index, massBin in enumerate(massBins): # ~ print (fitFile.ls()) function = fitFile.Get("fn_m%d_%s" % (massBin, model)) fitR = fitFile.Get("fitR_m%d_%s" % (massBin, model)) pars = fitR.GetParams() errs = fitR.Errors() function.SetParameter(0, pars[0]) function.SetParameter(1, pars[1]) function.SetParameter(2, pars[2]) function.SetParError(0, errs[0]) function.SetParError(1, errs[1]) function.SetParError(2, errs[2]) # ~ if useADD: # ~ function.SetParameter(3, pars[3]) # ~ function.SetParError(3, errs[3]) functionUnc = fitFile.Get("fn_unc_m%d_%s" % (massBin, model)) graph = TGraphErrors() graph.SetTitle("%s%s%s%s_M%d" % (label, histo, cs, model, massBin)) graph.SetName("%s%s%s%s_M%d" % (label, histo, cs, model, massBin)) if args.useADD: for indel, l in enumerate(lambdas + [100000]): uncert = ( abs((functionUnc.Eval(l / 1000) / function.Eval(l / 1000))**2 + (functionUnc.Eval(100000) / function.Eval(100000))))**0.5 # ~ print (function.Eval(100000) , backgroundHist.GetBinContent(index+1)) graph.SetPoint( indel, float(l / 1000), function.Eval(l / 1000) - function.Eval(100000) + backgroundHist.GetBinContent(index + 1)) graph.SetPointError( indel, 0, (uncert**2 + backgroundHist.GetBinError(index + 1) **2)**0.5) else: for indel, l in enumerate(lambdas + [100000]): uncert = ( abs((functionUnc.Eval(l) / function.Eval(l))**2 + (functionUnc.Eval(100000) / function.Eval(100000))))**0.5 # ~ print (function.Eval(100000) , backgroundHist.GetBinContent(index+1)) graph.SetPoint( indel, l, function.Eval(l) - function.Eval(100000) + backgroundHist.GetBinContent(index + 1)) graph.SetPointError( indel, 0, (uncert**2 + backgroundHist.GetBinError(index + 1) **2)**0.5) graphs.append(deepcopy(graph)) if args.useADD: suffix += "_add" outFile = TFile(outDir + "/graphsForPriors_%s.root" % suffix, "RECREATE") for graph in graphs: graph.Write() outFile.Close()
inFile.Get("hnew3").Draw() c.Print(remainder[0] + ".pdf", "Title:test") mmean.append(inFile.Get("hnew3").GetFunction("gaus").GetParameter(1)) mresArr.append(inFile.Get("hnew3").GetFunction("gaus").GetParameter(2)) mmeanErr.append(inFile.Get("hnew3").GetFunction("gaus").GetParError(1)) mresArrErr.append(inFile.Get("hnew3").GetFunction("gaus").GetParError(2)) outfile.cd() graph = TGraphErrors(len(massArr), massArr, mresL1p0Arr, zeroArr, mresL1p0Err) graph.Draw("A*") graph.SetTitle("Mass resolution at z=0") graph.GetXaxis().SetTitle("A' mass [GeV]") graph.GetYaxis().SetTitle("constant term [GeV]") graph.Fit("pol1") graph.Write("mres_l1_p0") c.Print(remainder[0] + ".pdf", "Title:test") graph = TGraphErrors(len(massArr), massArr, mresL1p1Arr, zeroArr, mresL1p1Err) graph.Draw("A*") graph.SetTitle("Slope of mass resolution vs. Z") graph.GetXaxis().SetTitle("A' mass [GeV]") graph.GetYaxis().SetTitle("linear term [GeV/mm]") graph.Fit("pol1") graph.Write("mres_l1_p1") c.Print(remainder[0] + ".pdf", "Title:test") graph = TGraphErrors(len(massArr), massArr, mmean, zeroArr, mmeanErr) graph.Draw("A*") graph.SetTitle("Mean Mass") graph.GetXaxis().SetTitle("Vector mass [GeV]")
# tmpGr = TGraph(len(fileNameIndex)) # tmpGr = TGraph(len(fileNameIndex)-1) tmpGr = TGraphErrors(len(fileNameIndex)-1) tmpGr.SetTitle("") tmpGr.GetXaxis().SetTitle("Energy [GeV]") tmpGr.GetYaxis().SetTitle("Efficiency") styleGraph(tmpGr,1) for i in range(0,len(fileNameIndex)): fileName = absPath + fileNamePrefix + fileNameIndex[i] + fileNamePostfix myFile = ROOT.TFile.Open(fileName,"read") iHist = myFile.Get(iDir+"/"+histName) maxBin = iHist.GetMaximumBin() energy = iHist.GetBinCenter(maxBin) eff = iHist.GetBinContent(maxBin) effErr = iHist.GetBinError(maxBin) tmpGr.SetPoint(i,energy,eff) tmpGr.SetPointError(i,0,effErr) print("E:%f, eff:%f +- %f" % (energy, eff, effErr)) outRootFile.cd() tmpGr.Write() outRootFile.Close() c1 = TCanvas( 'c1', 'A Simple Graph Example', 0, 0, 800, 600 ) c1.cd() # tmpGr.Draw("ALP") # c1.SaveAs(iDir+".png")
limitVsMass.GetXaxis().SetTitle("mass [GeV/c^{2}]") limitVsMass.GetYaxis().SetTitle("#lambda_{s}") limitVsMass.SetMinimum(0) limitVsMass.Draw("ape") can.Update() line = TLine(limitVsMass.GetXaxis().GetXmin(),2.5,limitVsMass.GetXaxis().GetXmax(),2.5) line.SetLineStyle(2) line.SetLineColor(ROOT.kRed) line.Draw("same,r") can.Update() #can.SaveAs("gif/limitVsLambdaS.gif") outfile = TFile("out/limitPlot_%s.root"%theDir,"recreate") outfile.cd() limitVsMass.Write("limitVsMass") outfile.Write() outfile.Close() #gres[0].Draw("ape")
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events = TGraphErrors(14) for x in xrange(1, 15): efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetPoint(x - 1, jetToMETTriggerRate.GetY()[x], metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetY()[x]) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetPointError(x - 1, jetToMETTriggerRate.GetEY()[x], metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetEY()[x]) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetTitle("ff_H_WW_enuenu_1000events") efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetName("efficiencyPlotWithRate_ff_H_WW_enuenu_1000events") efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetYaxis().SetTitle("% accepted events") efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetYaxis().SetTitleOffset(1.2) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetYaxis().SetRangeUser(0, 1.1) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetMarkerColor(4) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetLineColor(1) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetMarkerStyle(21) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetXaxis().SetTitle("Rate [Hz]") efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetXaxis().SetTitleOffset(1.2) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.Draw("AP") efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.Write() line_200kHz.Draw() label_200kHz.Draw() text.Draw() canvas.Update() canvas.Print("metEfficiencyPlotWithRate_ff_H_WW_enuenu_1000events.svg", "svg") canvas.Print("metEfficiencyPlotWithRate_ff_H_WW_enuenu_1000events.png", "png") canvas.Print("metEfficiencyPlotWithRate_ff_H_WW_enuenu_1000events.pdf", "pdf") canvas.SetLogx(0) canvas.SetLogy(0) text.SetX1NDC(0.5) text.SetX2NDC(0.9) metTriggerEfficiency_ff_H_WW_munumunu_1000events = DelphesSim_ff_H_WW_munumunu_1000events_efficiency_file.Get("metTriggerEfficiency_errors") metTriggerEfficiency_ff_H_WW_munumunu_1000events.SetMarkerColor(4) metTriggerEfficiency_ff_H_WW_munumunu_1000events.SetLineColor(1)
samplingString = "sampl: " + str(round(fitResult.Get().Parameter(1), 4)) + " #pm " + str( round(fitResult.Get().Error(1), 4)) draw_text([formula], [0.55, 0.8, 0.88, 0.86], colour, 0) draw_text([constString, samplingString], [0.55, 0.7, 0.88, 0.78], colour + 1, 0) cRes.Update() # Save canvas and root file with graph, const term and sampling term if calo_init.output(0): cRes.SaveAs(calo_init.output(0) + ".png") plots = TFile(calo_init.output(0) + ".root", "RECREATE") else: cRes.SaveAs("energy_resolution_plots.png") plots = TFile("energy_resolution_plots.root", "RECREATE") gRes.Write() const = numpy.zeros(1, dtype=float) sampl = numpy.zeros(1, dtype=float) constErr = numpy.zeros(1, dtype=float) samplErr = numpy.zeros(1, dtype=float) t = TTree("params", "Fit parameters") t.Branch("const", const, "const/D") t.Branch("sampl", sampl, "sampl/D") t.Branch("constErr", constErr, "constErr/D") t.Branch("samplErr", samplErr, "samplErr/D") const[0] = fitResult.Get().Parameter(0) sampl[0] = fitResult.Get().Parameter(1) constErr[0] = fitResult.Get().Error(0) samplErr[0] = fitResult.Get().Error(1) t.Fill() plots.Write()
graph2.GetXaxis().SetTitle("Temperature (degree Celsius)") graph2.GetYaxis().SetTitle("Peaks Amp (mV)") for i in range(len(timestamps_array)): binx1 = graph2.GetXaxis().FindBin(timestamps_array[i]) if timestamps_array[i] < time.mktime(datetime.datetime(2019, 7, 5, 14, 0).timetuple()): graph2.GetXaxis().SetBinLabel(binx1, "26.6") elif timestamps_array[i] < time.mktime(datetime.datetime(2019, 7, 5, 15, 50).timetuple()) and timestamps_array[i] >= time.mktime(datetime.datetime(2019, 7, 5, 14, 0).timetuple()): graph2.GetXaxis().SetBinLabel(binx1, "26.7") elif timestamps_array[i] >= time.mktime(datetime.datetime(2019, 7, 5, 15, 50).timetuple()) and timestamps_array[i] < time.mktime(datetime.datetime(2019, 7, 5, 15, 57).timetuple()): graph2.GetXaxis().SetBinLabel(binx1, "26.8") elif timestamps_array[i] >= time.mktime(datetime.datetime(2019, 7, 5, 15, 57).timetuple()) and timestamps_array[i] < time.mktime(datetime.datetime(2019, 7, 5, 16, 5).timetuple()): graph2.GetXaxis().SetBinLabel(binx1, "26.9") elif timestamps_array[i] >= time.mktime(datetime.datetime(2019, 7, 5, 16, 5).timetuple()) and timestamps_array[i] < time.mktime(datetime.datetime(2019, 7, 5, 16, 30).timetuple()): graph2.GetXaxis().SetBinLabel(binx1, "27.0") elif timestamps_array[i] >= time.mktime(datetime.datetime(2019, 7, 5, 16, 30).timetuple()): graph2.GetXaxis().SetBinLabel(binx1, "27.1") graph2.Draw() c1.Update() c1.Print(temp_pdf) # Save graphs to file outputFile = '%speak3_time_plot%s.root' % (OutputPath, scan_nums) f1 = TFile(outputFile, "RECREATE") graph1.Write() graph2.Write() f1.Close()
cEff = TCanvas('cEff', '', 800, 800) cEff.DrawFrame(hPromptFrac.GetBinLowEdge(1), 1.e-4, ptMax, 1., ';#it{p}_{T} (GeV/#it{c}); (Acc#times#font[152]{e})') cEff.SetLogy() hEffAccPrompt.Draw('same') hEffAccFD.Draw('same') legEff.Draw() cEff.Update() outFile = TFile(args.outFileName, 'recreate') hCrossSection.Write() for systSource in systGetter: gCrossSectionSyst[systSource].Write() if args.system == 'pp': gCrossSectionSystLumi.Write() hRawYields.Write() hEffAccPrompt.Write() hEffAccFD.Write() hPromptFrac.Write() hFDFrac.Write() hEvForNorm.Write() cCrossSec.Write() cFrac.Write() cEff.Write() systErr.Write() outFile.Close() if not args.batch: input('Press enter to exit')
print("Would you like to make a histogram of %s? [y/n]" % (labels[i - 2])) yes = ('yes', 'y', 'ye') no = ('no', 'n') name = labels[i - 2] hist = str(labels[i - 2]) hist = hist.strip("['']") print(hist) choice = raw_input() if choice in yes: name = TGraphErrors(len(Arrx[i - 1]), Arrx[i - 1], Det[i - 1], Err[i - 1], Errs[i - 1]) name.SetTitle(" ;X [CM];Hits [PE]") name.SetMarkerColor(i * 3) name.SetLineColor(i * 3) #name.SetYTitle("Hits [PE]") name.Write("%s" % (hist)) elif choice in no: p = True else: sys.stdout.write("Please respond with 'yes' or 'no'") Arrx[i] = array('f', []) Det[i] = array('f', []) Errs[i] = array('f', []) Err[i] = array('f', []) else: Arrx[i].append(float(words[0])) Det[i].append(float(words[2])) Errs[i].append(float(words[3])) Err[i].append(float(words[1])) print('done')
def MakeHistsToFit2(file, f_out_str): E_arr = array('d', []) E_arr_err = array('d', []) effic_arr = array('d', []) effic_arr_err = array('d', []) c1 = TCanvas("c1", "c1", 1600, 900) c1.SetGridx(1) c1.SetGridy(1) #Find which energy files exist, create file list and energy array f_wogamma_list = [] curr_E_val = 0.1 while curr_E_val <= 3.0: normfile = REL_DIR + "tree_pi+pi-p_nofit_" + str(curr_E_val) + ".root" if (os.path.isfile(normfile)): E_arr.append(curr_E_val) E_arr_err.append(0) f_wogamma_list.append(TFile.Open(normfile, 'read')) # print "File found!!!" # print "Was looking for file: " + normfile # print "Current E val: " + str(curr_E_val) # else: # print "File not found!!!!!!!!!!!!!!!!!!!!!!!!!!!!" # print "Was looking for file: " + normfile # print "Current E val: " + str(curr_E_val) curr_E_val += 0.05 #Get normalization factor norm_arr = array('d', []) for i in range(0, len(f_wogamma_list)): my_tr = TTree() my_tr = f_wogamma_list[i].Get("pi+pi-p_nofit_Tree") norm_arr.append(my_tr.GetEntries()) # print "Energy: " + str(E_arr[i]) # print "Normalization: " + str(norm_arr[i]) #Create and fit histograms in larger file f = TFile.Open(file, 'read') my_tr = TTree() my_tr = f.Get("gamma_pi+pi-p_nofit_Tree") h_DeltaPhi_list = [] h_DeltaTheta_list = [] h_EGammaPostCuts_list = [] for i in range(0, len(E_arr)): h_DeltaPhi_curr = TH1F() my_tr.Draw("DeltaPhi>>h_DeltaPhi_curr(1000,-180.,180.)", "") h_DeltaPhi_curr = gPad.GetPrimitive("h_DeltaPhi_curr") h_DeltaPhi_curr.SetName("h_DeltaPhi_" + str(E_arr[i])) h_DeltaPhi_list.append(h_DeltaPhi_curr) h_DeltaTheta_curr = TH1F() my_tr.Draw("DeltaTheta>>h_DeltaTheta_curr(1000,-25.,10.)", "") h_DeltaTheta_curr = gPad.GetPrimitive("h_DeltaTheta_curr") h_DeltaTheta_curr.SetName("h_DeltaTheta_" + str(E_arr[i])) h_DeltaTheta_list.append(h_DeltaTheta_curr) h_EGammaPostCuts_curr = TH1F() E_cut_str = "abs(ThrownE-" + str(E_arr[i]) + ")<0.0001" print "Cut string: " + E_cut_str my_tr.Draw("FoundE>>h_EGammaPostCuts_curr(1000,0,4)", "abs(DeltaPhi)<2.&&abs(DeltaTheta)<0.5&&" + E_cut_str) h_EGammaPostCuts_curr = gPad.GetPrimitive("h_EGammaPostCuts_curr") h_EGammaPostCuts_curr.SetName("h_EGammaPostCuts_" + str(E_arr[i])) h_EGammaPostCuts_list.append(h_EGammaPostCuts_curr) my_gaus_fit = TF1("my_gaus_fit", "gausn") my_gaus_fit.SetParLimits(0, 0, 30000) my_gaus_fit.SetParameter(1, E_arr[i]) my_gaus_fit.SetParLimits(1, E_arr[i] - 0.5, E_arr[i] + 0.1) my_gaus_fit.SetParLimits(2, 0.02, 0.5) my_gaus_fit.SetNpx(1000) h_EGammaPostCuts_curr.Fit(my_gaus_fit, "Q", "", E_arr[i] - 0.3, E_arr[i] + 0.2) c1.SaveAs(".plots/ReactionFilterFit_pipip_" + str(E_arr[i]) + ".png") effic = my_gaus_fit.GetParameter( 0) / h_EGammaPostCuts_curr.GetBinWidth(0) / norm_arr[i] effic_err = my_gaus_fit.GetParError( 0) / h_EGammaPostCuts_curr.GetBinWidth(0) / norm_arr[i] if (E_arr[i] < 0.2): effic = h_EGammaPostCuts_curr.GetEntries() / norm_arr[i] effic_err = sqrt(h_EGammaPostCuts_curr.GetEntries()) / norm_arr[i] if (h_EGammaPostCuts_curr.GetEntries() < 100.): effic = -1 effic_err = 0 print "File Entries: " + str(my_tr.GetEntries()) print "Histogram Entries: " + str(h_EGammaPostCuts_curr.GetEntries()) print "Gaussian yield: " + str( my_gaus_fit.GetParameter(0) / h_EGammaPostCuts_curr.GetBinWidth(0)) print "Normalization: " + str(norm_arr[i]) print "Efficiency: " + str(effic) effic_arr.append(effic) effic_arr_err.append(effic_err) gr_gauscore_effic = TGraphErrors(len(E_arr), E_arr, effic_arr, E_arr_err, effic_arr_err) gr_gauscore_effic.SetName("gr_gauscore_effic") f_out = TFile(f_out_str, "RECREATE") gr_gauscore_effic.Write() for i in range(0, len(E_arr)): h_DeltaPhi_list[i].Write() for i in range(0, len(E_arr)): h_DeltaTheta_list[i].Write() for i in range(0, len(E_arr)): h_EGammaPostCuts_list[i].Write() f_out.Close() # curr_E_val = 0.1 # curr_E_val = 2.0 # while curr_E_val <= 3.: # while curr_E_val <= 2.2: # print "Curr E thing " + str(curr_E_val) # normfile = REL_DIR+"tree_pi+pi-p_nofit_"+str(curr_E_val)+".root" # my_tr2 = TTree() # my_tr2 = f_wogamma_list[i].Get("pi+pi-p_nofit_Tree") # NormalizationFactor = my_tr2.GetEntries() # curr_E_val+=0.05 return
cRes.Update() if not calo_init.args.noLinearity: padLin.cd() gLin.Draw("ape") draw_text(["linearity"], [0.2,0.78, 0.4,0.88], 1, 0).SetTextSize(0.05*factor) if calo_init.args.specialLabel: draw_text([calo_init.args.specialLabel], [0.67,0.78, 0.95,0.88], kGray+3, 0).SetTextSize(0.05*factor) # Save canvas and root file with graph, const term and sampling term if calo_init.output(0): cRes.SaveAs(calo_init.output(0)+".png") plots = TFile(calo_init.output(0)+".root","RECREATE") else: cRes.SaveAs("energy_resolution_plots.gif") plots = TFile("energy_resolution_plots.root","RECREATE") gRes.Write() gLin.Write() const = numpy.zeros(1, dtype=float) sampl = numpy.zeros(1, dtype=float) constErr = numpy.zeros(1, dtype=float) samplErr = numpy.zeros(1, dtype=float) t = TTree("params", "Fit parameters") t.Branch("const", const, "const/D"); t.Branch("sampl", sampl, "sampl/D"); t.Branch("constErr", constErr, "constErr/D"); t.Branch("samplErr", samplErr, "samplErr/D"); const[0] = fitResult.Get().Parameter(0) sampl[0] = fitResult.Get().Parameter(1) constErr[0] = fitResult.Get().Error(0) samplErr[0] = fitResult.Get().Error(1) t.Fill()
PhiHistC.Fit("gaus") ThetaHistCS.Fit("gaus") PhiHistCS.Fit("gaus") ThetaHist.Write() PhiHist.Write() ThetaHistC.Write() PhiHistC.Write() ThetaHistCS.Write() PhiHistCS.Write() truephis.append(phi) truephiserror.append(0.) angresphi.append(PhiHistCS.GetFunction("gaus").GetParameter(2)*1000) angresphierror.append(PhiHistCS.GetFunction("gaus").GetParError(2)*1000) phis.append(PhiHistCS.GetFunction("gaus").GetParameter(1)*180./math.pi-phi) print "true phi "+str(phi)+" measured phi "+str(PhiHistCS.GetFunction("gaus").GetParameter(1)*180./math.pi)+" sigma phi "+str(PhiHistCS.GetFunction("gaus").GetParameter(2)*1000) gStyle.SetOptStat(111) phi_linearity = TGraph(len(truephis), truephis, phis) phi_linearity.GetXaxis().SetTitle("#phi (deg)") phi_linearity.GetYaxis().SetTitle("#phi measured - #phi true (deg)") phi_linearity.SetName("phis_linearity") phi_linearity.Write() sigma_linearity = TGraphErrors(len(truephis), truephis, angresphi, truephiserror, angresphierror) sigma_linearity.GetYaxis().SetTitle("#sigma (mrad)") sigma_linearity.GetXaxis().SetTitle("#phi (deg)") sigma_linearity.SetName("sigma_linearity") sigma_linearity.Write()
s = sliceeff.Fit(efffunc, "S") sliceeff.Draw("AP") #c.Print(outfilename+".pdf"); if s.Get() and s.Get().IsValid() and s.Get().CovMatrixStatus() == 3: massArr.append(cleanhist.GetYaxis().GetBinCenter(iy)) zeroArr.append(0) xintArr.append(s.Parameter(1)) yintArr.append(s.Parameter(0)) xintErrArr.append(s.ParError(1)) yintErrArr.append(s.ParError(0)) xintgraph = TGraphErrors(len(massArr), massArr, xintArr, zeroArr, xintErrArr) xintgraph.SetTitle("X-intercept;mass [GeV];D1") xintgraph.SetName("xintgraph") xintgraph.Write() xintgraph.Draw("A*") xintgraph.GetYaxis().SetRangeUser(0, 1000) xintgraph.Fit("pol3") c.Print(outfilename + ".pdf") yintgraph = TGraphErrors(len(massArr), massArr, yintArr, zeroArr, yintErrArr) yintgraph.Draw("A*") yintgraph.GetYaxis().SetRangeUser(0.5, 1.5) c.Print(outfilename + ".pdf") #clean.Draw("D1>>cleanslice(10,0,500)",xfcut+" && mass>{0} && mass<{1}".format(5.0,5.2)) #cleanslice = gDirectory.Get("cleanslice") #messyclean.Draw("D1>>messyslice(10,0,500)",xfcut+" && mass>{0} && mass<{1}".format(5.0,5.2)) #messyslice = gDirectory.Get("messyslice")
iBinX = Cmap_t0.GetXaxis().FindBin( MATRIX[ix][iy][iz].center[0]) iBinY = Cmap_t0.GetYaxis().FindBin( MATRIX[ix][iy][iz].center[1]) iBinZ = Cmap_t0.GetZaxis().FindBin( MATRIX[ix][iy][iz].center[2]) Cmap.SetBinContent(iBinX, iBinY, iBinZ, C[ix][iy][iz]) if MATRIX[ix][iy][iz].is_degradate(t * dt / 3600): IntegrityMap.SetBinContent(iBinX, iBinY, iBinZ, 0) else: IntegrityMap.SetBinContent(iBinX, iBinY, iBinZ, 1) gMassEvolution.SetPoint(gMassEvolution.GetN(), t * dt / 3600, IntegralT) gMassRelease.SetPoint(gMassRelease.GetN(), t * dt / 3600, (Total_amount_solute - IntegralT) / Total_amount_solute) IntegrityMap.Write('IntegrityMap_t' + str(t * dt)) # Cmap.Write( 'Ct_'+str(t*dt) ) print "Completed!" gMassEvolution.Write("Mass_Evolution") gMassRelease.Write("Mass_Release") gData.Write("YData") gData_2.Write("YData_april2015") hDegradation_time_distribution.Write() FileOutRoot.Close()