def do_toymc(self, sigtree, hrec, hout0): print('We are doing toy mc...') if self.ntoys < 0: print('WARNING: ntoys < 0, set it to 1') self.ntoys = 1 nevents = int(hrec.Integral()) list_hout = [] toymcfile = TFile('toymcfile.root', 'recreate') for itoy in range(self.ntoys): print('doing toymc ', itoy, '...') datatree = TTree(self.data_treename, 'toymc_' + str(itoy)) mrec = array('f', [0]) datatree.Branch('mrec', mrec, 'mrec/F') for i in range(nevents): mrec[0] = hrec.GetRandom() datatree.Fill() datatree.Write() x, hout, binning = self.unfold_core(sigtree, datatree, self.nsplit, dotoymc=1) list_hout.append(hout) if self.debug or 0: self.showhist(hout0) for hout in list_hout: print('toymc results', hout) self.showhist(hout) self.Vx = self.get_newVx_from_toymc(hout0, list_hout) toymcfile.Close()
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 main(): args = sys.argv[1:] if len(args)==5: file_in = args[0] file_out = args[1] ecms = float(args[2]) D_sample = args[3] sample_type = args[4] elif len(args)==6: file_in = args[0] file_out = args[1] ecms = float(args[2]) D_sample = args[3] D_type = args[4] sample_type = args[5] else: return usage() f_in = TFile(file_in) f_out = TFile(file_out, 'recreate') t_out = TTree('save', 'save') cms = TLorentzVector(0.011*ecms, 0, 0, ecms) if sample_type == 'raw': save_raw(f_in, cms, t_out, D_sample) if sample_type == 'signal' or sample_type == 'background': save_missing(f_in, cms, t_out, D_sample, D_type, sample_type) f_out.cd() t_out.Write() f_out.Close()
def makeEMSTree(dirname, fname): print dirname ifname = dirname.rstrip("/") + "/" + fname + ".txt" if len(dirname.split("/")) > 1: outdir = "root/" + dirname.split('/')[1] else: outdir = "root" try: os.makedirs(outdir) except: pass ofname = outdir + "/" + fname + ".root" print ofname #output file and tree outfile = TFile(ofname, "RECREATE") tree = TTree("tree", "tree of " + fname) #create tree from text file # Raw formats: desc = "time:amplitude:area:areaFromScope" tree.ReadFile(ifname, desc) # delimiter = space #tree.ReadFile(ifname,desc,",") # delimiter = comma #save output tree outfile.cd() tree.Write() outfile.Close() #print message print "Created tree in root file: %s" % ofname
def createTrees(hist_cfg, out_dir, verbose=False, friend_func=None): '''Writes out TTrees from histogram configuration for each contribution. Takes list of variables attached to histogram config (hist_cfg.vars) to create branches. ''' plot = DataMCPlot(hist_cfg.name) # Used to cache TTrees vcfgs = hist_cfg.vars for cfg in hist_cfg.cfgs: out_file = TFile('/'.join([out_dir, hist_cfg.name + '_' + cfg.name + '.root']), 'RECREATE') out_tree = TTree('tree', '') # Create branches for all variables branches = [array('f', [0.]) for i in xrange(len(vcfgs))] for branch_name, branch in zip([v.name for v in vcfgs], branches): out_tree.Branch(branch_name, branch, branch_name+'/F') # Create branch with full weight including lumi x cross section full_weight = array('f', [0.]) out_tree.Branch('full_weight', full_weight, 'full_weight/F') branches.append(full_weight) total_scale = hist_cfg.total_scale if hist_cfg.total_scale else 1. fillIntoTree(out_tree, branches, cfg, hist_cfg, vcfgs, total_scale, plot, verbose, friend_func) out_file.cd() out_tree.Write() out_file.Write() out_file.Close() return plot
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 WriteTree(runSet): print 'Writing tree' # Make a tree froot = TFile('mu.root', 'RECREATE') tree = TTree("mu", "Flat ntuple for mu") tree.SetDirectory(froot) leaves = "run/F:lb/F:mu/F" leafValues = array("f", [0.0, 0.0, 0.0]) newBranch = tree.Branch("mu_vars", leafValues, leaves) for r, lbs in runSet.iteritems(): for i in range(lbs.FirstLB(), lbs.LastLB()): leafValues[2] = lbs.GetMeanPileUp(i) leafValues[0] = float(r) leafValues[1] = i print 'mu: %s run: %s lb: %s' % (leafValues[2], leafValues[0], leafValues[1]) tree.Fill() tree.Write() #froot.Write() froot.Close()
def splitTree(): dsNum, subNum = 0, 25 inPath = "/global/homes/w/wisecg/project/waveskim/waveSkimDS%d_%d.root" % (dsNum, subNum) outPath = "./cutSkimDS%d_%d.root" % (dsNum, subNum) inFile = TFile(inPath) bigTree = inFile.Get("skimTree") theCut = inFile.Get("theCut").GetTitle() bigTree.Draw(">>elist",theCut,"entrylist") elist = gDirectory.Get("elist") bigTree.SetEntryList(elist) nList = elist.GetN() outFile = TFile(outPath,"RECREATE") lilTree = TTree() lilTree.SetMaxTreeSize(150000000) lilTree = bigTree.CopyTree("") lilTree.Write("",TObject.kOverwrite) thisCut = TNamed("theCut",theCut) thisCut.Write()
def convert(path_in, path_out, mode): for i in xrange(len(path_in)): try: f_in = TFile(path_in[i]) t_in = f_in.Get('save') entries = t_in.GetEntries() logging.info(mode[i] + ' entries :' + str(entries)) except: logging.error(path_in[i] + ' is invalid!') sys.exit() print '--> Begin to process file: ' + path_in[i] f_out = TFile(path_out[i], 'RECREATE') t_out = TTree('save', 'save') m_rm_D = array('d', [999.]) t_out.Branch('rm_D', m_rm_D, 'm_rm_D/D') nentries = t_in.GetEntries() for ientry in xrange(nentries): t_in.GetEntry(ientry) m_rm_D[0] = t_in.m_rm_D t_out.Fill() m_rm_D[0] = t_in.m_rm_Dmiss t_out.Fill() f_out.cd() t_out.Write() f_out.Close() print '--> End of processing file: ' + path_out[i]
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 loadDataMJD(): """ RooFit can't handle the vector<double> format for energies. So save a few select branches only (can add branches if necessary) into a new file. """ dsNum = 1 ch = TChain("skimTree") # ch.Add("~/project/cuts/fs/fitSlo-DS%d-*.root" % dsNum) ch.Add("~/project/cuts/fs_rn/fs_rn-DS%d-*.root" % dsNum) # ch.Add("~/project/cuts/fs_rn_wf/fs_rn_wf-DS%d-*.root" % dsNum) # ch.Add("~/project/cuts/fs_wf/fs_wf-DS%d-*.root" % dsNum) # ch.Add("~/project/cuts/rn/riseNoise-DS%d-*.root" % dsNum) # ch.Add("~/project/cuts/rn_wf/rn_wf-DS%d-*.root" % dsNum) # ch.Add("~/project/cuts/wf/wfstd-DS%d-*.root" % dsNum) fOut = TFile("./data/mjd_data.root", "RECREATE") tOut = TTree("skimTree", "skimTree") run = array('i', [0]) iEvent = array('i', [0]) iHit = array('i', [0]) channel = array('i', [0]) trapENFCal = array('d', [0.]) weight = array('d', [0.]) isEnr = array('i', [0]) tOut.Branch("run", run, "run/I") tOut.Branch("iEvent", iEvent, "iEvent/I") tOut.Branch("iHit", iHit, "iHit/I") tOut.Branch("channel", channel, "channel/I") tOut.Branch("trapENFCal", trapENFCal, "trapENFCal/D") tOut.Branch("weight", weight, "weight/D") tOut.Branch("isEnr", isEnr, "isEnr/I") for iEvt in range(ch.GetEntries()): ch.GetEntry(iEvt) run[0] = ch.run iEvent[0] = ch.iEvent for iH in range(ch.channel.size()): iHit[0] = ch.iHit.at(iH) channel[0] = ch.channel.at(iH) trapENFCal[0] = ch.trapENFCal.at(iH) weight[0] = 1. if "P" in ch.detName.at(iH): isEnr[0] = 1 elif "B" in ch.detName.at(iH): isEnr[0] = 0 else: print "WTF, error" exit(0) tOut.Fill() tOut.Write() fOut.Close() # verify f2 = TFile("./data/mjd_data.root") t2 = f2.Get("skimTree") t2.Scan("run:channel:isEnr:trapENFCal")
def make_prim_tree(): #input #inp = TFile.Open("../../lmon.root") inp = TFile.Open("../../data/ew/ew1bx1.root") tree = inp.Get("DetectorTree") #number of events, negative for all nev = -1 #output out = TFile("prim_bx1.root", "recreate") gROOT.ProcessLine("struct EntryF {Float_t v;};") x = rt.EntryF() y = rt.EntryF() z = rt.EntryF() en = rt.EntryF() otree = TTree("prim_tree", "prim_tree") otree.Branch("x", addressof(x, "v"), "x/F") otree.Branch("y", addressof(y, "v"), "y/F") otree.Branch("z", addressof(z, "v"), "z/F") otree.Branch("en", addressof(en, "v"), "en/F") hits = ew_hits("ew", tree) if nev < 0: nev = tree.GetEntries() for ievt in range(nev): tree.GetEntry(ievt) #print("Next event") for ihit in range(hits.get_n()): hit = hits.get_hit(ihit) #hit by primary photon if hit.prim == 0 or hit.pdg != 22: continue hit.global_to_zpos(-18644) # mm x.v = hit.x y.v = hit.y z.v = hit.z z.en = hit.en otree.Fill() #print(hit.x, hit.y, hit.z) # , hit.en #print(hit.pdg, hit.prim, hit.conv) #only first hit by primary particle break otree.Write() out.Close()
def splitFile(inPath, outPath): """ ./job-panda.py -splitf [inPath] [outPath] Used by specialSplit. """ from ROOT import TFile, TTree, TObject inFile = TFile(inPath) bigTree = inFile.Get("skimTree") outFile = TFile(outPath, "RECREATE") lilTree = TTree() lilTree.SetMaxTreeSize(30000000) # 30MB lilTree = bigTree.CopyTree("") lilTree.Write("", TObject.kOverwrite)
def simpleCopy(): # inFile = TFile("/global/homes/w/wisecg/project/bg-lat/latSkimDS1_0_0.root") inFile = TFile("/Users/wisecg/project/bg-lat/latSkimDS1_0_0.root") skimTree = inFile.Get("skimTree") outFile = TFile("test.root", "RECREATE") outTree = TTree() outTree = skimTree.CopyTree("") outTree.Write() outFile.Close()
def splitTree(dsNum, subNum=None, runNum=None): """ ./job-panda.py -split (-sub dsNum subNum) (-run dsNum runNum) Split a SINGLE waveSkim file into small (~50MB) files to speed up LAT parallel processing. Can call 'batchSplit' instead to submit each run in the list as a job, splitting the files in parallel. NOTE: The cut written into the first file is NOT copied into the additional files (I couldn't get it to work within this function -- kept getting "file not closed" errors.) To clean up, do that with the 'writeCut' function below, potentially AFTER a big parallel job. """ from ROOT import TFile, TTree, gDirectory, TEntryList, TNamed, TObject, gROOT print("Splitting tree. dsNum:", dsNum, "subNum:", subNum, "runNum:", runNum) # Set input and output paths. Clear out any files from a previous # try before you attempt a copy (avoid the double underscore) inPath, outPath = "", "" if runNum == None: # bg mode inPath = "%s/waveSkimDS%d_%d.root" % (dsi.waveDir, dsNum, subNum) outPath = "%s/splitSkimDS%d_%d.root" % (dsi.splitDir, dsNum, subNum) fileList = sorted( glob.glob("%s/splitSkimDS%d_%d*.root" % (dsi.splitDir, dsNum, subNum))) for f in fileList: os.remove(f) elif subNum == None: # cal mode inPath = "%s/waveSkimDS%d_run%d.root" % (dsi.calWaveDir, dsNum, runNum) outPath = "%s/splitSkimDS%d_run%d.root" % (dsi.calSplitDir, dsNum, runNum) fileList = sorted( glob.glob("%s/splitSkimDS%d_run%d*.root" % (dsi.calSplitDir, dsNum, runNum))) for f in fileList: os.remove(f) inFile = TFile(inPath) bigTree = inFile.Get("skimTree") theCut = inFile.Get("theCut").GetTitle() bigTree.Draw(">>elist", theCut, "entrylist") elist = gDirectory.Get("elist") bigTree.SetEntryList(elist) nList = elist.GetN() outFile = TFile(outPath, "RECREATE") lilTree = TTree() lilTree.SetMaxTreeSize(50000000) # 50 MB thisCut = TNamed("theCut", theCut) thisCut.Write("", TObject.kOverwrite) lilTree = bigTree.CopyTree( "") # this does NOT write the cut into the extra files lilTree.Write("", TObject.kOverwrite)
def plot_xsec_contour(sample): output_file_name = "lhe.root" output_file = TFile(output_file_name, "RECREATE") output_tree = TTree("Physics", "Physics") gROOT.ProcessLine( "struct MyStruct{ Float_t xsec; Float_t mdm; Float_t mhs; Float_t mzp; Float_t whs; Float_t wzp; };" ) from ROOT import MyStruct s = MyStruct() output_tree.Branch('xsec', AddressOf(s, 'xsec'), 'xsec/F') output_tree.Branch('mdm', AddressOf(s, 'mdm'), 'mdm/F') output_tree.Branch('mhs', AddressOf(s, 'mhs'), 'mhs/F') output_tree.Branch('mzp', AddressOf(s, 'mzp'), 'mzp/F') output_tree.Branch('whs', AddressOf(s, 'whs'), 'whs/F') output_tree.Branch('wzp', AddressOf(s, 'wzp'), 'wzp/F') for i, su in enumerate(sample): s.xsec = 0. s.mdm = 0. s.mhs = 0. s.mzp = 0. s.whs = 0. s.wzp = 0. with open('../samples/' + su + '.lhe', "rt") as fin: for line in fin: if "Integrated weight (pb)" in line: #print line.split(' ')[-1] s.xsec = float(line.split(' ')[-1]) if "# mdm" in line: #print line.split(' ')[-3] s.mdm = float(line.split(' ')[-3]) if "# mhs" in line: #print line.split(' ')[-3] s.mhs = float(line.split(' ')[-3]) if "# mzp" in line: #print line.split(' ')[-3] s.mzp = float(line.split(' ')[-3]) #hs if "DECAY 54" in line: #print line.split(' ')[-1] s.whs = float(line.split(' ')[-1]) #zp if "DECAY 55" in line: #print line.split(' ')[-1] s.wzp = float(line.split(' ')[-1]) output_tree.Fill() output_tree.Write() output_file.Close() #plot contour gROOT.Macro('Contour.C("lhe.root","BBbarDM_hs50")')
def skim_data(wk): """ run this automatically w/ process() apply energy thresholds to create reduced size "skim" ROOT files for faster plotting --> output files: "./data/skim/week_{}.root" """ wk = "4" out_name = "./data/skim/week_{}.root".format(wk) # load metadata runs = run_info["runs"][wk] chans = run_info["goodres_chans"][wk] thresh = run_info["thresholds"][wk] # build a ROOT TCut string print("Skimming data from week", wk, "run list:", runs) cut = "(" for chan in chans: cut += "(Channel=={} && Energy>{}) || ".format(chan, thresh[int(chan)]) cut = cut[:-4] cut += ")" print(" Using cut:", cut) # load data files = [] for r in runs: # handle runs where we have multiple subfiles (_x.root) tmp = glob.glob("./data/run_{}/FILTERED/compassF_run_{}*.root".format( r, r)) files.extend(tmp) runtime = 0 ch = TChain("Data_F") for f in sorted(files): runtime += get_runtime(f) ch.Add(f) print(" Data loaded. Found", ch.GetEntries(), "entries.") print(" Runtime (hrs): {:.2f}".format(runtime)) # create a TTree from the TCut and write to the output file print("Writing to output file:\n ", out_name) out_file = TFile(out_name, "RECREATE") out_tree = TTree() out_tree = ch.CopyTree(cut) out_tree.Write() out_file.Close() # check it f2 = TFile(out_name) tt2 = f2.Get("Data_F") print("Done. Skim file has", tt2.GetEntries(), "entries.")
def ROC(stree, btree, selection, score_retrieval, outname): bhist = histfill(btree, selection, score_retrieval) shist = histfill(stree, selection, score_retrieval) outtree = TTree(outname, outname) tpr = np.zeros(1) fpr = np.zeros(1) outtree.Branch("tpr", tpr, "tpr/D") outtree.Branch("fpr", fpr, "fpr/D") n_signal = shist.Integral() n_background = bhist.Integral() for i in range(10000): tpr[0] = 1. - (shist.Integral(0, i + 1) / n_signal) fpr[0] = 1. - (bhist.Integral(0, i + 1) / n_background) outtree.Fill() outtree.Write()
def skim_data(weekend): rdata = [[1, 3, 4, 5], [9, 13], [27], [33], [34]] runList = rdata[weekend] thresh = {} thresh[1] = {0: 80, 1: 60, 2: 70, 3: 80} thresh[1] = {0: 80, 1: 60, 2: 70, 3: 80} thresh[3] = {0: 80, 1: 60, 2: 70, 3: 80} thresh[4] = {0: 80, 1: 60, 2: 70, 3: 80} thresh[5] = {0: 80, 1: 60, 2: 70, 3: 80} thresh[9] = {0: 80, 1: 70, 2: 100, 3: 90} thresh[13] = {0: 80, 1: 70, 2: 100, 3: 90} thresh[27] = {0: 80, 1: 75, 2: 70, 3: 90} thresh[33] = {0: 80, 1: 230, 2: 300, 3: 430} thresh[34] = {0: 80, 1: 230, 2: 300, 3: 430} # print(thresh) # for key in thresh: # print(key, thresh[key]) fileDir, skimDir = "./data", "./skim" for run in runList: filelist = glob.glob("{}/run_{}/FILTERED/compassF_run_{}".format( fileDir, run, run) + "*.root") print(filelist) for f in sorted(filelist): fcut = "(Channel==0 && Energy > {}) || ".format(thresh[run][0]) fcut += "(Channel==1 && Energy > {}) || ".format(thresh[run][1]) fcut += "(Channel==2 && Energy > {}) || ".format(thresh[run][2]) fcut += "(Channel==3 && Energy > {})".format(thresh[run][3]) ch = TChain("Data_F") ch.Add(f) print("Found %d entries" % (ch.GetEntries())) outName = "{}/run_{}.root".format(skimDir, run) outFile = TFile(outName, "RECREATE") outTree = TTree() outTree = ch.CopyTree(fcut) outTree.Write() outFile.Close() f2 = TFile(outName) tt2 = f2.Get("Data_F") print(tt2.GetEntries())
def write_rootfile(self): """ Put the signal and bkg histos and the config as a json string into the currently open rootfile. rootfile - writable TFile """ self.histo.Write() self.bkg_histo.Write() config_str = json.dumps(self.config.to_dict()) config_array = array.array('B', config_str) t = TTree("configtree", "BumpHunter Config") t.Branch("config", config_array, "config[%s]/C" % len(config_array)) t.Fill() t.Write()
def execute(self, log_out, log_err): # Use local ROOT imports so ROOT env isn't necessary just to load the module. from ROOT import gROOT, TFile, TTree output_file = self.outputs[0] input_files = self.inputs logger.info("Creating output ROOT tuple '%s'" % output_file) logger.info("Input text files: %s" % str(input_files)) treeFile = TFile(output_file, "RECREATE") tree = TTree("ntuple", "data from text tuple " + input_files[0]) if len(input_files) > 1: inputfile = tempfile.NamedTemporaryFile(delete=False) print inputfile.name firstfile = True for filename in input_files: if os.path.isfile(filename): f = open(filename, 'r') firstline = True for i in f: if firstline: if firstfile: branchdescriptor = i inputfile.write(i) else: if branchdescriptor != i: print "branch descriptor doesn't match" sys.exit(-1) else: inputfile.write(i) firstline = False f.close() firstfile = False else: logger.warn("Ignoring non-existant input file '%s'" % filename) inputfile.close() print tree.ReadFile(inputfile.name) os.remove(inputfile.name) else: print tree.ReadFile(input_files[0]) tree.Write()
class tree_manager: def __init__(self, name): self.tree = TTree(name, '') self.arrays = {} def Branch(self, key): self.arrays[key] = array.array('d', [0.0]) return self.tree.Branch(key, self.arrays[key], key + '/D') def __setitem__(self, key, value): self.arrays[key][0] = value def Fill(self): return self.tree.Fill() def Write(self): return self.tree.Write()
def runTest(): w = initializeWorkspace() # example optimization for a cut on 'x' # eff(S) = 1-x # eff(B) = exp(-5*x) # S(X=0) = 4 # B(x=0) = 30 # dS/S = 15%, dB/B = 35% # let's scan X, print values of limit and save them to a tree S0 = 4 B0 = 20 dS = 0.1 dB = 0.35 fOut = TFile.Open("figureOfMerit.root", "RECREATE") tOut = TTree("fom", "fom") # x = 0 # S = 0 # B = 0 # limit = 0 # naive = 0 # tOut.Branch("x", AddressOf(x), "X/D") # tOut.Branch("S", AddressOf(S), "S/D") # tOut.Branch("B", AddressOf(B), "B/D") # tOut.Branch("limit", AddressOf(limit), "limit/D") # tOut.Branch("naive", AddressOf(naive), "naive/D") gROOT.ProcessLine( "struct vars { float x; float S; float B; float limit; float naive; };" ) from ROOT import vars var = vars() tOut.Branch("var", AddressOf(var), "x/F:S:B:limit:naive") print " %6s %6s %6s %6s %6s" % (" X ", " S ", " B ", "limit", "naive") # Tree's don't freakin work ! for x in range(0, 4): var.x = float(x) / 20. var.S = S0 * (1 - var.x) var.B = B0 * math.exp(-5 * var.x) var.limit = limitBayesian(w, var.B, dB, var.S, dS) var.naive = 2 * math.sqrt(var.B + (var.B * dB * var.B * dB)) / var.S print " %6.2f %6.2f %6.2f %6.2f %6.2f" % (var.x, var.S, var.B, var.limit, var.naive) tOut.Fill() tOut.Write() fOut.Close()
def main(barrel=first_arg, layer=second_arg): runs = askruns() staven = input('Type the number of the first stave in the (half-)layer: ') runnum = array('i', [0]) currstave = array('i', [0]) currchip = array('i', [0]) hits = array('f', [0]) col = array('i', [0]) row = array('i', [0]) f = open("datatoanalyse.txt", "r") ## file with all paths #open file with all the paths ftree = TFile.Open("../Data/{}_Layer{}_fakehitrate_tree_from_run{}_to_run{}.root".format(barrel, layer, runs[0], runs[1]), "recreate") ## file containing the tree roottree1 = TTree("fhitscan", "fhitscan"); roottree1.Branch("runnum", runnum, "runnum/I") roottree1.Branch("stavenum", currstave, "stavenum/I") roottree1.Branch("chipnum", currchip, "chipnum/I") roottree1.Branch("hits", hits, "hits/F") roottree1.Branch("col", col, "col/I") roottree1.Branch("row", row, "row/I") for xline in f: #loop on file lines (paths) run = re.search('run(.+?)/hit', xline) if(run): runnum[0] = int(run.group(1)) # run number if(runs[0] <= runnum[0] <= runs[1]): #read data datahit = readdata(str(xline.rstrip())) # fill the tree with the number of hits for i in range(len(datahit)):## loop on rows currstave[0] = int(staven) + math.floor(i / 512.); for j in range(len(datahit[i])): ##loop on columns currchip[0] = math.floor(j / 1024) row[0] = i col[0] = j hits[0] = datahit[i][j] if(hits[0]>0): roottree1.Fill() roottree1.Write() ftree.Close() f.close()
def WriteToFile(self, inputval=[], output="out.root"): """write a list to root file, the tree name is default as "sig", the branch is default as "val" Args: inputval(list): the input list, all element will convert into double output(str): the name of root file, the default value is "out.root" Returns: void """ fout = TFile(output, "recreate") tout = TTree("sig", "") val = array("d", [0.0]) tout.Branch("val", val, "val/D") for i in inputval: val[0] = i tout.Fill() tout.Write() fout.Close()
def main(): args = sys.argv[1:] if len(args) < 4: usage() sys.exit() file_in = args[0] file_out = args[1] ecms = float(args[2]) mode = args[3] f_in = TFile(file_in) f_out = TFile(file_out, 'recreate') t_out = TTree('save', 'save') cms = TLorentzVector(0.011 * ecms, 0, 0, ecms) save(f_in, t_out, cms, mode) f_out.cd() t_out.Write() f_out.Close()
def main(): args = sys.argv[1:] if len(args) < 2: return usage() file_in = args[0] file_out = args[1] ecms = float(args[2]) print 'Begin to process file: ' + file_in + ' ...' f_in = TFile(file_in) f_out = TFile(file_out, 'recreate') t_out = TTree('save', 'save') cms = TLorentzVector(0.011 * ecms, 0, 0, ecms) save_raw(f_in, cms, t_out) f_out.cd() t_out.Write() f_out.Close() print 'End of processing file: ' + file_out + ' ...'
def save_Tree(filepath, time_win=0.0, win_percent=0.0): allfiles = read_filename(filepath) rootfile = TFile(filepath + "/" + 'position_and_amp.root', "recreate") t1 = TTree("t1", "include position and amp info") x = np.array([0], dtype="int") y = np.array([0], dtype="int") z = np.array([0], dtype="int") Amp = np.array([0.0], dtype="float") t1.Branch("x", x, "x/I") t1.Branch("y", y, "y/I") t1.Branch("z", z, "z/I") t1.Branch("Amp", Amp, "Amp/D") for csvfile in allfiles: position = get_position_value(csvfile, time_win, win_percent) x[0] = int(position.x) y[0] = int(position.y) z[0] = int(position.z) Amp[0] = position.Amp t1.Fill() t1.Write() rootfile.Close()
def setUp(self): """ Create an external file with a tree (scalar and vector branch) and create tags and a sample using the external file. """ # create temporary directory super(TQTreeFormulaObservableTest, self).setUp() # create ROOT file and empty tree file = TFile( os.path.join(self.tempdir, "TQTreeFormulaObservable.root"), "recreate") tree = TTree("NOMINAL", "") x = array("d", [3.14]) tree.Branch("n_taus", x, "n_taus/D") vec = std_vector('double')() vec.push_back(1.42) vec.push_back(2.72) tree.Branch("tau_pt", vec) tree.Fill() x[0] = 42 vec.clear() vec.push_back(125.16) tree.Fill() tree.Write() file.Close() # create tags and sample self.tags = TQTaggable("a=n_taus,b=tau_pt") self.sample = TQSample("sample") self.sample.importTags(self.tags) self.sample = TQSample("sample") self.sample.setTreeLocation( os.path.join(self.tempdir, "TQTreeFormulaObservable.root:NOMINAL"))
def setUp(self): """ Create an external file with a single, empty tree and create tags and a sample using the external file. """ # create temporary directory super(TQFilterObservableTest, self).setUp() # create ROOT file and empty tree file = TFile( os.path.join(self.tempdir, "TQFilterObservable.root"), "recreate") tree = TTree("NOMINAL", "") tree.Write() file.Close() # create tags and sample self.tags = TQTaggable("a=2.2,b=3.3") self.tags.setTagBool("c", True) self.sample = TQSample("sample") self.sample.importTags(self.tags) self.sample.setTreeLocation( os.path.join(self.tempdir, "TQFilterObservable.root:NOMINAL"))