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

Comparing UserCode/VHbb/python/myutils/HistoMaker.py (file contents):
Revision 1.2 by nmohr, Fri Jan 25 16:18:00 2013 UTC vs.
Revision 1.4 by peller, Tue Feb 5 10:02:03 2013 UTC

# Line 5 | Line 5 | from array import array
5   from printcolor import printc
6   from BetterConfigParser import BetterConfigParser
7   from TreeCache import TreeCache
8 + from math import sqrt
9 + from copy import copy
10  
11   class HistoMaker:
12      def __init__(self, samples, path, config, optionsList):
13          self.path = path
14          self.config = config
15          self.optionsList = optionsList
16 +        self.nBins = optionsList[0]['nBins']
17          self.lumi=0.
18          self.cuts = []
19          for options in optionsList:
20              self.cuts.append(options['cut'])
21 <        self.tc = TreeCache(self.cuts,samples,path)
22 <
21 >        #self.tc = TreeCache(self.cuts,samples,path)
22 >        self.tc = TreeCache(self.cuts,samples,path,config)
23 >        self._rebin = False
24 >        self.mybinning = None
25  
26      def get_histos_from_tree(self,job):
27          if self.lumi == 0:
28              raise Exception("You're trying to plot with no lumi")
29          
30          hTreeList=[]
26        groupList=[]
31  
32          #get the conversion rate in case of BDT plots
33          TrainFlag = eval(self.config.get('Analysis','TrainFlag'))
# Line 39 | Line 43 | class HistoMaker:
43              group=job.group
44              treeVar=options['var']
45              name=options['name']
46 <            nBins=int(options['nBins'])
46 >            nBins=self.nBins
47 >            #int(options['nBins'])
48              xMin=float(options['xMin'])
49              xMax=float(options['xMax'])
50              weightF=options['weight']
# Line 60 | Line 65 | class HistoMaker:
65                  else:
66                      full=False
67              elif job.type == 'DATA':
68 <                if options['blind'] == 'blind':
64 <                    output.cd()
68 >                if options['blind']:
69                      if treeVar == 'H.mass':
70                          CuttedTree.Draw('%s>>%s(%s,%s,%s)' %(treeVar,name,nBins,xMin,xMax),treeVar+'<90. || '+treeVar + '>150.' , "goff,e")
71                      else:
# Line 98 | Line 102 | class HistoMaker:
102                  hTree.SetBinError(1,uFlowErr)
103                  hTree.SetBinError(hTree.GetNbinsX(),oFlowErr)
104              hTree.SetDirectory(0)
105 <            hTreeList.append(hTree)
106 <            groupList.append(group)
107 <        
108 <        return hTreeList, groupList
109 <        
110 <
111 < ######################
112 < def orderandadd(histos,typs,setup):
113 < #ORDER AND ADD TOGETHER
114 <    ordnung=[]
115 <    ordnungtyp=[]
116 <    num=[0]*len(setup)
117 <    for i in range(0,len(setup)):
118 <        for j in range(0,len(histos)):
119 <            if typs[j] in setup[i]:
120 <                num[i]+=1
121 <                ordnung.append(histos[j])
122 <                ordnungtyp.append(typs[j])
123 <    del histos
124 <    del typs
125 <    histos=ordnung
126 <    typs=ordnungtyp
127 <    print typs
128 <    for k in range(0,len(num)):
129 <        for m in range(0,num[k]):
130 <            if m > 0:
131 <                #add
132 <                histos[k].Add(histos[k+1],1)
133 <                printc('magenta','','\t--> added %s to %s'%(typs[k],typs[k+1]))
134 <                del histos[k+1]
135 <                del typs[k+1]
136 <    del histos[len(setup):]
137 <    del typs[len(setup):]
138 <    return histos, typs
105 >            gDict = {}
106 >            if self._rebin:
107 >                gDict[group] = self.mybinning.rebin(hTree)
108 >            else:
109 >                gDict[group] = hTree
110 >            hTreeList.append(gDict)
111 >        return hTreeList
112 >      
113 >    @property
114 >    def rebin(self):
115 >        return self._rebin
116 >
117 >    @property
118 >    def rebin(self, value):
119 >        if self._rebin and value:
120 >            return True
121 >        elif self._rebin and not value:
122 >            self.nBins = self.norebin_nBins
123 >            self._rebin = False
124 >        elif not self._rebin and value:
125 >            if self.mybinning is None:
126 >                raise Exception('define rebinning first')
127 >            else:
128 >                self.nBins = self.rebin_nBins
129 >                self._rebin = True
130 >                return True
131 >        elif not self._rebin and not self.value:
132 >            return False
133 >
134 >    def calc_rebin(self, bg_list, nBins_start=1000, tolerance=0.35):
135 >        self.norebin_nBins = self.nBins
136 >        self.rebin_nBins = nBins_start
137 >        self.nBins = nBins_start
138 >        i=0
139 >        #add all together:
140 >        for job in bg_list:
141 >            if not i:
142 >                totalBG = self.get_histos_from_tree(job)[0].values()[0]
143 >            else:
144 >                totalBG.Add(self.get_histos_from_tree(job)[0].values()[0],1)
145 >            i+=1
146 >        ErrorR=0
147 >        ErrorL=0
148 >        TotR=0
149 >        TotL=0
150 >        binR=self.rebin_nBins
151 >        binL=1
152 >        rel=1.0
153 >        #---- from right
154 >        while rel > tolerance:
155 >            TotR+=totalBG.GetBinContent(binR)
156 >            ErrorR=sqrt(ErrorR**2+totalBG.GetBinError(binR)**2)
157 >            binR-=1
158 >            if not TotR == 0 and not ErrorR == 0:
159 >                rel=ErrorR/TotR
160 >                #print rel
161 >        #print 'upper bin is %s'%binR
162 >
163 >        #---- from left
164 >        rel=1.0
165 >        while rel > tolerance:
166 >            TotL+=totalBG.GetBinContent(binL)
167 >            ErrorL=sqrt(ErrorL**2+totalBG.GetBinError(binL)**2)
168 >            binL+=1
169 >            if not TotL == 0 and not ErrorL == 0:
170 >                rel=ErrorL/TotL
171 >                #print rel
172 >        #it's the lower edge
173 >        binL+=1
174 >        #print 'lower bin is %s'%binL
175 >
176 >        inbetween=binR-binL
177 >        stepsize=int(inbetween)/(int(self.norebin_nBins)-2)
178 >        modulo = int(inbetween)%(int(self.norebin_nBins)-2)
179 >
180 >        #print'stepsize %s'% stepsize
181 >        #print 'modulo %s'%modulo
182 >        binlist=[binL]
183 >        for i in range(0,int(self.norebin_nBins)-3):
184 >            binlist.append(binlist[-1]+stepsize)
185 >        binlist[-1]+=modulo
186 >        binlist.append(binR)
187 >        binlist.append(self.rebin_nBins+1)
188 >
189 >        self.mybinning = Rebinner(int(self.norebin_nBins),array('d',[-1.0]+[totalBG.GetBinLowEdge(i) for i in binlist]),True)
190 >        self._rebin = True
191 >
192 >
193 >    @staticmethod
194 >    def orderandadd(histo_dicts,setup):
195 >        print histo_dicts
196 >        ordered_histo_dict = {}
197 >        for sample in setup:
198 >            nSample = 0
199 >            for histo_dict in histo_dicts:
200 >                if histo_dict.has_key(sample):
201 >                    if nSample == 0:
202 >                        ordered_histo_dict[sample] = histo_dict[sample]
203 >                    else:
204 >                        printc('magenta','','\t--> added %s to %s'%(sample,sample))
205 >                        ordered_histo_dict[sample].Add(histo_dict[sample])
206 >                    nSample += 1
207 >        return ordered_histo_dict
208 >
209 > class Rebinner:
210 >    def __init__(self,nBins,lowedgearray,active=True):
211 >        self.lowedgearray=lowedgearray
212 >        self.nBins=nBins
213 >        self.active=active
214 >    def rebin(self, histo):
215 >        if not self.active: return histo
216 >        #print 'rebinning'
217 >        #print histo.Integral()
218 >        ROOT.gDirectory.Delete('hnew')
219 >        histo.Rebin(self.nBins,'hnew',self.lowedgearray)
220 >        binhisto=ROOT.gDirectory.Get('hnew')
221 >        #print binhisto.Integral()
222 >        newhisto=ROOT.TH1F('new','new',self.nBins,self.lowedgearray[0],self.lowedgearray[-1])
223 >        newhisto.Sumw2()
224 >        for bin in range(1,self.nBins+1):
225 >            newhisto.SetBinContent(bin,binhisto.GetBinContent(bin))
226 >            newhisto.SetBinError(bin,binhisto.GetBinError(bin))
227 >        newhisto.SetName(binhisto.GetName())
228 >        newhisto.SetTitle(binhisto.GetTitle())
229 >        #print newhisto.Integral()
230 >        return copy(newhisto)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines