def makeDependencyPlot(path,selection,plots,useMC,backgrounds,runRange,cmsExtra): colors = createMyColors() for plotName in plots: plot = getPlot(plotName) plot.addRegion(selection) plot.cuts = plot.cuts % runRange.runCut if "Forward" in selection.name: region = "forward" elif "Central" in selection.name: region = "central" else: region = "inclusive" tmpCuts = plot.cuts for binName in ["lowMass","highMass"]: plot.cuts = tmpCuts plot.cuts += "*(p4.M() > %f && p4.M() < %f)"%(getattr(mllBins,binName).low,getattr(mllBins,binName).high) histEE, histMM, histEM = getHistograms(path,plot,runRange,False,[]) histSF = histEE.Clone("histSF") histSF.Add(histMM.Clone()) histOFSF = histEM.Clone("histOFSF") histOFEE = histEM.Clone("histOFEE") histOFMM = histEM.Clone("histOFMM") histOFSF.Scale(getattr(rSFOF,region).val) histOFEE.Scale(getattr(rEEOF,region).val) histOFMM.Scale(getattr(rMMOF,region).val) if useMC: histEEMC, histMMMC, histEMMC = getHistograms(path,plot,runRange,True,backgrounds) histSFMC = histEEMC.Clone("histSFMC") histSFMC.Add(histMMMC.Clone()) histOFSFMC = histEMMC.Clone("histOFSFMC") histOFEEMC = histEMMC.Clone("histOFEEMC") histOFMMMC = histEMMC.Clone("histOFMMMC") histOFSFMC.Scale(getattr(rSFOF,region).valMC) histOFEEMC.Scale(getattr(rEEOF,region).valMC) histOFMMMC.Scale(getattr(rMMOF,region).valMC) histsSFMC = {} histsOFMC = {} histsSFMC["SF"] = histSFMC histsSFMC["EE"] = histEEMC histsSFMC["MM"] = histMMMC histsOFMC["SF"] = histOFSFMC histsOFMC["EE"] = histOFEEMC histsOFMC["MM"] = histOFMMMC histsSF = {} histsOF = {} histsSF["SF"] = histSF histsSF["EE"] = histEE histsSF["MM"] = histMM histsOF["SF"] = histOFSF histsOF["EE"] = histOFEE histsOF["MM"] = histOFMM for combination in ["SF","EE","MM"]: hCanvas = TCanvas("hCanvas", "Distribution", 800,800) plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1) ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3) style = setTDRStyle() ROOT.gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() sfHist = histsSF[combination] bkgHist = histsOF[combination] sfHist.SetMarkerStyle(20) bkgHist.SetLineColor(ROOT.kBlue+3) bkgHist.SetLineWidth(2) yMax = sfHist.GetBinContent(sfHist.GetMaximumBin()) if plot.yMax == 0: yMax = yMax*1.35 else: yMax = plot.yMax plotPad.DrawFrame(plot.firstBin,0,plot.lastBin, yMax,"; %s ; %s" %(plot.xaxis,plot.yaxis)) latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)"%runRange.printval) latexCMS.DrawLatex(0.21,0.88,"CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.21,yLabelPos,"%s"%(cmsExtra)) if combination == "SF": rSFOFErr = getattr(rSFOF,region).err elif combination == "EE": rSFOFErr = getattr(rEEOF,region).err elif combination == "MM": rSFOFErr = getattr(rMMOF,region).err errGraph, histUp, histDown = getErrHist(plot,combination,region,bkgHist,None,rSFOFErr) errGraph.SetFillColor(myColors["MyBlue"]) errGraph.SetFillStyle(3001) #~ errGraph.SetLineColor(myColors["MyDarkBlue"]) #~ errGraph.SetMarkerColor(myColors["MyDarkBlue"]) errGraph.Draw("SAME02") bkgHist.Draw("samehist") sfHist.Draw("samepe") leg = TLegend(0.62, 0.51, 0.89, 0.92,"","brNDC") leg.SetFillColor(10) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) from ROOT import TH1F,kWhite legendHistDing = TH1F() legendHistDing.SetFillColor(kWhite) if region == "inclusive": leg.AddEntry(legendHistDing,"Inclusive signal region","h") elif region == "central": leg.AddEntry(legendHistDing,"Central signal region","h") elif region == "forward": leg.AddEntry(legendHistDing,"Forward signal region","h") leg.AddEntry(sfHist,"Data","PL") leg.AddEntry(bkgHist, "Flav. Sym. backgrounds","l") leg.AddEntry(errGraph,"Background uncert.", "f") leg.Draw("same") plotPad.RedrawAxis() ratioPad.cd() ratioGraphs = ratios.RatioGraph(sfHist,bkgHist, xMin=plot.firstBin, xMax=plot.lastBin,title="%s / OF"%combination,yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=1000) ratioGraphs.addErrorByHistograms( "rSFOF", histUp, histDown,color= myColors["MyBlue"],fillStyle=3001) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) leg2 = TLegend(0.175, 0.78, 0.475, 0.9,"","brNDC") leg2.SetFillColor(10) leg2.SetLineColor(10) leg2.SetShadowColor(0) leg2.SetBorderSize(1) leg2.AddEntry(errGraph,"Systematic uncert.", "f") leg2.Draw("same") ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("fig/rSFOFDependency_%s_%s_%s_%s_%s.pdf"%(selection.name,plot.variablePlotName,runRange.label,combination,binName))
def draw_fits(self, save_dir, root_dir=None): """ Draw all fits one-by-one Args: save_dir: directory where to save plots root_dir: TDirectory where to save summary plots """ gStyle.SetOptStat(0) gStyle.SetOptStat(0000) gStyle.SetPalette(1) gStyle.SetCanvasColor(0) gStyle.SetFrameFillColor(0) bins2 = self.get_bins2() bins1_ranges = self.pars_factory.bins1_edges_low.copy() bins1_ranges.append(self.pars_factory.bins1_edges_up[-1]) n_bins1 = len(bins1_ranges) - 1 def fill_wrapper(histo, ibin, central, err=None): histo.SetBinContent(ibin, central) if err is not None: histo.SetBinError(ibin, err) # Summarize in mult histograms in pT bins yieldshistos = {ibin2: TH1F("hyields%d" % (ibin2), "", \ n_bins1, array("d", bins1_ranges)) for ibin2 in bins2} means_histos = {ibin2:TH1F("hmeans%d" % (ibin2), "", \ n_bins1, array("d", bins1_ranges)) for ibin2 in bins2} sigmas_histos = {ibin2: TH1F("hsigmas%d" % (ibin2), "", \ n_bins1, array("d", bins1_ranges)) for ibin2 in bins2} signifs_histos = {ibin2: TH1F("hsignifs%d" % (ibin2), "", \ n_bins1, array("d", bins1_ranges)) for ibin2 in bins2} have_summary_pt_bins = [] means_init_mc_histos = TH1F("hmeans_init_mc", "", n_bins1, array("d", bins1_ranges)) sigmas_init_mc_histos = TH1F("hsigmas_init_mc", "", n_bins1, array("d", bins1_ranges)) means_init_data_histos = TH1F("hmeans_init_data", "", n_bins1, array("d", bins1_ranges)) sigmas_init_data_histos = TH1F("hsigmas_init_data", "", n_bins1, array("d", bins1_ranges)) nx = 4 ny = 2 canvy = 533 if n_bins1 > 12: nx = 5 ny = 4 canvy = 1200 elif n_bins1 > 8: nx = 4 ny = 3 canvy = 800 canvas_init_mc = TCanvas("canvas_init_mc", "MC", 1000, canvy) canvas_init_data = TCanvas("canvas_init_data", "Data", 1000, canvy) canvas_data = {ibin2: TCanvas("canvas_data%d" % (ibin2), "Data", 1000, canvy) \ for ibin2 in bins2} canvas_init_mc.Divide(nx, ny) canvas_init_data.Divide(nx, ny) for c in canvas_data.values(): c.Divide(nx, ny) # Need to cache some object for which the canvas is only written after the loop... for (ibin1, ibin2), fit in self.central_fits.items(): bin_id_match = self.pars_factory.bin_matching[ibin1] # Some variables set for drawing title = f"{self.pars_factory.bins1_edges_low[ibin1]:.1f} < #it{{p}}_{{T}} < " \ f"{self.pars_factory.bins1_edges_up[ibin1]:.1f}" \ f"(prob > {self.pars_factory.prob_cut_fin[bin_id_match]:.2f})" x_axis_label = "#it{M}_{inv} (GeV/#it{c}^{2})" n_sigma_signal = self.pars_factory.n_sigma_signal suffix_write = self.pars_factory.make_suffix(ibin1, ibin2) kernel = fit.kernel histo = fit.histo # Central fits y_axis_label = \ f"Entries/({histo.GetBinWidth(1) * 1000:.0f} MeV/#it{{c}}^{{2}})" canvas = TCanvas("fit_canvas", suffix_write, 700, 700) fit.draw(canvas, sigma_signal=n_sigma_signal, x_axis_label=x_axis_label, y_axis_label=y_axis_label, title=title) if self.pars_factory.apply_weights is False: canvas.SaveAs( make_file_path(save_dir, "fittedplot", "eps", None, suffix_write)) else: canvas.SaveAs( make_file_path(save_dir, "fittedplotweights", "eps", None, suffix_write)) canvas.Close() fit.draw(canvas_data[ibin2].cd(ibin1 + 1), sigma_signal=n_sigma_signal, x_axis_label=x_axis_label, y_axis_label=y_axis_label, title=title) if fit.success: fill_wrapper(yieldshistos[ibin2], ibin1 + 1, kernel.GetRawYield(), kernel.GetRawYieldError()) fill_wrapper(means_histos[ibin2], ibin1 + 1, kernel.GetMean(), kernel.GetMeanUncertainty()) fill_wrapper(sigmas_histos[ibin2], ibin1 + 1, kernel.GetSigma(), kernel.GetSigmaUncertainty()) signif = Double() signif_err = Double() kernel.Significance(n_sigma_signal, signif, signif_err) fill_wrapper(signifs_histos[ibin2], ibin1 + 1, signif, signif_err) # Residual plot c_res = TCanvas('cRes', 'The Fit Canvas', 800, 800) c_res.cd() h_pulls = histo.Clone(f"{histo.GetName()}_pull") h_residual_trend = histo.Clone( f"{histo.GetName()}_residual_trend") h_pulls_trend = histo.Clone(f"{histo.GetName()}_pulls_trend") _ = kernel.GetOverBackgroundResidualsAndPulls( \ h_pulls, h_residual_trend, h_pulls_trend, \ self.pars_factory.fit_range_low[ibin1], \ self.pars_factory.fit_range_up[ibin1]) h_residual_trend.Draw() c_res.SaveAs( make_file_path(save_dir, "residual", "eps", None, suffix_write)) c_res.Close() # Summary plots to be done only once per pT bin if ibin1 in have_summary_pt_bins: continue have_summary_pt_bins.append(ibin1) # Pre-fit MC suffix_write = self.pars_factory.make_suffix( ibin1, self.pars_factory.bins2_int_bin) pre_fit_mc = self.pre_fits_mc[ibin1] kernel = pre_fit_mc.kernel histo = pre_fit_mc.histo y_axis_label = \ f"Entries/({histo.GetBinWidth(1) * 1000:.0f} MeV/#it{{c}}^{{2}})" canvas = TCanvas("fit_canvas_mc_init", suffix_write, 700, 700) pre_fit_mc.draw(canvas, x_axis_label=x_axis_label, y_axis_label=y_axis_label, title=title) canvas.SaveAs( make_file_path(save_dir, "fittedplot_integrated_mc", "eps", None, suffix_write)) canvas.Close() pre_fit_mc.draw(canvas_init_mc.cd(ibin1 + 1), x_axis_label=x_axis_label, y_axis_label=y_axis_label, title=title) if pre_fit_mc.success: # Only fill these summary plots in case of success means_init_mc_histos.SetBinContent(ibin1 + 1, kernel.GetParameter(1)) means_init_mc_histos.SetBinError(ibin1 + 1, kernel.GetParError(1)) sigmas_init_mc_histos.SetBinContent(ibin1 + 1, kernel.GetParameter(2)) sigmas_init_mc_histos.SetBinError(ibin1 + 1, kernel.GetParError(2)) pre_fit_data = self.pre_fits_data[ibin1] kernel = pre_fit_data.kernel histo = pre_fit_data.histo # Pre-fit data y_axis_label = \ f"Entries/({histo.GetBinWidth(1) * 1000:.0f} MeV/#it{{c}}^{{2}})" canvas = TCanvas("fit_canvas_data_init", suffix_write, 700, 700) pre_fit_data.draw(canvas, sigma_signal=n_sigma_signal, x_axis_label=x_axis_label, y_axis_label=y_axis_label, title=title) canvas.SaveAs( make_file_path(save_dir, "fittedplot_integrated", "eps", None, suffix_write)) canvas.Close() pre_fit_data.draw(canvas_init_data.cd(ibin1 + 1), sigma_signal=n_sigma_signal, x_axis_label=x_axis_label, y_axis_label=y_axis_label, title=title) if pre_fit_data.success: # Only fill these summary plots in case of success means_init_data_histos.SetBinContent(ibin1 + 1, kernel.GetMean()) means_init_data_histos.SetBinError(ibin1 + 1, kernel.GetMeanUncertainty()) sigmas_init_data_histos.SetBinContent(ibin1 + 1, kernel.GetSigma()) sigmas_init_data_histos.SetBinError( ibin1 + 1, kernel.GetSigmaUncertainty()) canvas_init_mc.SaveAs(make_file_path(save_dir, "canvas_InitMC", "eps")) canvas_init_mc.Close() canvas_init_data.SaveAs( make_file_path(save_dir, "canvas_InitData", "eps")) canvas_init_data.Close() for ibin2 in bins2: suffix2 = f"ibin2_{ibin2}" canvas_data[ibin2].SaveAs( make_file_path(save_dir, "canvas_FinalData", "eps", None, suffix2)) if root_dir: root_dir.cd() yieldshistos[ibin2].Write() means_histos[ibin2].Write() sigmas_histos[ibin2].Write() signifs_histos[ibin2].Write() #canvas_data[ibin2].Close() latex_bin2_var = self.ana_config["latexbin2var"] latex_hadron_name = self.ana_config["latexnamehadron"] # Plot some summary historgrams leg_strings = [f"{self.pars_factory.bins2_edges_low[ibin2]} #leq {latex_bin2_var} < " \ f"{self.pars_factory.bins2_edges_up[ibin2]}" for ibin2 in bins2] save_name = make_file_path(save_dir, "Yields", "eps", None, [self.case, self.ana_type]) # Yields summary plot plot_histograms( [yieldshistos[ibin2] for ibin2 in bins2], True, True, leg_strings, "uncorrected yields", "#it{p}_{T} (GeV/#it{c})", f"Uncorrected yields {latex_hadron_name} {self.ana_type}", "mult. / int.", save_name) save_name = make_file_path(save_dir, "Means", "eps", None, [self.case, self.ana_type]) # Means summary plot plot_histograms([means_histos[ibin2] for ibin2 in bins2], False, True, leg_strings, "Means", "#it{p}_{T} (GeV/#it{c})", "#mu_{fit} " + f"{latex_hadron_name} {self.ana_type}", "mult. / int.", save_name) save_name = make_file_path(save_dir, "Sigmas", "eps", None, [self.case, self.ana_type]) #Sigmas summary plot plot_histograms([sigmas_histos[ibin2] for ibin2 in bins2], False, True, leg_strings, "Sigmas", "#it{p}_{T} (GeV/#it{c})", "#sigma_{fit} " + f"{latex_hadron_name} {self.ana_type}", "mult. / int.", save_name) # Plot the initialized means and sigma for MC and data save_name = make_file_path(save_dir, "Means_mult_int", "eps", None, [self.case, self.ana_type]) plot_histograms([means_init_mc_histos, means_init_data_histos], False, False, ["MC", "data"], "Means of int. mult.", "#it{p}_{T} (GeV/#it{c})", "#mu_{fit} " + f"{latex_hadron_name} {self.ana_type}", "", save_name) save_name = make_file_path(save_dir, "Sigmas_mult_int", "eps", None, [self.case, self.ana_type]) plot_histograms([sigmas_init_mc_histos, sigmas_init_data_histos], False, False, ["MC", "data"], "Sigmas of int. mult.", "#it{p}_{T} (GeV/#it{c})", "#sigma_{fit} " + f"{latex_hadron_name} {self.ana_type}", "", save_name)
def __plot_3d(self): global unique_cnt definite_integral=0. uid = next(unique_cnt) header = self.__parser.get_header_info() hdata = self.__parser.get_histogram_data()[ 'DATA' ] name = header[ 'H_NAME' ] + ' ' + str( uid ) name = name[1:] nrbins = header[ 'RBINS' ] npbins = header[ 'PBINS' ] nzbins = header[ 'ZBINS' ] rl = header[ 'RRAN' ][0] ru = header[ 'RRAN' ][1] pl = header[ 'PRAN' ][0] pu = header[ 'PRAN' ][1] zl = header[ 'ZRAN' ][0] zu = header[ 'ZRAN' ][1] ## ------ TH2D::TH2D(const char* name, const char* title, int nbinsx, double xlow, double xup, int nbinsy, double ylow, double yup) self.__histo = TH2D(name, name, int( nrbins * npbins ) , float( zl ), float( zu ), int( nrbins * npbins ), float( pl ),float( pu )) self.__histo.SetXTitle("X [cm]") self.__histo.GetXaxis().CenterTitle(kTRUE) self.__histo.GetXaxis().SetTitleOffset(1.1) self.__histo.GetXaxis().SetTitleSize(0.04) self.__histo.GetXaxis().SetLabelSize(0.03) self.__histo.GetXaxis().SetTickLength(0.02) self.__histo.GetXaxis().SetNdivisions(20510) self.__histo.SetYTitle("Y [cm]") self.__histo.GetYaxis().CenterTitle(kTRUE) self.__histo.GetYaxis().SetTitleOffset(1.2) self.__histo.GetYaxis().SetTitleSize(0.04) self.__histo.GetYaxis().SetLabelSize(0.03) self.__histo.GetYaxis().SetTickLength(0.02) self.__histo.GetYaxis().SetNdivisions(20510) self.__histo.SetLineColor(kRed); #self.__histo.SetMinimum(1e-9); self.__histo.GetZaxis().SetTitle("Z [cm]"); ResR = ( ru - rl ) / nrbins ResP = ( pu - pl ) / npbins ResZ = ( zu - zl ) / nzbins FirstR = rl + ResR / 2. FirstP = pl + ResP / 2. FirstZ = zl + ResZ / 2. N = nrbins * npbins * nzbins rPos = [ None ] * N pPos = [ None ] * N zPos = [ None ] * N # -> fill the histo now! pos_cnt = 0 uid = next(unique_cnt) header = self.__parser.get_header_info() hdata = self.__parser.get_histogram_data() name = header[ 'H_NAME' ] + str( uid ) bins = header[ 'RBINS' ] self.__histo = [ None ]* (npbins+1) #ddebg = [[],[],[],[] ] #edebg = [ [],[],[],[]] for i in range(npbins): self.__histo[i] = TH1F(name+' phi='+str(FirstP+i*ResP), name+' phi='+str(FirstP+i*ResP), int(nrbins), float(rl), float(ru)) #SUPERPOSITION COMING RIGHT NOW!!! self.__histo[npbins] = TH1F(name+' Superposition', name+' Superposition', int(nrbins), float(rl), float(ru)) #AND ENDS RIGHT HERE for indx, data_point in enumerate( hdata[ 'DATA' ] ): self.__histo[int(indx/nrbins)].SetBinContent( indx%nrbins +1, data_point ) if indx%nrbins==0 and indx!=0: print "Definite integral for %d graph = %.4f" %(int(indx/nrbins),definite_integral) definite_integral=data_point else: definite_integral+=data_point print "Definite integral for 5 graph = %.4f" %definite_integral #ddebg[int(indx/100)].append(data_point) #for indx, error in enumerate( hdata[ 'ERRORS' ] ): #self.__histo[int(indx/100)].SetBinError( indx%100 + 1, error ) #edebg[int(indx/100)].append(error) #print len(ddebg[0]), len(ddebg[1]), len(ddebg[2]), len(ddebg[3]) #print len(edebg[0]), len(edebg[1]), len(edebg[2]), len(edebg[3]), min_val = min( hdata[ 'DATA' ] ) max_val = max( hdata[ 'DATA' ] ) for l in range(npbins): self.__histo[l].SetMarkerStyle( 20 ) self.__histo[l].SetMarkerSize( 0.6 )
density=True, color=None, histtype='step', label='bkgTest') plt.xlabel("Sig_Prob") plt.ylabel("#Events (Area scaled to 1)") plt.legend() plt.savefig("Discriminator.pdf") print("Discriminator plotted!!!") # In[33]: # Discriminator Shape in ROOT plotting c1 = TCanvas() nBins = 10 sigTrainHisto = TH1F("", "", nBins, 0, 1) bkgTrainHisto = TH1F("", "", nBins, 0, 1) sigTestHisto = TH1F("", "", nBins, 0, 1) bkgTestHisto = TH1F("", "", nBins, 0, 1) sigTrainHisto.FillN(sigTrainPredict.shape[0], (sigTrainPredict[:, 0]).astype(float), np.ones(sigTrainPredict.shape[0])) bkgTrainHisto.FillN(bkgTrainPredict.shape[0], (bkgTrainPredict[:, 0]).astype(float), np.ones(bkgTrainPredict.shape[0])) sigTestHisto.FillN(sigTestPredict.shape[0], (sigTestPredict[:, 0]).astype(float), np.ones(sigTestPredict.shape[0])) bkgTestHisto.FillN(bkgTestPredict.shape[0], (bkgTestPredict[:, 0]).astype(float), np.ones(bkgTestPredict.shape[0]))
coef=2 ) import ROOT, array from ROOT import TFile, TH1F, TGraph, TCanvas, TLegend fout = TFile("2lss_1tau_ttV_performance_maxDepth3_10Var_frWt_wMEMall.root", "RECREATE") c1 = TCanvas() c1.SetFillColor(10) c1.SetBorderSize(2) c1.SetLeftMargin(0.12) c1.SetBottomMargin(0.12) c1.SetRightMargin(0.05) c1.SetLogy() histogram_base = TH1F("histogram_base", "", 100, 0., 1.) histogram_base.SetTitle("") histogram_base.SetStats(False) histogram_base.SetMinimum(0.001) histogram_base.SetMaximum(10.) histogram_base.GetXaxis().SetTitle("Signal Eff.") histogram_base.GetYaxis().SetTitle("Background Eff.") histogram_base.Draw("hist") x_train = array.array("f", [0]) y_train = array.array("f", [0]) x_test = array.array("f", [0]) y_test = array.array("f", [0]) effs = np.linspace(0, 1, 50)
import ROOT, math from ROOT import TF1, TCanvas, TLegend, TH1F, TRandom3 try: input = raw_input except: pass nev = 100000 m0 = 10. reso = 0.03 # in % hmass1 = TH1F("mass1", "mass1", 100, 9.5, 10.5) hmass2 = TH1F("mass2", "mass2", 100, 9.5, 10.5) hmass3 = TH1F("mass3", "mass3", 100, 9.5, 10.5) r = TRandom3() absreso = reso * m0 for iev in xrange(nev): m1 = r.Gaus(m0, reso) hmass1.Fill(m1) m2 = r.Gaus(m1, reso * math.sqrt(15)) hmass2.Fill(m2) m3 = r.Gaus(m2, reso) hmass3.Fill(m3) hmass1.SetLineColor(ROOT.kRed)
def fitped(run,tdc,vthmin,vthmax,asic=1,ncha=24,rising=True,old=defped): rb=1 fi=1 la=ncha+1 #if (asic==2): # fi=ncha+1 # la=2*ncha+1 asicmap={} for i in {1,2}: asicmap[i]=[] for j in range(49): asicmap[i].append(0) asicmap[1][1]=30 asicmap[1][2]=28 asicmap[1][3]=26 asicmap[1][4]=24 asicmap[1][5]=23 asicmap[1][6]=22 asicmap[1][7]=21 asicmap[1][8]=20 asicmap[1][9]=19 asicmap[1][10]=18 asicmap[1][11]=17 asicmap[1][12]=16 asicmap[1][13]=15 asicmap[1][14]=14 asicmap[1][15]=13 asicmap[1][16]=12 asicmap[1][17]=11 asicmap[1][18]=10 asicmap[1][19]=9 asicmap[1][20]=8 asicmap[1][21]=7 asicmap[1][22]=6 asicmap[1][23]=5 asicmap[1][24]=4 asicmap[2][25]=30 asicmap[2][26]=28 asicmap[2][27]=26 asicmap[2][28]=24 asicmap[2][29]=23 asicmap[2][30]=22 asicmap[2][31]=21 asicmap[2][32]=20 asicmap[2][33]=19 asicmap[2][34]=18 asicmap[2][35]=17 asicmap[2][36]=16 asicmap[2][37]=15 asicmap[2][38]=14 asicmap[2][39]=13 asicmap[2][40]=12 asicmap[2][41]=11 asicmap[2][42]=10 asicmap[2][43]=9 asicmap[2][44]=8 asicmap[2][45]=7 asicmap[2][46]=6 asicmap[2][47]=5 asicmap[2][48]=4 asicmap={} for i in {1,2}: asicmap[i]=[] for j in range(50): asicmap[i].append(0) f=open("/opt/TdcAnalysis/feb_mapping.json") s=json.loads(f.read()) prh=s["v1_56"]["FlexTop"]["High"]["PR"] prl=s["v1_56"]["FlexTop"]["Low"]["PR"] tdch0=s["v1_56"]["FlexTop"]["High"]["TDC"][0] tdch1=s["v1_56"]["FlexTop"]["High"]["TDC"][1] tdcl0=s["v1_56"]["FlexTop"]["Low"]["TDC"][0] tdcl1=s["v1_56"]["FlexTop"]["Low"]["TDC"][1] for i in range(12): asicmap[1][tdch0[i]]=prh[i] asicmap[1][tdcl0[i]]=prl[i] asicmap[2][tdcl1[i]]=prl[i] asicmap[2][tdch1[i]]=prh[i] print(asicmap) ped=[] for i in range(32): ped.append(0) f82=TFile("Histos/InTime/histo%d_0.root" % run); f82.cd("/run%d/TDC%d" % (run,tdc)); c1=TCanvas(); #c2=TCanvas("c2","Test",1400,900); #c2.cd() #c2.Divide(6,4) #c2.Draw() #c2.Update() #val = raw_input() #c2.Draw() fout=open("summary_pedestal_%d_tdc%d.txt" % (run,tdc),"w"); fout.write("+--+-----+-----+-----+ \n"); gStyle.SetOptFit(); hmean=TH1F("hmean","Summary %d %d " %(run,tdc),vthmax-vthmin+1,vthmin,vthmax) hnoise=TH1F("hnoise","Summary noise %d %d " %(run,tdc),100,0.,30.) hpmean=TH1F("hpmean","Summary %d %d " %(run,tdc),2*ncha,0.,2.*ncha); hpnoise=TH1F("hpnoise","Summary noise %d %d " %(run,tdc),2*ncha,0.,2.*ncha); scfit=TF1("scfit","[0]*TMath::Erfc((x-[1])/[2])",vthmin+1,vthmax); for ip in range(la-1,fi,-1): #c2.cd() if (asicmap[asic][ip]==0): continue; hs=None if (rising): hs=f82.Get("/run%d/TDC%d/vthc%d" % (run,tdc,ip)); else: hs=f82.Get("/run%d/TDC%d/vthd%d" % (run,tdc,ip)); if (hs==None): continue; if (hs.GetEntries()==0): continue print(ip,fi,la," found") hs.Scale(1./2700.); nmax=0 for i in range(1,hs.GetNbinsX()): if (hs.GetBinContent(i)==0): if (hs.GetBinContent(i-1)!=0 and hs.GetBinContent(i+1)!=0): hs.SetBinContent(i,(hs.GetBinContent(i-1)+hs.GetBinContent(i+1))/2.) else: if (hs.GetBinContent(i)>nmax): nmax=hs.GetBinContent(i) hs.GetXaxis().SetRangeUser(vthmin-1,vthmax); icolor= ip%4 +1 istyle= ip/4+1 hs.SetLineColor(icolor) hs.SetLineStyle(int(istyle)) hs.SetLineWidth(2) c1.cd() c1.Draw() if (ip==0): hs.Draw() else: hs.Draw("SAME") c1.Update() c1.SaveAs("Run%d_AllStrip%d_%d.root" % (run,tdc,asic)); c1.SaveAs("Run%d_AllStrip%d_%d.png" % (run,tdc,asic)); val = raw_input() for ip in range(fi,la): #c2.cd() if (asicmap[asic][ip]==0): continue; hs=None if (rising): hs=f82.Get("/run%d/TDC%d/vthc%d" % (run,tdc,ip)); else: hs=f82.Get("/run%d/TDC%d/vthd%d" % (run,tdc,ip)); if (hs==None): continue; if (hs.GetEntries()==0): continue #hs.Scale(1./2700.); hder=TH1F("hder%d" % ip,"derivative",900/rb,0.,900.) hs.Rebin(rb) nmax=0 for i in range(1,hs.GetNbinsX()): if (hs.GetBinContent(i)==0): if (hs.GetBinContent(i-1)!=0 and hs.GetBinContent(i+1)!=0): hs.SetBinContent(i,(hs.GetBinContent(i-1)+hs.GetBinContent(i+1))/2.) else: if (hs.GetBinContent(i)>nmax): nmax=hs.GetBinContent(i) for i in range(1,hs.GetNbinsX()): if (hs.GetBinContent(i)-hs.GetBinContent(i+1)>-10): hder.SetBinContent(i,hs.GetBinContent(i)-hs.GetBinContent(i+1)) hder.Rebin(2) hder.GetXaxis().SetRangeUser(vthmin-1,vthmax); scfit.SetParameter(0,nmax/2.); scfit.SetParameter(1,hder.GetMean()); scfit.SetParameter(2,hder.GetRMS()); hs.GetXaxis().SetRangeUser(vthmin-1,vthmax); hs.Fit("scfit","Q","",vthmin+2,vthmax); #hs.GetXaxis().SetRangeUser(vthmin-1,scfit.GetParameter(1)+60); #gPad.SetLogy(); rped=scfit.GetParameter(1) c1.cd() c1.Draw() hder.Draw() c1.Update() val1 = raw_input() print("heho ",val1,rped,hder.GetMean()) rped=hder.GetMean() if (len(val1)>0): rped=float(val1) hs.Draw() c1.cd() c1.Draw() c1.Update() fout.write("|%2d|%5.1f|%5.1f|%5.2f| \n" % (ip,scfit.GetParameter(0),rped,scfit.GetParameter(2))); ipr=0 if (ip%2==1): ipr=ip/2 else: ipr=31-ip/2 firmwaret=[31,29,27,25,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6] #firmwaco=[31,29,27,25,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4] firmware2=[24,5,3,1,0,2,4,6,7,8,9,10,26,28,30,31,29,27,25,23,22,21,20,19] firmwareta1=[21,20,23,22,25,24,27,26,29,28,31,30,1,0,3,2,5,4,7,6,10,8,15,12] firmwareta2=[21,20,23,22,25,24,27,26,29,28,31,30,1,0,3,2,5,4,7,6,10,8,14,12] firmwaretb=[30,26,28,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,30,26,28,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4] if (asic==1): firmware=firmwareta1 else: firmware=firmwareta2 firmware=firmwaretb #if (ip>0): # ipr=firmware[ip-fi-1] #else: # ipr=0 print(ip,fi,ip-fi) ipr=firmware[ip-fi] ipr=asicmap[asic][ip] ped[ipr]=rped print(ip,ipr,rped,scfit.GetParameter(2)) hmean.Fill(rped) hnoise.Fill(scfit.GetParameter(2)) hpmean.SetBinContent(ip+1,rped); hpnoise.SetBinContent(ip+1,scfit.GetParameter(2)) #c1.SaveAs("Run%d_Strip%d.root" % (run,ip)); val = raw_input() #hder.Draw() #c1.Update() #val = raw_input() c1.cd() hmean.Draw() hpmean.GetYaxis().SetRangeUser(vthmin,vthmax) hpmean.Draw() c1.Update() c1.SaveAs("Summary_%d_TDC%d.png" % (run,tdc)); val = raw_input() hnoise.Draw() c1.Update() val = raw_input() hpnoise.Draw() c1.Update() val = raw_input() c1.Update() c1.SaveAs("Summary_Noise_%d_TDC%d.png" % (run,tdc)); fout.write("+--+-----+-----+-----+ \n"); fout.close() print(ped) val = raw_input() med=5550.0 for i in range(32): if (ped[i]==0): continue; if (ped[i] < med): #print(med,ped[i]) med=ped[i] med=med+5 med=480 print("Alignment to :",med) dac=ped for i in range(32): if (ped[i]==0): continue; old[i]=0 dac[i]=int(round(old[i]+(med-ped[i])*1./2.97)) print("cor%d_%d=" % (tdc,asic),dac) return dac
ZMass_mu_hist_extraMu = [] ZMass_mu_hist_extraEl = [] # lepton histos electronISO_Max_hist = [] electronISO_Min_hist = [] muonISO_Max_hist = [] muonISO_Min_hist = [] electronSIP_Max_hist = [] electronSIP_Min_hist = [] muonSIP_Max_hist = [] muonSIP_Min_hist = [] for i in range(0, len(RunNum_B)): histo2 = TH1F('ZMass_ele' + str(i), 'ZMass_ele' + str(i), 120, 60, 120) histo21 = TH1F('ZMass_ele_EBEB_' + str(i), 'ZMass_ele_EBEB_' + str(i), 120, 60, 120) histo22 = TH1F('ZMass_ele_EBEE_' + str(i), 'ZMass_ele_EBEE_' + str(i), 120, 60, 120) histo23 = TH1F('ZMass_ele_EEEE_' + str(i), 'ZMass_ele_EEEE_' + str(i), 120, 60, 120) if not ZTree: histo13 = TH1F('ZMass_ele_extraMu' + str(i), 'ZMass_ele_extraMu' + str(i), 120, 60, 120) histo16 = TH1F('ZMass_ele_extraEl' + str(i), 'ZMass_ele_extraEl' + str(i), 120, 60, 120) histo3 = TH1F('ZMass_mu' + str(i), 'ZMass_mu' + str(i), 120, 60, 120) histo24 = TH1F('ZMass_mu_MBMB_' + str(i), 'ZMass_mu_MBMB_' + str(i), 120, 60, 120)
c1.GetFrame().SetFillColor(21) c1.GetFrame().SetBorderSize(6) c1.GetFrame().SetBorderMode(-1) # Create a new ROOT binary machine independent file. # Note that this file may contain any kind of ROOT objects, histograms, # pictures, graphics objects, detector geometries, tracks, events, etc.. # This file is now becoming the current directory. hfile = gROOT.FindObject('py-hsimple.root') if hfile: hfile.Close() hfile = TFile('py-hsimple.root', 'RECREATE', 'Demo ROOT file with histograms') # Create some histograms, a profile histogram and an ntuple hpx = TH1F('hpx', 'This is the px distribution', 100, -4, 4) hpxpy = TH2F('hpxpy', 'py vs px', 40, -4, 4, 40, -4, 4) hprof = TProfile('hprof', 'Profile of pz versus px', 100, -4, 4, 0, 20) ntuple = TNtuple('ntuple', 'Demo ntuple', 'px:py:pz:random:i') # Set canvas/frame attributes. hpx.SetFillColor(48) gBenchmark.Start('hsimple') # Initialize random number generator. gRandom.SetSeed() rannor, rndm = gRandom.Rannor, gRandom.Rndm # For speed, bind and cache the Fill member functions, histos = ['hpx', 'hpxpy', 'hprof', 'ntuple']
# to fill histograms in a loop and show the graphics results # from ROOT import TCanvas, TH1F, TSlider from ROOT import gROOT, gBenchmark, gRandom gROOT.Reset() # Create a new canvas, and customize it. c1 = TCanvas('c1', 'The HSUM example', 200, 10, 600, 400) c1.SetGrid() gBenchmark.Start('hsum') # Create some histograms. total = TH1F('total', 'This is the total distribution', 100, -4, 4) main = TH1F('main', 'Main contributor', 100, -4, 4) s1 = TH1F('s1', 'This is the first signal', 100, -4, 4) s2 = TH1F('s2', 'This is the second signal', 100, -4, 4) total.Sumw2( ) # this makes sure that the sum of squares of weights will be stored # Set canvas/frame attributes. total.SetMarkerStyle(21) total.SetMarkerSize(0.7) main.SetFillColor(16) s1.SetFillColor(42) s2.SetFillColor(46) # Initialize random number generator. gRandom.SetSeed()
def DCRComp(run1Start,run1End,run2Start,run2End,filePath): # Setup variables firstruns = "" secondruns = ""# Used for each run in the first run range calibrationSkim1 = TChain("skimTree","skimTree") calibrationSkim2 = TChain("skimTree","skimTree") # Destination folder, trying to prevent a common formatting error if (filePath[-1] != '/'): filePath += '/' fileName = filePath + "DCRcompforRuns%d-%d_and_%d-%d.pdf" % (run1Start,run1End,run2Start,run2End) # Add functionality for multiple datasets? # NOTE: Be wary of comparing across multiple datasets. This hasn't been tested yet # So far, only datasets 5 and 6 are known by the program (see below) skimPath1 = "/global/project/projectdirs/majorana/data/mjd/surfmjd/analysis/skim/" skimPath2 = "/global/project/projectdirs/majorana/data/mjd/surfmjd/analysis/skim/" runBoundariesDS5cM1 = [24305,24318,24539,24552,24761,24775,24971,24984,25248,25261,25479,25492] runBoundariesDS5cM2 = [23960,23970,24322,24332,24556,24567,24779,24789,24988,24998,25265,25275,25496,25506] # MAKE SURE THIS HAS THE CORRECT CUTS cuts = "trapENFCal < 2635 && trapENFCal > 2605 && isGood && !wfDCBits && !muVeto && mH == 1" # If there is only one module being calibrated in DS5 cutStr5cM1 = " && C == 1" cutStr5cM2 = " && C == 2" if (run1Start <= 25507 and run1Start > 18712): # DS5c skimPath1 += "DS5ccal/GAT-v01-07-164-g8e0a877/skimDS5_" if (run1Start in runBoundariesDS5cM1): cuts += cutStr5cM1 if (run1Start in runBoundariesDS5cM2): cuts += cutStr5cM2 else: raise ValueError('First run boundary is not in either DS5c calibration range') if (run1Start > 25507): # DS6 skimPath1 += "DS6cal/GAT-v01-06/skimDS6_" if (run2Start <= 25507 and run2Start > 18712): # DS5c skimPath2 += "DS5ccal/GAT-v01-07-164-g8e0a877/skimDS5_" if (run1Start in runBoundariesDS5cM1): cuts += cutStr5cM1 if (run1Start in runBoundariesDS5cM2): cuts += cutStr5cM2 else: raise ValueError('First run boundary is not in either DS5c calibration range') if (run2Start > 25507): # DS6 skimPath2 += "DS6cal/GAT-v01-06/skimDS6_" cutStr = cuts # Build the first run range's TChain for i in range(run1Start, run1End+1): firstruns = skimPath1 + "run%d_small.root" % i calibrationSkim1.Add(firstruns,0) # Build the second run range's TChain for i in range(run2Start, run2End+1): secondruns = skimPath2 + "run%d_small.root" % i calibrationSkim2.Add(secondruns,0) # channel list from the built data in P3LTP # I don't need to use this now, but can check against it # IE check that every channel in this list has data # and that every channel with data is in this list chanList = [680,681,678,679,674,675,672,673,632,633,630,631,626,627,690,691,692,693,648,649,640,641,642,643,664,665,662,663,660,661,658,659,616,617,610,611,608,609,584,585,600,601,598,599,592,593,696,697,624,625,628,629,688,689,694,695,614,615,1122,1123,1108,1109,1106,1107,1128,1129,1204,1205,1110,1111,1126,1127,1124,1125,1202,1203,1170,1171,1172,1173,1174,1175,1176,1177,1168,1169,1120,1121,1206,1207,1208,1209,1232,1233,1236,1237,1238,1239,1234,1235,1328,1329,1298,1299,1296,1297,1302,1303,1332,1333,1268,1269,1304,1305,1330,1331] # Test case channel list #chanList = [1204,1174,1173] # Draw the whole dcr distribution vs channel # make sure there are enough bins that each channel is one bin c2 = TCanvas('c2','c2',400,400) drawStr = "dcr90:channel>>bighist1" bighist1 = TH2F("bighist1", "All Channels DCR Comparison",800,550,1350,1000,-0.001,0.001) calibrationSkim1.Draw(drawStr,cutStr,"COLZ") bighist1.SetLineColor(30) bighist1.SetStats(False) bighist1.GetXaxis().SetTitle("Channel") bighist1.GetYaxis().SetTitle("DCR99") bighist1.GetYaxis().SetTitleOffset(2.1) drawStr = "dcr90:channel>>bighist2" bighist2 = TH2F("bighist2", "All Channels DCR Comparison",800,550,1350,1000,-0.001,0.001) calibrationSkim2.Draw(drawStr,cutStr, "SAME COLZ") bighist2.SetLineColor(45) bighist2.SetStats(False) bighist2.GetXaxis().SetTitle("Channel") bighist2.GetYaxis().SetTitle("DCR99") bighist2.GetYaxis().SetTitleOffset(2.1) c2.SetLogz() gPad.SetLeftMargin(0.15) gPad.SetRightMargin(0.12) # Fix the different z scales maxz = max(bighist1.GetMaximum(),bighist2.GetMaximum()) bighist1.GetZaxis().SetRangeUser(0,maxz) bighist2.GetZaxis().SetRangeUser(0,maxz) c2.Update() # Save the big TH2F as a root file rootfileName = filePath + "DCRcomp%d-%d_and_%d-%d.root" % (run1Start, run1End, run2Start, run2End) c2.SaveAs(rootfileName) # Start the big pdf c2.Print(fileName + "(","Title: All Channels") c2.Close() # TCanvas for the individual channels c3 = TCanvas('c3','c3', 400, 400) c3.cd() # Make txt file for chanList problems txtFileTitle = "channelProblemsforRuns%d-%d_and_%d-%d.txt" % (run1Start,run1End,run2Start,run2End) chanFile = open(txtFileTitle,"w+") # Want a hist of all DCR90 efficiencies for the run range # Only do this for the second run range (so I'm not doubling the plot) # Remove entries from this if they don't have any results active_channels = [680,681,678,679,674,675,672,673,632,633,630,631,626,627,690,691,692,693,648,649,640,641,642,643,664,665,662,663,660,661,658,659,616,617,610,611,608,609,584,585,600,601,598,599,592,593,696,697,624,625,628,629,688,689,694,695,614,615,1122,1123,1108,1109,1106,1107,1128,1129,1204,1205,1110,1111,1126,1127,1124,1125,1202,1203,1170,1171,1172,1173,1174,1175,1176,1177,1168,1169,1120,1121,1206,1207,1208,1209,1232,1233,1236,1237,1238,1239,1234,1235,1328,1329,1298,1299,1296,1297,1302,1303,1332,1333,1268,1269,1304,1305,1330,1331] active_channels = sorted(active_channels) active_chan_effs = [] # Channel loop for channel in range(550,1351): # Conver channel to a bin number for slices bigX = bighist1.GetXaxis() currentbin = bigX.FindBin(channel) # Hack to get all the titles properly in the pdf canvastitle = "Channel %d" % channel bighist1.SetTitle(canvastitle) bighist2.SetTitle(canvastitle) # Get slices / bin content for each channel (the x axis of bighist) histname1 = "hist1_chan%d" % channel histname2 = "hist2_chan%d" % channel hist1 = bighist1.ProjectionY(histname1,currentbin,currentbin,"d") hist2 = bighist2.ProjectionY(histname2,currentbin,currentbin,"d") # Only proceed if the hists aren't empty if ((hist1.GetEntries() == 0 and hist2.GetEntries() == 0)): # Check that every empty channel isn't in chanList if (channel in chanList): chanFile.write("Channel %d has no output for runs %d - %d and %d - %d \n" % (channel, run1Start, run1End, run2Start, run2End)) active_channels.remove(channel) else: # Make sure every channel with output is in chanList if (channel not in chanList): chanFile.write("Channel %d is not in chanList \n" % channel) c3.Clear() c3.SetTitle(canvastitle) hstack = THStack("hstack","") hstack.SetTitle(canvastitle) hist1.SetLineColor(40) gPad.SetLogy() hstack.Add(hist1) # Get the dcr99 value by integrating the hist xaxis1 = hist1.GetXaxis() minbin = xaxis1.FindBin(-0.001) maxbin = xaxis1.FindBin(0.001) zerobin = xaxis1.FindBin(0) goodintegral1 = hist1.Integral(minbin,zerobin) totalintegral1 = hist1.Integral(minbin,maxbin) # Don't divide by zero if (goodintegral1 != 0): dcr90_1 = goodintegral1/totalintegral1 else : dcr90_1 = 0 hist2.SetLineColor(30) hstack.Add(hist2) # Get the second dcr99 value xaxis2 = hist2.GetXaxis() minbin = xaxis2.FindBin(-0.001) maxbin = xaxis2.FindBin(0.001) zerobin = xaxis2.FindBin(0) goodintegral2 = hist2.Integral(minbin,zerobin) totalintegral2 = hist2.Integral(minbin,maxbin) # Don't divide by zero if (goodintegral2 != 0): dcr90_2 = goodintegral2/totalintegral2 else: dcr90_2 = 0 active_chan_effs.append(dcr90_2) # Formatting for the THStack hstack.Draw() xaxisStack = hstack.GetXaxis() xaxisStack.SetTitle("DCR99") hstack.GetYaxis().SetTitle("Count") xaxisStack.SetLabelSize(0.02) xaxisStack.SetTitleOffset(1.2) # Draw vertical line at dcr90 = 0 for reference c3.Update() ymax = max(hist1.GetMaximum(), hist2.GetMaximum()) vert = TLine(0,0,0,ymax) vert.SetLineColor(2) vert.Draw() # Draw the legend chanlegend = TLegend(0.6,0.8,0.9,0.9) entry1 = chanlegend.AddEntry(hist1, "#splitline{Run Range %d - %d}{%f Efficiency}" % (run1Start, run1End, dcr90_1), "l") entry2 = chanlegend.AddEntry(hist2, "#splitline{Run Range %d - %d}{%f Efficiency}" % (run2Start, run2End, dcr90_2), "l") # If the Efficiencies differ by more than 1%, make their text red if (abs(dcr90_1 - dcr90_2) > 0.01): entry1.SetTextColor(2) entry2.SetTextColor(2) entry1.SetTextSize(0.02) entry2.SetTextSize(0.02) chanlegend.Draw() # Save as one big pdf file pagetitle = "Title: " + canvastitle c3.Update() c3.Print(fileName,pagetitle) # Close the pdf with a blank page c3.Clear() c3.Print(fileName + ")","I need to close the document somehow") c3.Close() # I want a spreadsheet of all the DCR90 efficiencies # Will make a file for each calibration run set, and then concatenate them later spreadsheetfilename = filePath + "eff_sheet_%d-%d.txt" % (run2Start,run2End) spreadsheet = open(spreadsheetfilename,"w+") # Make the dcr90 efficiency plot for the second run set only c_eff = TCanvas('c_eff','c_eff',800,400) c_eff.cd() # active_channels should be the x-axis labels # active_chan_effs should be the y-values num_chan = len(active_channels) eff_hist = TH1F('eff_hist',"DCR99 Efficiencies for Calibration Runs %d-%d" % (run2Start, run2End),num_chan,0,num_chan) eff_xaxis = eff_hist.GetXaxis() # Input data and write to the spreadsheet for i in range(0,num_chan): eff_xaxis.SetBinLabel(i+1, str(active_channels[i])) eff_hist.SetBinContent(i+1,active_chan_effs[i]) spreadsheet.write("%d %d %d %f \n" % (run2Start,run2End,active_channels[i],active_chan_effs[i])) c_eff.SetGridx() eff_hist.SetStats(False) eff_xaxis.SetLabelSize(0.03) eff_xaxis.SetTitle("Channel") eff_xaxis.SetTitleOffset(1.4) eff_hist.GetYaxis().SetTitle("DCR99 Efficiency") eff_hist.Draw() c_eff.Update() # Save eff_fileName = filePath + "DCR99_Efficiencies_Runs_%d-%d.pdf" % (run2Start,run2End) eff_title = "DCR99 Efficiencies for Calibration Runs %d-%d" % (run2Start, run2End) c_eff.SaveAs(eff_fileName,eff_title) c_eff.Close() spreadsheet.close()
def smear(mu, sigma0, smearfactor, N=100000, lcut=None, ucut=None, nbins=80): print ">>> smearing for N(%s,%s) with a factor of %s" % (mu, sigma0, smearfactor) # HISTS xmin, xmax = mu - sigma0 * 5, mu + sigma0 * 4 sigma1 = sigma0 * (1 + smearfactor) histname0 = "unsmeared" histname1 = "smeared" histtitle0 = "unsmeared, #sigma_{0} = %s" % (sigma0) histtitle1 = "smeared, #sigma_{new} = %s" % (sigma1) hist0 = TH1F(histname0, histtitle0, nbins, xmin, xmax) hist1 = TH1F(histname1, histtitle1, nbins, xmin, xmax) # FIT FUNCTIONS xminf = xmin if lcut == None else lcut xmaxf = xmax if ucut == None else ucut gaus0 = TF1("gaus0", "gaus", xminf, xmaxf) gaus1 = TF1("gaus1", "gaus", xminf, xmaxf) gaus0.SetTitle("%s fit" % histname0) gaus1.SetTitle("%s fit" % histname1) gaus0.SetParameters(N, mu, sigma0) gaus1.SetParameters(N, mu, sigma1) #gaus0.SetParLimits(2,sigma0*0.9,sigma0*1.1) #gaus1.SetParLimits(2,sigma1*0.9,sigma1*1.1) hists = [(hist0, gaus0), (hist1, gaus1)] # SMEAR & FILL #sigma1 = smearfactor #sigma1 = (smearfactor**2)/2. #sigma1 = sqrt(2.*(smearfactor)) #sigma1 = sqrt(-2.*log(smearfactor)) #sigma1 = 1./(2*smearfactor**2) sigma2 = sqrt(sigma1**2 - sigma0**2) print ">>> sigma0 = %.3f, sigma1 = %.3f, sigma2 = %.3f" % ( sigma0, sigma1, sigma2) print ">>> generating %s events..." % (N) for i in xrange(N): xval0 = gRandom.Gaus(mu, sigma0) if lcut != None and xval0 < lcut: continue if ucut != None and xval0 > ucut: continue #rand = gRandom.Gaus(1,smearfactor) #xval1 = xval0 * rand #rand = gRandom.Gaus(0,1+smearfactor) #xval1 = xval0 + rand rand = gRandom.Gaus(0, 1) xval1 = xval0 + sigma2 * rand hist0.Fill(xval0) if lcut != None and xval1 < lcut: continue if ucut != None and xval1 > ucut: continue hist1.Fill(xval1) # PLOT SETTINGS xtitle = "x variable" ytitle = "events" title = "Gauss(%s,%s)" % (mu, "#sigma") canvasname = "smear_%.1f-%.1f_by_%.2f" % (mu, sigma0, smearfactor) if lcut != None: canvasname += "_gt%.1f" % (lcut) if ucut != None: canvasname += "_lt%.1f" % (ucut) canvasname = canvasname.replace('.', 'p') ymin, ymax = 0, 1.14 * max(hist0.GetMaximum(), hist1.GetMaximum()) rmin, rmax = 0.60, 1.40 lmargin, rmargin = 0.14, 0.04 # CANVAS print ">>> plotting..." canvas = TCanvas("canvas", "canvas", 100, 100, 800, 800) canvas.Divide(2) # MAIN plot canvas.cd(1) gPad.SetPad("pad1", "pad1", 0, 0.33, 1, 1, 0, -1, 0) gPad.SetFillColor(0) gPad.SetBorderMode(0) gPad.SetFrameFillStyle(0) gPad.SetFrameBorderMode(0) gPad.SetTopMargin(0.06) gPad.SetBottomMargin(0.02) gPad.SetLeftMargin(lmargin) gPad.SetRightMargin(rmargin) gPad.SetGrid() gPad.cd() textsize = 0.050 x1, width = 0.18, 0.25 y1, height = 0.89, textsize * 1.08 * 5 legend = TLegend(x1, y1, x1 + width, y1 - height) legend.SetTextSize(textsize) legend.SetBorderSize(0) legend.SetFillStyle(0) legend.SetFillColor(0) legend.SetTextFont(62) legend.SetHeader(title) legend.SetTextFont(42) # FRAME frame = gPad.DrawFrame(xmin, ymin, xmax, ymax) frame.GetYaxis().SetTitleSize(0.070) frame.GetXaxis().SetTitleSize(0.070) frame.GetXaxis().SetLabelSize(0.000) frame.GetYaxis().SetLabelSize(0.060) frame.GetXaxis().SetTitleOffset(1.00) frame.GetYaxis().SetTitleOffset(1.06) frame.GetXaxis().SetNdivisions(508) frame.GetXaxis().SetTitle(xtitle) frame.GetYaxis().SetTitle(ytitle) # DRAW & FIT print ">>> fitting..." fits = [] for i, (hist, gaus) in enumerate(hists): color = colors[i % len(colors)] hist.SetLineColor(color) hist.SetLineWidth(2) hist.SetLineStyle(1) gaus.SetLineColor(color + 1) gaus.SetLineWidth(2) gaus.SetLineStyle(2) hist.Fit(gaus.GetName(), '0', '', xminf, xmaxf) hist.Draw('SAME') gaus.Draw('SAME') gtitle = "#sigma_{fit} = %.3f" % (gaus.GetParameter(2) ) #gaus.GetTitle() legend.AddEntry(hist, hist.GetTitle(), 'l') legend.AddEntry(gaus, gtitle, 'l') print ">>> real unsmeared sigma: %5.3f" % (sigma0) print ">>> fitted unsmeared sigma: %5.3f" % (gaus0.GetParameter(2)) print ">>> real smear factor: %5.3f" % (smearfactor) print ">>> fitted smeared sigma: %5.3f" % (gaus1.GetParameter(2)) legend.Draw() frame.Draw('SAMEAXIS') gPad.Modified() # RATIO plot canvas.cd(2) gPad.SetPad("pad2", "pad2", 0, 0, 1, 0.32, 0, -1, 0) gPad.SetTopMargin(0.04) gPad.SetBottomMargin(0.29) gPad.SetLeftMargin(lmargin) gPad.SetRightMargin(rmargin) # RATIO FRAME rframe = gPad.DrawFrame(xmin, rmin, xmax, rmax) rframe.GetYaxis().CenterTitle() rframe.GetXaxis().SetTitleSize(0.144) rframe.GetYaxis().SetTitleSize(0.140) rframe.GetXaxis().SetLabelSize(0.130) rframe.GetYaxis().SetLabelSize(0.120) rframe.GetXaxis().SetLabelOffset(0.012) rframe.GetXaxis().SetTitleOffset(0.85) rframe.GetYaxis().SetTitleOffset(0.53) rframe.GetXaxis().SetNdivisions(508) rframe.GetYaxis().CenterTitle(True) rframe.GetYaxis().SetTitle("ratio") rframe.GetXaxis().SetTitle(xtitle) rframe.GetYaxis().SetNdivisions(5) # RATIO ratios = [] for i, (hist, gaus) in enumerate(hists): #if i==0: continue #ratio = hist.Clone(hist.GetName()+"_ratio") #ratio.Divide(hist0) ratio = divideHists(hist, hist0, name=hist.GetName() + "_ratio") ratio.Draw('HISTSAME') ratios.append(ratio) #ratiof = createTH1FromTF1(gaus,nbins,xmin,xmax) #ratiof.Divide(hist0) ratiof = divideTF1ByTH1(gaus, hist0, name=gaus.GetName() + "_ratio") ratiof.Draw('HISTSAME') ratios.append(ratiof) print ratiof #line = TLine(xmin,1.,xmax,1.) #line.SetLineColor(hist0.GetLineColor()) #line.SetLineWidth(hist0.GetLineWidth()) #line.SetLineStyle(1) #line.Draw('SAME') gPad.SetGrid() gPad.Modified() rframe.Draw('sameaxis') canvas.SaveAs(canvasname + ".png") canvas.SaveAs(canvasname + ".pdf") canvas.Close() print ">>> "
treeMCTTbar = inputMCTTbartree.Get("ZTree/candTree") treeText = "ZTree" else: print("Error: wrong option!") else: print("Error: choose a period!") # ******************** # do data histos # ******************** if (redoDATAHistos): TH1.SetDefaultSumw2( ) # set sumw2 = true fro all the histograms created from now on PFMET_hist_ele = TH1F('PFMET_ele', 'PFMET_ele', 125, 0, 250) #Z->ee PFMET_hist_mu = TH1F('PFMET_mu', 'PFMET_mu', 125, 0, 250) #Z->mumu # read tree print "reading tree", inputDATAtree.GetName(), treeText, treeDATA.GetName( ), "..." treeDATA.SetBranchStatus("*", 0) # disable all branches if ZTree: treeDATA.SetBranchStatus("Zsel", 1) treeDATA.SetBranchStatus("ZMass", 1) else: treeDATA.SetBranchStatus("ZZsel", 1) treeDATA.SetBranchStatus("LepLepId", 1) treeDATA.SetBranchStatus("PFMET", 1)
def getErrHist(plot,combination,region,ofHist,dyHist,rSFOFErr): if combination == "SF": localZPred = zPredictions.SF localROutIn = rOutIn elif combination == "EE": localZPred = zPredictions.EE localROutIn = rOutInEE elif combination == "MM": localZPred = zPredictions.MM localROutIn = rOutInMM hist = TH1F("errHist","errHist",plot.nBins,plot.firstBin,plot.lastBin) histUp = TH1F("errHist","errHist",plot.nBins,plot.firstBin,plot.lastBin) histDown = TH1F("errHist","errHist",plot.nBins,plot.firstBin,plot.lastBin) graph = TGraphAsymmErrors() for i in range(1,hist.GetNbinsX()+1): hist.SetBinContent(i,1) hist.SetBinError(i,ofHist.GetBinContent(i)*rSFOFErr) if dyHist is not None: print "hier" for i in range(hist.FindBin(mllBins.lowMass.low+0.01),hist.FindBin(mllBins.lowMass.high-0.01)): if region == "inclusive": zErrCentral = (((localZPred.central.err*localROutIn.lowMass.central.val)**2 + (localZPred.central.val*localROutIn.lowMass.central.err)**2)**0.5) / (localZPred.central.val*localROutIn.lowMass.central.val) * dyHist.GetBinContent(i) zErrForward = (((localZPred.forward.err*localROutIn.lowMass.forward.val)**2 + (localZPred.forward.val*localROutIn.lowMass.forward.err)**2)**0.5) / (localZPred.forward.val*localROutIn.lowMass.forward.val) * dyHist.GetBinContent(i) zErr = zErrCentral + zErrForward else: zErr = (((getattr(localZPred,region).err*getattr(localROutIn.lowMass,region).val)**2 + (getattr(localZPred,region).val*getattr(localROutIn.lowMass,region).err)**2)**0.5) / ((getattr(localZPred,region).val*getattr(localROutIn.lowMass,region).val)) * dyHist.GetBinContent(i) hist.SetBinError(i,(hist.GetBinError(i)**2 + zErr**2)**0.5) for i in range(hist.FindBin(mllBins.highMass.low+0.01),hist.FindBin(plot.lastBin-0.01)+1): if region == "inclusive": zErrCentral = (((localZPred.central.err*localROutIn.highMass.central.val)**2 + (localZPred.central.val*localROutIn.highMass.central.err)**2)**0.5) / (localZPred.central.val*localROutIn.highMass.central.val) * dyHist.GetBinContent(i) zErrForward = (((localZPred.forward.err*localROutIn.highMass.forward.val)**2 + (localZPred.forward.val*localROutIn.highMass.forward.err)**2)**0.5) / (localZPred.forward.val*localROutIn.highMass.forward.val) * dyHist.GetBinContent(i) zErr = zErrCentral + zErrForward else: zErr = (((getattr(localZPred,region).err*getattr(localROutIn.highMass,region).val)**2 + (getattr(localZPred,region).val*getattr(localROutIn.highMass,region).err)**2)**0.5) / ((getattr(localZPred,region).val*getattr(localROutIn.highMass,region).val)) * dyHist.GetBinContent(i) hist.SetBinError(i,(hist.GetBinError(i)**2 + zErr**2)**0.5) for i in range(hist.FindBin(mllBins.onZ.low+0.01),hist.FindBin(mllBins.onZ.high-0.01)): if region == "inclusive": zErrCentral = (localZPred.central.err / localZPred.central.val) * dyHist.GetBinContent(i) zErrForward = (localZPred.forward.err / localZPred.forward.val) * dyHist.GetBinContent(i) zErr = zErrCentral + zErrForward else: zErr = (getattr(localZPred,region).err / getattr(localZPred,region).val) * dyHist.GetBinContent(i) hist.SetBinError(i,(hist.GetBinError(i)**2 + zErr**2)**0.5) for i in range(0,hist.GetNbinsX()+1): graph.SetPoint(i,plot.firstBin - ((plot.lastBin-plot.firstBin)/plot.nBins)*0.5 +(i)*((plot.lastBin-plot.firstBin)/plot.nBins),dyHist.GetBinContent(i) + ofHist.GetBinContent(i)) graph.SetPointError(i,((plot.firstBin-plot.lastBin)/plot.nBins)*0.5,((plot.firstBin-plot.lastBin)/plot.nBins)*0.5,(hist.GetBinError(i)**2 + dyHist.GetBinContent(i) + ofHist.GetBinContent(i))**0.5,(hist.GetBinError(i)**2 + dyHist.GetBinContent(i) + ofHist.GetBinContent(i))**0.5) for i in range(1,hist.GetNbinsX()+1): histUp.SetBinContent(i,dyHist.GetBinContent(i) + ofHist.GetBinContent(i) + hist.GetBinError(i)) histDown.SetBinContent(i,dyHist.GetBinContent(i) + ofHist.GetBinContent(i) - hist.GetBinError(i)) #~ hist.SetBinError(i,hist.GetBinError(i) / (dyHist.GetBinContent(i) + ofHist.GetBinContent(i))) hist.SetBinError(i,0) else: for i in range(0,hist.GetNbinsX()+1): graph.SetPoint(i,plot.firstBin - ((plot.lastBin-plot.firstBin)/plot.nBins)*0.5 +(i)*((plot.lastBin-plot.firstBin)/plot.nBins),ofHist.GetBinContent(i)) graph.SetPointError(i,((plot.firstBin-plot.lastBin)/plot.nBins)*0.5,((plot.firstBin-plot.lastBin)/plot.nBins)*0.5,(hist.GetBinError(i)**2 + ofHist.GetBinContent(i))**0.5,(hist.GetBinError(i)**2 + ofHist.GetBinContent(i))**0.5) for i in range(1,hist.GetNbinsX()+1): histUp.SetBinContent(i,ofHist.GetBinContent(i) + hist.GetBinError(i)) histDown.SetBinContent(i,ofHist.GetBinContent(i) - hist.GetBinError(i)) if ofHist.GetBinContent(i) > 0: hist.SetBinError(i,hist.GetBinError(i) / (ofHist.GetBinContent(i))) else: hist.SetBinError(i,0) return graph, histUp, histDown
def __plot_3d(self): global unique_cnt uid = next(unique_cnt) header = self.__parser.get_header_info() hdata = self.__parser.get_histogram_data() name = header[ 'H_NAME' ] name = name[1:] nrbins = header[ 'RBINS' ] npbins = header[ 'PBINS' ] nzbins = header[ 'ZBINS' ] rl = header[ 'RRAN' ][0] ru = header[ 'RRAN' ][1] pl = header[ 'PRAN' ][0] pu = header[ 'PRAN' ][1] zl = header[ 'ZRAN' ][0] zu = header[ 'ZRAN' ][1] ## ------ TH2D::TH2D(const char* name, const char* title, int nbinsx, double xlow, double xup, int nbinsy, double ylow, double yup) self.__histo = TH3D("RPZ " + name,"RPZ " + name, int( nrbins ), float( rl ), float( ru ), int( npbins ), float( pl ),float( pu ), int( nzbins ), float( zl ), float( zu )) self.__histo.SetXTitle("R [cm]") self.__histo.GetXaxis().CenterTitle(kTRUE) self.__histo.GetXaxis().SetTitleOffset(1.1) self.__histo.GetXaxis().SetTitleSize(0.04) self.__histo.GetXaxis().SetLabelSize(0.03) self.__histo.GetXaxis().SetTickLength(0.02) self.__histo.GetXaxis().SetNdivisions(20510) self.__histo.SetYTitle("P [rad]") self.__histo.GetYaxis().CenterTitle(kTRUE) self.__histo.GetYaxis().SetTitleOffset(1.2) self.__histo.GetYaxis().SetTitleSize(0.04) self.__histo.GetYaxis().SetLabelSize(0.03) self.__histo.GetYaxis().SetTickLength(0.02) self.__histo.GetYaxis().SetNdivisions(20510) #self.__histo.SetMinimum(1e-9); self.__histo.GetZaxis().SetTitle("Z [cm]"); self.__histo.GetZaxis().CenterTitle(kTRUE) self.__histo.GetZaxis().SetTitleOffset(1.2) self.__histo.GetZaxis().SetTitleSize(0.04) self.__histo.GetZaxis().SetLabelSize(0.03) self.__histo.GetZaxis().SetTickLength(0.02) self.__histo.GetZaxis().SetNdivisions(20510) ResR = ( header[ 'RRAN' ][1] - header[ 'RRAN' ][0] ) / nrbins ResP = ( pu - pl ) / npbins ResZ = ( zu - zl ) / nzbins FirstR = header[ 'RRAN' ][0] + ResR / 2. FirstP = pl + ResP / 2. FirstZ = zl + ResZ / 2. N = nrbins * npbins * nzbins rPos = [ None ] * N pPos = [ None ] * N zPos = [ None ] * N # -> fill the histo now! if nzbins > 1: pos_cnt = 0 for zentry in range( nzbins ): zPos[zentry] = FirstZ + float(zentry) * ResZ; for pentry in range( npbins ): pPos[pentry] = FirstP + float( pentry ) * ResP for rentry in range( nrbins ): data_point = hdata[ 'DATA' ][ pos_cnt ] rPos[rentry] = FirstR + float( rentry ) * ResR self.__histo.SetBinContent( int ( rentry ), int( pentry ), int( zentry ), float( data_point )) pos_cnt += 1 else: self.__histo = TH1F(name, name, int(nrbins), float(rl), float(ru)) data_points = [0] * nrbins error_points = [0] * nrbins pos_cnt = 0 for pentry in range( npbins ): for rentry in range( nrbins ): data_points[rentry] += hdata[ 'DATA' ][ pos_cnt ] error_points[rentry] += hdata[ 'ERRORS' ][ pos_cnt ] pos_cnt += 1 data_points[:] = [ x / npbins for x in data_points ] error_points[:] = [ x / npbins for x in error_points ] for indx, data_point in enumerate( data_points ): self.__histo.SetBinContent( indx+1, data_point ) for indx, error_point in enumerate( hdata[ 'ERRORS' ] ) : error_point *= self.__histo.GetBinContent( indx ) * 0.01 / 2 self.__histo.SetBinError( indx , error_point ) min_val = min( hdata[ 'DATA' ] ) max_val = max( hdata[ 'DATA' ] )
file2Name=file1Name var=args.variable h1 = f1.Get(var) h2 = f2.Get(var) h1.GetXaxis().SetTitle("X axis title") h1.GetYaxis().SetTitle("Y axis title") elif args.pileUp: basePath = "/lstore/cms/dbastos/Stop4Body/" nTupleDir = "nTuples_v2018-08-24/" var = "nVert" f1 = ROOT.TFile(basePath+nTupleDir+file1Name,"READ") f2 = ROOT.TFile(basePath+nTupleDir+file2Name,"READ") t1=f1.Get("bdttree") t2=f2.Get("bdttree") h1 = TH1F("h1",var,50,0,50) h2 = TH1F("h2",var,50,0,50) t1.Draw("nVert>>h1","","goff") t2.Draw("nVert>>h2","","goff") else: f1 = ROOT.TFile(file1Name,"READ") f2 = ROOT.TFile(file2Name,"READ") c1 = TCanvas("c1",var, 1200, 1350) #c1.Range() hs= THStack("hs","") hs.Add(h1) hs.Add(h2)
def main(): f = open(filelistStr, "r") rtfileoutput = TFile(rtfileoutputStr, "recreate") waveDir = rtfileoutput.mkdir("Waveforms") resultsDir = rtfileoutput.mkdir("Results") # afterpulse counting num_afterpulse_events = [0, 0, 0, 0] afterpulse_probability = [0, 0, 0, 0] # prepare for histograms hAmplitude_list = [] hAmplitudeBin_list = [] hWave_list = [] hPedMean_list = [] hPedWidth_list = [] hFinalCharge_list = [] hNbOfPulses_list = [] hPulseStartTime_list = [] # start time of the pulse # time distribution of the pulses that are not due to fiber trigger (ie., # dark pulses or else) hPulseTimeDist_list = [] # time distribution of the pulses that are not due to fiber trigger (ie., # dark pulses or else) hPulseWidth_list = [] hPulseAmplitudeVsTime_list = [ ] # 2D histogram: pulse amplitude vs. pulse time bin # 2D histogram: pulse amplitude vs. pulse time bin hPulseAmplitudeVsWidth_list = [] hWaveAvg_list = [] # average of raw waveforms # special test on time difference between the first channel hTimeDiff = TH1F("hTimeDiff", "Time diference", 100, -10, 10) # unit in ns hTimeDiff.SetXTitle("Time difference (ns)") hTimeDiff.SetYTitle("N") for i in range(0, NCH, 1): # will keep a few waveforms name = "Wave_" + str(i) hist = TH1F(name, "", NSamples, 0, NSamples) hist.SetXTitle("Sample number") hist.SetYTitle("Amplitude (mV)") hist.SetLineColor(i + 1) hWave_list.append(hist) # will keep average waveforms name = "WaveAvg_" + str(i) hist = TH1F(name, "", NSamples, 0, NSamples) hist.SetXTitle("Sample number") hist.SetYTitle("Amplitude (mV)") hist.SetLineColor(i + 1) hWaveAvg_list.append(hist) # histogram of pulse baseline name = "PedMean_" + str(i) hist = TH1F(name, "", 1000, -5, 5) hist.SetXTitle("Amplitude (mv)") hist.SetYTitle("Counts") hist.SetLineColor(i + 1) hPedMean_list.append(hist) # histogram of pulse baseline width name = "PedWidth_" + str(i) hist = TH1F(name, "", 1000, -5, 5) hist.SetXTitle("Amplitude (mV)") hist.SetYTitle("Counts") hist.SetLineColor(i + 1) hPedWidth_list.append(hist) # pulse charge due to fiber triggers, unit converted to fC name = "FinalCharge_" + str(i) # would be best to have different settings for LED on vs LED off if ledStatus == False: hist = TH1F(name, "", 1000, -5, 20) else: hist = TH1F(name, "", 2000, -5, 200) hist.SetXTitle("Charge (pC)") hist.SetYTitle("Counts") hist.SetLineColor(i + 1) hFinalCharge_list.append(hist) # pulse amplitude, or nimimum (because of negative pulse) name = "PulseAmplitude_" + str(i) hist = TH1F(name, "", 500, 0, 500) hist.SetXTitle("Amplitude (mV)") hist.SetYTitle("Counts") hist.SetLineColor(i + 1) hAmplitude_list.append(hist) # pulse width, or nimimum (because of negative pulse) name = "PulseWidth_" + str(i) hist = TH1F(name, "", 100, 0, 100) hist.SetXTitle("Pulse width (ns)") hist.SetYTitle("Counts") # hist.SetLineColor(i+1) hPulseWidth_list.append(hist) # time bin where pulse amplitude is found, used to determine charge # integration region name = "PulseAmplitudeBin_" + str(i) hist = TH1F(name, "", 200, 100, 300) hist.SetXTitle("Amplitude bin number") hist.SetYTitle("Counts") hist.SetLineColor(i + 1) hAmplitudeBin_list.append(hist) # number of pulses found in the waveform not in the fiber trigger # region name = "NbOfPulses_" + str(i) hist = TH1F(name, "", 20, 0, 20) hist.SetXTitle("Number of pulses in a 20 #mus window") hist.SetYTitle("Counts") hist.SetLineColor(i + 1) hNbOfPulses_list.append(hist) # pulse start time, only choose those pulses above threshold name = "PulseStartTime_" + str(i) hist = TH1F(name, "", 200, 100, 300) hist.SetXTitle("Pulse start time bin (1.6 ns/bin)") hist.SetYTitle("Counts") # hist.SetLineColor(i+1) hPulseStartTime_list.append(hist) # pulse time distributions for those pulses are 100 ns later than the # fiber triggered pulse name = "PulseTimeDist_" + str(i) hist = TH1F(name, "", NSamples / 10, 0, NSamples) hist.SetXTitle("Pulse time bin (16 ns/bin)") hist.SetYTitle("Counts") hist.SetLineColor(i + 1) hPulseTimeDist_list.append(hist) # pulse time distributions for those pulses are 100 ns later than the # fiber triggered pulse name = "PulseAmpVsTimeBin_" + str(i) hist = TH2F(name, "", NSamples / 10, 0, NSamples, 500, 0, 500) hist.SetXTitle("Pulse time bin") hist.SetYTitle("Pulse Amplitude (mV)") hist.SetLineColor(i + 1) hPulseAmplitudeVsTime_list.append(hist) # pulse time distributions for those pulses are 100 ns later than the # fiber triggered pulse name = "PulseAmpVsWidth_" + str(i) hist = TH2F(name, "", 100, 0, 100, 500, 0, 500) hist.SetXTitle("Pulse time bin") hist.SetYTitle("Pulse Amplitude (mV)") hPulseAmplitudeVsWidth_list.append(hist) # process the waveforms baseline_mean = 0.0 baseline_width = 0.0 threshold = 0.0 sumwave = [[0 for x in range(NSamples)] for y in range(NCH)] # special test for time diff flag1 = [False for x in range(Nwaves)] time1 = [0 for x in range(Nwaves)] flag2 = [False for x in range(Nwaves)] time2 = [0 for x in range(Nwaves)] for ch in range(NCH): for waveNb in range(Nwaves): # flag to determine whether there was afterpulse afterpulse_flag = False afilename = f.readline().rstrip() awave = np.asarray(decode_wfm(afilename)) baseline_mean = np.average(awave[NSamples - 1000:NSamples]) baseline_width = np.std(awave[NSamples - 1000:NSamples]) threshold = baseline_mean - Nsigma * baseline_width hPedMean_list[ch].Fill(baseline_mean) hPedWidth_list[ch].Fill(baseline_width) TimeBinOfAmplitude = np.argmin(awave[70:800]) + 70 if ch == 0 and awave[TimeBinOfAmplitude] < threshold: flag1[waveNb] = True time1[waveNb] = TimeBinOfAmplitude if ch == 1 and awave[TimeBinOfAmplitude] < threshold: flag2[waveNb] = True time2[waveNb] = TimeBinOfAmplitude # get charge integration about the amplitude: 20.8 ns before to 36.8 ns after the amplitude # sumcharge = 0.0 # if TimeBinOfAmplitude>=168 and TimeBinOfAmplitude<=180: sumcharge = np.sum(awave[TimeBinOfAmplitude - 13:TimeBinOfAmplitude + 23]) pulsestartbin = TimeBinOfAmplitude while awave[ pulsestartbin] < threshold and pulsestartbin >= TimeBinOfAmplitude - 20: pulsestartbin -= 1 hPulseStartTime_list[ch].Fill(pulsestartbin - 1) # else: # sumcharge = np.sum(awave[172-13:172+23]) # convert charge involving the 50 Ohm impedance fC = (sumcharge - baseline_mean * (23 + 13 + 1)) * QFactor # if awave[TimeBinOfAmplitude] < threshold: hAmplitude_list[ch].Fill( -1000.0 * (awave[TimeBinOfAmplitude] - baseline_mean)) hAmplitudeBin_list[ch].Fill(TimeBinOfAmplitude) # print TimeBinOfAmplitude, awave[TimeBinOfAmplitude] hFinalCharge_list[ch].Fill(-1.0 * fC) # search for number of pulses peakindex = peakutils.peak.indexes(-1.0 * awave[0:NSamples], thres=-1.0 * threshold, min_dist=31, thres_abs=True) for pulse_i in range(len(peakindex)): # skip pulse if it is below threshold in magnitude if awave[peakindex[pulse_i]] > threshold: continue hPulseTimeDist_list[ch].Fill( peakindex[pulse_i]) # +TimeBinOfAmplitude+200 hPulseAmplitudeVsTime_list[ch].Fill( peakindex[pulse_i], -1000.0 * (awave[peakindex[pulse_i]] - baseline_mean)) # determine the pulse width thisindex = peakindex[pulse_i] thiswidth = 0 while awave[thisindex] <= threshold and thisindex >= 2: # print pulse_i, ch, thiswaveform[ch][thisindex], # threshold[ch] thiswidth += 1 thisindex -= 1 # if thisindex<=1: # print eventNb, ch, pulse_i, thiswaveform[ch][thisindex] thisindex = peakindex[pulse_i] while awave[thisindex + 1] <= threshold and thisindex <= NSamples - 3: thiswidth += 1 thisindex += 1 # if thisindex>=NSamples-2: # print eventNb, ch, pulse_i, thiswaveform[ch][thisindex] hPulseWidth_list[ch].Fill((thiswidth + 2) * 2) hPulseAmplitudeVsWidth_list[ch].Fill( (thiswidth + 2) * 2, -1000.0 * (awave[peakindex[pulse_i]] - baseline_mean)) # determine whether this occurred after an LED pulse if peakindex[pulse_i] > afterpulse_cut_index: # if so, trigger the afterpulse flag afterpulse_flag = True if waveNb % 100 == 0: # print ch, waveNb, afilename for bin in range(0, NSamples, 1): hWave_list[ch].SetBinContent( bin + 1, -1000.0 * (awave[bin] - baseline_mean)) # hWave_list[ch].SetBinContent(bin+1,awave[bin]) waveDir.cd() lenname = int(len(afilename)) newName = "Wave_Ch_" + \ str(ch) + "_" + str(waveNb) + \ afilename[lenname - 4 - 17:lenname - 4] titleName = "Evt " + str(waveNb) + \ "_Ch" + str(ch) + "_PulseBins_" for pulse_i in range(len(peakindex)): titleName += str(peakindex[pulse_i]) titleName += "_" hWave_list[ch].SetName(newName) hWave_list[ch].SetTitle(titleName) hWave_list[ch].SetEntries(NSamples) hWave_list[ch].Write() hNbOfPulses_list[ch].Fill(len(peakindex)) # average of raw waveforms for each PMT for bin in range(0, NSamples, 1): sumwave[ch][bin] += 1000.0 * (awave[bin] - baseline_mean) # if afterpulse flag has been triggered, mark that an afterpulse occurred if afterpulse_flag == True: num_afterpulse_events[ch] += 1.0 # calculate afterpulse probability for the channel afterpulse_probability[ch] = num_afterpulse_events[ch] / Nwaves for ch in range(NCH): for bin in range(NSamples): hWaveAvg_list[ch].SetBinContent(bin + 1, sumwave[ch][bin] / Nwaves) waveDir.cd() hWaveAvg_list[ch].Write() for waveNb in range(Nwaves): if flag1[waveNb] is True and flag2[waveNb] is True: hTimeDiff.Fill(time1[waveNb] - time2[waveNb]) f.close() # write results resultsDir.cd() for i in range(0, NCH, 1): # fit the charge distributions with Poisson distribution plus # exponential background hFinalCharge_list[i].Write() for i in range(0, NCH, 1): hAmplitude_list[i].Write() for i in range(0, NCH, 1): hAmplitudeBin_list[i].Write() for i in range(0, NCH, 1): hPedMean_list[i].Write() for i in range(0, NCH, 1): hPulseStartTime_list[i].Write() for i in range(0, NCH, 1): hPedWidth_list[i].Write() for i in range(0, NCH, 1): hPulseTimeDist_list[i].Write() print "number of pulses: ", hPulseTimeDist_list[i].GetEntries() for i in range(0, NCH, 1): hPulseWidth_list[i].Write() for i in range(0, NCH, 1): hPulseAmplitudeVsTime_list[i].Write() for i in range(0, NCH, 1): hPulseAmplitudeVsWidth_list[i].Write() for i in range(0, NCH, 1): hNbOfPulses_list[i].Write() # write afterpulse probabilities for i in range(0, NCH, 1): print "afterpulse probability: ", afterpulse_probability[i] hTimeDiff.Write() rtfileoutput.Close()
def Draw( self, path ): graphs = [] for vd in self.vector_distributions: if vd.get_size() > 0: graphs.append( TGraph( vd.get_size(), vd.get_array_x(), vd.get_array_y() ) ) else: graphs.append( TGraph() ) limits_x = [ -math.pi , math.pi ] limits_y = [ self.map_bins_part[ 0 ][ 0 ], self.map_bins_part[ -1 ][ 1 ] ] lines = [] for i in range( len( self.map_bins_part ) ): if i%3 == 0: r_bot = self.map_bins_part[ i ][ 0 ] r_top = self.map_bins_part[ i ][ 1 ] for j in range( len( self.map_bins_part[ i ][ 2 ] ) ): theta_clockw = self.map_bins_part[ i ][ 2 ][ j ][ 0 ] theta_anticw = self.map_bins_part[ i ][ 2 ][ j ][ 1 ] lines.append( TLine( theta_clockw, r_bot, theta_clockw, r_top ) ) lines.append( TLine( theta_anticw, r_bot, theta_anticw, r_top ) ) if theta_anticw > theta_clockw: lines.append( TLine( theta_clockw, r_bot, theta_anticw, r_bot ) ) lines.append( TLine( theta_clockw, r_top, theta_anticw, r_top ) ) else: lines.append( TLine( theta_clockw, r_bot, math.pi , r_bot ) ) lines.append( TLine( -math.pi , r_bot, theta_anticw, r_bot ) ) lines.append( TLine( theta_clockw, r_top, math.pi , r_top ) ) lines.append( TLine( -math.pi , r_top, theta_anticw, r_top ) ) for line in lines: line.SetLineColor( 15 ) for i in range( len( self.map_bins_part ) ): if i%3 == 0: for j in range( len( self.map_bins_part[ i ][ 2 ] ) ): graphs_subset = [ graphs[ -1 ], graphs[ self.map_bins_part[ i ][ 2 ][ j ][ 2 ] ] ] colors = [ 3, 2 ] if len( self.map_bins_part[ i ][ 2 ] ) > 1: graphs_subset.append( graphs[ self.map_bins_part[ i ][ 2 ][ j-1 ][ 2 ] ] ) colors.append( 4 ) if len( self.map_bins_part[ i ][ 2 ] ) > 2: graphs_subset.append( graphs[ self.map_bins_part[ i ][ 2 ][ ( j+1 )%len( self.map_bins_part[ i ][ 2 ] ) ][ 2 ] ] ) colors.append( 4 ) if i > 0: graphs_subset.append( graphs[ self.map_bins_part[ i-1 ][ 2 ][ j ][ 2 ] ] ) colors.append( 4 ) if i < len( self.map_bins_part )-1: graphs_subset.append( graphs[ self.map_bins_part[ i+1 ][ 2 ][ j ][ 2 ] ] ) colors.append( 4 ) filename = path+'/'+self.__class__.__name__+'_map_'+str( ( i/3 )+1 )+'_'+str( j+1 )+'.png' draw_graphs( graphs_subset, colors, 0.5, '#theta', 'r', limits_x, limits_y, filename, lines ) for graph in graphs: graph.Delete() for vd in self.vector_distributions: vd.reset() templates = self.GetTemplates() hists = [] for a in self.loop_channels: hists.append( TH1F( create_name_hist(), '', self.num_bins_t, 0.0, float( self.num_bins_t ) ) ) map_bins_part = self.GetMapBinsPart() for i in range( len( map_bins_part ) ): if i%3 == 0: for j in range( len( map_bins_part[ i ][ 2 ] ) ): k = map_bins_part[ i ][ 2 ][ j ][ 2 ] if k > -1: for a in self.loop_channels: for n in self.loop_bins_t: hists[ a ].SetBinContent( n+1, templates[ k ][ a ][ n ] ) filename = path+'/'+self.__class__.__name__+'_pulse_'+str( ( i/3 )+1 )+'_'+str( j+1 )+'.png' draw_hists( hists, [ 2+a for a in self.loop_channels ], 'Time (bin)', '', filename, '', legend = True) for hist in hists: hist.Reset() if i > 0: k = map_bins_part[ i-1 ][ 2 ][ j ][ 2 ] if k > -1: for a in self.loop_channels: for n in self.loop_bins_t: hists[ a ].SetBinContent( n+1, templates[ k ][ a ][ n ] ) filename = path+'/'+self.__class__.__name__+'_pulse_'+str( ( i/3 )+1 )+'_'+str( j+1 )+'_bot.png' #draw_hists( hists, [ 2+a for a in self.loop_channels ], 'Time (bin)', '', filename, '') for hist in hists: hist.Reset() if i < len( map_bins_part )-1: k = map_bins_part[ i+1 ][ 2 ][ j ][ 2 ] if k > -1: for a in self.loop_channels: for n in self.loop_bins_t: hists[ a ].SetBinContent( n+1, templates[ k ][ a ][ n ] ) filename = path+'/'+self.__class__.__name__+'_pulse_'+str( ( i/3 )+1 )+'_'+str( j+1 )+'_top.png' #draw_hists( hists, [ 2+a for a in self.loop_channels ], 'Time (bin)', '', filename, '') for hist in hists: hist.Reset() for hist in hists: hist.Delete() return True
def fithr2(run,tdc,vthmin,vthmax): outd= "output/run%d/gric%d" % (run,tdc) os.system("mkdir -p "+outd) rb=1 fi=0 la=63 ped=[] for i in range(64): ped.append(0) f82=TFile("/tmp/histo%d_0.root" % run); f82.cd("/gric/B01SCURVE%d" % (tdc)); c1=TCanvas(); #c2=TCanvas("c2","Test",1400,900); #c2.cd() #c2.Divide(6,4) #c2.Draw() #c2.Update() #val = raw_input() #c2.Draw() fout=open(outd+"/summary_pedestal.txt","w"); fout.write("+--+-----+-----+-----+ \n"); gStyle.SetOptFit(); ncha=64 hmean=TH1F("hmean","Summary %d %d " %(run,tdc),vthmax-vthmin+1,vthmin,vthmax) hnoise=TH1F("hnoise","Summary noise %d %d " %(run,tdc),100,0.,30.) hpmean=TH1F("hpmean","Summary %d %d " %(run,tdc),2*ncha,0.,2.*ncha); hpmax=TH1F("hpmean","Summary max %d %d " %(run,tdc),2*ncha,0.,2.*ncha); hpnoise=TH1F("hpnoise","Summary noise %d %d " %(run,tdc),2*ncha,0.,2.*ncha); # scfit=TF1("scfit","[0]*TMath::Erfc((x-[1])/[2])",vthmin+1,vthmax); scfit=TF1("scfit","gaus",vthmin+1,vthmax); for ip in range(la,fi,-1): #c2.cd() hs=None hs=f82.Get("/gric/B10SCURVE%d/Padc%d" % (tdc,ip)); if (hs==None): continue; if (hs.GetEntries()==0): continue print(ip,fi,la," found") hs.Scale(1./10.); nmax=0 for i in range(1,hs.GetNbinsX()): if (hs.GetBinContent(i)==0): if (hs.GetBinContent(i-1)!=0 and hs.GetBinContent(i+1)!=0): hs.SetBinContent(i,(hs.GetBinContent(i-1)+hs.GetBinContent(i+1))/2.) else: if (hs.GetBinContent(i)>nmax): nmax=hs.GetBinContent(i) hs.GetXaxis().SetRangeUser(vthmin-1,vthmax); icolor= ip%4 +1 istyle= ip/4+1 hs.SetLineColor(icolor) hs.SetLineStyle(int(istyle)) hs.SetLineWidth(2) c1.cd() c1.Draw() if (ip==63): hs.Draw() else: hs.Draw("SAME") c1.Update() #c1.SaveAs("Run%d_AllStrip%d.root" % (run,tdc,asic)); c1.SaveAs(outd+"/AllStrip.pdf"); val = raw_input() for ip in range(fi,la+1): #c2.cd() hs=None hs=f82.Get("/gric/B10SCURVE%d/Padc%d" % (tdc,ip)); if (hs==None): continue; if (hs.GetEntries()==0): continue #hs.Scale(1./2700.); hder=TH1F("hder%d" % ip,"derivative",int(400/rb),0.,400.) #hs.Rebin(rb) #hs.Smooth() vmax=0 for i in range(1,hs.GetNbinsX()-1): if (hs.GetBinContent(i)==0): if (hs.GetBinContent(i-1)!=0 and hs.GetBinContent(i+1)!=0): hs.SetBinContent(i,(hs.GetBinContent(i-1)+hs.GetBinContent(i+1))/2.) else: if (hs.GetBinContent(i)>0 and hs.GetBinCenter(i) <vthmax): vmax=hs.GetBinCenter(i) #print(i,hs.GetBinContent(i),vmax,hs.GetNbinsX()-1) for i in range(1,hs.GetNbinsX()): if (hs.GetBinContent(i)-hs.GetBinContent(i+1)>-10): hder.SetBinContent(i,hs.GetBinContent(i)-hs.GetBinContent(i+1)) #hder.Rebin(2) hder.Smooth() hder.GetXaxis().SetRangeUser(vthmin-1,vthmax); nmax=0 xmax=0 for i in range(1,hder.GetNbinsX()): if (hder.GetBinContent(i)>nmax): nmax=hder.GetBinContent(i) xmax=hder.GetBinCenter(i) scfit.SetParameter(0,nmax); scfit.SetParameter(1,xmax); scfit.SetParameter(2,hder.GetRMS()*0.5); #scfit.SetParameter(2,5.); hs.GetXaxis().SetRangeUser(vthmin+1,vthmax); hder.Fit("scfit","Q","",xmax-10,xmax+20); #hs.GetXaxis().SetRangeUser(vthmin-1,scfit.GetParameter(1)+60); #gPad.SetLogy(); rped=scfit.GetParameter(1) c1.cd() c1.Draw() hder.Draw() c1.Update() #val1 = raw_input() print("heho ",rped,hder.GetMean(),scfit.GetParameter(2)) rped=hder.GetMean() hs.Draw() c1.cd() c1.Draw() c1.Update() fout.write("|%2d|%5.1f|%5.1f|%5.2f| \n" % (ip,rped,scfit.GetParameter(2),vmax)); hmean.Fill(rped) hpmax.SetBinContent(ip+1,vmax) hnoise.Fill(scfit.GetParameter(2)) hpmean.SetBinContent(ip+1,rped); hpnoise.SetBinContent(ip+1,scfit.GetParameter(2)) #c1.SaveAs("Run%d_Strip%d.root" % (run,ip)); #val = raw_input() #hder.Draw() #c1.Update() #val = raw_input() c1.Divide(2,2) c1.cd(1) hmean.Draw() hpmean.GetYaxis().SetRangeUser(vthmin,vthmax) hpmean.Draw() c1.Update() #c1.SaveAs(outd+"/Pedestal.pdf"); #val = raw_input() c1.cd(2) hnoise.Draw() c1.Update() #c1.SaveAs(outd+"/NoiseInt.pdf"); #val = raw_input() c1.cd(3) hpnoise.Draw() c1.Update() #val = raw_input() c1.Update() #c1.SaveAs(outd+"/Noise.pdf"); c1.cd(4) hpmax.Draw() c1.Update() val = raw_input() c1.Update() c1.SaveAs(outd+"/Summary.pdf"); c1.Close() fout.write("+--+-----+-----+-----+ \n"); fout.close() return 0
def runplik(file_name, sample_name): histograms = dict() for i in variables.getname(): #Nbin, minbin, maxbin = variables.getrange(i); bins = variables.getrange(i) buff = {} for ii in cuts.cuts: #buff[ii.getname()] = TH1F(i+ii.getname(), i, Nbin, minbin, maxbin); buff[ii.getname()] = TH1F(i + ii.getname(), i, len(bins) - 1, bins) histograms[i] = buff # open the file f1 = TFile(file_name) p1 = f1.Get('m2n/eventTree') entries = p1.GetEntriesFast() mu = WmuCollection() p1.SetBranchAddress('wmu', mu) tau = WtauCollection() p1.SetBranchAddress('wtau', tau) pair = WpairCollection() p1.SetBranchAddress('wpair', pair) jets = WjetCollection() p1.SetBranchAddress('wjet', jets) evt = Wevent() p1.SetBranchAddress('wevent', evt) genweightsum = 0 ztautauSF = 1 if 'DY' not in sample_name else 0.79 wjetsSF = 1 if 'WJets' not in sample_name else 0.76 tauidSF = 0.9 for jentry in xrange(entries): p1.GetEntry(jentry) NPU = evt.npu() if (NPU >= 0 and NPU < 80 and not 'Run' in sample_name): PUWeight = pu.weight[NPU] elif NPU >= 80 and not 'Run' in sample_name: PUWeight = 0 else: PUWeight = 1 #genweight = math.copysign(1, evt.genevtweight()); genweight = evt.genevtweight() #PUWeight=1. #<----------wywalic genweightsum += genweight if mu.size() != 0: goodjets = [] for j in jets: dphim = abs(j.phi() - mu[0].phi()) dphit = abs(j.phi() - tau[0].phi()) if dphim > pi: dphim -= (2 * pi) if dphit > pi: dphit -= (2 * pi) dRm = sqrt((j.eta() - mu[0].eta())**2 + dphim**2) dRt = sqrt((j.eta() - tau[0].eta())**2 + dphit**2) if j.pt() >= 30 and dRm > 0.5 and dRt > 0.5 and abs( j.eta()) < 4.7: goodjets.append(j) for ii in cuts.cuts: if ii.calculate(mu[0], tau[0], pair[0], evt, goodjets): for k, v in variables.getvariable(mu[0], tau[0], pair[0], evt, goodjets).items(): histograms[k][ii.getname()].Fill( v, genweight * PUWeight * ztautauSF * wjetsSF * weights.mutotaufakerateSF(tau[0].eta()) * tauidSF * weights.etotaufakerateSF(tau[0].eta())) outfilename = file_name.replace('.root', sample_name + '.root') outfile = TFile(outfilename, 'RECREATE') for k in histograms.keys(): for kk in histograms[k].keys(): histograms[k][kk].Write() geninfo = f1.Get('ininfo/evtweight').Clone() geninfo.Write() outfile.Write() outfile.Close() file_ = open('./root/' + sample_name + '.txt', 'a+') file_.write(sample_name + file_name + '; entris: ' + str(entries) + '; genweightsum: ' + str(genweightsum) + '\n') file_.close() return outfilename
def plot(MillePedeUser, alignables, config): logger = logging.getLogger("mpsvalidate") alignables.create_list(MillePedeUser) # number of bins to start numberOfBins = 10000 ###################################################################### # initialize data hierarchy # plots[mode][struct] # plots = [] # loop over mode for modeNumber, mode in enumerate(["xyz", "rot", "dist"]): plots.append([]) # loop over structures for structNumber, struct in enumerate(alignables.structures): plots[modeNumber].append(PlotData(mode)) # initialize histograms for modeNumber, mode in enumerate(["xyz", "rot", "dist"]): for structNumber, struct in enumerate(alignables.structures): # use a copy for shorter name plot = plots[modeNumber][structNumber] for i in range(3): if (mode == "xyz"): plot.histo.append( TH1F( "{0} {1} {2}".format(struct.get_name(), plot.xyz[i], mode), "Parameter {0}".format(plot.xyz[i]), numberOfBins, -1000, 1000)) else: plot.histo.append( TH1F( "{0} {1} {2}".format(struct.get_name(), plot.xyz[i], mode), "Parameter {0}".format(plot.xyz[i]), numberOfBins, -0.1, 0.1)) plot.histo[i].SetXTitle(plot.unit) plot.histo[i].GetXaxis().SetTitleOffset(0.85) plot.histoAxis.append(plot.histo[i].GetXaxis()) # add labels plot.title = TPaveLabel( 0.1, 0.8, 0.9, 0.9, "Module: {0} {1}".format(struct.get_name(), mode)) plot.text = TPaveText(0.05, 0.1, 0.95, 0.75) plot.text.SetTextAlign(12) plot.text.SetTextSizePixels(20) # save copy plots[modeNumber][structNumber] = plot ###################################################################### # fill histogram # for line in MillePedeUser: # is module ? if (line.ObjId == 1): for modeNumber, mode in enumerate(["xyz", "rot", "dist"]): for structNumber, struct in enumerate(alignables.structures): # use a copy for shorter name plot = plots[modeNumber][structNumber] # module in struct ? if (struct.contains_detid(line.Id)): for i in range(3): if (abs(line.Par[plot.data[i]]) != 999999): # transform xyz data from cm to #mu m if (mode == "xyz"): plot.histo[i].Fill(10000 * line.Par[plot.data[i]]) else: plot.histo[i].Fill(line.Par[plot.data[i]]) # save copy plots[modeNumber][structNumber] = plot ###################################################################### # find the best range # for modeNumber, mode in enumerate(["xyz", "rot", "dist"]): for structNumber, struct in enumerate(alignables.structures): # use a copy for shorter name plot = plots[modeNumber][structNumber] for i in range(3): # get first and last bin with content and chose the one which # has a greater distance to the center if (abs(numberOfBins / 2 - plot.histo[i].FindFirstBinAbove()) > abs(plot.histo[i].FindLastBinAbove() - numberOfBins / 2)): plot.maxBinShift[i] = abs( numberOfBins / 2 - plot.histo[i].FindFirstBinAbove()) # set the maxShift value plot.maxShift[i] = plot.histo[i].GetBinCenter( plot.histo[i].FindFirstBinAbove()) else: plot.maxBinShift[i] = abs( plot.histo[i].FindLastBinAbove() - numberOfBins / 2) # set the maxShift value plot.maxShift[i] = plot.histo[i].GetBinCenter( plot.histo[i].FindLastBinAbove()) # skip empty histogram if (abs(plot.maxBinShift[i]) == numberOfBins / 2 + 1): plot.maxBinShift[i] = 0 # three types of ranges # 1. multiple of standard dev if (config.rangemode == "stddev"): for i in range(3): if (plot.histo[i].GetEntries() != 0 and plot.histo[i].GetStdDev() != 0): # if the plotrange is much bigger than the standard # deviation use config.widthstdev * StdDev als Range if (max(plot.maxShift) / plot.histo[i].GetStdDev() > config.defpeak): # corresponding bin config.widthstdev*StdDev binShift = int(plot.histo[i].FindBin( config.widthstddev * plot.histo[i].GetStdDev()) - numberOfBins / 2) else: binShift = max(plot.maxBinShift) # save used binShift plot.binShift[i] = binShift # 2. show all if (config.rangemode == "all"): for i in range(3): plot.binShift[i] = plot.maxBinShift[i] # 3. use given ranges if (config.rangemode == "given"): for i in range(3): if (mode == "xyz"): valuelist = config.rangexyzM if (mode == "rot"): valuelist = config.rangerotM if (mode == "dist"): valuelist = config.rangedistM for value in valuelist: # maximum smaller than given value if (abs(plot.maxShift[i]) < value): binShift = value break # if not possible, force highest if (abs(plot.maxShift[i]) > valuelist[-1]): binShift = valuelist[-1] # calculate binShift plot.binShift[i] = int(binShift / plot.histo[i].GetBinWidth(1)) # all plot the same range if (config.samerange == 1): for i in range(3): plot.binShift[i] = max(plot.binShift) # save used range for i in range(3): plot.usedRange[i] = plot.binShift[i] # count entries which are not shown anymore for i in range(3): # bin 1 to begin of histogram for j in range(1, numberOfBins / 2 - plot.binShift[i]): plot.hiddenEntries[i] += plot.histo[i].GetBinContent(j) # from the end of shown bins to the end of histogram for j in range(numberOfBins / 2 + plot.binShift[i], plot.histo[i].GetNbinsX()): plot.hiddenEntries[i] += plot.histo[i].GetBinContent(j) # apply new range for i in range(3): if (plot.histo[i].GetEntries() != 0): # merge bins, ca. 100 should be visible in the resulting # plot mergeNumberBins = plot.binShift[i] # skip empty histogram if (mergeNumberBins != 0): # the 2*maxBinShift bins should shrink to 100 bins mergeNumberBins = int(2. * mergeNumberBins / config.numberofbins) # the total number of bins should be dividable by the # bins shrinked together if (mergeNumberBins == 0): mergeNumberBins = 1 while (numberOfBins % mergeNumberBins != 0 and mergeNumberBins != 1): mergeNumberBins -= 1 # Rebin and save new created histogram and axis plot.histo[i] = plot.histo[i].Rebin(mergeNumberBins) plot.histoAxis[i] = plot.histo[i].GetXaxis() # set view range. it is important to note that the number of bins have changed with the rebinning # the total number and the number of shift must be # corrected with / mergeNumberBins plot.histoAxis[i].SetRange( int(numberOfBins / (2 * mergeNumberBins) - plot.binShift[i] / mergeNumberBins), int(numberOfBins / (2 * mergeNumberBins) + plot.binShift[i] / mergeNumberBins)) # error if shift is bigger than limit limit = config.limit[mode] for i in range(3): # skip empty if (plot.histo[i].GetEntries() > 0): plot.text.AddText("max. shift {0}: {1:.2}".format( plot.xyz[i], plot.maxShift[i])) if (abs(plot.maxShift[i]) > limit): plot.text.AddText( "! {0} shift bigger than {1} !".format( plot.xyz[i], limit)) if (plot.hiddenEntries[i] != 0): plot.text.AddText("! {0} {1} outlier !".format( plot.xyz[i], int(plot.hiddenEntries[i]))) # save copy plots[modeNumber][structNumber] = plot ###################################################################### # make the plots # # show the skewness in the legend gStyle.SetOptStat("emrs") for modeNumber, mode in enumerate(["xyz", "rot", "dist"]): for structNumber, struct in enumerate(alignables.structures): # use a copy for shorter name plot = plots[modeNumber][structNumber] canvas = TCanvas( "canvasModules{0}_{1}".format(struct.get_name(), mode), "Parameter", 300, 0, 800, 600) canvas.Divide(2, 2) canvas.cd(1) plot.title.Draw() plot.text.Draw() # draw identification ident = identification(config) ident.Draw() # is there any plot? plotNumber = 0 # loop over coordinates for i in range(3): if (plot.histo[i].GetEntries() > 0): plotNumber += 1 canvas.cd(i + 2) setstatsize(canvas, plot.histo[i], config) plot.histo[i].DrawCopy() if (plotNumber == 0): break canvas.Update() # save as pdf canvas.Print("{0}/plots/pdf/modules_{1}_{2}.pdf".format( config.outputPath, mode, struct.get_name())) # export as png image = TImage.Create() image.FromPad(canvas) image.WriteImage("{0}/plots/png/modules_{1}_{2}.png".format( config.outputPath, mode, struct.get_name())) # add to output list output = OutputData(plottype="mod", name=struct.get_name(), parameter=mode, filename="modules_{0}_{1}".format( mode, struct.get_name())) config.outputList.append(output) ###################################################################### # make plots with substructure # if (config.showsubmodule == 1): alignables.create_children_list() for modeNumber, mode in enumerate(["xyz", "rot", "dist"]): for structNumber, struct in enumerate(alignables.structures): # use a copy for shorter name plot = plots[modeNumber][structNumber] subModule.plot(MillePedeUser, alignables, mode, struct, plot, config)
def createhisto(stringname, nbins, rmin, rmax): hden = TH1F("hden" + stringname, "hden" + stringname, nbins, rmin, rmax) hnum = TH1F("hnum" + stringname, "hnum" + stringname, nbins, rmin, rmax) hnum.Sumw2() hden.Sumw2() return hden, hnum
and returns the input parameters of the file for later use.""" try: x_par = float(search(r'x([^y]*)', filename).group()[1:]) y_par = float(search(r'y([^z]*)', filename).group()[1:]) z_par = float(search(r'z([^k]*)', filename).group()[1:]) ke_par = float(search(r'ke([^" "]*)', filename).group()[2:]) return (x_par, y_par, z_par, ke_par) except AttributeError: print("Bad form for filename.") for i in range(len(ratFiles)): print("Obtaining residuals for %s \n" % (filenames[i])) #Declare histograms print("Filling Histograms\n") Energy = TH1F("Energy %s" % (filenames[i]), "Fit Energy Dif", 250, -1, 1) X_Position = TH1F("X Position %s" % (filenames[i]), "Fit X Position Dif", 250, -500, 500) Y_Position = TH1F("Y Position %s" % (filenames[i]), "Fit Y Position Dif", 250, -500, 500) Z_Position = TH1F("Z Position %s" % (filenames[i]), "Fit Z Position Dif", 250, -500, 500) #Loop over all events for ds, run in rat.dsreader(ratFiles[i]): #Get Monte Carlo part of evemt mc = ds.GetMC() #Loop over all reconstructed particles in event (possible more than MC) for iev in range(0, ds.GetEVCount()): #Get reconstructed part of event ev = ds.GetEV(iev)
#!/usr/bin/python from ROOT import TGraph #import sys import csv from datetime import date import array as arr from ROOT import TCanvas, gROOT, TGraph, TH1F, TFile, gStyle, TLegend savefile = TFile("x.root", "update") n = 4 hcpuPerEvent1T = TH1F( "hcpuPerEvent1T", "PSNR en diferente iteraciones de la erosion;Iteraciones;PSRN", n, 0, n) hcpuPerEvent4T = TH1F("hcpuPerEvent4T", "CPU time per event;config;CPU time (sec)", n, 0, n) hcpuPerEvent1AT = TH1F("hcpuPerEvent1AT", "CPU time per event;config;CPU time (sec)", n, 0, n) hcpuPerEvent1CT = TH1F("hcpuPerEvent1CT", "CPU time per event;config;CPU time (sec)", n, 0, n) hcpuPerEvent1DT = TH1F("hcpuPerEvent1DT", "CPU time per event;config;CPU time (sec)", n, 0, n) hcpuPerEvent1ET = TH1F("hcpuPerEvent1ET", "CPU time per event;config;CPU time (sec)", n, 0, n) class Job: """ Job information """ def __init__(self, iname, itime, iflag):
elif (ZTree): tree = inputTree.Get("ZTree/candTree") treeText = "ZTree" else: print("Error: wrong option!") else: print("Error: choose a period!") if (redoHistos): TH1.SetDefaultSumw2( ) # set sumw2 = true fro all the histograms created from now on # define ISO histograms # Z->ee Z_ele_1st_LepBDT_hist = TH1F('LepBDT leading ele', 'LepBDT leading ele', 100, -1.1, 1.1) Z_ele_1st_LepBDT_hist_EB = TH1F('LepBDT leading ele in ECAL Barrel', 'LepBDT leading ele in ECAL Barrel', 100, -1.1, 1.1) Z_ele_1st_LepBDT_hist_EE = TH1F('LepBDT leading ele in ECAL Endcap', 'LepBDT leading ele in ECAL Endcap', 100, -1.1, 1.1) # Z->mumu Z_mu_1st_LepBDT_hist = TH1F('LepBDT leading mu', 'LepBDT leading mu', 40, 0., 10.) Z_mu_1st_LepBDT_hist_MB = TH1F('LepBDT leading mu in Muon Barrel', 'LepBDT leading mu in Muon Barrel', 40, 0., 10.) Z_mu_1st_LepBDT_hist_ME = TH1F('LepBDT leading mu in Muon Endcap', 'LepBDT leading mu in Muon Endcap', 40, 0.,
else: print("Error: choose a period!") # output directory outputDir = "FitResults_DATA_" + str(period) + "_" + str(treeText) gSystem.Exec("mkdir -p " + outputDir) print "Output directory created!" if (redoHistos): TH1.SetDefaultSumw2( ) # set sumw2 = true fro all the histograms created from now on #define histogramms #Z->ee histos ZMass_ele_hist = TH1F('ZMass_ele', 'ZMass_ele', 120, 60, 120) #ZMass , Z->ee ZMass_ele_hist_EBEB = TH1F('ZMass_ele_EBEB', 'ZMass_ele_EBEB', 120, 60, 120) #ZMass , Z->ee , Barrel-Barrel ZMass_ele_hist_EBEE = TH1F('ZMass_ele_EBEE', 'ZMass_ele_EBEE', 120, 60, 120) #ZMass , Z->ee , Barrel-Endcap ZMass_ele_hist_EEEE = TH1F('ZMass_ele_EEEE', 'ZMass_ele_EEEE', 120, 60, 120) #ZMass , Z->ee , Endcap-Endcap if not ZTree: ZMass_ele_hist_extraMu = TH1F('ZMass_ele_extraMu', 'ZMass_ele_extraMu', 120, 60, 120) #ZMass , Z->ee + Extra mu ZMass_ele_hist_extraEl = TH1F('ZMass_ele_extraEl', 'ZMass_ele_extraEl', 120, 60, 120) #ZMass , Z->ee + Extra e #Z->mumu histos ZMass_mu_hist = TH1F('ZMass_mu', 'ZMass_mu', 120, 60, 120) #ZMass , Z->mumu ZMass_mu_hist_MBMB = TH1F('ZMass_mu_MBMB', 'ZMass_mu_MBMB', 120, 60,
t0.append(float(row0[0])) # Channel 1 t1.append(float(row1[0])) dti = t0[-1] - t1[-1] if dti > -10000 and dti < 10000: dt.append(dti) nevt += 1 # for it0,it1,idt in zip(t0,t1,dt): # print it0,it1,idt print nevt print np.std(dt) print np.mean(dt) # plt.hist(dt,100) # plt.show() c1 = TCanvas("c1") h1 = TH1F("h1", "", 250, -2000, 2000) for idt in dt: h1.Fill(idt) c1.SetLogy() h1.GetXaxis().SetTitle("Time Difference (ps)") h1.GetXaxis().CenterTitle() h1.GetYaxis().SetTitle("Number of Events") h1.GetYaxis().CenterTitle() h1.Draw() raw_input()
t1 = infile.Get("tree1") # check the tree name and input... t2 = infile.Get("tree2") # check the tree name and input... px = numpy.array([0], 'd') py = numpy.array([0], 'd') pz = numpy.array([0], 'd') t1.SetBranchAddress("px", px) # SetBranchAddress for each tree t1.SetBranchAddress("py", py) t1.SetBranchAddress("pz", pz) t2.SetBranchAddress("px", px) # SetBranchAddress for each tree t2.SetBranchAddress("py", py) t2.SetBranchAddress("pz", pz) hist1 = TH1F("hist1", "hist1", NBins, IBin, FBin) # define 1D histogram hist2 = TH1F("hist2", "hist2", NBins, IBin, FBin) hist3 = TH1F("hist3", "hist3", NBins, IBin, FBin) ENUM = t1.GetEntries() for i in range(ENUM): t1.GetEntry(i) if ((px[0] > -1) & (py[0] > 0.5) & (pz[0] < 3.)): hist1.Fill(px[0]) else: continue ENUM = t2.GetEntries() for i in range(ENUM): t2.GetEntry(i) if ((px[0] < -0.1) & (py[0] < 0.5) & (pz[0] < 2)):
import numpy as np # Trick for docker install to run headless # and never use plt.show() import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from scipy.optimize import minimize from array import array from ROOT import (TH1F, TH2F, TH1D, TF1, TFile, TCanvas, gPad, gStyle, TLatex, TGraphErrors) allowed_types = (TH1F, TH1D) default_histo = TH1F('default', '', 100, 0, 1) default_histo2d = TH2F('default', '', 100, 0, 1, 100, 0, 1) def load_histos(file): ''' Use the ROOT file structure to load a dictionary of histograms. ''' h = {} for k in file.GetListOfKeys(): h[k.GetName()] = file.Get(k.GetName()) return h def numpify(histo): """ TH1F to np.arrays. """ if type(histo) not in allowed_types:
def makePlot(sfHist,ofHist,selection,plot,runRange,region,cmsExtra,combination,dyHist=None): colors = createMyColors() hCanvas = TCanvas("hCanvas", "Distribution", 800,800) plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1) ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3) style = setTDRStyle() ROOT.gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() yMax = sfHist.GetBinContent(sfHist.GetMaximumBin()) if plot.yMax == 0: yMax = yMax*1.35 else: yMax = plot.yMax yMax = 15 plotPad.DrawFrame(plot.firstBin,0,plot.lastBin, yMax,"; %s ; %s" %(plot.xaxis,plot.yaxis)) bkgHist = ofHist.Clone("bkgHist") if dyHist is not None: bkgHist.Add(dyHist) sfHist.SetMarkerStyle(20) bkgHist.SetLineColor(ROOT.kBlue+3) bkgHist.SetLineWidth(2) dyHist.SetLineColor(ROOT.kGreen+3) dyHist.SetFillColor(ROOT.kGreen+3) dyHist.SetFillStyle(3002) latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)"%"19.4") latexCMS.DrawLatex(0.21,0.88,"CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.21,yLabelPos,"%s"%(cmsExtra)) if combination == "SF": rSFOFErr = getattr(rSFOF,region).err elif combination == "EE": rSFOFErr = getattr(rEEOF,region).err elif combination == "MM": rSFOFErr = getattr(rMMOF,region).err errGraph, histUp, histDown = getErrHist(plot,combination,region,ofHist,dyHist,rSFOFErr) errGraph.SetFillColor(myColors["MyBlue"]) errGraph.SetFillStyle(3001) #~ errGraph.SetLineColor(myColors["MyDarkBlue"]) #~ errGraph.SetMarkerColor(myColors["MyDarkBlue"]) errGraph.Draw("SAME02") bkgHist.Draw("samehist") dyHist.Draw("samehist") sfHist.Draw("samepe") lines = getLines(0, sfHist.GetBinContent(sfHist.GetMaximumBin())+10,xPos=[mllBins.lowMass.high,mllBins.onZ.low,mllBins.onZ.high, mllBins.highMass.low ]) for line in lines: line.Draw() leg = TLegend(0.62, 0.51, 0.89, 0.92,"","brNDC") leg.SetFillColor(10) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) from ROOT import TH1F,kWhite legendHistDing = TH1F() legendHistDing.SetFillColor(kWhite) if region == "inclusive": leg.AddEntry(legendHistDing,"ATLAS signal region","h") elif region == "central": leg.AddEntry(legendHistDing,"Central signal region","h") elif region == "forward": leg.AddEntry(legendHistDing,"Forward signal region","h") leg.AddEntry(sfHist,"Data","PL") leg.AddEntry(bkgHist, "Total backgrounds","l") leg.AddEntry(dyHist,"Drell--Yan", "f") leg.AddEntry(errGraph,"Total uncert.", "f") leg.Draw("same") plotPad.RedrawAxis() ratioPad.cd() ratioGraphs = ratios.RatioGraph(sfHist,bkgHist, xMin=plot.firstBin, xMax=plot.lastBin,title="Data / Bgnd",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=1000) ratioGraphs.addErrorByHistograms( "rSFOF", histUp, histDown,color= myColors["MyBlue"],fillStyle=3001) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) leg2 = TLegend(0.175, 0.78, 0.475, 0.9,"","brNDC") leg2.SetFillColor(10) leg2.SetLineColor(10) leg2.SetShadowColor(0) leg2.SetBorderSize(1) leg2.AddEntry(errGraph,"Systematic uncert.", "f") leg2.Draw("same") ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("fig/mllResult_%s_%s_%s.pdf"%(selection.name,runRange.label,combination))