ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/VHbb/python/evaluateMVA.py
(Generate patch)

Comparing UserCode/VHbb/python/evaluateMVA.py (file contents):
Revision 1.17 by peller, Tue Nov 27 09:00:27 2012 UTC vs.
Revision 1.25 by bortigno, Tue Feb 19 18:03:41 2013 UTC

# Line 1 | Line 1
1   #!/usr/bin/env python
2 + from __future__ import print_function
3   import sys
4   import os
5   import ROOT
5 from ROOT import TFile
6   from array import array
7   from math import sqrt
8   from copy import copy
# Line 10 | Line 10 | from copy import copy
10   import warnings
11   warnings.filterwarnings( action='ignore', category=RuntimeWarning, message='creating converter.*' )
12   from optparse import OptionParser
13 from BetterConfigParser import BetterConfigParser
14 from samplesclass import sample
15 from mvainfos import mvainfo
13   import pickle
14 < from progbar import progbar
18 < from printcolor import printc
14 >
15  
16   #CONFIGURE
17 < print 'hello'
17 > ROOT.gROOT.SetBatch(True)
18 > print('hello')
19   #load config
23 #os.mkdir(path+'/sys')
20   argv = sys.argv
21   parser = OptionParser()
22   parser.add_option("-U", "--update", dest="update", default=0,
23                        help="update infofile")
24   parser.add_option("-D", "--discr", dest="discr", default="",
25                        help="discriminators to be added")
30 #parser.add_option("-I", "--inpath", dest="inpath", default="",
31 #                      help="path to samples")
32 #parser.add_option("-O", "--outpath", dest="outpath", default="",
33 #                      help="path where to store output samples")
26   parser.add_option("-S", "--samples", dest="names", default="",
27                        help="samples you want to run on")
28   parser.add_option("-C", "--config", dest="config", default=[], action="append",
29                        help="configuration file")
30   (opts, args) = parser.parse_args(argv)
31 +
32   if opts.config =="":
33          opts.config = "config"
34 +
35 + #Import after configure to get help message
36 + from myutils import BetterConfigParser, progbar, printc, ParseInfo, MvaEvaluator
37 +
38   config = BetterConfigParser()
42 #config.read('./config7TeV_ZZ')
39   config.read(opts.config)
40   anaTag = config.get("Analysis","tag")
41  
42   #get locations:
43   Wdir=config.get('Directories','Wdir')
48 MVASubdir=config.get('Directories','MVAdir')
44   samplesinfo=config.get('Directories','samplesinfo')
45  
46   #systematics
52 systematics=config.get('systematics','systematics')
53 systematics=systematics.split(' ')
54
55 #TreeVar Array
56 #MVA_Vars={}
57 #for systematic in systematics:
58 #    MVA_Vars[systematic]=config.get('treeVars',systematic)
59 #    MVA_Vars[systematic]=MVA_Vars[systematic].split(' ')
60
61 ######################
62 #Evaluate multi: Must Have same treeVars!!!
63
64 #OUTpath=opts.outpath
65 #INpath=opts.inpath
47   INpath = config.get('Directories','MVAin')
48   OUTpath = config.get('Directories','MVAout')
49  
50 < infofile = open(samplesinfo,'r')
51 < info = pickle.load(infofile)
71 < infofile.close()
50 > info = ParseInfo(samplesinfo,INpath)
51 >
52   arglist=opts.discr #RTight_blavla,bsbsb
53  
54   namelistIN=opts.names
55   namelist=namelistIN.split(',')
56  
57 < doinfo=bool(int(opts.update))
57 > #doinfo=bool(int(opts.update))
58  
59   MVAlist=arglist.split(',')
80 MVAdir=config.get('Directories','vhbbpath')
60  
61   #CONFIG
62   #factory
63   factoryname=config.get('factory','factoryname')
64 +
65 + #load the namespace
66 + VHbbNameSpace=config.get('VHbbNameSpace','library')
67 + ROOT.gSystem.Load(VHbbNameSpace)
68 +
69   #MVA
86 #MVAnames=[]
87 #for MVA in MVAlist:
88 #    print MVA
89 #    MVAnames.append(config.get(MVA,'MVAname'))
90 #print Wdir+'/weights/'+factoryname+'_'+MVAname+'.info'
91 #MVAinfofiles=[]
70   MVAinfos=[]
71 + MVAdir=config.get('Directories','vhbbpath')
72   for MVAname in MVAlist:
73      MVAinfofile = open(MVAdir+'/data/'+factoryname+'_'+MVAname+'.info','r')
74      MVAinfos.append(pickle.load(MVAinfofile))
75      MVAinfofile.close()
76      
98 treeVarSet=MVAinfos[0].varset
99 #variables
100 #TreeVar Array
101 MVA_Vars={}
102 for systematic in systematics:
103    MVA_Vars[systematic]=config.get(treeVarSet,systematic)
104    MVA_Vars[systematic]=MVA_Vars[systematic].split(' ')
105 #Spectators:
106 #spectators=config.get(treeVarSet,'spectators')
107 #spectators=spectators.split(' ')
108 #progbar quatsch
77   longe=40
78   #Workdir
79   workdir=ROOT.gDirectory.GetPath()
112 #os.mkdir(Apath+'/MVAout')
80  
81 < #Book TMVA readers: MVAlist=["MMCC_bla","CC5050_bla"]
82 < readers=[]
83 < for MVA in MVAlist:
84 <    readers.append(ROOT.TMVA.Reader("!Color:!Silent"))
85 <
86 < #define variables and specatators
120 < MVA_var_buffer = []
121 < MVA_var_buffer4 = []
122 < for i in range(len( MVA_Vars['Nominal'])):
123 <    MVA_var_buffer.append(array( 'f', [ 0 ] ))
124 <    for reader in readers:
125 <        reader.AddVariable( MVA_Vars['Nominal'][i],MVA_var_buffer[i])
126 < #MVA_spectator_buffer = []
127 < #for i in range(len(spectators)):
128 < #    MVA_spectator_buffer.append(array( 'f', [ 0 ] ))
129 < #    for reader in readers:
130 < #        reader.AddSpectator(spectators[i],MVA_spectator_buffer[i])
131 < #Load raeder
132 < for i in range(0,len(readers)):
133 <    readers[i].BookMVA(MVAinfos[i].MVAname,MVAdir+'/data/'+MVAinfos[i].getweightfile())
134 < #--> Now the MVA is booked
135 <
136 < #Apply samples
137 < infofile = open(samplesinfo,'r')
138 < Ainfo = pickle.load(infofile)
139 < infofile.close()
81 >
82 >
83 > theMVAs = []
84 > for mva in MVAinfos:
85 >    theMVAs.append(MvaEvaluator(config,mva))
86 >
87  
88   #eval
89 < for job in Ainfo:
90 <    if eval(job.active):
91 <        if job.name in namelist:
92 <            #get trees:
93 <            print INpath+'/'+job.prefix+job.identifier+'.root'
94 <            input = TFile.Open(INpath+'/'+job.prefix+job.identifier+'.root','read')
95 <            print OUTpath+'/'+job.prefix+job.identifier+'.root'
96 <            outfile = TFile.Open(OUTpath+'/'+job.prefix+job.identifier+'.root','recreate')
97 <            input.cd()
98 <            obj = ROOT.TObject
99 <            for key in ROOT.gDirectory.GetListOfKeys():
100 <                input.cd()
101 <                obj = key.ReadObj()
102 <                #print obj.GetName()
103 <                if obj.GetName() == job.tree:
104 <                    continue
105 <                outfile.cd()
106 <                #print key.GetName()
107 <                obj.Write(key.GetName())
108 <            tree = input.Get(job.tree)
109 <            nEntries = tree.GetEntries()
110 <            outfile.cd()
111 <            newtree = tree.CloneTree(0)
112 <            #input.Close()
113 <
114 <            #MCs:
115 <            if job.type != 'DATA':
116 <                MVA_formulas={}
117 <                MVA_formulas4={}
118 <                for systematic in systematics:
119 <                    #print '\t\t - ' + systematic
120 <                    MVA_formulas[systematic]=[]
121 <                    MVA_formulas4[systematic]=[]
122 <                    #create TTreeFormulas
123 <                    for j in range(len( MVA_Vars['Nominal'])):
124 <                        MVA_formulas[systematic].append(ROOT.TTreeFormula("MVA_formula%s_%s"%(j,systematic),MVA_Vars[systematic][j],tree))
125 <                        MVA_formulas4[systematic].append(ROOT.TTreeFormula("MVA_formula4%s_%s"%(j,systematic),MVA_Vars['Nominal'][j]+'+('+MVA_Vars[systematic][j]+'-'+MVA_Vars['Nominal'][j]+')*4',tree))#HERE change
126 <                outfile.cd()
127 <                #Setup Branches
128 <                MVAbranches=[]
129 <                MVAbranches4=[]
130 <                for i in range(0,len(readers)):
131 <                    MVAbranches.append(array('f',[0]*11))
132 <                    MVAbranches4.append(array('f',[0]*11))
186 <                    newtree.Branch(MVAinfos[i].MVAname,MVAbranches[i],'nominal:JER_up:JER_down:JES_up:JES_down:beff_up:beff_down:bmis_up:bmis_down:beff1_up:beff1_down/F')
187 <                    newtree.Branch(MVAinfos[i].MVAname+'_4',MVAbranches4[i],'nominal:JER_up:JER_down:JES_up:JES_down:beff_up:beff_down:bmis_up:bmis_down:beff1_up:beff1_down/F')
188 <                print '\n--> ' + job.name +':'
189 <                #progbar setup
190 <                if nEntries >= longe:
191 <                    step=int(nEntries/longe)
192 <                    long=longe
193 <                else:
194 <                    long=nEntries
195 <                    step = 1
196 <                bar=progbar(long)
197 <                #Fill event by event:
198 <                for entry in range(0,nEntries):
199 <                    if entry % step == 0:
200 <                        bar.move()
201 <                    #load entry
202 <                    tree.GetEntry(entry)
203 <                    for systematic in systematics:
204 <                        for j in range(len( MVA_Vars['Nominal'])):
205 <                            MVA_var_buffer[j][0] = MVA_formulas[systematic][j].EvalInstance()
206 <                            
207 <                        for j in range(0,len(readers)):
208 <                            MVAbranches[j][systematics.index(systematic)] = readers[j].EvaluateMVA(MVAinfos[j].MVAname)
209 <                            
210 <                        for j in range(len( MVA_Vars['Nominal'])):
211 <                            MVA_var_buffer[j][0] = MVA_formulas4[systematic][j].EvalInstance()
89 >
90 > samples = info.get_samples(namelist)
91 > print(samples)
92 > for job in samples:
93 >    #get trees:
94 >    print(INpath+'/'+job.prefix+job.identifier+'.root')
95 >    input = ROOT.TFile.Open(INpath+'/'+job.prefix+job.identifier+'.root','read')
96 >    print(OUTpath+'/'+job.prefix+job.identifier+'.root')
97 >    outfile = ROOT.TFile.Open(OUTpath+'/'+job.prefix+job.identifier+'.root','recreate')
98 >    input.cd()
99 >    obj = ROOT.TObject
100 >    for key in ROOT.gDirectory.GetListOfKeys():
101 >        input.cd()
102 >        obj = key.ReadObj()
103 >        #print obj.GetName()
104 >        if obj.GetName() == job.tree:
105 >            continue
106 >        outfile.cd()
107 >        #print key.GetName()
108 >        obj.Write(key.GetName())
109 >    tree = input.Get(job.tree)
110 >    nEntries = tree.GetEntries()
111 >    outfile.cd()
112 >    newtree = tree.CopyTree() #hard skim to get faster
113 >    input.Close()
114 >            
115 >    #Set branch adress for all vars
116 >    for i in range(0,len(theMVAs)):
117 >        theMVAs[i].setVariables(newtree,job)
118 >    outfile.cd()
119 >    #Setup Branches
120 >    mvaVals=[]
121 >    for i in range(0,len(theMVAs)):
122 >        if job.type == 'Data':
123 >            mvaVals.append(array('f',[0]))
124 >            newtree.Branch(MVAinfos[i].MVAname,mvaVals[i],'nominal/F')
125 >        else:
126 >            mvaVals.append(array('f',[0]*11))
127 >            newtree.Branch(theMVAs[i].MVAname,mvaVals[i],'nominal:JER_up:JER_down:JES_up:JES_down:beff_up:beff_down:bmis_up:bmis_down:beff1_up:beff1_down/F')
128 >        MVA_formulas_Nominal = []
129 >        print('\n--> ' + job.name +':')
130 >    #Fill event by event:
131 >    for entry in range(0,nEntries):
132 >        newtree.GetEntry(entry)
133                              
134 <                        for j in range(0,len(readers)):
135 <                            MVAbranches4[j][systematics.index(systematic)] = readers[j].EvaluateMVA(MVAinfos[j].MVAname)
136 <                    #Fill:
137 <                    newtree.Fill()
138 <                newtree.AutoSave()
139 <                outfile.Close()
134 >        for i in range(0,len(theMVAs)):
135 >            theMVAs[i].evaluate(mvaVals[i],job)
136 >        #Fill:
137 >        newtree.Fill()
138 >    newtree.AutoSave()
139 >    outfile.Close()
140                  
141 <            #DATA:
221 <            if job.type == 'DATA':
222 <                #MVA Formulas
223 <                MVA_formulas_Nominal = []
224 <                #create TTreeFormulas
225 <                for j in range(len( MVA_Vars['Nominal'])):
226 <                    MVA_formulas_Nominal.append(ROOT.TTreeFormula("MVA_formula%s_Nominal"%j, MVA_Vars['Nominal'][j],tree))
227 <                outfile.cd()
228 <                MVAbranches=[]
229 <                for i in range(0,len(readers)):
230 <                    MVAbranches.append(array('f',[0]))
231 <                    newtree.Branch(MVAinfos[i].MVAname,MVAbranches[i],'nominal/F')
232 <                    newtree.Branch(MVAinfos[i].MVAname+'_4',MVAbranches[i],'nominal/F')
233 <                #progbar          
234 <                print '\n--> ' + job.name +':'
235 <                if nEntries >= longe:
236 <                    step=int(nEntries/longe)
237 <                    long=longe
238 <                else:
239 <                    long=nEntries
240 <                    step = 1
241 <                bar=progbar(long)
242 <                #Fill event by event:
243 <                for entry in range(0,nEntries):
244 <                    if entry % step == 0:
245 <                        bar.move()
246 <                    #load entry
247 <                    tree.GetEntry(entry)
248 <                    #nominal:
249 <                    for j in range(len( MVA_Vars['Nominal'])):
250 <                            MVA_var_buffer[j][0] = MVA_formulas_Nominal[j].EvalInstance()
251 <                            
252 <                    for j in range(0,len(readers)):
253 <                        MVAbranches[j][0]= readers[j].EvaluateMVA(MVAinfos[j].MVAname)
254 <                    newtree.Fill()
255 <                newtree.AutoSave()
256 <                outfile.Close()
257 <
258 < print '\n'
259 <
260 < #Update Info:
261 < if doinfo:
262 <    for job in Ainfo:        
263 <        for MVAinfo in MVAinfos:
264 <            job.addcomment('Added MVA %s'%MVAinfo.MVAname)
265 <        job.addpath(MVAdir)
266 <    infofile = open(samplesinfo,'w')
267 <    pickle.dump(Ainfo,infofile)
268 <    infofile.close()
269 <
270 <
141 > print('\n')

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines