def FillRandom(layerid, detid, nhits): rnd = TRandom() rnd.SetSeed() suf = suffix(layerid, detid) for n in range(nhits): xtrk = rnd.Uniform(0, x_chip_sensitive) ytrk = rnd.Uniform(-y_chip_sensitive / 2, +y_chip_sensitive / 2) histos["h_hits" + suf].Fill(xtrk, ytrk)
def FindInitialGuess(npoints, hexp, hsim, mflags=[True, True, True], binlow=None, binup=None, filename='grid_initial_guess.yaml'): import itertools import random from ROOT import TRandom import numpy as np from likelihood import chi2 import yaml data = {} af, bf, cf = mflags #If for any reason the minimum is at a certain limit redefine limits around it seed = random.randint(0, 500) print("Finding a tentative initial guess. Using seed:", seed) ran = TRandom(seed) chiaux = np.inf for step in range(npoints): m = ran.Uniform(0, 4) d = ran.Uniform(-100, 100) calpars = [m, d] fwhmpars = np.array( [ran.Uniform(0, 2), ran.Uniform(0, 2), ran.Uniform(0, 2)])[mflags].tolist() pars = fwhmpars + calpars if (chi2(pars, hexp, hsim, mflags=mflags, binlow=binlow, binup=binup) < chiaux): chiaux = chi2(pars, hexp, hsim, mflags=mflags, binlow=binlow, binup=binup) fpars = pars print('step:', step, 'pars:', pars, 'chisq:', chiaux) if (af and bf and cf): data['a'] = float(pars[0]) data['b'] = float(pars[1]) data['c'] = float(pars[2]) if (bf and cf): data['b'] = float(pars[0]) data['c'] = float(pars[1]) data['m'] = fpars[-2] data['d'] = fpars[-1] data['binlow'] = binlow data['binup'] = binup print('Printing', filename) with open(filename, 'w') as outfile: yaml.dump(data, outfile, default_flow_style=False)
def run_example(save=True): ########################################## # first define some objects to play with # ########################################## random = TRandom(getpid()) # Create a histogram to play with bin_edges = array("d", [2, 3, 5, 7, 11, 13, 17, 19]) hist_1 = TH1F("some_histogram_1", "", len(bin_edges) - 1, bin_edges) hist_2 = TH1F("some_histogram_2", "", len(bin_edges) - 1, bin_edges) # Fill histogram from a random number generation for i in range(len(bin_edges) + 1): hist_1.SetBinContent(i + 1, random.Poisson(42)) hist_1.SetBinError(i + 1, random.Gaus(10)) hist_2.SetBinContent(i + 1, random.Poisson(42)) hist_2.SetBinError(i + 1, random.Gaus(10)) ################################### # The actual plotting starts here # ################################### # Generate 3 styles with constant markerstyle styles = generate_styles(StyleObject1D, 2, markerstyle=34) # Create a figure with one cell (1 column and one row) figure = ROOTFigure(1, 1, size=(400, 600), row_margin=0.05, column_margin=0.1) # plot is actually defined automatically now since it's a 1x1 grid # hence the following should be skipped # plot = figure.define_plot(0, 0) # so one can add an object via the figure... figure.add_object(hist_1, style=styles[0], label="MyHist1") # ...or obtain the current single plot cell plot = figure.change_plot() # ...and add another object via plot.add_object(hist_2, style=styles[1], label="MyHist2") # Set some axis limits and titles explicitly plot.axes("x", title="x_title") plot.axes("y", limits=[0, 120], title="y_title") figure.create() if save: figure.save("example_one_plot.eps") return True
def run_example(save=True): ########################################## # first define some objects to play with # ########################################## random = TRandom(getpid()) # Create a histogram to play with bin_edges = array("d", [2, 3, 5, 7, 11, 13, 17, 19]) hist_1 = TH2F("some_histogram_1", "", len(bin_edges) - 1, bin_edges, len(bin_edges) - 1, bin_edges) #hist_2 = TH1F("some_histogram_2", "", len(bin_edges) - 1, bin_edges) # Fill histogram from a random number generation for i in range(len(bin_edges) + 1): for j in range(len(bin_edges) + 1): hist_1.SetBinContent(i + 1, j + 1, random.Poisson(42)) hist_1.SetBinError(i + 1, j + 1, random.Gaus(10)) hist_2 = hist_1.ProjectionX() ################################### # The actual plotting starts here # ################################### # Generate 3 styles with constant markerstyle style = StyleObject1D() style.draw_options = "colz" style_2 = StyleObject1D() # Create a figure with one cell (1 column and one row) figure = ROOTFigure(1, 2, size=(400, 600), row_margin=((0.06, 0.005), (0.005, 0.05)), column_margin=(0.11, 0.1)) # plot is actually defined automatically now since it's a 1x1 grid # hence the following should be skipped plot_1 = figure.define_plot() plot_1.axes("x", title="x_title", title_offset=2.5) plot_1.axes("y", title="y_title_1", title_offset=1.9) # so one can add an object via the figure... plot_1.add_object(hist_1, style=style) plot = figure.define_plot(share_x=plot_1) plot.add_object(hist_2, style=style_2) plot.axes("y", title="ProjectionX", title_offset=1.9) figure.create() if save: figure.save("test_2D_plot.eps") return True
def AddFWHM(h, name, modelpars, mflags=[True, True, True]): import random from ROOT import TH1I, TRandom #seed = random.randint(0, 500) seed = 123 ran = TRandom(seed) nbins = h.GetNbinsX() hout = TH1I(name, '', nbins, h.GetBinLowEdge(1), h.GetXaxis().GetBinUpEdge(nbins)) for i in range(1, nbins + 1): for j in range(1, int(h.GetBinContent(i)) + 1): hout.Fill( ran.Gaus( h.GetBinCenter(i), FWHM(h.GetBinCenter(i), modelpars, mflags=mflags) / 2.35)) return hout
def bkgtracks(N): tracks = [] resolution = 0.001 ## cm (10 um) rnd = TRandom() rnd.SetSeed() for i in range(N): R = cfgmap["Rbeampipe"] - cfgmap["Wbeampipe"] phi = rnd.Uniform(0, 2 * ROOT.TMath.Pi()) x0 = R * ROOT.TMath.Cos(phi) y0 = R * ROOT.TMath.Sin(phi) z0 = cfgmap["zDipoleExit"] z4 = cfgmap["zLayer4"] x4 = rnd.Uniform(1.15 * cfgmap["xPsideL"], 1.15 * cfgmap["xEsideR"]) y4 = rnd.Uniform(-1.15 * cfgmap["Hstave"] / 2, 1.15 * cfgmap["Hstave"] / 2) r0 = [x0, y0, z0] r4 = [x4, y4, z4] z1 = cfgmap["zLayer1"] x1 = xofz(r4, r0, z1) + rnd.Gaus(0, resolution) y1 = yofz(r4, r0, z1) + rnd.Gaus(0, resolution) z2 = cfgmap["zLayer2"] x2 = xofz(r4, r0, z2) + rnd.Gaus(0, resolution) y2 = yofz(r4, r0, z2) + rnd.Gaus(0, resolution) z3 = cfgmap["zLayer3"] x3 = xofz(r4, r0, z3) + rnd.Gaus(0, resolution) y3 = yofz(r4, r0, z3) + rnd.Gaus(0, resolution) z5 = 360 x5 = xofz(r4, r0, z5) y5 = yofz(r4, r0, z5) line = TPolyLine3D() line.SetNextPoint(x0, y0, z0) line.SetNextPoint(x1, y1, z1) line.SetNextPoint(x2, y2, z2) line.SetNextPoint(x3, y3, z3) line.SetNextPoint(x4, y4, z4) line.SetNextPoint(x5, y5, z5) line.SetLineColor(ROOT.kRed) tracks.append(line) return tracks
def generateToyFunctions(normNom, normErr, p1, p1err, p2, p2err, corrMatrix, covMatrix, nToys): from ROOT import TF1, TRandom from math import sqrt functions = [] formula = "[0]*TMath::Power(x, [1]+[2]*TMath::Log(x))" gaussDist = TRandom() x1Nom = (-0.997412*p1-0.0719019*p2) x2Nom = (0.0719019*p1-0.997412*p2) print "p1 is ", p1 print "p1err is ", p1err print "x1Nom is ", x1Nom print "p2 is ", p2 print "p2err is ", p2err print "x2Nom is ", x2Nom x1err = -0.997412*p1err-0.0719019*p2err x2err = 0.0719019*p1err-0.997412*p2err print "x1err is ", -0.997412*p1err-0.0719019*p2err print "x2err is ", (0.0719019*p1err-0.997412*p2err) for i in range (0, nToys): print "--------" print "toy %i:" % i x1 = gaussDist.Gaus(x1Nom,x1err) x2 = gaussDist.Gaus(x2Nom, x2err) varp1 = (-0.997412*x1+0.0719019*x2) varp2 = (-0.0719019*x1-0.997412*x2) print "original p1, p2: %f, %f" % (p1, p2) print "original p1err, p2err: %f, %f" % (p1err, p2err) print "translates to x1, x2: %f, %f" % (x1Nom, x2Nom) print "x1err, x2err: %f, %f" % (x1err, x2err) print "picked x1, x2: %f, %f" % (x1, x2) print "translates to p1, p2: %f, %f" % (varp1, varp2) functions.append(TF1("f_%i" % i, formula, 700, 4700)) functions[-1].SetParameters(1, varp1, varp2) if functions[-1].Integral(700, 4700) == 0: del(functions[-1]) else: prenorm = functions[-1].Integral(700, 4700) norm = gaussDist.Gaus(normNom, normErr)/prenorm print "norm is: ", norm functions[-1].SetParameter(0, norm) return functions
def GetContours(clusters, positions, h, hsig=None): contourspts = [] contours = [] bkgmarkers = [] sigmarkers = [] rnd = TRandom() rnd.SetSeed() for i in range(len(clusters)): cluster = clusters[i] position = positions[i] icol = int(rnd.Uniform(0, len(colors))) col = colors[icol] contourpts, contdata, contour = GetClusterContour(cluster, h, col) # marker,issig = GetClusterMarker(position,h,col,hsig) marker, issig = GetClusterMarker(position, h, ROOT.kGray + 1, hsig) contourspts.append(contourpts) contours.append(contour) if (issig): sigmarkers.append(marker) else: bkgmarkers.append(marker) return contourspts, bkgmarkers, sigmarkers, contours
def Rebin(h, name, newbinwidth, xlow): import random from ROOT import TH1I, TRandom binwidth = h.GetBinWidth(1) nbins = h.GetNbinsX() xup = h.GetXaxis().GetBinUpEdge(nbins) L = xup - xlow if (L % newbinwidth == 0): newnbin = int(L / newbinwidth) h2 = TH1I(name, "", newnbin, xlow, xup) if (L % newbinwidth > 0): newnbin = int(L / newbinwidth) + 1 newxup = xup + newbinwidth h2 = TH1I(name, "", newnbin, xlow, newxup) #seed = random.randint(0, 500) seed = 123 ran = TRandom(seed) for i in range(1, nbins + 1): for j in range(1, int(h.GetBinContent(i)) + 1): h2.Fill( ran.Uniform(h.GetBinLowEdge(i), h.GetXaxis().GetBinUpEdge(i))) return h2
xval = 0.04 sigmaAtX = mres.Eval(xval) blahh = 0 #print pdf.IntegralOneDim(xval-1.4*sigmaAtX,xval+1.4*sigmaAtX,1e-12,1e-12,ROOT.Double(blahh)) pdfIntegral = pdf.IntegralOneDim(0.0, 0.1, 1e-12, 1e-12, ROOT.Double(blahh)) if (nEvents == 0): nEvents = pdfIntegral * 0.5 / 2.8 print nEvents fullRange = pdf.IntegralOneDim(0.02 - 1.4 * mres.Eval(0.02), 0.06 + 1.4 * mres.Eval(0.06), 1e-12, 1e-12, ROOT.Double(blahh)) / 2.8 print "full range has {0} independent regions".format(fullRange) rand = TRandom() c = TCanvas("c", "c", 800, 600) c.Print(remainder[0] + ".pdf[") outfile = TFile(remainder[0] + ".root", "RECREATE") c.SetLogy(0) n_massbins = 50 minmass = 0.02 maxmass = 0.06 data = TH1D("data", "data", 200, 0, 0.1) pvalHist = TH1D("pval", "pval", 100000, 0, 1.0) allpvalHist = TH1D("allpval", "allpval", 100000, 0, 1.0) pvalCdfHist = TH1D("pvalCdf", "pvalCdf", 100000, 0, 1.0)
def seed (s): global rootrandom raise ValueError("s should be used! ") rootrandom = TRandom(0xdeadbeef)
from ROOT import TRandom #from heppy.utils.pdebug import pdebugger raise ValueError('does not behave as python random! the seed is always the same...') rootrandom = TRandom() def expovariate (a): x=rootrandom.Exp(1./a) #pdebugger.info( x) return x def uniform (a, b): x=rootrandom.Uniform(a, b) #pdebugger.info( x) return x def gauss (a, b): x= rootrandom.Gaus(a,b) #pdebugger.info( x) return x def seed (s): global rootrandom raise ValueError("s should be used! ") rootrandom = TRandom(0xdeadbeef)
hpx = TH1F('hpx', 'This is the px distribution', 100, -4, 4) hpx.Print() #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 random = TRandom() random.SetSeed(0) # Fill histograms randomly. #px, py = Double(), Double() kUPDATE = 1000 for i in xrange(2500000): # Generate random values. # px, py = random.gauss(0, 1), random.gauss(0, 1) px, py = random.Gaus(0, 1), random.Gaus(0, 1) # pt = (px*px + py*py)**0.5 pt = math.sqrt(px * px + py * py) # pt = (px*px + py*py) # random = rndm(1) # Fill histograms.
def run_example(save=True): ########################################## # first define some objects to play with # ########################################## random = TRandom(getpid()) # Create a histogram to play with bin_edges = array("d", [2, 3, 5, 7, 11, 13, 17, 19]) hist_1 = TH1F("some_histogram_1", "", len(bin_edges) - 1, bin_edges) hist_2 = TH1F("some_histogram_2", "", len(bin_edges) - 1, bin_edges) # Fill histogram from a random number generation for i in range(len(bin_edges) + 1): hist_1.SetBinContent(i + 1, random.Poisson(42)) hist_1.SetBinError(i + 1, random.Gaus(10)) hist_2.SetBinContent(i + 1, random.Poisson(42)) hist_2.SetBinError(i + 1, random.Gaus(10)) ################################### # The actual plotting starts here # ################################### # Generate 5 styles, keep markerstyle the same for all styles = generate_styles(StyleObject1D, 5, markerstyle=21) # the overall figure with a grid of 3 columns and 4 rows (default is 1 column and 1 row) figure = ROOTFigure(3, 4, size=(600, 600), column_margin=(0.05, 0.025)) # define a plot from cell (1, 1) to cell (2, 2) figure.define_plot(1, 1, 2, 2, y_log=True) # internally, set to current plot so we can add objects figure.add_object(hist_1, style=styles[0], label="MyLabel1") figure.add_object(hist_2, style=styles[1], label="MyLabel2") # define another plot and store the return value in plot2 cause we want to share its x and y-axis later # since this should only take one cell, we only need low column and low row plot2 = figure.define_plot(0, 0, 1, 0) # add same objects as above figure.add_object(hist_1, style=styles[0], label="MyLabel1") figure.add_object(hist_2, style=styles[1], label="MyLabel2") # now add another plot and we want to share the y-axis again figure.define_plot(2, 0, share_y=plot2) figure.add_object(hist_1, style=styles[2], label="MyLabel4") # now add another plot and we want to share the x-axis plot3 = figure.define_plot(0, 1) figure.add_object(hist_1, style=styles[2], label="MyLabel5") # now add another plot and we want to share the x-axis again figure.define_plot(0, 2, 0, 3, share_x=plot3) figure.add_object(hist_1, style=styles[2], label="MyLabel6") plot4 = figure.define_plot(1, 3) figure.add_object(hist_1, style=styles[2], label="MyLabel7") figure.define_plot(2, 3, share_y=plot4) figure.add_object(hist_1, style=styles[3], label="MyLabel8") figure.add_object(hist_2, style=styles[4], label="MyLabel9") # until now, nothing actually happened, the above is really only a specification # only with this call things are actually created and drawn figure.create() if save: figure.save("test_plot_arrangement.eps") return True
def run_example(save=True): ########################################## # first define some objects to play with # ########################################## random = TRandom(getpid()) # Construct a TGraph to play with n_points = 100 graph = TGraph(n_points) for i in range(n_points): graph.SetPoint(i, random.Gaus(16.5, 5), random.Poisson(21)) # Create a histogram to play with bin_edges = array("d", [2, 3, 5, 7, 11, 13, 17, 19]) hist = TH1F("some_histogram", "", len(bin_edges) - 1, bin_edges) # Fill histogram from a random number generation for i in range(len(bin_edges) - 1): hist.SetBinContent(i + 1, random.Poisson(42)) hist.SetBinError(i + 1, random.Gaus(10)) # And now add a function func = TF1("func", "84*sin(x)*sin(x)/x", 1, 10) ################################### # The actual plotting starts here # ################################### # Generate 5 styles, keep markerstyle the same for all styles = generate_styles(StyleObject1D, 5, markerstyle=34) styles_graphs = generate_styles(StyleObject1D, 5, markerstyle=21, draw_options=["P"]) # make explicity style for the function func_style = StyleObject1D() func_style.linecolor = kBlack # number of columns and rows n_cols = 3 n_rows = 4 # Define a MxN grid with overall margins on the left, bottom, right and top figure = make_grid(ROOTFigure, (n_cols, n_rows), 0.08, 0.05, 0.05, 0.05, size=(1000, 1000), x_title="x_title", y_title="y_title") for i in range(n_cols * n_rows): # change current plot figure.change_plot(i) # Add a histogram figure.add_object(hist, style=styles[i % len(styles)], label=f"MyHist{i}") # Add another object, say a TGraph figure.add_object(graph, style=styles_graphs[i % len(styles_graphs)], label=f"MyGraph_{i}") # Add another object, now a TF1 figure.add_object(func, style=func_style, label=f"MyFunc_{i}") # And some text figure.add_text("Text", 0.5, 0.1) figure.create() if save: figure.save("test_grid_mxn.eps") return True
return retval def centerOfGravity(y1, y2): return (y1 * xmin + y2 * xmax) / (y1 + y2) from ROOT import TH1D, TCanvas, TRandom hin = TH1D("hin", "x_in", 100, xmin * 2., xmax * 2.) hout = TH1D("hout", "x_out", 100, xmin * 2., xmax * 2.) hres = TH1D("hres", "residual", 100, -30., 30.) nev = 1000 rang = TRandom() thickness = 150 chargePerUm = 77 totalCharge = chargePerUm * thickness for i in range(0, nevents): xin = rang.Uniform(xmin, xmax) hin.Fill(xin) leftCharge = (1 - etaFunc(xin)) * totalCharge rightCharge = (etaFunc(xin)) * totalCharge #print "Pos: " + str(xin) #print "Charge: " + str(leftCharge) + " " + str(rightCharge)
sidesarr = getLogicSidesArr() n = 0 ### init n for n in range(Nevt): ## clear the output vectors clusters_xyz.clear() clusters_type.clear() clusters_id.clear() ### embed some noise ***clusters*** ids = [ 1000, 2000, 3000, 4000 ] ## assuming there's no chance to have more than 1k noise clusters per layer layer2z = {1: 300, 2: 310, 3: 320, 4: 330} rnd = TRandom() rnd.SetSeed() for side in sidesarr: for kN in range(NnoiseClusters): for layer in layers: x = rnd.Uniform(xPsideL, xPsideR) if ( side == "Pside") else rnd.Uniform(xEsideL, xEsideR) y = rnd.Uniform(-0.75, +0.75) z = layer2z[layer] cluster = ROOT.TPolyMarker3D() cluster.SetNextPoint(x, y, z) clusters_xyz.push_back(cluster) clusters_type.push_back(-1) clusters_id.push_back(ids[layer - 1]) ids[layer - 1] += 1
def main(): ########################################################################################## ########################################################################################## ########################################################################################## ### read fits to root file # fitsEx = GetFits() svd0Seed = ROOT.std.vector( float )() svd1Seed = ROOT.std.vector( float )() svd2Seed = ROOT.std.vector( float )() chi2xzSeed = ROOT.std.vector( float )() chi2yzSeed = ROOT.std.vector( float )() residxzSeed = ROOT.std.vector( float )() residyzSeed = ROOT.std.vector( float )() issigSeed = ROOT.std.vector( int )() iGenMatch = ROOT.std.vector( int )() x1Seed = ROOT.std.vector( float )() y1Seed = ROOT.std.vector( float )() z1Seed = ROOT.std.vector( float )() x2Seed = ROOT.std.vector( float )() y2Seed = ROOT.std.vector( float )() z2Seed = ROOT.std.vector( float )() x3Seed = ROOT.std.vector( float )() y3Seed = ROOT.std.vector( float )() z3Seed = ROOT.std.vector( float )() x4Seed = ROOT.std.vector( float )() y4Seed = ROOT.std.vector( float )() z4Seed = ROOT.std.vector( float )() pxSeed = ROOT.std.vector( float )() pySeed = ROOT.std.vector( float )() pzSeed = ROOT.std.vector( float )() eSeed = ROOT.std.vector( float )() pxGen = ROOT.std.vector( float )() pyGen = ROOT.std.vector( float )() pzGen = ROOT.std.vector( float )() eGen = ROOT.std.vector( float )() qGen = ROOT.std.vector( float )() iGen = ROOT.std.vector( int )() tF = TFile("../data/root/seeds_"+proc+".root","RECREATE") tF.cd() tT = TTree("seeds","seeds") tT.Branch('svd0Seed',svd0Seed) tT.Branch('svd1Seed',svd1Seed) tT.Branch('svd2Seed',svd2Seed) tT.Branch('chi2xzSeed',chi2xzSeed) tT.Branch('chi2yzSeed',chi2yzSeed) tT.Branch('residxzSeed',residxzSeed) tT.Branch('residyzSeed',residyzSeed) tT.Branch('issigSeed',issigSeed) tT.Branch('iGenMatch',iGenMatch) tT.Branch('x1Seed',x1Seed) tT.Branch('y1Seed',y1Seed) tT.Branch('z1Seed',z1Seed) tT.Branch('x2Seed',x2Seed) tT.Branch('y2Seed',y2Seed) tT.Branch('z2Seed',z2Seed) tT.Branch('x3Seed',x3Seed) tT.Branch('y3Seed',y3Seed) tT.Branch('z3Seed',z3Seed) tT.Branch('x4Seed',x4Seed) tT.Branch('y4Seed',y4Seed) tT.Branch('z4Seed',z4Seed) tT.Branch('pxSeed',pxSeed) tT.Branch('pySeed',pySeed) tT.Branch('pzSeed',pzSeed) tT.Branch('eSeed',eSeed) tT.Branch('pxGen',pxGen) tT.Branch('pyGen',pyGen) tT.Branch('pzGen',pzGen) tT.Branch('eGen',eGen) tT.Branch('qGen',qGen) tT.Branch('iGen',iGen) histos = { "h_residuals_xz_sig": TH1D("residuals_xz_sig",";residuals_{xz};Tracks", 500,0,0.5), "h_residuals_yz_sig": TH1D("residuals_yz_sig",";residuals_{yz};Tracks", 500,0,500), "h_residuals_xz_bkg": TH1D("residuals_xz_bkg",";residuals_{xz};Tracks", 500,0,0.5), "h_residuals_yz_bkg": TH1D("residuals_yz_bkg",";residuals_{yz};Tracks", 500,0,500), "h_svd_dd0_sig": TH1D("svd_dd0_sig",";svd_{dd0};Tracks", 500,21,24), "h_svd_dd0_bkg": TH1D("svd_dd0_bkg",";svd_{dd0};Tracks", 500,21,24), "h_svd_dd1_sig": TH1D("svd_dd1_sig",";svd_{dd1};Tracks", 500,0,0.1), "h_svd_dd1_bkg": TH1D("svd_dd1_bkg",";svd_{dd1};Tracks", 500,0,0.1), "h_svd_dd2_sig": TH1D("svd_dd2_sig",";svd_{dd2};Tracks", 500,0,0.05), "h_svd_dd2_bkg": TH1D("svd_dd2_bkg",";svd_{dd2};Tracks", 500,0,0.05), "h_prob_xz_sig": TH1D("prob_xz_sig",";prob_{xz};Tracks", 500,0,1.0), "h_prob_yz_sig": TH1D("prob_yz_sig",";prob_{yz};Tracks", 500,0,1.0), "h_prob_xz_bkg": TH1D("prob_xz_bkg",";prob_{xz};Tracks", 500,0,1.0), "h_prob_yz_bkg": TH1D("prob_yz_bkg",";prob_{yz};Tracks", 500,0,1.0), "h_chi2ndf_xz_sig": TH1D("chi2ndf_xz_sig",";chi2ndf_{xz};Tracks", 500,0,0.001), "h_chi2ndf_yz_sig": TH1D("chi2ndf_yz_sig",";chi2ndf_{yz};Tracks", 500,0,0.001), "h_chi2ndf_xz_bkg": TH1D("chi2ndf_xz_bkg",";chi2ndf_{xz};Tracks", 500,0,0.001), "h_chi2ndf_yz_bkg": TH1D("chi2ndf_yz_bkg",";chi2ndf_{yz};Tracks", 500,0,0.001), "h_seed_resE" : TH1D("seed_resE", ";(E_{seed}-E_{gen})/E_{gen};Tracks", 100,-3,+3), "h_seed_resPz": TH1D("seed_resPz",";(Pz_{seed}-Pz_{gen})/Pz_{gen};Tracks", 100,-3,+3), "h_seed_resPy": TH1D("seed_resPy",";(Py_{seed}-Py_{gen})/Py_{gen};Tracks", 100,-10,+10), "h_seed_resE_vs_x" : TH2D("seed_resE_vs_x", ";x;(E_{seed}-E_{gen})/E_{gen};Tracks", 100,detXmin,detXmax, 100,-5,+5), "h_seed_resPy_vs_x" : TH2D("seed_resPy_vs_x", ";x;(Py_{seed}-Py_{gen})/Py_{gen};Tracks", 100,detXmin,detXmax, 100,-10,+10), "h_N_sigacc": TH1D("N_sigacc", ";Track multiplicity;Events", 40,30,190), "h_N_all_seeds": TH1D("N_all_seeds", ";Track multiplicity;Events", 40,30,190), "h_N_matched_seeds": TH1D("N_matched_seeds", ";Track multiplicity;Events", 40,30,190), "h_N_good_seeds": TH1D("N_good_seeds", ";Track multiplicity;Events", 40,30,190), "h_seeding_score": TH1D("h_seeding_score", ";N_{seeds}^{matched}/N_{signa}^{in.acc} [%];Events", 20,91,101), "h_seeding_pool": TH1D("h_seeding_pool", ";N_{seeds}^{all}/N_{signa}^{in.acc} [%];Events", 50,90,590), } sidesarr = getLogicSidesArr() pdfname = "../output/pdf/seedingdemo_"+proc+".pdf" intfile = TFile("../data/root/rec_"+proc+".root","READ") intree = intfile.Get("res") nevents = intree.GetEntries() print("with %d events" % nevents) nmax = 100000 n=0 ### init n for event in intree: Nsigall = 0 Nsigacc = 0 Nseeds = 0 Nmatched = 0 Ngood = 0 ## clear the output vectors svd0Seed.clear() svd1Seed.clear() svd2Seed.clear() chi2xzSeed.clear() chi2yzSeed.clear() residxzSeed.clear() residyzSeed.clear() issigSeed.clear() iGenMatch.clear() x1Seed.clear() y1Seed.clear() z1Seed.clear() x2Seed.clear() y2Seed.clear() z2Seed.clear() x3Seed.clear() y3Seed.clear() z3Seed.clear() x4Seed.clear() y4Seed.clear() z4Seed.clear() pxSeed.clear() pySeed.clear() pzSeed.clear() eSeed.clear() pxGen.clear() pyGen.clear() pzGen.clear() eGen.clear() qGen.clear() iGen.clear() ### start the loop if(n>nmax): break ### draw? dodraw = (n<=NeventsToDraw) ### container for all clusters allpointsEside = initpoints() allpointsPside = initpoints() ## clusters' vectors are always written out (even if empty) for all gen tracks! ## each generated track in the vector always has 4 clusters accessed via TPolyMarker3D::GetPoint() for i in range(event.polm_clusters.size()): ############################################################### if(proc=="bppp"): if(sides=="e+" and event.qgen[i]<0): continue ## only positrons if(sides=="e-" and event.qgen[i]>0): continue ## only electrons if(proc=="trident" and event.qgen[i]<0): continue ## only positrons ############################################################### Nsigall += 1 wgt = event.wgtgen[i] pgen = event.pgen[i] ### cut on acceptance if(event.acctrkgen[i]!=1): continue Nsigacc += 1 ### write the truth track momentum and its index pxGen.push_back(pgen.Px()) pyGen.push_back(pgen.Py()) pzGen.push_back(pgen.Pz()) eGen.push_back(pgen.E()) qGen.push_back(event.qgen[i]) iGen.push_back(i) ### loop over all clusters of the track and put in the allpoints classified by the layer for jxy in range(event.polm_clusters[i].GetN()): rcls = [ ROOT.Double(), ROOT.Double(), ROOT.Double() ] event.polm_clusters[i].GetPoint(jxy,rcls[0],rcls[1],rcls[2]) ### the clusters if(rcls[0]>0): AddPoint(allpointsEside,rcls,True,i) if(rcls[0]<0): AddPoint(allpointsPside,rcls,True,i) Nsig4 = getNnon0(allpointsEside["Cls"][4])+getNnon0(allpointsPside["Cls"][4]) ### embed some noise clusters rnd = TRandom() rnd.SetSeed() for kN in range(NnoiseClusters): for layer in layers: for side in sidesarr: x = 0 if(side=="Pside"): x = rnd.Uniform(xPsideL,xPsideR) if(side=="Eside"): x = rnd.Uniform(xEsideL,xEsideR) y = rnd.Uniform(-0.75,+0.75) if(layer==1): z = 300 if(layer==2): z = 310 if(layer==3): z = 320 if(layer==4): z = 330 rnoise = [x,y,z] if(side=="Pside"): AddPoint(allpointsPside,rnoise) if(side=="Eside"): AddPoint(allpointsEside,rnoise) Nbkgsig4 = getNnon0(allpointsEside["Cls"][4])+getNnon0(allpointsPside["Cls"][4]) ### just draw the full event drawall(pdfname+"(",allpointsEside,allpointsPside,dodraw) ### loop on the 2 sides for side in sidesarr: allpoints = allpointsEside if(side=="Eside") else allpointsPside ### the initial pool for pivot clusters Nall4 = getNnon0(allpoints["Cls"][4]) ### loop over the clusters and start the seeding for j4 in range(Nall4): r4 = getpoint(allpoints["Cls"][4],j4) xpivot = r4[0] ### electron / positron? particlename = getparticlename(allpoints["Cls"][4],j4) ### get the yz window winpts_yz,winlin_yz = getyzwindow(allpoints["Cls"][4],j4) ### set the wide window starting from cluster_seed1 (window corners must be added clockwise!) winpts_xz_wide,winlin_xz_wide = getwidewindow(allpoints["Cls"][4],j4) ### discard all clusters which are not in the wide window widepoints = initpoints() trimwide(allpoints,widepoints,winpts_xz_wide,winpts_yz,xpivot) Nwide1 = getNnon0(widepoints["Cls"][1]) # if(Nwide1<1): print("Failed Nwide1") ### draw the wide window draw(pdfname,widepoints,dodraw,particlename,winlin_yz,winlin_xz_wide) ### choose one cluster in layer 1 as the second seed for j1 in range(Nwide1): ### get the narrow window (window corners must be added clockwise!) winpts_xz_narr,winlin_xz_narr = getnarrwindow(allpoints["Cls"][4],widepoints["Cls"][1],j4,j1) ### discard all clusters which are not in the narrow window narrpoints = initpoints() trimnarr(widepoints,narrpoints,winpts_xz_narr) Nnarr2 = getNnon0(narrpoints["Cls"][2]) Nnarr3 = getNnon0(narrpoints["Cls"][3]) ### check if there are at least 1 cluster in both layer 2 and layer 3 within the narrow window if(Nnarr2<1 or Nnarr3<1): continue ### draw the narrow window draw(pdfname,narrpoints,dodraw,particlename,None,winlin_xz_narr) ### get the seed - note: could be that there are several combinations but the seed momentum would be identical pseed = makeseed(allpoints["Cls"][4],widepoints["Cls"][1],j4,j1,particlename) # if(pseed.E()>Emax or pseed.E()<Emin): print("pseed.E()>Emax or pseed.E()<Emin") if(pseed.E()>Emax or pseed.E()<Emin): continue ### set the cluster in layer 1 r1 = getpoint(widepoints["Cls"][1],j1) ### loop on the clusters in layer 2 and 3: for j2 in range(Nnarr2): # for j2 in range(narrpoints["Cls"][2].GetN()): r2 = getpoint(narrpoints["Cls"][2],j2) for j3 in range(Nnarr3): # for j3 in range(narrpoints["Cls"][3].GetN()): r3 = getpoint(narrpoints["Cls"][3],j3) Nseeds += 1 issig1 = widepoints["IsSig"][1][j1] issig2 = narrpoints["IsSig"][2][j2] issig3 = narrpoints["IsSig"][3][j3] issig4 = allpoints["IsSig"][4][j4] trkid4 = allpoints["TrkId"][4][j4] trkid3 = narrpoints["TrkId"][3][j3] trkid2 = narrpoints["TrkId"][2][j2] trkid1 = widepoints["TrkId"][1][j1] issig = (issig4 and issig1 and issig2 and issig3) trkid = str(trkid4) if(trkid4==trkid1 and trkid1==trkid2 and trkid2==trkid3) else "mult" issiguniq = (issig and trkid!="mult") if(issiguniq): Nmatched += 1 ### two independent 2d fits chi2_xz,prob_xz,chi2_yz,prob_yz = seed2dfit(pdfname,r1,r2,r3,r4,dodraw) if(issiguniq): histos["h_chi2ndf_xz_sig"].Fill(chi2_xz) histos["h_chi2ndf_yz_sig"].Fill(chi2_yz) histos["h_prob_xz_sig"].Fill(prob_xz) histos["h_prob_yz_sig"].Fill(prob_yz) else: histos["h_chi2ndf_xz_bkg"].Fill(chi2_xz) histos["h_chi2ndf_yz_bkg"].Fill(chi2_yz) histos["h_prob_xz_bkg"].Fill(prob_xz) histos["h_prob_yz_bkg"].Fill(prob_yz) ### a single 3d fit res_xz, res_yz = seed3dfit(pdfname,r1,r2,r3,r4,dodraw) if(issiguniq): histos["h_residuals_xz_sig"].Fill(res_xz) histos["h_residuals_yz_sig"].Fill(res_yz) else: histos["h_residuals_xz_bkg"].Fill(res_xz) histos["h_residuals_yz_bkg"].Fill(res_yz) ### a single 3d fit SVD lfitpts, dd = seed3dfitSVD(pdfname,r1,r2,r3,r4,dodraw) ### set again the pseed according to lfit cluster1 = TPolyMarker3D() cluster2 = TPolyMarker3D() cluster1.SetNextPoint(lfitpts[0][0],lfitpts[0][1],lfitpts[0][2]) cluster2.SetNextPoint(lfitpts[1][0],lfitpts[1][1],lfitpts[1][2]) if(isel(lfitpts[0][0])): pseed = makeseed(cluster2,cluster1,0,0,particlename) else: pseed = makeseed(cluster1,cluster2,0,0,particlename) if(pseed.E()>Emax or pseed.E()<Emin): continue ### the SVD alg if(issiguniq): histos["h_svd_dd0_sig"].Fill(dd[0]) histos["h_svd_dd1_sig"].Fill(dd[1]) histos["h_svd_dd2_sig"].Fill(dd[2]) else: histos["h_svd_dd0_bkg"].Fill(dd[0]) histos["h_svd_dd1_bkg"].Fill(dd[1]) histos["h_svd_dd2_bkg"].Fill(dd[2]) ### get the generated matched track momentum pgen = TLorentzVector() igen = -1 for k in range(iGen.size()): if(iGen[k]==j4): igen = k break ### write out the good seeds svd0Seed.push_back(dd[0]) svd1Seed.push_back(dd[1]) svd2Seed.push_back(dd[2]) chi2xzSeed.push_back(chi2_xz) chi2yzSeed.push_back(chi2_yz) residxzSeed.push_back(res_xz) residyzSeed.push_back(res_yz) issigSeed.push_back(issiguniq) iGenMatch.push_back(igen) x1Seed.push_back(r1[0]) y1Seed.push_back(r1[1]) z1Seed.push_back(r1[2]) x2Seed.push_back(r2[0]) y2Seed.push_back(r2[1]) z2Seed.push_back(r2[2]) x3Seed.push_back(r3[0]) y3Seed.push_back(r3[1]) z3Seed.push_back(r3[2]) x4Seed.push_back(r4[0]) y4Seed.push_back(r4[1]) z4Seed.push_back(r4[2]) pxSeed.push_back(pseed.Px()) pySeed.push_back(pseed.Py()) pzSeed.push_back(pseed.Pz()) eSeed.push_back(pseed.E()) ### cut on some quality isgood = (dd[1]<0.005 and dd[2]<0.0025) if(not isgood): continue Ngood += 1 ### check perforrmance of seeding pgen.SetPxPyPzE(pxGen[igen],pyGen[igen],pzGen[igen],eGen[igen]) resE = (pseed.E()-pgen.E())/pgen.E() resPz = (pseed.Pz()-pgen.Pz())/pgen.Pz() resPy = (pseed.Py()-pgen.Py())/pgen.Py() histos["h_seed_resE"].Fill(resE) histos["h_seed_resPz"].Fill(resPz) histos["h_seed_resPy"].Fill(resPy) histos["h_seed_resE_vs_x"].Fill(r4[0],resE) histos["h_seed_resPy_vs_x"].Fill(r4[0],resPy) histos["h_N_sigacc"].Fill(Nsigacc) histos["h_N_all_seeds"].Fill(Nseeds) histos["h_N_matched_seeds"].Fill(Nmatched) histos["h_N_good_seeds"].Fill(Ngood) histos["h_seeding_score"].Fill(Nmatched/Nsigacc*100) histos["h_seeding_pool"].Fill(Nseeds/Nsigacc*100) if(dodraw): cnv = TCanvas("","",2000,2000) cnv.SaveAs(pdfname+")") print("Event: %g --> Nsigall=%g, Nsigacc=%g, Nseeds=%g, Nmatched=%g, Ngood=%g --> Seeds matching performance: Nmatched/Nsigacc=%5.1f%%" % (n,Nsigall,Nsigacc,Nseeds,Nmatched,Ngood,Nmatched/Nsigacc*100)) tT.Fill() if(n%10==0 and n>0): print(" processed %d events" % n) n+=1 print("Total events processed: ",n) cnv = TCanvas("","",1000,1000) cnv.Divide(2,2) cnv.cd(1) histos["h_chi2ndf_xz_sig"].SetLineColor(ROOT.kRed); histos["h_chi2ndf_xz_sig"].Draw() histos["h_chi2ndf_xz_bkg"].SetLineColor(ROOT.kBlack); histos["h_chi2ndf_xz_bkg"].Draw("same") cnv.cd(2) histos["h_chi2ndf_yz_sig"].SetLineColor(ROOT.kRed); histos["h_chi2ndf_yz_sig"].Draw() histos["h_chi2ndf_yz_bkg"].SetLineColor(ROOT.kBlack); histos["h_chi2ndf_yz_bkg"].Draw("same") cnv.cd(3) histos["h_prob_xz_sig"].SetLineColor(ROOT.kRed); histos["h_prob_xz_sig"].Draw() histos["h_prob_xz_bkg"].SetLineColor(ROOT.kBlack); histos["h_prob_xz_bkg"].Draw("same") cnv.cd(4) histos["h_prob_yz_sig"].SetLineColor(ROOT.kRed); histos["h_prob_yz_sig"].Draw() histos["h_prob_yz_bkg"].SetLineColor(ROOT.kBlack); histos["h_prob_yz_bkg"].Draw("same") cnv.SaveAs("../output/pdf/chi2ndf_"+proc+".pdf") cnv = TCanvas("","",1000,500) cnv.Divide(2,1) cnv.cd(1) histos["h_residuals_xz_sig"].SetLineColor(ROOT.kRed); histos["h_residuals_xz_sig"].Draw() histos["h_residuals_xz_bkg"].SetLineColor(ROOT.kBlack); histos["h_residuals_xz_bkg"].Draw("same") cnv.cd(2) histos["h_residuals_yz_sig"].SetLineColor(ROOT.kRed); histos["h_residuals_yz_sig"].Draw() histos["h_residuals_yz_bkg"].SetLineColor(ROOT.kBlack); histos["h_residuals_yz_bkg"].Draw("same") cnv.SaveAs("../output/pdf/resid3dfit_"+proc+".pdf") cnv = TCanvas("","",1500,500) cnv.Divide(3,1) cnv.cd(1) histos["h_svd_dd0_sig"].SetLineColor(ROOT.kRed); histos["h_svd_dd0_sig"].Draw() histos["h_svd_dd0_bkg"].SetLineColor(ROOT.kBlack); histos["h_svd_dd0_bkg"].Draw("same") cnv.cd(2) histos["h_svd_dd1_sig"].SetLineColor(ROOT.kRed); histos["h_svd_dd1_sig"].Draw() histos["h_svd_dd1_bkg"].SetLineColor(ROOT.kBlack); histos["h_svd_dd1_bkg"].Draw("same") cnv.cd(3) histos["h_svd_dd2_sig"].SetLineColor(ROOT.kRed); histos["h_svd_dd2_sig"].Draw() histos["h_svd_dd2_bkg"].SetLineColor(ROOT.kBlack); histos["h_svd_dd2_bkg"].Draw("same") cnv.SaveAs("../output/pdf/svd3dfit_"+proc+".pdf") cnv = TCanvas("","",1000,1000) cnv.Divide(2,2) cnv.cd(1); histos["h_seed_resE"].Draw("hist") cnv.cd(2); histos["h_seed_resPy"].Draw("hist") cnv.cd(3); histos["h_seed_resE_vs_x"].Draw("col") cnv.cd(4); histos["h_seed_resPy_vs_x"].Draw("col") cnv.SaveAs("../output/pdf/seedsres_"+proc+".pdf") cnv = TCanvas("","",1500,500) cnv.Divide(3,1) cnv.cd(1) histos["h_N_sigacc"].SetLineColor(ROOT.kBlack); histos["h_N_sigacc"].Draw() histos["h_N_all_seeds"].SetLineColor(ROOT.kBlue); histos["h_N_all_seeds"].Draw("same") histos["h_N_matched_seeds"].SetLineColor(ROOT.kGreen); histos["h_N_matched_seeds"].Draw("same") histos["h_N_good_seeds"].SetLineColor(ROOT.kRed); histos["h_N_good_seeds"].Draw("same") cnv.cd(2) histos["h_seeding_pool"].Draw("hist") cnv.cd(3) histos["h_seeding_score"].Draw("hist") cnv.SaveAs("../output/pdf/seedsmult_"+proc+".pdf") tF.cd() tT.Write() tF.Write() tF.Close() if __name__=="__main__": main()
def run_example(save=True): ########################################## # first define some objects to play with # ########################################## random = TRandom(getpid()) # Create a histogram to play with bin_edges = array("d", [2, 3, 5, 7, 11, 13, 17, 19]) hist_1 = TH1F("some_histogram_1", "", len(bin_edges) - 1, bin_edges) hist_2 = TH1F("some_histogram_2", "", len(bin_edges) - 1, bin_edges) # Fill histogram from a random number generation for i in range(len(bin_edges) + 1): hist_1.SetBinContent(i + 1, random.Poisson(42)) hist_1.SetBinError(i + 1, random.Gaus(10)) hist_2.SetBinContent(i + 1, random.Poisson(42)) hist_2.SetBinError(i + 1, random.Gaus(10)) # Ratio, make use of function to clone a ROOT object which will immediately # acquire a new name so no problems with overlapping names and ROOT complaining h_ratio = clone_root(hist_1) h_ratio.Divide(hist_2) ################################### # The actual plotting starts here # ################################### # Generate 2 styles with constant markerstyle styles = generate_styles(StyleObject1D, 2, markerstyles=34, markersizes=2) # Create a figure with one cell (1 column and one row) figure = ROOTFigure(1, 2, size=(400, 600), row_margin=[(0.1, 0), (0, 0.1)], column_margin=0.1, height_ratios=[1, 2]) # since counting starts in the bottom left corner and we use the automatic generation of plot # the first one will be the ratio ratio_plot = figure.define_plot() # add the ratio figure.add_object(h_ratio, style=styles[0]) # set axis ratio_plot.axes("x", title="x_axis", title_offset=3) ratio_plot.axes("y", title="Hist1 / Hist2", title_offset=1.8) # share the x-axis with the ratio plot main_plot = figure.define_plot(share_x=ratio_plot) # add nominal histograms figure.add_object(hist_1, style=styles[0], label="Hist1") figure.add_object(hist_2, style=styles[1], label="Hist2") # set y-axis main_plot.axes("y", title="Entries") # create and save figure.create() if save: figure.save("example_ratio_plot.eps") return True
def seed(s): global rootrandom rootrandom = TRandom(s)