def _to_root(self, data, filename): import ROOT from ROOT import TFile, TTree, gROOT, AddressOf columns = [ self._root_column(data, i, c['type'], c['name']) for i, c in enumerate(data['cols']) ] header = 'struct data_t { ' + ';'.join(columns) + '; };' gROOT.ProcessLine(header) row = ROOT.data_t() f = TFile(filename, 'RECREATE') tree = TTree('data', 'data from RHAPI') tree.Branch('data', row) for r in data['data']: for i, c in enumerate(data['cols']): v = r[i] if v is None: if c['type'] == 'NUMBER': v = -1 else: v = '' try: setattr(row, c['name'], v) except Exception as e: print(c['name'], '=', v) print(c, v) print(e) tree.Fill() tree.Print() tree.Write()
def staff(): staff = ROOT.staff_t() # The input file cern.dat is a copy of the CERN staff data base # from 1988 f = TFile('staff.root', 'RECREATE') tree = TTree('T', 'staff data from ascii file') tree.Branch('staff', staff, 'Category/I:Flag:Age:Service:Children:Grade:Step:Hrweek:Cost') tree.Branch('Divisions', AddressOf(staff, 'Division'), 'Division/C') tree.Branch('Nation', AddressOf(staff, 'Nation'), 'Nation/C') # note that the branches Division and Nation cannot be on the first branch fname = os.path.expandvars('$ROOTSYS/tutorials/tree/cernstaff.dat') for line in open(fname).readlines(): t = filter(lambda x: x, re.split('\s+', line)) staff.Category = int(t[0]) # assign as integers staff.Flag = int(t[1]) staff.Age = int(t[2]) staff.Service = int(t[3]) staff.Children = int(t[4]) staff.Grade = int(t[5]) staff.Step = int(t[6]) staff.Hrweek = int(t[7]) staff.Cost = int(t[8]) staff.Division = t[9] # assign as strings staff.Nation = t[10] tree.Fill() tree.Print() tree.Write()
def staff(): FitParam = ROOT.FitParameters_t() f = TFile("FitParam.root", "RECREATE") tree = TTree('T', "Fitparameters from main program") tree.Branch("FitParam", FitParam, 'Drift_Velocity:Fit_Gradient') fname = "test.txt" hdv = TH1F("hdv", "Drift Velocity Distribution", 100, 0.002615, 0.002645) hfg = TH1F("hfg", "Track Angle Distribution", 100, 0, 0.3) hprof = TProfile("hprof", "Profile of Drift Velocity vs Track Angle", 100, 0.002615, 0.002645, 0, 0.3) histos = ['hdv', 'hfg', 'hprof'] for name in histos: exec('%sFill = %s.Fill' % (name, name)) for line in open(fname).readlines(): t = list(filter(lambda x: x, re.split(',', line))) FitParam.Drift_Velocity = float(t[0]) FitParam.Fit_Gradient = float(t[1]) hdv.Fill(float(t[0])) hfg.Fill(float(t[1])) hprof.Fill(float(t[0]), float(t[1])) tree.Fill() c1 = TCanvas("c1", "Drift Velocity Histogram", 200, 10, 700, 500) c1.SetGridx() c1.SetGridy() hdv.Print() hdv.Draw() c1.Modified() c1.Update() c2 = TCanvas("c2", "Angular Distribution Histogram", 200, 10, 700, 500) c2.SetGrid() hfg.Print() hfg.Draw() c2.Modified() c2.Update() c3 = TCanvas("c3", "Profile", 200, 10, 700, 500) hprof.Print() hprof.Draw() c3.Modified() c3.Update() tree.Print() tree.Write() for name in histos: exec('del %sFill' % name) del histos x = input("Enter any key to continue")
def exportroot(events): try: from ROOT import TFile, TTree from array import array except: print("Unable to import ROOT") return f = TFile(args.root, 'recreate') t = TTree('t1', 'adc data') maxn = events[0].maxlen // 16 - 1 print(maxn) d1 = array('i', maxn * [0]) d2 = array('i', maxn * [0]) d3 = array('i', maxn * [0]) d4 = array('i', maxn * [0]) t.Branch('ch1', d1, 'ch1[' + str(maxn) + ']/I') t.Branch('ch2', d2, 'ch2[' + str(maxn) + ']/I') t.Branch('ch3', d3, 'ch3[' + str(maxn) + ']/I') t.Branch('ch4', d4, 'ch4[' + str(maxn) + ']/I') for event in events: #print("EVENT MAX LEN: ", event.maxlen//16) if 16 in event.wave: #for key, value in event.wave.items() : # print (key, value) for j in range(event.maxlen // 16 - 1): #print(event.wave[16].size) d1[j] = event.wave[16][j] # print d1[j] d2[j] = event.wave[17][j] d3[j] = event.wave[18][j] d4[j] = event.wave[19][j] # print d1 t.Fill() t.Print() #t.Show(0) #t.Show(1) #t.Show(2) #t.Show(3) #t.Scan("*") f.Write() f.Close()
def fitsToRoot(): # Create root file and tree f = TFile(path_root + "GRID_2008_2015.root", "RECREATE") tree = TTree("data_GRID", "data_GRID") obt = array('d', [0]) tree.Branch('obt', obt, 'obt/D') contact = array('I', [0]) tree.Branch('contact', contact, 'contact/I') filenames = filesInFolderAsList(path) c = 0 for name in filenames: c = c + 1 print str(c) + "/" + str(len(filenames)) # open fits file hdulist = fits.open(path + name) #hdulist.info() #print(hdulist['EVENTS'].columns) # Get table inside EVENTS event_data = Table(hdulist['EVENTS'].data) #print(event_data['TIME']) contact[0] = int(name[3:9]) print contact[0] #Iterate through tabel and append TIME to tree for row in event_data: obt[0] = (row['TIME']) #if (354153660 - 60) < obt[0] and obt[0] < (362102460 + 60): tree.Fill() hdulist.close() #tree.Scan("","","col=20.6f") tree.Print() tree.Show(0) #tree.Scan("obt","", "col=20.6f") tree.GetCurrentFile().Write() tree.GetCurrentFile().Close()
uncM = array.array("f", [0]) uncVZ = array.array("f", [0]) events.Branch("uncM", uncM, "uncM/F") events.Branch("uncVZ", uncVZ, "uncVZ/F") #for i in range(int(h_zvm.GetEntries())): # events.GetEntry(i) # events.Fill() for i in range(h_zvm.GetNbinsX()): uncM[0] = h_zvm.GetXaxis().GetBinCenter(i + 1) for j in range(h_zvm.GetNbinsY()): uncVZ[0] = h_zvm.GetYaxis().GetBinCenter(j + 1) for k in range(int(h_zvm.GetBinContent(i + 1, j + 1))): events.Fill() events.Print() outrootfile.Write() #outrootfile.Close() #events = inFile.Get("cut") #events.Print() events.Draw("uncVZ:{0}>>hnew(100,0,0.1,100,-60,60)".format(massVar), "", "colz") gDirectory.Get("hnew").SetTitle("vertexing data") gDirectory.Get("hnew").GetXaxis().SetTitle("mass [GeV]") gDirectory.Get("hnew").GetYaxis().SetTitle("vertex z [mm]") c.Print(remainder[0] + ".pdf") gStyle.SetOptStat(1111) effFile = remainder[2] #acceptanceFile = TFile(remainder[2])
class ntupleMake: Version = 2.6 __Validated__ = False outputFilename="" __muMass = muCnst.mass()/1000. __piMass = piCnst.mass()/1000. # built-in methods def __init__(self, runNum, nuPrdStrt, outputFilename="nuStorm.root"): # first a TTree with the run information - written once self.outputFilename = outputFilename self.outfile = TFile( self.outputFilename, 'RECREATE', 'ROOT file with an NTuple' ) # first a TTree with the run information - written once self.runInfo = ROOT.information() self.infoTree = TTree('runInfo', 'run information') self.infoTree.Branch( 'information', self.runInfo, 'runNumber/F:Version:FluxPlaneW:FluxPlaneH:PZ:DetectW:DetecH:DetecD:DetecZ:Emit') # self.infoTree.Branch( 'Flux Plane', AddressOf( self.runInfo, 'PWidth'), 'Width/F:Height:Z') # self.infoTree.Branch( 'Detector Box', AddressOf( self.runInfo, 'DBWidth'), 'Width/F:Height:Depth:Z') # Parameters for the run self.runInfo.runNumber = runNum self.runInfo.Version = self.Version # Parameters for the flux plane self.runInfo.PWidth = 10.0 self.runInfo.PHeight = 10.0 self.runInfo.PZ = nuPrdStrt.HallWallDist() # Parameters for the detector box self.runInfo.DBWidth = nuPrdStrt.DetHlfWdth()*2.0 self.runInfo.DBHeight = nuPrdStrt.DetHlfWdth()*2.0 self.runInfo.DBDepth = nuPrdStrt.DetLngth() self.runInfo.DBZ = nuPrdStrt.Hall2Det() self.emittanceUnits = 'mm' self.infoTree.Fill() self.infoTree.Write() # a TTree for the production data from every event self.event = ROOT.event_t() self.evTree = TTree('beam', 'nuStorm Event') self.evTree.Branch( 'pion', self.event, 'E/F:pX:pY:pZ' ) self.evTree.Branch( 'muon', addressof( self.event, 'Emu'), 'E/F:pX:pY:pZ' ) self.evTree.Branch( 'Decay', addressof( self.event, 's'), 's/F:x:y:z:xp:yp:t') self.evTree.Branch( 'Electron', addressof( self.event, 'Ee'), 'E/F:pX:pY:pZ') self.evTree.Branch( 'NuMu', addressof( self.event, 'Enumu'), 'E/F:pX:pY:pZ') self.evTree.Branch( 'Nue', addressof( self.event, 'Enue'), 'E/F:pX:pY:pZ') # a TTree for the flux data self.flux = ROOT.flux_t() self.fluxTree = TTree('flux', 'nuStorm Event') self.fluxTree.Branch( 'NuE', addressof( self.flux, 'nuEx'), 'x/F:y:px:py:pz:E') self.fluxTree.Branch( 'NuMu', addressof( self.flux, 'nuMux'), 'x/F:y:px:py:pz:E') def __repr__(self): return "make an TTree" def __str__(self): return "ntuple Maker: outputFilename = %s" \ % \ (self.outputFilename) def treeFill(self, nuEvt): # tracespace coordinates of the decay point self.event.s = nuEvt.getTraceSpaceCoord()[0] self.event.x = nuEvt.getTraceSpaceCoord()[1] self.event.y = nuEvt.getTraceSpaceCoord()[2] self.event.z = nuEvt.getTraceSpaceCoord()[3] self.event.xp = nuEvt.getTraceSpaceCoord()[4] self.event.yp = nuEvt.getTraceSpaceCoord()[5] self.event.t = 0.0; # get the 4 vector of the muon. In fact Emu ~ Pmu ~ PMuz - but calculate precisely pMu = nuEvt.getpmuGen() self.event.Emu = np.sqrt(pMu*pMu + self.__muMass**2) pBeam = nuEvt.getPb() self.event.pMuX = pBeam[0] self.event.pMuY = pBeam[1] self.event.pMuZ = pBeam[2] # get the 4 vector of the electron self.event.Ee = nuEvt.gete4mmtm()[0] self.event.peX = nuEvt.gete4mmtm()[1][0] self.event.peY = nuEvt.gete4mmtm()[1][1] self.event.peZ = nuEvt.gete4mmtm()[1][2] # get the 4 vector of the muon neutrino self.event.Enumu = nuEvt.getnumu4mmtm()[0] self.event.pnumuX = nuEvt.getnumu4mmtm()[1][0] self.event.pnumuY = nuEvt.getnumu4mmtm()[1][1] self.event.pnumuZ = nuEvt.getnumu4mmtm()[1][2] # get the 4 vector of the electron neutrino self.event.Enue = nuEvt.getnue4mmtm()[0] self.event.pnueX = nuEvt.getnue4mmtm()[1][0] self.event.pnueY = nuEvt.getnue4mmtm()[1][1] self.event.pnueZ = nuEvt.getnue4mmtm()[1][2] self.evTree.Fill() # fill the tree from a pion flash decau def pionTreeFill(self, piEvt): # tracespace coordinates of the decay point self.event.s = piEvt.getTraceSpaceCoord()[0] self.event.x = piEvt.getTraceSpaceCoord()[1] self.event.y = piEvt.getTraceSpaceCoord()[2] self.event.z = piEvt.getTraceSpaceCoord()[3] self.event.xp = piEvt.getTraceSpaceCoord()[4] self.event.yp = piEvt.getTraceSpaceCoord()[5] self.event.t = 0.0; # get the 4 vector of the decay muon. self.event.Emu = piEvt.getmu4mmtm()[0] self.event.pMuX = piEvt.getmu4mmtm()[1][0] self.event.pMuY = piEvt.getmu4mmtm()[1][1] self.event.pMuZ = piEvt.getmu4mmtm()[1][2] # get the 4 vector of the pion pPion = piEvt.getppiGen() self.event.Epi = np.sqrt(pPion*pPion + self.__piMass**2) self.event.pPiX = pPion*self.event.xp self.event.pPiY = pPion*self.event.yp self.event.pPiZ = np.sqrt(pPion*pPion - self.event.peX**2 - self.event.peY**2) # get the 4 vector of the muon neutrino self.event.Enumu = piEvt.getnumu4mmtm()[0] self.event.pnumuX = piEvt.getnumu4mmtm()[1][0] self.event.pnumuY = piEvt.getnumu4mmtm()[1][1] self.event.pnumuZ = piEvt.getnumu4mmtm()[1][2] self.evTree.Fill() def fluxFill(self, hitE, hitMu): self.flux.nuEx = hitE[0] self.flux.nuEy = hitE[1] self.flux.nuEpx = hitE[5] self.flux.nuEpy = hitE[6] self.flux.nuEpz = hitE[7] self.flux.nuEE = hitE[8] self.flux.nuMux = hitMu[0] self.flux.nuMuy = hitMu[1] self.flux.nuMupx = hitMu[5] self.flux.nuMupy = hitMu[6] self.flux.nuMupz = hitMu[7] self.flux.nuMuE = hitMu[8] self.fluxTree.Fill() # # Fill the flux branch from pion flash run - just remove the electron code def flashFluxFill(self, hitMu): self.flux.nuMux = hitMu[0] self.flux.nuMuy = hitMu[1] self.flux.nuMupx = hitMu[5] self.flux.nuMupy = hitMu[6] self.flux.nuMupz = hitMu[7] self.flux.nuMuE = hitMu[8] self.fluxTree.Fill() def output(self): # Write out the data self.evTree.Write() self.fluxTree.Write() return def closeFile(self): self.evTree.Print() self.evTree.Write() self.fluxTree.Print() self.fluxTree.Write() return def initNtuple(self, labels): self.ntuple = TNtuple( 'ntuple', ' nuStorm source', ':'.join( labels ) ) if self.__Validated__: print ("ntuple is ", self.ntuple) return
t_in.SetBranchAddress("MET",_MET) t_in.SetBranchAddress("weight",_weight) #t_in.SetBranchAddress("Wmass",_Wmass) # looping through events: # Signal: for i in range(0,t_in.GetEntries()): t_in.GetEntry(i) pi_pT_array[0] = _pi_pT gamma_eT_array[0] = _gamma_eT nBjets_25_array[0] = _nBjets_25 lep_pT_array[0] = _lep_pT piRelIso_05_ch_array[0] = _piRelIso_05_ch MET_array[0] = _MET weight_array[0] = _weight # Wmass_array[0] = _Wmass if isMuon: _BDT_output[0] = reader.EvaluateMVA("BDT_mu") else: _BDT_output[0] = reader.EvaluateMVA("BDT_ele") t_out.Fill() # Write trees to root file t_out.Print() fOut.Write() fOut.Close() del reader
def FitHistsGetEffic(hist_fname, fit_out_fname, MIN_E, MAX_E, E_STEP, scale_factor): E_arr = array('d', []) E_arr_err = array('d', []) effic_arr = array('d', []) effic_arr_err = array('d', []) norm_arr = array('d', []) curr_E_val = MIN_E while curr_E_val <= MAX_E + 0.0001: E_arr.append(curr_E_val) if (NORMALIZE_EXTERNAL): E_arr_err.append(0) if (not NORMALIZE_EXTERNAL): E_arr_err.append(E_STEP / 2.) curr_E_val += E_STEP c1 = TCanvas("c1", "c1", 1600, 900) c1.SetGridx(1) c1.SetGridy(1) #Get normalization from external files assuming matching directory scheme for embedded photon gun data if (NORMALIZE_EXTERNAL): #Get normalization curr_E_val = MIN_E while curr_E_val <= MAX_E + 0.0001: print "Getting normalization for energy value: " + str(curr_E_val) thisfile_string = NORM_BASE_DIR + str( curr_E_val) + "/" + NORM_FILENAME if (not os.path.isfile(thisfile_string)): print "file not found, normalization will be 0: " + thisfile_string norm_arr.append(0.) curr_E_val += E_STEP continue normfile = TFile.Open(thisfile_string, 'read') my_tr = TTree() my_tr.Print() my_tr = normfile.Get(NORM_TREENAME) norm_arr.append(my_tr.GetEntries()) curr_E_val += E_STEP #Done getting normalization # Get normalization from same root file f_in = TFile.Open(hist_fname) #Open rootfile if (not NORMALIZE_EXTERNAL): for i in range(0, len(E_arr)): E_cut_str = str(E_arr[i] - E_STEP / 2.) + "<ThrownE&&ThrownE<" + str( E_arr[i] + E_STEP / 2.) + "&&ThrownTheta<9&&ThrownTheta>4" h_curr = f_in.Get("h_EThrown_" + E_cut_str) norm_arr.append(h_curr.GetEntries() / scale_factor) #Fit stuff for i in range(0, len(E_arr)): h_curr = TH1F() E_cut_str = str(E_arr[i] - E_STEP / 2.) + "<ThrownE&&ThrownE<" + str( E_arr[i] + E_STEP / 2.) + "&&ThrownTheta<9&&ThrownTheta>4" if (NORMALIZE_EXTERNAL): h_curr = f_in.Get("h_EGammaPostCuts_" + str(E_arr[i])) if (not NORMALIZE_EXTERNAL): h_curr = f_in.Get("h_EGammaPostCuts_" + E_cut_str) curr_E_val = E_arr[i] norm_count = norm_arr[i] if (norm_count < MIN_EVENTS): effic_arr.append(-1) effic_arr_err.append(0) continue my_gaus_fit = TF1("my_gaus_fit", "gausn", 0.001, 3.) my_gaus_fit.SetParLimits(0, 0, 10000) my_gaus_fit.SetParLimits(1, curr_E_val - 0.2, curr_E_val + 0.1) my_gaus_fit.SetParLimits(2, 0.005, 0.4) my_gaus_fit.SetNpx(1000) h_curr.GetXaxis().SetRangeUser(curr_E_val - 1.2, curr_E_val + 0.5) h_curr.Fit(my_gaus_fit, "Q", "", curr_E_val - E_BELOWTHROWN_TOFIT, curr_E_val + E_ABOVETHROWN_TOFIT) h_curr.Fit(my_gaus_fit, "QL", "", curr_E_val - E_BELOWTHROWN_TOFIT, curr_E_val + E_ABOVETHROWN_TOFIT) if (POLY_ORDER >= 1): gaus_fit_amplitude = my_gaus_fit.GetParameter(0) gaus_fit_mean = my_gaus_fit.GetParameter(1) gaus_fit_sigma = my_gaus_fit.GetParameter(2) gaus_plus_poly_fit = TF1("gaus_plus_poly_fit", "gausn+pol" + str(POLY_ORDER) + "(3)", 0.001, 3.) gaus_plus_poly_fit.SetParameter(0, gaus_fit_amplitude) gaus_plus_poly_fit.SetParameter(1, gaus_fit_mean) gaus_plus_poly_fit.SetParameter(2, gaus_fit_sigma) gaus_plus_poly_fit.SetParLimits(0, 0, 10000) gaus_plus_poly_fit.SetParLimits(1, curr_E_val - 0.2, curr_E_val + 0.1) gaus_plus_poly_fit.SetParLimits(2, 0.005, 0.4) h_curr.Fit(gaus_plus_poly_fit, "Q", "", curr_E_val - E_BELOWTHROWN_TOFIT, curr_E_val + E_ABOVETHROWN_TOFIT) h_curr.Fit(gaus_plus_poly_fit, "QL", "", curr_E_val - E_BELOWTHROWN_TOFIT, curr_E_val + E_ABOVETHROWN_TOFIT) c1.SaveAs(".plots/FitE_" + str(curr_E_val) + ".png") effic_arr.append( (my_gaus_fit.GetParameter(0) / h_curr.GetBinWidth(0)) / norm_count) effic_arr_err.append( my_gaus_fit.GetParError(0) / h_curr.GetBinWidth(0) / norm_count) gr_gauscore_effic = TGraphErrors(len(E_arr), E_arr, effic_arr, E_arr_err, effic_arr_err) gr_gauscore_effic.SetMarkerStyle(15) gr_gauscore_effic.SetMarkerSize(1.2) gr_gauscore_effic.SetMarkerColor(kBlue) gr_gauscore_effic.SetName("gr_gauscore_effic") f_out = TFile(fit_out_fname, "RECREATE") f_out.cd() gr_gauscore_effic.Write() f_out.Close()
else: _BDT_output[0] = reader.EvaluateMVA("BDT_ele") tsig_out.Fill() # Background: for i in range(0,tbkg_in.GetEntries()): tbkg_in.GetEntry(i) pi_pT_array[0] = _pi_pT gamma_eT_array[0] = _gamma_eT nBjets_25_array[0] = _nBjets_25 lep_pT_array[0] = _lep_pT piRelIso_05_ch_array[0] = _piRelIso_05_ch MET_array[0] = _MET weight_array[0] = _weight Wmass_array[0] = _Wmass if isMuon: _BDT_output[0] = reader.EvaluateMVA("BDT_mu") else: _BDT_output[0] = reader.EvaluateMVA("BDT_ele") tbkg_out.Fill() # Write trees to root file tsig_out.Print() tbkg_out.Print() fOut.Write() fOut.Close() del reader