Пример #1
0
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()
Пример #2
0
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()
Пример #3
0
    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")
Пример #4
0
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'
Пример #5
0
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()
Пример #6
0
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")')
Пример #7
0
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
Пример #8
0
    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))
Пример #9
0
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
Пример #10
0
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'
Пример #11
0
   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

my2 = MyStruct()
my3 = MyStruct()
my4 = MyStruct()
my6 = MyStruct()

tr2.Branch('Arg', AddressOf(my2, 'Arg'), 'Arg/I')
tr2.Branch('Frame', AddressOf(my2, 'Frame'), 'Frame/I')
tr2.Branch('Event_th', AddressOf(my2, 'Event_th'), 'Event_th/I')
tr2.Branch('Split_th', AddressOf(my2, 'Split_th'), 'Split_th/I')
tr2.Branch('X', AddressOf(my2, 'X'), 'X/I')
tr2.Branch('Y', AddressOf(my2, 'Y'), 'Y/I')
tr2.Branch('Xray', AddressOf(my2, 'Xray'), 'Xray/I')
tr2.Branch('PH17', AddressOf(my2, 'PH17'), 'PH17/I')
tr2.Branch('PH18', AddressOf(my2, 'PH18'), 'PH18/I')
tr2.Branch('PH19', AddressOf(my2, 'PH19'), 'PH19/I')
tr2.Branch('PH24', AddressOf(my2, 'PH24'), 'PH24/I')
Пример #12
0
   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')
Пример #13
0
   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');
Пример #14
0
                   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
