def TextFileToRootGraphs(self, limit_text_file,med_idx=0):#, limit_text_filename): filename = limit_text_file #limit_text_filename limit_root_file = limit_text_file.replace(".txt",".root") f = open(filename,"r") med=array('f') mchi=array('f') expm2=array('f') expm1=array('f') expmed=array('f') expp1=array('f') expp2=array('f') obs=array('f') errx=array('f') for line in f: if len(line.rsplit())<7: continue med.append(float(line.rstrip().split()[1])) mchi.append(float(line.rstrip().split()[0])) expm2.append(float(line.rstrip().split()[4]) - float(line.rstrip().split()[2]) ) expm1.append(float(line.rstrip().split()[4]) - float(line.rstrip().split()[3]) ) expmed.append(float(line.rstrip().split()[4])) expp1.append(float(line.rstrip().split()[5]) - float(line.rstrip().split()[4]) ) expp2.append(float(line.rstrip().split()[6]) - float(line.rstrip().split()[4]) ) obs.append(float(line.rstrip().split()[7])) errx.append(0.0) print ('expm2: ', expm2) print ('expm1: ', expm1) print ('expmed: ', expmed) print ('expp1: ', expp1) print ('expp2: ', expp2) g_exp2 = TGraphAsymmErrors(int(len(med)), med, expmed, errx, errx, expm2, expp2 ) ; g_exp2.SetName("exp2") g_exp1 = TGraphAsymmErrors(int(len(med)), med, expmed, errx, errx, expm1, expp1 ) ; g_exp1.SetName("exp1") g_expmed = TGraphAsymmErrors(int(len(med)), med, expmed) ; g_expmed.SetName("expmed") g_obs = TGraphAsymmErrors(int(len(med)), med, obs ) ; g_obs.SetName("obs") f1 = TFile(limit_root_file,'RECREATE') g_exp2.Write() g_exp1.Write() g_expmed.Write() g_obs.Write() f1.Write() f1.Close() return limit_root_file
def HistToAsymmErrs(name,hist) : X = [] EXlow = [] EXhigh = [] Y = [] EYlow = [] EYhigh = [] for i in range(hist.GetNbinsX()) : X .append(hist.GetBinCenter (i+1)) EXlow .append(hist.GetBinWidth (i+1)/2.) EXhigh.append(hist.GetBinWidth (i+1)/2.) Y .append(hist.GetBinContent(i+1)) EYlow .append(hist.GetBinError (i+1)) EYhigh.append(hist.GetBinError (i+1)) a_X = array('d',X ) a_EXlow = array('d',EXlow ) a_EXhigh = array('d',EXhigh ) a_Y = array('d',Y ) a_EYlow = array('d',EYlow ) a_EYhigh = array('d',EYhigh ) asymm = TGraphAsymmErrors(len(a_X),a_X,a_Y,a_EXlow,a_EXhigh,a_EYlow,a_EYhigh) asymm.GetXaxis().SetTitle(hist.GetXaxis().GetTitle()) asymm.GetYaxis().SetTitle(hist.GetYaxis().GetTitle()) asymm.SetLineWidth(2) asymm.SetName(name) return asymm
def makeResidHist(data, bkg): pulls = TGraphAsymmErrors(data.GetN()) pulls.SetName("Pulls") pulls.SetLineWidth(data.GetLineWidth()) pulls.SetLineStyle(data.GetLineStyle()) pulls.SetLineColor(data.GetLineColor()) pulls.SetMarkerSize(data.GetMarkerSize()) pulls.SetMarkerStyle(data.GetMarkerStyle()) pulls.SetMarkerColor(data.GetMarkerColor()) pulls.SetFillStyle(data.GetFillStyle()) pulls.SetFillColor(data.GetFillColor()) # Add histograms, calculate Poisson confidence interval on sum value for i in range(data.GetN()): x = data.GetX()[i] dyl = data.GetErrorYlow(i) dyh = data.GetErrorYhigh(i) yy = data.GetY()[i] - bkg.Interpolate(x) #bkg.GetBinContent(i+1) norm = dyl if yy > 0. else dyh if norm == 0.: yy, dyh, dyl = 0., 0., 0. else: yy /= norm dyh /= norm dyl /= norm pulls.SetPoint(i, x, yy) pulls.SetPointEYhigh(i, dyh) pulls.SetPointEYlow(i, dyl) return pulls
def efficiency(total, passed): name = uuid4().hex if total.GetDimension() == 1: # Reset bin content for bins with 0 in the total to total = 1, passed # = 0. Due to negative weights and low stats some bins can have # passed > total; set the content for such bins to passed = total. _make_consistent(passed, total) # Divide(pass,total,"cl=0.683 b(1,1) mode") rep = TGraphAsymmErrors(passed, total, "cl=0.683 b(1,1) mode") #rep = TGraphAsymmErrors(passed, total) #passed_bins = get_bins(passed, True) #total_bins = get_bins(total, True) #rep_bins = get_bins(rep) #if all([x == 0.0 for x,y in rep_bins]): #print('{0} {1}'.format(process._label, filter)) #print(['{0:7.2f}'.format(y) for x,y in passed_bins]) #print(['{0:7.2f}'.format(y) for x,y in total_bins]) #print(['{0:7.2f}'.format(y) for x,y in rep_bins]) #print(['({0:.0f}, {1:.2f})'.format(x, y) for x,y in rep_bins]) else: rep = passed.Clone(name) rep.Divide(total) rep.SetName(name) return rep
def QuadratureUpDown(asymlist, hists=[], doFlatUnc=False, FlatUp=0.0, FlatDown=0.0): # These are TGraphAsymmErrors total_unc_up_sq = [] total_unc_dn_sq = [] for i in range(asymlist[0].GetN()): total_unc_up_sq.append(0) total_unc_dn_sq.append(0) # # asym err hists # for i in range(asymlist[0].GetN()): for j in range(len(asymlist)): E_up = asymlist[j].GetEYhigh()[i] E_dn = asymlist[j].GetEYlow()[i] total_unc_up_sq[i] += math.pow(E_up, 2) total_unc_dn_sq[i] += math.pow(E_dn, 2) # # hists # for i in range(len(total_unc_up_sq)): for j in range(len(hists)): E_up = hists[j].GetBinError(i + 1) E_dn = hists[j].GetBinError(i + 1) total_unc_up_sq[i] += math.pow(E_up, 2) total_unc_dn_sq[i] += math.pow(E_dn, 2) # # flat uncertainty # if doFlatUnc: for i in range(len(total_unc_up_sq)): total_unc_up_sq[i] += math.pow(FlatUp * asymlist[0].GetY()[i], 2) total_unc_dn_sq[i] += math.pow(FlatDown * asymlist[0].GetY()[i], 2) # # sqrt # for i in range(len(total_unc_up_sq)): total_unc_up_sq[i] = math.sqrt(total_unc_up_sq[i]) total_unc_dn_sq[i] = math.sqrt(total_unc_dn_sq[i]) #print 'Setting up unc to ',total_unc_up_sq[i] #print 'Setting dn unc to ',total_unc_dn_sq[i] #print total_unc_up_sq #print total_unc_dn_sq yup = array('d', total_unc_up_sq) ydn = array('d', total_unc_dn_sq) #print yup #print ydn result = TGraphAsymmErrors(asymlist[0].GetN(), asymlist[0].GetX(), asymlist[0].GetY(), asymlist[0].GetEXlow(), asymlist[0].GetEXhigh(), ydn, yup) result.GetXaxis().SetTitle(asymlist[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(asymlist[0].GetName() + ' Total Error') return result
def envelope(thedict, thelist, nominal): # # Takes the nominal and makes an envelope around it # diff_up = nominal.Clone() key = 'diff_up' diff_up.SetNameTitle(key, key) diff_dn = nominal.Clone() key = 'diff_dn' diff_dn.SetNameTitle(key, key) for i in range(diff_up.GetNbinsX()): diff_up.SetBinContent(i + 1, 0) diff_dn.SetBinContent(i + 1, 0) # for var in thelist: if var == 'dummy': continue for i in range(nominal.GetNbinsX()): curr_diff_up = diff_up.GetBinContent(i + 1) curr_diff_dn = diff_dn.GetBinContent(i + 1) nominal_bc = nominal.GetBinContent(i + 1) thisvar_bc = thedict[var].GetBinContent(i + 1) diff_up.SetBinContent(i + 1, max(curr_diff_up, thisvar_bc - nominal_bc)) diff_dn.SetBinContent(i + 1, min(curr_diff_dn, thisvar_bc - nominal_bc)) nbins = nominal.GetNbinsX() x = array( 'd', list(nominal.GetBinCenter(a + 1) for a in range(nominal.GetNbinsX()))) xup = array( 'd', list( nominal.GetBinWidth(a + 1) / 2. for a in range(nominal.GetNbinsX()))) xdn = array( 'd', list( nominal.GetBinWidth(a + 1) / 2. for a in range(nominal.GetNbinsX()))) y = array( 'd', list(nominal.GetBinContent(a + 1) for a in range(nominal.GetNbinsX()))) yup = array( 'd', list(diff_up.GetBinContent(a + 1) for a in range(nominal.GetNbinsX()))) ydn = array( 'd', list( diff_dn.GetBinContent(a + 1) * -1. for a in range(nominal.GetNbinsX()))) result = TGraphAsymmErrors(nbins, x, y, xdn, xup, ydn, yup) result.GetXaxis().SetTitle(nominal.GetXaxis().GetTitle()) result.GetYaxis().SetTitle(nominal.GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(nominal.GetName() + ' Envelope') return result
def geterrorband(*hists, **kwargs): """Make an error band histogram for a list of histograms, or stack. Returns an TGraphAsymmErrors object.""" verbosity = LOG.getverbosity(kwargs) hists = unwraplistargs(hists) hists = [ h.GetStack().Last() if isinstance(h, THStack) else h for h in hists ] sysvars = kwargs.get( 'sysvars', []) # list of tuples with up/cent/down variation histograms name = kwargs.get('name', None) or "error_" + hists[0].GetName() title = kwargs.get( 'title', None) or ("Sys. + stat. unc." if sysvars else "Stat. unc.") color = kwargs.get('color', kBlack) hist0 = hists[0] nbins = hist0.GetNbinsX() if sysvars and isinstance(sysvars, dict): sysvars = [v for k, v in sysvars.iteritems()] error = TGraphAsymmErrors() error.SetName(name) error.SetTitle(title) LOG.verb("geterrorband: Making error band for %s" % (hists), verbosity, 2) TAB = LOG.table( "%5s %7s %6s %10s %11s %-20s %-20s %-20s", "%5d %7.6g %6.6g %10.2f %11.2f +%8.2f -%8.2f +%8.2f -%8.2f +%8.2f -%8.2f", verb=verbosity, level=3) TAB.printheader("ibin", "xval", "xerr", "nevts", "sqrt(nevts)", "statistical unc.", "systematical unc.", "total unc.") ip = 0 for ibin in range(1, nbins + 1): xval = hist0.GetXaxis().GetBinCenter(ibin) xerr = 0 if ibin in [0, nbins + 1] else hist0.GetXaxis().GetBinWidth(ibin) / 2 yval = 0 statlow2, statupp2 = 0, 0 syslow2, sysupp2 = 0, 0 for hist in hists: # STATISTICS yval += hist.GetBinContent(ibin) statlow2 += hist.GetBinErrorLow(ibin)**2 statupp2 += hist.GetBinErrorUp(ibin)**2 for histup, hist, histdown in sysvars: # SYSTEMATIC VARIATIONS syslow2 += (hist.GetBinContent(ibin) - histdown.GetBinContent(ibin))**2 sysupp2 += (hist.GetBinContent(ibin) - histup.GetBinContent(ibin))**2 ylow2, yupp2 = statlow2 + syslow2, statupp2 + sysupp2, error.SetPoint(ip, xval, yval) error.SetPointError(ip, xerr, xerr, sqrt(ylow2), sqrt(yupp2)) TAB.printrow(ibin, xval, xerr, yval, sqrt(abs(yval)), sqrt(statupp2), sqrt(statlow2), sqrt(sysupp2), sqrt(syslow2), sqrt(yupp2), sqrt(ylow2)) ip += 1 seterrorbandstyle(error, color=color) #error.SetLineColor(hist0.GetLineColor()) error.SetLineWidth(hist0.GetLineWidth()) # use draw option 'E2 SAME' return error
def makeEffPlotsVars(tree, varx, vary, sel, nbinx, xmin, xmax, nbiny, ymin, ymax, xtitle, ytitle, leglabel=None, header='', addon='', option='pt', marker=20): binning = [20, 30, 40, 50, 60, 70, 80, 100, 150, 200] c = TCanvas() if option == 'pt': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, array('d', binning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, array('d', binning)) elif option == 'eta': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin, xmax) elif option == 'nvtx': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(vbinning) - 1, array('d', vbinning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(vbinning) - 1, array('d', vbinning)) tree.Draw(varx + ' >> ' + _hist_.GetName(), sel) tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary) g_efficiency = TGraphAsymmErrors() g_efficiency.BayesDivide(_ahist_, _hist_) g_efficiency.GetXaxis().SetTitle(xtitle) g_efficiency.GetYaxis().SetTitle('efficiency') g_efficiency.GetYaxis().SetNdivisions(507) g_efficiency.SetLineWidth(3) g_efficiency.SetName(header) g_efficiency.SetMinimum(0.) g_efficiency.GetYaxis().SetTitleOffset(1.3) g_efficiency.SetMarkerStyle(marker) g_efficiency.SetMarkerSize(1) g_efficiency.Draw('ap') # save(c, 'plots/' + addon) return copy.deepcopy(g_efficiency)
def GetTGraphAsymmErrors(histo, offset): graph_in = TGraphAsymmErrors(histo) graph_in.SetName(histo.GetName() + '_tmp') graph_out = TGraphAsymmErrors(histo) graph_out.SetName(histo.GetName() + '_offset') for i in range(graph_in.GetN()): graph_out.GetX()[i] = graph_in.GetX()[i] + offset graph_out.GetEXlow()[i] = graph_in.GetEXlow()[i] + offset graph_out.GetEXhigh()[i] = graph_in.GetEXhigh()[i] - offset x_min = graph_out.GetX()[0] - graph_out.GetEXlow()[0] if (x_min > 0): x_min = 0 x_max = graph_out.GetX()[graph_out.GetN() - 1] + graph_out.GetEXhigh()[graph_out.GetN() - 1] graph_out.GetXaxis().SetLimits(x_min, x_max) return graph_out
def QuadratureUpDown(name,asymlist=[],hists=[],AddHists=False) : # These are TGraphAsymmErrors asymlist1 = [] for i in asymlist : asymlist1.append(i) for i in range(len(hists)) : asymlist1.append(HistToAsymmErrs(hists[i].GetName()+' QuadratureUpDown Asymm',hists[i])) nbins = asymlist1[0].GetN() total_unc_up_sq = [] total_unc_dn_sq = [] for i in range(nbins) : total_unc_up_sq.append(0) total_unc_dn_sq.append(0) # # asym err hists # for i in range(nbins) : for j in range(len(asymlist1)) : E_up = asymlist1[j].GetEYhigh()[i] E_dn = asymlist1[j].GetEYlow()[i] total_unc_up_sq[i] += math.pow(E_up,2) total_unc_dn_sq[i] += math.pow(E_dn,2) # # # # hists # # # for i in range(nbins) : # for j in range(len(hists)) : # E_up = hists[j].GetBinError(i+1) # E_dn = hists[j].GetBinError(i+1) # total_unc_up_sq[i] += math.pow(E_up,2) # total_unc_dn_sq[i] += math.pow(E_dn,2) # # sqrt # for i in range(nbins) : total_unc_up_sq[i] = math.sqrt(total_unc_up_sq[i]) total_unc_dn_sq[i] = math.sqrt(total_unc_dn_sq[i]) y = [] for i in range(nbins) : y.append(asymlist1[0].GetY()[i]) if AddHists : for j in range(1,len(asymlist1)) : y[-1] += asymlist1[j].GetY()[i] ybincontent = array('d',y) yup = array('d',total_unc_up_sq) ydn = array('d',total_unc_dn_sq) result = TGraphAsymmErrors(asymlist1[0].GetN(),asymlist1[0].GetX(),ybincontent ,asymlist1[0].GetEXlow(),asymlist1[0].GetEXhigh() ,ydn,yup) result.GetXaxis().SetTitle(asymlist1[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist1[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result
def getDataPoissonErrors(hist, kPoisson=False, drawZeroBins=False, drawXbars=False, centerBin=True): '''Make data poisson errors for a histogram with two different methods: - TH1.kPoisson - chi-squared quantile ''' # https://github.com/DESY-CMS-SUS/cmgtools-lite/blob/8_0_25/TTHAnalysis/python/plotter/mcPlots.py#L70-L102 # https://github.com/DESY-CMS-SUS/cmgtools-lite/blob/8_0_25/TTHAnalysis/python/plotter/susy-1lep/RcsDevel/plotDataPredictWithSyst.py#L12-L21 if kPoisson: hist.SetBinErrorOption(TH1D.kPoisson) Nbins = hist.GetNbinsX() xaxis = hist.GetXaxis() alpha = (1 - 0.6827) / 2. graph = TGraphAsymmErrors(Nbins) graph.SetName(hist.GetName() + "_graph") graph.SetTitle(hist.GetTitle()) for i in xrange(1, Nbins + 1): N = hist.GetBinContent(i) if N <= 0 and not drawZeroBins: continue dN = hist.GetBinError(i) yscale = 1 if centerBin: x = xaxis.GetBinCenter(i) else: x = xaxis.GetBinLowEdge(i) if N > 0 and dN > 0 and abs(dN**2 / N - 1) > 1e-4: # check is error is Poisson yscale = (dN**2 / N) N = (N / dN)**2 if kPoisson: EYlow = hist.GetBinErrorLow(i) EYup = hist.GetBinErrorUp(i) else: EYlow = (N - Math.chisquared_quantile_c(1 - alpha, 2 * N) / 2.) if N > 0 else 0 EYup = Math.chisquared_quantile_c(alpha, 2 * (N + 1)) / 2. - N y = yscale * N EXup = xaxis.GetBinUpEdge(i) - x if drawXbars else 0 EXlow = x - xaxis.GetBinLowEdge(i) if drawXbars else 0 graph.SetPoint(i - 1, x, y) graph.SetPointError(i - 1, EXlow, EXup, EYlow, EYup) #print ">>> getDataPoissonErrors - bin %2d: (x,y) = ( %3.1f - %4.2f + %4.2f, %4.2f - %4.2f + %4.2f )"%(i,x,EXlow,EXup,y,EYlow,EYup) graph.SetLineWidth(hist.GetLineWidth()) graph.SetLineColor(hist.GetLineColor()) graph.SetLineStyle(hist.GetLineStyle()) graph.SetMarkerSize(hist.GetMarkerSize()) graph.SetMarkerColor(hist.GetMarkerColor()) graph.SetMarkerStyle(hist.GetMarkerStyle()) return graph
def dividebybinsize(hist, **kwargs): """Divide each bin by its bin width. If a histogram has assymmetric errors (e.g. data with Poisson), return a TGraphAsymmErrors instead.""" verbosity = LOG.getverbosity(kwargs) LOG.verbose('dividebybinsize: "%s"' % (hist.GetName()), verbosity, 2) zero = kwargs.get('zero', True) # include bins that are zero in TGraph zeroerrs = kwargs.get('zeroerrs', True) # include errors for zero bins errorX = kwargs.get('errorX', gStyle.GetErrorX()) # horizontal error bars nbins = hist.GetXaxis().GetNbins() TAB = LOG.table("%5s %8.6g %8.6g %10.3f %9.4f %8.4f %8.4f %10.4f", verb=verbosity, level=3) TAB.printheader("ibin", "xval", "width", "yval", "yerr", "yupp", "ylow", "yerr/width") if hist.GetBinErrorOption( ) == TH1.kPoisson: # make asymmetric Poisson errors (like for data) graph = TGraphAsymmErrors() graph.SetName(hist.GetName() + "_graph") graph.SetTitle(hist.GetTitle()) copystyle(graph, hist) ip = 0 # skip zero bins if not zero for ibin in xrange(1, nbins + 1): xval = hist.GetXaxis().GetBinCenter(ibin) width = hist.GetXaxis().GetBinWidth(ibin) xerr = width / 2 if errorX else 0 yval = hist.GetBinContent(ibin) yerr = hist.GetBinError(ibin) yupp = hist.GetBinErrorUp(ibin) ylow = hist.GetBinErrorLow(ibin) TAB.printrow(ibin, xval, width, yval, yerr, yupp, ylow, yval / width) hist.SetBinContent(ibin, yval / width) hist.SetBinError(ibin, yerr / width) if yval != 0 or zero: graph.SetPoint(ip, xval, yval / width) if yval != 0 or zeroerrs: graph.SetPointError(ip, xerr, xerr, ylow / width, yupp / width) else: graph.SetPointError(ip, xerr, xerr, 0, 0) ip += 1 return graph else: for ibin in xrange(0, nbins + 2): xval = hist.GetXaxis().GetBinCenter(ibin) width = hist.GetXaxis().GetBinWidth(ibin) yval = hist.GetBinContent(ibin) yerr = hist.GetBinError(ibin) hist.SetBinContent(ibin, yval / width) hist.SetBinError(ibin, yerr / width) TAB.printrow(ibin, xval, width, yval, yerr, hist.GetBinErrorUp(ibin), hist.GetBinErrorLow(ibin), yval / width) return hist
def makeEffPlotsVars(tree, varx, vary, sel, nbinx, xmin, xmax, nbiny, ymin, ymax, xtitle, ytitle, leglabel=None, header='', addon='', option='pt', marker=20, col=1): binning = [20, 200] if args.onebin else [ 20, 30, 40, 50, 60, 70, 80, 100, 150, 200 ] if option == 'pt': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, array('d', binning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, array('d', binning)) elif option == 'eta': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin, xmax) tree.Draw(varx + ' >> ' + _hist_.GetName(), sel) tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary) g_efficiency = TGraphAsymmErrors() g_efficiency.Divide(_ahist_, _hist_, "cl=0.683 b(1,1) mode") g_efficiency.GetXaxis().SetTitle(xtitle) g_efficiency.GetYaxis().SetTitle('efficiency') g_efficiency.GetYaxis().SetNdivisions(507) g_efficiency.SetLineWidth(3) g_efficiency.SetName(header) g_efficiency.SetMinimum(0.) g_efficiency.GetYaxis().SetTitleOffset(1.3) g_efficiency.SetMarkerStyle(marker) g_efficiency.SetMarkerSize(1) g_efficiency.SetMarkerColor(col) g_efficiency.SetLineColor(col) g_efficiency.Draw('ap') # save(c, 'plots/' + addon) return g_efficiency
def rescaleEff(fin): var = "pt" num = fin.Get("%s_rv_cat0_tot" % var).Clone() den = fin.Get("%s_cat0_tot" % var).Clone() xbins = numpy.array([0., 10., 20., 30., 40., 50., 70., 110., 250.]) num_rebin = num.Rebin(len(xbins) - 1, "num_rebin", xbins) den_rebin = den.Rebin(len(xbins) - 1, "den_rebin", xbins) eff = TGraphAsymmErrors(num_rebin, den_rebin) eff.SetName("efficiency") return eff
def getGraph(result, label): masses = result["mass"] massErr = result["massErr"] sigma = result["sigma"] sigmaErr = result["sigmaErr"] res = TGraphAsymmErrors(len(masses)) res.SetName(label) for i, mass in enumerate(masses): res.SetPoint(i, mass, sigma[i]) res.SetPointError(i, massErr[i], massErr[i], sigmaErr[i], sigmaErr[i]) return res
def FlatErrorToAsymmErrs(name,nomhist,up_frac=0.,dn_frac=0.) : nom_2_asymm = HistToAsymmErrs(nomhist.GetName()+' FlatErrorToAsymmErrs Asymm',nomhist) EYlow = [] EYhigh = [] for i in range(nom_2_asymm.GetN()) : EYlow.append(nom_2_asymm.GetY()[i]*dn_frac) EYhigh.append(nom_2_asymm.GetY()[i]*up_frac) a_EYlow = array('d',EYlow ) a_EYhigh = array('d',EYhigh ) result = TGraphAsymmErrors(nom_2_asymm.GetN(),nom_2_asymm.GetX(),nom_2_asymm.GetY() ,nom_2_asymm.GetEXlow(),nom_2_asymm.GetEXhigh() ,a_EYlow,a_EYhigh) result.GetXaxis().SetTitle(nom_2_asymm.GetXaxis().GetTitle()) result.GetYaxis().SetTitle(nom_2_asymm.GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result
def getGraph(result, label, Data=False): ptda = result["ptda"] if Data: sigma = result["da_nChi2"] else: sigma = result["mc_nChi2"] sigmaErr = 0 res = TGraphAsymmErrors(len(ptda)) res.SetName(label) for i, pt in enumerate(ptda): res.SetPoint(i, pt, sigma[i]) res.SetPointError(i, ptda[i] - ptbins[i], ptbins[i + 1] - ptda[i], 0, 0) return res
def diffGraph(self, g, h, opt): gdiff = TGraphAsymmErrors(g) gdiff.SetName(g.GetName() + h.GetName() + '_diff') for i in range(0, gdiff.GetN()): x = Double(0.) y = Double(0.) g.GetPoint(i, x, y) gdiff.SetPoint(i, x, y - h.GetBinContent(i + 1)) if opt == 1: # keep bin errors pass elif opt == 2: gdiff.SetPointEYhigh( i, math.sqrt(g.GetErrorYhigh(i)**2 + h.GetBinError(i + 1)**2)) return gdiff
def PseudoTextToGraphTimeScan(textfilename): print "parsing: ", textfilename dirname = "timescanOutput/" filename = textfilename f = open(filename, "r").readlines() firstLine = f.pop(0) #removes the first line adc_ = array('f') adc_1 = array('f') adc_2 = array('f') adc_3 = array('f') adc_4 = array('f') prob = array('f') prob_e = array('f') errx = array('f') for line in f: adc_.append(float(line.rstrip().split()[0])) adc_1.append(float(line.rstrip().split()[0]) + 0.1) adc_2.append(float(line.rstrip().split()[0]) + 0.2) adc_3.append(float(line.rstrip().split()[0]) + 0.3) adc_4.append(float(line.rstrip().split()[0]) + 0.4) prob.append(float(line.rstrip().split()[1])) prob_e.append(float(line.rstrip().split()[2])) errx.append(0.0) g_prob_ = TGraphAsymmErrors(int(len(adc_)), adc_, prob, errx, errx, prob_e, prob_e) g_prob_.SetName("prob_") f1 = TFile(filename.replace('.txt', '.root'), 'RECREATE') g_prob_.Write() f1.Close()
def LinearUpDown(name,asymlist=[],hists=[],AddHists=False) : for i in range(len(hists)) : asymlist.append(HistToAsymmErrs(hists[i].GetName()+' LinearUpDown Asymm',hists[i])) nbins = asymlist[0].GetN() total_unc_up = [] total_unc_dn = [] for i in range(nbins) : total_unc_up.append(0) total_unc_dn.append(0) # # asym err hists # for i in range(nbins) : for j in range(len(asymlist)) : total_unc_up[i] += asymlist[j].GetEYhigh()[i] total_unc_dn[i] += asymlist[j].GetEYlow()[i] y = [] for i in range(nbins) : y.append(asymlist[0].GetY()[i]) if AddHists : for j in range(1,len(asymlist)) : y[-1] += asymlist[j].GetY()[i] ybincontent = array('d',y) yup = array('d',total_unc_up) ydn = array('d',total_unc_dn) result = TGraphAsymmErrors(asymlist[0].GetN(),asymlist[0].GetX(),ybincontent ,asymlist[0].GetEXlow(),asymlist[0].GetEXhigh() ,ydn,yup) result.GetXaxis().SetTitle(asymlist[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result return
def getRatio(result, result2, label, Data=False): ptda = result["ptda"] ptda2 = result2["ptda"] if Data: sigma = result["da_nChi2"] sigma2 = result2["da_nChi2"] else: sigma = result["mc_nChi2"] sigma2 = result2["mc_nChi2"] print(sigma) print(sigma2) ratio = TGraphAsymmErrors(len(ptda)) ratio.SetName(label) for i, pt in enumerate(ptda): ratio.SetPoint(i, pt, sigma[i] / sigma2[i]) ratio.SetPointError(i, ptda[i] - ptbins[i], ptbins[i + 1] - ptda[i], 0, 0) return ratio
def fixPlots_withErrors(middleGraph): thisBandsGraph = TGraphAsymmErrors() thisBandsGraph.SetName(middleGraph.GetName()) thisBandsGraph.SetMarkerStyle(middleGraph.GetMarkerStyle()) thisBandsGraph.SetMarkerSize(middleGraph.GetMarkerSize()) thisBandsGraph.SetMarkerColor(middleGraph.GetMarkerColor()) thisBandsGraph.SetLineColor(middleGraph.GetLineColor()) for iPoint in xrange(0, middleGraph.GetN()): # Retrieve middle graph for (x,y) coordinates dataPointX = Double(0) dataPointY = Double(0) dataErrorX = Double(0) middleGraph.GetPoint(iPoint, dataPointX, dataPointY) dataErrorX = middleGraph.GetErrorX(iPoint) dataErrorY = middleGraph.GetErrorY(iPoint) dataPointY = fabs(dataPointY - 1) if (iPoint < middleGraph.GetN()): #if(dataPointY != 0 and iPoint < middleGraph.GetN()): print "fixPlots:", dataPointX thisBandsGraph.SetPoint(iPoint, dataPointX, dataPointY) thisBandsGraph.SetPointError(iPoint, dataErrorX, dataErrorX, dataErrorY, dataErrorY) #if (dataPointY == 0) : #thisBandsGraph.SetPoint(iPoint, dataPointX, dataPointY) #thisBandsGraph.SetPointError(iPoint, dataErrorX, dataErrorX, dataErrorY, dataErrorY) return thisBandsGraph
def makeEffPlotsVars(tree, varx, numeratorAddSelection, baseSelection, binning, xtitle='', header='', addon='', marker=20, col=1): _denomHist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, binning) _nominatorHist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, binning) tree.Draw(varx + ' >> ' + _denomHist_.GetName(), baseSelection) tree.Draw(varx + ' >> ' + _nominatorHist_.GetName(), baseSelection + ' && ' + numeratorAddSelection) g_eff = TGraphAsymmErrors() g_eff.Divide(_nominatorHist_, _denomHist_, "cl=0.683 b(1,1) mode") g_eff.GetXaxis().SetTitle(xtitle) g_eff.GetYaxis().SetTitle('efficiency') g_eff.GetYaxis().SetNdivisions(507) g_eff.SetLineWidth(3) g_eff.SetName(header) g_eff.SetMinimum(0.) g_eff.GetYaxis().SetTitleOffset(1.3) g_eff.SetMarkerStyle(marker) g_eff.SetMarkerSize(1) g_eff.SetMarkerColor(col) g_eff.SetLineColor(col) g_eff.Draw('ap') return g_eff
expm1.append(expmed_ - expm1_) expmed.append(expmed_) expp1.append(expp1_ - expmed_) expp2.append(expp2_ - expmed_) obs.append(obs_) errx.append(0.0) log += str(ival_) + " " + str(expm2_) + " " + str( expm1_) + " " + str(expmed_) + " " + str(expp1_) + " " + str( expp2_) + " " + str(obs_) + "\n" # print ival, float(line.rstrip().split()[4]), xsec_, float(line.rstrip().split()[4])/xsec_ log += "\n" g_exp2 = TGraphAsymmErrors(int(len(xvals)), xvals, expmed, errx, errx, expm2, expp2) g_exp2.SetName("exp2") g_exp1 = TGraphAsymmErrors(int(len(xvals)), xvals, expmed, errx, errx, expm1, expp1) g_exp1.SetName("exp1") g_expmed = TGraphAsymmErrors(int(len(xvals)), xvals, expmed) g_expmed.SetName("expmed") g_obs = TGraphAsymmErrors(int(len(xvals)), xvals, obs) g_obs.SetName("obs") f1 = TFile(scanname + '/' + scanname + '_MH4-' + str(M) + '.root', 'RECREATE') g_exp2.Write() g_exp1.Write() g_expmed.Write() g_obs.Write()
latex.SetTextColor(1) latex.SetTextFont(42) latex.SetTextAlign(33) latex.SetTextSize(0.04) latex.SetTextFont(62) latex.DrawLatex(0.30, 0.96, "GIF++") etichetta = TLatex() etichetta.SetNDC() etichetta.SetTextSize(0.04) etichetta.SetTextColor(4) etichetta.SetTextFont(102) etichetta.DrawLatex(0.45, 0.8, "#splitline{SL1_L1 threshold scan}{Runs: "+str(run_interval)+"}") can_scan_SL1_L1.Update() can_scan_SL1_L1.Print(outpath + "ThresholdScan_SL1_L1_"+run_interval+".png") can_scan_SL1_L1.Print(outpath + "ThresholdScan_SL1_L1_"+run_interval+".pdf") graph.SetName("ThresholdScan_SL1_L1_"+run_interval) new_file_SL1_L1 = TFile(outpath + "Graph_thresholdScan_SL1_L1_"+run_interval+ ".root",'RECREATE') graph.Write() graph.Set(0) #SL1_L4 can_scan_SL1_L4 = TCanvas("can_scan_SL1_L4","can_scan_SL1_L4", 1000, 800) can_scan_SL1_L4.SetGrid() can_scan_SL1_L4.cd() graph = TGraphAsymmErrors() n=0 for a in sorted(scan_SL1_L4): #print scan_SL1_L4[a] graph.SetPoint(n,a,scan_SL1_L4[a]) n = n+1 graph.SetMarkerSize(1.)
def makeBand(middleGraph, lowerGraph, upperGraph, noorder): bandsGraph = TGraphAsymmErrors() bandsGraph.SetName(middleGraph.GetName()) bandsGraph.SetMarkerStyle(middleGraph.GetMarkerStyle()) bandsGraph.SetMarkerColor(middleGraph.GetMarkerColor()) bandsGraph.SetLineColor(middleGraph.GetLineColor()) x1 = Double(0) x2 = Double(0) x3 = Double(0) y = [] y.append(Double(0)) y.append(Double(0)) y.append(Double(0)) tmp = Double(0) if lowerGraph.GetN() != upperGraph.GetN() or lowerGraph.GetN( ) != middleGraph.GetN(): print "Plots don't have the same number of points!" print "Lower: ", lowerGraph.GetN() print "Upper: ", upperGraph.GetN() print "Middle: ", middleGraph.GetN() return 0 #again a hack to forget about the 1st point for iPoint in xrange(1, lowerGraph.GetN()): middleGraph.GetPoint(iPoint, x1, y[0]) lowerGraph.GetPoint(iPoint, x1, y[1]) upperGraph.GetPoint(iPoint, x1, y[2]) if (iPoint == lowerGraph.GetN() - 1): x2 = x1 else: upperGraph.GetPoint(iPoint + 1, x2, buf) if (iPoint == 0): x3 = x1 else: upperGraph.GetPoint(iPoint - 1, x3, buf) tmp = Double(0) yup = Double(0) yce = Double(0) ydn = Double(0) if noorder == 0: yce = y[0] ydn = y[1] yup = y[2] elif noorder == 1: tmp = y[2] if y[1] < y[2]: y[2] = y[1] y[1] = tmp yce = y[0] ydn = y[1] yup = y[2] else: for p in [0, 1, 2]: for q in [0, 1, 2]: if y[q] > y[q + 1]: tmp = y[q + 1] y[q + 1] = y[q] y[q] = tmp ydn = y[0] yce = y[1] yup = y[2] bandsGraph.SetPoint(iPoint, x1, yce) ex0 = Double(lowerGraph.GetErrorX(iPoint)) binwl = Double(0) binwh = Double(0) if (ex0 == 0): binwl = (x1 - x3) / 2. binwh = (x2 - x1) / 2. if binwl == 0.: binwl = binwh if binwh == 0.: binwh = binwl else: binwl = ex0 binwh = ex0 dxl = Double(yce - ydn) dxh = Double(yup - yce) if noorder == 0: if dxl < 0: tmp = -dxl dxl = dxh dxh = tmp bandsGraph.SetPointError(iPoint, binwl, binwh, dxl, dxh) return bandsGraph
latex.SetTextSize(0.04) latex.SetTextFont(62) latex.DrawLatex(0.30, 0.96, "GIF++") etichetta = TLatex() etichetta.SetNDC() etichetta.SetTextSize(0.04) etichetta.SetTextColor(418) etichetta.SetTextFont(102) etichetta.DrawLatex( 0.2, 0.8, "#splitline{SL1_L1 HV scan}{Runs: " + str(run_interval) + "}") can_HV_scan_SL1_L1.Update() can_HV_scan_SL1_L1.Print(outpath + "HVScan_SL1_L1_" + str(run_interval) + options.optionalstring + ".png") can_HV_scan_SL1_L1.Print(outpath + "HVScan_SL1_L1_" + str(run_interval) + options.optionalstring + ".pdf") graph_HV_L1.SetName("HV_scan_SL1_L1_" + run_interval) new_file_HV_scan_SL1_L1 = TFile( outpath + "Graph_HV_scan_SL1_L1_" + run_interval + options.optionalstring + ".root", 'RECREATE') graph_HV_L1.Write() graph_HV_L1.Set(0) print "Graph_HV_scan_SL1_L1_" + run_interval + options.optionalstring + ".root written in " + outpath ##Prepare the canvas to plot the HV scan for SL1_L4 can_HV_scan_SL1_L4 = TCanvas("can_HV_scan_SL1_L4", "can_HV_scan_SL1_L4", 1000, 800) can_HV_scan_SL1_L4.SetGrid() can_HV_scan_SL1_L4.cd() ##Prepare summary TGraph graph_HV_L4 = TGraphAsymmErrors() n = 0
def RootifyCrossBR(self): for processname in self.processnames: outfilename_cross = self.crosssecfolder+'/Crosssections_%s%s.root' % (processname, self.tag) cross_module = importlib.import_module('crosssections.ChiPsi.Crosssections_%s' % (processname)) crosssections = cross_module.crosssection if self.submit: outfile = TFile(outfilename_cross, 'RECREATE') else: print yellow('--> Would have created outfile %s' % (outfilename_cross)) print green('--> Now at sample %s' % (processname)) for lamb in self.lambdas: if not lamb in crosssections: continue print green(' --> Now at lambda: %s' % (get_lambdastring(lamb))) xsecs_per_mref = crosssections[lamb] graph2d = TGraph2D() npoints2d=0 set_points ={} all_combinations = get_all_combinations(preferred_configurations=preferred_configurations) for mlq in all_combinations: set_points[mlq] = {} for mch in all_combinations[mlq]: set_points[mlq][mch] = False for mref in xsecs_per_mref: xsecs = xsecs_per_mref[mref] final_xsecs = [] mdeps = array('d') sigmas = array('d') tot_los = array('d') tot_his = array('d') mdeps_lo = array('d') mdeps_hi = array('d') for tuple in xsecs: mdep, sigma, q_lo, q_hi, pdf = tuple tot_lo = XsecTotErr(sigma, q_lo, pdf) tot_hi = XsecTotErr(sigma, q_hi, pdf) final_xsecs.append((mdep, sigma, tot_lo, tot_hi)) mdeps.append(mdep) sigmas.append(sigma) tot_los.append(tot_lo) tot_his.append(tot_hi) mdeps_lo.append(0.) mdeps_hi.append(0.) if 'LQLQ' in processname or 'LQTChannel' in processname: graph2d.SetPoint(npoints2d, mdep, mref, sigma) set_points[mdep][mref] = True elif 'PsiPsi' in processname: graph2d.SetPoint(npoints2d, mref, mdep, sigma) set_points[mref][mdep] = True else: raise ValueError('processname does not contain \'LQLQ\' or \'PsiPsi\', what kind of process are we looking at here?') npoints2d += 1 # make TGraph out of it graph = TGraphAsymmErrors(len(mdeps), mdeps, sigmas, mdeps_lo, mdeps_hi, tot_los, tot_his) xaxistitle = 'M_{LQ} [GeV]' if ('LQLQ' in processname or 'LQTChannel' in processname) else 'M_{#chi_{1}} [GeV]' graph.GetXaxis().SetTitle('M_{LQ} [GeV]') graph.GetYaxis().SetTitle('#sigma [pb]') graphname = processname if 'LQLQ' in processname or 'LQTChannel' in processname: graphname += '_MC1%i' % (mref) elif 'PsiPsi' in processname: graphname += '_MLQ%i' % (mref) else: raise ValueError('processname does not contain \'LQLQ\' or \'PsiPsi\', what kind of process are we looking at here?') graphname += '_L%s' % (get_lambdastring(lamb)) graph.SetName(graphname) # print 'graphname: %s' % (graphname) graphtitle = processname if 'LQLQ' in processname or 'LQTChannel' in processname: graphtitle += ', M_{#chi_{1}} = %i GeV' % (mref) elif 'PsiPsi' in processname: graphtitle += ', M_{LQ} = %i GeV' % (mref) graphtitle += ', #lambda = %s' % (get_lambdastring(lamb).replace('p', '.')) # print 'graphtitle: %s' % (graphtitle) graph.SetTitle(graphtitle) if self.submit: outfile.cd() graph.Write() else: print yellow(' --> Would have written graph %s to outfile' % (graphname)) # fill remaining points in 2d graph with zeros for mlq in set_points: for mch in set_points[mlq]: if not set_points[mlq][mch]: graph2d.SetPoint(npoints2d, mlq, mch, 0.) npoints2d += 1 graph2d.SetName(processname + '_L%s' % (get_lambdastring(lamb))) graph2d.GetXaxis().SetTitle('M_{LQ} [GeV]') graph2d.GetYaxis().SetTitle('M_{#chi_{1}} = %i [GeV]') graph2d.GetZaxis().SetTitle('#sigma [pb]') graph2d.SetTitle(processname + ', #lambda = %s' % (get_lambdastring(lamb).replace('p', '.'))) if self.submit: graph2d.Write() else: print yellow(' --> Would have written 2d-graph to outfile') if self.submit: outfile.Close() # also rootify BRs if we are looking at the LQLQ process without decays (just for fun, could also be any other LQLQ process) if processname == 'LQLQ': outfilename_br = self.crosssecfolder+'/Branchingratios_%s%s.root' % (processname, self.tag) if self.submit: outfile = TFile(outfilename_br, 'RECREATE') else: print yellow('--> Would have created outfile %s' % (outfilename_br)) br_module = importlib.import_module('crosssections.ChiPsi.Branchingratios_%s' % (processname)) allbrs = br_module.branchingratio for lamb in allbrs.keys(): brs = allbrs[lamb] brs2d = {} npoints2d = {} set_points ={} for mlq in all_combinations: set_points[mlq] = {} for mch in all_combinations[mlq]: set_points[mlq][mch] = {} for decaymode in decaymode_dict.keys(): set_points[mlq][mch][decaymode] = False decaymodes_present = [] for mlq in sorted(brs): mchs_per_decaymode = {} brs_per_decaymode = {} for mch in sorted(brs[mlq]): for decaymode in brs[mlq][mch]: if not decaymode in decaymodes_present: decaymodes_present.append(decaymode) if not decaymode in mchs_per_decaymode.keys(): mchs_per_decaymode[decaymode] = array('d') if not decaymode in brs_per_decaymode.keys(): brs_per_decaymode[decaymode] = array('d') # if not decaymode in set_points[mlq][mch].keys(): # # print mlq, mch, decaymode # set_points[mlq][mch][decaymode] = False if not decaymode in brs2d.keys(): graphname2d = processname + ('_L%s_%i_%i' % (get_lambdastring(lamb), abs(decaymode[0]), abs(decaymode[1]))) # print graphname2d npoints2d[decaymode] = 0 brs2d[decaymode] = TGraph2D() brs2d[decaymode].SetName(graphname2d) brs2d[decaymode].GetXaxis().SetTitle('M_{LQ} [GeV]') brs2d[decaymode].GetYaxis().SetTitle('M_{#chi_{1}} = %i [GeV]') brs2d[decaymode].GetZaxis().SetTitle('BR (LQLQ#rightarrow%s)' % (decaymode_dict[decaymode])) brs2d[decaymode].SetTitle(processname + ', %s' % (decaymode_dict[decaymode])) mchs_per_decaymode[decaymode].append(mch) brs_per_decaymode[decaymode].append(brs[mlq][mch][decaymode][0]) brs2d[decaymode].SetPoint(npoints2d[decaymode], mlq, mch, brs[mlq][mch][decaymode][0]) set_points[mlq][mch][decaymode] = True npoints2d[decaymode] += 1 for decaymode in mchs_per_decaymode.keys(): graph = TGraph(len(mchs_per_decaymode[decaymode]), mchs_per_decaymode[decaymode], brs_per_decaymode[decaymode]) graphname = processname + ('_MLQ%i_L%s_%i_%i' % (mlq, get_lambdastring(lamb), abs(decaymode[0]), abs(decaymode[1]))) graph.SetName(graphname) graph.GetXaxis().SetTitle('M_{#chi_{1}} [GeV]') graph.GetYaxis().SetTitle('BR (LQLQ#rightarrow%s)' % (decaymode_dict[decaymode])) graph.SetTitle(processname + ', %s' % (decaymode_dict[decaymode])) if self.submit: graph.Write() else: print yellow(' --> Would have written graph %s to outfile' % (graphname)) # fill remaining points in 2d graph with zeros for mlq in set_points: for mch in set_points[mlq]: for decaymode in set_points[mlq][mch]: if not set_points[mlq][mch][decaymode] and decaymode in decaymodes_present: # print decaymode # print brs2d.keys() # print npoints2d.keys() # print 'Setting BR for MLQ=%i, MCH=%i, decay=(%i, %i) to 0' % (mlq, mch, decaymode[0], decaymode[1]) brs2d[decaymode].SetPoint(npoints2d[decaymode], mlq, mch, 0) npoints2d[decaymode] += 1 if self.submit: for decaymode in brs2d: brs2d[decaymode].Write() else: print yellow(' --> Would have written 2d-graphs to outfile') outfile.Close()
prob_29.append(float(line.rstrip().split()[9])) prob_e_29.append(float(line.rstrip().split()[10])) errx.append(0.0) #adc_1 = [i+0.1 for i in adc_] #adc_2 = [i+0.2 for i in adc_] #adc_3 = [i+0.3 for i in adc_] #adc_4 = [i+0.4 for i in adc_] print adc_1 g_prob_ = TGraphAsymmErrors(int(len(adc_)), adc_, prob, errx, errx, prob_e, prob_e) g_prob_.SetName("prob_") g_prob_26_ = TGraphAsymmErrors(int(len(adc_1)), adc_1, prob_26, errx, errx, prob_e_26, prob_e_26) g_prob_26_.SetName("prob_26_") g_prob_27_ = TGraphAsymmErrors(int(len(adc_)), adc_2, prob_27, errx, errx, prob_e_27, prob_e_27) g_prob_27_.SetName("prob_27_") g_prob_28_ = TGraphAsymmErrors(int(len(adc_)), adc_3, prob_28, errx, errx, prob_e_28, prob_e_28) g_prob_28_.SetName("prob_28_") g_prob_29_ = TGraphAsymmErrors(int(len(adc_)), adc_4, prob_29, errx, errx, prob_e_29, prob_e_29) g_prob_29_.SetName("prob_29_") f1 = TFile(filename.replace('.txt', '.root'), 'RECREATE')
def TextToGraphTimeScan(textfilename): dirname="timescanOutput/" #filenames=['timescanOutput/Rate_2017data_FrontTrain_cutval_2.txt','timescanOutput/Rate_2017data_FrontTrain_cutval_4.txt','timescanOutput/Rate_2017data_FrontTrain_cutval_6.txt','timescanOutput/Rate_2017data_FrontTrain_cutval_8.txt','timescanOutput/Rate_2017data_FrontTrain_cutval_10.txt'] filename = textfilename f = open(filename,"r").readlines() firstLine = f.pop(0) #removes the first line adc_ = array('f') adc_1 = array('f') adc_2 = array('f') adc_3 = array('f') adc_4 = array('f') prob = array('f') prob_e = array('f') prob_26 = array('f') prob_e_26 = array('f') prob_27 = array('f') prob_e_27 = array('f') prob_28 = array('f') prob_e_28 = array('f') prob_29 = array('f') prob_e_29 = array('f') errx = array('f') for line in f: adc_.append( float( line.rstrip().split()[0])) adc_1.append( float( line.rstrip().split()[0]) + 0.1) adc_2.append( float( line.rstrip().split()[0]) + 0.2) adc_3.append( float( line.rstrip().split()[0]) + 0.3) adc_4.append( float( line.rstrip().split()[0]) + 0.4) prob.append( float( line.rstrip().split()[1]) ) prob_e.append( float( line.rstrip().split()[2]) ) prob_26.append( float( line.rstrip().split()[3]) ) prob_e_26.append( float( line.rstrip().split()[4]) ) prob_27.append( float( line.rstrip().split()[5]) ) prob_e_27.append( float( line.rstrip().split()[6]) ) prob_28.append( float( line.rstrip().split()[7]) ) prob_e_28.append( float( line.rstrip().split()[8]) ) prob_29.append( float( line.rstrip().split()[9]) ) prob_e_29.append( float( line.rstrip().split()[10]) ) errx.append(0.0) #adc_1 = [i+0.1 for i in adc_] #adc_2 = [i+0.2 for i in adc_] #adc_3 = [i+0.3 for i in adc_] #adc_4 = [i+0.4 for i in adc_] print adc_1 g_prob_ = TGraphAsymmErrors(int(len(adc_)), adc_, prob, errx, errx, prob_e, prob_e ) ; g_prob_.SetName("prob_") g_prob_26_ = TGraphAsymmErrors(int(len(adc_1)), adc_1, prob_26, errx, errx, prob_e_26, prob_e_26 ) ; g_prob_26_.SetName("prob_26_") g_prob_27_ = TGraphAsymmErrors(int(len(adc_)), adc_2, prob_27, errx, errx, prob_e_27, prob_e_27 ) ; g_prob_27_.SetName("prob_27_") g_prob_28_ = TGraphAsymmErrors(int(len(adc_)), adc_3, prob_28, errx, errx, prob_e_28, prob_e_28 ) ; g_prob_28_.SetName("prob_28_") g_prob_29_ = TGraphAsymmErrors(int(len(adc_)), adc_4, prob_29, errx, errx, prob_e_29, prob_e_29 ) ; g_prob_29_.SetName("prob_29_") f1 = TFile(filename.replace('.txt','.root'), 'RECREATE') g_prob_.Write() g_prob_26_.Write() g_prob_27_.Write() g_prob_28_.Write() g_prob_29_.Write() f1.Close()