def energylinearity(): outputfile = "EMLinearityEnergyRes" displayfile = TFile(outputfile + ".root", "RECREATE") MeanEnergyScin = array('d') MeanEnergyCher = array('d') MeanEnergy = array('d') resolutionscin = array('d') resolutioncher = array('d') resolution = array('d') towers = array('d') ##inputfiles = sorted(glob.glob(datapath+"*"), key=os.path.getmtime) #get files from tower 1 to 75 ordered by creation time inputfiles = [ "/home/software/Calo/results/newresults/barrel2/Barrel_" + str(i) + ".root" for i in range(1, 76) ] #inputfiles = ["/home/software/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)] #inputfiles = ["/home/lorenzo/Desktop/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)] for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: " + str(inputfile) + " \n" tree = TTree() inputfile.GetObject("B4", tree) ScinEnergyHist = TH1F("scinenergy_", str(counter + 1) + "_scin", 200, 0., 100.) CherEnergyHist = TH1F("cherenergy_", str(counter + 1) + "_cher", 200, 0., 100.) RecEnergyHist = TH1F("RecEnergy_", str(counter + 1) + "_Energy", 200, 0., 100.) Energytot = 0.0 energy = 40.0 sqrtenergy = 1 / (40.0**0.5) towers.append(counter + 1.) #loop over events for Event in range(int(tree.GetEntries())): tree.GetEntry(Event) #Set values of the tree PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name PrimaryParticleEnergy = tree.PrimaryParticleEnergy EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter Energyem = tree.Energyem # Energy deposited by the em component EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected) EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected) NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected BarrelR_VectorSignals = tree.VectorSignalsR # Vector of energy deposited in Scin fibers (Birk corrected) BarrelL_VectorSignals = tree.VectorSignalsL # Vector of energy deposited in Scin fibers (Birk corrected) BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers BarrelL_VectorSignalsCher = tree.VectorSignalsCherL VectorR = tree.VectorR VectorL = tree.VectorL #apply calibrations Calib_BarrelL_VectorSignals = calibration2.calibscin( BarrelL_VectorSignals) Calib_BarrelR_VectorSignals = calibration2.calibscin( BarrelR_VectorSignals) Calib_BarrelL_VectorSignalsCher = calibration2.calibcher( BarrelL_VectorSignalsCher) Calib_BarrelR_VectorSignalsCher = calibration2.calibcher( BarrelR_VectorSignalsCher) #end of calibrations energyscin = sum(Calib_BarrelR_VectorSignals) + sum( Calib_BarrelL_VectorSignals) energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum( Calib_BarrelL_VectorSignalsCher) ScinEnergyHist.Fill(energyscin) CherEnergyHist.Fill(energycher) #sigmascin = 0.15*(energyscin**0.5)+0.012*energyscin #old value #sigmacher = 0.18*(energycher**0.5)+0.0045*energycher #old value sigmascin = 0.177 * (energyscin**0.5) + 0.006 * energyscin sigmacher = 0.194 * (energycher**0.5) + 0.001 * energycher RecEnergyHist.Fill( (energyscin / (sigmascin**2) + energycher / (sigmacher**2)) / (1 / sigmascin**2 + 1 / sigmacher**2)) #RecEnergyHist.Fill((energyscin+energycher)/2) Energytot += (sum(VectorL) + sum(VectorR)) / 1000 Energytot = Energytot / int(tree.GetEntries()) print Energytot, ScinEnergyHist.GetMean(), CherEnergyHist.GetMean() displayfile.cd() gStyle.SetOptStat(111) ScinEnergyHist.Fit("gaus") CherEnergyHist.Fit("gaus") RecEnergyHist.Fit("gaus") RecEnergyHist.Write() ScinEnergyHist.Write() CherEnergyHist.Write() #MeanEnergyScin.append(ScinEnergyHist.GetFunction("gaus").GetParameter(1)/Energytot) MeanEnergyScin.append(ScinEnergyHist.GetMean() / energy) #MeanEnergyCher.append(CherEnergyHist.GetFunction("gaus").GetParameter(1)/Energytot) MeanEnergyCher.append(CherEnergyHist.GetMean() / energy) MeanEnergy.append( RecEnergyHist.GetFunction("gaus").GetParameter(1) / energy) resolution.append( RecEnergyHist.GetFunction("gaus").GetParameter(2) / RecEnergyHist.GetFunction("gaus").GetParameter(1)) resolutionscin.append( ScinEnergyHist.GetFunction("gaus").GetParameter(2) / ScinEnergyHist.GetFunction("gaus").GetParameter(1)) resolutioncher.append( CherEnergyHist.GetFunction("gaus").GetParameter(2) / CherEnergyHist.GetFunction("gaus").GetParameter(1)) print MeanEnergyScin, MeanEnergyCher LinearityGraph = TGraph(len(towers), towers, MeanEnergy) LinearityGraph.SetName("LinearityGraph") LinearityGraph.Write() LinearityGraphScin = TGraph(len(towers), towers, MeanEnergyScin) LinearityGraphCher = TGraph(len(towers), towers, MeanEnergyCher) LinearityGraphCher.SetName("LinearityGraphCher") LinearityGraphCher.Write() LinearityGraphScin.SetName("LinearityGraphScin") LinearityGraphScin.Write() ResolutionGraphScin = TGraph(len(towers), towers, resolutionscin) ResolutionGraphCher = TGraph(len(towers), towers, resolutioncher) ResolutionGraphScin.SetName("ResolutionGraphScin") ResolutionGraphScin.Write() ResolutionGraphCher.SetName("ResolutionGraphCher") ResolutionGraphCher.Write() ResolutionGraph = TGraph(len(towers), towers, resolution) ResolutionGraph.SetName("ResolutionGraph") ResolutionGraph.Write() x2 = array('d', (0., 90., 90., 0.)) y2 = array('d', (0.024, 0.024, 0.034, 0.034)) Fillgraph2 = TGraph(4, x2, y2) Fillgraph2.SetName("ban") Fillgraph2.Write() linefill1 = TF1("1", str(1.0), 0., 90.) linefill1.Write() EMResolutions = TMultiGraph() EMResolutions.Add(ResolutionGraphScin) EMResolutions.Add(ResolutionGraphCher) EMResolutions.Add(ResolutionGraph) EMResolutions.SetName("EMResolutions") EMResolutions.Write() Linearities = TMultiGraph() Linearities.Add(LinearityGraph) Linearities.Add(LinearityGraphScin) Linearities.Add(LinearityGraphCher) Linearities.SetName("Linearities") Linearities.Write()
def jetdisplay(): outputfile = "zjj" displayfile = TFile(outputfile+".root","RECREATE") energies = [30,50,70,90, 150, 250] inputfiles = ["jetscan_leakage_029/jetscan_"+str(e)+".root" for e in energies] #for geant4.10.5 inputfiles = ["resultsgeant4.10.5/jetscan/jetscan"+str(e)+".root" for e in energies] #end of geant4.10.5 #for geant4.10.5 with X0 or B inputfiles = ["resultsgeant4.10.5/jetscan_leakage_X0/jetscan/jetscan"+str(e)+".root" for e in energies] #end of geant4.10.5 with X0 or B #for CaloLoop #inputfiles = ["/home/software/Calo/CaloLoop/CaloJet/resultsgeant4.10.5/jetscan_leakage_B/jetscan/jetscan"+str(e)+".root" for e in energies] #end CaloLoop for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: "+str(inputfile)+" \n" tree = TTree() inputfile.GetObject("MyTree", tree) #graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.) #graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.) #graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.) #graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.) #graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.) graphtest = TH1F("test"+str(energies[counter]), "test"+str(energies[counter]), 80, -40., 40.) graphenergy = TH1F("energy"+str(energies[counter]), "energy"+str(energies[counter]), 200, 0., 300.) graphenergytruth = TH1F("energytruth"+str(energies[counter]), "energytruth"+str(energies[counter]), 200, 0., 300.) graphjs = TH1F("energyjs"+str(energies[counter]), "energyjs"+str(energies[counter]), 200, 0., 300.) graphjc = TH1F("energyjc"+str(energies[counter]), "energyjc"+str(energies[counter]), 200, 0., 300.) graph_emcomp02 = TH1F("emcomp02_"+str(energies[counter]), "emcomp02"+str(energies[counter]), 80, -40, 40) graph_emcomp04 = TH1F("emcomp04_"+str(energies[counter]), "emcomp04"+str(energies[counter]), 80, -40, 40) graph_emcomp06 = TH1F("emcomp06_"+str(energies[counter]), "emcomp06"+str(energies[counter]), 80, -40, 40) graph_emcomp08 = TH1F("emcomp08_"+str(energies[counter]), "emcomp08"+str(energies[counter]), 80, -40, 40) graph_emcomp1 = TH1F("emcomp1_"+str(energies[counter]), "emcomp1"+str(energies[counter]), 80, -40, 40) #loop over events for Event in range(tree.GetEntries()): tree.GetEntry(Event) #print "Event "+str(Event) nmuon = tree.nmuon nneu = tree.nneu mjjr = tree.mjjr mjjt = tree.mjjt edep = tree.edep muene_che = tree.muene_che muene_sci = tree.muene_sci emcomp1 = tree.emcomp1 emcomp2 = tree.emcomp2 eleak = tree.eleak eleakn = tree.eleakn j1t_E = tree.j1t_E j1t_m = tree.j1t_m j1t_theta = tree.j1t_theta j1t_pt = tree.j1t_pt j1t_eta = tree.j1t_eta j1t_phi = tree.j1t_phi j2t_E = tree.j2t_E j2t_m = tree.j2t_m j2t_theta = tree.j2t_theta j2t_pt = tree.j2t_pt j2t_eta = tree.j2t_eta j2t_phi = tree.j2t_phi j1r_E = tree.j1r_E j1r_m = tree.j1r_m j1r_theta = tree.j1r_theta j1r_pt = tree.j1r_pt j1r_eta = tree.j1r_eta j1r_phi = tree.j1r_phi j2r_E = tree.j2r_E j2r_m = tree.j2r_m j2r_theta = tree.j2r_theta j2r_pt = tree.j2r_pt j2r_eta = tree.j2r_eta j2r_phi = tree.j2r_phi j1s_E = tree.j1s_E j1s_m = tree.j1s_m j1s_theta = tree.j1s_theta j1s_pt = tree.j1s_pt j1s_eta = tree.j1s_eta j1s_phi = tree.j1s_phi j2s_E = tree.j2s_E j2s_m = tree.j2s_m j2s_theta = tree.j2s_theta j2s_pt = tree.j2s_pt j2s_eta = tree.j2s_eta j2s_phi = tree.j2s_phi j1c_E = tree.j1c_E j1c_m = tree.j1c_m j1c_theta = tree.j1c_theta j1c_pt = tree.j1c_pt j1c_eta = tree.j1c_eta j1c_phi = tree.j1c_phi j2c_E = tree.j2c_E j2c_m = tree.j2c_m j2c_theta = tree.j2c_theta j2c_pt = tree.j2c_pt j2c_eta = tree.j2c_eta j2c_phi = tree.j2c_phi cut1 = nmuon==0 and nneu==0 cut2 = abs(j1t_eta)<2.0 and abs(j2t_eta)<2.0 cut3 = eleak<3000. cut3 = True cut4 = j1t_E+j2t_E>0.999*energies[counter] cut4= True cut5 = abs(j1t_E-j2t_E)<5. cut5 = abs(j1t_phi-j2t_phi)>0.1 if cut1 and cut2 and cut3 and cut4 and cut5: deltaj1 = 0.04406*j1r_E+0.1158 deltaj2 = 0.04406*j2r_E+0.1158 deltaj1 = 0.03401*j1r_E+0.9152 deltaj2 = 0.03401*j2r_E+0.9152 deltaj1 = 0.04911*j1r_E+0.5723 deltaj2 = 0.04911*j2r_E+0.5723 graphtest.Fill(j1r_E+deltaj1-j1t_E) graphtest.Fill(j2r_E+deltaj2-j2t_E) #deltaj1_2 = 0.0098*(j1r_E+deltaj1)+0.186 #deltaj2_2 = 0.0098*(j2r_E*deltaj2)+0.186 ''' if (emcomp1+emcomp2)<0.2*90.: graph_emcomp02.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp02.Fill(j2r_E+deltaj2-j2t_E) if 0.2*90.<emcomp1+emcomp2<0.4*90.: graph_emcomp04.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp04.Fill(j2r_E+deltaj2-j2t_E) if 0.4*90.<emcomp1+emcomp2<0.6*90.: graph_emcomp06.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp06.Fill(j2r_E+deltaj2-j2t_E) if 0.6*90.<emcomp1+emcomp2<0.8*90.: graph_emcomp08.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp08.Fill(j2r_E+deltaj2-j2t_E) if 0.8*90.<emcomp1+emcomp2<90.: graph_emcomp1.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp1.Fill(j2r_E+deltaj2-j2t_E) ''' graphenergy.Fill(j1r_E+deltaj1) graphenergy.Fill(j2r_E+deltaj2) graphenergytruth.Fill(j1t_E) graphenergytruth.Fill(j2t_E) graphjs.Fill(j2s_E) graphjs.Fill(j1s_E) graphjc.Fill(j2c_E) graphjc.Fill(j1c_E) displayfile.cd() graphtest.Write() graphenergy.Write() graphenergytruth.Write() graphjs.Write() graphjc.Write()
def recenergy(particle, name, chivalue): outputfile = str(particle) + "_Femanalysis" + str(chivalue) + "_" + str( name) displayfile = TFile(outputfile + ".root", "RECREATE") ''' if name == "FTFPBERT": chi = 0.3 if name == "FTFPBERTTRV": chi = 0.3 if name == "QGSPBERT": chi = 0.3 if name == "QBBC": chi = 0.3 ''' MeanEnergyScin = array('d') MeanEnergyCher = array('d') Energy = array('d') Energyerror = array('d') energyfractionscin = array('d') energyfractionscinerror = array('d') energyfractioncher = array('d') energyfractionchererror = array('d') energyfraction = array('d') energyfractionerror = array('d') resolutionscin = array('d') resolutionscinerror = array('d') resolutioncher = array('d') resolutionchererror = array('d') resolution = array('d') resolutionerror = array('d') chiarray = array('d') chierrorarray = array('d') zeros = array('d') containment = array('d') containmenterror = array('d') femvalues = array('d') zvalues = array('d') femvalueserror = array('d') zvalueserror = array('d') znormvalues = array('d') znormvalueserror = array('d') t = [10, 30, 50, 70, 100, 120, 140, 150] sqrtenergies = array('d', [1 / (x**0.5) for x in t]) energies = array('d', t) #inputfiles = ["/home/software/Calo/results/energycont_2p0m/Pion_"+str(i)+".root" for i in t] #inputfiles = ["/home/software/Calo/results/pionenergyscan_QGSPBICHP/Pion_"+str(i)+".root" for i in t] #inputfiles = ["/home/lorenzo/Desktop/Calo/newresults/FTFPBERTTRV/Pion_"+str(i)+"_FTFPBERTTRV_office.root" for i in t] #inputfiles = ["/Users/lorenzo/Desktop/ToPC/newresults/"+str(name)+"/Pion_"+str(i)+".root" for i in t] if particle == "pion": inputfiles = [ "/home/lorenzo/Calo/results/Pion_25_3_2020/" + str(name) + "" + "/Pion_" + str(i) + ".root" for i in t ] #inputfiles = ["/home/lorenzo/Calo/results/geant4.10.4.p01/Pion_30_4_2020/"+str(name)+""+"/Pion_"+str(i)+".root" for i in t] if particle == "proton": inputfiles = [ "/home/lorenzo/Calo/results/Proton_25_3_2020/" + str(name) + "" + "/Proton_" + str(i) + ".root" for i in t ] if particle == "neutron": inputfiles = [ "/home/lorenzo/Calo/results/Neutron_25_3_2020/" + str(name) + "" + "/Neutron_" + str(i) + ".root" for i in t ] if particle == "kaon": inputfiles = [ "/home/lorenzo/Calo/results/Kaon_5_4_2020/" + str(name) + "" + "/Kaon_" + str(i) + ".root" for i in t ] for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: " + str(inputfile) + " \n" tree = TTree() inputfile.GetObject("B4", tree) ScinEnergyHist = TH1F("scinenergy_" + str(t[counter]), str(t[counter]) + "_scin", 400, 0., 200.) CherEnergyHist = TH1F("cherenergy_" + str(t[counter]), str(t[counter]) + "_cher", 400, 0., 200.) RecEnergyHist = TH1F("RecEnergy_" + str(t[counter]), str(t[counter]) + "_Energy", 400, 0., 200.) #Signalscinhist = TH1F("scintot_", str(counter+1)+"_scin", 3000, 0., 30000) EnergyHist = TH1F("Energy_" + str(t[counter]), str(t[counter]) + "_Energy", 400, 0., 200.) LeakageHist = TH1F("Leak_" + str(t[counter]), str(t[counter]) + "_Leak", 1000, 0., 100.) NeutrinoLeakageHist = TH1F("NeutrinoNeutrinoLeak_" + str(t[counter]), str(t[counter]) + "_Leak", 1000, 0., 100.) TotalLeakageHist = TH1F("TotalLeak_" + str(t[counter]), str(t[counter]) + "_Leak", 1000, 0., 100.) ChiHist = TH1F("Chi_" + str(t[counter]), str(t[counter]) + "_Chi", 200, 0., 2.) scatterplot = TH2F("scatterplot_" + str(t[counter]), str(t[counter]), int(400), 0., 200., int(400), 0., 200.) EnergyContHist = TH1F("EnergyCont_" + str(t[counter]), str(t[counter]) + "_EnergyCont", 400, 0., 200.) hesscatterplot = TH2F("H/E_S" + str(t[counter]), "H/E_S" + str(t[counter]), 200, 0., 1.1, 200, 0., 1.1) hecscatterplot = TH2F("H/E_C" + str(t[counter]), "H/E_C" + str(t[counter]), 200, 0., 1.1, 200, 0., 1.1) #fem and z histo femhisto = TH1F("fem_" + str(t[counter]), str(t[counter]) + "_fem", 100, 0., 1.) zhisto = TH1F("z" + str(t[counter]), str(t[counter]) + "_z", 100, 0., 1.) znormhisto = TH1F("z_norm" + str(t[counter]), str(t[counter]) + "_z_norm", 200, 0., 2.) zfemhisto = TH2F("z_fem_histo" + str(t[counter]), str(t[counter]) + "_z_fem_histo", 200, 0., 2., 200, 0., 2.) #loop over events entries = 50000 for Event in range(entries): tree.GetEntry(Event) if Event % 1000 == 0: print Event #Set values of the tree PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name PrimaryParticleEnergy = tree.PrimaryParticleEnergy EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter Energyem = tree.Energyem # Energy deposited by the em component EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected) EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected) NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected BarrelR_VectorSignals = tree.VectorSignalsR # Vector of energy deposited in Scin fibers (Birk corrected) BarrelL_VectorSignals = tree.VectorSignalsL # Vector of energy deposited in Scin fibers (Birk corrected) BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers BarrelL_VectorSignalsCher = tree.VectorSignalsCherL VectorR = tree.VectorR VectorL = tree.VectorL Leak = tree.leakage NeutrinoLeak = tree.neutrinoleakage #totalsignalscin = sum(BarrelR_VectorSignals)+sum(BarrelL_VectorSignals) #Signalscinhist.Fill(totalsignalscin) energytot = (sum(VectorR) + sum(VectorL)) / 1000 EnergyHist.Fill(energytot) LeakageHist.Fill(Leak / 1000.) NeutrinoLeakageHist.Fill(NeutrinoLeak / 1000.) TotalLeakageHist.Fill(Leak / 1000. + NeutrinoLeak / 1000.) if float(t[counter]) < 12.: cutleak = 0.5 if float(t[counter]) > 12. and float(t[counter]) < 50.: cutleak = 1.0 if float(t[counter]) > 50.: cutleak = 3.0 if (Leak / 1000. + NeutrinoLeak / 1000.) < cutleak: #apply calibrations Calib_BarrelL_VectorSignals = calibration.calibscin( BarrelL_VectorSignals) Calib_BarrelR_VectorSignals = calibration.calibscin( BarrelR_VectorSignals) Calib_BarrelL_VectorSignalsCher = calibration.calibcher( BarrelL_VectorSignalsCher) Calib_BarrelR_VectorSignalsCher = calibration.calibcher( BarrelR_VectorSignalsCher) #end of calibrations energyscin = sum(Calib_BarrelR_VectorSignals) + sum( Calib_BarrelL_VectorSignals) energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum( Calib_BarrelL_VectorSignalsCher) e_c = float(t[counter]) - (Leak / 1000. + NeutrinoLeak / 1000.) hesscatterplot.Fill(Energyem / 1000. / e_c, energyscin / e_c) hecscatterplot.Fill(Energyem / 1000. / e_c, energycher / e_c) femhisto.Fill(Energyem / 1000. / e_c) z = (1. - energycher / energyscin) / ( 1. - (chivalue * energycher / energyscin)) zhisto.Fill(z) znormhisto.Fill(z / (1 - (Energyem / 1000. / e_c))) zfemhisto.Fill(z, (1 - (Energyem / 1000. / e_c))) EnergyContHist.Fill(e_c) ScinEnergyHist.Fill(energyscin) CherEnergyHist.Fill(energycher) scatterplot.Fill(energyscin / float(t[counter]), energycher / float(t[counter])) chi = chivalue newchi = (energyscin - e_c) / (energycher - e_c) ChiHist.Fill(newchi) RecEnergyHist.Fill( 1. / 0.99 * (energyscin - chi * energycher) / (1. - chi)) print energies[counter], ScinEnergyHist.GetMean( ), CherEnergyHist.GetMean(), RecEnergyHist.GetMean() displayfile.cd() gStyle.SetOptStat(111) #ScinEnergyHist.Fit("gaus") #CherEnergyHist.Fit("gaus") #RecEnergyHist.Scale(1/RecEnergyHist.Integral()) #print RecEnergyHist.Integral() RecEnergyHist.Fit("gaus") RecEnergyHist.Write() ScinEnergyHist.Write() CherEnergyHist.Write() #Signalscinhist.Write() EnergyHist.Write() EnergyContHist.Write() e_cont = EnergyContHist.GetMean() e_cont_error = EnergyContHist.GetRMS() / float(entries)**0.5 scatterplot.Write() #cut1 = TCutG("cut1",4) #cut1.SetVarX("x") #cut1.SetVarY("y") #cut1.SetPoint(0,0.,0.) #cut1.SetPoint(1,1.,0.) #cut1.SetPoint(2,1.,1.) #cut1.SetPoint(3,0.,1.) #profile = scatterplot.ProfileX("",1,400,"[cut1]") #profile.GetYaxis().SetRangeUser(0.,1.5) #profile.Write() func2 = TF1("func2", '[0]+x*(1.-[0])', 0., 1.) pp = hesscatterplot.ProfileX() pp.Fit(func2) pp.Write() hesscatterplot.Write() hecscatterplot.Write() femhisto ppc = hecscatterplot.ProfileX() ppc.Fit(func2) ppc.Write() LeakageHist.Write() NeutrinoLeakageHist.Write() TotalLeakageHist.Write() ChiHist.Write() #scin_sqrtenergies.append(1./(ScinEnergyHist.GetFunction("gaus").GetParameter(1)**0.5)) #cher_sqrtenergies.append(1./(CherEnergyHist.GetFunction("gaus").GetParameter(1)**0.5)) Energy.append(RecEnergyHist.GetFunction("gaus").GetParameter(1)) Energyerror.append(3. * RecEnergyHist.GetFunction("gaus").GetParameter(2) / float(entries)**0.5) MeanEnergyScin.append(ScinEnergyHist.GetMean()) MeanEnergyCher.append(CherEnergyHist.GetMean()) resolution.append( RecEnergyHist.GetFunction("gaus").GetParameter(2) / RecEnergyHist.GetFunction("gaus").GetParameter(1)) sigma_energy_e = ( (RecEnergyHist.GetFunction("gaus").GetParameter(2) / (float(entries)**0.5)) / RecEnergyHist.GetFunction("gaus").GetParameter(1) + RecEnergyHist.GetFunction("gaus").GetParError(2) / RecEnergyHist.GetFunction("gaus").GetParameter(2)) * ( RecEnergyHist.GetFunction("gaus").GetParameter(2) / RecEnergyHist.GetFunction("gaus").GetParameter(1)) resolutionerror.append(sigma_energy_e) energyfractionscin.append(ScinEnergyHist.GetMean() / float(t[counter])) energyfractionscinerror.append( 3 * (ScinEnergyHist.GetRMS() / entries**0.5) / float(t[counter])) energyfractioncher.append(CherEnergyHist.GetMean() / float(t[counter])) energyfractionchererror.append( 3 * (CherEnergyHist.GetRMS() / entries**0.5) / float(t[counter])) energyfraction.append( RecEnergyHist.GetFunction("gaus").GetParameter(1) / float(t[counter])) energyfractionerror.append( 3 * (RecEnergyHist.GetFunction("gaus").GetParameter(2) / entries**0.5) / float(t[counter])) resolutionscin.append(ScinEnergyHist.GetRMS() / ScinEnergyHist.GetMean()) sigma_energy_e = ( ScinEnergyHist.GetMeanError() / ScinEnergyHist.GetMean() + ScinEnergyHist.GetRMSError() / ScinEnergyHist.GetRMS()) * ( ScinEnergyHist.GetRMS() / ScinEnergyHist.GetMean()) resolutionscinerror.append(sigma_energy_e) resolutioncher.append(CherEnergyHist.GetRMS() / CherEnergyHist.GetMean()) sigma_energy_e = ( CherEnergyHist.GetMeanError() / CherEnergyHist.GetMean() + CherEnergyHist.GetRMSError() / CherEnergyHist.GetRMS()) * ( CherEnergyHist.GetRMS() / CherEnergyHist.GetMean()) resolutionchererror.append(sigma_energy_e) chiarray.append(ChiHist.GetBinCenter(ChiHist.GetMaximumBin())) chierrorarray.append(3 * ChiHist.GetRMS() / (entries**0.5)) zeros.append(0.0) containment.append(e_cont / float(t[counter])) containmenterror.append(e_cont_error / float(t[counter])) femhisto.Write() zhisto.Write() zfemhisto.Write() znormhisto.Write() femvalues.append(femhisto.GetMean()) zvalues.append(zhisto.GetMean()) femvalueserror.append(femhisto.GetRMS() / (entries**0.5)) zvalueserror.append(zhisto.GetRMS() / (entries**0.5)) znormvalues.append(znormhisto.GetMean()) znormvalueserror.append(znormhisto.GetRMS() / (entries**0.5)) containmentgraph = TGraphErrors(len(energies), energies, containment, zeros, containmenterror) containmentgraph.SetName("containment") containmentgraph.Write() ChiGraph = TGraphErrors(len(energies), energies, chiarray, zeros, chierrorarray) ChiGraph.SetName("Chi") ChiGraph.Write() LinearityGraph2 = TGraphErrors(len(energies), energies, Energy, zeros, Energyerror) LinearityGraph2.SetName("LinearityGraph2") LinearityGraph2.Write() LinearityGraph = TGraphErrors(len(energies), energies, energyfraction, zeros, energyfractionerror) LinearityGraph.SetName("LinearityGraph") LinearityGraph.Write() LinearityGraphScin = TGraphErrors(len(energies), energies, energyfractionscin, zeros, energyfractionscinerror) LinearityGraphCher = TGraphErrors(len(energies), energies, energyfractioncher, zeros, energyfractionchererror) LinearityGraphCher.SetName("LinearityGraphCher") LinearityGraphCher.Write() LinearityGraphScin.SetName("LinearityGraphScin") LinearityGraphScin.Write() ResolutionGraphScin = TGraphErrors(len(energies), sqrtenergies, resolutionscin, zeros, resolutionscinerror) func = TF1("func", "[0]/(x**0.5)+[1]", 10., 150.) ResolutionGraphCher = TGraphErrors(len(energies), sqrtenergies, resolutioncher, zeros, resolutionchererror) #ResolutionGraphScin.Fit("func", "R") #ResolutionGraphCher.Fit("func", "R") ResolutionGraphScin.SetName("ResolutionGraphScin") ResolutionGraphScin.Write() ResolutionGraphCher.SetName("ResolutionGraphCher") ResolutionGraphCher.Write() ResolutionGraph = TGraphErrors(len(energies), sqrtenergies, resolution, zeros, resolutionerror) #ResolutionGraph.Fit("func", "R") ResolutionGraph.SetName("ResolutionGraph") ResolutionGraph.Write() LinearityGraph.SetMinimum(0.976) #0.976 LinearityGraph.SetMaximum(1.024) #1.024 LinearityGraph.GetXaxis().SetLimits(0.0, 155.0) LinearityGraph.SetTitle("") LinearityGraph.GetXaxis().SetLabelSize(.105) LinearityGraph.GetYaxis().SetLabelSize(0.105) LinearityGraph.GetXaxis().SetNdivisions(520) LinearityGraph.GetYaxis().SetNdivisions(504) LinearityGraph2.SetTitle("") LinearityGraph2.SetMinimum(0.0) LinearityGraph2.SetMaximum(155.0) LinearityGraph2.GetXaxis().SetLimits(0.0, 155.0) LinearityGraph2.GetXaxis().SetLabelSize(0.) LinearityGraph2.GetXaxis().SetNdivisions(520) LinearityGraph2.GetYaxis().SetNdivisions(520) c = TCanvas("c", "canvas", 800, 800) # Upper histogram plot is pad1 pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetBottomMargin(0.02) # joins upper and lower plot pad1.SetLeftMargin(0.1) pad1.SetRightMargin(0.1) pad1.Draw() # Lower ratio plot is pad2 c.cd() # returns to main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3) pad2.SetTopMargin(0.05) # joins upper and lower plot pad2.SetBottomMargin(0.3) pad2.SetLeftMargin(0.1) pad2.SetRightMargin(0.1) pad2.Draw() pad1.cd() LinearityGraph2.Draw() pad2.cd() LinearityGraph.Draw("AP") ratioline = TF1("ratioline", str(np.mean(energyfraction)), 0., 160.) ratioline.SetLineColor(1) ratioline.SetLineWidth(1) ratioline.SetLineStyle(9) ratioline.Draw("same") ratioline.Write() c.Update() #c.SaveAs("MLratio.pdf") c.Write() femgraph = TGraphErrors(len(energies), energies, femvalues, zeros, femvalueserror) femgraph.SetName("fem_graph") femfit = TF1("femfit", "1.-(x/[0])**([1]-1.)", 10., 150.) femgraph.Fit("femfit", "R") femgraph.Write() zvalues = array('d', [math.log(x) for x in zvalues]) logenergies = array('d', [math.log(x) for x in energies]) zgraph = TGraphErrors(len(logenergies), logenergies, zvalues, zeros, zvalueserror) zgraph.SetName("z_graph") zfit = TF1("zfit", "pol1", 2.2, 5.1) zgraph.Fit("zfit", "R") zgraph.Write() znormgraph = TGraphErrors(len(energies), energies, znormvalues, zeros, znormvalueserror) znormgraph.SetName("znorm_graph") znormgraph.Write() ''' Resolutions = TMultiGraph() Resolutions.Add(ResolutionGraphScin) Resolutions.Add(ResolutionGraphCher) Resolutions.Add(ResolutionGraph) Resolutions.SetName("EMResolutions") Resolutions.Write() Linearities = TMultiGraph() Linearities.Add(LinearityGraph) Linearities.Add(LinearityGraphScin) Linearities.Add(LinearityGraphCher) Linearities.SetName("Linearities") Linearities.Write() ''' return RecEnergyHist.GetFunction("gaus").GetParameter( 2), RecEnergyHist.GetFunction("gaus").GetParameter( 1), RecEnergyHist.GetFunction("gaus").GetChisquare()
def makeRooDataSet(type, infile_name, outfile_name, tree_name, nevents): """ Make RooDataSets from TTrees""" inputfile = TFile.Open(infile_name, "READ") print "Importing tree" tree = TTree() inputfile.GetObject(tree_name, tree) #get the tree from the data file #define variables for the RooDataSet m_mumu = RooRealVar("m_mumu", "m_mumu", 0.0, 4.0) y_mumu = RooRealVar("y_mumu", "y_mumu", 0.0, 2.0) pt_mumu = RooRealVar("pt_mumu", "pt_mumu", 0.0, 260.0) eta_gamma = RooRealVar("eta_gamma", "eta_gamma", -3.5, 3.5) pt_gamma = RooRealVar("pt_gamma", "pt_gamma", 0.0, 100.0) m_gamma = RooRealVar("m_gamma", "m_gamma", -0.1, 0.1) m_chi_rf1S = RooRealVar("m_chi_rf1S", "m_chi_rf1S", 0.0, 7.0) m_chi_rf2S = RooRealVar("m_chi_rf2S", "m_chi_rf2S", -1.0, 1.0) #Qvalue = RooRealVar("Qvalue","Q", -15., 15.) s = RooRealVar("s", "s", -10., 10.) ctpv = RooRealVar("ctpv", "ctpv", -1.0, 3.5) ctpv_error = RooRealVar("ctpv_err", "ctpv_err", -1.0, 1.0) pi0_abs_mass = RooRealVar("pi0_abs_mass", "pi0_abs_mass", 0.0, 2.2) psi1S_nsigma = RooRealVar("psi1S_nsigma", "psi1S_nsigma", 0.0, 1.0) psi2S_nsigma = RooRealVar("psi2S_nsigma", "psi2S_nsigma", 0.0, 1.0) psi3S_nsigma = RooRealVar("psi3S_nsigma", "psi3S_nsigma", 0.0, 1.0) rho_conv = RooRealVar("rho_conv", "rho_conv", 0.0, 70.0) dz = RooRealVar("dz", "dz", -1.0, 1.0) probFit1S = RooRealVar("probFit1S", "probFit1S", 0, 1) probFit2S = RooRealVar("probFit2S", "probFit2S", 0, 1) dataArgSet = RooArgSet(m_mumu, y_mumu, pt_mumu, eta_gamma, pt_gamma, m_gamma, m_chi_rf1S) dataArgSet.add(m_chi_rf2S) dataArgSet.add(s) dataArgSet.add(ctpv) dataArgSet.add(ctpv_error) dataArgSet.add(pi0_abs_mass) dataArgSet.add(psi1S_nsigma) dataArgSet.add(psi2S_nsigma) dataArgSet.add(rho_conv) dataArgSet.add(dz) dataArgSet.add(probFit1S) dataArgSet.add(probFit2S) print "Creating DataSet" dataSet = RooDataSet("chicds", "Chic RooDataSet", dataArgSet) entries = tree.GetEntries() print entries if nevents is not 0: entries = nevents for ientry in range(0, entries): tree.GetEntry(ientry) # unfort ntuples are slightly different for chic and chib if type == 'chic': m_mumu.setVal(tree.dimuon_mass) y_mumu.setVal(tree.dimuon_rapidity) pt_mumu.setVal(tree.dimuon_pt) eta_gamma.setVal(tree.photon_eta) pt_gamma.setVal(tree.photon_pt) #m_gamma.setVal(tree.photon_p4.M()) m_chi_rf1S.setVal(tree.rf1S_chic_mass) #m_chi_rf1S.setVal(tree.rf2S_chi_p4.M()) #Qvalue.setVal((tree.chi_p4).M() - tree.dimuon_p4.M()) #Qvalue.setVal((tree.chi_p4).M()**2 - tree.dimuon_p4.M()**2) #Qvalue.setVal((tree.rf1S_chic_mass**2 -tree.dimuon_mass**2) # / (3.5107**2 - 3.0969**2 ) -1) # this should be the correct one if the refitted variable was available # s.setVal((tree.rf1S_chic_mass**2 - tree.rf1S_dimuon_p4.M()**2)/ (3.5107**2 - 3.0969**2 ) -1) s.setVal((tree.rf1S_chic_mass**2 - 3.0969**2) / (3.5107**2 - 3.0969**2) - 1) psi1S_nsigma.setVal(tree.psi1S_nsigma) psi2S_nsigma.setVal(0) psi3S_nsigma.setVal(0) elif type == 'chib': m_mumu.setVal(tree.dimuon_mass) y_mumu.setVal(tree.dimuon_rapidity) pt_mumu.setVal(tree.dimuon_pt) eta_gamma.setVal(tree.photon_eta) pt_gamma.setVal(tree.photon_pt) m_chi_rf1S.setVal(tree.rf1S_chib_mass) m_chi_rf2S.setVal(tree.rf2S_chib_mass) Qvalue.setVal(tree.chib_mass - tree.dimuon_mass) psi1S_nsigma.setVal(tree.Y1S_nsigma) psi2S_nsigma.setVal(tree.Y2S_nsigma) psi3S_nsigma.setVal(tree.Y3S_nsigma) ctpv.setVal(tree.ct_pv) ctpv_error.setVal(tree.ct_pv_error) #pi0_abs_mass.setVal(tree.pi0_abs_mass) rho_conv.setVal(tree.Conv) dz.setVal(tree.Dz) probFit1S.setVal(tree.probfit1S) #probFit2S.setVal(tree.probFit2S) #if (tree.chic_pdgId == 20443):dataSet.add(dataArgSet) dataSet.add(dataArgSet) outfile = TFile(outfile_name, 'recreate') dataSet.Write()
def jetdisplay(): outputfile = "zjj" displayfile = TFile(outputfile + ".root", "RECREATE") energies = [30, 50, 70, 90, 150, 250] cut = [16.72, 31.115, 55.548, 58.715, 99.335, 160.8] inputfiles = [ "jetscan_leakage_029/jetscan_" + str(e) + ".root" for e in energies ] #for geant4.10.5 inputfiles = [ "resultsgeant4.10.5/jetscan_leakage/jetscan/jetscan" + str(e) + ".root" for e in energies ] #end of geant4.10.5 #for geant4.10.5 with X0 or B #inputfiles = ["resultsgeant4.10.5/jetscan_leakage_X0/jetscan/jetscan"+str(e)+".root" for e in energies] #end of geant4.10.5 with X0 or B #for CaloLoop #inputfiles = ["/home/software/Calo/CaloLoop/CaloJet/resultsgeant4.10.5/jetscan_leakage_B/jetscan/jetscan"+str(e)+".root" for e in energies] #end CaloLoop #for geant4.10.5.p01 FTFPBERT inputfiles = [ "results_FTFPBERT/noBnoX0/jetscan/jetscan_" + str(e) + ".root" for e in energies ] #end geant4.10.5.p01 FTFPBERT for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: " + str(inputfile) + " \n" tree = TTree() inputfile.GetObject("MyTree", tree) #graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.) #graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.) #graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.) #graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.) #graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.) graphtest = TH1F("test" + str(energies[counter]), "test" + str(energies[counter]), 80, -40., 40.) graphenergy = TH1F("energy" + str(energies[counter]), "energy" + str(energies[counter]), 200, 0., 100.) graphenergytruth = TH1F("energytruth" + str(energies[counter]), "energytruth" + str(energies[counter]), 200, 0., 100.) graphjs = TH1F("energyjs" + str(energies[counter]), "energyjs" + str(energies[counter]), 200, 0., 100.) graphjc = TH1F("energyjc" + str(energies[counter]), "energyjc" + str(energies[counter]), 200, 0., 100.) graph_emcomp02 = TH1F("emcomp02_" + str(energies[counter]), "emcomp02" + str(energies[counter]), 80, -40, 40) graph_emcomp04 = TH1F("emcomp04_" + str(energies[counter]), "emcomp04" + str(energies[counter]), 80, -40, 40) graph_emcomp06 = TH1F("emcomp06_" + str(energies[counter]), "emcomp06" + str(energies[counter]), 80, -40, 40) graph_emcomp08 = TH1F("emcomp08_" + str(energies[counter]), "emcomp08" + str(energies[counter]), 80, -40, 40) graph_emcomp1 = TH1F("emcomp1_" + str(energies[counter]), "emcomp1" + str(energies[counter]), 80, -40, 40) scatterplot = TH2F("diff_" + str(energies[counter]), "diff_" + str(energies[counter]), 70, -20., 50., 70, -50., 20) scatterplotedep = TH2F("edep_" + str(energies[counter]), "edep_" + str(energies[counter]), 100, 0.0, 100.0, 100, 0.0, 100.0) #loop over events for Event in range(tree.GetEntries()): tree.GetEntry(Event) #print "Event "+str(Event) nmuon = tree.nmuon nneu = tree.nneu mjjr = tree.mjjr mjjt = tree.mjjt edep = tree.edep muene_che = tree.muene_che muene_sci = tree.muene_sci emcomp1 = tree.emcomp1 emcomp2 = tree.emcomp2 eleak = tree.eleak eleakn = tree.eleakn j1t_E = tree.j1t_E j1t_m = tree.j1t_m j1t_theta = tree.j1t_theta j1t_pt = tree.j1t_pt j1t_eta = tree.j1t_eta j1t_phi = tree.j1t_phi j2t_E = tree.j2t_E j2t_m = tree.j2t_m j2t_theta = tree.j2t_theta j2t_pt = tree.j2t_pt j2t_eta = tree.j2t_eta j2t_phi = tree.j2t_phi j1r_E = tree.j1r_E j1r_m = tree.j1r_m j1r_theta = tree.j1r_theta j1r_pt = tree.j1r_pt j1r_eta = tree.j1r_eta j1r_phi = tree.j1r_phi j2r_E = tree.j2r_E j2r_m = tree.j2r_m j2r_theta = tree.j2r_theta j2r_pt = tree.j2r_pt j2r_eta = tree.j2r_eta j2r_phi = tree.j2r_phi j1s_E = tree.j1s_E j1s_m = tree.j1s_m j1s_theta = tree.j1s_theta j1s_pt = tree.j1s_pt j1s_eta = tree.j1s_eta j1s_phi = tree.j1s_phi j2s_E = tree.j2s_E j2s_m = tree.j2s_m j2s_theta = tree.j2s_theta j2s_pt = tree.j2s_pt j2s_eta = tree.j2s_eta j2s_phi = tree.j2s_phi j1c_E = tree.j1c_E j1c_m = tree.j1c_m j1c_theta = tree.j1c_theta j1c_pt = tree.j1c_pt j1c_eta = tree.j1c_eta j1c_phi = tree.j1c_phi j2c_E = tree.j2c_E j2c_m = tree.j2c_m j2c_theta = tree.j2c_theta j2c_pt = tree.j2c_pt j2c_eta = tree.j2c_eta j2c_phi = tree.j2c_phi cut1 = nmuon == 0 and nneu == 0 cut2 = abs(j1t_eta) < 2.0 and abs(j2t_eta) < 2.0 eleak = eleak / 1000. cut3 = eleak < 0.1 #cut3 = True cut4 = j1s_E + j2s_E > cut[counter] cut4 = True #cut5 = abs(j1t_E-j2t_E)<5. #cut5 = abs(j1t_phi-j2t_phi)>0.1 cut5 = True if cut1 and cut2 and cut3 and cut4 and cut5: #deltaj1 = 0.04406*j1r_E+0.1158 #deltaj2 = 0.04406*j2r_E+0.1158 #deltaj1 = 0.02825*j1r_E+0.4056 #deltaj2 = 0.02825*j2r_E+0.4056 #deltaj1 = 0.04135*j1r_E+0.08789 #deltaj2 = 0.04135*j2r_E+0.08789 #deltaj1 = 0.07113*j1r_E+0.5201 #deltaj2 = 0.07113*j2r_E+0.5201 deltaj1 = 0.0 deltaj2 = 0.0 graphtest.Fill(j1r_E + deltaj1 - j1t_E) graphtest.Fill(j2r_E + deltaj2 - j2t_E) ''' if (emcomp1+emcomp2)<0.2*90.: graph_emcomp02.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp02.Fill(j2r_E+deltaj2-j2t_E) if 0.2*90.<emcomp1+emcomp2<0.4*90.: graph_emcomp04.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp04.Fill(j2r_E+deltaj2-j2t_E) if 0.4*90.<emcomp1+emcomp2<0.6*90.: graph_emcomp06.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp06.Fill(j2r_E+deltaj2-j2t_E) if 0.6*90.<emcomp1+emcomp2<0.8*90.: graph_emcomp08.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp08.Fill(j2r_E+deltaj2-j2t_E) if 0.8*90.<emcomp1+emcomp2<90.: graph_emcomp1.Fill(j1r_E+deltaj1-j1t_E) graph_emcomp1.Fill(j2r_E+deltaj2-j2t_E) ''' graphenergy.Fill(j1r_E + deltaj1) graphenergy.Fill(j2r_E + deltaj2) graphenergytruth.Fill(j1t_E) graphenergytruth.Fill(j2t_E) graphjs.Fill(j2s_E) graphjs.Fill(j1s_E) graphjc.Fill(j2c_E) graphjc.Fill(j1c_E) scatterplot.Fill(j2r_E + deltaj2 - j2t_E, j1r_E + deltaj1 - j1t_E) scatterplotedep.Fill(edep, j1s_E + j2s_E) displayfile.cd() graphtest.Write() graphenergy.Write() graphenergytruth.Write() graphjs.Write() graphjc.Write() #graph_emcomp02.Write() #graph_emcomp04.Write() #graph_emcomp06.Write() #graph_emcomp08.Write() #graph_emcomp1.Write() scatterplot.Write() scatterplotedep.Write()
class Run(Analysis): """ Run class containing all the information for a single run. """ NTelPlanes = 4 def __init__(self, number=None, testcampaign=None, load_tree=True, verbose=None): """ :param number: if None is provided it creates a dummy run :param testcampaign: if None is provided ... :param load_tree: load the ROOT TTree :param verbose: turn on more output """ # Basics super(Run, self).__init__(testcampaign, verbose=verbose, pickle_dir='Run') self.Number = number # Directories / Test Campaign self.IrradiationFile = join(self.Dir, self.MainConfig.get('MISC', 'irradiation file')) # Configuration & Root Files self.Config = self.load_run_config() self.RootFileDir = self.load_rootfile_dirname() self.RootFilePath = self.load_rootfile_path() # Run Info self.InfoFile = join(self.TCDir, 'run_log.json') self.Info = self.load_run_info() self.RootFile = None self.Tree = TTree() self.TreeName = self.Config.get('BASIC', 'treename') self.DUTs = [self.dut(i + 1, self.Info) for i in range(self.get_n_diamonds())] if self.Number is not None else None # Settings self.Plane = Plane() self.TriggerPlanes = self.load_trigger_planes() # General Information self.Flux = self.get_flux() self.Type = self.get_type() # Times self.LogStart = self.load_log_start() self.LogEnd = self.load_log_stop() self.Duration = self.LogEnd - self.LogStart self.Converter = Converter(self) if self.set_run(number, load_tree): # tree info self.TimeOffset = None self.Time = self.load_time_vec() self.StartEvent = 0 self.NEvents = int(self.Tree.GetEntries()) self.EndEvent = self.NEvents - 1 self.StartTime = self.get_time_at_event(self.StartEvent) self.EndTime = self.get_time_at_event(self.EndEvent) self.TotalTime = self.load_total_time() self.TotalMinutes = self.TotalTime / 60000. self.Duration = timedelta(seconds=self.TotalTime) self.LogEnd = self.LogStart + self.Duration # overwrite if we know exact duration self.NPlanes = self.load_n_planes() self.TInit = time() - self.InitTime def __str__(self): return f'{self.__class__.__name__} {self.Number}{self.evt_str} ({self.TCString})' def __repr__(self): return self.__str__() def __call__(self, number, load_tree=False): self.set_run(number, load_tree) return self def __gt__(self, other): return self.Number > (other.Number if isinstance(other, Run) else other) @property def evt_str(self): return f' with {make_ev_str(self.Info["events"])} ev' if 'events' in self.Info else f' with {make_ev_str(self.NEvents)} ev' if self.Tree.Hash() else '' def set_run(self, number, load_tree): if number is None: return False if number < 0 and type(number) is not int: critical('incorrect run number') self.Number = number self.load_run_info() self.Flux = self.get_flux() # check for conversion if load_tree: self.Converter.convert_run() self.load_rootfile() else: return False if not self.rootfile_is_valid(): self.Converter.convert_run() self.load_rootfile() return True def get_type(self): return self.Config.get('BASIC', 'type') if self.Number is not None else None def set_estimate(self, n=None): self.Tree.SetEstimate(choose(n, -1)) def is_volt_scan(self): return any(name in self.Info['runtype'] for name in ['voltage', 'hv']) # ---------------------------------------- # region INIT @property def dut(self): return DUT def load_rootfile(self, prnt=True): self.info('Loading information for rootfile: {file}'.format(file=basename(self.RootFilePath)), endl=False, prnt=prnt) self.RootFile = TFile(self.RootFilePath) self.Tree = self.RootFile.Get(self.TreeName) return self.Tree def load_run_config(self): base_file_name = join(get_base_dir(), 'config', self.TCString, 'RunConfig.ini') if not file_exists(base_file_name): critical('RunConfig.ini does not exist for {0}! Please create it in config/{0}!'.format(self.TCString)) parser = Config(base_file_name) # first read the main config file with general information for all splits if parser.has_section('SPLIT') and self.Number is not None: split_runs = [0] + loads(parser.get('SPLIT', 'runs')) + [inf] config_nr = next(i for i in range(1, len(split_runs)) if split_runs[i - 1] <= self.Number < split_runs[i]) parser.read(join(get_base_dir(), 'config', self.TCString, 'RunConfig{nr}.ini'.format(nr=config_nr))) # add the content of the split config return parser @staticmethod def make_root_filename(run): return f'TrackedRun{run:0>3}.root' def make_root_subdir(self): return join('root', 'pads' if self.get_type() == 'pad' else self.get_type()) def load_rootfile_path(self, run=None): run = choose(run, self.Number) return None if run is None else join(self.RootFileDir, self.make_root_filename(run)) def load_rootfile_dirname(self): return ensure_dir(join(self.TCDir, self.make_root_subdir())) if self.Number is not None else None def load_trigger_planes(self): return array(self.Config.get_list('BASIC', 'trigger planes', [1, 2])) def get_n_diamonds(self, run_number=None): run_info = self.load_run_info(run_number) return len([key for key in run_info if key.startswith('dia') and key[-1].isdigit()]) def load_dut_numbers(self): return [i + 1 for i in range(len([key for key in self.Info.keys() if key.startswith('dia') and key[-1].isdigit()]))] def load_dut_type(self): dut_type = self.Config.get('BASIC', 'type') if self.Number is not None else None if dut_type not in ['pixel', 'pad', None]: critical("The DUT type {0} has to be either 'pixel' or 'pad'".format(dut_type)) return dut_type def load_default_info(self): with open(join(self.Dir, 'Runinfos', 'defaultInfo.json')) as f: return load(f) def load_run_info_file(self): if not file_exists(self.InfoFile): critical('Run Log File: "{f}" does not exist!'.format(f=self.InfoFile)) with open(self.InfoFile) as f: return load(f) def load_run_info(self, run_number=None): data = self.load_run_info_file() run_number = self.Number if run_number is None else run_number if run_number is not None: run_info = data.get(str(run_number)) if run_info is None: # abort if the run is still not found critical('Run {} not found in json run log file!'.format(run_number)) self.Info = run_info self.Info['masked pixels'] = [0] * 4 self.translate_diamond_names() return run_info else: self.Info = self.load_default_info() return self.Info def load_dut_names(self): return [self.Info['dia{nr}'.format(nr=i)] for i in range(1, self.get_n_diamonds() + 1)] def load_biases(self): return [int(self.Info['dia{nr}hv'.format(nr=i)]) for i in range(1, self.get_n_diamonds() + 1)] def load_log_start(self): return conv_log_time(self.Info['starttime0']) def load_log_stop(self): return conv_log_time(self.Info['endtime']) def load_total_time(self): return (self.Time[-1] - self.Time[0]) / 1000 def load_n_planes(self): if self.has_branch('cluster_col'): self.Tree.Draw('@cluster_col.size()', '', 'goff', 1) return int(self.Tree.GetV1()[0]) else: return 4 def load_time_vec(self): t = get_time_vec(self.Tree) t0 = datetime.fromtimestamp(t[0] / 1000) if t[0] < 1e12 else None self.TimeOffset = None if t0 is None or t0.year > 2000 and t0.day == self.LogStart.day else t[0] - time_stamp(self.LogStart) * 1000 return t if self.TimeOffset is None else t - self.TimeOffset def load_plane_efficiency(self, plane): return self.load_plane_efficiencies()[plane - 1] def load_plane_efficiencies(self): return [ufloat(e, .03) for e in self.Config.get_list('BASIC', 'plane efficiencies', default=[.95, .95])] # endregion INIT # ---------------------------------------- # ---------------------------------------- # region MASK def load_mask_file_path(self): mask_dir = self.MainConfig.get('MAIN', 'maskfile directory') if self.MainConfig.has_option('MAIN', 'maskfile directory') else join(self.DataDir, self.TCDir, 'masks') if not dir_exists(mask_dir): warning('Mask file directory does not exist ({})!'.format(mask_dir)) return join(mask_dir, basename(self.Info['maskfile'])) def load_mask(self, plane=None): mask_file = self.load_mask_file_path() if basename(mask_file).lower() in ['no mask', 'none', 'none!', ''] or self.Number is None: return try: data = genfromtxt(mask_file, [('id', 'U10'), ('pl', 'i'), ('x', 'i'), ('y', 'i')]) if 'cornBot' not in data['id']: warning('Invalid mask file: "{}". Not taking any mask!'.format(mask_file)) mask = [[data[where((data['pl'] == pl) & (data['id'] == n))][0][i] for n in ['cornBot', 'cornTop'] for i in [2, 3]] for pl in sorted(set(data['pl']))] mask = [[max(1, m[0]), max(1, m[1]), min(self.Plane.NCols - 2, m[2]), min(self.Plane.NRows - 2, m[3])] for m in mask] # outer pixels are ignored return mask if plane is None else mask[plane - 1] if plane - 1 < len(mask) else None except Exception as err: warning(err) warning('Could not read mask file... not taking any mask!') def get_mask_dim(self, plane=1, mm=True): return Plane.get_mask_dim(self.load_mask(plane), mm) def get_mask_dims(self, mm=True): return array([self.get_mask_dim(pl, mm) for pl in [1, 2]]) def get_unmasked_area(self, plane): return None if self.Number is None else Plane.get_area(self.load_mask(plane)) def find_for_in_comment(self): for name in ['for1', 'for2']: if name not in self.Info: for cmt in self.Info['comments'].split('\r\n'): cmt = cmt.replace(':', '') cmt = cmt.split(' ') if str(cmt[0].lower()) == name: self.Info[name] = int(cmt[1]) return 'for1' in self.Info # endregion MASK # ---------------------------------------- # ---------------------------------------- # region HELPERS def translate_diamond_names(self): for key, value in [(key, value) for key, value in self.Info.items() if key.startswith('dia') and key[-1].isdigit()]: self.Info[key] = self.translate_dia(value) def register_new_dut(self): if input('Do you want to add a new diamond? [y,n] ').lower() in ['y', 'yes']: dut_type = int(input('Enter the DUT type (1 for pCVD, 2 for scCVD, 3 for silicon): ')) - 1 dut_name = input('Enter the name of the DUT (no "_"): ') alias = input(f'Enter the alias (no "_", for default {dut_name.lower()} press enter): ') self.add_alias(alias, dut_name, dut_type) self.add_dut_info(dut_name) return True else: return False @staticmethod def add_alias(alias, dut_name, dut_type): alias_file = join(Dir, 'config', 'DiamondAliases.ini') with open(alias_file, 'r+') as f: lines = [line.strip(' \n') for line in f.readlines()] i0 = lines.index(['# pCVD', '# scCVD', '# Silicon'][dut_type]) i = next(i for i, line in enumerate(lines[i0:], i0) if line.strip() == '') lines.insert(i, f'{(alias if alias else dut_name).lower()} = {dut_name}') f.seek(0) f.writelines([f'{line}\n' for line in lines]) info(f'added entry: {(alias if alias else dut_name).lower()} = {dut_name} in {alias_file}') def add_dut_info(self, dut_name): dia_info_file = join(Dir, 'Runinfos', 'dia_info.json') data = load_json(dia_info_file) if dut_name in data: return warning('The entered DUT name already exists!') tc = get_input(f'Enter the beam test [YYYYMM]', self.TCString) data[dut_name] = {'irradiation': {tc: get_input(f'Enter the irradiation for {tc}', '0')}, 'boardnumber': {tc: get_input(f'Enter the board number for {tc}')}, 'thickness': get_input('Enter the thickness'), 'size': get_input('Enter the lateral size ([x, y])'), 'manufacturer': get_input('Enter the manufacturer')} with open(dia_info_file, 'w') as f: dump(data, f, indent=2) info(f'added {dut_name} to {dia_info_file}') def translate_dia(self, dia): name, suf = dia.split('_')[0].lower(), '_'.join(dia.split('_')[1:]) if name not in Config(join(self.Dir, 'config', 'DiamondAliases.ini')).options('ALIASES'): warning(f'{dia} was not found in config/DiamondAliases.ini!') if not self.register_new_dut(): critical(f'unknown diamond {dia}') parser = Config(join(self.Dir, 'config', 'DiamondAliases.ini')) return '_'.join([parser.get('ALIASES', name)] + ([suf] if suf else [])) def reload_run_config(self, run_number): self.Number = run_number self.Config = self.load_run_config() self.Info = self.load_run_info() self.RootFileDir = self.load_rootfile_dirname() self.RootFilePath = self.load_rootfile_path() return self.Config def rootfile_is_valid(self, file_path=None): tfile = self.RootFile if file_path is None else TFile(file_path) ttree = self.Tree if file_path is None else tfile.Get(self.TreeName) is_valid = not tfile.IsZombie() and tfile.ClassName() == 'TFile' and ttree and ttree.ClassName() == 'TTree' if not is_valid: warning('Invalid TFile or TTree! Deleting file {}'.format(tfile.GetName())) remove_file(tfile.GetName()) return is_valid def calculate_plane_flux(self, plane=1, corr=True): """estimate the flux [kHz/cm²] through a trigger plane based on Poisson statistics.""" rate, eff, area = self.Info[f'for{plane}'], self.load_plane_efficiency(plane), self.get_unmasked_area(plane) return -log(1 - rate / Plane.Frequency) * Plane.Frequency / area / 1000 / (eff if corr else ufloat(1, .05)) # count zero hits of Poisson def find_n_events(self, n, cut, start=0): evt_numbers = self.get_tree_vec(var='Entry$', cut=cut, nentries=self.NEvents, firstentry=start) return int(evt_numbers[:n][-1] + 1 - start) def get_max_run(self): return int(max(self.load_run_info_file(), key=int)) # endregion HELPERS # ---------------------------------------- # ---------------------------------------- # region GET def get_flux(self, plane=None, corr=True): if self.Number is None: return if not self.find_for_in_comment(): # warning('no plane rates in the data...') return self.Info['measuredflux'] / (mean(self.load_plane_efficiencies()) if corr else 1) return self.get_mean_flux(corr) if plane is None else self.calculate_plane_flux(plane, corr) def get_mean_flux(self, corr=True): return mean([self.get_flux(pl, corr) for pl in [1, 2]]) def get_time(self): return ufloat(time_stamp(self.LogStart + self.Duration / 2), self.Duration.seconds / 2) def get_channel_name(self, channel): self.Tree.GetEntry() return self.Tree.sensor_name[channel] def get_time_at_event(self, event): """ For negative event numbers it will return the time stamp at the startevent. """ return self.Time[min(event, self.EndEvent)] / 1000. def get_event_at_time(self, seconds, rel=True): """ Returns the event nunmber at time dt from beginning of the run. Accuracy: +- 1 Event """ if seconds - (0 if rel else self.StartTime) >= self.TotalTime or seconds == -1: # return time of last event if input is too large return self.NEvents - 1 return where(self.Time <= 1000 * (seconds + (self.StartTime if rel else 0)))[0][-1] def get_tree_vec(self, var, cut='', dtype=None, nentries=None, firstentry=0): return get_tree_vec(self.Tree, var, cut, dtype, nentries, firstentry) def get_tree_tuple(self): return (self.Tree, self.RootFile) if self.Tree is not None else False def get_time_vec(self): return self.Time if hasattr(self, 'Time') else None def get_bias_strings(self): return [str(b) for b in self.load_biases()] @save_pickle('HR', suf_args=0) def get_high_rate_run(self, high=True): from src.run_selection import RunSelector return int(RunSelector(testcampaign=self.TCString).get_high_rate_run(self.Number, high)) def get_low_rate_run(self): return self.get_high_rate_run(high=False) # endregion GET # ---------------------------------------- # ---------------------------------------- # region SHOW def show_info(self): print('Run information for', self) for key, value in sorted(self.Info.items()): print(f'{key:<13}: {value}') def has_branch(self, name): return bool(self.Tree.GetBranch(name)) def info(self, msg, endl=True, blank_lines=0, prnt=True): return info(msg, endl, prnt=self.Verbose and prnt, blank_lines=blank_lines) def add_to_info(self, t, txt='Done', prnt=True): return add_to_info(t, txt, prnt=self.Verbose and prnt)
def jetdisplay(): outputfile = "wwlj" displayfile = TFile(outputfile+".root","RECREATE") #for geant4.10.5 FTFPBERT inputfiles = ["Results/noBnoX0/2j_0.445/wwjl_0.445.root"] #end geant4.10.5 FTFPBERT for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: "+str(inputfile)+" \n" tree = TTree() inputfile.GetObject("MyTree", tree) #graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.) #graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.) #graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.) #graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.) #graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.) graphtest = TH1F("test", "test", 80, -40., 40.) graphenergy = TH1F("energy", "energy", 100, 60., 160.) graphenergytruth = TH1F("energytruth", "energytruth", 100, 60., 160.) graphjs = TH1F("energyjs", "energyjs", 200, 0., 100.) graphjc = TH1F("energyjc", "energyjc", 200, 0., 100.) graphdiff = TH1F("diff_mass", "diff_mass", 250, -25.,25.) #loop over events for Event in range(tree.GetEntries()): tree.GetEntry(Event) #print "Event "+str(Event) nmuon = tree.nmuon nneu = tree.nneu mjjr = tree.mjjr mjjt = tree.mjjt edep = tree.edep muene_che = tree.muene_che muene_sci = tree.muene_sci emcomp1 = tree.emcomp1 emcomp2 = tree.emcomp2 eleak = tree.eleak eleakn = tree.eleakn drmmu = tree.drmmu emu = tree.emu enumu = tree.enumu j1t_E = tree.j1t_E j1t_m = tree.j1t_m j1t_theta = tree.j1t_theta j1t_pt = tree.j1t_pt j1t_eta = tree.j1t_eta j1t_phi = tree.j1t_phi j2t_E = tree.j2t_E j2t_m = tree.j2t_m j2t_theta = tree.j2t_theta j2t_pt = tree.j2t_pt j2t_eta = tree.j2t_eta j2t_phi = tree.j2t_phi j1r_E = tree.j1r_E j1r_m = tree.j1r_m j1r_theta = tree.j1r_theta j1r_pt = tree.j1r_pt j1r_eta = tree.j1r_eta j1r_phi = tree.j1r_phi j2r_E = tree.j2r_E j2r_m = tree.j2r_m j2r_theta = tree.j2r_theta j2r_pt = tree.j2r_pt j2r_eta = tree.j2r_eta j2r_phi = tree.j2r_phi #deltaj1 = 0.04406*j1r_E+0.1158 #deltaj1 = 0.04135*j1r_E+0.08789 deltaj1 = 0.07113*j1r_E+0.5201 j1 = TLorentzVector() j1.SetPtEtaPhiE(j1r_pt, j1r_eta, j1r_phi, j1r_E) #deltaj2 = 0.04406*j2r_E+0.1158 #deltaj2 = 0.04135*j2r_E+0.08789 deltaj2 = 0.07113*j2r_E+0.5201 j2 = TLorentzVector() j2.SetPtEtaPhiE(j2r_pt, j2r_eta, j2r_phi, j2r_E) newmass = (j1+j2).M() j1s_E = tree.j1s_E j1s_m = tree.j1s_m j1s_theta = tree.j1s_theta j1s_pt = tree.j1s_pt j1s_eta = tree.j1s_eta j1s_phi = tree.j1s_phi j2s_E = tree.j2s_E j2s_m = tree.j2s_m j2s_theta = tree.j2s_theta j2s_pt = tree.j2s_pt j2s_eta = tree.j2s_eta j2s_phi = tree.j2s_phi j1c_E = tree.j1c_E j1c_m = tree.j1c_m j1c_theta = tree.j1c_theta j1c_pt = tree.j1c_pt j1c_eta = tree.j1c_eta j1c_phi = tree.j1c_phi j2c_E = tree.j2c_E j2c_m = tree.j2c_m j2c_theta = tree.j2c_theta j2c_pt = tree.j2c_pt j2c_eta = tree.j2c_eta j2c_phi = tree.j2c_phi cut1 = nmuon==1 and nneu==1 cut2 = abs(j1t_eta)<2.0 and abs(j2t_eta)<2.0 #cut3 = enumu+j1t_E+j2t_E>162.45 cut3 = True cut4 = eleak-emu+muene_sci<1. cut5 = j1r_E+j2r_E>68.0 cut5 = True if cut1 and cut2 and cut3 and cut4 and cut5: graphtest.Fill(j1r_E-j1t_E) graphtest.Fill(j2r_E-j2t_E) deltaj1 = 0.02175*j1r_E+0.0808 deltaj2 = 0.02175*j2r_E+0.0808 graphenergy.Fill(newmass) #graphenergy.Fill(j2r_E+deltaj2) #graphenergytruth.Fill(j1t_E) #graphenergytruth.Fill(j2t_E+j1t_E) graphenergytruth.Fill(mjjt) graphdiff.Fill(newmass-mjjt) graphjs.Fill(j2s_E) graphjs.Fill(j1s_E) graphjc.Fill(j2c_E) graphjc.Fill(j1c_E) displayfile.cd() #graphtest.Write() scale = 1./graphenergy.Integral() graphenergy.Scale(scale) graphenergy.Write() graphenergytruth.Write() graphdiff.Write()
def recenergy(name): outputfile = "MLPionEnergyRes" + str(name) #displayfile = TFile(outputfile+".root","RECREATE") ''' MeanEnergyScin = array('d') MeanEnergyCher = array('d') Energy = array('d') energyfractionscin = array('d') energyfractioncher = array('d') energyfraction = array('d') resolutionscin = array('d') resolutioncher = array('d') resolution = array('d') ''' trainvector = np.array([[0, 0]]) labelvector = np.array([[0]]) inputfiles = [ "/home/lorenzo/Calo/results/trainPion_6_4_2020/trainPionFTFPBERT.root" ] for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: " + str(inputfile) + " \n" tree = TTree() inputfile.GetObject("B4", tree) #loop over events for Event in range(200000): tree.GetEntry(Event) if Event % 10000 == 0: print "-> for training: ", Event #Set values of the tree PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name PrimaryParticleEnergy = tree.PrimaryParticleEnergy EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter Energyem = tree.Energyem # Energy deposited by the em component EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected) EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected) NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected BarrelR_VectorSignals = tree.VectorSignalsR # Vector of energy deposited in Scin fibers (Birk corrected) BarrelL_VectorSignals = tree.VectorSignalsL # Vector of energy deposited in Scin fibers (Birk corrected) BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers BarrelL_VectorSignalsCher = tree.VectorSignalsCherL VectorR = tree.VectorR VectorL = tree.VectorL Leak = tree.leakage NeutrinoLeak = tree.neutrinoleakage if PrimaryParticleEnergy / 1000. < 12.: cutleak = 0.5 if PrimaryParticleEnergy / 1000. > 12. and PrimaryParticleEnergy / 1000. < 50.: cutleak = 1.0 if PrimaryParticleEnergy / 1000. > 50.: cutleak = 3.0 if (Leak / 1000. + NeutrinoLeak / 1000.) < cutleak and PrimaryParticleEnergy / 1000. > 3.0: signalscin = sum(BarrelR_VectorSignals) + sum( BarrelL_VectorSignals) signalcher = sum(BarrelR_VectorSignalsCher) + sum( BarrelL_VectorSignalsCher) #e_c = float(t[counter])#-(Leak/1000.+NeutrinoLeak/1000.) e_c = PrimaryParticleEnergy / 1000. vector = np.array([[signalscin, signalcher]]) label = np.array([[e_c]]) trainvector = np.append(trainvector, vector, axis=0) labelvector = np.append(labelvector, label, axis=0) trainvector = np.delete(trainvector, 0, 0) #cancel first entry because it was set to 0,0,0 labelvector = np.delete(labelvector, 0, 0) indices = np.arange(trainvector.shape[0]) np.random.shuffle(indices) trainvector = trainvector[indices] labelvector = labelvector[indices] #random shuffle entries #normalize entries to maximum maxs = 0 maxc = 0 max1 = 0 max2 = 0 for i in range(len(trainvector)): max1 = trainvector[i][0] if max1 > maxs: maxs = max1 max2 = trainvector[i][1] if max2 > maxc: maxc = max2 for i in range(len(trainvector)): trainvector[i][0] = trainvector[i][0] / maxs trainvector[i][1] = trainvector[i][1] / maxc labelvector[i][0] = labelvector[i][ 0] / 200. #normalize energy to 200. i.e. max energy trainvector2 = trainvector[:len(trainvector) / 2] labelvector2 = labelvector[:len(labelvector) / 2] evalvector = trainvector[len(trainvector) / 2:len(trainvector)] evallabelvector = labelvector[len(labelvector) / 2:len(labelvector)] print len(trainvector2), len(evalvector) return trainvector2, labelvector2, evalvector, evallabelvector, maxs, maxc
class TrigNtupleHandler: def __init__(self): self.fileName = 'lumi.root' self.treeName = 'lumiData' self.file = None self.tree = None self.updatemode = False # Flag showing whether BCID data is initialized self.bcidData = False # Flag showing whether L1 trigger counts are initialized self.l1TrigData = True def open(self, update=True): print 'NtupleHandler.open() called' if os.path.exists(self.fileName) and update: print 'Opening %s for updating' % self.fileName self.updatemode = True self.file = TFile(self.fileName, 'update') self.tree = self.file.Get(self.treeName) else: print 'Creating %s for writing' % self.fileName self.updatemode = False self.file = TFile(self.fileName, 'create') self.tree = TTree(self.treeName, self.treeName) def close(self): print 'ScanNtupleHandler.close() called' self.tree.Write('', TObject.kOverwrite) self.file.Close() def init(self): print 'ScanNtupleHandler.init() called' self.initLBData() self.initBCIDData() def save(self): self.tree.Fill() def readLastEntry(self): entries = self.tree.GetEntries() self.tree.GetEntry(entries - 1) # Fill information from LumiLBData object def fillLumi(self, lumi): # Erase any old data self.clear() # Time in COOL format (ns) self.lbData.coolStartTime = lumi.startTime.timerunlb() self.lbData.coolEndTime = lumi.endTime.timerunlb() # Time in seconds self.lbData.startTime = lumi.startTime.timerunlb() / 1.E9 self.lbData.endTime = lumi.endTime.timerunlb() / 1.E9 # LB duration in seconds self.lbData.lbTime = (lumi.endTime.timerunlb() - lumi.startTime.timerunlb()) / 1.E9 self.lbData.run = lumi.runLB.run self.lbData.lb = lumi.runLB.lb # Need to fill these elsewhere # self.lbData.fill = 0 # self.lbData.eBeam = 0. # self.lbData.stable = False # self.lbData.ready = False # self.lbData.physics = False # if lumi.onlEvtsPerBX > 0.: # self.lbData.muToLumi = lumi.onlInstLumi/lumi.onlEvtsPerBX self.lbData.onlInstLum = lumi.onlInstLumi self.lbData.onlInstLumAll = lumi.onlInstLumiAll self.lbData.onlEvtsPerBX = lumi.onlEvtsPerBX self.lbData.onlPrefChan = lumi.onlPrefChan self.lbData.onlValid = lumi.onlValid self.lbData.olcValid = lumi.olcValid self.lbData.nColl = lumi.bcid.nbcol() self.lbData.nBeam1 = lumi.bcid.nb1() self.lbData.nBeam2 = lumi.bcid.nb2() self.lbData.qBeam1Col = lumi.IBeam1 self.lbData.qBeam2Col = lumi.IBeam2 self.lbData.qBeam1All = lumi.IBeam1All self.lbData.qBeam2All = lumi.IBeam2All self.lbData.specLumi = lumi.specLumi self.lbData.geomLumi = lumi.geomLumi self.lbData.maxEvtsPerBX = lumi.maxEvtsPerBX self.lbData.l1LiveFrac = lumi.l1Livefrac # Get this from the veto folders # self.lbData.avgLiveFrac = -1. # self.lbData.lumiWtLiveFrac = -1. self.lbData.matched = lumi.matched if not self.bcidData: return # And fill the per-BCID values for (bcid, caliLumi) in lumi.bcid.caliLumi.iteritems(): self.lumiDel[int(bcid)] = caliLumi for (bcid, q) in lumi.bcid.b1Curr.iteritems(): self.qBeam1[int(bcid)] = q for (bcid, q) in lumi.bcid.b2Curr.iteritems(): self.qBeam2[int(bcid)] = q i = 0 for bcid in sorted(list(lumi.bcid.b1BCID)): self.b1BCID[i] = bcid i += 1 i = 0 for bcid in sorted(list(lumi.bcid.b2BCID)): self.b2BCID[i] = bcid i += 1 i = 0 for bcid in sorted(list(lumi.bcid.colBCID)): self.colBCID[i] = bcid i += 1 # Still need live fraction # Pass TriggerL1Data object for lumi block filled by TriggerHandler # Also need mapping of channel names to channel values def fillL1Trig(self, trigData, trigChan): for (trig, chan) in trigChan.iteritems(): self.l1TBP[chan] = trigData.TBP[trig] self.l1TAP[chan] = trigData.TAP[trig] self.l1TAV[chan] = trigData.TAV[trig] def defineBranch(self, name, type): self.tree.Branch(name, AddressOf(self.lbData, name), name + '/' + type) def loadBranch(self, name): branch = self.tree.GetBranch(name) branch.SetAddress(AddressOf(self.lbData, name)) def initLBData(self): # Define the main lumiblock data # Time is in ns # ULong64_t startTime;\ # ULong64_t endTime;\ LBDataStructStr = "struct LBDataStruct {\ ULong64_t coolStartTime;\ ULong64_t coolEndTime;\ Double_t startTime;\ Double_t endTime;\ Float_t lbTime;\ UInt_t fill;\ UInt_t run;\ UInt_t lb;\ Float_t eBeam;\ Bool_t stable;\ Bool_t ready;\ Bool_t physics;\ Bool_t larVeto;\ \ UInt_t onlValid;\ UInt_t olcValid;\ UInt_t onlPrefChan;\ Float_t muToLumi;\ Float_t onlInstLum;\ Float_t onlInstLumAll;\ Float_t onlEvtsPerBX;\ \ UInt_t nColl;\ UInt_t nBeam1;\ UInt_t nBeam2;\ Float_t qBeam1Col;\ Float_t qBeam2Col;\ Float_t qBeam1All;\ Float_t qBeam2All;\ \ Float_t specLumi;\ Float_t geomLumi;\ Float_t maxEvtsPerBX;\ \ Float_t l1LiveFrac;\ Float_t avgLiveFrac;\ Float_t lumiWtLiveFrac;\ \ UInt_t matched;\ };" # Replace sizes if needed gROOT.ProcessLine(LBDataStructStr) from ROOT import LBDataStruct self.lbData = LBDataStruct() self.varList = [] self.varList.append(('startTime', 'D')) self.varList.append(('endTime', 'D')) self.varList.append(('coolStartTime', 'l')) self.varList.append(('coolEndTime', 'l')) self.varList.append(('lbTime', 'F')) self.varList.append(('fill', 'i')) self.varList.append(('run', 'i')) self.varList.append(('lb', 'i')) self.varList.append(('eBeam', 'F')) # Boolean status flags self.varList.append(('stable', 'O')) self.varList.append(('ready', 'O')) self.varList.append(('physics', 'O')) self.varList.append(('larVeto', 'O')) # Luminosity information self.varList.append(('onlPrefChan', 'i')) self.varList.append(('muToLumi', 'F')) self.varList.append(('onlInstLum', 'F')) self.varList.append(('onlInstLumAll', 'F')) self.varList.append(('onlEvtsPerBX', 'F')) self.varList.append(('onlValid', 'i')) # From LBLESTONL & 0x3FF self.varList.append(('olcValid', 'i')) # From LUMINOSITY # Total bunch information self.varList.append(('nColl', 'i')) self.varList.append(('nBeam1', 'i')) self.varList.append(('nBeam2', 'i')) self.varList.append(('qBeam1Col', 'F')) # Total charge colliding self.varList.append(('qBeam2Col', 'F')) self.varList.append(('qBeam1All', 'F')) # Total charge in all BCIDs self.varList.append(('qBeam2All', 'F')) self.varList.append(('specLumi', 'F')) self.varList.append(('geomLumi', 'F')) self.varList.append(('maxEvtsPerBX', 'F')) # Livetime information self.varList.append(('l1LiveFrac', 'F')) self.varList.append(('avgLiveFrac', 'F')) self.varList.append( ('lumiWtLiveFrac', 'F')) # lumi-weighted per-BCID livefraction # Where the lumi information came from self.varList.append(('matched', 'i')) for (var, type) in self.varList: if self.updatemode: self.loadBranch(var) else: self.defineBranch(var, type) def initBCIDData(self): self.bcidData = True # Delivered luminosity self.lumiDel = array.array('f', (0., ) * 3564) self.qBeam1 = array.array('f', (0., ) * 3564) # Charge per BCID self.qBeam2 = array.array('f', (0., ) * 3564) self.liveFrac = array.array('f', (0., ) * 3564) # Deadtime if self.updatemode: self.tree.GetBranch('lumiDel').SetAddress(self.lumiDel) self.tree.GetBranch('qBeam1').SetAddress(self.qBeam1) self.tree.GetBranch('qBeam2').SetAddress(self.qBeam2) self.tree.GetBranch('liveFrac').SetAddress(self.liveFrac) else: self.tree.Branch('lumiDel', self.lumiDel, 'lumiDel[3564]/F') self.tree.Branch('qBeam1', self.qBeam1, 'qBeam1[3564]/F') self.tree.Branch('qBeam2', self.qBeam2, 'qBeam2[3564]/F') self.tree.Branch( 'liveFrac', self.liveFrac, 'liveFrac[3564]/F') # Per-BCID livetime from lumi counters # BCID arrays (unsigned shorts) self.b1BCID = array.array('H', (0, ) * 3564) self.b2BCID = array.array('H', (0, ) * 3564) self.colBCID = array.array('H', (0, ) * 3564) if self.updatemode: self.tree.GetBranch('b1BCID').SetAddress(self.b1BCID) self.tree.GetBranch('b2BCID').SetAddress(self.b2BCID) self.tree.GetBranch('colBCID').SetAddress(self.colBCID) else: self.tree.Branch('b1BCID', self.b1BCID, 'b1BCID[nBeam1]/s') # Unsigned short self.tree.Branch('b2BCID', self.b2BCID, 'b2BCID[nBeam2]/s') # Unsigned short self.tree.Branch('colBCID', self.colBCID, 'colBCID[nColl]/s') # Unsigned short def initL1TrigData(self): self.l1TrigData = True # Counts by channel ID self.l1TBP = array.array('I', (0, ) * 256) self.l1TAP = array.array('I', (0, ) * 256) self.l1TAV = array.array('I', (0, ) * 256) if self.updatemode: self.tree.GetBranch('l1TBP').SetAddress(self.l1TBP) self.tree.GetBranch('l1TAP').SetAddress(self.l1TAP) self.tree.GetBranch('l1TAV').SetAddress(self.l1TAV) else: self.tree.Branch('l1TBP', self.l1TBP, 'l1TBP[256]/i') self.tree.Branch('l1TAP', self.l1TAP, 'l1TAP[256]/i') self.tree.Branch('l1TAV', self.l1TAV, 'l1TAV[256]/i') # Set all ntuple variables to default values def clear(self): self.lbData.startTime = 0 self.lbData.endTime = 0 self.lbData.lbTime = 0. self.lbData.fill = 0 self.lbData.run = 0 self.lbData.lb = 0 self.lbData.eBeam = 0. self.lbData.stable = False self.lbData.ready = False self.lbData.physics = False self.lbData.larVeto = False self.lbData.onlPrefChan = 0 self.lbData.muToLumi = 0. self.lbData.onlInstLum = -1. self.lbData.onlInstLumAll = -1. self.lbData.onlEvtsPerBX = -1. self.lbData.onlValid = 0xFFFFFF self.lbData.olcValid = 0xFFFFFF self.lbData.nColl = 0 self.lbData.nBeam1 = 0 self.lbData.nBeam2 = 0 self.lbData.qBeam1Col = -1. self.lbData.qBeam2Col = -1. self.lbData.qBeam1All = -1. self.lbData.qBeam2All = -1. self.lbData.specLumi = -1. self.lbData.geomLumi = -1. self.lbData.maxEvtsPerBX = -1. self.lbData.l1LiveFrac = -1. self.lbData.avgLiveFrac = -1. self.lbData.lumiWtLiveFrac = -1. self.lbData.matched = 0 if self.bcidData: # Per-BCID arrays for i in range(3564): self.lumiDel[i] = 0. self.qBeam1[i] = 0. self.qBeam2[i] = 0. self.liveFrac[i] = 0. self.b1BCID[i] = 0 self.b2BCID[i] = 0 self.colBCID[i] = 0 if self.l1TrigData: # L1 trigger counts for i in range(256): self.l1TBP[i] = 0 self.l1TAP[i] = 0 self.l1TAV[i] = 0
class CompareSpring15: def __init__(self): self.ref="" self.test="" self.cref=None self.ctest=None self.lref=[] self.ltest=[] self.ref_missing=[] self.test_missing=[] self.bad_events=[] self.bad_leptons=[] self.bad_met=[] self.bad_mvamet=[] self.bad_jets=[] self.good_events=[] def load(self, ref, test): self.ref=ref self.test=test #self.cref=TChain(ref.split(":")[1]) #self.ctest=TChain(test.split(":")[1]) #self.cref.Add(ref.split(":")[0]) #self.ctest.Add(test.split(":")[0]) self.fref=TFile(ref.split(":")[0]) self.ftest=TFile(test.split(":")[0]) self.cref=TTree() self.fref.GetObject(ref.split(":")[1], self.cref) self.ctest=TTree() self.ftest.GetObject(test.split(":")[1], self.ctest) self.lref=load_entries( self.cref) self.ltest=load_entries( self.ctest) def Compare(self): print self.cref.GetEntries(), self.ctest.GetEntries() self.ref_min_pt_1 = 9999999999.; self.ref_min_pt_2 = 9999999999.; self.test_min_pt_1 = 9999999999.; self.test_min_pt_2 = 9999999999.; iref=0 itest=0 self.cref.LoadBaskets(2000000000) self.ctest.LoadBaskets(2000000000) while(iref<len(self.lref)): ref_id=self.lref[iref][1] while(itest<len(self.ltest)): test_id=self.ltest[itest][1] if(test_id<ref_id): self.ref_missing.append(self.ltest[itest]) elif(test_id >ref_id): self.test_missing.append(self.lref[iref]) break else: break itest+=1 if(test_id != ref_id): iref+=1 continue if(self.cref.pt_1 < self.ref_min_pt_1): self.ref_min_pt_1 = self.cref.pt_1; if(self.cref.pt_2 < self.ref_min_pt_2): self.ref_min_pt_2 = self.cref.pt_2; if(self.ctest.pt_1 < self.test_min_pt_1): self.test_min_pt_1 = self.ctest.pt_1; if(self.ctest.pt_2 < self.test_min_pt_2): self.test_min_pt_2 = self.ctest.pt_2; isGood = True self.cref.GetEntry(self.lref[iref][0]) self.ctest.GetEntry(self.ltest[itest][0]) # compare leptons if( not areEqual(self.cref.pt_1, self.ctest.pt_1) or not areEqual(self.cref.iso_1, self.ctest.iso_1) or not areEqual(self.cref.pt_2, self.ctest.pt_2) or not areEqual(self.cref.iso_2, self.ctest.iso_2) ): isGood = False; print "Event", self.lref[iref][1] print " lep1: pt=",self.cref.pt_1, self.ctest.pt_1,\ ", eta=",self.cref.eta_1,self.ctest.eta_1,\ ", phi=",self.cref.phi_1,self.ctest.phi_1,\ ", iso=",self.cref.iso_1,self.ctest.iso_1,\ ", q=",self.cref.q_1,self.ctest.q_1 print " lep2: pt=",self.cref.pt_2, self.ctest.pt_2,\ ", eta=",self.cref.eta_2,self.ctest.eta_2,\ ", phi=",self.cref.phi_2,self.ctest.phi_2,\ ", iso=",self.cref.iso_2,self.ctest.iso_2,\ ", q=",self.cref.q_2,self.ctest.q_2 refDR=deltaR(self.cref.eta_1, self.cref.phi_1, self.cref.eta_2, self.cref.phi_2) testDR=deltaR(self.ctest.eta_1, self.ctest.phi_1, self.ctest.eta_2, self.ctest.phi_2) print " deltaR(lep1, lep2)=",refDR,testDR self.bad_leptons.append((self.lref[iref],self.ltest[itest])) # compare met if( not areEqual(self.cref.met, self.ctest.met)): isGood = False; print "Event", self.lref[iref][1] print " met: |met|=",self.cref.met, self.ctest.met self.bad_met.append((self.lref[iref],self.ltest[itest])) iref+=1 itest+=1 def Print(self): print len(self.ref_missing), "Events missing in ref tree" print len(self.test_missing), "Events missing in test tree" print "Events missing in test tree:" print [x[1] for x in self.test_missing] for x in self.test_missing: self.cref.GetEntry(x[0]) print str(self.cref.run)+":"+str(self.cref.lumi)+":"+str(self.cref.evt) for x in self.ref_missing: self.ctest.GetEntry(x[0]) print str(self.ctest.run)+":"+str(self.ctest.lumi)+":"+str(self.ctest.evt) print print "Events missing in ref tree:" print [x[1] for x in self.ref_missing] print print len(self.bad_leptons), "Events with bad leptons" print [x[0][1] for x in self.bad_leptons] print print len(self.bad_met), "Events with bad pfmet" print [x[0][1] for x in self.bad_met] print self.ref_min_pt_1, self.test_min_pt_1 print self.ref_min_pt_2, self.test_min_pt_2
def recenergy(): outputfile = "EMEnergyRes" displayfile = TFile(outputfile + ".root", "RECREATE") MeanEnergyScin = array('d') MeanEnergyCher = array('d') Energy = array('d') energyfractionscin = array('d') energyfractioncher = array('d') energyfraction = array('d') resolutionscin = array('d') resolutioncher = array('d') resolution = array('d') energies = array( 'd', [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]) energies = array('d', [40, 50, 60, 70, 80, 90, 100]) energies = array('d', [5, 10, 40, 60, 80, 100, 150]) sqrtenergies = array('d', [1 / (x**0.5) for x in energies]) scin_sqrtenergies = array('d') cher_sqrtenergies = array('d') #inputfiles = sorted(glob.glob(datapath+"*"), key=os.path.getmtime) #get files from tower 1 to 75 ordered by creation time t = [5, 10, 40, 60, 80, 100, 150] inputfiles = [ "/home/software/Calo/results/newenergyscan3_noangsmearing/Electron_" + str(i) + ".root" for i in t ] for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: " + str(inputfile) + " \n" tree = TTree() inputfile.GetObject("B4", tree) ScinEnergyHist = TH1F("scinenergy_", str(counter + 1) + "_scin", 500, 0., 200.) CherEnergyHist = TH1F("cherenergy_", str(counter + 1) + "_cher", 500, 0., 200.) RecEnergyHist = TH1F("RecEnergy_", str(counter + 1) + "_Energy", 500, 0., 200.) Signalscinhist = TH1F("scintot_", str(counter + 1) + "_scin", 3000, 0., 30000) EnergyHist = TH1F("Energy_", str(counter + 1) + "_Energy", 500, 0., 200.) #loop over events for Event in range(int(tree.GetEntries())): tree.GetEntry(Event) #Set values of the tree PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name PrimaryParticleEnergy = tree.PrimaryParticleEnergy EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter Energyem = tree.Energyem # Energy deposited by the em component EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected) EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected) NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected BarrelR_VectorSignals = tree.VectorSignalsR # Vector of energy deposited in Scin fibers (Birk corrected) BarrelL_VectorSignals = tree.VectorSignalsL # Vector of energy deposited in Scin fibers (Birk corrected) BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers BarrelL_VectorSignalsCher = tree.VectorSignalsCherL VectorR = tree.VectorR VectorL = tree.VectorL totalsignalscin = sum(BarrelR_VectorSignals) + sum( BarrelL_VectorSignals) Signalscinhist.Fill(totalsignalscin) energytot = (sum(VectorR) + sum(VectorL)) / 1000 EnergyHist.Fill(energytot) #apply calibrations Calib_BarrelL_VectorSignals = calibration.calibscin( BarrelL_VectorSignals) Calib_BarrelR_VectorSignals = calibration.calibscin( BarrelR_VectorSignals) Calib_BarrelL_VectorSignalsCher = calibration.calibcher( BarrelL_VectorSignalsCher) Calib_BarrelR_VectorSignalsCher = calibration.calibcher( BarrelR_VectorSignalsCher) #end of calibrations energyscin = sum(Calib_BarrelR_VectorSignals) + sum( Calib_BarrelL_VectorSignals) energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum( Calib_BarrelL_VectorSignalsCher) ScinEnergyHist.Fill(energyscin) sigmascin = 0.15 * (energyscin**0.5) + 0.012 * energyscin CherEnergyHist.Fill(energycher) sigmacher = 0.18 * (energycher**0.5) + 0.0045 * energycher RecEnergyHist.Fill( (energyscin / (sigmascin**2) + energycher / (sigmacher**2)) / (1 / sigmascin**2 + 1 / sigmacher**2)) print energies[counter], ScinEnergyHist.GetMean( ), CherEnergyHist.GetMean() displayfile.cd() gStyle.SetOptStat(111) ScinEnergyHist.Fit("gaus") CherEnergyHist.Fit("gaus") RecEnergyHist.Fit("gaus") RecEnergyHist.Write() ScinEnergyHist.Write() CherEnergyHist.Write() Signalscinhist.Write() EnergyHist.Write() scin_sqrtenergies.append( 1. / (ScinEnergyHist.GetFunction("gaus").GetParameter(1)**0.5)) cher_sqrtenergies.append( 1. / (CherEnergyHist.GetFunction("gaus").GetParameter(1)**0.5)) MeanEnergyScin.append( ScinEnergyHist.GetFunction("gaus").GetParameter(1)) MeanEnergyCher.append( CherEnergyHist.GetFunction("gaus").GetParameter(1)) resolution.append( RecEnergyHist.GetFunction("gaus").GetParameter(2) / RecEnergyHist.GetFunction("gaus").GetParameter(1)) energyfractionscin.append( ScinEnergyHist.GetFunction("gaus").GetParameter(1)) energyfractioncher.append( CherEnergyHist.GetFunction("gaus").GetParameter(1)) energyfraction.append( RecEnergyHist.GetFunction("gaus").GetParameter(1)) resolutionscin.append( ScinEnergyHist.GetFunction("gaus").GetParameter(2) / ScinEnergyHist.GetFunction("gaus").GetParameter(1)) resolutioncher.append( CherEnergyHist.GetFunction("gaus").GetParameter(2) / CherEnergyHist.GetFunction("gaus").GetParameter(1)) LinearityGraph = TGraph(len(energies), energies, energyfraction) LinearityGraph.SetName("LinearityGraph") LinearityGraph.Write() LinearityGraphScin = TGraph(len(energies), energies, energyfractionscin) LinearityGraphCher = TGraph(len(energies), energies, energyfractioncher) LinearityGraphCher.SetName("LinearityGraphCher") LinearityGraphCher.Write() LinearityGraphScin.SetName("LinearityGraphScin") LinearityGraphScin.Write() ResolutionGraphScin = TGraph(len(energies), scin_sqrtenergies, resolutionscin) func = TF1("func", "[0]*x+[1]", 0.1, 0.45) ResolutionGraphCher = TGraph(len(energies), cher_sqrtenergies, resolutioncher) ResolutionGraphScin.Fit("func", "R") ResolutionGraphCher.Fit("func", "R") ResolutionGraphScin.SetName("ResolutionGraphScin") ResolutionGraphScin.Write() ResolutionGraphCher.SetName("ResolutionGraphCher") ResolutionGraphCher.Write() ResolutionGraph = TGraph(len(energies), sqrtenergies, resolution) ResolutionGraph.Fit("func", "R") ResolutionGraph.SetName("ResolutionGraph") ResolutionGraph.Write() rd52copper = array('d', [ 0.04478505426185217, 0.027392527130926082, 0.02420093893609386, 0.02229837387624884, 0.020999999999999998 ]) rd52graph = TGraph(len(energies), sqrtenergies, rd52copper) rd52graph.SetName("rd52resolution") rd52graph.Write() EMResolutions = TMultiGraph() EMResolutions.Add(ResolutionGraphScin) EMResolutions.Add(ResolutionGraphCher) EMResolutions.Add(ResolutionGraph) EMResolutions.Add(rd52graph) EMResolutions.SetName("EMResolutions") EMResolutions.Write() Linearities = TMultiGraph() Linearities.Add(LinearityGraph) Linearities.Add(LinearityGraphScin) Linearities.Add(LinearityGraphCher) Linearities.SetName("Linearities") Linearities.Write()
def towercalibration(): outputfile = "TowersRight" displayfile = TFile(outputfile+".root","RECREATE") MeanScin = array('d') MeanCher = array('d') RMSScin = array('d') RMSCher = array('d') Tower = array('d') EnergyTower = array('d') Zeros = array('d') errorsscin = array('d') errorscher = array('d') Energy = array('d') ResponseMeanScin = array('d') ResponseMeanCher = array('d') ResponseRMSScin = array('d') ResponseRMSCher = array('d') ResponseZeros = array('d') Responseerrorsscin = array('d') Responseerrorscher = array('d') energytot = array('d') scinsignaltot = array('d') chersignaltot = array('d') ScinSignalTot = array('d') #inputfiles = sorted(glob.glob(datapath+"*"), key=os.path.getmtime) #get files from tower 1 to 75 ordered by creation time inputfiles = ["/home/software/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)] inputfiles = ["/home/software/Calo/results/newresults/barrel1/Barrel_"+str(i)+".root" for i in range(1,76)] #inputfiles = ["/home/lorenzo/Desktop/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)] #inputfiles = ["/home/lorenzo/Desktop/Calo/results/SliceScan/Slice_"+str(i)+".root" for i in range(1,36)] #inputfiles = ["/home/lorenzo/Desktop/Calo/results/ScanInsideTower/Step_"+str(i)+".root" for i in range(0,11)] for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: "+str(inputfile)+" \n" tree = TTree() inputfile.GetObject("B4", tree) ScinHist = TH1F("scin_", str(counter+1)+"_scin", 1000, 0., 1000.) CherHist = TH1F("cher_", str(counter+1)+"_cher", 600, 0., 600.) EnergyTowerHist = TH1F("Energy_",str(counter+1)+"_Energy", 200, 0., 200.) EnergyHist = TH1F("E_", str(counter+1)+"_Energy", 200, 0., 200.) ResponseScinHist = TH1F("responsescin_", str(counter+1)+"_scin", 1000, 0., 1000.) ResponseCherHist = TH1F("responsecher_", str(counter+1)+"_cher", 600, 0., 600.) Signalscinhist = TH1F("scintot_", str(counter+1)+"_scin", 3000, 0., 30000) #loop over events for Event in range(int(tree.GetEntries())): tree.GetEntry(Event) #Set values of the tree PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name PrimaryParticleEnergy = tree.PrimaryParticleEnergy EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter Energyem = tree.Energyem # Energy deposited by the em component EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected) EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected) NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected BarrelR_VectorSignals = tree.VectorSignalsR # Vector of energy deposited in Scin fibers (Birk corrected) BarrelL_VectorSignals = tree.VectorSignalsL # Vector of energy deposited in Scin fibers (Birk corrected) BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers BarrelL_VectorSignalsCher = tree.VectorSignalsCherL VectorR = tree.VectorR VectorL = tree.VectorL signalscin = max(BarrelR_VectorSignals) signalcher = max(BarrelR_VectorSignalsCher) energytower = max(VectorR)/1000 totalenergy = (sum(VectorR)+sum(VectorL))/1000 ScinHist.Fill(signalscin/energytower) CherHist.Fill(signalcher/energytower) EnergyTowerHist.Fill(energytower) totalsignalscin = sum(BarrelR_VectorSignals)+sum(BarrelL_VectorSignals) totalsignalcher = sum(BarrelR_VectorSignalsCher)+sum(BarrelL_VectorSignalsCher) EnergyHist.Fill(totalenergy) ResponseScinHist.Fill(totalsignalscin/totalenergy) ResponseCherHist.Fill(totalsignalcher/totalenergy) Signalscinhist.Fill(totalsignalscin) energytot.append(totalenergy) scinsignaltot.append(totalsignalscin) chersignaltot.append(totalsignalcher) if list(BarrelR_VectorSignals).index(max(BarrelR_VectorSignals)) != counter+1: print "WRONG!!!!!!!!!!!" if Event < 1: print "Max found at: "+str(list(BarrelR_VectorSignals).index(signalscin))+str(list(BarrelR_VectorSignalsCher).index(signalcher))+str(list(VectorR).index(energytower*1000))+" for file "+str(counter+1) #to check tower mostly hitten is the correct one displayfile.cd() ROOTHistograms.create_eventdisplay_scin(PrimaryParticleName, BarrelR_VectorSignals, BarrelL_VectorSignals, str(counter), 0.0) ROOTHistograms.create_eventdisplay_cher(PrimaryParticleName, BarrelR_VectorSignalsCher, BarrelL_VectorSignalsCher, str(counter), 0.0) print np.mean(energytot), np.mean(scinsignaltot), np.mean(chersignaltot) displayfile.cd() gStyle.SetOptStat(111) ScinHist.Fit("gaus") CherHist.Fit("gaus") ScinHist.Write() CherHist.Write() EnergyTowerHist.Write() #MeanScin.append(ScinHist.GetFunction("gaus").GetParameter(1)) MeanScin.append(ScinHist.GetMean()) #MeanCher.append(CherHist.GetFunction("gaus").GetParameter(1)) MeanCher.append(CherHist.GetMean()) RMSScin.append(ScinHist.GetRMS()) RMSCher.append(CherHist.GetRMS()) EnergyTower.append(EnergyTowerHist.GetMean()/40.0) Energy.append(EnergyHist.GetMean()/40.) ScinSignalTot.append(Signalscinhist.GetMean()) Signalscinhist.Write() #print ScinHist.GetMean(), CherHist.GetMean(), EnergyTowerHist.GetMean() #print ScinHist.GetRMS(), CherHist.GetRMS() Tower.append(counter+1) Zeros.append(0.) errorsscin.append(ScinHist.GetRMS()/(3000**0.5)) errorscher.append(CherHist.GetRMS()/(3000**0.5)) ResponseScinHist.Fit("gaus") ResponseCherHist.Fit("gaus") ResponseScinHist.Write() ResponseCherHist.Write() #ResponseMeanScin.append(ResponseScinHist.GetFunction("gaus").GetParameter(1)) ResponseMeanScin.append(ResponseScinHist.GetMean()) #ResponseMeanCher.append(ResponseCherHist.GetFunction("gaus").GetParameter(1)) ResponseMeanCher.append(ResponseCherHist.GetMean()) ResponseRMSScin.append(ResponseScinHist.GetRMS()) ResponseRMSCher.append(ResponseCherHist.GetRMS()) Responseerrorsscin.append(ResponseScinHist.GetRMS()/(3000**0.5)) Responseerrorscher.append(ResponseCherHist.GetRMS()/(3000**0.5)) n = len(MeanCher) ScinTotGraph = TGraph(n, Tower, ScinSignalTot) ScinTotGraph.SetName("ScinTotGraph") ScinTotGraph.Write() EnergyGraph = TGraph(n, Tower, Energy) print "Energy containment: "+str(Energy) EnergyGraph.SetName("EnergyGraph") EnergyGraph.Write() EnergyTowerGraph = TGraph(n, Tower, EnergyTower) EnergyTowerGraph.SetName("EnergyTower") EnergyTowerGraph.Write() linefill36 = TF1("36gev", str(0.9), 0., 90.) linefill99 = TF1("99", str(0.99), 0., 90.) linefill99.Write() linefill36.Write() RMSGraphScin = TGraph(n, Tower, RMSScin) RMSGraphScin.SetName("Calibration_RMSGraphScin") RMSGraphCher = TGraph(n, Tower, RMSCher) RMSGraphCher.SetName("Calibration_RMSGraphCher") MeanGraphScin = TGraphErrors(n, Tower, MeanScin, Zeros, errorsscin) print "ScinCalibrations "+str(MeanScin) MeanGraphScin.SetName("Calibration_Scin") MeanGraphCher = TGraphErrors(n, Tower, MeanCher, Zeros, errorscher) print "CherCalibrations "+str(MeanCher) MeanGraphCher.SetName("Calibration_Cher") x = array('d', (0., 90., 90., 0.)) y = array('d', (np.mean(MeanScin)-0.01*np.mean(MeanScin), np.mean(MeanScin)-0.01*np.mean(MeanScin), np.mean(MeanScin)+0.01*np.mean(MeanScin), np.mean(MeanScin)+0.01*np.mean(MeanScin))) Fillgraph = TGraph(4, x, y ) Fillgraph.SetName("Calibration_banscin") linefillgraph = TF1("CalibrationMeanScin", str(np.mean(MeanScin)), 0., 90.) linefillgraph.Write() Fillgraph.Write() x2 = array('d', (0., 90., 90., 0.)) y2 = array('d', (np.mean(MeanCher)-0.01*np.mean(MeanCher), np.mean(MeanCher)-0.01*np.mean(MeanCher), np.mean(MeanCher)+0.01*np.mean(MeanCher), np.mean(MeanCher)+0.01*np.mean(MeanCher))) Fillgraph2 = TGraph(4, x2, y2 ) Fillgraph2.SetName("Calibration_bancher") linefillgraph2 = TF1("CalibrationMeanCher", str(np.mean(MeanCher)), 0., 90.) linefillgraph2.Write() Fillgraph2.Write() MeanGraphCher.Write() MeanGraphScin.Write() RMSGraphCher.Write() RMSGraphScin.Write() ResponseRMSGraphScin = TGraph(n, Tower, ResponseRMSScin) ResponseRMSGraphScin.SetName("ResponseRMSGraphScin") ResponseRMSGraphCher = TGraph(n, Tower, ResponseRMSCher) ResponseRMSGraphCher.SetName("ResponseRMSGraphCher") ResponseMeanGraphScin = TGraphErrors(n, Tower, ResponseMeanScin, Zeros, Responseerrorsscin) print "Response scin: "+str(ResponseMeanScin) ResponseMeanGraphScin.SetName("ResponseMeanGraphScin") ResponseMeanGraphCher = TGraphErrors(n, Tower, ResponseMeanCher, Zeros, Responseerrorscher) ResponseMeanGraphCher.SetName("ResponseMeanGraphCher") print "Response cher: "+str(ResponseMeanCher) x = array('d', (0., 90., 90., 0.)) y = array('d', (np.mean(ResponseMeanScin)-0.01*np.mean(ResponseMeanScin), np.mean(ResponseMeanScin)-0.01*np.mean(ResponseMeanScin), np.mean(ResponseMeanScin)+0.01*np.mean(ResponseMeanScin), np.mean(ResponseMeanScin)+0.01*np.mean(ResponseMeanScin))) Fillgraph = TGraph(4, x, y ) Fillgraph.SetName("ResponseBan_scin") linefillgraph = TF1("ResponseMeanScin", str(np.mean(ResponseMeanScin)), 0., 90.) linefillgraph.Write() Fillgraph.Write() x2 = array('d', (0., 90., 90., 0.)) y2 = array('d', (np.mean(ResponseMeanCher)-0.01*np.mean(ResponseMeanCher), np.mean(ResponseMeanCher)-0.01*np.mean(ResponseMeanCher), np.mean(ResponseMeanCher)+0.01*np.mean(ResponseMeanCher), np.mean(ResponseMeanCher)+0.01*np.mean(ResponseMeanCher))) Fillgraph2 = TGraph(4, x2, y2 ) Fillgraph2.SetName("ResponseBan_cher") linefillgraph2 = TF1("ResponseMeanCher", str(np.mean(ResponseMeanCher)), 0., 90.) linefillgraph2.Write() Fillgraph2.Write() ResponseMeanGraphCher.Write() ResponseMeanGraphScin.Write() ResponseRMSGraphCher.Write() ResponseRMSGraphScin.Write()
def jetdisplay(): outputfile = "hznb" displayfile = TFile(outputfile + ".root", "RECREATE") inputfiles = ["hznb_noleakage_029/hznb.root"] #for geant4.10.5 inputfiles = ["resultsgeant4.10.5/jetscan_leakage_X0/hznb/hznb.root"] #end of geant4.10.5 for counter, inputfile in enumerate(inputfiles): inputfile = TFile(inputfile) print "Analyzing: " + str(inputfile) + " \n" tree = TTree() inputfile.GetObject("MyTree", tree) #graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.) #graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.) #graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.) #graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.) #graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.) graphtest = TH1F("test", "test", 80, -40., 40.) graphenergy = TH1F("energy", "energy", 100, 60., 160.) graphenergytruth = TH1F("energytruth", "energytruth", 100, 60., 160.) graphjs = TH1F("energyjs", "energyjs", 200, 0., 100.) graphjc = TH1F("energyjc", "energyjc", 200, 0., 100.) #loop over events for Event in range(tree.GetEntries()): tree.GetEntry(Event) #print "Event "+str(Event) nmuon = tree.nmuon nneu = tree.nneu mjjr = tree.mjjr mjjt = tree.mjjt edep = tree.edep muene_che = tree.muene_che muene_sci = tree.muene_sci emcomp1 = tree.emcomp1 emcomp2 = tree.emcomp2 eleak = tree.eleak eleakn = tree.eleakn j1t_E = tree.j1t_E j1t_m = tree.j1t_m j1t_theta = tree.j1t_theta j1t_pt = tree.j1t_pt j1t_eta = tree.j1t_eta j1t_phi = tree.j1t_phi j2t_E = tree.j2t_E j2t_m = tree.j2t_m j2t_theta = tree.j2t_theta j2t_pt = tree.j2t_pt j2t_eta = tree.j2t_eta j2t_phi = tree.j2t_phi j1r_E = tree.j1r_E j1r_m = tree.j1r_m j1r_theta = tree.j1r_theta j1r_pt = tree.j1r_pt j1r_eta = tree.j1r_eta j1r_phi = tree.j1r_phi j2r_E = tree.j2r_E j2r_m = tree.j2r_m j2r_theta = tree.j2r_theta j2r_pt = tree.j2r_pt j2r_eta = tree.j2r_eta j2r_phi = tree.j2r_phi deltaj1 = 0.04406 * j1r_E + 0.1158 deltaj1 = 0.04135 * j1r_E + 0.08789 deltaj1 = 0.04911 * j1r_E + 0.5723 j1 = TLorentzVector() j1.SetPtEtaPhiE(j1r_pt + deltaj1 * np.sin(j1r_theta), j1r_eta, j1r_phi, j1r_E + deltaj1) deltaj2 = 0.04406 * j2r_E + 0.1158 deltaj2 = 0.04135 * j2r_E + 0.08789 deltaj2 = 0.04911 * j2r_E + 0.5723 j2 = TLorentzVector() j2.SetPtEtaPhiE(j2r_pt + deltaj2 * np.sin(j2r_theta), j2r_eta, j2r_phi, j2r_E + deltaj2) newmass = (j1 + j2).M() j1s_E = tree.j1s_E j1s_m = tree.j1s_m j1s_theta = tree.j1s_theta j1s_pt = tree.j1s_pt j1s_eta = tree.j1s_eta j1s_phi = tree.j1s_phi j2s_E = tree.j2s_E j2s_m = tree.j2s_m j2s_theta = tree.j2s_theta j2s_pt = tree.j2s_pt j2s_eta = tree.j2s_eta j2s_phi = tree.j2s_phi j1c_E = tree.j1c_E j1c_m = tree.j1c_m j1c_theta = tree.j1c_theta j1c_pt = tree.j1c_pt j1c_eta = tree.j1c_eta j1c_phi = tree.j1c_phi j2c_E = tree.j2c_E j2c_m = tree.j2c_m j2c_theta = tree.j2c_theta j2c_pt = tree.j2c_pt j2c_eta = tree.j2c_eta j2c_phi = tree.j2c_phi cut1 = nmuon == 0 and nneu == 2 cut2 = abs(j1t_eta) < 2.0 and abs(j2t_eta) < 2.0 cut3 = eleak < 3000. cut4 = j1t_E + j2t_E > 85.0 cut5 = edep > 100 if cut1 and cut2 and cut3 and cut4 and cut5: graphtest.Fill(j1r_E - j1t_E) graphtest.Fill(j2r_E - j2t_E) graphenergy.Fill(newmass) #graphenergy.Fill(j2r_E+deltaj2) #graphenergytruth.Fill(j1t_E) #graphenergytruth.Fill(j2t_E+j1t_E) graphenergytruth.Fill(mjjt) graphjs.Fill(j2s_E) graphjs.Fill(j1s_E) graphjc.Fill(j2c_E) graphjc.Fill(j1c_E) displayfile.cd() #graphtest.Write() graphenergy.Write() graphenergytruth.Write()
gr.Draw("apl") elif opt2d: nentries = tree.GetEntries() hhh.SetName(modulename) hhh.SetTitle(gtitle) if 'zAxis' in dir() and len(zAxis) > 0: hhh.GetZaxis().SetTitle(zAxis) canv.SetRightMargin(0.14) hhh.GetYaxis().SetTitle("Channel") hhh.GetXaxis().SetTitle("Module") if multi: Matrix = [[1 for y in range(48)] for x in range(64)] for i in range(nentries): tree.GetEntry(i) if vals.size() > 0: x = int(module_n[0]) y = int(channel_n[0]) Matrix[x][y] *= vals[0] sc = Matrix[modmax - 1][chanmax] if norm and Matrix[modmax - 1][chanmax] > 0 else 1 for x in range(modmin, modmax + 1): for y in range(chanmin, chanmax + 1): hhh.Fill(x, y, Matrix[x - 1][y] / sc) else: for i in range(nentries): tree.GetEntry(i) #print (("%f %f %f") % (module_n[0], channel_n[0],vals[0])) if norm:
def makeRooDataSet(type,infile_name,outfile_name,tree_name,nevents): """ Make RooDataSets from TTrees""" inputfile = TFile.Open(infile_name,"READ") print "Importing tree" tree = TTree() inputfile.GetObject(tree_name, tree) #get the tree from the data file #define variables for the RooDataSet m_mumu = RooRealVar("m_mumu", "m_mumu", 0.0, 4.0) y_mumu = RooRealVar("y_mumu", "y_mumu", 0.0, 2.0 ) pt_mumu = RooRealVar("pt_mumu", "pt_mumu", 0.0, 260.0) eta_gamma = RooRealVar("eta_gamma","eta_gamma",-3.5, 3.5) pt_gamma = RooRealVar("pt_gamma", "pt_gamma", 0.0, 100.0) m_gamma = RooRealVar("m_gamma", "m_gamma", -0.1,0.1) m_chi_rf1S = RooRealVar("m_chi_rf1S", "m_chi_rf1S", 0.0, 7.0) m_chi_rf2S = RooRealVar("m_chi_rf2S", "m_chi_rf2S", -1.0, 1.0) Qvalue = RooRealVar("Qvalue","Q", -15., 15.) ctpv = RooRealVar("ctpv","ctpv", -1.0, 3.5) ctpv_error = RooRealVar("ctpv_err","ctpv_err", -1.0, 1.0) pi0_abs_mass = RooRealVar("pi0_abs_mass","pi0_abs_mass", 0.0, 2.2) psi1S_nsigma = RooRealVar("psi1S_nsigma","psi1S_nsigma",0.0,1.0) psi2S_nsigma = RooRealVar("psi2S_nsigma","psi2S_nsigma",0.0,1.0) psi3S_nsigma = RooRealVar("psi3S_nsigma","psi3S_nsigma",0.0,1.0) rho_conv = RooRealVar("rho_conv", "rho_conv", 0.0, 70.0) dz = RooRealVar("dz","dz", -1.0, 1.0) probFit1S = RooRealVar('probFit1S','probFit1S',0,1) probFit2S = RooRealVar('probFit2S','probFit2S',0,1) probFit3S = RooRealVar('probFit3S','probFit3S',0,1) dataArgSet = RooArgSet(m_mumu, y_mumu, pt_mumu, eta_gamma, pt_gamma, m_gamma, m_chi_rf1S) dataArgSet.add( m_chi_rf2S ) dataArgSet.add( Qvalue ) dataArgSet.add( ctpv ) dataArgSet.add( ctpv_error ) dataArgSet.add( pi0_abs_mass ) dataArgSet.add( psi1S_nsigma ) dataArgSet.add( psi2S_nsigma ) dataArgSet.add( rho_conv ) dataArgSet.add( dz ) dataArgSet.add( probFit1S) dataArgSet.add( probFit2S) dataArgSet.add( probFit3S) print "Creating DataSet" dataSet = RooDataSet("chicds","Chic RooDataSet", dataArgSet) entries = tree.GetEntries() print entries if nevents is not 0: entries = nevents for ientry in range(0,entries): tree.GetEntry(ientry) # unfort ntuples are slightly different for chic and chib if applyscale: if usekinfit : spatial = tree.rf2S_photon_p4.Vect() spatial *= (1/escale) corr_photon_p4=TLorentzVector() #corr_photon_p4.SetVectM(spatial,tree.rf1S_photon_p4.M()) corr_photon_p4.SetVectM(spatial,0) corr_chi_p4 = tree.rf2S_dimuon_p4 + corr_photon_p4 else: spatial = tree.photon_p4.Vect() spatial *= (1/escale) corr_photon_p4=TLorentzVector() corr_photon_p4.SetVectM(spatial,tree.photon_p4.M()) corr_chi_p4 = tree.dimuon_p4 + corr_photon_p4 else : corr_chi_p4 = tree.chi_p4 if type == 'chic': m_mumu.setVal(tree.dimuon_p4.M()) y_mumu.setVal(tree.dimuon_p4.Rapidity()) pt_mumu.setVal(tree.dimuon_p4.Pt()) eta_gamma.setVal(tree.photon_p4.Eta()) pt_gamma.setVal(tree.photon_p4.Pt()) m_gamma.setVal(tree.photon_p4.M()) m_chi_rf1S.setVal(tree.rf1S_chi_p4.M()) m_chi_rf1S.setVal(tree.rf2S_chi_p4.M()) if usekinfit : Qvalue.setVal(corr_chi_p4.M()) else: Qvalue.setVal((corr_chi_p4).M() - tree.dimuon_p4.M()) print 'corr value ' , corr_chi_p4.M() #Qvalue.setVal((tree.chi_p4).M()**2 - tree.dimuon_p4.M()**2) psi1S_nsigma.setVal(tree.psi1S_nsigma) psi2S_nsigma.setVal(tree.psi2S_nsigma) psi3S_nsigma.setVal(0) elif type == 'chib': m_mumu.setVal(tree.dimuon_p4.M()) y_mumu.setVal(tree.dimuon_p4.Rapidity()) pt_mumu.setVal(tree.dimuon_p4.Pt()) eta_gamma.setVal(tree.photon_p4.Eta()) pt_gamma.setVal(tree.photon_p4.Pt()) m_chi_rf1S.setVal(tree.rf1S_chi_p4.M()) m_chi_rf2S.setVal(tree.rf2S_chi_p4.M()) if usekinfit : Qvalue.setVal(corr_chi_p4.M()) else: Qvalue.setVal(corr_chi_p4.M() - tree.dimuon_p4.M()) psi1S_nsigma.setVal(tree.Y1S_nsigma) psi2S_nsigma.setVal(tree.Y2S_nsigma) psi3S_nsigma.setVal(tree.Y3S_nsigma) ctpv.setVal(tree.ctpv) ctpv_error.setVal(tree.ctpv_error) pi0_abs_mass.setVal(tree.pi0_abs_mass) rho_conv.setVal(tree.conv_vertex) dz.setVal(tree.dz) probFit1S.setVal(tree.probFit1S) probFit2S.setVal(tree.probFit2S) probFit3S.setVal(tree.probFit3S) if selectchi1: if ( tree.chic_pdgId == 20443): dataSet.add(dataArgSet) else : dataSet.add(dataArgSet) outfile = TFile(outfile_name,'recreate') dataSet.Write()
def jetdisplay(): inputfile1 = "wwlj_truth.root" inputfile2 = "wwlj.root" inputfile1 = TFile(inputfile1) inputfile2 = TFile(inputfile2) print "Analyzing: " + str(inputfile1) + " \n" tree1 = TTree() tree2 = TTree() inputfile1.GetObject("truth", tree1) inputfile2.GetObject("B4", tree2) tree1.AddFriend(tree2) outputfile = "wwlj_output" displayfile = TFile(outputfile + ".root", "RECREATE") graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.) graphmass_truth = TH1F("mass_jet_truth", "mass_jet_truth", 100, 0., 200.) #loop over events for Event in range(int(10)): tree1.GetEntry(Event) #Set values of the tree numtru = tree1.mcs_n print numtru muvec = [] inputparticles_tru = [] nmuon = 0 #loop over true particles for itru in range(0, numtru): partid = tree1.mcs_pdgId[itru] #for particle depositing in calo, store them as input for jet building if abs(partid) != 13 and abs(partid) != 12 and abs( partid) != 14 and abs(partid) != 16: trup = TLorentzVector() trup.SetPtEtaPhiM(tree1.mcs_pt[itru], tree1.mcs_eta[itru], tree1.mcs_phi[itru], tree1.mcs_m[itru]) inputparticles_tru.append( fastjet.PseudoJet(trup.Px(), trup.Py(), trup.Pz(), trup.E())) #store muons in event if abs(partid) == 13: muon = TLorentzVector() muon.SetPtEtaPhiM(tree1.mcs_pt[itru], tree1.mcs_eta[itru], tree1.mcs_phi[itru], tree1.mcs_m[itru]) muvec.append(muon) nmuon = nmuon + 1 print " nmuon ", nmuon #now build truth jets jet_def = fastjet.JetDefinition(fastjet.ee_genkt_algorithm, 2 * math.pi, 1.) clust_seq = fastjet.ClusterSequence(inputparticles_tru, jet_def) jetexc = fastjet.sorted_by_E(clust_seq.exclusive_jets(int(2))) print "*********** jets ************" for jet in jetexc: print jet.e(), jet.eta(), jet.phi() print "*********** muons ************" for muon in muvec: print muon.E(), muon.Eta(), muon.Phi() jet1_truth = jetexc[0] jet2_truth = jetexc[1] j = jet1_truth + jet2_truth graphmass_truth.Fill(j.m()) # now handle calo sim BarrelR_VectorSignals = tree2.VectorSignalsR BarrelL_VectorSignals = tree2.VectorSignalsL BarrelR_VectorSignalsCher = tree2.VectorSignalsCherR BarrelL_VectorSignalsCher = tree2.VectorSignalsCherL VectorR = tree2.VectorR VectorL = tree2.VectorL Calib_BarrelL_VectorSignals = calibration.calibscin( BarrelL_VectorSignals) Calib_BarrelR_VectorSignals = calibration.calibscin( BarrelR_VectorSignals) Calib_BarrelL_VectorSignalsCher = calibration.calibcher( BarrelL_VectorSignalsCher) Calib_BarrelR_VectorSignalsCher = calibration.calibcher( BarrelR_VectorSignalsCher) energy = float( sum(Calib_BarrelR_VectorSignals) + sum(Calib_BarrelL_VectorSignals)) print " simulated energy ", energy if (energy > 0): threshold = 0.1 inputparticles_scin = [] inputparticles_cher = [] #right part for towerindex in range(75 * 36): theta, phi, eta = newmap_truth.maptower(towerindex, "right") energy_scin = Calib_BarrelR_VectorSignals[towerindex] pt_scin = energy_scin * np.sin(theta * math.pi / 180.) energy_cher = Calib_BarrelR_VectorSignalsCher[towerindex] pt_cher = energy_cher * np.sin(theta * math.pi / 180.) towerscin = TLorentzVector() towerscin.SetPtEtaPhiM(pt_scin, eta, phi * math.pi / 180., 0.) towercher = TLorentzVector() towercher.SetPtEtaPhiM(pt_cher, eta, phi * math.pi / 180., 0.) deltamumin = 999999. for muon in muvec: deltaR = abs(towerscin.DeltaR(muon)) if deltaR < deltamumin: deltamumin = deltaR if energy_scin > threshold: if deltamumin < 0.1: print " deltamumin ", deltamumin if deltamumin > 0.1: inputparticles_scin.append( fastjet.PseudoJet(towerscin.Px(), towerscin.Py(), towerscin.Pz(), towerscin.E())) inputparticles_cher.append( fastjet.PseudoJet(towercher.Px(), towercher.Py(), towercher.Pz(), towercher.E())) #left part for towerindex in range(75 * 36): theta, phi, eta = newmap_truth.maptower(towerindex, "left") energy_scin = Calib_BarrelL_VectorSignals[towerindex] pt_scin = energy_scin * np.sin(theta * math.pi / 180.) energy_cher = Calib_BarrelL_VectorSignalsCher[towerindex] pt_cher = energy_cher * np.sin(theta * math.pi / 180.) towerscin = TLorentzVector() towerscin.SetPtEtaPhiM(pt_scin, eta, phi * math.pi / 180., 0.) towercher = TLorentzVector() towercher.SetPtEtaPhiM(pt_cher, eta, phi * math.pi / 180., 0.) deltamumin = 999999. for muon in muvec: deltaR = abs(towerscin.DeltaR(muon)) if deltaR < deltamumin: deltamumin = deltaR if energy_scin > threshold: if deltamumin < 0.1: print " deltamumin ", deltamumin if deltamumin > 0.1: inputparticles_scin.append( fastjet.PseudoJet(towerscin.Px(), towerscin.Py(), towerscin.Pz(), towerscin.E())) inputparticles_cher.append( fastjet.PseudoJet(towercher.Px(), towercher.Py(), towercher.Pz(), towercher.E())) print "len: ", len(inputparticles_scin) print "lencher: ", len(inputparticles_cher) jet_def = fastjet.JetDefinition(fastjet.ee_genkt_algorithm, 2 * math.pi, 1.) clust_seq = fastjet.ClusterSequence(inputparticles_scin, jet_def) clust_seq_cher = fastjet.ClusterSequence(inputparticles_cher, jet_def) print "n jet: ", len(clust_seq.exclusive_jets(int(2))), len( clust_seq_cher.exclusive_jets(int(2))) jet1_scin = clust_seq.exclusive_jets(int(2))[0] jet2_scin = clust_seq.exclusive_jets(int(2))[1] jet1_cher = clust_seq_cher.exclusive_jets(int(2))[0] jet2_cher = clust_seq_cher.exclusive_jets(int(2))[1] #merge jet jet1, jet2 = mergejet(jet1_scin, jet2_scin, jet1_cher, jet2_cher) jet = jet1 + jet2 graphmass.Fill(jet.m()) graphmass.Write() graphmass_truth.Write()
def gettestdata(name, t1, maxs, maxc): testvector = np.array([[0, 0]]) testlabelvector = np.array([[0]]) inputfiles1 = [ "/home/lorenzo/Calo/results/Pion_25_3_2020/" + str(name) + "" + "/Pion_" + str(i) + ".root" for i in t1 ] for counter, inputfile in enumerate(inputfiles1): inputfile = TFile(inputfile) print "Analyzing: " + str(inputfile) + " \n" tree = TTree() inputfile.GetObject("B4", tree) #loop over events for Event in range(0, 50000): tree.GetEntry(Event) if Event % 10000 == 0: print "-> for predicting: ", Event #Set values of the tree PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name PrimaryParticleEnergy = tree.PrimaryParticleEnergy EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter Energyem = tree.Energyem # Energy deposited by the em component EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected) EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected) NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected BarrelR_VectorSignals = tree.VectorSignalsR # Vector of energy deposited in Scin fibers (Birk corrected) BarrelL_VectorSignals = tree.VectorSignalsL # Vector of energy deposited in Scin fibers (Birk corrected) BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers BarrelL_VectorSignalsCher = tree.VectorSignalsCherL VectorR = tree.VectorR VectorL = tree.VectorL Leak = tree.leakage NeutrinoLeak = tree.neutrinoleakage if float(t1[counter]) < 12.: cutleak = 0.5 if float(t1[counter]) > 12. and float(t1[counter]) <= 50.: cutleak = 1.0 if float(t1[counter]) > 50.: cutleak = 3.0 if (Leak / 1000. + NeutrinoLeak / 1000.) < cutleak: signalscin = sum(BarrelR_VectorSignals) + sum( BarrelL_VectorSignals) signalcher = sum(BarrelR_VectorSignalsCher) + sum( BarrelL_VectorSignalsCher) e_c = float(t1[counter]) #-(Leak/1000.+NeutrinoLeak/1000.) vector = np.array([[signalscin, signalcher]]) label = np.array([[e_c]]) testvector = np.append(testvector, vector, axis=0) testlabelvector = np.append(testlabelvector, label, axis=0) testvector = np.delete(testvector, 0, 0) testlabelvector = np.delete(testlabelvector, 0, 0) indices = np.arange(testvector.shape[0]) np.random.shuffle(indices) testvector = testvector[indices] testlabelvector = testlabelvector[indices] for i in range(len(testvector)): testvector[i][0] = testvector[i][0] / maxs testvector[i][1] = testvector[i][1] / maxc testlabelvector[i][0] = testlabelvector[i][0] / 200. return testvector, testlabelvector