def AddNewBranches(inputfilename, treename, outputfilename): fcosin = TFile(inputfilename) tcosin = fcosin.Get(treename) fcosout = TFile(outputfilename,'RECREATE') tcosout = tcosin.CopyTree("") gROOT.ProcessLine(\ "struct MyStruct{\ Double_t adouble;\ };") from ROOT import MyStruct cos1 = MyStruct() newBranchcos1 = tcosout.Branch('B_s0_Cos1', AddressOf(cos1,'adouble'), 'B_s0_Cos1/D') cos2 = MyStruct() newBranchcos2 = tcosout.Branch('B_s0_Cos2', AddressOf(cos2,'adouble'), 'B_s0_Cos2/D') phi = MyStruct() newBranchphi = tcosout.Branch('B_s0_Phi1', AddressOf(phi,'adouble'), 'B_s0_Phi1/D') t = MyStruct() newBrancht = tcosout.Branch('B_s0_t', AddressOf(t,'adouble'), 'B_s0_t/D') terr = MyStruct() newBranchterr = tcosout.Branch('B_s0_terr', AddressOf(terr,'adouble'), 'B_s0_terr/D') kp = TLorentzVector() pim = TLorentzVector() km = TLorentzVector() pip = TLorentzVector() print "Processing events ..." for ev, i in enumerate(tcosout): if (ev%1000==0): print ev, '/', tcosout.GetEntries() kp.SetXYZM(eval('i.'+KpPx_name),eval('i.'+KpPy_name),eval('i.'+KpPz_name),493.667) pim.SetXYZM(eval('i.'+PimPx_name),eval('i.'+PimPy_name),eval('i.'+PimPz_name),139.570) km.SetXYZM(eval('i.'+KmPx_name),eval('i.'+KmPy_name),eval('i.'+KmPz_name),493.667) pip.SetXYZM(eval('i.'+PipPx_name),eval('i.'+PipPy_name),eval('i.'+PipPz_name),139.570) angles = get_Angles(kp,pim,km,pip) cos1.adouble = angles[0] cos2.adouble = angles[1] phi.adouble = angles[2] t.adouble = eval('i.'+tau_name)*1000. terr.adouble = eval('i.'+tauerr_name)*1000. newBranchcos1.Fill() newBranchcos2.Fill() newBranchphi.Fill() newBrancht.Fill() newBranchterr.Fill() print "All events processed." tcosout.Write() fcosout.Close()
def btagEfficiencyTreeProducer(stageName="Z+jet", muChannel=True, path='../testfiles/'): #search for category number stage=-1 for cat in categoryNames : stage+=1 if cat==stageName : break # prepare output path='/nfs/user/llbb/Pat_8TeV_532p4/DYjets_Summer12_V2/' ROOT.gROOT.ProcessLine( "struct MyStruct {\ Float_t pt;\ Float_t eta;\ Int_t flavor;\ Float_t ssvhe;\ Float_t ssvhp;\ Float_t csv;\ Float_t eventWeight;\ };" ) from ROOT import MyStruct mystruct = MyStruct() f = ROOT.TFile( 'mybtagEfftree.root', 'RECREATE' ) tree = ROOT.TTree( 'btagEff', 'btag efficiency' ) tree.Branch( 'data', mystruct, 'pt/F:eta/F:flavor/I:ssvhe/F:ssvhp/F:csv/F:eventWeight/F' ) # input if os.path.isdir(path): dirList=os.listdir(path) files=[] for fname in dirList: files.append(path+fname) elif os.path.isfile(path): files=[path] else: files=[] events = AnalysisEvent(files) EventSelection.prepareAnalysisEvent(events) # event loop eventCnt = 0 print "starting loop on events" for event in events: categoryData = event.catMu if muChannel else event.catEle goodJets = event.goodJets_mu if muChannel else event.goodJets_ele if EventSelection.isInCategory(stage, categoryData): eventCnt = eventCnt +1 if eventCnt%100==0 : print ".", if eventCnt%1000==0 : print "" # event weight mystruct.eventWeight = event.weight(weightList=["PileUp"]) # that's where we access the jets for index,jet in enumerate(event.jets): if not goodJets[index]: continue mystruct.pt = jet.pt() mystruct.eta = jet.eta() mystruct.flavor = jet.partonFlavour() mystruct.ssvhe = jet.bDiscriminator("simpleSecondaryVertexHighEffBJetTags") mystruct.ssvhp = jet.bDiscriminator("simpleSecondaryVertexHighPurBJetTags") mystruct.csv = jet.bDiscriminator("combinedSecondaryVertexBJetTags") tree.Fill() f.Write() f.Close() print ""
def writeCLTree(mg,mchi,xsec, box, model, directory, CLs, CLsExp): clTree = rt.TTree("clTree", "clTree") myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi;Double_t xsec;" iCL = 0 myStructCmd+= "Double_t CL%i;"%(iCL+0) myStructCmd+= "Double_t CL%i;"%(iCL+1) myStructCmd+= "Double_t CL%i;"%(iCL+2) myStructCmd+= "Double_t CL%i;"%(iCL+3) myStructCmd+= "Double_t CL%i;"%(iCL+4) myStructCmd+= "Double_t CL%i;"%(iCL+5) iCL+=6 myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() clTree.Branch("mg", rt.AddressOf(s,"mg"),'mg/D') clTree.Branch("mchi", rt.AddressOf(s,"mchi"),'mchi/D') clTree.Branch("xsec", rt.AddressOf(s,"xsec"),'xsec/D') s.mg = mg s.mchi = mchi s.xsec = xsec iCL = 0 clTree.Branch("CLs_%s"%box, rt.AddressOf(s,"CL%i"%(iCL+0)),'CL%i/D'%(iCL+0)) clTree.Branch("CLsExpPlus2_%s"%box, rt.AddressOf(s,"CL%i"%(iCL+1)),'CL%i/D'%(iCL+1)) clTree.Branch("CLsExpPlus_%s"%box, rt.AddressOf(s,"CL%i"%(iCL+2)),'CL%i/D'%(iCL+2)) clTree.Branch("CLsExp_%s"%box, rt.AddressOf(s,"CL%i"%(iCL+3)),'CL%i/D'%(iCL+3)) clTree.Branch("CLsExpMinus_%s"%box, rt.AddressOf(s,"CL%i"%(iCL+4)),'CL%i/D'%(iCL+4)) clTree.Branch("CLsExpMinus2_%s"%box, rt.AddressOf(s,"CL%i"%(iCL+5)),'CL%i/D'%(iCL+5)) exec 's.CL%i = CLs[iCL]'%(iCL+0) exec 's.CL%i = CLsExp[iCL][0]'%(iCL+1) exec 's.CL%i = CLsExp[iCL][1]'%(iCL+2) exec 's.CL%i = CLsExp[iCL][2]'%(iCL+3) exec 's.CL%i = CLsExp[iCL][3]'%(iCL+4) exec 's.CL%i = CLsExp[iCL][4]'%(iCL+5) iCL += 6 clTree.Fill() xsecString = str(xsec).replace(".","p") outputFileName = "%s/CLs_mg_%s_mchi_%s_xsec_%s_%s.root" %(directory, mg, mchi, xsecString,'_'.join(boxes)) print "CLs values being written to %s"%outputFileName fileOut = rt.TFile.Open(outputFileName, "recreate") clTree.Write() fileOut.Close() return outputFileName
def writeXsecTree(box, directory, mg, mchi, xsecULObs, xsecULExpPlus2, xsecULExpPlus, xsecULExp, xsecULExpMinus, xsecULExpMinus2): outputFileName = "%s/xsecUL_mg_%s_mchi_%s_%s.root" %(directory, mg, mchi, '_'.join(boxes)) print "INFO: xsec UL values being written to %s"%outputFileName fileOut = rt.TFile.Open(outputFileName, "recreate") xsecTree = rt.TTree("xsecTree", "xsecTree") myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi;" ixsecUL = 0 myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+0) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+1) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+2) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+3) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+4) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+5) ixsecUL+=6 myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() xsecTree.Branch("mg", rt.AddressOf(s,"mg"),'mg/D') xsecTree.Branch("mchi", rt.AddressOf(s,"mchi"),'mchi/D') s.mg = mg s.mchi = mchi ixsecUL = 0 xsecTree.Branch("xsecULObs_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+0)),'xsecUL%i/D'%(ixsecUL+0)) xsecTree.Branch("xsecULExpPlus2_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+1)),'xsecUL%i/D'%(ixsecUL+1)) xsecTree.Branch("xsecULExpPlus_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+2)),'xsecUL%i/D'%(ixsecUL+2)) xsecTree.Branch("xsecULExp_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+3)),'xsecUL%i/D'%(ixsecUL+3)) xsecTree.Branch("xsecULExpMinus_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+4)),'xsecUL%i/D'%(ixsecUL+4)) xsecTree.Branch("xsecULExpMinus2_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+5)),'xsecUL%i/D'%(ixsecUL+5)) exec 's.xsecUL%i = xsecULObs[ixsecUL]'%(ixsecUL+0) exec 's.xsecUL%i = xsecULExpPlus2[ixsecUL]'%(ixsecUL+1) exec 's.xsecUL%i = xsecULExpPlus[ixsecUL]'%(ixsecUL+2) exec 's.xsecUL%i = xsecULExp[ixsecUL]'%(ixsecUL+3) exec 's.xsecUL%i = xsecULExpMinus[ixsecUL]'%(ixsecUL+4) exec 's.xsecUL%i = xsecULExpMinus2[ixsecUL]'%(ixsecUL+5) ixsecUL += 4 xsecTree.Fill() fileOut.cd() xsecTree.Write() fileOut.Close() return outputFileName
def writeXsecTree(box, model, directory, massPoint, xsecULObs, xsecULExpPlus2, xsecULExpPlus, xsecULExp, xsecULExpMinus, xsecULExpMinus2): outputFileName = "%s/xsecUL_%s_%s_%s.root" %(directory, model, massPoint, box) print "INFO: xsec UL values being written to %s"%outputFileName fileOut = rt.TFile.Open(outputFileName, "recreate") xsecTree = rt.TTree("xsecTree", "xsecTree") myStructCmd = "struct MyStruct{Double_t mass;" ixsecUL = 0 myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+0) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+1) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+2) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+3) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+4) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+5) ixsecUL+=6 myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() xsecTree.Branch("mass", rt.AddressOf(s,"mass"),'mass/D') s.mass = float(massPoint) ixsecUL = 0 xsecTree.Branch("xsecULObs_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+0)),'xsecUL%i/D'%(ixsecUL+0)) xsecTree.Branch("xsecULExpPlus2_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+1)),'xsecUL%i/D'%(ixsecUL+1)) xsecTree.Branch("xsecULExpPlus_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+2)),'xsecUL%i/D'%(ixsecUL+2)) xsecTree.Branch("xsecULExp_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+3)),'xsecUL%i/D'%(ixsecUL+3)) xsecTree.Branch("xsecULExpMinus_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+4)),'xsecUL%i/D'%(ixsecUL+4)) xsecTree.Branch("xsecULExpMinus2_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+5)),'xsecUL%i/D'%(ixsecUL+5)) exec 's.xsecUL%i = xsecULObs[ixsecUL]'%(ixsecUL+0) exec 's.xsecUL%i = xsecULExpPlus2[ixsecUL]'%(ixsecUL+1) exec 's.xsecUL%i = xsecULExpPlus[ixsecUL]'%(ixsecUL+2) exec 's.xsecUL%i = xsecULExp[ixsecUL]'%(ixsecUL+3) exec 's.xsecUL%i = xsecULExpMinus[ixsecUL]'%(ixsecUL+4) exec 's.xsecUL%i = xsecULExpMinus2[ixsecUL]'%(ixsecUL+5) ixsecUL += 4 xsecTree.Fill() fileOut.cd() xsecTree.Write() fileOut.Close() return outputFileName
def CreateTree(self): # too much complication lvl, use CreateTree2 if len(self.internalData): # <- TOTAL WORKAROUND: START -> # # SEE: http://wlav.web.cern.ch/wlav/pyroot/tpytree.html leafStr = "" for key in self.internalData: s, leafStr = self.__CreateDummyStructAsStr( self.internalData[key]) print(s) print(leafStr) gROOT.ProcessLine(s) break #all modules are assumed to have the same set of measured parameters from ROOT import MyStruct ms = MyStruct() # <- TOTAL WORKAROUND: END -> # self.outputFile = TFile(self.outputFileName, "recreate") tree = TTree("tree", "readData") tree.Branch("b", ms, leafStr) tree.SetBranchAddress("b", tree) for key in self.internalData: setattr(ms, "key", key) for d in self.internalData[key]: setattr(ms, d, (self.internalData[key])[d]) tree.Fill() # break tree.Write() self.outputFile.Close() print("Data saved as TTree object")
def output_file_nonTrain(y_pred_cls, y_pred_adv_cls, evt_weight, x_test_index, INPUT_FILE, proc_tree, alpha_str): # Create a lookup table for discriminator value by event number disc_lookup_signal = {} disc_lookup_signal_adv = {} proc_evt_weight = {} for disc_val, disc_val_adv, evt_wt, run, lumi, event in zip( y_pred_cls, y_pred_adv_cls, evt_weight, x_test_index[:, 0], x_test_index[:, 1], x_test_index[:, 2]): disc_lookup_signal[(run, lumi, event)] = disc_val disc_lookup_signal_adv[(run, lumi, event)] = disc_val_adv proc_evt_weight[(run, lumi, event)] = evt_wt # We write out the signal and background events to a new ROOT file. # For events in the test set, we append the GBM discriminator. # For events in the train set, we set the discriminator to -1 # to avoid accidentally reusing the training set in the analysis. print len(disc_lookup_signal), len(disc_lookup_signal_adv) out_name = os.path.basename(INPUT_FILE).replace( '.root', alpha_str + '_NNscore.root') out_proc = rt.TFile(out_name, 'RECREATE') out_proc_tree = proc_tree.CloneTree(0) # This is the boilerplate code for writing something # to a ROOT tree from Python. rt.gROOT.ProcessLine("struct MyStruct2{float disc_advNN;};") rt.gROOT.ProcessLine("struct MyStruct3{float disc_simpleNN;};") rt.gROOT.ProcessLine("struct MyStruct{double evt_wt;};") from ROOT import MyStruct3, MyStruct2, MyStruct s = MyStruct3() s_adv = MyStruct2() s_wt = MyStruct() disc_branch_proc = out_proc_tree.Branch('disc_simpleNN', rt.AddressOf(s, 'disc_simpleNN'), 'disc_simpleNN/F') disc_branch_sig_proc = out_proc_tree.Branch( 'disc_advNN', rt.AddressOf(s_adv, 'disc_advNN'), 'disc_advNN/F') evt_weight_branch_proc = out_proc_tree.Branch('evt_weight', rt.AddressOf(s_wt, 'evt_wt'), 'evt_weight/D') print "Writing new ROOT process file with discriminator appended" fill_discriminator(proc_tree, out_proc_tree, disc_lookup_signal, disc_lookup_signal_adv, proc_evt_weight, s, s_adv, s_wt) # Cristian's code uses GetCurrentFile() for this part. # I will do that too just in case (paranoia). out_proc.cd() out_proc_tree.GetCurrentFile().Write() #signalNevents.Write() out_proc_tree.GetCurrentFile().Close() print 'done writing output'
def ns2ps(inputfilename,outputfilename): ftin = TFile(NTUPLE_PATH+inputfilename+'.root') ttin = ftin.Get('DecayTree') ftout = TFile(NTUPLE_PATH+outputfilename+'.root','RECREATE') print "Copying the original tree ..." ttout = ttin.CopyTree("") print "Tree copied." gROOT.ProcessLine(\ "struct MyStruct{\ Float_t afloat;\ };") from ROOT import MyStruct t = MyStruct() newBrancht = ttout.Branch('B_s0_t', AddressOf(t,'afloat'), 'B_s0_t/F') terr = MyStruct() newBranchterr = ttout.Branch('B_s0_terr', AddressOf(terr,'afloat'), 'B_s0_terr/F') print "Processing events ..." for i in ttout: t.afloat = eval('i.'+tau_name)*1000. terr.afloat = eval('i.'+tauerr_name)*1000. newBrancht.Fill() newBranchterr.Fill() print "All events processed." ttout.Write() ftout.Close()
def readTree(t, name): fname = 'result_'+nameid+'.root' print fname f = TFile( fname, 'recreate' ) tN = TTree( 't1', 'tree with histos' ) gROOT.ProcessLine( "struct MyStruct {\ Int_t ttbb_;\ Double_t DRbb_;\ Double_t weight_;\ };" ); from ROOT import MyStruct s = MyStruct() tN.Branch('ttbb',AddressOf(s,'ttbb_'),'ttbb_/I') tN.Branch('DRbb',AddressOf(s,'DRbb_'),'DRbb_/D') tN.Branch('weight',AddressOf(s,'weight_'),'weight_/D') l = TLorentzVector() l2 = TLorentzVector() l3 = TLorentzVector() # Event loop nev = t.GetEntries() for n in t: particles = n.Particle # weights = n.Rwgt event = n.Event output = isTTBB(particles) s.ttbb_=output[0] s.DRbb_=output[1] s.weight_= cxlist[fid]/nev tN.Fill() f.Write() f.Close()
def writeXsecTree(directory, model, mg, mchi, xsecULTotal, xsecULHighPt, xsecULHighRes, xsecULHbb, xsecULZbb): outputFileName = "%s/xsecUL_%s_mg_%s_mchi_%s.root" % (directory, model, mg, mchi) print "INFO: xsec UL values being written to %s" % outputFileName fileOut = rt.TFile.Open(outputFileName, "recreate") xsecTree = rt.TTree("xsecTree", "xsecTree") myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi;" for ixsecUL in range(0, 5): myStructCmd += "Double_t xsecUL%i;" % (ixsecUL) myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() xsecTree.Branch("mg", rt.AddressOf(s, "mg"), 'mg/D') xsecTree.Branch("mchi", rt.AddressOf(s, "mchi"), 'mchi/D') s.mg = mg s.mchi = mchi ixsecUL = 0 for box in ['Total', 'HighPt', 'HighRes', 'Hbb', 'Zbb']: xsecTree.Branch("xsecUL%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL)), 'xsecUL%i/D' % (ixsecUL)) exec 's.xsecUL%i = xsecUL%s[0]' % (ixsecUL, box) ixsecUL += 1 xsecTree.Fill() fileOut.cd() xsecTree.Write() fileOut.Close() return outputFileName
def __init__(self, schema): self.log = logging.getLogger('root') self.log = self.log.getChild(self.__class__.__name__) self.schema = schema # Create ROOT file and TTree filename = 'gnomon.root' self.file = ROOT.TFile(filename, 'RECREATE') self.t = ROOT.TTree('t', '') # This code will be passed into CINT self.names_lookup, self.types_lookup = self.make_lookups(schema) my_struct_code = self.form_cint(self.names_lookup, self.types_lookup) self.log.info('Using following structure for converting Python: %s' % my_struct_code) ROOT.gROOT.ProcessLine(my_struct_code) from ROOT import MyStruct self.my_struct = MyStruct() for key, val in self.names_lookup.iteritems(): name = val my_type = self.types_lookup[key] code = None if my_type == 'string': code = 'C' elif my_type == 'integer': code = 'I' elif my_type == 'number' or my_type == 'array': code = 'F' elif my_type == 'object': pass elif my_type == 'boolean': code = 'O' else: raise ValueError x = ROOT.AddressOf(self.my_struct, str(name)) if my_type == 'array': self.t.Branch(name, x, '%s[%d]/%s' % (name, BUFFER_SIZE, code)) else: self.t.Branch(name, x, '%s/%s' % (name, code))
def AddCosines(inputfilename,inputfileextradir,inputfileextradirname,outputfilename): fcosin = TFile(NTUPLE_PATH + inputfilename + '.root') if inputfileextradir: tcosin = fcosin.Get(inputfileextradirname).Get('DecayTree') else: tcosin = fcosin.Get('DecayTree') fcosout = TFile(NTUPLE_PATH + outputfilename + '.root','RECREATE') print "Copying the original tree ..." tcosout = tcosin.CopyTree("") print "Tree copied." gROOT.ProcessLine(\ "struct MyStruct{\ Double_t adouble;\ };") from ROOT import MyStruct cos1 = MyStruct() newBranchcos1 = tcosout.Branch('B_s0_Cos1', AddressOf(cos1,'adouble'), 'B_s0_Cos1/D') cos2 = MyStruct() newBranchcos2 = tcosout.Branch('B_s0_Cos2', AddressOf(cos2,'adouble'), 'B_s0_Cos2/D') kp = TLorentzVector() pim = TLorentzVector() km = TLorentzVector() pip = TLorentzVector() print "Processing events ..." for i in tcosout: kp.SetXYZM(eval('i.'+KpPx_name),eval('i.'+KpPy_name),eval('i.'+KpPz_name),493.667) pim.SetXYZM(eval('i.'+PimPx_name),eval('i.'+PimPy_name),eval('i.'+PimPz_name),139.570) km.SetXYZM(eval('i.'+KmPx_name),eval('i.'+KmPy_name),eval('i.'+KmPz_name),493.667) pip.SetXYZM(eval('i.'+PipPx_name),eval('i.'+PipPy_name),eval('i.'+PipPz_name),139.570) angles = get_Angles(kp,pim,km,pip) cos1.afloat = angles[0] cos2.afloat = angles[1] newBranchcos1.Fill() newBranchcos2.Fill() print "All events processed." tcosout.Write() fcosout.Close()
for ii in vectors_cand_seed: tree.Branch(ii[0]+"_seed",ii[1]) # Create a struct for the run information rt.gROOT.ProcessLine(\ "struct MyStruct{\ Int_t run;\ Int_t ls;\ Int_t event;\ };") from ROOT import MyStruct # Create branches in the tree s = MyStruct() tree.Branch("run",rt.AddressOf(s,"run"),"run/I") tree.Branch("ls",rt.AddressOf(s,"ls"),"ls/I") tree.Branch("event",rt.AddressOf(s,"event"),"event/I") #retreives the lables for a handle for an event def getAllLabels(event): for ii in handles: input_tag = ii[0] #triplet (label, middle, process( handle = ii[1] event.getByLabel(input_tag, handle) #gets the maps for all of the handles and returns a list def getMaps(): maps = []
Int_t Y;\ Int_t Xray;\ Int_t PH17;\ Int_t PH18;\ Int_t PH19;\ Int_t PH24;\ Int_t PH25;\ Int_t PH26;\ Int_t PH31;\ Int_t PH32;\ Int_t PH33;\ };" ); from ROOT import MyStruct my = MyStruct() tr.Branch('Arg', AddressOf(my,'Arg'), 'Arg/I'); tr.Branch('Frame', AddressOf(my,'Frame'), 'Frame/I'); tr.Branch('Event_th', AddressOf(my,'Event_th'), 'Event_th/I'); tr.Branch('Split_th', AddressOf(my,'Split_th'), 'Split_th/I'); tr.Branch('X', AddressOf(my,'X'), 'X/I'); tr.Branch('Y', AddressOf(my,'Y'), 'Y/I'); tr.Branch('Xray', AddressOf(my,'Xray'), 'Xray/I'); tr.Branch('PH17', AddressOf(my,'PH17'), 'PH17/I'); tr.Branch('PH18', AddressOf(my,'PH18'), 'PH18/I'); tr.Branch('PH19', AddressOf(my,'PH19'), 'PH19/I'); tr.Branch('PH24', AddressOf(my,'PH24'), 'PH24/I'); tr.Branch('PH25', AddressOf(my,'PH25'), 'PH25/I'); tr.Branch('PH26', AddressOf(my,'PH26'), 'PH26/I'); tr.Branch('PH31', AddressOf(my,'PH31'), 'PH31/I');
else: sitelist.append(mystruct.fSite) h1rate.Fill(float(altitude)) tree.Fill() f.Write() f = TFile('raw.root', 'UPDATE') gROOT.ProcessLine("struct MyStruct {\ Float_t fLat;\ Float_t fLong;\ Float_t fAlt;\ Int_t fTimestamp;\ Char_t fSite[64];\ };") from ROOT import MyStruct mystruct = MyStruct() sitereset() tree = TTree('rawdata', 'Rawdata') tree.Branch('lat', mystruct, 'Lat/F') tree.Branch('long', mystruct, 'Long/F') tree.Branch('alt', mystruct, 'Alt/F') tree.Branch('timestamp', mystruct, 'Timestamp/I') tree.Branch('site', AddressOf(mystruct, 'fSite'), 'Site/C') h1rate = TH1F('h1rate', 'Cumulative rate distribution', 100, 0, 20) f.Write() cherrypy.quickstart(MyMonitoring())
def saveConstants(detector, file): from ROOT import TFile from ROOT import TTree from ROOT import gROOT from ROOT import AddressOf f = TFile(file, 'RECREATE') t = TTree('Corrections', 'Corrections') gROOT.ProcessLine(\ "struct MyStruct{\ Int_t index;\ Int_t type;\ Int_t bec;\ Int_t layer;\ Int_t sector;\ Int_t ring;\ Int_t hits;\ Double_t tx;\ Double_t ty;\ Double_t tz;\ Double_t rx;\ Double_t ry;\ Double_t rz;\ Double_t etx;\ Double_t ety;\ Double_t etz;\ Double_t erx;\ Double_t ery;\ Double_t erz;\ };" ) from ROOT import MyStruct # Create branches in the tree s = MyStruct() t.Branch('index', AddressOf(s, 'index'), 'index/I') t.Branch('type', AddressOf(s, 'type'), 'type/I') t.Branch('bec', AddressOf(s, 'bec'), 'bec/I') t.Branch('layer', AddressOf(s, 'layer'), 'layer/I') t.Branch('sector', AddressOf(s, 'sector'), 'sector/I') t.Branch('ring', AddressOf(s, 'ring'), 'ring/I') t.Branch('hits', AddressOf(s, 'hits'), 'hits/I') t.Branch('tx', AddressOf(s, 'tx'), 'tx/D') t.Branch('ty', AddressOf(s, 'ty'), 'ty/D') t.Branch('tz', AddressOf(s, 'tz'), 'tz/D') t.Branch('rx', AddressOf(s, 'rx'), 'rx/D') t.Branch('ry', AddressOf(s, 'ry'), 'ry/D') t.Branch('rz', AddressOf(s, 'rz'), 'rz/D') t.Branch('etx', AddressOf(s, 'etx'), 'etx/D') t.Branch('ety', AddressOf(s, 'ety'), 'ety/D') t.Branch('etz', AddressOf(s, 'etz'), 'etz/D') t.Branch('erx', AddressOf(s, 'erx'), 'erx/D') t.Branch('ery', AddressOf(s, 'ery'), 'ery/D') t.Branch('erz', AddressOf(s, 'erz'), 'erz/D') t.SetMarkerStyle(20) #print detector for i in range(detector.nModules()): detector.GetModule(i) s.index = i if "Pixel" in detector.GetModule(i).Det: det = 1 elif "SCT" in detector.GetModule(i).Det: det = 2 elif "TRT" in detector.GetModule(i).Det: det = 3 else: det = 0 s.type = det if "Barrel" in detector.GetModule(i).BarrelEC: bec = 0 elif "EndCapA" in detector.GetModule( i).BarrelEC or "EndcapA" in detector.GetModule(i).BarrelEC: bec = -1 elif "EndCapC" in detector.GetModule( i).BarrelEC or "EndcapC" in detector.GetModule(i).BarrelEC: bec = 1 else: bec = 999 s.bec = bec s.layer = int(detector.GetModule(i).Layer) s.sector = int(detector.GetModule(i).PhiModule) s.ring = int(detector.GetModule(i).EtaModule) s.hits = int(detector.GetModule(i).Hits) s.tx = detector.GetModule(i).Tx s.ty = detector.GetModule(i).Ty s.tz = detector.GetModule(i).Tz s.rx = detector.GetModule(i).Rx s.ry = detector.GetModule(i).Ry s.rz = detector.GetModule(i).Rz s.bx = detector.GetModule(i).Bx s.etx = detector.GetModule(i).ETx s.ety = detector.GetModule(i).ETy s.etz = detector.GetModule(i).ETz s.erx = detector.GetModule(i).ERx s.ery = detector.GetModule(i).ERy s.erz = detector.GetModule(i).ERz s.ebx = detector.GetModule(i).EBx t.Fill() f.Write() f.Close()
def convertToROOT(path, ascii_file): try: ascifilename = path+'/'+ascii_file+'.txt' spamReader = csv.reader(open(ascifilename, 'rb'), delimiter=' ', skipinitialspace=True) print "ASCI file name =", ascifilename except IOError: print 'File %s does not exist' % (ascifilename) return 666 stuff = MyStruct() ArrSize = 3700 nB1 = array('i', [ 0 ] ) nB2 = array('i', [ 0 ] ) b1_bunches = array('i', ArrSize*[0]) b2_bunches = array('i', ArrSize*[0]) b1_time_zc = array('f', ArrSize*[0]) b2_time_zc = array('f', ArrSize*[0]) #b1_time_le = array('f', ArrSize*[0]) #b2_time_le = array('f', ArrSize*[0]) b1_amp = array('f', ArrSize*[0]) b2_amp = array('f', ArrSize*[0]) b1_int = array('f', ArrSize*[0]) b2_int = array('f', ArrSize*[0]) b1_len = array('f', ArrSize*[0]) b2_len = array('f', ArrSize*[0]) nCol = array('i', [ 0 ] ) deltaT = array('f', [ 0 ] ) bMode = array('i', [ 0 ] ) rootFile = TFile(path+'/root/'+ascii_file+'.root',"recreate") bunchTree = TTree("bunchTree","") bunchTree.Branch("vars", stuff, "version/F:status/i:scale/F:b1_offset:b1_gain:b2_offset:b2_gain:orb_len_trig:orb_len_1:orb_1_2:cog_ddly_c3_c4:cog_ddly_c1_c3:cog_ddly_c2_c4:cog_ddly_c1_c2") bunchTree.Branch("time", AddressOf( stuff, 'daTime' ), "daTime/l") bunchTree.Branch('nB1', nB1, 'nB1/I') bunchTree.Branch('nB2', nB2, 'nB2/I') bunchTree.Branch('b1_bunches', b1_bunches, 'b1_bunches[nB1]/I') bunchTree.Branch('b2_bunches', b2_bunches, 'b2_bunches[nB2]/I') bunchTree.Branch('b1_time_zc', b1_time_zc, 'b1_time_zc[nB1]/F') bunchTree.Branch('b2_time_zc', b2_time_zc, 'b2_time_zc[nB2]/F') #bunchTree.Branch('b1_time_le', b1_time_le, 'b1_time_le[nB1]/F') #bunchTree.Branch('b2_time_le', b2_time_le, 'b2_time_le[nB2]/F') bunchTree.Branch('b1_amp', b1_amp, 'b1_amp[nB1]/F') bunchTree.Branch('b2_amp', b2_amp, 'b2_amp[nB2]/F') bunchTree.Branch('b1_int', b1_int, 'b1_int[nB1]/F') bunchTree.Branch('b2_int', b2_int, 'b2_int[nB2]/F') bunchTree.Branch('b1_len', b1_len, 'b1_len[nB1]/F') bunchTree.Branch('b2_len', b2_len, 'b2_len[nB2]/F') bunchTree.Branch('nCol', nCol, 'nCol/I') bunchTree.Branch('deltaT', deltaT, 'deltaT/F') bunchTree.Branch('bMode', bMode, 'bMode/I') i=0 for row in spamReader: #if i>500: break if (row[0] == "#" or row[2]!="1"): continue stuff.version = float(row[0]) #Parse date and time, save as TDatime date = re.split("-|T|:|U|", row[1]) #print date dt = TDatime(int(date[0]), int(date[1]), int(date[2]), int(date[3]), int(date[4]), int(date[5])) stuff.daTime = dt.Convert() stuff.status = bool(row[2]) try: stuff.scale = float(row[3]) except ValueError: stuff.scale = 1.0 stuff.b1_offset = float(row[4]) stuff.b1_gain = float(row[5]) stuff.b2_offset = float(row[6]) stuff.b2_gain = float(row[7]) '''# Zero-crossing ''' nB1[0] = int(row[8]) nB2[0] = int(row[10]) """ if row[8]!=row[12]: print "Miss-match in number of bunches for beam 1 !!!\n", continue if row[10]!=row[14]: continue print "Miss-match in number of bunches for beam 2 !!!\n" if row[16]!= row[8] or row[18]!= row[10]: print "\n \t ---Leading edge and zc Number of bunches don't match --- \n" continue if row[20]!= row[8] or row[22]!= row[10]: print "\n \t --- Number of bunches don't match Amplitudes--- \n" continue if (nB1[0]!=0 and nB2[0]!=0) and (row[24]!= row[8] or row[27]!= row[10]): print "\n \t --- Number of bunches don't match Integrals--- \n" print i, [row[a] for a in [24,8,27, 10]] continue """ #12,13 = foldovwer stuff # This is the arrays for B1 bunchNum = n.array(re.split(",",row[9]), dtype = n.int) time_zc = n.array(re.split(",",row[14]), dtype = n.float) amp = n.array(re.split(",",row[16]), dtype = n.float) integ = n.array(re.split(",",row[18]), dtype = n.float) length = n.array(re.split(",",row[20]), dtype = n.float) # Debugging the Intensity problems # n.set_printoptions(precision=3) # if i>2950 and i<2965: #print 'line number ', i, row[1] # print 'Int=', integ[0:10]*0.960E9 #print 'Len=', length[0:3]*1E9 # for a in range (0,29): #print a, row[a][:60] for j in range(nB1[0]): try: b1_bunches[j] = bunchNum[j] except IndexError: print 'Warning: out of range... but will continue' print 'bunchNum', bunchNum for a in range (0,29): print a, row[a][:40] return 666 b1_time_zc[j] = time_zc[j] if bunchNum[j] > 3300: b1_time_zc[j] += ORBIT_LEN*1e-9 b1_amp[j] = amp[j] if nB1[0]!=0 and nB2[0]!=0: b1_int[j] = integ[j] b1_len[j] = length[j] # now the same for B2 bunchNum = n.array(re.split(",",row[11]), dtype = n.int) time_zc = n.array(re.split(",",row[15]), dtype = n.float) amp = n.array(re.split(",",row[17]), dtype = n.float) integ = n.array(re.split(",",row[19]), dtype = n.float) length = n.array(re.split(",",row[21]), dtype = n.float) for j in range(nB2[0]): try: b2_bunches[j] = bunchNum[j] except IndexError: print 'Warning: out of range... but will continue' print 'bunchNum', bunchNum return 666 b2_time_zc[j] = time_zc[j] if bunchNum[j] > 3300: b2_time_zc[j] += ORBIT_LEN*1e-9 b2_amp[j] = amp[j] if nB1[0]!=0 and nB2[0]!=0: b2_int[j] = integ[j] b2_len[j] = length[j] '''Checks''' #if (nB1[0]==358): # print b1_bunches ''' if (nB1[0]==352 and nB2[0]==352): print "b1 po", b1_bunches[0], b1_bunches[1], b1_bunches[2] print "b2 po", b2_bunches[0], b2_bunches[1], b2_bunches[2] print "b1 zc", b1_time_zc[0], b1_time_zc[1], b1_time_zc[2] print "b2 zc", b2_time_zc[0], b2_time_zc[1], b2_time_zc[2] print "b1 le", b1_time_le[0], b1_time_le[1], b1_time_le[2] print "b2 le", b2_time_le[0], b2_time_le[1], b2_time_le[2] ''' stuff.orb_len_trig = 0.0 stuff.orb_len_1 = 0.0 stuff.orb_1_2 = 0.0 stuff.cog_ddly_c3_c4 = 0.0 stuff.cog_ddly_c1_c3 = 0.0 stuff.cog_ddly_c2_c4 = 0.0 stuff.cog_ddly_c1_c2 = 0.0 if nB1[0]!=0 and nB2[0]!=0: stuff.orb_len_trig = float(row[22]) stuff.orb_len_1 = float(row[23]) stuff.orb_1_2 = float(row[24]) stuff.cog_ddly_c3_c4 = float(row[25]) stuff.cog_ddly_c1_c3 = float(row[26]) stuff.cog_ddly_c2_c4 = float(row[27]) stuff.cog_ddly_c1_c2 = float(row[28]) if stuff.version>=4.6: nCol[0] = int(row[29]) deltaT[0] = float(row[30]) if stuff.version>=4.8: #print row[30:] bMode = int(row[31]) else: bMode = 0 bunchTree.Fill() i+=1 bunchTree.Write() print 'Number of entries in this tree =', bunchTree.GetEntries() rootFile.Close() return 42
VarParsing.varType.string, 'name of output root file') options.register ('infilename', 'TempOut.csv', VarParsing.multiplicity.singleton, VarParsing.varType.string, 'name of input file from lcr2.py') options.parseArguments() ofile = TFile(options.outfilename,"RECREATE") tr = TTree("AnalysisTree","AnalysisTree") s = MyStruct() hltpath = TString("") tr.Branch('run',AddressOf(s,'runnr'),'runnr/i') tr.Branch('luminosityBlock',AddressOf(s,'luminosityBlock'),'luminosityBlock/i') #tr.Branch("HLTpath","TString",hltpath) #tr.Branch('L1bit','TString',l1bit) tr.Branch('intgRecLumi',AddressOf(s,'intgRecLumi'),'intgRecLumi/D') #tr.Branch('HLTpresc',AddressOf(s,'HLTpresc'),'HLTpresc/D') #tr.Branch('L1presc',AddressOf(s,'L1presc'),'L1presc/D') infile = open("TempOut.csv", "r") infile.readline()
def convertToROOT(path, ascii_file): try: ascifilename = path+'/'+ascii_file+'.txt' spamReader = csv.reader(open(ascifilename, 'rb'), delimiter=' ', skipinitialspace=True) print "ASCI file name =", ascifilename except IOError: print 'File %s does not exist' % (ascifilename) return stuff = MyStruct() root_fileName = path+'/root/'+ascii_file+'.root' print "Creating the file: ", root_fileName root_file = TFile(root_fileName,"recreate") timeTree = TTree("timeTree","") timeTree.Branch("vars1", stuff, "version/F:status/I:scale/D:b1_offset:b1_gain:b2_offset:b2_gain:nB1/I:nB2/I:\ b1_phase_min/D:b1_phase_max:b1_phase_mean:b1_phase_sigma:\ b2_phase_min/D:b2_phase_max:b2_phase_mean:b2_phase_sigma:\ bb_phase_min/D:bb_phase_max:bb_phase_mean:bb_phase_sigma:\ bcmain_jitter/F:b1_flag/I:b2_flag/I:nCol/I:bMode/I") timeTree.Branch("vars5", AddressOf( stuff, 'daTime' ), "daTime/l") i=0 for row in spamReader: # if i>500: break #print row if (row[0] == "#" or row[4]=="?"): continue #if i>600: print i, [row[a] for a in [16,17,18,8,9]] stuff.version = float(row[0]) # Parse date and time, save as TDatime date = re.split("-|T|:|U|", row[1]) # print date dt = TDatime(int(date[0]), int(date[1]), int(date[2]), int(date[3]), int(date[4]), int(date[5])) stuff.daTime = dt.Convert() # stuff.daTime = dt.Convert(kTRUE) # dt.Print() stuff.status = bool(int(row[2])) try: stuff.scale = float(row[3]) except ValueError: stuff.scale = 1.0 stuff.b1_offset = float(row[4]) stuff.b1_gain = float(row[5]) stuff.b2_offset = float(row[6]) stuff.b2_gain = float(row[7]) stuff.nB1 = int(row[8]) stuff.nB2 = int(row[9]) # print "N bunches = ", stuff.nB1, stuff.nB2 if stuff.nB1!=0: if row[10]!="-": stuff.b1_phase_min = float(row[10]) if row[11]!="-": stuff.b1_phase_max = float(row[11]) if row[12]!="-": stuff.b1_phase_mean = float(row[12]) if row[13]!="-": stuff.b1_phase_sigma = float(row[13]) if stuff.nB2!=0: if row[14]!="-": stuff.b2_phase_min = float(row[14]) if row[15]!="-": stuff.b2_phase_max = float(row[15]) if row[16]!="-": stuff.b2_phase_mean = float(row[16]) if row[17]!="-": stuff.b2_phase_sigma = float(row[17]) if (stuff.nB1!=0 and stuff.nB2!=0): if row[18]!="-": stuff.bb_phase_min = float(row[18]) if row[19]!="-": stuff.bb_phase_max = float(row[19]) if row[20]!="-": stuff.bb_phase_mean = float(row[20]) if row[21]!="-": stuff.bb_phase_sigma = float(row[21]) # print 'Delta T = ', stuff.bb_phase_mean # if (len(row)!=22): print "len(row) = ", len(row) if len(row)>21: stuff.bcmain_jitter = float(row[22]) stuff.b1_flag = int(row[23]) stuff.b2_flag = int(row[24]) if stuff.version>=4.6: stuff.nCol = int(row[25]) if stuff.version>=4.8: #print row[25:] stuff.bMode = int(row[26]) else: stuff.bMode = 0 timeTree.Fill() i+=1 timeTree.Write() print timeTree.GetEntries() root_file.Close() return 42
def writeXsecTree(box, model, directory, mg, mchi, xsecULObs, xsecULExpPlus2, xsecULExpPlus, xsecULExp, xsecULExpMinus, xsecULExpMinus2): outputFileName = "%s/xsecUL_mg_%s_mchi_%s_%s.root" %(directory, mg, mchi, box) print "INFO: xsec UL values being written to %s"%outputFileName fileOut = rt.TFile.Open(outputFileName, "recreate") xsecTree = rt.TTree("xsecTree", "xsecTree") try: from ROOT import MyStruct except ImportError: myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi; Double_t x; Double_t y;" ixsecUL = 0 myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+0) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+1) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+2) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+3) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+4) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+5) ixsecUL+=6 myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() xsecTree.Branch("mg", rt.AddressOf(s,"mg"),'mg/D') xsecTree.Branch("mchi", rt.AddressOf(s,"mchi"),'mchi/D') xsecTree.Branch("x", rt.AddressOf(s,"x"),'x/D') xsecTree.Branch("y", rt.AddressOf(s,"y"),'y/D') s.mg = mg s.mchi = mchi if 'T1x' in model: s.x = float(model[model.find('x')+1:model.find('y')].replace('p','.')) s.y = float(model[model.find('y')+1:].replace('p','.')) elif model == 'T1bbbb': s.x = 1 s.y = 0 elif model == 'T1tttt': s.x = 0 s.y = 1 else: s.x = -1 s.y = -1 ixsecUL = 0 xsecTree.Branch("xsecULObs_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+0)),'xsecUL%i/D'%(ixsecUL+0)) xsecTree.Branch("xsecULExpPlus2_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+1)),'xsecUL%i/D'%(ixsecUL+1)) xsecTree.Branch("xsecULExpPlus_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+2)),'xsecUL%i/D'%(ixsecUL+2)) xsecTree.Branch("xsecULExp_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+3)),'xsecUL%i/D'%(ixsecUL+3)) xsecTree.Branch("xsecULExpMinus_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+4)),'xsecUL%i/D'%(ixsecUL+4)) xsecTree.Branch("xsecULExpMinus2_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+5)),'xsecUL%i/D'%(ixsecUL+5)) exec 's.xsecUL%i = xsecULObs[ixsecUL]'%(ixsecUL+0) exec 's.xsecUL%i = xsecULExpPlus2[ixsecUL]'%(ixsecUL+1) exec 's.xsecUL%i = xsecULExpPlus[ixsecUL]'%(ixsecUL+2) exec 's.xsecUL%i = xsecULExp[ixsecUL]'%(ixsecUL+3) exec 's.xsecUL%i = xsecULExpMinus[ixsecUL]'%(ixsecUL+4) exec 's.xsecUL%i = xsecULExpMinus2[ixsecUL]'%(ixsecUL+5) ixsecUL += 4 xsecTree.Fill() fileOut.cd() xsecTree.Write() fileOut.Close() return outputFileName
# Make a tree fit_toy_tree = rt.TTree('fit_toy_tree','tree containing the toy fit parameters') # Create a struct rt.gROOT.ProcessLine(\ "struct MyStruct{\ Float_t mr0;\ Float_t n;\ Float_t b;\ Float_t ntot;\ };") from ROOT import MyStruct # Create branches in the tree struct = MyStruct() fit_toy_tree.Branch('mr0',rt.AddressOf(struct,'mr0'),'mr0/F') fit_toy_tree.Branch('n',rt.AddressOf(struct,'n'),'n/F') fit_toy_tree.Branch('b',rt.AddressOf(struct,'b'),'b/F') fit_toy_tree.Branch('ntot',rt.AddressOf(struct,'ntot'),'ntot/F') mr0_list = fit_toy_summary.get_mr0() n_list = fit_toy_summary.get_n() b_list = fit_toy_summary.get_b() ntot_list = fit_toy_summary.get_ntot() # Fill tree for toy in range(fit_toy_summary.get_ntoys()): struct.mr0 = mr0_list[toy] struct.n = n_list[toy] struct.b = b_list[toy]
else: return float('nan') structString = "struct MyStruct{ULong_t event;" for var in variables: structString +="Float_t "+var+";" for var in extraVariables: structString +="Float_t "+var+";" structString +="};" ROOT.gROOT.ProcessLine(structString) from ROOT import MyStruct s = MyStruct() #rwHisto = "" #if globals().has_key("reweightingHistoFile"): # if reweightingHistoFile!="": # rf = ROOT.TFile(reweightingHistoFile) # htmp = rf.Get("ngoodVertices_Data") # ROOT.gDirectory.cd("PyROOT:/") # rwHisto = htmp.Clone() # rf.Close() # print "Using reweightingHisto", reweightingHistoFile, rwHisto # #if rwHisto == "": # print "Don't use nvtx reweighting" def getReweightingHisto(filename=""):
Cut = [CutB1, CutB2] structString = "struct MyStruct{ULong_t event;" for var in variables: structString +="Float_t "+var+";" for var in extraVariables: structString +="Float_t "+var+";" structString +="};" ROOT.gROOT.ProcessLine(structString) from ROOT import MyStruct s = MyStruct() if not os.path.isdir(outputDir): os.system("mkdir "+outputDir) t = R.TTree( "Events", "Events", 1 ) t.Branch("event", ROOT.AddressOf(s, "event"), "event/l") for var in variables: t.Branch(var, ROOT.AddressOf(s,var), var+'/F') for var in extraVariables: t.Branch(var, ROOT.AddressOf(s,var), var+'/F') # ============================================================================ for cut in Cut: c = R.TChain('Events') c.Add(inputDir+'*.root')
leaf = c.GetAlias(varNameHisto) if leaf!='': return c.GetLeaf(leaf).GetValue() else: return float('nan') structString = "struct MyStruct{" for var in variables: structString +="Float_t "+var+";" structString +="};" ROOT.gROOT.ProcessLine(structString) from ROOT import MyStruct s = MyStruct() rwHisto = "" if globals().has_key("reweightingHistoFile"): if reweightingHistoFile!="": rf = ROOT.TFile(reweightingHistoFile) htmp = rf.Get("ngoodVertices_Data") ROOT.gDirectory.cd("PyROOT:/") rwHisto = htmp.Clone() rf.Close() print "Using reweightingHisto", reweightingHistoFile, rwHisto for m in chmodes: commoncf = "-1" exec(m) print "Mode:", chmode, "for", mode
Beam_ener = 5.0 # Setup output branches PID_v = r.vector('Int_t')() P_X_v = r.vector('Double_t')() P_Y_v =r.vector('Double_t')() P_Z_v =r.vector('Double_t')() E_v =r.vector('Double_t')() M_v =r.vector('Double_t')() # Create a struct which acts as the TBranch for non-vectors gROOT.ProcessLine( "struct MyStruct{ Int_t n_particles; Double_t weight; };") from ROOT import MyStruct # Assign the variables to the struct s = MyStruct() output_tree.Branch('n_particles',AddressOf(s,'n_particles'),'n_particles/I') output_tree.Branch('weight',AddressOf(s,'weight'),'weight/D') output_tree.Branch("PID",PID_v) output_tree.Branch("P_X",P_X_v) output_tree.Branch("P_Y",P_Y_v) output_tree.Branch("P_Z",P_Z_v) output_tree.Branch("E",E_v) output_tree.Branch("M",M_v) in_ev = 0 # To know when to look for particles we must know when we are inside an event in_ev_1 = 0 # The first line after <event> is information so we must skip that as well s.n_particles = 0 for line in input_file: # if line[:1] == "#": # continue
pass i = Image.open(input_file) pixels = i.load() # this is not a list output_tree = TTree("Physics", "Physics") print "Setup complete \nOpened picture " + input_file + " \nConverting to .root format and outputing to " + output_file_name # Create a struct which acts as the TBranch for non-vectors gROOT.ProcessLine( "struct MyStruct{ Double_t X_v; Double_t Y_v; Double_t Pixel_v; };") from ROOT import MyStruct # Assign the variables to the struct s = MyStruct() output_tree.Branch('X_v',AddressOf(s,'X_v'),'X_v/D') output_tree.Branch('Y_v',AddressOf(s,'Y_v'),'Y_v/D') output_tree.Branch('Pixel_v',AddressOf(s,'Pixel_v'),'Pixel_v/D') width, height = i.size output_th2f = TH2F("histo_2d","Pixel ditribution; x(px) ; y(px) ",width,0,width,height,0,height) for y in range(height): cur_row_ttl = 0 for x in range(width): cur_pixel = pixels[x, y] cur_pixel_mono = sum(cur_pixel) / len(cur_pixel) cur_row_ttl += cur_pixel_mono s.X_v = x
def getJobStatistics(LOGDIR,OUTFILE): DIR_SUMMARY = {} SUMMARY = {} ###stores full stat SINGLE_DIR_DATA = {} ###stores single entries MEAN_COMP = {} ### stores stat info firstDir = True tempI=0 samplesBinEdges = {} #{'lowerBin':{},'upperBin':{}} #Begin dir analysis if os.path.isdir(LOGDIR)==False and os.path.islink(LOGDIR)==False: print LOGDIR print "[ERROR] Directory not Valid" exit(1) SUMMARY = {"Success":0, "Failures":0, "Error":{}} spDirName = splitDirName(LOGDIR) if OUTFILE=="": OUTFILE = LOGDIR.strip('/').split("/")[-1]+'.root' print "---" print "OutFile:",OUTFILE print "Analyzing "+LOGDIR print "---" ###Parsing Files CRAB_LOGDIR = LOGDIR+"/res/" ### use stdout or xml for both? if options.TYPE == "CRAB": LOGS = os.popen("ls "+CRAB_LOGDIR+"*.stdout") elif options.TYPE == "CMSSW": LOGS = os.popen("ls "+LOGDIR+"/*.xml") elif options.TYPE == "CMSSWCRAB": LOGS = os.popen("ls "+CRAB_LOGDIR+"CMSSW*.stdout") else: printError("Please choose a type: CRAB, CMSSW or CMSSWCRAB") ### creating a TTree outFile = ROOT.TFile(OUTFILE,"RECREATE") perfTree = ROOT.TTree('Performance', 'Performance') ### loop over logfiles/jobs Total_jobs=0 Total_successfulJobs=0 valueContainer = {} for x in LOGS: #Parse crabDir x = x.strip('\n') if options.TYPE == "CRAB": rValue = parseDir_Crab(LOGDIR, x, acceptedSummaries) elif options.TYPE == "CMSSW": rValue = parseDir_CMSSW( x, acceptedSummaries) elif options.TYPE == "CMSSWCRAB": rValue = parseDir_CMSSWCrab( LOGDIR, x, 'cmssw', acceptedSummaries) if rValue!=1: job_output = rValue else: continue #end Parse crabDir Total_jobs+=1 if job_output["Success"]: Total_successfulJobs+=1 ###User Quantities, aka combination of logged quantities totalMB = 0 totalActualMB = 0 totalReadTime = 0 if job_output.has_key('tstoragefile-read-total-megabytes'): totalMB += float(job_output['tstoragefile-read-total-megabytes']) if job_output.has_key('tstoragefile-readv-total-megabytes'): totalMB += float(job_output['tstoragefile-readv-total-megabytes']) if job_output.has_key('tstoragefile-read-actual-total-megabytes'): totalActualMB += float(job_output['tstoragefile-read-actual-total-megabytes']) if job_output.has_key('tstoragefile-readv-actual-total-megabytes'): totalActualMB += float(job_output['tstoragefile-readv-actual-total-megabytes']) ### TODO: some estimate of read_kB/event ### TODO: find a good error handling computeErrorStat(job_output, SUMMARY) ### here, we are creating the tree structure, depending on the log content for label in job_output.keys(): if not valueContainer.has_key(label): if isinstance( job_output[label] , float) or isinstance( job_output[label] , list) : valueContainer[label]=ROOT.std.vector( float )() perfTree.Branch(str(makeCleanLabel(label,job_output)),valueContainer[str(label)]) if label=="Error": valueContainer[label]=ROOT.std.vector( float )() perfTree.Branch(str(makeCleanLabel(label,job_output)),valueContainer[str(label)]) # valueContainer[label+"_weight"]=ROOT.std.vector( float )() # perfTree.Branch(str(makeCleanLabel(label,job_output))+"_weight",valueContainer[str(label)]) pushJobOutput( label, job_output, SINGLE_DIR_DATA) isFirstJob=False ###end log cycle ### ###the previous loop gathers the info and creates the tree structure ###this one actually fills the tree ###TODO: better if conditions for job in range(0,Total_successfulJobs): for label in SINGLE_DIR_DATA.keys(): if label=="Error": continue if isinstance( SINGLE_DIR_DATA[label][job] , float): valueContainer[label].clear() valueContainer[label].push_back(SINGLE_DIR_DATA[label][job]) elif isinstance( SINGLE_DIR_DATA[label][job] , list): valueContainer[label].clear() for entry in SINGLE_DIR_DATA[label][job]: valueContainer[label].push_back(entry) ###tree filling perfTree.Fill() # Still need to record errors: label="Error" for err in SUMMARY[label].keys(): print str(err)+" : "+str(SUMMARY[label][err]) for job in range(0,int(SUMMARY[label][err])): valueContainer[label].clear() valueContainer[label].push_back(float(err)) perfTree.Fill() #############################################3 something entirely new here -- the job info! gROOT.ProcessLine( "struct MyStruct {\ Char_t site[100];\ Char_t dataset[200];\ Char_t sw[100];\ Char_t config[100];\ Char_t script[100];\ Char_t eventsJob[100];\ Char_t timestamp[100];\ Char_t comments[200];\ Char_t njobs[100];\ };" ); from ROOT import MyStruct, AddressOf; mystruct = MyStruct(); info_tree = ROOT.TTree("info_tree","info_tree"); info_tree.Branch("site",AddressOf(mystruct,'site'),'site/C'); info_tree.Branch("dataset",AddressOf(mystruct,'dataset'),'dataset/C'); info_tree.Branch("sw",AddressOf(mystruct,'sw'),'sw/C'); info_tree.Branch("config",AddressOf(mystruct,'config'),'config/C'); info_tree.Branch("comments",AddressOf(mystruct,'comments'),'comments/C'); info_tree.Branch("eventsJob",AddressOf(mystruct,'eventsJob'),'eventsJob/C'); info_tree.Branch("timestamp",AddressOf(mystruct,'timestamp'),'timestamp/C'); info_tree.Branch("njobs",AddressOf(mystruct,'njobs'),'njobs/C'); # fullstring=LOGDIR.strip('/').split("/")[-1].replace(".root","") # print "starting out with fullstring ",fullstring # bla_site = fullstring[0:fullstring.find("-")] # bla_rest = fullstring[fullstring.find("-")+1:len(fullstring)] # bla_script=bla_rest[0:bla_rest.find("-")] # bla_rest = bla_rest[bla_rest.find("-")+1:len(bla_rest)] # bla_nevents=int(bla_rest[0:bla_rest.find("-")]) # bla_rest = bla_rest[bla_rest.find("-")+1:len(bla_rest)] # bla_config=bla_rest[0:bla_rest.find("-")] # bla_rest = bla_rest[bla_rest.find("-")+1:len(bla_rest)] # bla_timestamp=bla_rest[0:bla_rest.find("__")] #mystruct.site="%s" % bla_site #mystruct.config="%s" % bla_config #mystruct.script="%s" % bla_script #mystruct.timestamp="%s" % bla_timestamp #mystruct.nevents="ne%s" % bla_nevents #mystruct.njobs="nj%s" % str(Total_jobs) mystruct.site="%s" % options.SITE mystruct.config="%s" % options.CONFIG mystruct.sw="%s" % options.SW mystruct.timestamp="%s" % options.TIMESTAMP mystruct.eventsJob="ne%s" % options.EVENTSJOB mystruct.njobs="nj%s" % str(Total_jobs) mystruct.comments="ne%s" % options.COMMENTS info_tree.Fill() #############################################3 /something entirely new here -- the job info! outFile.Write() outFile.Close()
smoothXsecTree = rt.TTree("smoothXsecTree", "smoothXsecTree") myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi;Double_t x;Double_t y;" ixsecUL = 0 myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+0) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+1) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+2) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+3) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+4) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+5) ixsecUL+=6 myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() smoothXsecTree.Branch("mg", rt.AddressOf(s,"mg"),'mg/D') smoothXsecTree.Branch("mchi", rt.AddressOf(s,"mchi"),'mchi/D') smoothXsecTree.Branch("x", rt.AddressOf(s,"x"),'x/D') smoothXsecTree.Branch("y", rt.AddressOf(s,"y"),'y/D') if 'T1x' in model: s.x = float(model[model.find('x')+1:model.find('y')].replace('p','.')) s.y = float(model[model.find('y')+1:].replace('p','.')) elif model == 'T1bbbb': s.x = 1 s.y = 0 elif model == 'T1tttt': s.x = 0 s.y = 1 else: s.x = -1
#Comparator def getPt(TLorentzVector): return TLorentzVector[0].Pt() ############################################################################ # Create a struct which acts as the TBranch for non-vectors gROOT.ProcessLine( "struct MyStruct{ Int_t n_particles; Double_t weight; Int_t njet; Float_t xsec1; Float_t xsec1_error; Float_t xsec2; Float_t xsec2_error; Int_t counter; Int_t SSmumu; Int_t OSmumu; Int_t SSee; Int_t OSee; Int_t SSemu; Int_t OSemu; };" ) from ROOT import MyStruct # Assign the variables to the struct s = MyStruct() output_tree.Branch('n_particles', AddressOf(s, 'n_particles'), 'n_particles/I') output_tree.Branch('weight', AddressOf(s, 'weight'), 'weight/D') # exponential not working output_tree.Branch('njet', AddressOf(s, 'njet'), 'njet/I') output_tree.Branch('xsec1', AddressOf(s, 'xsec1'), 'xsec1/F') output_tree.Branch('xsec1_error', AddressOf(s, 'xsec1_error'), 'xsec1_error/F') output_tree.Branch('xsec2', AddressOf(s, 'xsec2'), 'xsec2/F') output_tree.Branch('xsec2_error', AddressOf(s, 'xsec2_error'), 'xsec2_error/F') output_tree.Branch('counter', AddressOf(s, 'counter'), 'counter/I') #topology counter output_tree.Branch('SSmumu', AddressOf(s, 'SSmumu'), 'SSmumu/I') output_tree.Branch('OSmumu', AddressOf(s, 'OSmumu'), 'OSmumu/I') output_tree.Branch('SSee', AddressOf(s, 'SSee'), 'SSee/I') output_tree.Branch('OSee', AddressOf(s, 'OSee'), 'OSee/I')
Float_t vthrcal6;\ Float_t vthrcal7;\ Float_t vthrhv0;\ Float_t vthrhv1;\ Float_t vthrhv2;\ Float_t vthrhv3;\ Float_t vthrhv4;\ Float_t vthrhv5;\ Float_t vthrhv6;\ Float_t vthrhv7;\ };") from ROOT import MyStruct # Create branches in the tree s = MyStruct() mytree.Branch('rootInt',AddressOf(s,'channel'),'channel/I') mytree.Branch('rootFloat',AddressOf(s,'peak'),'peak/F') mytree.Branch('rootFloat',AddressOf(s,'pedestal'),'pedestal/F') mytree.Branch('rootFloat',AddressOf(s,'pedrms'),'pedrms/F') mytree.Branch('rootFloat',AddressOf(s,'deltat'),'deltat/F') mytree.Branch('rootFloat',AddressOf(s,'time'),'time/F') mytree.Branch('rootFloat',AddressOf(s,'caltemp'),'caltemp/F') mytree.Branch('rootFloat',AddressOf(s,'hvtemp'),'hvtemp/F') mytree.Branch('rootInt',AddressOf(s,'thr0'),'thr0/I') mytree.Branch('rootInt',AddressOf(s,'thr1'),'thr1/I') mytree.Branch('rootInt',AddressOf(s,'thr2'),'thr2/I') mytree.Branch('rootInt',AddressOf(s,'thr3'),'thr3/I') mytree.Branch('rootInt',AddressOf(s,'thr4'),'thr4/I') mytree.Branch('rootInt',AddressOf(s,'thr5'),'thr5/I') mytree.Branch('rootInt',AddressOf(s,'thr6'),'thr6/I')
myCLs.sort() myCLsHisto = rt.TH1D("ExpectedCLs_%s" %BoxName, 100, min(myCLs), max(myCLs)) for thisCLs in myCLs: myCLsHisto.Fill(thisCLs) clExpectedTree = rt.TTree("clExpectedTree", "clExpectedTree") rt.gROOT.ProcessLine( "struct MyStruct{\ Double_t m0;\ Double_t m12;\ Double_t CLexp;\ Double_t CLexpPlus;\ Double_t CLexpMinus;};") from ROOT import MyStruct s = MyStruct() clTree.Branch("m0", rt.AddressOf(s,"m0"),'m0/D') clTree.Branch("m12", rt.AddressOf(s,"m12"),'m12/D') clTree.Branch("CLexp_%s" %BoxName, rt.AddressOf(s,"CLexp"),'CLexp/D') clTree.Branch("CLexpPlus_%s" %BoxName, rt.AddressOf(s,"CLexpPlus"),'CLexpPlus/D') clTree.Branch("CLexpMinus_%s" %BoxName, rt.AddressOf(s,"CLexpMinus"),'CLexpMinus/D') s.m0 = m0 s.m12 = m12 s.CLexp, s.CLexpPlus, s.CLexpMinus = ComputeMedian(myCLsHisto) clExpectedTree.Fill() outFile = rt.TFile(fileName.split(".root")[0]+"_expected.root", "recreate") clExpectedTree.Fill() myCLsHisto.Fill() outFile.Close()
tr = TTree('tree_ne', 'tree') gROOT.ProcessLine(\ "struct MyStruct {\ Int_t Arg;\ Int_t Frame;\ Int_t Event_th;\ Int_t Split_th;\ Int_t X;\ Int_t Y;\ Int_t Xray;\ Int_t count;\ };" ) from ROOT import MyStruct my = MyStruct() tr.Branch('Arg', AddressOf(my, 'Arg'), 'Arg/I') tr.Branch('Frame', AddressOf(my, 'Frame'), 'Frame/I') tr.Branch('Event_th', AddressOf(my, 'Event_th'), 'Event_th/I') tr.Branch('Split_th', AddressOf(my, 'Split_th'), 'Split_th/I') tr.Branch('X', AddressOf(my, 'X'), 'X/I') tr.Branch('Y', AddressOf(my, 'Y'), 'Y/I') tr.Branch('Xray', AddressOf(my, 'Xray'), 'Xray/I') tr.Branch('count', AddressOf(my, 'count'), 'count/I') argvs = sys.argv root = TFile(argvs[-1]) for i in range(1, 7): print 'tree = %s' % i
tin_bkg = fin_bkg.Get("DecayTree") fout = TFile( "/afs/cern.ch/work/j/jugarcia/public/FastNTuples/Bd2Dptaunu/Bd2Dptaunu_ToyForBDT.root", "RECREATE") tout_signal = tin_signal.CloneTree(0) tout_bkg = tin_bkg.CloneTree(0) gROOT.ProcessLine(\ "struct MyStruct{\ Float_t afloat;\ };" ) from ROOT import MyStruct evtype = MyStruct() weight = MyStruct() mass = MyStruct() br_evtype_signal = tout_signal.Branch('signal', AddressOf(evtype, 'afloat'), 'signal/F') br_weight_signal = tout_signal.Branch('weight', AddressOf(weight, 'afloat'), 'weight/F') br_mass_signal = tout_signal.Branch('Dplus_MM_toy', AddressOf(mass, 'afloat'), 'Dplus_MM_toy/F') br_evtype_bkg = tout_bkg.Branch('signal', AddressOf(evtype, 'afloat'), 'signal/F') br_weight_bkg = tout_bkg.Branch('weight', AddressOf(weight, 'afloat'), 'weight/F') br_mass_bkg = tout_bkg.Branch('Dplus_MM_toy', AddressOf(mass, 'afloat'), 'Dplus_MM_toy/F')
var_min_Kp_Km_ETA) reader.AddVariable("max_pip_pim_ETA := max(pip_LOKI_ETA,pim_LOKI_ETA)", var_max_pip_pim_ETA) reader.AddVariable("min_pip_pim_ETA := min(pip_LOKI_ETA,pim_LOKI_ETA)", var_min_pip_pim_ETA) var_Bs_M = array('f', [0]) reader.AddSpectator("Bs_M", var_Bs_M) reader.BookMVA("BDT", "dataset1/weights/TMVAClassification_BDT.weights.xml") #reader.BookMVA("BDTG","dataset1/weights/TMVAClassification_BDTG.weights.xml") gROOT.ProcessLine("struct MyStruct{ Float_t afloat; };") from ROOT import MyStruct bdt_output = MyStruct() #bdtg_output = MyStruct() br_bdt = tout.Branch('BDT', AddressOf(bdt_output, 'afloat'), 'BDT/F') #br_bdtg = tout.Branch('BDTG', AddressOf(bdtg_output,'afloat'), 'BDTG/F') print "Processing events ..." for ev in tout: var_Bs_PT[0] = ev.Bs_PT var_Kst_PT[0] = ev.Kst_PT var_Kstb_PT[0] = ev.Kstb_PT var_max_Kp_Km_PT[0] = max(ev.Kp_PT, ev.Km_PT) var_min_Kp_Km_PT[0] = min(ev.Kp_PT, ev.Km_PT) var_max_pip_pim_PT[0] = max(ev.pip_PT, ev.pim_PT) var_min_pip_pim_PT[0] = min(ev.pip_PT, ev.pim_PT) var_Bs_DIRA_OWNPV[0] = ev.Bs_DIRA_OWNPV
print "Setup complete \nOpened file " + str(sys.argv[1]) + " \nConverting to .root format and outputing to " + output_file_name # Setup output branches PID_v = r.vector('Int_t')() P_X_v = r.vector('Double_t')() P_Y_v =r.vector('Double_t')() P_Z_v =r.vector('Double_t')() E_v =r.vector('Double_t')() M_v =r.vector('Double_t')() # Create a struct which acts as the TBranch for non-vectors gROOT.ProcessLine( "struct MyStruct{ Int_t n_particles; Double_t weight; };") from ROOT import MyStruct # Assign the variables to the struct s = MyStruct() output_tree.Branch('n_particles',AddressOf(s,'n_particles'),'n_particles/I') output_tree.Branch('weight',AddressOf(s,'weight'),'weight/D') output_tree.Branch("PID",PID_v) output_tree.Branch("P_X",P_X_v) output_tree.Branch("P_Y",P_Y_v) output_tree.Branch("P_Z",P_Z_v) output_tree.Branch("E",E_v) output_tree.Branch("M",M_v) skippedLines = [] in_ev = 0 # To know when to look for particles we must know when we are inside an event in_ev_1 = 0 # The first line after <event> is information so we must skip that as well s.n_particles = 0 s.weight = 0 for line in input_file:
Float_t rate;\ Int_t hits;\ Float_t thr;\ Float_t vthrcal;\ Float_t vthrhv;\ };" # Create a ROOT struct to hold information from each json run gROOT.ProcessLine(struct_run_string) gROOT.ProcessLine(struct_channel_string) from ROOT import MyStruct from ROOT import MyStructChannel # Create branches in the tree s = MyStruct() ## general run info channel_branch = [MyStructChannel() for i in range(96)] mytree.Branch('run', AddressOf(s, 'run'), 'run/I') mytree.Branch('peak', AddressOf(s, 'peak'), 'peak/F') mytree.Branch('dt', AddressOf(s, 'dt'), 'dt/F') mytree.Branch('pedestal', AddressOf(s, 'pedestal'), 'pedestal/F') mytree.Branch('pedrms', AddressOf(s, 'pedrms'), 'pedrms/F') mytree.Branch('time', AddressOf(s, 'time'), 'time/F') mytree.Branch('localtime', AddressOf(s, 'localtime'), 'localtime/D') mytree.Branch('skipped_words', AddressOf(s, 'skipped_words'), 'skipped_words/I') mytree.Branch('overflows', AddressOf(s, 'overflows'), 'overflows/I') mytree.Branch('caltemp', AddressOf(s, 'caltemp'), 'caltemp/F') mytree.Branch('hvtemp', AddressOf(s, 'hvtemp'), 'hvtemp/F') mytree.Branch('calp', AddressOf(s, 'calp'), 'calp/F')
Int_t nJets=0;\ Float_t Tau_pt=0;\ Float_t Tau_phi=0;\ Float_t Tau_eta=0;\ Int_t nTaus=0;\ Float_t MET=0;\ Float_t TransMass=0;\ Float_t tj1Dist=0;\ Float_t DPhi_tau_miss=0;\ Float_t DPhi_bjet_miss=0;\ Float_t Upsilon=0;\ };") from ROOT import MyStruct mystruct = MyStruct() #File list of samples to be read from if isSignal: samples = [ 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_1000', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_10000', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_1500', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_2000', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_2500', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_3000', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_5000', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_7000', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_750', 'ChargedHiggs_HplusTB_HplusToTauNu_HeavyMass_M_800', 'ChargedHiggs_HplusTB_HplusToTauNu_IntermediateMassNoNeutral_M_145',
'met_tst_nolep_phi', 'met_tst_phi', 'metsig_tst', ] ints = [ 'passJetCleanTight', 'trigger_met_encoded', 'trigger_met_encodedv2', ] bols = [ 'passVjetsFilter', 'passVjetsFilterTauEl', 'passVjetsPTV', ] from ROOT import MyStruct mystruct = MyStruct() tree_out = ROOT.TTree('QCDDDNominal', 'Nominal data driven QCD') #tree_out.Branch( 'myfloats', mystruct, 'jj_mass/F:jj_dphi/F:jj_deta/F' ) tree_out.Branch('jj_mass', ROOT.AddressOf(mystruct, 'jj_mass'), 'jj_mass/F') tree_out.Branch('jj_dphi', ROOT.AddressOf(mystruct, 'jj_dphi'), 'jj_dphi/F') tree_out.Branch('jj_deta', ROOT.AddressOf(mystruct, 'jj_deta'), 'jj_deta/F') tree_out.Branch('w', ROOT.AddressOf(mystruct, 'w'), 'w/F') tree_out.Branch('TriggerEffWeight', ROOT.AddressOf(mystruct, 'TriggerEffWeight'), 'TriggerEffWeight/F') tree_out.Branch('TriggerEffWeightBDT', ROOT.AddressOf(mystruct, 'TriggerEffWeightBDT'), 'TriggerEffWeightBDT/F') tree_out.Branch('met_tenacious_tst_j1_dphi', ROOT.AddressOf(mystruct, 'met_tenacious_tst_j1_dphi'), 'met_tenacious_tst_j1_dphi/F')
leaf = c.GetAlias(varNameHisto) if leaf != '': return c.GetLeaf(leaf).GetValue() else: return float('nan') #Define and compile C struct; do not recompile when changes have been made in a single py session because the import statement will not update the struct structString = "struct MyStruct{" for var in variables: structString += "Float_t " + var + ";" structString += "};" ROOT.gROOT.ProcessLine(structString) from ROOT import MyStruct s = MyStruct() #Did you specify a PU reweighting hist file? rwHisto = "" if globals().has_key("reweightingHistoFile"): if reweightingHistoFile != "": rf = ROOT.TFile(reweightingHistoFile) htmp = rf.Get("ngoodVertices_Data") ROOT.gDirectory.cd("PyROOT:/") rwHisto = htmp.Clone() rf.Close() print "Using reweightingHisto", reweightingHistoFile, rwHisto if not os.path.isdir(outputDir): os.system("mkdir " + outputDir) if not os.path.isdir(outputDir + "/" + chmode + "/"):
'OutFile.root', VarParsing.multiplicity.singleton, VarParsing.varType.string, 'name of output root file') options.parseArguments() #os.system("lumiCalc2.py -i "+options.JSONname+" lumibyls -b stable --hltpath "+options.HLTpath+" -o TempOut.csv") os.system("pixelLumiCalc.py -i "+options.JSONname+" lumibyls --hltpath "+options.HLTpath+" -o TempOut.csv") ofile = TFile(options.outfilename,"RECREATE") tr = TTree("AnalysisTree","AnalysisTree") s = MyStruct() hltpath = TString("") tr.Branch('run',AddressOf(s,'runnr'),'runnr/i') tr.Branch('luminosityBlock',AddressOf(s,'luminosityBlock'),'luminosityBlock/i') tr.Branch("HLTpath","TString",hltpath) #tr.Branch('L1bit','TString',l1bit) tr.Branch('intgRecLumi',AddressOf(s,'intgRecLumi'),'intgRecLumi/D') tr.Branch('HLTpresc',AddressOf(s,'HLTpresc'),'HLTpresc/D') tr.Branch('L1presc',AddressOf(s,'L1presc'),'L1presc/D') #''' #input: {run:[lumilsnum(0),cmslsnum(1),timestamp(2),beamstatus(3),beamenergy(4),deliveredlumi(5),recordedlumi(6),calibratedlumierror(7),{hltpath:[l1name,l1prescale,hltprescale,efflumi]},bxdata,beamdata]} #'''
def output_file(y_pred_cls,y_pred_adv_cls,evt_weight, y_test, z_test,x_test_index,SIGNAL_FILE,sigtree,BKG_FILE_2018,bkgtree3,alpha_str): # Create a lookup table for discriminator value by event number disc_lookup_signal = {} disc_lookup_bkg = {} disc_lookup_signal_adv = {} disc_lookup_bkg_adv = {} sig_evt_weight={} bkg_evt_weight={} ys=[] h_sig_simple=rt.TH1F("simpleNN_VBF","simpleNN_VBF",100,0.,1.); h_sig_adv=rt.TH1F("advNN_VBF","advNN_VBF",100,0.,1.); h_bkg_simple=rt.TH1F("simpleNN_VBF","simpleNN_VBF",100,0.,1.); h_bkg_adv=rt.TH1F("advNN_VBF","advNN_VBF",100,0.,1.); print len(y_pred_cls), len(y_pred_adv_cls), len(evt_weight), len(y_test), len(x_test_index[:,0]),len(x_test_index[:,1]), len(x_test_index[:,2]) print y_test.sum() ctr=0 for disc_val, disc_val_adv, evt_wt, y_val, mass, run, lumi, event in zip(y_pred_cls, y_pred_adv_cls, evt_weight, y_test, z_test,x_test_index[:,0],x_test_index[:,1], x_test_index[:,2]): ctr+=1 if y_val!=1. and y_val!=0.: print y_val if y_val == 1.: disc_lookup_signal[(run, lumi, event)] = disc_val disc_lookup_signal_adv[(run, lumi, event)] = disc_val_adv sig_evt_weight[(run, lumi, event)] = evt_wt if (mass<120. or mass>130.): h_sig_simple.Fill(disc_val,evt_wt) h_sig_adv.Fill(disc_val_adv, evt_wt) ys.append(1) #print y_val #print disc_val elif y_val == 0: disc_lookup_bkg[(run, lumi, event)] = disc_val disc_lookup_bkg_adv[(run, lumi, event)] = disc_val_adv bkg_evt_weight[(run, lumi, event)] = evt_wt if (mass<120. or mass>130.): h_bkg_simple.Fill(disc_val,evt_wt) h_bkg_adv.Fill(disc_val_adv, evt_wt) #print y_val #print disc_val # We write out the signal and background events to a new ROOT file. # For events in the test set, we append the GBM discriminator. # For events in the train set, we set the discriminator to -1 # to avoid accidentally reusing the training set in the analysis. print np.sum(ys) print len(ys) print ctr print len(disc_lookup_signal), len(disc_lookup_signal_adv) print len(disc_lookup_bkg), len(disc_lookup_bkg_adv) out_signal_name = os.path.basename(SIGNAL_FILE).replace('.root', alpha_str+'_NNscore_new.root') out_signal = rt.TFile(out_signal_name, 'RECREATE') out_signal_tree = sigtree.CloneTree(0) out_bkg_name = os.path.basename(BKG_FILE_2018).replace('.root', alpha_str+'_NNscore_new.root') out_bkg = rt.TFile(out_bkg_name, 'RECREATE') out_bkg_tree3 = bkgtree3.CloneTree(0) rt.gROOT.ProcessLine("struct MyStruct2{float disc_advNN;};") rt.gROOT.ProcessLine("struct MyStruct3{float disc_simpleNN;};") rt.gROOT.ProcessLine("struct MyStruct{double evt_wt;};") from ROOT import MyStruct3, MyStruct2, MyStruct s = MyStruct3() s_adv = MyStruct2() s_wt = MyStruct() disc_branch_sig = out_signal_tree.Branch('disc_simpleNN', rt.AddressOf(s, 'disc_simpleNN'), 'disc_simpleNN/F'); disc_branch_bkg3 = out_bkg_tree3.Branch('disc_simpleNN', rt.AddressOf(s, 'disc_simpleNN'), 'disc_simpleNN/F'); disc_branch_sig_adv = out_signal_tree.Branch('disc_advNN', rt.AddressOf(s_adv, 'disc_advNN'), 'disc_advNN/F'); disc_branch_bkg_adv3 = out_bkg_tree3.Branch('disc_advNN', rt.AddressOf(s_adv, 'disc_advNN'), 'disc_advNN/F'); evt_weight_branch_sig = out_signal_tree.Branch('evt_weight', rt.AddressOf(s_wt, 'evt_wt'), 'evt_weight/D'); evt_weight_branch_bkg3 = out_bkg_tree3.Branch('evt_weight', rt.AddressOf(s_wt, 'evt_wt'), 'evt_weight/D'); print "Writing new ROOT signal file with discriminator appended" fill_discriminator(sigtree, out_signal_tree, disc_lookup_signal,disc_lookup_signal_adv, sig_evt_weight,s, s_adv,s_wt) print "Writing new ROOT background file with discriminator appended" fill_discriminator(bkgtree3, out_bkg_tree3, disc_lookup_bkg,disc_lookup_bkg_adv, bkg_evt_weight,s, s_adv,s_wt) out_signal.cd() h_sig_simple.Write() h_sig_adv.Write() out_signal_tree.GetCurrentFile().Write() out_signal_tree.GetCurrentFile().Close() out_bkg.cd() h_bkg_simple.Write() h_bkg_adv.Write() out_bkg_tree3.GetCurrentFile().Write() out_bkg_tree3.GetCurrentFile().Close() print 'done writing output'
def rewrite_tree(oldfile, newname): f = ROOT.TFile.Open(oldfile) oldtree = f.Get('NOMINAL') gROOT.ProcessLine("struct MyStruct {\ Int_t fEvent;\ Double_t fNOMINAL_pileup_combined_weight;\ Double_t fcross_section;\ Double_t ffilter_efficiency;\ Double_t fkfactor;\ Double_t fweight_mc;\ Double_t fPt;\ Double_t fmetE;\ Double_t fdPhi;\ Double_t fPhiMiss;\ Double_t fMt;\ Double_t fEta;\ };") from ROOT import MyStruct mystruct = MyStruct() f1 = TFile('/eos/user/g/gtolkach/data/' + newname, 'RECREATE') tree = TTree('NOMINAL', 'Just A Tree') tree.Branch('event', mystruct, 'fEvent/I') if oldfile.find('data_mu') == -1: tree.Branch('NOMINAL_pileup_combined_weight', AddressOf(mystruct, 'fNOMINAL_pileup_combined_weight'), 'fNOMINAL_pileup_combined_weight/D') tree.Branch('cross_section', AddressOf(mystruct, 'fcross_section'), 'fcross_section/D') tree.Branch('filter_efficiency', AddressOf(mystruct, 'ffilter_efficiency'), 'ffilter_efficiency/D') tree.Branch('kfactor', AddressOf(mystruct, 'fkfactor'), 'fkfactor/D') tree.Branch('kweight_mc', AddressOf(mystruct, 'fweight_mc'), 'fweight_mc/D') tree.Branch('Pt', AddressOf(mystruct, 'fPt'), 'fPt/D') tree.Branch('metE', AddressOf(mystruct, 'fmetE'), 'fmetE/D') tree.Branch('dPhi', AddressOf(mystruct, 'fdPhi'), 'fdPhi/D') tree.Branch('PhiMiss', AddressOf(mystruct, 'fPhiMiss'), 'fPhiMiss/D') tree.Branch('Mt', AddressOf(mystruct, 'fMt'), 'fMt/D') tree.Branch('Eta', AddressOf(mystruct, 'fEta'), 'fEta/D') cutflowhisto = ROOT.TH1D("cutflow", ";Cut;Event", 5, 1, 6) cutflowhisto.GetXaxis().SetBinLabel(1, "All") cutflowhisto.GetXaxis().SetBinLabel(2, "charge") cutflowhisto.GetXaxis().SetBinLabel(3, "medium ") cutflowhisto.GetXaxis().SetBinLabel(4, "isoTight") cutflowhisto.GetXaxis().SetBinLabel(5, "n_bjets") for i in range(0, oldtree.GetEntries()): # for i in range(0, 60000): oldtree.GetEntry(i) mystruct.fEvent = i cutflowhisto.Fill(1) #cuts if not (oldtree.lep_0_q == -1): continue cutflowhisto.Fill(2) if not (oldtree.lep_0_id_medium == 1): continue cutflowhisto.Fill(3) if not (oldtree.lep_0_iso_FCTight == 1): continue cutflowhisto.Fill(4) if not (oldtree.n_bjets == 0): continue cutflowhisto.Fill(5) # if oldfile.find('data_mu') != -1: # if not(oldtree.lep_0_q == -1): # continue # print(oldtree.lep_0_q) # mystruct.fPt = oldtree.lep_0_p4_fast.Pt() # mystruct.fmetE = oldtree.met_reco_p4_fast.E() # if math.fabs(oldtree.lepmet_dphi) > 3.14159: # mystruct.fdPhi = 2*3.14159 - math.fabs(oldtree.lepmet_dphi) # else: # mystruct.fdPhi = math.fabs(oldtree.lepmet_dphi) # mystruct.fPhiMiss = oldtree.met_reco_p4_fast.Phi() # mystruct.fMt = oldtree.lepmet_mt # mystruct.fEta = oldtree.lep_0_p4_fast.Eta() # # if oldfile.find('data_mu') == -1: # mystruct.fNOMINAL_pileup_combined_weight = oldtree.NOMINAL_pileup_combined_weight # mystruct.fcross_section = oldtree.cross_section # mystruct.ffilter_efficiency = oldtree.filter_efficiency # mystruct.fkfactor = oldtree.kfactor # mystruct.fweight_mc = oldtree.weight_mc mystruct.fPt = oldtree.lep_0_p4_fast.Pt() mystruct.fmetE = oldtree.met_reco_p4_fast.E() if math.fabs(oldtree.lepmet_dphi) > 3.14159: mystruct.fdPhi = 2 * 3.14159 - math.fabs(oldtree.lepmet_dphi) else: mystruct.fdPhi = math.fabs(oldtree.lepmet_dphi) mystruct.fPhiMiss = oldtree.met_reco_p4_fast.Phi() mystruct.fMt = oldtree.lepmet_mt mystruct.fEta = oldtree.lep_0_p4_fast.Eta() tree.Fill() if oldfile.find('data_mu') == -1: h_metadata = f.Get('h_metadata') h_metadata.Write() c1 = ROOT.TCanvas() cutflowhisto.Draw() c1.Draw() c1.SaveAs('hist.pdf') f1.Write() f.Close() f1.Close()
# For events in the train set, we set the discriminator to -1 # to avoid accidentally reusing the training set in the analysis. out_signal_name = os.path.basename(signalFileName).replace( '.root', '_BDT.root') out_signal = root.TFile(out_signal_name, 'RECREATE') out_signal_tree = signalTree.CloneTree(0) out_bkg_name = os.path.basename(bkgFileName).replace('.root', '_BDT.root') out_bkg = root.TFile(out_bkg_name, 'RECREATE') out_bkg_tree = bkgTree.CloneTree(0) # This is the boilerplate code for writing something # to a ROOT tree from Python. root.gROOT.ProcessLine("struct MyStruct{float disc;};") from ROOT import MyStruct s = MyStruct() disc_branch_sig = out_signal_tree.Branch('disc', root.AddressOf(s, 'disc'), 'disc/F') disc_branch_bkg = out_bkg_tree.Branch('disc', root.AddressOf(s, 'disc'), 'disc/F') print "Writing new ROOT signal file with discriminator appended" fill_discriminator(signalTree, out_signal_tree, disc_lookup_signal, s) print "Writing new ROOT background file with discriminator appended" fill_discriminator(bkgTree, out_bkg_tree, disc_lookup_bkg, s) # Cristian's code uses GetCurrentFile() for this part. # I will do that too just in case (paranoia). out_signal.cd() out_signal_tree.GetCurrentFile().Write() #signalNevents.Write()
from random import shuffle ############################## ######### GENERATION ######### ############################## gROOT.ProcessLine( "struct MyStruct {\ Float_t f_muonMass1;\ Float_t f_muonMass2;\ Float_t f_muonMass3;\ Float_t f_muonMass4;\ };" ) from ROOT import MyStruct mystruct = MyStruct() f = TFile( 'ZBosonNtuple.root', 'RECREATE' ) tree = TTree( 'T', 'Z Boson Data' ) tree.Branch( 'muons', mystruct, 'f_muonMass1/F:f_muonMass2:f_muonMass3:f_muonMass4' ) rand = TRandom() muonMass = {} for i in range(10000): muonMass[0] = rand.Exp(30)*90 muonMass[1] = abs(rand.Gaus(91.2,1.3) - muonMass[0]) muonMass[2] = rand.Exp(30) muonMass[3] = rand.Exp(30)
nEntries = ch.GetEntries() print "nEntries = ", nEntries #*****set brances***** #set branche satus, at first, all off #event information #new tree outFile = FileName + '_HH_no_PNet_Discriminator.root' newFile = root.TFile(outFile, "RECREATE") ch_new = ch.CloneTree(0) root.gROOT.ProcessLine("struct MyStruct{float disc_hh;};") from ROOT import MyStruct # Create branches in the tree s = MyStruct() bpt = ch_new.Branch('disc_hh', root.AddressOf(s, 'disc_hh'), 'disc_hh/F') for i in range(nEntries): ch.GetEntry(i) if i % 10000 == 0: print "Processing event nr. %i of %i" % (i, nEntries) s.disc_hh = disc[i] ch_new.Fill() ch_new.Print() # use GetCurrentFile just in case we went over the # (customizable) maximum file size ch_new.GetCurrentFile().Write() Nevents.Write() ch_new.GetCurrentFile().Close()
PID_v = r.vector('Int_t')() P_X_v = r.vector('Double_t')() P_Y_v =r.vector('Double_t')() P_Z_v =r.vector('Double_t')() E_v =r.vector('Double_t')() M_v =r.vector('Double_t')() # Create a struct which acts as the TBranch for non-vectors gROOT.ProcessLine(\ "struct MyStruct{\ Int_t n_particles;\ };") from ROOT import MyStruct # Assign the variables to the struct s = MyStruct() output_tree.Branch('n_particles',AddressOf(s,'n_particles'),'n_particles/I') output_tree.Branch("PID",PID_v) output_tree.Branch("P_X",P_X_v) output_tree.Branch("P_Y",P_Y_v) output_tree.Branch("P_Z",P_Z_v) output_tree.Branch("E",E_v) output_tree.Branch("M",M_v) in_ev = 0 # To know when to look for particles we must know when we are inside an event in_ev_1 = 0 # The first line after <event> is information so we must skip that as well s.n_particles = 0 for line in input_file: if line[:1] == "#": continue
else: return float('nan') structString = "struct MyStruct{ULong_t event;" for var in variables: structString +="Float_t "+var+";" for var in extraVariables: structString +="Float_t "+var+";" structString +="};" ROOT.gROOT.ProcessLine(structString) from ROOT import MyStruct s = MyStruct() def getReweightingHisto(filename=""): if filename=="": return "" rf = ROOT.TFile(filename) htmp = rf.Get("ngoodVertices_Data") ROOT.gDirectory.cd("PyROOT:/") rwHisto = htmp.Clone() rf.Close() return rwHisto from defaultMu2012Samples import dy, wjetsInc, ttbar, ttbarPowHeg, stop, getSignal T1tttt = {}
def btagEfficiencyTreeProducer(stageName="Z+jet", output="mybtagEfftree.root", path='../testfiles/'): #search for category number stage=-1 liststage = [] for cat in categoryNames : stage+=1 if stageName in cat : liststage.append(stage) print "Will run on stages: " for ls in liststage : print categoryNames[ls] # prepare output #path='/nfs/user/llbb/Pat_8TeV_ReReco/Summer12_DYjets/pat53_1.root' ROOT.gROOT.ProcessLine( "struct MyStruct {\ Float_t pt;\ Float_t eta;\ Int_t flavor;\ Float_t ssvhe;\ Float_t ssvhp;\ Float_t csv;\ Float_t jbp;\ Float_t jp;\ Float_t csvv1;\ Float_t ivfhe;\ Float_t ivfhp;\ Float_t sv2;\ Float_t csvivf;\ Float_t csvv1sl;\ Float_t eventWeight;\ Float_t CSVMWeight;\ };" ) from ROOT import MyStruct mystruct = MyStruct() f = ROOT.TFile( output, 'RECREATE' ) tree = ROOT.TTree( 'btagEff', 'btag efficiency' ) tree.Branch( 'data', mystruct, 'pt/F:eta/F:flavor/I:ssvhe/F:ssvhp/F:csv/F:jbp/F:jp/F:csvv1/F:ivfhe/F:ivfhp/F:sv2/F:csvivf/F:csvv1sl/F:eventWeight/F:CSVMWeight/F' ) # input if os.path.isdir(path): dirList=os.listdir(path) files=[] for fname in dirList: files.append(path+fname) elif os.path.isfile(path): files=[path] else: files=[] events = AnalysisEvent(files) EventSelection.prepareAnalysisEvent(events) # event loop eventCnt = 0 print "starting loop on events" for event in events: categoryData = event.category goodJets = event.goodJets_all Pass = 0 for ls in liststage: if isInCategory(ls, categoryData) : Pass+=1 if Pass>0: eventCnt = eventCnt +1 if eventCnt%100==0 : print ".", if eventCnt%1000==0 : print eventCnt # event weight mystruct.eventWeight = event.weight(weightList=["PileUp"]) # that's where we access the jets for index,jet in enumerate(event.jets): if not goodJets[index]: continue mystruct.pt = jet.pt() mystruct.eta = jet.eta() mystruct.flavor = jet.partonFlavour() mystruct.ssvhe = jet.bDiscriminator("simpleSecondaryVertexHighEffBJetTags") mystruct.ssvhp = jet.bDiscriminator("simpleSecondaryVertexHighPurBJetTags") mystruct.csv = jet.bDiscriminator("combinedSecondaryVertexBJetTags") mystruct.jbp = jet.bDiscriminator("jetBProbabilityBJetTags") mystruct.jp = jet.bDiscriminator("jetProbabilityBJetTags") mystruct.csvv1 = jet.bDiscriminator("combinedSecondaryVertexV1BJetTags") mystruct.ivfhe = jet.bDiscriminator("simpleInclusiveSecondaryVertexHighEffBJetTags") mystruct.ivfhp = jet.bDiscriminator("simpleInclusiveSecondaryVertexHighPurBJetTags") mystruct.sv2 = jet.bDiscriminator("doubleSecondaryVertexHighEffBJetTags") mystruct.csvivf = jet.bDiscriminator("combinedInclusiveSecondaryVertexBJetTags") mystruct.csvv1sl = jet.bDiscriminator("combinedSecondaryVertexSoftPFLeptonV1BJetTags") btagW.myJetSet.reset() btagW.myJetSet.addJet(configuration.SF_uncert, jet.partonFlavour(),jet.pt(),jet.eta(), btagW.algo1, btagW.algo2) mystruct.CSVMWeight = btagW.getWeight(btagW.myJetSet, 1, 1) tree.Fill() f.Write() f.Close() print ""
def writeXsecTree(box, model, directory, mg, mchi, xsecULObs, xsecULExpPlus2, xsecULExpPlus, xsecULExp, xsecULExpMinus, xsecULExpMinus2): outputFileName = "%s/%s_xsecUL_mg_%s_mchi_%s_%s.root" %(directory, model, mg, mchi, box) print "INFO: xsec UL values being written to %s"%outputFileName fileOut = rt.TFile.Open(outputFileName, "recreate") xsecTree = rt.TTree("xsecTree", "xsecTree") try: from ROOT import MyStruct except ImportError: myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi; Double_t x; Double_t y;" ixsecUL = 0 myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+0) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+1) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+2) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+3) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+4) myStructCmd+= "Double_t xsecUL%i;"%(ixsecUL+5) ixsecUL+=6 myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() xsecTree.Branch("mg", rt.AddressOf(s,"mg"),'mg/D') xsecTree.Branch("mchi", rt.AddressOf(s,"mchi"),'mchi/D') xsecTree.Branch("x", rt.AddressOf(s,"x"),'x/D') xsecTree.Branch("y", rt.AddressOf(s,"y"),'y/D') s.mg = mg s.mchi = mchi if 'T1x' in model: s.x = float(model[model.find('x')+1:model.find('y')].replace('p','.')) s.y = float(model[model.find('y')+1:].replace('p','.')) elif model == 'T1bbbb': s.x = 1 s.y = 0 elif model == 'T1tttt': s.x = 0 s.y = 1 else: s.x = -1 s.y = -1 ixsecUL = 0 xsecTree.Branch("xsecULObs_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+0)),'xsecUL%i/D'%(ixsecUL+0)) xsecTree.Branch("xsecULExpPlus2_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+1)),'xsecUL%i/D'%(ixsecUL+1)) xsecTree.Branch("xsecULExpPlus_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+2)),'xsecUL%i/D'%(ixsecUL+2)) xsecTree.Branch("xsecULExp_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+3)),'xsecUL%i/D'%(ixsecUL+3)) xsecTree.Branch("xsecULExpMinus_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+4)),'xsecUL%i/D'%(ixsecUL+4)) xsecTree.Branch("xsecULExpMinus2_%s"%box, rt.AddressOf(s,"xsecUL%i"%(ixsecUL+5)),'xsecUL%i/D'%(ixsecUL+5)) exec 's.xsecUL%i = xsecULObs[ixsecUL]'%(ixsecUL+0) exec 's.xsecUL%i = xsecULExpPlus2[ixsecUL]'%(ixsecUL+1) exec 's.xsecUL%i = xsecULExpPlus[ixsecUL]'%(ixsecUL+2) exec 's.xsecUL%i = xsecULExp[ixsecUL]'%(ixsecUL+3) exec 's.xsecUL%i = xsecULExpMinus[ixsecUL]'%(ixsecUL+4) exec 's.xsecUL%i = xsecULExpMinus2[ixsecUL]'%(ixsecUL+5) ixsecUL += 4 xsecTree.Fill() fileOut.cd() xsecTree.Write() fileOut.Close() return outputFileName
nEntries = ch.GetEntries() print "nEntries = ", nEntries #*****set brances***** #set branche satus, at first, all off #event information #new tree outFile = FileName + '_ttZDiscriminator.root' newFile = root.TFile(outFile, "RECREATE") ch_new = ch.CloneTree(0) root.gROOT.ProcessLine("struct MyStruct{float disc_ttZ;};") from ROOT import MyStruct # Create branches in the tree s = MyStruct() bpt = ch_new.Branch('disc_ttZ', root.AddressOf(s, 'disc_ttZ'), 'disc_ttZ/F') for i in range(nEntries): ch.GetEntry(i) if i % 10000 == 0: print "Processing event nr. %i of %i" % (i, nEntries) s.disc_ttZ = disc[i] ch_new.Fill() ch_new.Print() # use GetCurrentFile just in case we went over the # (customizable) maximum file size ch_new.GetCurrentFile().Write() Nevents.Write() ch_new.GetCurrentFile().Close()
P_X_v = r.vector('Double_t')() P_Y_v = r.vector('Double_t')() P_Z_v = r.vector('Double_t')() E_v = r.vector('Double_t')() M_v = r.vector('Double_t')() P4_v = r.vector('ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float>>')() Wgt_v = r.vector('Double_t')() # Create a struct which acts as the TBranch for non-vectors gROOT.ProcessLine("struct MyStruct{ Int_t n_particles; };") gROOT.ProcessLine("struct MyFloat{ Float_t weight; };") from ROOT import MyStruct from ROOT import MyFloat # Assign the variables to the struct s = MyStruct() event_wgt = MyFloat() output_tree.Branch('n_particles', AddressOf(s, 'n_particles'), 'n_particles/I') output_tree.Branch("PID", PID_v) output_tree.Branch("P_X", P_X_v) output_tree.Branch("P_Y", P_Y_v) output_tree.Branch("P_Z", P_Z_v) output_tree.Branch("E", E_v) output_tree.Branch("M", M_v) output_tree.Branch("P4", P4_v) output_tree.Branch("Wgt", Wgt_v) output_tree.Branch('event_wgt', AddressOf(event_wgt, 'weight'), 'event_wgt/F') in_ev = 0 # To know when to look for particles we must know when we are inside an event in_ev_1 = 0 # The first line after <event> is information so we must skip that as well in_wgt = 0 # To know when to look for weights we must know when we are inside an event
outputFile = root.TFile(outputFilename, "RECREATE") outputFile.cd() outputTree = inputTree.CloneTree(0) nEntries = inputTree.GetEntries() print("nEntries = ", nEntries) _disc_var_name = 'disc_' + _bkg_type + '_' + _year + '_' + _bdt_type root.gROOT.ProcessLine("struct MyStruct{float disc;};") from ROOT import MyStruct nSamplings = 100 random = root.TRandom3(1000) # Create branches in the tree my_s = MyStruct() my_s_JESUp = MyStruct() my_s_JESDown = MyStruct() my_s_JMSUp = MyStruct() my_s_JMSDown = MyStruct() my_s_JMRUp = MyStruct() my_s_JMRDown = MyStruct() #print(my_s) #print (root.addressof(my_s)) #print (root.addressof(my_s,'disc')) #root.addressof(my_s,'disc') branch_disc = outputTree.Branch(_disc_var_name, root.addressof(my_s, 'disc'), _disc_var_name + '/F') branch_disc_JESUp = outputTree.Branch(_disc_var_name + "_JESUp",
def main1TrackMVA(_name="Lb_Lcmunu_MagUp.root"): #---Get the Track Reconstruction Efficiency correction factor Correction = 1. / 1.035 #This is a number I get from LHCb-PUB-2015-024 #---Set the random number generator, but seed it for reproducibility random.seed(0) #_name = "tupleoutMC_trackeronly_v19" fin = r.TFile.Open(_name, "READ") tin = fin.Get("tupleout/DecayTree") for br in ["nVeloClusters", "nITClusters", "nOTClusters", "nPVs"]: tin.SetBranchStatus(br, 1) for br in [ "Lb_TRACK_NDOF_DAU*", "Lb_PT_DAU*", "Lb_P_DAU*", "Lb_IPCHI2_OWNPV_DAU*", "Lb_TRACK_GHOSTPROB_DAU*", "Lb_TRACK_CHI2_DAU*" ]: tin.SetBranchStatus(br, 1) for br in ["*COMB*", "Lb_HLt1TwoTrackMVAEmulations*"]: tin.SetBranchStatus(br, 1) for head in ["mu", "K", "pi", "p"]: for br in ["PT", "IPCHI2_OWNPV", "PX", "PY", "PZ", "PT", "P"]: tin.SetBranchStatus(head + "_" + br, 1) fout = r.TFile.Open(_name[:-5] + '_wHLT1OneTrackEmulation.root', 'RECREATE') tout = r.TTree("DecayTree", "DecayTree") r.gROOT.ProcessLine("struct MyStruct0{Bool_t abool;};") r.gROOT.ProcessLine("struct MyStruct{Int_t aint;};") r.gROOT.ProcessLine("struct MyStruct2{Float_t afloat;};") from ROOT import MyStruct0 from ROOT import MyStruct from ROOT import MyStruct2 isGECPassed = MyStruct0() isTrackPassed_K = MyStruct0() isTrackPassed_p = MyStruct0() isTrackPassed_pi = MyStruct0() isAdditional_K = MyStruct0() isAdditional_p = MyStruct0() isAdditional_pi = MyStruct0() isPassed_K = MyStruct0() isPassed_p = MyStruct0() isPassed_pi = MyStruct0() isTrackReco_K = MyStruct0() isTrackReco_p = MyStruct0() isTrackReco_pi = MyStruct0() HLT1TrackMVA_TOS_K = MyStruct0() HLT1TrackMVA_TOS_p = MyStruct0() HLT1TrackMVA_TOS_pi = MyStruct0() HLT1TrackMVA_TOS_Corr_K = MyStruct0() HLT1TrackMVA_TOS_Corr_p = MyStruct0() HLT1TrackMVA_TOS_Corr_pi = MyStruct0() Lc_HLT1TrackMVA_Emu_TOS = MyStruct() Lc_HLT1TrackMVA_Emu_EffCorrected_TOS = MyStruct() Lc_HLT1TwoTrackMVA_Emu_TOS = MyStruct() Lc_HLT1TwoTrackMVA_Emu_EffCorrected_TOS = MyStruct() mu_Phi = MyStruct2() K_Phi = MyStruct2() pi_Phi = MyStruct2() p_Phia = MyStruct2() mu_Theta = MyStruct2() K_Theta = MyStruct2() pi_Theta = MyStruct2() p_Theta = MyStruct2() isGECPassed_branch = tout.Branch("isGECPassed", r.AddressOf(isGECPassed, 'abool'), "isGECPassed/B") isTrackPassed_branch_K = tout.Branch("isTrackPassed_K", r.AddressOf(isTrackPassed_K, 'abool'), "isTrackPassed_K/B") isTrackPassed_branch_p = tout.Branch("isTrackPassed_p", r.AddressOf(isTrackPassed_p, 'abool'), "isTrackPassed_p/B") isTrackPassed_branch_pi = tout.Branch( "isTrackPassed_pi", r.AddressOf(isTrackPassed_pi, 'abool'), "isTrackPassed_pi/B") isAdditional_branch_K = tout.Branch("isAdditional_K", r.AddressOf(isAdditional_K, 'abool'), "isAdditional_K/B") isAdditional_branch_p = tout.Branch("isAdditional_p", r.AddressOf(isAdditional_p, 'abool'), "isAdditional_p/B") isAdditional_branch_pi = tout.Branch("isAdditional_pi", r.AddressOf(isAdditional_pi, 'abool'), "isAdditional_pi/B") isPassed_branch_K = tout.Branch("isPassed_K", r.AddressOf(isPassed_K, 'abool'), "isPassed_K/B") isPassed_branch_p = tout.Branch("isPassed_p", r.AddressOf(isPassed_p, 'abool'), "isPassed_p/B") isPassed_branch_pi = tout.Branch("isPassed_pi", r.AddressOf(isPassed_pi, 'abool'), "isPassed_pi/B") isTrackReco_branch_K = tout.Branch("isTrackReco_K", r.AddressOf(isTrackReco_K, 'abool'), "isTrackReco_K/B") isTrackReco_branch_p = tout.Branch("isTrackReco_p", r.AddressOf(isTrackReco_p, 'abool'), "isTrackReco_p/B") isTrackReco_branch_pi = tout.Branch("isTrackReco_pi", r.AddressOf(isTrackReco_pi, 'abool'), "isTrackReco_pi/B") HLT1TrackMVA_Emu_TOS_branch_K = tout.Branch( "HLT1TrackMVA_TOS_K", r.AddressOf(HLT1TrackMVA_TOS_K, 'abool'), "HLT1TrackMVA_TOS_K/B") HLT1TrackMVA_Emu_TOS_branch_p = tout.Branch( "HLT1TrackMVA_TOS_p", r.AddressOf(HLT1TrackMVA_TOS_p, 'abool'), "HLT1TrackMVA_TOS_p/B") HLT1TrackMVA_Emu_TOS_branch_pi = tout.Branch( "HLT1TrackMVA_TOS_pi", r.AddressOf(HLT1TrackMVA_TOS_pi, 'abool'), "HLT1TrackMVA_TOS_pi/B") HLT1TrackMVA_Emu_TOS_Corr_branch_K = tout.Branch( "HLT1TrackMVA_TOS_Corr_K", r.AddressOf(HLT1TrackMVA_TOS_Corr_K, 'abool'), "HLT1TrackMVA_TOS_Corr_K/B") HLT1TrackMVA_Emu_TOS_Corr_branch_p = tout.Branch( "HLT1TrackMVA_TOS_Corr_p", r.AddressOf(HLT1TrackMVA_TOS_Corr_p, 'abool'), "HLT1TrackMVA_TOS_Corr_p/B") HLT1TrackMVA_Emu_TOS_Corr_branch_pi = tout.Branch( "HLT1TrackMVA_TOS_Corr_pi", r.AddressOf(HLT1TrackMVA_TOS_Corr_pi, 'abool'), "HLT1TrackMVA_TOS_Corr_pi/B") Lc_HLT1TrackMVA_Emu_TOS_branch = tout.Branch( "Lc_HLT1TrackMVA_Emu_TOS", r.AddressOf(Lc_HLT1TrackMVA_Emu_TOS, 'aint'), "Lc_HLT1TrackMVA_Emu_TOS/I") Lc_HLT1TrackMVA_Emu_EffCorrected_TOS_branch = tout.Branch( "Lc_HLT1TrackMVA_Emu_EffCorrected_TOS", r.AddressOf(Lc_HLT1TrackMVA_Emu_EffCorrected_TOS, 'aint'), "Lc_HLT1TrackMVA_Emu_EffCorrected_TOS/I") Lc_HLT1TwoTrackMVA_Emu_TOS_branch = tout.Branch( "Lc_HLT1TwoTrackMVA_Emu_TOS", r.AddressOf(Lc_HLT1TwoTrackMVA_Emu_TOS, 'aint'), "Lc_HLT1TwoTrackMVA_Emu_TOS/I") Lc_HLT1TwoTrackMVA_Emu_EffCorrected_TOS_branch = tout.Branch( "Lc_HLT1TwoTrackMVA_Emu_EffCorrected_TOS", r.AddressOf(Lc_HLT1TwoTrackMVA_Emu_EffCorrected_TOS, 'aint'), "Lc_HLT1TwoTrackMVA_Emu_EffCorrected_TOS/I") mu_Phi_branch = tout.Branch("mu_Phi", r.AddressOf(mu_Phi, "afloat"), "mu_Phi/F") K_Phi_branch = tout.Branch("K_Phi", r.AddressOf(K_Phi, "afloat"), "K_Phi/F") pi_Phi_branch = tout.Branch("pi_Phi", r.AddressOf(pi_Phi, "afloat"), "pi_Phi/F") p_Phi_branch = tout.Branch("p_Phi", r.AddressOf(p_Phia, "afloat"), "p_Phi/F") mu_Theta_branch = tout.Branch("mu_Theta", r.AddressOf(mu_Theta, "afloat"), "mu_Theta/F") K_Theta_branch = tout.Branch("K_Theta", r.AddressOf(K_Theta, "afloat"), "K_Theta/F") pi_Theta_branch = tout.Branch("pi_Theta", r.AddressOf(pi_Theta, "afloat"), "pi_Theta/F") p_Theta_branch = tout.Branch("p_Theta", r.AddressOf(p_Theta, "afloat"), "p_Theta/F") #------------------------------------------------------------------------------------------------------------- NEvents = tin.GetEntries() i = 0 print("Processing events ...") for ev in tin: if (i % 1000 == 0): sys.stdout.write("\rProcessed " + str(round(float(i) / NEvents * 100, 2)) + "%") sys.stdout.flush() #if (i == 15000): # break Lc_HLT1TrackMVA_Emu_TOS.aint = 0 Lc_HLT1TrackMVA_Emu_EffCorrected_TOS.aint = 0 Lc_HLT1TwoTrackMVA_Emu_TOS.aint = 0 Lc_HLT1TwoTrackMVA_Emu_EffCorrected_TOS.aint = 0 mu_Phi.afloat = 0 K_Phi.afloat = 0 pi_Phi.afloat = 0 p_Phia.afloat = 0 mu_Theta.afloat = 0 K_Theta.afloat = 0 pi_Theta.afloat = 0 p_Theta.afloat = 0 #------------------------------------------------------------------------------ #---Global event decisions GECvariables = GetGECVariables(ev) IsGECPassed = GECDecision(GECvariables) isGECPassed.abool = IsGECPassed #---Save all needed informations once for all Variables_vec = {} AdditionalVariables_vec = {} TwoTrackVariables_vec = {} for head in ["DAU_1", "DAU_2", "DAU_3", "DAU_4"]: Variables_vec[head] = GetVariables(head, ev) AdditionalVariables_vec[head] = AdditionalVariables( ev, head, Correction) for head in ["1_2", "1_3", "1_4", "2_3", "2_4", "3_4"]: TwoTrackVariables_vec[head] = GetTwoTrackVariables(ev, head) #---Single particle decisions for head in ["DAU_1", "DAU_2", "DAU_3"]: IsTrackPassed = TrackInputDecision(Variables_vec[head]) IsAdditional = TrackAdditionalDecision( AdditionalVariables_vec[head]) IsPassed = TrackMVADecision(Variables_vec[head]) IsTrackReconstructed = TrackReconstructedDecision( AdditionalVariables_vec[head]) if head == "DAU_1": isTrackPassed_K.abool = IsTrackPassed isAdditional_K.abool = IsAdditional isPassed_K.abool = IsPassed isTrackReco_K.abool = IsTrackReconstructed if head == "DAU_2": isTrackPassed_p.abool = IsTrackPassed isAdditional_p.abool = IsAdditional isPassed_p.abool = IsPassed isTrackReco_p.abool = IsTrackReconstructed if head == "DAU_3": isTrackPassed_pi.abool = IsTrackPassed isAdditional_pi.abool = IsAdditional isPassed_pi.abool = IsPassed isTrackReco_pi.abool = IsTrackReconstructed if (IsTrackReconstructed and IsPassed and IsGECPassed and IsTrackPassed and IsAdditional): Lc_HLT1TrackMVA_Emu_EffCorrected_TOS.aint = 1 if (IsPassed and IsGECPassed and IsTrackPassed and IsAdditional): Lc_HLT1TrackMVA_Emu_TOS.aint = 1 ''' #---Two particle decisions for k in range(1,3): j = k+1 while (j<=3): combination = str(k)+"_"+str(j) variables_k = Variables_vec["DAU_"+str(k)] variables_j = Variables_vec["DAU_"+str(j)] AdditionalVariables_k = AdditionalVariables_vec["DAU_"+str(k)] AdditionalVariables_j = AdditionalVariables_vec["DAU_"+str(j)] IsTrackPassed_k = TrackInputDecision(variables_k) IsTrackPassed_j = TrackInputDecision(variables_j) IsTrackPassed = IsTrackPassed_k and IsTrackPassed_j IsAdditional_k = TrackAdditionalDecision(AdditionalVariables_k) IsAdditional_j = TrackAdditionalDecision(AdditionalVariables_j) IsAdditional = IsAdditional_k and IsAdditional_j IsInputPassed_k = TwoTrackInputDecision(variables_k) IsInputPassed_j = TwoTrackInputDecision(variables_j) IsInputPassed = IsInputPassed_k and IsInputPassed_j variables_comb = TwoTrackVariables_vec[combination] IsPassed = TwoTrackMVADecision(variables_comb) IsTrackReconstructed_k = TrackReconstructedDecision(AdditionalVariables_k) IsTrackReconstructed_j = TrackReconstructedDecision(AdditionalVariables_j) IsTrackReconstructed = IsTrackReconstructed_k and IsTrackReconstructed_j if (IsPassed and IsInputPassed and IsGECPassed and IsTrackPassed and IsAdditional): Lc_HLT1TwoTrackMVA_Emu_TOS.aint = 1 if (IsTrackReconstructed and IsPassed and IsInputPassed and IsGECPassed and IsTrackPassed and IsAdditional): Lc_HLT1TwoTrackMVA_Emu_EffCorrected_TOS.aint = 1 j = j+1 #-----Fill the additional variables mu_Phi.afloat = math.atan(getattr(tin, "mu_PY") / getattr(tin, "mu_PX" )) K_Phi.afloat = math.atan(getattr(tin, "K_PY") / getattr(tin, "K_PX" )) p_Phia.afloat = math.atan(getattr(tin, "p_PY") / getattr(tin, "p_PX")) pi_Phi.afloat = math.atan(getattr(tin, "pi_PY") / getattr(tin, "pi_PX")) mu_Theta.afloat = math.acos(getattr(tin, "mu_PZ") / getattr(tin, "mu_P" )) K_Theta.afloat = math.acos(getattr(tin, "K_PZ") / getattr(tin, "K_P" )) p_Theta.afloat = math.acos(getattr(tin, "p_PZ") / getattr(tin, "p_P")) pi_Theta.afloat = math.acos(getattr(tin, "pi_PZ") / getattr(tin, "pi_P")) ''' i = i + 1 tout.Fill() print("\nAll events processed.") tout.Write() fout.Close() fin.Close()
# Setup output branches Layer_v = r.vector('Int_t')() Sector_v = r.vector('Int_t')() Id_v = r.vector('Int_t')() Edep_v =r.vector('Double_t')() X_v = r.vector('Double_t')() Y_v =r.vector('Double_t')() Z_v =r.vector('Double_t')() # Create a struct which acts as the TBranch for non-vectors gROOT.ProcessLine( "struct MyStruct{ Int_t n_hits; Int_t PID_v; Double_t P_X_v; Double_t P_Y_v; Double_t P_Z_v;};") from ROOT import MyStruct # Assign the variables to the struct s = MyStruct() output_tree.Branch('N_hits',AddressOf(s,'n_hits'),'n_hits/I') output_tree.Branch("PID",AddressOf(s,'PID_v'),'PID_v/I') output_tree.Branch("P_X",AddressOf(s,'P_X_v'),'P_X_v/D') output_tree.Branch("P_Y",AddressOf(s,'P_Y_v'),'P_Y_v/D') output_tree.Branch("P_Z",AddressOf(s,'P_Z_v'),'P_Z_v/D') output_tree.Branch("Edep",Edep_v) output_tree.Branch("X",X_v) output_tree.Branch("Y",Y_v) output_tree.Branch("Z",Z_v) output_tree.Branch("Layer",Layer_v) output_tree.Branch("Sector",Sector_v) output_tree.Branch("Id",Id_v) in_ev = 0 # To know when to look for particles we must know when we are inside an event in_ev_1 = 0 # The first line after <event> is information so we must skip that as well s.n_hits = 0