Пример #15
0
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()
Пример #16
0
def plot(sample, n, v, hbins, hmin, hmax, hlog, xlabel, ylabel, scanlabel,
         scantype):

    global output
    file = {}
    tree = {}
    hist = {}
    leaf = {}
    xsec = {}

    max = 0
    min = 1e99

    x, y = array('d'), array('d')
    graph = {}

    ################ aqui es el comienzo de las especificaciones de root
    if config.STATBOX:
        ROOT.gStyle.SetOptStat(1111)
    else:
        ROOT.gStyle.SetOptStat(0)

    ROOT.gROOT.SetBatch(True)

    ##DISCRETE ITERATION: CREATE HISTOGRAM
    for i, s in enumerate(sample):
        file[s] = TFile(input + s + ".root", "READ")
        tree[s] = file[s].Get("Physics")
        hist[s] = TH1F(s, ";" + v, hbins, hmin, hmax)
        tree[s].Project(s, v, "")
        #Get Cross section from tree
        leaf[s] = tree[s].GetLeaf("xsec1")
        leaf[s].GetBranch().GetEntry(1)
        xsec[s] = leaf[s].GetValue()
        hist[s].SetLineColor(colour[i])
        hist[s].SetLineWidth(2)  #3
        hist[s].SetFillColorAlpha(colour[i], 0.35)
        hist[s].SetFillStyle(3005)
        if "Axial" in s or "Pseudo" in s:
            hist[s].SetLineStyle(2)
        #normalize to 1
        if config.NORM2AU:
            if hist[s].Integral() > 0: hist[s].Scale(1. / hist[s].Integral())
        else:
            #if hist[s].Integral()>0:
            #hist[s].Scale(1./float(xsec[s]))
            hist[s].Scale(float(xsec[s]))

        if hist[s].GetMaximum() > max: max = hist[s].GetMaximum() * 6
        if hist[s].GetMinimum() < min: min = hist[s].GetMinimum()

    ################# Legend ########################
    if config.LEGEND or not config.manual:
        if config.STATBOX:
            leg = TLegend(0.4, 0.9 - 0.035 * len(sample), 0.68,
                          0.89)  # (x1,y1;x2,y2)
        else:
            leg = TLegend(0.5994437, 0.7240964, 0.8706537, 0.8903614)
            #leg = TLegend(0.6, 0.9-0.035*len(sample), 0.88, 0.89) # (x1,y1;x2,y2)

        leg.SetBorderSize(0)
        leg.SetFillStyle(1)  #1001
        leg.SetFillColor(0)

    ##DISCRETE ITERATION: CREATE LEGEND
    for i, s in enumerate(sample):

        #if LEGEND or manual:
        #    #compare different processes
        #    leg.AddEntry(hist[s], s, "l")
        name = s.split("_")[0]
        hzp = s.split("_")[2].split("-")[1]
        hdm = s.split("_")[3].split("-")[1]
        dm = s.split("_")[4].split("-")[1]

        if config.LEGEND:

            text = ""

            if name == 'BBbarDM400Match1jet':
                if 'ScanZp' in scantype:
                    text += " ; M_{Z'} = "
                    text += hzp
                    text += " GeV"
                elif 'ScanDM' in scantype:
                    text += " ; M_{#chi} = "
                    text += dm
                    text += " GeV"
                elif 'Scanhs' in scantype:
                    text += " ; M_{hs} = "
                    text += hdm
                    text += " GeV"

            elif name == 'BBbarDM400':
                if 'ScanZp' in scantype:
                    text += "M_{Z'} = "
                    text += hzp
                    text += " GeV"
                elif 'ScanDM' in scantype:
                    text += " ; M_{#chi} = "
                    text += dm
                    text += " GeV"
                elif 'Scanhs' in scantype:
                    text += " ; M_{hs} = "
                    text += hdm
                    text += " GeV"

            elif name == 'BBbarDM':
                #text+="BBbarDM"
                if 'ScanZp' in scantype:
                    text += "M_{Z'} = "
                    text += hzp
                    text += " GeV"
                elif 'ScanDM' in scantype:
                    text += " ; M_{#chi} = "
                    text += dm
                    text += " GeV"
                elif 'Scanhs' in scantype:
                    text += " ; M_{hs} = "
                    text += hdm
                    text += " GeV"

            elif name == 'DiJetsDM':
                #text+="DiJetsDM"
                if 'ScanZp' in scantype:
                    text += "M_{Z'} = "
                    text += hzp
                    text += " GeV"
                elif 'ScanDM' in scantype:
                    text += " ; M_{#chi} = "
                    text += dm
                    text += " GeV"
                elif 'Scanhs' in scantype:
                    text += " ; M_{hs} = "
                    text += hdm
                    text += " GeV"

            elif 'MonojetDM' in s:
                #text+="MonojetDM"
                if 'ScanZp' in scantype:
                    text += "M_{Z'} = "
                    text += hzp
                    text += " GeV"
                elif 'ScanDM' in scantype:
                    text += " ; M_{#chi} = "
                    text += dm
                    text += " GeV"
                elif 'Scanhs' in scantype:
                    text += " ; M_{hs} = "
                    text += hdm
                    text += " GeV"

            elif 'HadronicDM' in s:
                #text+="HadronicDM"
                if 'ScanZp' in scantype:
                    text += "M_{Z'} = "
                    text += hzp
                    text += " GeV"
                elif 'ScanDM' in scantype:
                    text += " ; M_{#chi} = "
                    text += dm
                    text += " GeV"
                elif 'Scanhs' in scantype:
                    text += " ; M_{hs} = "
                    text += hdm
                    text += " GeV"

            #mpxsec.append([phi,xsec[s]])
            x.append(float(s.split("_")[2].split("-")[1]))
            y.append(xsec[s])

            leg.AddEntry(hist[s], text, "l")

    c1 = TCanvas("c1", "Gen", 1600,
                 1200)  #1600,1200 Esto es el tamano de la imagen
    c2 = TCanvas("c2", "mpxsec", 1600, 1200)
    c1.cd()
    hist[sample[0]].SetMaximum(max * 1.2)
    hist[sample[0]].SetMinimum(min + 1.e6)

    hist[sample[0]].GetXaxis().SetTitle("%s" % xlabel)
    hist[sample[0]].GetYaxis().SetTitle("%s" % ylabel)
    hist[sample[0]].SetTitle("%s" % n)

    # DISCRETE ITERATION: PLOT AND DRAW
    for i, s in enumerate(sample):
        #hist[s].DrawClone("HIST" if i==0 else "HIST, SAME")
        hist[s].Draw("HIST" if i == 0 else "HIST, SAME")
    if hlog:
        c1.GetPad(0).SetLogy()
    if config.LEGEND:
        leg.Draw()
        c1.Update()

    title = ""
    ############################################

    drawlabel(0.37, 0.934, "CMS Simulation")
    drawlabel(0.47, 0.89, "g_{#chi} = 1.00 ; g_{q} = 0.25 ; th = 0.01")
    #if config.NORM2AU:
    drawlabel(0.45, 0.84, scanlabel)
    #drawlabel( 0.45 , 0.84 , "M_{Z'} = 2 TeV ; M_{#chi} = 100 GeV" )
    if 'BBbarDM' in s:
        if 'Match' in s:
            drawlabel(0.40, 0.77, "p p #rightarrow hs(b#bar{b}) j + #chi#chi")
        else:
            drawlabel(0.40, 0.77, "p p #rightarrow hs(b#bar{b}) + #chi#chi")
    elif 'DiJetsDM' in s:
        drawlabel(0.40, 0.77, "p p #rightarrow Z^{'}(jj) + #chi#chi")
    elif 'MonojetDM' in s:
        drawlabel(0.40, 0.77, "p p #rightarrow j + #chi#chi")
    elif 'HadronicDM' in s:
        drawlabel(0.40, 0.77, "p p #rightarrow jj + b#bar{b}")

    if "Axial" in s:
        output += "Axial_Zprime/"
        drawCMS(36000., "Axial-Vector")
    elif "Vector" in s:
        output += "Vector_Zprime/"
        drawCMS(36000., "Vector")

    if "Scalar" in s:
        output += "Scalar/"
        drawCMS(36000., "Scalar")
    elif "Pseudo" in s:
        output += "Pseudo/"
        drawCMS(36000., "Pseudo")

    #if singlefile==1:
    #    output+="Single_lhe/"
    #elif singlefile==0:
    #    output+="Combine_lhe/"

    #if not os.path.exists(output) and config.manual==0:
    #    os.makedirs(output)

    #Create output
    output += "%s/" % scantype

    if not os.path.exists(output):
        os.makedirs(output)
    #    output+="hs_50/"
    #elif "Mhs-70_" in s:
    #    output+="hs_70/"
    #elif "Mhs-90_" in s:
    #    output+="hs_90/"

    #if not os.path.exists(output):
    #    os.makedirs(output)
    #elif output=="Single_lhe/":
    #    print "folder Single_lhe is created"
    #elif output=="Combine_lhe/":
    #    print "folder Combine_lhe is created"

    if config.FPDF:
        c1.Print(output + title + n + ".pdf")
    if config.FPNG:
        c1.Print(output + title + n + ".png")

    if config.XSEC:

        c2.cd()
        if len(x) == len(y):
            gr = TGraph(len(x), x, y)

            gr.SetLineColor(2)
            gr.SetLineWidth(3)
            gr.SetMarkerColor(4)
            gr.SetMarkerStyle(21)
            gr.SetTitle('#Phi Mass point VS Cross Section')
            gr.GetXaxis().SetTitle('#Phi Mass [GeV]')
            gr.GetYaxis().SetTitle('Cross Section in pb')
            gr.Draw('ACP')

            c2.GetPad(0).SetLogy()

            if config.FPDF:
                c2.Print(output + "Xsec_vs_Masspoints.pdf")
            if config.FPNG:
                c2.Print(output + "Xsec_vs_Masspoints.png")

        else:
            print "Error, different size, x:%s ; y:%s" % (len(x), len(y))

        #### save root file for further process ####
        gROOT.ProcessLine("struct MyStruct{ Float_t mp; Float_t genxsec; };")
        from ROOT import MyStruct
        output_file = TFile(output + "rootfile.root", "RECREATE")
        output_tree = TTree("tree", "tree")
        s = MyStruct()
        output_tree.Branch('mp', AddressOf(s, 'mp'), 'mp/F')
        output_tree.Branch('genxsec', AddressOf(s, 'genxsec'), 'genxsec/F')
        for i, j in zip(x, y):
            s.mp = i
            s.genxsec = j
            output_tree.Fill()
        output_tree.Write()
        output_file.Close()
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",
Пример #18
0
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)

    OUTFILE = LOGDIR.strip('/').split("/")[-1] + '.root'
    #OUTFILE = 'BUGSQUASH.root'

    print " "
    print "OutFile:", OUTFILE
    print "Analyzing " + LOGDIR

    #totalFiles = 0
    ###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:
        print "[ERROR] No valid log/xml file given"
        exit(1)

    ### creating a TTree
    outFile = ROOT.TFile(OUTFILE, "RECREATE")
    perfTree = ROOT.TTree('Performance', 'Performance')
    ### loop over logfiles/jobs
    Total_jobs = 0
    Total_successfulJobs = 0
    #isFirstJob = True
    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

        ###UserQuantities
        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'])

        #	print job_output["Job_Number"]

        ### 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 config[100];\
	  Char_t script[100];\
	  Char_t nevents[100];\
	  Char_t timestamp[100];\
	  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("config", AddressOf(mystruct, 'config'), 'config/C')
    info_tree.Branch("script", AddressOf(mystruct, 'script'), 'script/C')
    info_tree.Branch("nevents", AddressOf(mystruct, 'nevents'), 'nevents/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)

    info_tree.Fill()

    ###############################################################info tree two
    #    information_tree = ROOT.TTree("information_tree","information_tree");
    #    label="site";
    #    configContainer = {}
    #    configContainer[label]=ROOT.std.vector( str )()
    #    information_tree.Branch(str(label),configContainer[str(label)])
    #    configContainer[label].push_back("blubbie");
    #    information_tree.Fill();

    ######

    information_tree = ROOT.TTree("information_tree", "information_tree")

    configContainer = {}

    configunit = "site"
    configContainer[configunit] = ROOT.std.vector(str)()
    information_tree.Branch(str(configunit), configContainer[configunit])
    configContainer[configunit].push_back(bla_site)

    configunit = "config"
    configContainer[configunit] = ROOT.std.vector(str)()
    information_tree.Branch(str(configunit), configContainer[configunit])
    configContainer[configunit].push_back(bla_config)

    configunit = "script"
    configContainer[configunit] = ROOT.std.vector(str)()
    information_tree.Branch(str(configunit), configContainer[configunit])
    configContainer[configunit].push_back(bla_script)

    configunit = "nevents"
    configContainer[configunit] = ROOT.std.vector(str)()
    information_tree.Branch(str(configunit), configContainer[configunit])
    configContainer[configunit].push_back(str(bla_nevents))

    configunit = "timestamp"
    configContainer[configunit] = ROOT.std.vector(str)()
    information_tree.Branch(str(configunit), configContainer[configunit])
    configContainer[configunit].push_back(bla_timestamp)

    information_tree.Fill()

    #############################################3 /something entirely new here -- the job info!

    outFile.Write()
    outFile.Close()
Пример #19
0
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
Пример #20
0
    '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')
Пример #21
0
                        if element not in my_value.keys():
                            raise ValueError(
                                'Dictionary is not 3-vector since missing %s',
                                element)
                        my_struct_code += 'float %s_%s;' % (key, element)
                else:
                    raise ValueError('Unsupported type in JSON')

            my_struct_code += '};'
            log.info('Using following structure for converting Python: %s',
                     my_struct_code)

            ROOT.gROOT.ProcessLine(my_struct_code)

            from ROOT import MyStruct
            my_struct = MyStruct()

            for key in keys:
                my_value = doc[key]
                my_type = type(my_value)

                code = None
                if my_type == unicode:
                    code = 'C'
                elif my_type == int:
                    code = 'I'
                elif my_type == float:
                    code = 'F'
                elif my_type == dict:
                    # Special case, need three branches
                    code = 'F'
Пример #22
0
def output_file_nonTrain(y_pred_cls, y_pred_adv1_cls, y_pred_adv2_cls,
                         y_pred_adv3_cls, evt_weight, x_test_index, z_test,
                         INPUT_FILE, proc_tree, alpha_str1, alpha_str2,
                         alpha_str3):
    # Create a lookup table for discriminator value by event number
    disc_lookup_signal = {}
    disc_lookup_signal_adv1 = {}
    disc_lookup_signal_adv2 = {}
    disc_lookup_signal_adv3 = {}
    proc_evt_weight = {}
    sum = 0
    h_sig_simple = rt.TH1F("simpleNN_VBF", "simpleNN_VBF", 50, 0., 1.)
    h_sig_adv1 = rt.TH1F("advNN_VBF", "advNN_VBF", 50, 0., 1.)
    h_sig_adv2 = rt.TH1F("advNN_VBF", "advNN_VBF", 50, 0., 1.)
    h_sig_adv3 = rt.TH1F("advNN_VBF", "advNN_VBF", 50, 0., 1.)

    h_sig_simple_Z = rt.TH1F("simpleNN_Z", "simpleNN_Z", 50, 0., 1.)
    h_sig_adv1_Z = rt.TH1F("advNN_Z", "advNN_Z", 50, 0., 1.)
    h_sig_adv2_Z = rt.TH1F("advNN_Z", "advNN_Z", 50, 0., 1.)
    h_sig_adv3_Z = rt.TH1F("advNN_Z", "advNN_Z", 50, 0., 1.)
    for disc_val, disc_val_adv1, disc_val_adv2, disc_val_adv3, evt_wt, mass, run, lumi, event in zip(
            y_pred_cls, y_pred_adv1_cls, y_pred_adv2_cls, y_pred_adv3_cls,
            evt_weight, z_test, x_test_index[:, 0], x_test_index[:, 1],
            x_test_index[:, 2]):

        disc_lookup_signal[(run, lumi, event)] = disc_val
        disc_lookup_signal_adv1[(run, lumi, event)] = disc_val_adv1
        disc_lookup_signal_adv2[(run, lumi, event)] = disc_val_adv2
        disc_lookup_signal_adv3[(run, lumi, event)] = disc_val_adv3
        proc_evt_weight[(run, lumi, event)] = evt_wt
        if (mass > 110. and mass < 150. and (mass < 120. or mass > 130.)):
            h_sig_simple.Fill(disc_val, evt_wt)
            h_sig_adv1.Fill(disc_val_adv1, evt_wt)
            h_sig_adv2.Fill(disc_val_adv2, evt_wt)
            h_sig_adv3.Fill(disc_val_adv3, evt_wt)
        if (mass > 76. and mass < 106.):
            h_sig_simple_Z.Fill(disc_val, evt_wt)
            h_sig_adv1_Z.Fill(disc_val_adv1, evt_wt)
            h_sig_adv2_Z.Fill(disc_val_adv2, evt_wt)
            h_sig_adv3_Z.Fill(disc_val_adv3, evt_wt)
        sum += evt_wt
    print "Sum of evt_Weight: ", sum
    # 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_adv1)
    #print INPUT_FILE
    #print os.path.basename(INPUT_FILE)
    out_name = os.path.basename(INPUT_FILE).replace(
        '.root', alpha_str1 + '_NNscore.root')
    out_proc1 = rt.TFile(out_name, 'RECREATE')
    out_proc_tree1 = proc_tree.CloneTree(0)
    out_name = os.path.basename(INPUT_FILE).replace(
        '.root', alpha_str2 + '_NNscore.root')
    out_proc2 = rt.TFile(out_name, 'RECREATE')
    out_proc_tree2 = proc_tree.CloneTree(0)
    out_name = os.path.basename(INPUT_FILE).replace(
        '.root', alpha_str3 + '_NNscore.root')
    out_proc3 = rt.TFile(out_name, 'RECREATE')
    out_proc_tree3 = 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 MyStruct4{float disc_advNN;};")
    rt.gROOT.ProcessLine("struct MyStruct5{float disc_advNN;};")

    rt.gROOT.ProcessLine("struct MyStruct{double evt_wt;};")
    from ROOT import MyStruct3, MyStruct2, MyStruct, MyStruct4, MyStruct5
    s = MyStruct3()
    s_adv1 = MyStruct2()
    s_adv2 = MyStruct4()
    s_adv3 = MyStruct5()
    s_wt = MyStruct()
    disc_branch_proc1 = out_proc_tree1.Branch('disc_simpleNN',
                                              rt.AddressOf(s, 'disc_simpleNN'),
                                              'disc_simpleNN/F')
    disc_branch_proc2 = out_proc_tree2.Branch('disc_simpleNN',
                                              rt.AddressOf(s, 'disc_simpleNN'),
                                              'disc_simpleNN/F')
    disc_branch_proc3 = out_proc_tree3.Branch('disc_simpleNN',
                                              rt.AddressOf(s, 'disc_simpleNN'),
                                              'disc_simpleNN/F')
    disc_branch_sig_proc1 = out_proc_tree1.Branch(
        'disc_advNN', rt.AddressOf(s_adv1, 'disc_advNN'), 'disc_advNN/F')
    disc_branch_sig_proc2 = out_proc_tree2.Branch(
        'disc_advNN', rt.AddressOf(s_adv2, 'disc_advNN'), 'disc_advNN/F')
    disc_branch_sig_proc3 = out_proc_tree3.Branch(
        'disc_advNN', rt.AddressOf(s_adv3, 'disc_advNN'), 'disc_advNN/F')
    evt_weight_branch_proc1 = out_proc_tree1.Branch(
        'evt_weight', rt.AddressOf(s_wt, 'evt_wt'), 'evt_weight/D')
    evt_weight_branch_proc2 = out_proc_tree2.Branch(
        'evt_weight', rt.AddressOf(s_wt, 'evt_wt'), 'evt_weight/D')
    evt_weight_branch_proc3 = out_proc_tree3.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_tree1, out_proc_tree2,
                       out_proc_tree3, disc_lookup_signal,
                       disc_lookup_signal_adv1, disc_lookup_signal_adv2,
                       disc_lookup_signal_adv3, proc_evt_weight, s, s_adv1,
                       s_adv2, s_adv3, s_wt)

    # Cristian's code uses GetCurrentFile() for this part.
    # I will do that too just in case (paranoia).
    out_proc1.cd()
    h_sig_simple.Write()
    h_sig_adv1.Write()
    h_sig_simple_Z.Write()
    h_sig_adv1_Z.Write()
    out_proc_tree1.GetCurrentFile().Write()
    #signalNevents.Write()
    out_proc_tree1.GetCurrentFile().Close()

    out_proc2.cd()
    h_sig_simple.Write()
    h_sig_adv2.Write()
    h_sig_simple_Z.Write()
    h_sig_adv2_Z.Write()
    out_proc_tree2.GetCurrentFile().Write()
    #signalNevents.Write()
    out_proc_tree2.GetCurrentFile().Close()

    out_proc3.cd()
    h_sig_simple.Write()
    h_sig_adv3.Write()
    h_sig_simple_Z.Write()
    h_sig_adv3_Z.Write()
    out_proc_tree3.GetCurrentFile().Write()
    #signalNevents.Write()
    out_proc_tree3.GetCurrentFile().Close()
    print 'done writing output'
Пример #23
0
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')
Пример #24
0
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
Пример #25
0
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;\
  };")
    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'
    )
    # 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
        if event.bestZmumuCandidate and event.bestZelelCandidate:
            goodJets = event.goodJets_all
        elif event.bestZelelCandidate:
            goodJets = event.goodJets_ele
        elif event.bestZmumuCandidate:
            goodJets = event.goodJets_mu
        else:
            goodJets = event.goodJets_none
        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")
                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
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()
Пример #28
0
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()
Пример #29
0
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