Пример #1
0
    def drawRatioPlot(self, dataHistogram, mcHistogram):

        self.pads['unten'].cd()
        ROOT.gPad.SetTicks(1,1)

        self.legends['ratio'] = ROOT.TLegend(0.39, 0.85, 0.93, 0.97)
        self.legends['ratio'].SetLineWidth(2)
        self.legends['ratio'].SetBorderSize(0)
        self.legends['ratio'].SetFillColor(0)
        self.legends['ratio'].SetFillStyle(4000)
        self.legends['ratio'].SetTextSize(0.075)
        self.legends['ratio'].SetNColumns(2)

        # draw ratio plot
        self.ratioPlot, error = getRatio(dataHistogram, mcHistogram, self.histogramOptions['minX'], self.histogramOptions['maxX'], "", self.maxRatioUncert, True)
        ksScore = dataHistogram.KolmogorovTest(mcHistogram)
        chiScore = dataHistogram.Chi2Test(mcHistogram, "UWCHI2/NDF")
        print ("INFO: data/MC ratio, KS test:", ksScore, " chi2:", chiScore)
        try:
            self.ratioPlot.SetStats(0)
            self.ratioPlot.GetXaxis().SetTitle(self.xAxis)
            self.ratioError = ROOT.TGraphErrors(error)
            self.ratioError.SetFillColor(ROOT.kGray+3)
            self.ratioError.SetFillStyle(3013)
            self.ratioPlot.Draw("E1")
            self.ratioError.Draw('SAME2')
        except Exception as e:
            print ("\x1b[31mERROR: with ratio histogram!", e, "\x1b[0m")

        self.m_one_line = ROOT.TLine(self.histogramOptions['minX'], 1, self.histogramOptions['maxX'], 1)
        self.m_one_line.SetLineStyle(ROOT.kSolid)
        self.m_one_line.Draw("Same")

        if not self.AddErrors:
            self.legends['ratio'].AddEntry(self.ratioError,"MC uncert. (stat.)","f")
        else:
            self.legends['ratio'].AddEntry(self.ratioError,"MC uncert. (stat. + syst.)","f")
        self.legends['ratio'].Draw() 
        if not self.blind:
            self.addObject(self.myText("#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}"%(chiScore), 0.17, 0.895, 1.55))
            t0 = ROOT.TText()
            t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
            t0.SetTextFont(ROOT.gStyle.GetLabelFont())
            if not self.log:
                t0.DrawTextNDC(0.1059, 0.96, "0")
Пример #2
0
    def doPlot(self):

        #if 'low' in self.filename:
        #    self.addFlag2 = 'Low p_{T}(V)'
        #else: self.addFlag2 = 'High p_{T}(V)'

        TdrStyles.tdrStyle()

        print 'histos:', self.histos
        print 'self.typs:', self.typs
        print 'self.setup:', self.setup

        histo_dict = HistoMaker.orderandadd([{
            self.typs[i]: self.histos[i]
        } for i in range(len(self.histos))], self.setup)

        print 'histo dict:', histo_dict
        print 'histos:', self.histos
        print 'self.typs:', self.typs

        self.histos = [histo_dict[key] for key in self.setup]
        self.typs = self.setup

        #print 'self.histos:', self.histos
        #print 'self.typs:', self.typs
        #print 'histo dict:', histo_dict

        c = ROOT.TCanvas(self.var, '', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        oben = ROOT.TPad('oben', 'oben', 0, 0.3, 1.0, 1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        unten = ROOT.TPad('unten', 'unten', 0, 0.0, 1.0, 0.3)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var, '')
        l = ROOT.TLegend(0.45, 0.6, 0.75, 0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        l.SetTextSize(0.035)
        l_2 = ROOT.TLegend(0.68, 0.6, 0.92, 0.92)
        l_2.SetLineWidth(2)
        l_2.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetFillStyle(4000)
        l_2.SetTextFont(62)
        l_2.SetTextSize(0.035)
        MC_integral = 0
        MC_entries = 0

        for histo in self.histos:
            MC_integral += histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m" % MC_integral

        #ORDER AND ADD TOGETHER

        if not 'DYc' in self.typs:
            self.typLegendDict.update({'DYlight': self.typLegendDict['DYlc']})
        #print self.typLegendDict

        print 'All histos:', self.histos

        k = len(self.histos)
        for j in range(0, k):
            i = k - j - 1
            print 'Color:', self.histos[i], int(
                self.colorDict[self.typs[i]]), self.histos[i].Integral()
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])
            #for bin in range(0,self.histos[i].GetNbinsX()+1):
            #    print 'MC in bin ', bin, ':', self.histos[i].GetBinContent(bin)

        print 'StackMaker Data Bins:', self.nBins, self.xMin, self.xMax
        d1 = ROOT.TH1F('noData', 'noData', self.nBins, self.xMin, self.xMax)

        print 'self.datanames:', self.datanames
        print 'Self.var:', self.var
        if 'Wmn' in self.datanames and not 'CSV' in self.var or 'Wen' in self.datanames and not 'CSV' in self.var:
            #print 'here'
            if not isVV:
                binBoundaries = [
                    -1., -0.966, -0.83184615, -0.69769231, -0.56353846,
                    -0.42938462, -0.29523077, -0.16107692, -0.02692308,
                    0.10723077, 0.24138462, 0.37553846, 0.50969231, 0.64384615,
                    0.778, 1.
                ]

            if isVV:
                binBoundaries = [
                    -1., -0.886, -0.746, -0.606, -0.466, -0.326, -0.186,
                    -0.046, 0.094, 0.234, 0.374, 0.514, 0.654, 0.794, 0.934, 1.
                ]

            bins = array('f', binBoundaries)
            d1 = ROOT.TH1F('noData', 'noData', self.nBins, bins)

        datatitle = 'Data'
        addFlag = ''
        if 'Zee' in self.datanames and 'Zuu' in self.datanames or 'Zll' in self.datanames:
            if isVV:
                addFlag = 'Z(l^{-}l^{+})Z(b#bar{b})'
            else:
                addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
        elif 'Zee' in self.datanames:
            if isVV: addFlag = 'Z(e^{-}e^{+})Z(b#bar{b})'
            else: addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
        elif 'Zuu' in self.datanames:
            if isVV: addFlag = 'Z(#mu^{-}#mu^{+})Z(b#bar{b})'
            else: addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
        elif 'Znn' in self.datanames:
            if isVV: addFlag = 'Z(#nu#nu)Z(b#bar{b})'
            else: 'Z(#nu#nu)H(b#bar{b})'
        elif 'Wmn' in self.datanames:
            if isVV:
                addFlag = 'W(#mu#nu)Z(b#bar{b})'
            else:
                addFlag = 'W(#mu#nu)H(b#bar{b})'
        elif 'Wen' in self.datanames:
            if isVV: addFlag = 'W(e#nu)Z(b#bar{b})'
            else: addFlag = 'W(e#nu)H(b#bar{b})'
        elif 'Wtn' in self.datanames:
            addFlag = 'W(#tau#nu)H(b#bar{b})'

        for i in range(0, len(self.datas)):
            print 'Datas:', self.datas
            print self.datas[i]
            #for bin in range(0,self.datas[i].GetNbinsX()+1):
            #    print 'Data in bin ', bin, ':', self.datas[0].GetBinContent(bin)
            d1.Add(self.datas[i], 1)
            for bin in range(0, self.datas[i].GetNbinsX() + 1):
                print 'Data in bin ', bin, ':', d1.GetBinContent(bin)

        print "\033[1;32m\n\tDATA integral = %s\033[1;m" % d1.Integral()
        flow = d1.GetEntries() - d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m" % flow

        if not isOverlay:
            self.overlay = False

        if self.overlay and not isinstance(self.overlay, list):
            self.overlay = [self.overlay]
        if self.overlay:
            print '\n\n\t\t========OVERLAY==========', self.overlay
            for _overlay in self.overlay:
                #if _overlay.GetName() == 'ZH125':
                if 'ZH' in _overlay.GetName() or 'WH' in _overlay.GetName(
                ) or 'log' in _overlay.GetName() and not isVV:
                    _overlay.SetLineColor(int(self.colorDict['ZH']))
                    _overlay.SetLineWidth(2)
                    _overlay.SetFillColor(0)
                    _overlay.SetFillStyle(4000)
                #if _overlay.GetName() == 'ggZH125':
                if 'ggZH' in _overlay.GetName():
                    _overlay.SetLineColor(int(self.colorDict['ggZH']))
                _overlay.SetLineWidth(2)
                _overlay.SetFillColor(0)
                _overlay.SetFillStyle(4000)

                if isVV:
                    _overlay.SetLineColor(int(self.colorDict['VVHF']))

        # PREfit overlay
        if self.prefit_overlay:
            print '\n\n\t\t========PREFIT OVERLAY==========', self.prefit_overlay
            for _prefit_overlay in self.prefit_overlay:
                _prefit_overlay.SetLineColor(6)
                _prefit_overlay.SetLineWidth(2)
                _prefit_overlay.SetFillColor(0)
                _prefit_overlay.SetFillStyle(4000)
                l_2.AddEntry(_prefit_overlay, 'PreFit', 'L')

        numLegend = 2 + k
        if self.overlay:
            numLegend += len(self.overlay)
        l.AddEntry(d1, datatitle, 'P')
        for j in range(0, k):
            if j < numLegend / 2. - 1:
                l.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]],
                           'F')
            else:
                l_2.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]],
                             'F')

        if self.overlay:
            overScale = 100000
            for _overlay in self.overlay:  #find minimum scale to use for all overlays
                stackMax = allStack.GetMaximum()
                overMax = _overlay.GetMaximum()
                print 'Overlay:', self.overlay
                print "overScale=", overScale,
                print "overMax=", overMax,
                print "stackMax=", stackMax,
                print "stackMax/overMax=", stackMax / overMax,
                overScale = min(overScale, stackMax / overMax)
                if overScale >= 100000: overScale = 100000
                elif overScale >= 50000: overScale = 50000
                elif overScale >= 20000: overScale = 20000
                elif overScale >= 10000: overScale = 10000
                elif overScale >= 5000: overScale = 5000
                elif overScale >= 2000: overScale = 2000
                elif overScale >= 1000: overScale = 1000
                elif overScale >= 500: overScale = 500
                elif overScale >= 200: overScale = 200
                elif overScale >= 100: overScale = 100
                elif overScale >= 50: overScale = 50
                elif overScale >= 20: overScale = 20
                elif overScale >= 10: overScale = 10
                elif overScale >= 5: overScale = 5
                elif overScale >= 2: overScale = 2
                else: overScale = 1
            for _overlay in self.overlay:
                _overlay.Scale(overScale)
                print '\n\tOverScale:', overScale

                #if 'ZH' in _overlay.GetName() or 'log' in _overlay.GetName() and not isVV:
                if not isVV:
                    l_2.AddEntry(
                        _overlay,
                        self.typLegendDict['VH'] + " x" + str(overScale), 'L')
                    #if 'ZH'in _overlay.GetName():
                    #l_2.AddEntry(_overlay,self.typLegendDict['ZH'],'L')
                    #if 'ggZH' in _overlay.GetName():
                    #l_2.AddEntry(_overlay,self.typLegendDict['ggZH'],'L')

                #if 'VV' in _overlay.GetName():
                if isVV:
                    l_2.AddEntry(_overlay, "VV x" + str(overScale), 'L')

                if 'WH' in _overlay.GetName():
                    l_2.AddEntry(
                        _overlay,
                        self.typLegendDict['VH'] + " x" + str(overScale), 'L')

        #if self.normalize:
        #if MC_integral != 0:
        #    stackscale = d1.Integral()/MC_integral
        #stackscale = MC_integral
        #else: stackscale = 1

        stackscale = 1

        if self.overlay:
            for _overlay in self.overlay:
                _overlay.Scale(stackscale)

        #if self.prefit_overlay:
        #    for _prefit_overlay in self.prefit_overlay:
        #        _prefit_overlay.Scale(1)

        stackhists = allStack.GetHists()
        #for blabla in stackhists:
        #    if MC_integral != 0: blabla.Scale(stackscale)

        allMC = allStack.GetStack().Last().Clone()

        print 'allStack:', allStack
        print 'allMC:', allMC
        print '# of Hists in stack:', allStack.ls()

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')

        # Tline temp hack for pt balance
        #pt_balance_line = ROOT.TLine(1, 0, 1, 3000)
        #pt_balance_line.SetLineStyle(ROOT.kSolid)
        #pt_balance_line.SetLineColor(ROOT.kRed)
        #pt_balance_line.Draw("Same")

        if not d1.GetSumOfWeights() % 1 == 0.0:
            #yTitle = 'S/(S+B) weighted entries'
            yTitle = 'Entries'
        else:
            yTitle = 'Entries'

        if not '/' in yTitle:
            if 'GeV' in self.xAxis:
                yAppend = '%.0f' % (allStack.GetXaxis().GetBinWidth(1))
            else:
                yAppend = '%.2f' % (allStack.GetXaxis().GetBinWidth(1))
            yTitle = '%s / %s' % (yTitle, yAppend)
            if 'GeV' in self.xAxis:
                yTitle += ' GeV'
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin, self.xMax)
        allStack.GetYaxis().SetRangeUser(0, 20000)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray + 3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')
        l_2.AddEntry(theErrorGraph, "MC uncert. (stat.)", "fl")
        Ymax = max(allStack.GetMaximum(), d1.GetMaximum()) * 1.7
        if self.log:
            allStack.SetMinimum(0.1)
            Ymax = Ymax * ROOT.TMath.Power(
                10, 1.2 *
                (ROOT.TMath.Log(1.2 *
                                (Ymax / 0.1)) / ROOT.TMath.Log(10))) * (0.2 *
                                                                        0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.3*(ROOT.TMath.Log(1.3*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.3*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1, 1)
        l.SetFillColor(0)
        l.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetBorderSize(0)

        if self.overlay:
            for _overlay in self.overlay:
                _overlay.Draw('same')
        d1.Draw("E,same")
        l.Draw()
        l_2.Draw()

        if self.prefit_overlay:
            for _prefit_overlay in self.prefit_overlay:
                _prefit_overlay.Draw('same')
        #d1.Draw("E,same")
        #l.Draw()
        #l_2.Draw()

        tPrel = self.myText("CMS Preliminary", 0.17, 0.88, 1.04)
        if not d1.GetSumOfWeights() % 1 == 0.0:
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" %
                (self.anaTag, (float(self.lumi) / 1000.)), 0.17, 0.83)
            #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f pb^{-1}"%(self.anaTag,(float(self.lumi))),0.17,0.78)
        else:
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" %
                (self.anaTag, (float(self.lumi) / 1000.)), 0.17, 0.83)
            #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f pb^{-1}"%(self.anaTag,(float(self.lumi))),0.17,0.83)

        tAddFlag = self.myText(addFlag, 0.17, 0.78)
        print 'Add Flag %s' % self.addFlag2
        if self.addFlag2:
            tAddFlag2 = self.myText(self.addFlag2, 0.17, 0.73)

        unten.cd()
        ROOT.gPad.SetTicks(1, 1)

        l2 = ROOT.TLegend(0.39, 0.85, 0.93, 0.97)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextSize(0.075)
        l2.SetNColumns(2)

        #Temp remopval of the ratio maker
        ratio, error = getRatio(d1, allMC, self.xMin, self.xMax, "",
                                self.maxRatioUncert)
        ksScore = d1.KolmogorovTest(allMC)
        chiScore = d1.Chi2Test(allMC, "UWCHI2/NDF")
        print ksScore
        print chiScore
        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray + 3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus", 0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus", 0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData, "R")
            print 'Fit on simulation'
            allMC.Fit(fitMC, "R")

        if not self.AddErrors == None:
            self.AddErrors.SetLineColor(1)
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(3001)
            self.AddErrors.Draw('SAME2')
            l2.AddEntry(self.AddErrors, "MC uncert. (stat. + syst.)", "f")

        l2.AddEntry(ratioError, "MC uncert. (stat.)", "f")

        ratioError.Draw('SAME2')
        ratio.Draw("E1SAME")
        ratio.SetTitle("")

        l2.Draw()

        m_one_line = ROOT.TLine(self.xMin, 1, self.xMax, 1)
        m_one_line.SetLineStyle(ROOT.kSolid)
        m_one_line.Draw("Same")

        if not self.blind:
            #tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
            tKsChi = self.myText(
                "#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}" % (chiScore),
                0.17, 0.895, 1.55)
            temp = 0

        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize() * 2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
            t0.DrawTextNDC(0.1059, 0.96, "0")

        PlotDir = self.plotDir + self.region
        if not os.path.exists(PlotDir):
            os.makedirs(os.path.dirname(PlotDir + '/'))
        name = '%s/%s' % (PlotDir, self.options['pdfName'])

        if self.log:
            name = '%s/log_%s' % (PlotDir, self.options['pdfName'])

        if self.filename != None:
            name = '%s/%s_%s' % (PlotDir, self.filename,
                                 self.options['pdfName'])

        if isVV:
            name = '%s/VV_%s' % (PlotDir, self.options['pdfName'])

        c.Print(name)

        # Now in png form
        name2 = name.replace('.pdf', '.png', 2)
        #print '---> name:', name2
        c.Print(name2)

        name3 = name2.replace('.png', '.root', 3)
        #print '---> name:', name3
        c.Print(name3)

        name4 = name3.replace('.root', '.C', 4)
        #print '---> name:', name4
        c.Print(name4)
Пример #3
0
    def doPlot(self):
        TdrStyles.tdrStyle()
        histo_dict = HistoMaker.orderandadd([{self.typs[i]:self.histos[i]} for i in range(len(self.histos))],self.setup)
        #sort
        self.histos=[histo_dict[key] for key in self.setup]
        self.typs=self.setup
    
        c = ROOT.TCanvas(self.var,'', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        #oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0)
        oben = ROOT.TPad('oben','oben',0,0.5 ,1.0,1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        #unten = ROOT.TPad('unten1','unten1',0,0.0,1.0,0.17)
        unten = ROOT.TPad('unten1','unten1',0,0.0,1.0,0.29)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)
        #unten1 = ROOT.TPad('unten2','unten2',0,0.17,1.0,0.3)
        unten1 = ROOT.TPad('unten2','unten2',0,0.29,1.0,0.5)
        unten1.SetTopMargin(0.)
        unten1.SetBottomMargin(0.)
        unten1.SetFillStyle(4000)
        unten1.SetFrameFillStyle(1000)
        unten1.SetFrameFillColor(0)


        oben.Draw()
        unten.Draw()
        unten1.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var,'')     
        #l = ROOT.TLegend(0.68, 0.65,0.92,0.92)
        l = ROOT.TLegend(0.6, 0.5,0.92,0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        #l.SetTextSize(0.035)
        l.SetTextSize(0.052)
        MC_integral=0
        MC_entries=0

        for histo in self.histos:
            MC_integral+=histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m"%MC_integral

        #ORDER AND ADD TOGETHER
        #print typs
        #print setup


        if not 'DYc' in self.typs: self.typLegendDict.update({'DYlight':self.typLegendDict['DYlc']})
        print self.typLegendDict

        k=len(self.histos)
    
        for j in range(0,k):
            #print histos[j].GetBinContent(1)
            i=k-j-1
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])

        d1 = ROOT.TH1F('noData','noData',self.nBins,self.xMin,self.xMax)
        datatitle='Data'
        addFlag = ''
        if 'Zee' in self.datanames and 'Zmm' in self.datanames:
	        addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
        elif 'Zee' in self.datanames:
	        addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
        elif 'Zmm' in self.datanames:
	        addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
        elif 'Znn' in self.datanames:
	        addFlag = 'Z(#nu#nu)H(b#bar{b})'
        elif 'Wmn' in self.datanames:
	        addFlag = 'W(#mu#nu)H(b#bar{b})'
        elif 'Wen' in self.datanames:
	        addFlag = 'W(e#nu)H(b#bar{b})'
        elif 'Wtn' in self.datanames:
	        addFlag = 'W(#tau#nu)H(b#bar{b})'
        else:
            addFlag = 'pp #rightarrow VH; H #rightarrow b#bar{b}'
        for i in range(0,len(self.datas)):
            d1.Add(self.datas[i],1)
        print "\033[1;32m\n\tDATA integral = %s\033[1;m"%d1.Integral()
        flow = d1.GetEntries()-d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m"%flow

        if self.overlay:
            self.overlay.SetLineColor(2)
            self.overlay.SetLineWidth(2)
            self.overlay.SetFillColor(0)
            self.overlay.SetFillStyle(4000)
            self.overlay.SetNameTitle('Overlay','Overlay')

        l.AddEntry(d1,datatitle,'P')
        for j in range(0,k):
            l.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')
        if self.overlay:
            l.AddEntry(self.overlay,self.typLegendDict['Overlay'],'L')
    
        if self.normalize:
            if MC_integral != 0:	stackscale=d1.Integral()/MC_integral
            if self.overlay:
                self.overlay.Scale(stackscale)
            stackhists=allStack.GetHists()
            for blabla in stackhists:
        	    if MC_integral != 0: blabla.Scale(stackscale)
   
        #if self.SignalRegion:
        #    allMC=allStack.GetStack().At(allStack.GetStack().GetLast()-1).Clone()
        #else:
        allMC=allStack.GetStack().Last().Clone()
        bkgMC=allStack.GetStack().First().Clone()

        sigRatio = allMC.Clone()
        sigRatio.Divide(bkgMC)

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')
        yTitle = 'Entries'
        if not '/' in yTitle:
            yAppend = '%.2f' %(allStack.GetXaxis().GetBinWidth(1)) 
            yTitle = '%s / %s' %(yTitle, yAppend)
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin,self.xMax)
        allStack.GetYaxis().SetRangeUser(0,20000)
        allStack.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*1.3)
        allStack.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 1.3)
        allStack.GetYaxis().SetTitleOffset(0.9)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray+3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')
        #l.AddEntry(theErrorGraph,"B total uncert.","fl")
        l.AddEntry(theErrorGraph,"Background uncert.","fl")
        Ymax = max(allStack.GetMaximum(),d1.GetMaximum())*1.7
        if self.log:
            allStack.SetMinimum(0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.2*(ROOT.TMath.Log(1.2*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.2*0.1)
            Ymax = Ymax*ROOT.TMath.Power(10,0.9*(ROOT.TMath.Log(0.9*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.2*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1,1)
        #allStack.Draw("hist")
        l.SetFillColor(0)
        l.SetBorderSize(0)
        
        #if self.overlay:
        #    self.overlay.Draw('hist,same')
        d1.Draw("E,same")
        l.Draw()

        #tPrel = self.myText("CMS",0.17,0.88,1.04)
        #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%('7TeV',(float(5000.)/1000.)),0.17,0.83)
        #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.78)
        #tAddFlag = self.myText(addFlag,0.17,0.78)
        tPrel = self.myText("CMS",0.17,0.85,1.56)
        tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%('7TeV',(float(5000.)/1000.)),0.17,0.77,1.2)
        tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.69,1.2)
        tAddFlag = self.myText(addFlag,0.17,0.61,1.2)
        #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.77,1.2)
        #tAddFlag = self.myText(addFlag,0.17,0.69,1.2)

        unten.cd()
        ROOT.gPad.SetTicks(1,1)

        l2 = ROOT.TLegend(0.5, 0.82,0.92,0.95)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextFont(62)
        #l2.SetTextSize(0.035)
        l2.SetNColumns(2)


        ratio, error = getRatio(d1,allMC,self.xMin,self.xMax,"",self.maxRatioUncert)
        ksScore = d1.KolmogorovTest( allMC )
        chiScore = d1.Chi2Test( allMC , "UWCHI2/NDF")
        print ksScore
        print chiScore
        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray+3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus",0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus",0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData,"R")
            print 'Fit on simulation'
            allMC.Fit(fitMC,"R")


        if not self.AddErrors == None:
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(1001)
            self.AddErrors.Draw('SAME2')

            l2.AddEntry(self.AddErrors,"MC uncert. (stat. + syst.)","f")

            #ksScore = d1.KolmogorovTest( self.AddErrors )
            #chiScore = d1.Chi2Test( self.AddErrors , "UWCHI2/NDF")


        l2.AddEntry(ratioError,"MC uncert. (stat.)","f")

        #l2.Draw()

        ratioError.Draw('SAME2')
        #ratio.GetXaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*3.6)
        ratio.GetXaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*2.6)
        ratio.GetXaxis().SetTitleOffset(0.9)
        #ratio.GetXaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 3.6)
        ratio.GetXaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 2.6)
        #ratio.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*2.8)
        #ratio.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 2.8)
        ratio.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*2.0)
        ratio.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 2.0)
        ratio.GetYaxis().SetTitleOffset(0.55)
        ratio.Draw("E1SAME")
        ratio.SetTitle("")
        ratio.SetYTitle("#frac{Data}{MC(S+B)}")
        if not self.blind:
            tKsChi = self.myText("#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}"%(chiScore),0.17,0.9,1.7)
        m_one_line = ROOT.TLine(self.xMin,1,self.xMax,1)
        m_one_line.SetLineStyle(ROOT.kDashed)
        m_one_line.Draw("Same")
        
        unten1.cd()
        ROOT.gPad.SetTicks(1,1)
        
        ratio1, error1 = getRatio(d1,bkgMC,self.xMin,self.xMax,"",self.maxRatioUncert)
        chiScore1 = d1.Chi2Test( bkgMC , "UWCHI2/NDF")
        ratio1.Draw("E1")
        #l2.Draw()

        ratioError1 = ROOT.TGraphErrors(error1)
        ratioError1.SetFillColor(ROOT.kGray+3)
        ratioError1.SetFillStyle(3013)
        ratioError1.Draw('SAME2')
        sigRatio.SetFillStyle(0)
        sigRatio.SetLineColor(2)
        sigRatio.SetLineWidth(2)
        sigRatio.Draw('HISTSAME')
        ratio1.Draw("E1SAME")
        ratio1.SetTitle("")
        ratio1.SetYTitle("#frac{Data}{MC(B)}")
        #ratio1.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*3.7)
        ratio1.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*2.7)
        ratio1.GetYaxis().SetTitleOffset(0.4)
        #ratio1.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 3.7)
        ratio1.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 2.7)

        m_one_line.Draw("Same")

        if not self.blind:
            tKsChi1 = self.myText("#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}"%(chiScore1),0.17,0.865,2.3)
        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
    	    t0.DrawTextNDC(0.1059,0.96, "0")
        if not os.path.exists(self.plotDir):
            os.makedirs(os.path.dirname(self.plotDir))
        name = '%s/%s' %(self.plotDir,self.options['pdfName'])
        c.Print(name)
        fOut = ROOT.TFile.Open(name.replace('.pdf','.root'),'RECREATE')
        for theHist in allStack.GetHists():
            theHist.SetDirectory(fOut)
            if theHist.GetName() == 'ZH' or theHist.GetName() == 'WH':
                theHist.SetName('VH')
            theHist.Write()
        d1.SetName('data_obs')
        d1.SetDirectory(fOut)
        d1.Write()
        fOut.Close()
Пример #4
0
    def doPlot(self):

        print "Start performing stacked plot"
        print "=============================\n"

        TdrStyles.tdrStyle()
        print "self.typs",self.typs
        print "self.histos",self.histos
        print "self.setup",self.setup
        #Groups all the subsample of the "Group" dictionnary into one sample
        histo_dict = HistoMaker.orderandadd([{self.typs[i]:self.histos[i]} for i in range(len(self.histos))],self.setup)
        #sort

        print "histo_dict",histo_dict
        for key in self.setup:
          print "The sample in setup are", key

        self.histos=[histo_dict[key] for key in self.setup]
        print "again, self.histos is",self.histos
        self.typs=self.setup

        c = ROOT.TCanvas(self.var,'', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.3)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var,'')     
        l = ROOT.TLegend(0.45, 0.6,0.75,0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        l.SetTextSize(0.035)
        l_2 = ROOT.TLegend(0.68, 0.6,0.92,0.92)
        l_2.SetLineWidth(2)
        l_2.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetFillStyle(4000)
        l_2.SetTextFont(62)
        l_2.SetTextSize(0.035)
        MC_integral=0
        MC_entries=0

        from array import array
        doubleVariable = array('d',[0])

	for histo in self.histos:
            print "histo name, title, integral,error: ",histo.GetName(),histo.GetTitle(),histo.IntegralAndError(0,histo.GetNbinsX(),doubleVariable),doubleVariable[0]
            MC_integral+=histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m"%MC_integral

        #ORDER AND ADD TOGETHER

#        if not 'DYc' in self.typs: self.typLegendDict.update({'DYlight':self.typLegendDict['DYlc']})
        print self.typLegendDict

        k=len(self.histos)
    
        for j in range(0,k):
            #print histos[j].GetBinContent(1)
            i=k-j-1
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])

        d1 = ROOT.TH1F('noData','noData',self.nBins,self.xMin,self.xMax)
        datatitle='Data'
        addFlag = ''
        if 'Zee' in self.datanames and 'Zmm' in self.datanames:
            addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
        elif 'Zee' in self.datanames:
            addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
        elif 'Zmm' in self.datanames:
            addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
        elif 'Znn' in self.datanames:
            addFlag = 'Z(#nu#nu)H(b#bar{b})'
        elif 'Wmn' in self.datanames:
            addFlag = 'W(#mu#nu)H(b#bar{b})'
        elif 'Wen' in self.datanames:
            addFlag = 'W(e#nu)H(b#bar{b})'
        elif 'Wtn' in self.datanames:
            addFlag = 'W(#tau#nu)H(b#bar{b})'

        for i in range(0,len(self.datas)):
            print "Adding data ",self.datas[i]," with integral:",self.datas[i].Integral()," and entries:",self.datas[i].GetEntries()
            d1.Add(self.datas[i],1)
        print "\033[1;32m\n\tDATA integral = %s\033[1;m"%d1.Integral()
        flow = d1.GetEntries()-d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m"%flow

        if self.overlay and not isinstance(self.overlay,list):
            self.overlay = [self.overlay]
        if self.overlay:
            for _overlay in self.overlay:
                _overlay.SetLineColor(99)
                _overlay.SetLineColor(int(self.colorDict[_overlay.GetTitle()]))
                _overlay.SetLineWidth(3)
                _overlay.SetFillColor(0)
                _overlay.SetFillStyle(4000)

        numLegend = 2+k
        if self.overlay:
            numLegend += len(self.overlay)
        l.AddEntry(d1,datatitle,'P')
        for j in range(0,k):
            if j < numLegend/2.-1:
                l.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')
            else:
                l_2.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')
        if self.overlay:
            overScale = 100000
            for _overlay in self.overlay: #find minimum scale to use for all overlays
                stackMax = allStack.GetMaximum()
                overMax = _overlay.GetMaximum() + 1e-30 
                print "overScale=",overScale,
                print "stackMax/overMax=",stackMax/overMax,
                print "overMax=",overMax,
                print "stackMax=",stackMax,
                overScale = min(overScale,stackMax/overMax)
                if overScale >= 100000: overScale=100000
                elif overScale >= 50000: overScale=50000
                elif overScale >= 20000: overScale=20000
                elif overScale >= 10000: overScale=10000
                elif overScale >= 5000: overScale=5000
                elif overScale >= 2000: overScale=2000
                elif overScale >= 1000: overScale=1000
                elif overScale >= 500: overScale=500
                elif overScale >= 200: overScale=200
                elif overScale >= 100: overScale=100
                elif overScale >= 50: overScale=50
                elif overScale >= 20: overScale=20
                elif overScale >= 10: overScale=10
                elif overScale >= 5: overScale=5
                elif overScale >= 2: overScale=2
                else: overScale=1
            for _overlay in self.overlay:
                _overlay.Scale(overScale)
                l_2.AddEntry(_overlay,self.typLegendDict[_overlay.GetTitle()]+" X"+str(overScale),'L')
#                l_2.AddEntry(_overlay,self.typLegendDict[_overlay.GetTitle()],'L')
    
        if self.normalize:
            print "I'm normalizing MC to data integral"
            if MC_integral != 0:        stackscale=d1.Integral()/MC_integral
            if self.overlay:
                for _overlay in self.overlay:
                    _overlay.Scale(stackscale)
            stackhists=allStack.GetHists()+allStack.GetStack()
            for blabla in stackhists:
                if MC_integral != 0: blabla.Scale(stackscale)
            print "new MC_integral: ",allStack.GetStack().Last().Integral()
   
        allMC=allStack.GetStack().Last().Clone()

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')
        #yTitle = 's/(s+b) weighted entries'
        if not d1.GetSumOfWeights() % 1 == 0.0:
            yTitle = 'S/(S+B) weighted entries'
        else:
            yTitle = 'Entries'
        if not '/' in yTitle:
            if 'GeV' in self.xAxis:
                yAppend = '%.0f' %(allStack.GetXaxis().GetBinWidth(1)) 
            else:
                yAppend = '%.2f' %(allStack.GetXaxis().GetBinWidth(1)) 
            yTitle = '%s / %s' %(yTitle, yAppend)
            if 'GeV' in self.xAxis:
                yTitle += ' GeV'
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin,self.xMax)
        allStack.GetYaxis().SetRangeUser(0,20000)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray+3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')
        l_2.AddEntry(theErrorGraph,"MC uncert. (stat.)","fl")
        Ymax = max(allStack.GetMaximum(),d1.GetMaximum())*1.7
        if self.log:
            allStack.SetMinimum(0.1)
            Ymax = Ymax*ROOT.TMath.Power(10,1.2*(ROOT.TMath.Log(1.2*(Ymax/0.2))/ROOT.TMath.Log(10)))*(0.2*0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.3*(ROOT.TMath.Log(1.3*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.3*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1,1)
        l.SetFillColor(0)
        l.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetBorderSize(0)
        
        if self.overlay:
            for _overlay in self.overlay:
                print("Drawing overlay")
                _overlay.Draw('hist,same')
        d1.Draw("E,same")
        l.Draw()
        l_2.Draw()

        tPrel = self.myText("CMS",0.17,0.88,1.04)
        print 'self.lumi is', self.lumi
        # if not d1.GetSumOfWeights() % 1 == 0.0:
            # tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%('7TeV',(float(5000.)/1000.)),0.17,0.83)
            # tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.78)
        # else:
            # tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.83)
        tLumi = self.myText("#sqrt{s} =  %s, L = %.3f fb^{-1}"%(self.anaTag,(float(self.lumi/1000.0))),0.17,0.83)
        tAddFlag = self.myText(addFlag,0.17,0.78)
        print 'Add Flag %s' %self.addFlag2
        if self.addFlag2:
            tAddFlag2 = self.myText(self.addFlag2,0.17,0.73)


        unten.cd()
        ROOT.gPad.SetTicks(1,1)

        l2 = ROOT.TLegend(0.39, 0.85,0.93,0.97)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextSize(0.075)
        l2.SetNColumns(2)


        ratio, error = getRatio(d1,allMC,self.xMin,self.xMax,"",self.maxRatioUncert, True)
        ksScore = d1.KolmogorovTest( allMC )
        chiScore = d1.Chi2Test( allMC , "UWCHI2/NDF")
        print ksScore
        print chiScore
        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray+3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus",0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus",0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData,"R")
            print 'Fit on simulation'
            allMC.Fit(fitMC,"R")


        if not self.AddErrors == None:
            self.AddErrors.SetLineColor(1)
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(3001)
            self.AddErrors.Draw('SAME2')

            l2.AddEntry(self.AddErrors,"MC uncert. (stat. + syst.)","f")


        l2.AddEntry(ratioError,"MC uncert. (stat.)","f")

        l2.Draw()

        ratioError.Draw('SAME2')
        ratio.Draw("E1SAME")
        ratio.SetTitle("")
        m_one_line = ROOT.TLine(self.xMin,1,self.xMax,1)
        m_one_line.SetLineStyle(ROOT.kSolid)
        m_one_line.Draw("Same")

        if not self.blind:
            #tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
            tKsChi = self.myText("#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}"%(chiScore),0.17,0.895,1.55)
        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
                t0.DrawTextNDC(0.1059,0.96, "0")
        if not os.path.exists(self.plotDir):
            os.mkdir(self.plotDir)
        if not os.path.exists(self.plotDir+'/pdf'):
            os.mkdir(self.plotDir+'/pdf')
        name = '%s/pdf/%s' %(self.plotDir,self.options['pdfName'])
        name = name.replace('\\',"_")
#        name = name.replace('/',"_")
        name = name.replace("'","_")
        name = name.replace('"',"_")
        name = name.replace('"',"_")
#        name = name.replace('.',"_")
        name = name.replace(',',"_")
        name = name.replace(' ',"_")
        pngName = (name.replace('.pdf','.png')).replace("/pdf","")
        rootName = (name.replace('.pdf','.root')).replace("/pdf","/root")
        c.Print(name)
        c.Print(pngName)
        c.Print(rootName)

        #print "DATA INTEGRAL: %s" %d1.Integral(d1.GetNbinsX()-2,d1.GetNbinsX()) 
        #fOut = ROOT.TFile.Open(name.replace('.pdf','.root'),'RECREATE')
        #for theHist in allStack.GetHists():
        #    if not self.AddErrors == None and not theHist.GetName() in ['ZH','WH','VH']:
                #print theHist.GetNbinsX()
                #print self.AddErrors.GetN()
                #print error.GetNbinsX()
        #        for bin in range(0,theHist.GetNbinsX()):
        #            theRelativeTotalError = self.AddErrors.GetErrorY(bin)
        #            if error.GetBinError(bin+1) > 0.:
        #                theRelativeIncrease = theRelativeTotalError/error.GetBinError(bin+1)
        #            else:
        #                theRelativeIncrease = 1.
                    #print 'TheTotalRelativeIncrease is: %.2f' %theRelativeIncrease
                    #print 'TheTotalStatError is: %.2f' %error.GetBinError(bin+1)
                    #print 'TheTotalError is: %.2f' %theRelativeTotalError
        #            theHist.SetBinError(bin,theHist.GetBinError(bin)*theRelativeIncrease)
        #    theHist.SetDirectory(fOut)
        #    if theHist.GetName() == 'ZH' or theHist.GetName() == 'WH':
        #        theHist.SetName('VH')
        #    theHist.Write()
        #d1.SetName('data_obs')
        #d1.SetDirectory(fOut)
        #d1.Write()
        #fOut.Close()
        self.doCompPlot(allStack,l)

        print "Finished performing stacked plot"
        print "================================\n"
Пример #5
0
    def doPlot(self):
        TdrStyles.tdrStyle()
        histo_dict = HistoMaker.orderandadd([{self.typs[i]:self.histos[i]} for i in range(len(self.histos))],self.setup)
        #sort
        print histo_dict
        self.histos=[histo_dict[key] for key in self.setup]
        self.typs=self.setup
    
        c = ROOT.TCanvas(self.var,'', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.3)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var,'')     
        l = ROOT.TLegend(0.45, 0.6,0.75,0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        l.SetTextSize(0.035)
        l_2 = ROOT.TLegend(0.68, 0.6,0.92,0.92)
        l_2.SetLineWidth(2)
        l_2.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetFillStyle(4000)
        l_2.SetTextFont(62)
        l_2.SetTextSize(0.035)
        MC_integral=0
        MC_entries=0

        for histo in self.histos:
            MC_integral+=histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m"%MC_integral

        #ORDER AND ADD TOGETHER

        if not 'DYc' in self.typs: self.typLegendDict.update({'DYlight':self.typLegendDict['DYlc']})
        print self.typLegendDict

        k=len(self.histos)
    
        for j in range(0,k):
            #print histos[j].GetBinContent(1)
            i=k-j-1
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])

        d1 = ROOT.TH1F('noData','noData',self.nBins,self.xMin,self.xMax)
        datatitle='Data'
        addFlag = ''
        if 'Zee' in self.datanames and 'Zmm' in self.datanames:
	        addFlag = '2-lepton, VZ(b#bar{b})'
        elif 'Zee' in self.datanames:
	        addFlag = '2-electron, VZ(b#bar{b})'
        elif 'Zmm' in self.datanames:
	        addFlag = '2-muon, VZ(b#bar{b})'
        elif 'Znn' in self.datanames:
	        addFlag = '0-lepton, VZ(b#bar{b})'
        elif 'Wmn' in self.datanames:
	        addFlag = '1-muon, VZ(b#bar{b})'
        elif 'Wen' in self.datanames:
	        addFlag = '1-electron, VZ(b#bar{b})'
        elif 'Wtn' in self.datanames:
	        addFlag = 'W(#tau#nu)H(b#bar{b})'

        for i in range(0,len(self.datas)):
            print self.datas[i]
            d1.Add(self.datas[i],1)
        print "\033[1;32m\n\tDATA integral = %s\033[1;m"%d1.Integral()
        flow = d1.GetEntries()-d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m"%flow

        if self.overlay and not isinstance(self.overlay,list):
            self.overlay = [self.overlay]
        if self.overlay:
            for _overlay in self.overlay:
                _overlay.SetLineColor(int(self.colorDict[_overlay.GetName()]))
                _overlay.SetLineWidth(2)
                _overlay.SetFillColor(0)
                _overlay.SetFillStyle(4000)

        numLegend = 2+k
        if self.overlay:
            numLegend += len(self.overlay)
        l.AddEntry(d1,datatitle,'PEL')
        for j in range(0,k):
            if j < numLegend/2.-1:
                l.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')
            else:
                l_2.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')
        if self.overlay:
            for _overlay in self.overlay:
                l_2.AddEntry(_overlay,self.typLegendDict[_overlay.GetName()],'L')
    
        if self.normalize:
            if MC_integral != 0:	stackscale=d1.Integral()/MC_integral
            if self.overlay:
                for _overlay in self.overlay:
                    _overlay.Scale(stackscale)
            stackhists=allStack.GetHists()
            for blabla in stackhists:
        	    if MC_integral != 0: blabla.Scale(stackscale)
   
        allMC=allStack.GetStack().Last().Clone()

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')
        #yTitle = 's/(s+b) weighted entries'
        if not d1.GetSumOfWeights() % 1 == 0.0:
            yTitle = 'S/(S+B) weighted entries'
        else:
            yTitle = 'Entries'
        if not '/' in yTitle:
            if 'GeV' in self.xAxis:
                yAppend = '%.0f' %(allStack.GetXaxis().GetBinWidth(1)) 
            else:
                yAppend = '%.2f' %(allStack.GetXaxis().GetBinWidth(1)) 
            yTitle = '%s / %s' %(yTitle, yAppend)
            if 'GeV' in self.xAxis:
                yTitle += ' GeV'
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin,self.xMax)
        allStack.GetYaxis().SetRangeUser(0,20000)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray+3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')
        l_2.AddEntry(theErrorGraph,"MC uncert. (stat.)","fl")
        Ymax = max(allStack.GetMaximum(),d1.GetMaximum())*1.7
        if self.log:
            allStack.SetMinimum(0.1)
            Ymax = Ymax*ROOT.TMath.Power(10,1.2*(ROOT.TMath.Log(1.2*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.2*0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.3*(ROOT.TMath.Log(1.3*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.3*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1,1)
        l.SetFillColor(0)
        l.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetBorderSize(0)
        
        if self.overlay:
            for _overlay in self.overlay:
                _overlay.Draw('hist,same')
        d1.Draw("E,same")
        l.Draw()
        l_2.Draw()

        tPrel = self.myText("CMS",0.17,0.88,1.1)
        if not d1.GetSumOfWeights() % 1 == 0.0:
            tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%('7TeV',(float(5000.)/1000.)),0.17,0.83)
            tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.78)
        else:
            tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.83)
        tAddFlag = self.myText(addFlag,0.17,0.78)
        print 'Add Flag %s' %self.addFlag2
        if self.addFlag2:
            tAddFlag2 = self.myText(self.addFlag2,0.17,0.78)
        aLabel = self.myText("(a)",0.8,0.5,1.1)

        unten.cd()
        ROOT.gPad.SetTicks(1,1)

        l2 = ROOT.TLegend(0.39, 0.85,0.93,0.97)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextSize(0.085)
        l2.SetNColumns(2)


        ratio, error = getRatio(d1,allMC,self.xMin,self.xMax,"",self.maxRatioUncert)
        ksScore = d1.KolmogorovTest( allMC )
        chiScore = d1.Chi2Test( allMC , "UWCHI2/NDF")
        print ksScore
        print chiScore
        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray+3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus",0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus",0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData,"R")
            print 'Fit on simulation'
            allMC.Fit(fitMC,"R")


        if not self.AddErrors == None:
            self.AddErrors.SetLineColor(1)
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(3001)
            self.AddErrors.Draw('SAME2')

            l2.AddEntry(self.AddErrors,"MC uncert. (stat. + syst.)","f")


        l2.AddEntry(ratioError,"Stat. uncert. on Tot. MC","f")

        l2.Draw()

        ratioError.Draw('SAME2')
        ratio.Draw("E1SAME")
        ratio.SetTitle("")
        m_one_line = ROOT.TLine(self.xMin,1,self.xMax,1)
        m_one_line.SetLineStyle(ROOT.kSolid)
        m_one_line.Draw("Same")

        if not self.blind:
            #tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
            tKsChi = self.myText("#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}"%(chiScore),0.17,0.895,1.75)
        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
    	    t0.DrawTextNDC(0.1059,0.96, "0")
        if not os.path.exists(self.plotDir):
            os.makedirs(os.path.dirname(self.plotDir))
        name = '%s/%s' %(self.plotDir,self.options['pdfName'])
        c.Print(name)
Пример #6
0
    def doPlot(self):

        print "Start performing stacked plot"
        print "=============================\n"

        TdrStyles.tdrStyle()
        print "self.typs", self.typs
        print "self.histos", self.histos
        print "self.setup", self.setup
        #Groups all the subsample of the "Group" dictionnary into one sample
        histo_dict = HistoMaker.orderandadd([{
            self.typs[i]: self.histos[i]
        } for i in range(len(self.histos))], self.setup)
        #sort

        print "histo_dict", histo_dict
        for key in self.setup:
            print "The sample in setup are", key

        self.histos = [
            histo_dict[key] for key in self.setup if key in histo_dict
        ]
        print "again, self.histos is", self.histos
        self.typs = self.setup

        if self.forceLog is not None and self.forceLog:
            self.log = True

        c = ROOT.TCanvas(self.var, '', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        oben = ROOT.TPad('oben', 'oben', 0, 0.3, 1.0, 1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        unten = ROOT.TPad('unten', 'unten', 0, 0.0, 1.0, 0.3)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var, '')
        l = ROOT.TLegend(0.45, 0.6, 0.75, 0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        l.SetTextSize(0.035)
        l_2 = ROOT.TLegend(0.68, 0.6, 0.92, 0.92)
        l_2.SetLineWidth(2)
        l_2.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetFillStyle(4000)
        l_2.SetTextFont(62)
        l_2.SetTextSize(0.035)
        MC_integral = 0
        MC_entries = 0

        from array import array
        doubleVariable = array('d', [0])

        for histo in self.histos:
            print "histo name, title, integral,error: ", histo.GetName(
            ), histo.GetTitle(), histo.IntegralAndError(
                0, histo.GetNbinsX(), doubleVariable), doubleVariable[0]
            MC_integral += histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m" % MC_integral

        #ORDER AND ADD TOGETHER

        #        if not 'DYc' in self.typs: self.typLegendDict.update({'DYlight':self.typLegendDict['DYlc']})
        print self.typLegendDict

        k = len(self.histos)

        for j in range(0, k):
            print 'j is', j
            #print histos[j].GetBinContent(1)
            i = k - j - 1
            if self.typs[i] in self.colorDict:
                self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])

        try:
            datas_nbins = self.datas[i].GetXaxis().GetNbins()
            datas_xMin = self.datas[i].GetXaxis().GetBinLowEdge(1)
            datas_xMax = self.datas[i].GetXaxis().GetBinLowEdge(
                datas_nbins) + self.datas[i].GetXaxis().GetBinWidth(
                    datas_nbins)
        except:
            datas_nbins = 0
            datas_xMin = 0
            datas_xMax = 0
        print 'data_nbins:', datas_nbins
        print 'datas_xMin:', datas_xMin
        print 'datas_xMax:', datas_xMax
        print 'nbins:', self.nBins
        print 'xMin:', self.xMin
        print 'xMax:', self.xMax

        d1 = ROOT.TH1F('noData', 'noData', self.nBins, self.xMin, self.xMax)
        datatitle = 'Data'
        addFlag = ''
        print 'self.datanames is', self.datanames
        isZee = False
        isZmm = False
        for data_ in self.datanames:
            print 'data_ is', data_
            if 'DoubleEG' in data_:
                isZee = True
                print 'isZee is True'
            if 'DoubleMuon' in data_:
                isZmm = True
                print 'isZmm is True'
        if ('Zee' in self.datanames
                and 'Zmm' in self.datanames) or (isZee and isZmm):
            addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
        elif 'Zee' in self.datanames or isZee:
            addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
        elif 'Zmm' in self.datanames or isZmm:
            addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
        elif 'Znn' in self.datanames:
            addFlag = 'Z(#nu#nu)H(b#bar{b})'
        elif 'Wmn' in self.datanames:
            addFlag = 'W(#mu#nu)H(b#bar{b})'
        elif 'Wen' in self.datanames:
            addFlag = 'W(e#nu)H(b#bar{b})'
        #if 'Muon' in self.datanames and 'Electron' in self.datanames:
        #    addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
        #elif 'Electron' in self.datanames:
        #    addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
        #elif 'Muon' in self.datanames:
        #    addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
        #elif 'Znn' in self.datanames:
        #    addFlag = 'Z(#nu#nu)H(b#bar{b})'
        #elif 'Wmn' in self.datanames:
        #    addFlag = 'W(#mu#nu)H(b#bar{b})'
        #elif 'Wen' in self.datanames:
        #    addFlag = 'W(e#nu)H(b#bar{b})'
        #elif 'Wtn' in self.datanames:
        #    addFlag = 'W(#tau#nu)H(b#bar{b})'

        for i in range(0, len(self.datas)):
            print "Adding data ", self.datas[i], " with integral:", self.datas[
                i].Integral(), " and entries:", self.datas[i].GetEntries(
                ), " and bins:", self.datas[i].GetNbinsX()
            d1.Add(self.datas[i], 1)
        print "\033[1;32m\n\tDATA integral = %s\033[1;m" % d1.Integral()
        flow = d1.GetEntries() - d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m" % flow

        if self.overlay and not isinstance(self.overlay, list):
            self.overlay = [self.overlay]
        print 'self.overlay is', self.overlay
        if self.overlay:
            for _overlay in self.overlay:
                print 'overlay title is', _overlay.GetTitle()
                _overlay.SetLineColor(99)
                _overlay.SetLineColor(int(self.colorDict[_overlay.GetTitle()]))
                _overlay.SetLineWidth(3)
                _overlay.SetFillColor(0)
                _overlay.SetFillStyle(4000)

                # PREfit overlay
        if self.prefit_overlay:
            print '\n\n\t\t========PREFIT OVERLAY==========', self.prefit_overlay
            for _prefit_overlay in self.prefit_overlay:
                _prefit_overlay.SetLineColor(ROOT.kRed)
                #_prefit_overlay.SetLineColor(ROOT.kBlue)
                _prefit_overlay.SetLineWidth(2)
                _prefit_overlay.SetFillColor(0)
                _prefit_overlay.SetFillStyle(4000)
                l_2.AddEntry(_prefit_overlay, 'PreFit', 'L')

        numLegend = 2 + k
        if self.overlay:
            numLegend += len(self.overlay)
        l.AddEntry(d1, datatitle, 'P')
        for j in range(0, k):
            legendEntryName = self.typLegendDict[self.typs[j]] if self.typs[
                j] in self.typLegendDict else self.typs[j]
            if j < numLegend / 2. - 1:
                l.AddEntry(self.histos[j], legendEntryName, 'F')
            else:
                l_2.AddEntry(self.histos[j], legendEntryName, 'F')
        if self.overlay:
            overScale = 100000
            for _overlay in self.overlay:  #find minimum scale to use for all overlays
                stackMax = allStack.GetMaximum()
                overMax = _overlay.GetMaximum() + 1e-30
                print "overScale=", overScale,
                print "stackMax/overMax=", stackMax / overMax,
                print "overMax=", overMax,
                print "stackMax=", stackMax,
                overScale = min(overScale, stackMax / overMax)
                if overScale >= 100000: overScale = 100000
                elif overScale >= 50000: overScale = 50000
                elif overScale >= 20000: overScale = 20000
                elif overScale >= 10000: overScale = 10000
                elif overScale >= 5000: overScale = 5000
                elif overScale >= 2000: overScale = 2000
                elif overScale >= 1000: overScale = 1000
                elif overScale >= 500: overScale = 500
                elif overScale >= 200: overScale = 200
                elif overScale >= 100: overScale = 100
                elif overScale >= 50: overScale = 50
                elif overScale >= 20: overScale = 20
                elif overScale >= 10: overScale = 10
                elif overScale >= 5: overScale = 5
                elif overScale >= 2: overScale = 2
                else: overScale = 1
            for _overlay in self.overlay:
                _overlay.Scale(overScale)
                l_2.AddEntry(
                    _overlay, self.typLegendDict[_overlay.GetTitle()] + " X" +
                    str(overScale), 'L')
#                l_2.AddEntry(_overlay,self.typLegendDict[_overlay.GetTitle()],'L')

        if self.normalize:
            print "I'm normalizing MC to data integral"
            if MC_integral != 0: stackscale = d1.Integral() / MC_integral
            if self.overlay:
                for _overlay in self.overlay:
                    _overlay.Scale(stackscale)
            stackhists = allStack.GetHists() + allStack.GetStack()
            for blabla in stackhists:
                if MC_integral != 0: blabla.Scale(stackscale)
            print "new MC_integral: ", allStack.GetStack().Last().Integral()

        allMC = allStack.GetStack().Last().Clone()

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')
        #yTitle = 's/(s+b) weighted entries'
        if not d1.GetSumOfWeights() % 1 == 0.0:
            yTitle = 'S/(S+B) weighted entries'
        else:
            yTitle = 'Entries'
        if not '/' in yTitle:
            if 'GeV' in self.xAxis:
                yAppend = '%.0f' % (allStack.GetXaxis().GetBinWidth(1))
            else:
                yAppend = '%.2f' % (allStack.GetXaxis().GetBinWidth(1))
            yTitle = '%s / %s' % (yTitle, yAppend)
            if 'GeV' in self.xAxis:
                yTitle += ' GeV'
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin, self.xMax)
        allStack.GetYaxis().SetRangeUser(0, 20000)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray + 3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')
        if not self.AddErrors:
            l_2.AddEntry(theErrorGraph, "MC uncert. (stat.)", "fl")
        else:
            l_2.AddEntry(theErrorGraph, "MC uncert. (stat.+ syst.)", "fl")
        Ymax = max(allStack.GetMaximum(), d1.GetMaximum()) * 1.7
        if self.log:
            allStack.SetMinimum(0.1)
            Ymax = Ymax * ROOT.TMath.Power(
                10, 1.2 *
                (ROOT.TMath.Log(1.2 *
                                (Ymax / 0.2)) / ROOT.TMath.Log(10))) * (0.2 *
                                                                        0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.3*(ROOT.TMath.Log(1.3*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.3*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1, 1)
        l.SetFillColor(0)
        l.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetBorderSize(0)

        if self.overlay:
            for _overlay in self.overlay:
                print("Drawing overlay")
                _overlay.Draw('hist,same')
        if self.prefit_overlay:
            for _prefit_overlay in self.prefit_overlay:
                print("Drawing overlay")
                _prefit_overlay.Draw('hist,same')
        d1.Draw("E,same")
        l.Draw()
        l_2.Draw()

        tPrel = self.myText("CMS", 0.17, 0.88, 1.04)
        print 'self.lumi is', self.lumi
        # if not d1.GetSumOfWeights() % 1 == 0.0:
        # tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%('7TeV',(float(5000.)/1000.)),0.17,0.83)
        # tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.78)
        # else:
        # tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.83)
        tLumi = self.myText(
            "#sqrt{s} =  %s, L = %.2f fb^{-1}" % (self.anaTag,
                                                  (float(self.lumi / 1000.0))),
            0.17, 0.83)
        tAddFlag = self.myText(addFlag, 0.17, 0.78)
        print 'Add Flag %s' % self.addFlag2
        if self.addFlag2:
            tAddFlag2 = self.myText(self.addFlag2, 0.17, 0.73)

        unten.cd()
        ROOT.gPad.SetTicks(1, 1)

        l2 = ROOT.TLegend(0.39, 0.85, 0.93, 0.97)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextSize(0.075)
        l2.SetNColumns(2)

        ratio, error = getRatio(d1, allMC, self.xMin, self.xMax, "",
                                self.maxRatioUncert, True)
        ksScore = d1.KolmogorovTest(allMC)
        chiScore = d1.Chi2Test(allMC, "UWCHI2/NDF")
        print ksScore
        print chiScore
        try:
            ratio.SetStats(0)
            ratio.GetXaxis().SetTitle(self.xAxis)
            ratioError = ROOT.TGraphErrors(error)
            ratioError.SetFillColor(ROOT.kGray + 3)
            ratioError.SetFillStyle(3013)
            ratio.Draw("E1")
        except Exception as e:
            print "ERROR with ratio histogram!", e

        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus", 0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus", 0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData, "R")
            print 'Fit on simulation'
            allMC.Fit(fitMC, "R")

        #if not self.AddErrors == None:
        #    self.AddErrors.SetLineColor(1)
        #    self.AddErrors.SetFillColor(5)
        #    self.AddErrors.SetFillStyle(3001)
        #    self.AddErrors.Draw('SAME2')

        #    l2.AddEntry(self.AddErrors,"MC uncert. (stat. + syst.)","f")

        r_err = {}
        if not self.ratio_band == None:
            for key in self.ratio_band:
                print 'key is', key
                r_err[key] = allMC.Clone()
                r_err[key].Divide(self.ratio_band[key])
                r_err[key].Draw('SAME2')
                r_err[key].SetLineStyle(self.ratio_band[key].GetLineStyle())
                r_err[key].SetLineWidth(self.ratio_band[key].GetLineWidth())
                r_err[key].SetLineColor(self.ratio_band[key].GetLineColor())

        try:
            if not self.AddErrors:
                l2.AddEntry(ratioError, "MC uncert. (stat.)", "f")
            else:
                l2.AddEntry(ratioError, "MC uncert. (stat. + syst.)", "f")
        except:
            pass

        l2.Draw()

        try:
            ratioError.Draw('SAME2')
        except:
            pass
        try:
            ratio.Draw("E1SAME")
            ratio.SetTitle("")
        except:
            pass
        m_one_line = ROOT.TLine(self.xMin, 1, self.xMax, 1)
        m_one_line.SetLineStyle(ROOT.kSolid)
        m_one_line.Draw("Same")

        if not self.blind:
            #tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
            tKsChi = self.myText(
                "#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}" % (chiScore),
                0.17, 0.895, 1.55)
        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize() * 2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
            t0.DrawTextNDC(0.1059, 0.96, "0")
        if not os.path.exists(self.plotDir):
            os.mkdir(self.plotDir)
        if not os.path.exists(self.plotDir + '/pdf'):
            os.mkdir(self.plotDir + '/pdf')
        name = '%s/pdf/%s' % (self.plotDir, self.options['pdfName'])
        name = name.replace('\\', "_")
        #        name = name.replace('/',"_")
        name = name.replace("'", "_")
        name = name.replace('"', "_")
        name = name.replace('"', "_")
        #        name = name.replace('.',"_")
        name = name.replace(',', "_")
        name = name.replace(' ', "_")
        pngName = (name.replace('.pdf', '.png')).replace("/pdf", "")
        rootName = (name.replace('.pdf', '.root')).replace("/pdf", "/root")
        CName = (name.replace('.pdf', '.C')).replace("/pdf", "/root")
        c.Print(name)
        c.Print(pngName)
        c.Print(rootName)
        c.Print(CName)
        #c.SaveAs(rootName)
        #c.SaveAs(CName)

        #print "DATA INTEGRAL: %s" %d1.Integral(d1.GetNbinsX()-2,d1.GetNbinsX())
        #fOut = ROOT.TFile.Open(name.replace('.pdf','.root'),'RECREATE')
        #for theHist in allStack.GetHists():
        #    if not self.AddErrors == None and not theHist.GetName() in ['ZH','WH','VH']:
        #print theHist.GetNbinsX()
        #print self.AddErrors.GetN()
        #print error.GetNbinsX()
        #        for bin in range(0,theHist.GetNbinsX()):
        #            theRelativeTotalError = self.AddErrors.GetErrorY(bin)
        #            if error.GetBinError(bin+1) > 0.:
        #                theRelativeIncrease = theRelativeTotalError/error.GetBinError(bin+1)
        #            else:
        #                theRelativeIncrease = 1.
        #print 'TheTotalRelativeIncrease is: %.2f' %theRelativeIncrease
        #print 'TheTotalStatError is: %.2f' %error.GetBinError(bin+1)
        #print 'TheTotalError is: %.2f' %theRelativeTotalError
        #            theHist.SetBinError(bin,theHist.GetBinError(bin)*theRelativeIncrease)
        #    theHist.SetDirectory(fOut)
        #    if theHist.GetName() == 'ZH' or theHist.GetName() == 'WH':
        #        theHist.SetName('VH')
        #    theHist.Write()
        #d1.SetName('data_obs')
        #d1.SetDirectory(fOut)
        #d1.Write()
        #fOut.Close()
        self.doCompPlot(allStack, l)

        print "Finished performing stacked plot"
        print "================================\n"
Пример #7
0
    def doPlot(self):
        TdrStyles.tdrStyle()
        histo_dict = HistoMaker.orderandadd([{
            self.typs[i]: self.histos[i]
        } for i in range(len(self.histos))], self.setup)
        #sort
        self.histos = [histo_dict[key] for key in self.setup]
        self.typs = self.setup

        c = ROOT.TCanvas(self.var, '', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        #oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0)
        oben = ROOT.TPad('oben', 'oben', 0, 0.5, 1.0, 1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        #unten = ROOT.TPad('unten1','unten1',0,0.0,1.0,0.17)
        unten = ROOT.TPad('unten1', 'unten1', 0, 0.0, 1.0, 0.29)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)
        #unten1 = ROOT.TPad('unten2','unten2',0,0.17,1.0,0.3)
        unten1 = ROOT.TPad('unten2', 'unten2', 0, 0.29, 1.0, 0.5)
        unten1.SetTopMargin(0.)
        unten1.SetBottomMargin(0.)
        unten1.SetFillStyle(4000)
        unten1.SetFrameFillStyle(1000)
        unten1.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()
        unten1.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var, '')
        #l = ROOT.TLegend(0.68, 0.65,0.92,0.92)
        l = ROOT.TLegend(0.6, 0.5, 0.92, 0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        #l.SetTextSize(0.035)
        l.SetTextSize(0.052)
        MC_integral = 0
        MC_entries = 0

        for histo in self.histos:
            MC_integral += histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m" % MC_integral

        #ORDER AND ADD TOGETHER
        #print typs
        #print setup

        if not 'DYc' in self.typs:
            self.typLegendDict.update({'DYlight': self.typLegendDict['DYlc']})
        print self.typLegendDict

        k = len(self.histos)

        for j in range(0, k):
            #print histos[j].GetBinContent(1)
            i = k - j - 1
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])

        d1 = ROOT.TH1F('noData', 'noData', self.nBins, self.xMin, self.xMax)
        datatitle = 'Data'
        addFlag = ''
        if 'Zee' in self.datanames and 'Zmm' in self.datanames:
            addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
        elif 'Zee' in self.datanames:
            addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
        elif 'Zmm' in self.datanames:
            addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
        elif 'Znn' in self.datanames:
            addFlag = 'Z(#nu#nu)H(b#bar{b})'
        elif 'Wmn' in self.datanames:
            addFlag = 'W(#mu#nu)H(b#bar{b})'
        elif 'Wen' in self.datanames:
            addFlag = 'W(e#nu)H(b#bar{b})'
        elif 'Wtn' in self.datanames:
            addFlag = 'W(#tau#nu)H(b#bar{b})'
        else:
            addFlag = 'pp #rightarrow VH; H #rightarrow b#bar{b}'
        for i in range(0, len(self.datas)):
            d1.Add(self.datas[i], 1)
        print "\033[1;32m\n\tDATA integral = %s\033[1;m" % d1.Integral()
        flow = d1.GetEntries() - d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m" % flow

        if self.overlay:
            self.overlay.SetLineColor(2)
            self.overlay.SetLineWidth(2)
            self.overlay.SetFillColor(0)
            self.overlay.SetFillStyle(4000)
            self.overlay.SetNameTitle('Overlay', 'Overlay')

        l.AddEntry(d1, datatitle, 'P')
        for j in range(0, k):
            l.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]], 'F')
        if self.overlay:
            l.AddEntry(self.overlay, self.typLegendDict['Overlay'], 'L')

        if self.normalize:
            if MC_integral != 0: stackscale = d1.Integral() / MC_integral
            if self.overlay:
                self.overlay.Scale(stackscale)
            stackhists = allStack.GetHists()
            for blabla in stackhists:
                if MC_integral != 0: blabla.Scale(stackscale)

        #if self.SignalRegion:
        #    allMC=allStack.GetStack().At(allStack.GetStack().GetLast()-1).Clone()
        #else:
        allMC = allStack.GetStack().Last().Clone()
        bkgMC = allStack.GetStack().First().Clone()

        sigRatio = allMC.Clone()
        sigRatio.Divide(bkgMC)

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')
        yTitle = 'Entries'
        if not '/' in yTitle:
            yAppend = '%.2f' % (allStack.GetXaxis().GetBinWidth(1))
            yTitle = '%s / %s' % (yTitle, yAppend)
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin, self.xMax)
        allStack.GetYaxis().SetRangeUser(0, 20000)
        allStack.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize() * 1.3)
        allStack.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 1.3)
        allStack.GetYaxis().SetTitleOffset(0.9)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray + 3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')
        #l.AddEntry(theErrorGraph,"B total uncert.","fl")
        l.AddEntry(theErrorGraph, "Background uncert.", "fl")
        Ymax = max(allStack.GetMaximum(), d1.GetMaximum()) * 1.7
        if self.log:
            allStack.SetMinimum(0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.2*(ROOT.TMath.Log(1.2*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.2*0.1)
            Ymax = Ymax * ROOT.TMath.Power(
                10, 0.9 *
                (ROOT.TMath.Log(0.9 *
                                (Ymax / 0.1)) / ROOT.TMath.Log(10))) * (0.2 *
                                                                        0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1, 1)
        #allStack.Draw("hist")
        l.SetFillColor(0)
        l.SetBorderSize(0)

        #if self.overlay:
        #    self.overlay.Draw('hist,same')
        d1.Draw("E,same")
        l.Draw()

        #tPrel = self.myText("CMS",0.17,0.88,1.04)
        #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%('7TeV',(float(5000.)/1000.)),0.17,0.83)
        #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.78)
        #tAddFlag = self.myText(addFlag,0.17,0.78)
        tPrel = self.myText("CMS Preliminary", 0.17, 0.85, 1.56)
        #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%('7TeV',(float(5000.)/1000.)),0.17,0.77,1.2)
        tLumi = self.myText(
            "#sqrt{s} =  %s, L = %.1f fb^{-1}" % (self.anaTag,
                                                  (float(self.lumi) / 1000.)),
            0.17, 0.69, 1.2)
        tAddFlag = self.myText(addFlag, 0.17, 0.61, 1.2)
        #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.77,1.2)
        #tAddFlag = self.myText(addFlag,0.17,0.69,1.2)

        unten.cd()
        ROOT.gPad.SetTicks(1, 1)

        l2 = ROOT.TLegend(0.5, 0.82, 0.92, 0.95)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextFont(62)
        #l2.SetTextSize(0.035)
        l2.SetNColumns(2)

        ratio, error = getRatio(d1, allMC, self.xMin, self.xMax, "",
                                self.maxRatioUncert)
        ksScore = d1.KolmogorovTest(allMC)
        chiScore = d1.Chi2Test(allMC, "UWCHI2/NDF")
        print ksScore
        print chiScore
        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray + 3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus", 0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus", 0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData, "R")
            print 'Fit on simulation'
            allMC.Fit(fitMC, "R")

        if not self.AddErrors == None:
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(1001)
            self.AddErrors.Draw('SAME2')

            l2.AddEntry(self.AddErrors, "MC uncert. (stat. + syst.)", "f")

            #ksScore = d1.KolmogorovTest( self.AddErrors )
            #chiScore = d1.Chi2Test( self.AddErrors , "UWCHI2/NDF")

        l2.AddEntry(ratioError, "MC uncert. (stat.)", "f")

        #l2.Draw()

        ratioError.Draw('SAME2')
        #ratio.GetXaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*3.6)
        ratio.GetXaxis().SetTitleSize(ROOT.gStyle.GetTitleSize() * 2.6)
        ratio.GetXaxis().SetTitleOffset(0.9)
        #ratio.GetXaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 3.6)
        ratio.GetXaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 2.6)
        #ratio.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*2.8)
        #ratio.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 2.8)
        ratio.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize() * 2.0)
        ratio.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 2.0)
        ratio.GetYaxis().SetTitleOffset(0.55)
        ratio.Draw("E1SAME")
        ratio.SetTitle("")
        ratio.SetYTitle("#frac{Data}{MC(S+B)}")
        if not self.blind:
            tKsChi = self.myText(
                "#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}" % (chiScore),
                0.17, 0.9, 1.7)
        m_one_line = ROOT.TLine(self.xMin, 1, self.xMax, 1)
        m_one_line.SetLineStyle(ROOT.kDashed)
        m_one_line.Draw("Same")

        unten1.cd()
        ROOT.gPad.SetTicks(1, 1)

        ratio1, error1 = getRatio(d1, bkgMC, self.xMin, self.xMax, "",
                                  self.maxRatioUncert)
        chiScore1 = d1.Chi2Test(bkgMC, "UWCHI2/NDF")
        ratio1.Draw("E1")
        #l2.Draw()

        ratioError1 = ROOT.TGraphErrors(error1)
        ratioError1.SetFillColor(ROOT.kGray + 3)
        ratioError1.SetFillStyle(3013)
        ratioError1.Draw('SAME2')
        sigRatio.SetFillStyle(0)
        sigRatio.SetLineColor(2)
        sigRatio.SetLineWidth(2)
        sigRatio.Draw('HISTSAME')
        ratio1.Draw("E1SAME")
        ratio1.SetTitle("")
        ratio1.SetYTitle("#frac{Data}{MC(B)}")
        #ratio1.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize()*3.7)
        ratio1.GetYaxis().SetTitleSize(ROOT.gStyle.GetTitleSize() * 2.7)
        ratio1.GetYaxis().SetTitleOffset(0.4)
        #ratio1.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 3.7)
        ratio1.GetYaxis().SetLabelSize(ROOT.gStyle.GetLabelSize() * 2.7)

        m_one_line.Draw("Same")

        if not self.blind:
            tKsChi1 = self.myText(
                "#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}" % (chiScore1),
                0.17, 0.865, 2.3)
        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize() * 2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
            t0.DrawTextNDC(0.1059, 0.96, "0")
        if not os.path.exists(self.plotDir):
            os.makedirs(os.path.dirname(self.plotDir))
        name = '%s/%s' % (self.plotDir, self.options['pdfName'])
        c.Print(name)
        fOut = ROOT.TFile.Open(name.replace('.pdf', '.root'), 'RECREATE')
        for theHist in allStack.GetHists():
            theHist.SetDirectory(fOut)
            if theHist.GetName() == 'ZH' or theHist.GetName() == 'WH':
                theHist.SetName('VH')
            theHist.Write()
        d1.SetName('data_obs')
        d1.SetDirectory(fOut)
        d1.Write()
        fOut.Close()
Пример #8
0
    def drawRatioPlot(self, dataHistogram, mcHistogram):

        self.pads['unten'].cd()
        ROOT.gPad.SetTicks(1,1)

        self.legends['ratio'] = ROOT.TLegend(0.39, 0.85, 0.93, 0.97)
        self.legends['ratio'].SetLineWidth(2)
        self.legends['ratio'].SetBorderSize(0)
        self.legends['ratio'].SetFillColor(0)
        self.legends['ratio'].SetFillStyle(4000)
        self.legends['ratio'].SetTextSize(0.075)
        self.legends['ratio'].SetNColumns(2)

        # convert TGraphAsymmErrors to TH1D
        if type(dataHistogram) == ROOT.TGraphAsymmErrors:
            print("INFO: converting TGraphAsymmErrors to TH1D for ratio plot...")
            convertedDataHistogram = ROOT.TH1D("data_th1d","data_th1d",self.histogramOptions['nBins'],self.histogramOptions['minX'], self.histogramOptions['maxX'])
            pointX = array.array('d', [0.0, 0.0])
            pointY = array.array('d', [0.0, 0.0])
            for i in range(dataHistogram.GetN()):
                dataHistogram.GetPoint(i, pointX, pointY)
                convertedDataHistogram.SetBinContent(1+i, pointY[0])
                convertedDataHistogram.SetBinError(1+i, 0.5*(dataHistogram.GetErrorYhigh(i)+dataHistogram.GetErrorYlow(i)))
                convertedDataHistogram.SetDrawOption("EP")
            dataHistogram = convertedDataHistogram

        # draw ratio plot
        self.ratioPlot, error = getRatio(dataHistogram, mcHistogram, self.histogramOptions['minX'], self.histogramOptions['maxX'], "", self.maxRatioUncert, True)

        ksScore = dataHistogram.KolmogorovTest(mcHistogram)
        chiScore = dataHistogram.Chi2Test(mcHistogram, "UWCHI2/NDF")
        print ("INFO: data/MC ratio, KS test:", ksScore, " chi2:", chiScore)
        try:
            self.ratioPlot.SetStats(0)
            self.ratioPlot.GetXaxis().SetTitle(self.xAxis)
            self.ratioError = ROOT.TGraphErrors(error)
            self.ratioError.SetFillColor(ROOT.kGray+3)
            self.ratioError.SetFillStyle(3013)
            self.ratioPlot.Draw("E1")
            self.ratioError.Draw('SAME2')
        except Exception as e:
            print ("\x1b[31mERROR: with ratio histogram!", e, "\x1b[0m")

        # blinded region
        if 'blindCut' in self.histogramOptions:

            # check if the blinding cut has the simple form var<num
            isSimpleCut = False
            print("DEBUG:", self.histogramOptions['blindCut'], self.histogramOptions['treeVar'], self.histogramOptions['blindCut'].startswith(self.histogramOptions['treeVar']))
            if self.histogramOptions['blindCut'].startswith(self.histogramOptions['treeVar']):
                if 'visualizeBlindCutThreshold' in self.histogramOptions:
                    isSimpleCut = True
                    blindingCutThreshold = float(self.histogramOptions['visualizeBlindCutThreshold'])
                else:
                    cond = self.histogramOptions['blindCut'].split(self.histogramOptions['treeVar'])[1]
                    print("DEBUG: cond=", cond)
                    if cond.startswith('<'):
                        num = cond.replace('<=','').replace('<','')
                        print("DEBUG: num=",num)
                        try:
                            blindingCutThreshold = float(num)
                            isSimpleCut = True
                        except:
                            pass

            if isSimpleCut:
                if blindingCutThreshold >= self.ratioPlot.GetXaxis().GetXmin() and blindingCutThreshold<=self.ratioPlot.GetXaxis().GetXmax():
                    blindedRegion = ROOT.TH1D("blind","blind",self.ratioPlot.GetXaxis().GetNbins(),self.ratioPlot.GetXaxis().GetXmin(),self.ratioPlot.GetXaxis().GetXmax())
                    for i in range(self.ratioPlot.GetXaxis().GetNbins()):
                        binLowEdgeValue = self.ratioPlot.GetXaxis().GetBinLowEdge(1+i)
                        value = 1.1
                        if binLowEdgeValue >= blindingCutThreshold:
                            error = 0.6
                        else:
                            error = 0.0
                        blindedRegion.SetBinContent(1+i, value)
                        blindedRegion.SetBinError(1+i, error)
                    blindedRegion.SetFillColor(ROOT.kRed)
                    blindedRegion.SetFillStyle(3018)
                    blindedRegion.SetMarkerSize(0)
                    blindedRegion.Draw("SAME E2")
                    self.addObject(blindedRegion)
                    print("DEBUG:", blindedRegion, self.ratioPlot.GetXaxis().GetNbins(),self.ratioPlot.GetXaxis().GetXmin(),self.ratioPlot.GetXaxis().GetXmax())

        self.m_one_line = ROOT.TLine(self.histogramOptions['minX'], 1, self.histogramOptions['maxX'], 1)
        self.m_one_line.SetLineStyle(ROOT.kSolid)
        self.m_one_line.Draw("Same")

        self.legends['ratio'].AddEntry(self.ratioError, self.mcUncertaintyLegend,"f")
        self.legends['ratio'].Draw() 
        if not self.blind:
            self.addObject(self.myText("#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}"%(chiScore), self.plotTextMarginLeft, 0.895, 1.55))
            t0 = ROOT.TText()
            t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
            t0.SetTextFont(ROOT.gStyle.GetLabelFont())
            if not self.log:
                t0.DrawTextNDC(0.1059, 0.96, "0")
Пример #9
0
    def drawRatioPlot(self, dataHistogram, mcHistogram):

        self.pads['unten'].cd()
        ROOT.gPad.SetTicks(1, 1)

        self.legends['ratio'] = ROOT.TLegend(0.39, 0.85, 0.93, 0.97)
        self.legends['ratio'].SetLineWidth(2)
        self.legends['ratio'].SetBorderSize(0)
        self.legends['ratio'].SetFillColor(0)
        self.legends['ratio'].SetFillStyle(4000)
        self.legends['ratio'].SetTextSize(0.075)
        self.legends['ratio'].SetNColumns(2)

        # draw ratio plot
        self.ratioPlot, error = getRatio(dataHistogram, mcHistogram,
                                         self.histogramOptions['minX'],
                                         self.histogramOptions['maxX'], "",
                                         self.maxRatioUncert, True)

        ksScore = dataHistogram.KolmogorovTest(mcHistogram)
        chiScore = dataHistogram.Chi2Test(mcHistogram, "UWCHI2/NDF")
        print("INFO: data/MC ratio, KS test:", ksScore, " chi2:", chiScore)
        try:
            self.ratioPlot.SetStats(0)
            self.ratioPlot.GetXaxis().SetTitle(self.xAxis)
            self.ratioError = ROOT.TGraphErrors(error)
            self.ratioError.SetFillColor(ROOT.kGray + 3)
            self.ratioError.SetFillStyle(3013)
            self.ratioPlot.Draw("E1")
            self.ratioError.Draw('SAME2')
        except Exception as e:
            print("\x1b[31mERROR: with ratio histogram!", e, "\x1b[0m")

        # blinded region
        if 'blindCut' in self.histogramOptions:

            # check if the blinding cut has the simple form var<num
            isSimpleCut = False
            print(
                "DEBUG:", self.histogramOptions['blindCut'],
                self.histogramOptions['treeVar'],
                self.histogramOptions['blindCut'].startswith(
                    self.histogramOptions['treeVar']))
            if self.histogramOptions['blindCut'].startswith(
                    self.histogramOptions['treeVar']):
                cond = self.histogramOptions['blindCut'].split(
                    self.histogramOptions['treeVar'])[1]
                print("DEBUG: cond=", cond)
                if cond.startswith('<'):
                    num = cond.replace('<=', '').replace('<', '')
                    print("DEBUG: num=", num)
                    try:
                        blindingCutThreshold = float(num)
                        isSimpleCut = True
                    except:
                        pass

            if isSimpleCut:
                blindedRegion = ROOT.TH1D("blind", "blind",
                                          self.ratioPlot.GetXaxis().GetNbins(),
                                          self.ratioPlot.GetXaxis().GetXmin(),
                                          self.ratioPlot.GetXaxis().GetXmax())
                for i in range(self.ratioPlot.GetXaxis().GetNbins()):
                    binLowEdgeValue = self.ratioPlot.GetXaxis().GetBinLowEdge(
                        1 + i)
                    value = 1.1
                    if binLowEdgeValue >= blindingCutThreshold:
                        error = 0.6
                    else:
                        error = 0.0
                    blindedRegion.SetBinContent(1 + i, value)
                    blindedRegion.SetBinError(1 + i, error)
                blindedRegion.SetFillColor(ROOT.kRed)
                blindedRegion.SetFillStyle(3018)
                blindedRegion.SetMarkerSize(0)
                blindedRegion.Draw("SAME E2")
                self.addObject(blindedRegion)
                print("DEBUG:", blindedRegion,
                      self.ratioPlot.GetXaxis().GetNbins(),
                      self.ratioPlot.GetXaxis().GetXmin(),
                      self.ratioPlot.GetXaxis().GetXmax())

        self.m_one_line = ROOT.TLine(self.histogramOptions['minX'], 1,
                                     self.histogramOptions['maxX'], 1)
        self.m_one_line.SetLineStyle(ROOT.kSolid)
        self.m_one_line.Draw("Same")

        if not self.AddErrors:
            self.legends['ratio'].AddEntry(self.ratioError,
                                           "MC uncert. (stat.)", "f")
        else:
            self.legends['ratio'].AddEntry(self.ratioError,
                                           "MC uncert. (stat. + syst.)", "f")
        self.legends['ratio'].Draw()
        if not self.blind:
            self.addObject(
                self.myText(
                    "#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}" %
                    (chiScore), 0.17, 0.895, 1.55))
            t0 = ROOT.TText()
            t0.SetTextSize(ROOT.gStyle.GetLabelSize() * 2.4)
            t0.SetTextFont(ROOT.gStyle.GetLabelFont())
            if not self.log:
                t0.DrawTextNDC(0.1059, 0.96, "0")
Пример #10
0
    def doPlot(self):

        #if 'low' in self.filename:
        #    self.addFlag2 = 'Low p_{T}(V)'
        #else: self.addFlag2 = 'High p_{T}(V)'

        TdrStyles.tdrStyle()

        print 'histos:', self.histos
        print 'self.typs:', self.typs
        print 'self.setup:', self.setup

        histo_dict = HistoMaker.orderandadd([{
            self.typs[i]: self.histos[i]
        } for i in range(len(self.histos))], self.setup)

        print 'histo dict:', histo_dict
        print 'histos:', self.histos
        print 'self.typs:', self.typs

        self.histos = [histo_dict[key] for key in self.setup]
        self.typs = self.setup

        #print 'self.histos:', self.histos
        #print 'self.typs:', self.typs
        #print 'histo dict:', histo_dict

        c = ROOT.TCanvas(self.var, '', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        #                               xlow  ylow  xup yup
        oben = ROOT.TPad('oben', 'oben', 0.0, 0.3, 1.0, 1.0)
        oben.SetBottomMargin(0.0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        unten = ROOT.TPad('unten', 'unten', 0.0, 0.0, 1.0, 0.29)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var, '')
        l = ROOT.TLegend(0.45, 0.6, 0.75, 0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        l.SetTextSize(0.035)
        l_2 = ROOT.TLegend(0.68, 0.6, 0.92, 0.92)
        l_2.SetLineWidth(2)
        l_2.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetFillStyle(4000)
        l_2.SetTextFont(62)
        l_2.SetTextSize(0.035)
        MC_integral = 0
        MC_entries = 0

        for histo in self.histos:
            MC_integral += histo.Integral()
            #print histo
            #print 'MC RMS:', histo.GetRMS()
            #print 'MC Mean:', histo.GetMean()

        print "\033[1;32m\n\tMC integral = %s\033[1;m" % MC_integral

        #ORDER AND ADD TOGETHER

        if not 'DYc' in self.typs:
            self.typLegendDict.update({'DYlight': self.typLegendDict['DYlc']})
        #print self.typLegendDict

        print 'All histos:', self.histos

        k = len(self.histos)
        for j in range(0, k):
            i = k - j - 1
            data4bin = 0
            print '\nColor:', self.histos[i], int(
                self.colorDict[self.typs[i]]), self.histos[i].Integral()
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])
            print '# of MC bins:', self.histos[i].GetNbinsX() + 1
            for bin in range(0, self.histos[i].GetNbinsX() + 1):
                print 'MC in bin ', bin, ':', self.histos[i].GetBinContent(bin)
                if bin > 11: data4bin += self.histos[i].GetBinContent(bin)

            print 'Region:', self.histos[i]
            print '==== MC in 4 most sensitive BDT bins:', data4bin

        print 'StackMaker Data Bins:', self.nBins, self.xMin, self.xMax
        d1 = ROOT.TH1F('noData', 'noData', self.nBins, self.xMin, self.xMax)

        print 'self.datanames:', self.datanames
        print 'Self.var:', self.var

        # if 'Wmn' in self.datanames and not 'CMVA' in self.var or 'Wen' in self.datanames and not 'CMVA' in self.var:
        #     if not isVV:
        #         binBoundaries = [0.3, 0.4, 0.5, 0.6, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 1.0]

        #     if isVV:
        #         binBoundaries = [0.3, 0.4, 0.5, 0.6, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 1.0]

        #     bins = array('f', binBoundaries)
        #     d1 = ROOT.TH1F('noData','noData',self.nBins,bins)

        # if 'Znn' in self.datanames and 'CMVA' not in self.var:
        #     print 'Rebin Znn'
        #     d1 = ROOT.TH1F('noData','noData',35, -0.8, 1)
        #     Znn_temp_data = ROOT.TH1F('noData','noData',35, -0.8, 1)

        Znn_temp_data = d1

        datatitle = 'Data'
        addFlag = ''

        # if 'Zee' in self.datanames and 'Zuu' in self.datanames or 'Zll' in self.datanames:
        #     if isVV:
        #         addFlag = '2-lep: Z(l^{-}l^{+})Z(b#bar{b})'
        #     else: addFlag = '2-lep: Z(l^{-}l^{+})H(b#bar{b})'
        # elif 'Zee' in self.datanames:
        #     if isVV: addFlag = '2-lep: Z(e^{-}e^{+})Z(b#bar{b})'
        #     else: addFlag = '2-lep: Z(e^{-}e^{+})H(b#bar{b})'
        # elif 'Zuu' in self.datanames:
        #     if isVV: addFlag = '2-lep: Z(#mu^{-}#mu^{+})Z(b#bar{b})'
        #     else: addFlag = '2-lep: Z(#mu^{-}#mu^{+})H(b#bar{b})'
        # elif 'Znn' in self.datanames:
        #     if isVV: addFlag = '0-lep: Z(#nu#nu)Z(b#bar{b})'
        #     else: addFlag = '0-lep: Z(#nu#nu)H(b#bar{b})'
        # elif 'Wmn' in self.datanames:
        #     if isVV:
        #         addFlag = '1-lep: W(#mu#nu)Z(b#bar{b})'
        #     else: addFlag = '1-lep: W(#mu#nu)H(b#bar{b})'
        # elif 'Wen' in self.datanames:
        #     if isVV: addFlag = '1-lep: W(e#nu)Z(b#bar{b})'
        #     else: addFlag = '1-lep: W(e#nu)H(b#bar{b})'
        # elif 'Wtn' in self.datanames:
        #         addFlag = 'W(#tau#nu)H(b#bar{b})'

        if 'Zee' in self.datanames:
            addFlag = '2-lep (e)'
        elif 'Zuu' in self.datanames:
            addFlag = '2-lep (#mu)'
        elif 'Znn' in self.datanames:
            addFlag = '0-lep'
        elif 'Wmn' in self.datanames:
            addFlag = '1-lep (#mu)'
        elif 'Wen' in self.datanames:
            addFlag = '1-lep (e)'

        addFlag3 = ''

        if 'Zlf' in self.options['pdfName'] or 'Zlight' in self.options[
                'pdfName']:
            addFlag3 = 'Z+udscg enriched'
        if 'Zhf' in self.options['pdfName'] or 'Zbb' in self.options['pdfName']:
            addFlag3 = 'Z+b#bar{b} enriched'
        if 'TT' in self.options['pdfName'] or 'tt' in self.options['pdfName']:
            addFlag3 = 't#bar{t} enriched'
        if 'whf' in self.options['pdfName']:
            addFlag3 = 'W+b#bar{b} enriched'
        if 'wlf' in self.options['pdfName']:
            addFlag3 = 'W+udscg enriched'

        data4bin = 0

        print 'Datafile:', self.datas
        print self.datas[i].GetNbinsX()

        for i in range(0, len(self.datas)):
            print 'Datas:', self.datas
            for bin in range(1, self.datas[i].GetNbinsX() + 1):
                print 'Data in bin ', bin, ':', self.datas[i].GetBinContent(
                    bin)
                if bin > 11: data4bin += self.datas[i].GetBinContent(bin)

                #if 'Znn' in self.datanames and 'gg_plus' in self.var and bin < 36:
                #   print 'Rebin Znn Data'
                #   Znn_temp_data.SetBinContent(bin, self.datas[i].GetBinContent(bin))

            #if 'Znn' in self.datanames and 'gg_plus' in self.var:
            #    d1.Add(Znn_temp_data,1)
            #else:
            d1.Add(self.datas[i], 1)

        print 'Data Region:', self.options['pdfName']
        print '\n\t ==== Data in 4 most sensitive BDT bins:', data4bin

        #print "\033[1;32m\n\tDATA integral = %s\033[1;m"%d1.Integral()
        flow = d1.GetEntries() - d1.Integral()

        #print 'Data Mean:', d1.GetRMS()
        #print 'Data RMS:', d1.GetMean()

        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m" % flow

        #print 'self.xMax:', self.xMin
        #print 'self.xMax:', self.xMax

        if not isOverlay:
            self.overlay = False

        if self.overlay and not isinstance(self.overlay, list):
            self.overlay = [self.overlay]
        if self.overlay:
            print '\n\n\t\t========OVERLAY==========', self.overlay
            for _overlay in self.overlay:
                #if _overlay.GetName() == 'ZH125':
                if 'ZH' in _overlay.GetName() or 'WH' in _overlay.GetName(
                ) or 'log' in _overlay.GetName() and not isVV:
                    _overlay.SetLineColor(int(self.colorDict['ZH']))
                    _overlay.SetLineWidth(2)
                    _overlay.SetFillColor(0)
                    _overlay.SetFillStyle(4000)
                #if _overlay.GetName() == 'ggZH125':
                #if 'ggZH' in _overlay.GetName():
                #    _overlay.SetLineColor(int(self.colorDict['ggZH']))
                #    _overlay.SetLineWidth(2)
                #    _overlay.SetFillColor(0)
                #    _overlay.SetFillStyle(4000)

                if isVV:
                    _overlay.SetLineColor(int(self.colorDict['VVHF']))

        # PREfit overlay
        if self.prefit_overlay:
            print '\n\n\t\t========PREFIT OVERLAY==========', self.prefit_overlay
            for _prefit_overlay in self.prefit_overlay:
                _prefit_overlay.SetLineColor(6)
                _prefit_overlay.SetLineWidth(2)
                _prefit_overlay.SetFillColor(0)
                _prefit_overlay.SetFillStyle(4000)
                l_2.AddEntry(_prefit_overlay, 'PreFit', 'L')

        numLegend = 2 + k
        if self.overlay:
            numLegend += len(self.overlay)
        l.AddEntry(d1, datatitle, 'P')
        for j in range(0, k):
            if j < numLegend / 2. - 1:
                l.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]],
                           'F')
            else:
                l_2.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]],
                             'F')

        if self.overlay:
            overScale = 100000
            for _overlay in self.overlay:  #find minimum scale to use for all overlays
                stackMax = allStack.GetMaximum()
                overMax = _overlay.GetMaximum()
                print 'Overlay:', self.overlay
                print "overScale=", overScale,
                print "overMax=", overMax,
                print "stackMax=", stackMax,
                print "stackMax/overMax=", stackMax / overMax,
                overScale = min(overScale, stackMax / overMax)
                if overScale >= 100000: overScale = 100000
                elif overScale >= 50000: overScale = 50000
                elif overScale >= 20000: overScale = 20000
                elif overScale >= 10000: overScale = 10000
                elif overScale >= 5000: overScale = 5000
                elif overScale >= 2000: overScale = 2000
                elif overScale >= 1000: overScale = 1000
                elif overScale >= 500: overScale = 500
                elif overScale >= 200: overScale = 200
                elif overScale >= 100: overScale = 100
                elif overScale >= 50: overScale = 50
                elif overScale >= 20: overScale = 20
                elif overScale >= 10: overScale = 10
                elif overScale >= 5: overScale = 5
                elif overScale >= 2: overScale = 2
                else: overScale = 1
            for _overlay in self.overlay:
                #_overlay.Scale(overScale)
                print '\n\tOverScale:', overScale

                #if 'ZH' in _overlay.GetName() or 'log' in _overlay.GetName() and not isVV:
                if not isVV:
                    #l_2.AddEntry(_overlay,self.typLegendDict['VH']+" x"+str(overScale),'L')
                    l_2.AddEntry(_overlay, self.typLegendDict['VH'], 'L')

                    #if 'ZH'in _overlay.GetName():
                    #l_2.AddEntry(_overlay,self.typLegendDict['ZH'],'L')
                    #if 'ggZH' in _overlay.GetName():
                    #l_2.AddEntry(_overlay,self.typLegendDict['ggZH'],'L')

                #if 'VV' in _overlay.GetName():
                if isVV:
                    l_2.AddEntry(_overlay, "VV x" + str(overScale), 'L')

                #if 'WH' in _overlay.GetName():
                #    l_2.AddEntry(_overlay,self.typLegendDict['VH']+" x"+str(overScale),'L')

        #if self.normalize:
        #if MC_integral != 0:
        #    stackscale = d1.Integral()/MC_integral
        #stackscale = MC_integral
        #else: stackscale = 1

        stackscale = 1

        #if self.overlay:
        #    for _overlay in self.overlay:
        #        _overlay.Scale(stackscale)

        #if self.prefit_overlay:
        #    for _prefit_overlay in self.prefit_overlay:
        #        _prefit_overlay.Scale(1)

        stackhists = allStack.GetHists()
        #for blabla in stackhists:
        #    if MC_integral != 0: blabla.Scale(stackscale)

        allMC = allStack.GetStack().Last().Clone()

        #print 'allStack:', allStack
        #print 'allMC:', allMC
        #print '# of Hists in stack:', allStack.ls()

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')

        # Tline temp hack for pt balance
        #pt_balance_line = ROOT.TLine(1, 0, 1, 1400)
        #pt_balance_line.SetLineStyle(ROOT.kSolid)
        #pt_balance_line.SetLineColor(ROOT.kRed)
        #pt_balance_line.Draw("Same")

        if not d1.GetSumOfWeights() % 1 == 0.0:
            #yTitle = 'S/(S+B) weighted entries'
            yTitle = 'Entries'
        else:
            yTitle = 'Entries'

        if not '/' in yTitle:
            if 'GeV' in self.xAxis:
                yAppend = '%.0f' % (allStack.GetXaxis().GetBinWidth(1))
            else:
                yAppend = '%.2f' % (allStack.GetXaxis().GetBinWidth(1))
            yTitle = '%s / %s' % (yTitle, yAppend)
            if 'GeV' in self.xAxis:
                yTitle += ' GeV'
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetYaxis().SetRangeUser(0, 20000)

        allStack.GetXaxis().SetRangeUser(self.xMin, self.xMax)
        #allStack.GetHistogram().GetXaxis().SetTickLength(0)
        allStack.GetHistogram().GetXaxis().SetLabelOffset(999)

        #allStack.GetHistogram().GetYaxis().SetLabelSize(0.01)

        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray + 3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')

        l_2.AddEntry(theErrorGraph, "MC uncert. (stat.)", "fl")

        # Add mu signal strength
        #l_2.AddEntry(0, '#mu = 1.19', '')

        Ymax = max(allStack.GetMaximum(), d1.GetMaximum()) * 1.7

        if self.log:
            allStack.SetMinimum(0.1)
            Ymax = Ymax * ROOT.TMath.Power(
                10, 1.2 *
                (ROOT.TMath.Log(1.2 *
                                (Ymax / 0.1)) / ROOT.TMath.Log(10))) * (0.2 *
                                                                        0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.3*(ROOT.TMath.Log(1.3*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.3*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1, 1)
        l.SetFillColor(0)
        l.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetBorderSize(0)

        if self.overlay:
            for _overlay in self.overlay:
                _overlay.Draw('hist same')

        d1.SetBinErrorOption(TH1.kPoisson)

        d1.Draw("E,same")

        # this shows poisson errors for empty data points
        # d1.Draw("E0,same")

        l.Draw()
        l_2.Draw()

        if self.prefit_overlay:
            for _prefit_overlay in self.prefit_overlay:
                _prefit_overlay.Draw('same')
        #d1.Draw("E,same")
        #l.Draw()
        #l_2.Draw()

        tPrel = self.myText("CMS Preliminary", 0.17, 0.88, 0.8)
        if not d1.GetSumOfWeights() % 1 == 0.0:
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" %
                (self.anaTag, (float(self.lumi) / 1000.)), 0.17, 0.83)
            #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f pb^{-1}"%(self.anaTag,(float(self.lumi))),0.17,0.78)
        else:
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" %
                (self.anaTag, (float(self.lumi) / 1000.)), 0.17, 0.83)
            #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f pb^{-1}"%(self.anaTag,(float(self.lumi))),0.17,0.83)

        tAddFlag = self.myText(addFlag, 0.17, 0.78)
        #print 'Add Flag %s' %self.addFlag2
        if self.addFlag2:
            tAddFlag2 = self.myText(self.addFlag2, 0.17, 0.73)
            if addFlag3:
                tAddFlag3 = self.myText(addFlag3, 0.17, 0.68)
        else:
            if addFlag3:
                tAddFlag3 = self.myText(addFlag3, 0.17, 0.73)

        unten.cd()
        ROOT.gPad.SetTicks(1, 1)

        l2 = ROOT.TLegend(0.3, 0.85, 0.93, 0.97)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextSize(0.075)
        l2.SetNColumns(2)

        # Ratio Maker
        ratio, error = getRatio(d1, allMC, self.xMin, self.xMax, "",
                                self.maxRatioUncert)
        ksScore = d1.KolmogorovTest(allMC)
        chiScore = d1.Chi2Test(allMC, "UWCHI2/NDF")

        #For BDT handle the empty data points
        # if 'BDT' in self.xAxis and 'Znn' not in self.options['pdfName'] and 'CR' not in self.options['pdfName']:

        #     for bin in range(1,ratio.GetNbinsX()+1):
        #         #print 'Ratio in bin ', bin, ':', ratio.GetBinContent(bin)
        #         #print 'Error in bin ', bin, ':', ratio.GetBinError(bin)
        #         if ratio.GetBinContent(bin) == 0:
        #             ratio.SetBinContent(bin,0.0001)
        #print '\t\tRatio in bin ', bin, ':', ratio.GetBinContent(bin)

        # Set the ratio error for zero data bins.
        # Formula is ratio^2 * sqrt( (dx/x)^2 + (dy/y)^2) -> delta data/ # MC in that bin
        #print '\t\tdata error, MC count:', np.sqrt(allStack.GetStack().Last().GetBinContent(bin)), allStack.GetStack().Last().GetBinContent(bin)
        #temp_error = 1.8 / allStack.GetStack().Last().GetBinContent(bin)
        #ratio.SetBinError(bin,temp_error)
        #print '\t\tError in bin ', bin, ':', ratio.GetBinError(bin)

        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratio.GetXaxis().SetLabelSize(0.09)
        ratio.GetXaxis().SetLabelOffset(0.03)
        ratio.GetYaxis().SetLabelSize(0.07)
        ratio.GetYaxis().SetLabelFont(22)
        ratio.GetYaxis().SetTitleFont(22)
        print 'Label size:', ratio.GetXaxis().GetLabelSize(), ratio.GetXaxis(
        ).GetLabelOffset()

        # Make the Ratio error bars
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray + 3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus", 0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus", 0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData, "R")
            print 'Fit on simulation'
            allMC.Fit(fitMC, "R")

        if not self.AddErrors == None:
            self.AddErrors.SetLineColor(1)
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(3001)
            self.AddErrors.Draw('SAME2')
            l2.AddEntry(self.AddErrors, "MC(stat.+Prefit syst.)", "f")

        if not self.AddErrors_Postfit == None:
            self.AddErrors_Postfit.SetLineColor(1)
            #self.AddErrors_Postfit.SetFillColorAlpha(2, 0.60)
            self.AddErrors_Postfit.SetFillColor(5)
            self.AddErrors_Postfit.SetFillStyle(3001)
            self.AddErrors_Postfit.Draw('SAME2')
            l2.AddEntry(self.AddErrors_Postfit, "MC(stat.+Postfit syst.)", "f")

        l2.AddEntry(ratioError, "MC(stat.)", "f")

        ratioError.Draw('SAME2')
        ratio.Draw("E1SAME")
        ratio.SetTitle("")

        l2.Draw()

        m_one_line = ROOT.TLine(self.xMin, 1, self.xMax, 1)
        m_one_line.SetLineStyle(ROOT.kSolid)
        m_one_line.Draw("Same")

        if not self.blind:
            #tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
            tKsChi = self.myText(
                "#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}" % (chiScore),
                0.17, 0.895, 1.55)
            temp = 0

        #t0 = ROOT.TText()
        #t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
        #t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        #if not self.log:

    #    t0.DrawTextNDC(0.1059,0.96, "0")

        PlotDir = self.plotDir + self.region
        if not os.path.exists(PlotDir):
            os.makedirs(os.path.dirname(PlotDir + '/'))
        name = '%s/%s' % (PlotDir, self.options['pdfName'])

        if self.log:
            name = '%s/log_%s' % (PlotDir, self.options['pdfName'])

        if self.filename != None:
            name = '%s/%s_%s' % (PlotDir, self.filename,
                                 self.options['pdfName'])

        if isVV:
            name = '%s/VV_%s' % (PlotDir, self.options['pdfName'])

        c.Print(name)

        # Now in png form
        name2 = name.replace('.pdf', '.png', 2)
        #print '---> name:', name2
        c.Print(name2)

        name3 = name2.replace('.png', '.root', 3)
        #print '---> name:', name3
        c.Print(name3)

        name4 = name3.replace('.root', '.C', 4)
        #print '---> name:', name4
        c.Print(name4)
Пример #11
0
    def doPlot(self):

        TdrStyles.tdrStyle()

        histo_dict = HistoMaker.orderandadd([{self.typs[i]:self.histos[i]} for i in range(len(self.histos))],self.setup)
        self.histos=[histo_dict[key] for key in self.setup]
        self.typs=self.setup
    
        #print 'self.histos:', self.histos
        #print 'self.typs:', self.typs
        #print 'histo dict:', histo_dict

        c = ROOT.TCanvas(self.var,'', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)
        
        oben = ROOT.TPad('oben','oben',0,0.3 ,1.0,1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        unten = ROOT.TPad('unten','unten',0,0.0,1.0,0.3)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var,'')     
        l = ROOT.TLegend(0.45, 0.6,0.75,0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        l.SetTextSize(0.035)
        l_2 = ROOT.TLegend(0.68, 0.6,0.92,0.92)
        l_2.SetLineWidth(2)
        l_2.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetFillStyle(4000)
        l_2.SetTextFont(62)
        l_2.SetTextSize(0.035)
        MC_integral=0
        MC_entries=0

        for histo in self.histos:
            MC_integral+=histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m"%MC_integral

        #ORDER AND ADD TOGETHER

        if not 'DYc' in self.typs: self.typLegendDict.update({'DYlight':self.typLegendDict['DYlc']})
        #print self.typLegendDict

        k=len(self.histos)
        for j in range(0,k):
            i=k-j-1
            print 'Color:', self.histos[i], int(self.colorDict[self.typs[i]]), self.histos[i].Integral()
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])
            

        print allStack

        d1 = ROOT.TH1F('noData','noData',self.nBins,self.xMin,self.xMax)
        datatitle='Data'
        addFlag = ''
        if 'Zee' in self.datanames and 'Zuu' in self.datanames or 'Zll' in self.datanames:
	        addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
        elif 'Zee' in self.datanames:
	        addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
        elif 'Zuu' in self.datanames:
	        addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
        elif 'Znn' in self.datanames:
	        addFlag = 'Z(#nu#nu)H(b#bar{b})'
        elif 'Wmn' in self.datanames:
	        addFlag = 'W(#mu#nu)H(b#bar{b})'
        elif 'Wen' in self.datanames:
	        addFlag = 'W(e#nu)H(b#bar{b})'
        elif 'Wtn' in self.datanames:
	        addFlag = 'W(#tau#nu)H(b#bar{b})'

        for i in range(0,len(self.datas)):
            print 'Datas:', self.datas
            print self.datas[i]
            d1.Add(self.datas[i],1)

        print "\033[1;32m\n\tDATA integral = %s\033[1;m"%d1.Integral()
        flow = d1.GetEntries()-d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m"%flow


        if self.overlay and not isinstance(self.overlay,list):
            self.overlay = [self.overlay]
        if self.overlay:
            print '\n\n\t\t========OVERLAY==========',self.overlay    
            for _overlay in self.overlay:
                #if _overlay.GetName() == 'ZH125':
                if 'ZH' in _overlay.GetName():
                    _overlay.SetLineColor(int(self.colorDict['ZH']))
                #if _overlay.GetName() == 'ggZH125':
                if 'ggZH' in _overlay.GetName():
                    _overlay.SetLineColor(int(self.colorDict['ggZH']))
                _overlay.SetLineWidth(2)
                _overlay.SetFillColor(0)
                _overlay.SetFillStyle(4000)

        # PREfit overlay
        if self.prefit_overlay:
            print '\n\n\t\t========PREFIT OVERLAY==========',self.prefit_overlay
            for _prefit_overlay in self.prefit_overlay:
                _prefit_overlay.SetLineColor(ROOT.kRed)
                _prefit_overlay.SetLineWidth(2)
                _prefit_overlay.SetFillColor(0)
                _prefit_overlay.SetFillStyle(4000)
                l_2.AddEntry(_prefit_overlay,'PreFit','L')
        
                
        numLegend = 2+k
        if self.overlay:
            numLegend += len(self.overlay)
        l.AddEntry(d1,datatitle,'P')
        for j in range(0,k):
            if j < numLegend/2.-1:
                l.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')
            else:
                l_2.AddEntry(self.histos[j],self.typLegendDict[self.typs[j]],'F')

        if self.overlay:
            overScale = 100000
            for _overlay in self.overlay: #find minimum scale to use for all overlays
                stackMax = allStack.GetMaximum()
                overMax = _overlay.GetMaximum()
                #print "overScale=",overScale,
                #print "stackMax/overMax=",stackMax/overMax,
                #print "overMax=",overMax,
                #print "stackMax=",stackMax,
                overScale = min(overScale,stackMax/overMax)
                if overScale >= 100000: overScale=100000
                elif overScale >= 50000: overScale=50000
                elif overScale >= 20000: overScale=20000
                elif overScale >= 10000: overScale=10000
                elif overScale >= 5000: overScale=5000
                elif overScale >= 2000: overScale=2000
                elif overScale >= 1000: overScale=1000
                elif overScale >= 500: overScale=500
                elif overScale >= 200: overScale=200
                elif overScale >= 100: overScale=100
                elif overScale >= 50: overScale=50
                elif overScale >= 20: overScale=20
                elif overScale >= 10: overScale=10
                elif overScale >= 5: overScale=5
                elif overScale >= 2: overScale=2
                else: overScale=1
            for _overlay in self.overlay:
                _overlay.Scale(overScale)
                print '\n\tOverScale:', overScale
                
                if 'ZH' in _overlay.GetName():
                    l_2.AddEntry(_overlay,self.typLegendDict['ZH']+" x"+str(overScale),'L')
                    #if 'ZH'in _overlay.GetName():
                    #l_2.AddEntry(_overlay,self.typLegendDict['ZH'],'L')
                    #if 'ggZH' in _overlay.GetName():
                    #l_2.AddEntry(_overlay,self.typLegendDict['ggZH'],'L')

    
        #if self.normalize:
        if MC_integral != 0:
            stackscale = d1.Integral()/MC_integral
            #stackscale = MC_integral
        else: stackscale = 1
         
        if self.overlay:
            for _overlay in self.overlay:
                _overlay.Scale(stackscale)

        #if self.prefit_overlay:
        #    for _prefit_overlay in self.prefit_overlay:
        #        _prefit_overlay.Scale(1)

       #stackhists = allStack.GetHists()
       #for blabla in stackhists:
       #    if MC_integral != 0: blabla.Scale(stackscale)
       
        allMC = allStack.GetStack().Last().Clone()

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')
        
        
        # Tline temp hack for pt balance
        pt_balance_line = ROOT.TLine(1, 0, 1, 130)
        pt_balance_line.SetLineStyle(ROOT.kSolid)
        pt_balance_line.SetLineColor(ROOT.kRed)
        #pt_balance_line.Draw("Same")
        

        if not d1.GetSumOfWeights() % 1 == 0.0:
            #yTitle = 'S/(S+B) weighted entries'
            yTitle = 'Entries'
        else:
            yTitle = 'Entries'

        if not '/' in yTitle:
            if 'GeV' in self.xAxis:
                yAppend = '%.0f' %(allStack.GetXaxis().GetBinWidth(1)) 
            else:
                yAppend = '%.2f' %(allStack.GetXaxis().GetBinWidth(1)) 
            yTitle = '%s / %s' %(yTitle, yAppend)
            if 'GeV' in self.xAxis:
                yTitle += ' GeV'
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin,self.xMax)
        allStack.GetYaxis().SetRangeUser(0,20000)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray+3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')
        l_2.AddEntry(theErrorGraph,"MC uncert. (stat.)","fl")
        Ymax = max(allStack.GetMaximum(),d1.GetMaximum())*1.7
        if self.log:
            allStack.SetMinimum(0.1)
            Ymax = Ymax*ROOT.TMath.Power(10,1.2*(ROOT.TMath.Log(1.2*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.2*0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.3*(ROOT.TMath.Log(1.3*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.3*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1,1)
        l.SetFillColor(0)
        l.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetBorderSize(0)
        
        if self.overlay:
            for _overlay in self.overlay:
                _overlay.Draw('same')
        d1.Draw("E,same")
        l.Draw()
        l_2.Draw()

        if self.prefit_overlay:
            for _prefit_overlay in self.prefit_overlay:
                _prefit_overlay.Draw('same')
        d1.Draw("E,same")
        l.Draw()
        l_2.Draw()


        tPrel = self.myText("CMS",0.17,0.88,1.04)
        if not d1.GetSumOfWeights() % 1 == 0.0:
            tLumi = self.myText("#sqrt{s} =  %s, L = %.3f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.83)
            #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f pb^{-1}"%(self.anaTag,(float(self.lumi))),0.17,0.78)
        else:
            tLumi = self.myText("#sqrt{s} =  %s, L = %.3f fb^{-1}"%(self.anaTag,(float(self.lumi)/1000.)),0.17,0.83)
            #tLumi = self.myText("#sqrt{s} =  %s, L = %.1f pb^{-1}"%(self.anaTag,(float(self.lumi))),0.17,0.83)

        tAddFlag = self.myText(addFlag,0.17,0.78)
        print 'Add Flag %s' %self.addFlag2
        if self.addFlag2:
            tAddFlag2 = self.myText(self.addFlag2,0.17,0.73)

        unten.cd()
        ROOT.gPad.SetTicks(1,1)

        l2 = ROOT.TLegend(0.39, 0.85,0.93,0.97)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextSize(0.075)
        l2.SetNColumns(2)

        #Temp remopval of the ratio maker
        ratio, error = getRatio(d1, allMC, self.xMin, self.xMax, "", self.maxRatioUncert)
        ksScore = d1.KolmogorovTest( allMC )
        chiScore = d1.Chi2Test( allMC , "UWCHI2/NDF")
        print ksScore
        print chiScore
        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray+3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus",0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus",0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData,"R")
            print 'Fit on simulation'
            allMC.Fit(fitMC,"R")

        if not self.AddErrors == None:
            self.AddErrors.SetLineColor(1)
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(3001)
            self.AddErrors.Draw('SAME2')
            l2.AddEntry(self.AddErrors,"MC uncert. (stat. + syst.)","f")

        l2.AddEntry(ratioError,"MC uncert. (stat.)","f")

        ratioError.Draw('SAME2')
        ratio.Draw("E1SAME")
        ratio.SetTitle("")
        
        
        
        l2.Draw()
        
        m_one_line = ROOT.TLine(self.xMin,1,self.xMax,1)
        m_one_line.SetLineStyle(ROOT.kSolid)
        m_one_line.Draw("Same")
        
        
        if not self.blind:
            #tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
            tKsChi = self.myText("#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}"%(chiScore),0.17,0.895,1.55)
            temp = 0

        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize()*2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
    	    t0.DrawTextNDC(0.1059,0.96, "0")

        PlotDir = self.plotDir+self.region
        if not os.path.exists(PlotDir):
            os.makedirs(os.path.dirname(PlotDir+'/'))
        name = '%s/%s' %(PlotDir, self.options['pdfName'])
        c.Print(name)
        
        # Now in png form
        name2 = name.replace('.pdf', '.png', 2)
        #print '---> name:', name2
        c.Print(name2)
        
        name3= name2.replace('.png', '.root', 3)
        #print '---> name:', name3
        c.Print(name3)
        
        name4= name3.replace('.root', '.C', 4)
        #print '---> name:', name4
        c.Print(name4)
        
        
        
        #print "DATA INTEGRAL: %s" %d1.Integral(d1.GetNbinsX()-2,d1.GetNbinsX()) 
        #fOut = ROOT.TFile.Open(name.replace('.pdf','.root'),'RECREATE')
        #for theHist in allStack.GetHists():
        #    if not self.AddErrors == None and not theHist.GetName() in ['ZH','WH','VH']:
                #print theHist.GetNbinsX()
                #print self.AddErrors.GetN()
                #print error.GetNbinsX()
        #        for bin in range(0,theHist.GetNbinsX()):
        #            theRelativeTotalError = self.AddErrors.GetErrorY(bin)
        #            if error.GetBinError(bin+1) > 0.:
        #                theRelativeIncrease = theRelativeTotalError/error.GetBinError(bin+1)
        #            else:
        #                theRelativeIncrease = 1.
                    #print 'TheTotalRelativeIncrease is: %.2f' %theRelativeIncrease
                    #print 'TheTotalStatError is: %.2f' %error.GetBinError(bin+1)
                    #print 'TheTotalError is: %.2f' %theRelativeTotalError
        #            theHist.SetBinError(bin,theHist.GetBinError(bin)*theRelativeIncrease)
        #    theHist.SetDirectory(fOut)
        #    if theHist.GetName() == 'ZH' or theHist.GetName() == 'WH':
        #        theHist.SetName('VH')
        #    theHist.Write()
        #d1.SetName('data_obs')
        #d1.SetDirectory(fOut)
        #d1.Write()
        #fOut.Close()

        # Make comparison normalized plots
        self.doCompPlot(allStack,l)
Пример #12
0
    def doPlot(self):
        TdrStyles.tdrStyle()
        histo_dict = HistoMaker.orderandadd([{
            self.typs[i]: self.histos[i]
        } for i in range(len(self.histos))], self.setup)
        #sort
        print histo_dict
        self.histos = [histo_dict[key] for key in self.setup]
        self.typs = self.setup

        c = ROOT.TCanvas(self.var, '', 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        oben = ROOT.TPad('oben', 'oben', 0, 0.3, 1.0, 1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        unten = ROOT.TPad('unten', 'unten', 0, 0.0, 1.0, 0.3)
        unten.SetTopMargin(0.)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var, '')
        l = ROOT.TLegend(0.45, 0.6, 0.75, 0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        l.SetTextSize(0.035)
        l_2 = ROOT.TLegend(0.68, 0.6, 0.92, 0.92)
        l_2.SetLineWidth(2)
        l_2.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetFillStyle(4000)
        l_2.SetTextFont(62)
        l_2.SetTextSize(0.035)
        MC_integral = 0
        MC_entries = 0

        for histo in self.histos:
            MC_integral += histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m" % MC_integral

        #ORDER AND ADD TOGETHER

        if not 'DYc' in self.typs:
            self.typLegendDict.update({'DYlight': self.typLegendDict['DYlc']})
        print self.typLegendDict

        k = len(self.histos)

        for j in range(0, k):
            #print histos[j].GetBinContent(1)
            i = k - j - 1
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])

        d1 = ROOT.TH1F('noData', 'noData', self.nBins, self.xMin, self.xMax)
        datatitle = 'Data'
        addFlag = ''
        if 'Zee' in self.datanames and 'Zmm' in self.datanames:
            addFlag = 'Z(l^{-}l^{+})H(b#bar{b})'
        elif 'Zee' in self.datanames:
            addFlag = 'Z(e^{-}e^{+})H(b#bar{b})'
        elif 'Zmm' in self.datanames:
            addFlag = 'Z(#mu^{-}#mu^{+})H(b#bar{b})'
        elif 'Znn' in self.datanames:
            addFlag = 'Z(#nu#nu)H(b#bar{b})'
        elif 'Wmn' in self.datanames:
            addFlag = 'W(#mu#nu)H(b#bar{b})'
        elif 'Wen' in self.datanames:
            addFlag = 'W(e#nu)H(b#bar{b})'
        elif 'Wtn' in self.datanames:
            addFlag = 'W(#tau#nu)H(b#bar{b})'

        for i in range(0, len(self.datas)):
            print self.datas[i]
            d1.Add(self.datas[i], 1)
        print "\033[1;32m\n\tDATA integral = %s\033[1;m" % d1.Integral()
        flow = d1.GetEntries() - d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m" % flow

        if self.overlay and not isinstance(self.overlay, list):
            self.overlay = [self.overlay]
        if self.overlay:
            for _overlay in self.overlay:
                _overlay.SetLineColor(int(self.colorDict[_overlay.GetName()]))
                _overlay.SetLineWidth(2)
                _overlay.SetFillColor(0)
                _overlay.SetFillStyle(4000)

        numLegend = 2 + k
        if self.overlay:
            numLegend += len(self.overlay)
        l.AddEntry(d1, datatitle, 'P')
        for j in range(0, k):
            if j < numLegend / 2. - 1:
                l.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]],
                           'F')
            else:
                l_2.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]],
                             'F')
        if self.overlay:
            for _overlay in self.overlay:
                l_2.AddEntry(_overlay, self.typLegendDict[_overlay.GetName()],
                             'L')

        if self.normalize:
            if MC_integral != 0: stackscale = d1.Integral() / MC_integral
            if self.overlay:
                for _overlay in self.overlay:
                    _overlay.Scale(stackscale)
            stackhists = allStack.GetHists()
            for blabla in stackhists:
                if MC_integral != 0: blabla.Scale(stackscale)

        allMC = allStack.GetStack().Last().Clone()

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle('')
        #yTitle = 's/(s+b) weighted entries'
        if not d1.GetSumOfWeights() % 1 == 0.0:
            yTitle = 'S/(S+B) weighted entries'
        else:
            yTitle = 'Entries'
        if not '/' in yTitle:
            if 'GeV' in self.xAxis:
                yAppend = '%.0f' % (allStack.GetXaxis().GetBinWidth(1))
            else:
                yAppend = '%.2f' % (allStack.GetXaxis().GetBinWidth(1))
            yTitle = '%s / %s' % (yTitle, yAppend)
            if 'GeV' in self.xAxis:
                yTitle += ' GeV'
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin, self.xMax)
        allStack.GetYaxis().SetRangeUser(0, 20000)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray + 3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw('SAME2')
        l_2.AddEntry(theErrorGraph, "MC uncert. (stat.)", "fl")
        Ymax = max(allStack.GetMaximum(), d1.GetMaximum()) * 1.7
        if self.log:
            allStack.SetMinimum(0.1)
            Ymax = Ymax * ROOT.TMath.Power(
                10, 1.2 *
                (ROOT.TMath.Log(1.2 *
                                (Ymax / 0.1)) / ROOT.TMath.Log(10))) * (0.2 *
                                                                        0.1)
            #Ymax = Ymax*ROOT.TMath.Power(10,1.3*(ROOT.TMath.Log(1.3*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.3*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1, 1)
        l.SetFillColor(0)
        l.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetBorderSize(0)

        if self.overlay:
            for _overlay in self.overlay:
                _overlay.Draw('hist,same')
        d1.Draw("E,same")
        l.Draw()
        l_2.Draw()

        tPrel = self.myText("CMS", 0.17, 0.88, 1.04)
        if not d1.GetSumOfWeights() % 1 == 0.0:
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" % ('7TeV',
                                                      (float(5000.) / 1000.)),
                0.17, 0.83)
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" %
                (self.anaTag, (float(self.lumi) / 1000.)), 0.17, 0.78)
        else:
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" %
                (self.anaTag, (float(self.lumi) / 1000.)), 0.17, 0.83)
        tAddFlag = self.myText(addFlag, 0.17, 0.78)
        print 'Add Flag %s' % self.addFlag2
        if self.addFlag2:
            tAddFlag2 = self.myText(self.addFlag2, 0.17, 0.73)

        unten.cd()
        ROOT.gPad.SetTicks(1, 1)

        l2 = ROOT.TLegend(0.39, 0.85, 0.93, 0.97)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextSize(0.075)
        l2.SetNColumns(2)

        ratio, error = getRatio(d1, allMC, self.xMin, self.xMax, "",
                                self.maxRatioUncert)
        ksScore = d1.KolmogorovTest(allMC)
        chiScore = d1.Chi2Test(allMC, "UWCHI2/NDF")
        print ksScore
        print chiScore
        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray + 3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus", 0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus", 0.7, 1.3)
            print 'Fit on data'
            d1.Fit(fitData, "R")
            print 'Fit on simulation'
            allMC.Fit(fitMC, "R")

        if not self.AddErrors == None:
            self.AddErrors.SetLineColor(1)
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(3001)
            self.AddErrors.Draw('SAME2')

            l2.AddEntry(self.AddErrors, "MC uncert. (stat. + syst.)", "f")

        l2.AddEntry(ratioError, "MC uncert. (stat.)", "f")

        l2.Draw()

        ratioError.Draw('SAME2')
        ratio.Draw("E1SAME")
        ratio.SetTitle("")
        m_one_line = ROOT.TLine(self.xMin, 1, self.xMax, 1)
        m_one_line.SetLineStyle(ROOT.kSolid)
        m_one_line.Draw("Same")

        if not self.blind:
            #tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
            tKsChi = self.myText(
                "#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}" % (chiScore),
                0.17, 0.895, 1.55)
        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize() * 2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
            t0.DrawTextNDC(0.1059, 0.96, "0")
        if not os.path.exists(self.plotDir):
            os.makedirs(os.path.dirname(self.plotDir))
        name = '%s/%s' % (self.plotDir, self.options['pdfName'])
        c.Print(name)
        #print "DATA INTEGRAL: %s" %d1.Integral(d1.GetNbinsX()-2,d1.GetNbinsX())
        #fOut = ROOT.TFile.Open(name.replace('.pdf','.root'),'RECREATE')
        #for theHist in allStack.GetHists():
        #    if not self.AddErrors == None and not theHist.GetName() in ['ZH','WH','VH']:
        #print theHist.GetNbinsX()
        #print self.AddErrors.GetN()
        #print error.GetNbinsX()
        #        for bin in range(0,theHist.GetNbinsX()):
        #            theRelativeTotalError = self.AddErrors.GetErrorY(bin)
        #            if error.GetBinError(bin+1) > 0.:
        #                theRelativeIncrease = theRelativeTotalError/error.GetBinError(bin+1)
        #            else:
        #                theRelativeIncrease = 1.
        #print 'TheTotalRelativeIncrease is: %.2f' %theRelativeIncrease
        #print 'TheTotalStatError is: %.2f' %error.GetBinError(bin+1)
        #print 'TheTotalError is: %.2f' %theRelativeTotalError
        #            theHist.SetBinError(bin,theHist.GetBinError(bin)*theRelativeIncrease)
        #    theHist.SetDirectory(fOut)
        #    if theHist.GetName() == 'ZH' or theHist.GetName() == 'WH':
        #        theHist.SetName('VH')
        #    theHist.Write()
        #d1.SetName('data_obs')
        #d1.SetDirectory(fOut)
        #d1.Write()
        #fOut.Close()
        self.doCompPlot(allStack, l)
Пример #13
0
    def doPlot(self):
        TdrStyles.tdrStyle()
        histo_dict = HistoMaker.orderandadd(
            [{self.typs[i]: self.histos[i]} for i in range(len(self.histos))], self.setup
        )
        # sort
        print histo_dict
        self.histos = [histo_dict[key] for key in self.setup]
        self.typs = self.setup

        c = ROOT.TCanvas(self.var, "", 600, 600)
        c.SetFillStyle(4000)
        c.SetFrameFillStyle(1000)
        c.SetFrameFillColor(0)

        oben = ROOT.TPad("oben", "oben", 0, 0.3, 1.0, 1.0)
        oben.SetBottomMargin(0)
        oben.SetFillStyle(4000)
        oben.SetFrameFillStyle(1000)
        oben.SetFrameFillColor(0)
        unten = ROOT.TPad("unten", "unten", 0, 0.0, 1.0, 0.3)
        unten.SetTopMargin(0.0)
        unten.SetBottomMargin(0.35)
        unten.SetFillStyle(4000)
        unten.SetFrameFillStyle(1000)
        unten.SetFrameFillColor(0)

        oben.Draw()
        unten.Draw()

        oben.cd()
        allStack = ROOT.THStack(self.var, "")
        l = ROOT.TLegend(0.45, 0.6, 0.75, 0.92)
        l.SetLineWidth(2)
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetFillStyle(4000)
        l.SetTextFont(62)
        l.SetTextSize(0.035)
        l_2 = ROOT.TLegend(0.68, 0.6, 0.92, 0.92)
        l_2.SetLineWidth(2)
        l_2.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetFillStyle(4000)
        l_2.SetTextFont(62)
        l_2.SetTextSize(0.035)
        MC_integral = 0
        MC_entries = 0

        for histo in self.histos:
            MC_integral += histo.Integral()
        print "\033[1;32m\n\tMC integral = %s\033[1;m" % MC_integral

        # ORDER AND ADD TOGETHER

        if not "DYc" in self.typs:
            self.typLegendDict.update({"DYlight": self.typLegendDict["DYlc"]})
        print self.typLegendDict

        k = len(self.histos)

        for j in range(0, k):
            # print histos[j].GetBinContent(1)
            i = k - j - 1
            self.histos[i].SetFillColor(int(self.colorDict[self.typs[i]]))
            self.histos[i].SetLineColor(1)
            allStack.Add(self.histos[i])

        d1 = ROOT.TH1F("noData", "noData", self.nBins, self.xMin, self.xMax)
        datatitle = "Data"
        addFlag = ""
        if "Zee" in self.datanames and "Zmm" in self.datanames:
            addFlag = "Z(l^{-}l^{+})H(b#bar{b})"
        elif "Zee" in self.datanames:
            addFlag = "Z(e^{-}e^{+})H(b#bar{b})"
        elif "Zmm" in self.datanames:
            addFlag = "Z(#mu^{-}#mu^{+})H(b#bar{b})"
        elif "Znn" in self.datanames:
            addFlag = "Z(#nu#nu)H(b#bar{b})"
        elif "Wmn" in self.datanames:
            addFlag = "W(#mu#nu)H(b#bar{b})"
        elif "Wen" in self.datanames:
            addFlag = "W(e#nu)H(b#bar{b})"
        elif "Wtn" in self.datanames:
            addFlag = "W(#tau#nu)H(b#bar{b})"

        for i in range(0, len(self.datas)):
            print self.datas[i]
            d1.Add(self.datas[i], 1)
        print "\033[1;32m\n\tDATA integral = %s\033[1;m" % d1.Integral()
        flow = d1.GetEntries() - d1.Integral()
        if flow > 0:
            print "\033[1;31m\tU/O flow: %s\033[1;m" % flow

        if self.overlay and not isinstance(self.overlay, list):
            self.overlay = [self.overlay]
        if self.overlay:
            for _overlay in self.overlay:
                _overlay.SetLineColor(int(self.colorDict[_overlay.GetName()]))
                _overlay.SetLineWidth(2)
                _overlay.SetFillColor(0)
                _overlay.SetFillStyle(4000)

        numLegend = 2 + k
        if self.overlay:
            numLegend += len(self.overlay)
        l.AddEntry(d1, datatitle, "P")
        for j in range(0, k):
            if j < numLegend / 2.0 - 1:
                l.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]], "F")
            else:
                l_2.AddEntry(self.histos[j], self.typLegendDict[self.typs[j]], "F")
        if self.overlay:
            for _overlay in self.overlay:
                l_2.AddEntry(_overlay, self.typLegendDict[_overlay.GetName()], "L")

        if self.normalize:
            if MC_integral != 0:
                stackscale = d1.Integral() / MC_integral
            if self.overlay:
                for _overlay in self.overlay:
                    _overlay.Scale(stackscale)
            stackhists = allStack.GetHists()
            for blabla in stackhists:
                if MC_integral != 0:
                    blabla.Scale(stackscale)

        allMC = allStack.GetStack().Last().Clone()

        allStack.SetTitle()
        allStack.Draw("hist")
        allStack.GetXaxis().SetTitle("")
        # yTitle = 's/(s+b) weighted entries'
        if not d1.GetSumOfWeights() % 1 == 0.0:
            yTitle = "S/(S+B) weighted entries"
        else:
            yTitle = "Entries"
        if not "/" in yTitle:
            if "GeV" in self.xAxis:
                yAppend = "%.0f" % (allStack.GetXaxis().GetBinWidth(1))
            else:
                yAppend = "%.2f" % (allStack.GetXaxis().GetBinWidth(1))
            yTitle = "%s / %s" % (yTitle, yAppend)
            if "GeV" in self.xAxis:
                yTitle += " GeV"
        allStack.GetYaxis().SetTitle(yTitle)
        allStack.GetXaxis().SetRangeUser(self.xMin, self.xMax)
        allStack.GetYaxis().SetRangeUser(0, 20000)
        theErrorGraph = ROOT.TGraphErrors(allMC)
        theErrorGraph.SetFillColor(ROOT.kGray + 3)
        theErrorGraph.SetFillStyle(3013)
        theErrorGraph.Draw("SAME2")
        l_2.AddEntry(theErrorGraph, "MC uncert. (stat.)", "fl")
        Ymax = max(allStack.GetMaximum(), d1.GetMaximum()) * 1.7
        if self.log:
            allStack.SetMinimum(0.1)
            Ymax = (
                Ymax
                * ROOT.TMath.Power(10, 1.2 * (ROOT.TMath.Log(1.2 * (Ymax / 0.1)) / ROOT.TMath.Log(10)))
                * (0.2 * 0.1)
            )
            # Ymax = Ymax*ROOT.TMath.Power(10,1.3*(ROOT.TMath.Log(1.3*(Ymax/0.1))/ROOT.TMath.Log(10)))*(0.3*0.1)
            ROOT.gPad.SetLogy()
        allStack.SetMaximum(Ymax)
        c.Update()
        ROOT.gPad.SetTicks(1, 1)
        l.SetFillColor(0)
        l.SetBorderSize(0)
        l_2.SetFillColor(0)
        l_2.SetBorderSize(0)

        if self.overlay:
            for _overlay in self.overlay:
                _overlay.Draw("hist,same")
        d1.Draw("E,same")
        l.Draw()
        l_2.Draw()

        tPrel = self.myText("CMS", 0.17, 0.88, 1.04)
        if not d1.GetSumOfWeights() % 1 == 0.0:
            tLumi = self.myText("#sqrt{s} =  %s, L = %.1f fb^{-1}" % ("7TeV", (float(5000.0) / 1000.0)), 0.17, 0.83)
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" % (self.anaTag, (float(self.lumi) / 1000.0)), 0.17, 0.78
            )
        else:
            tLumi = self.myText(
                "#sqrt{s} =  %s, L = %.1f fb^{-1}" % (self.anaTag, (float(self.lumi) / 1000.0)), 0.17, 0.83
            )
        tAddFlag = self.myText(addFlag, 0.17, 0.78)
        print "Add Flag %s" % self.addFlag2
        if self.addFlag2:
            tAddFlag2 = self.myText(self.addFlag2, 0.17, 0.73)

        unten.cd()
        ROOT.gPad.SetTicks(1, 1)

        l2 = ROOT.TLegend(0.39, 0.85, 0.93, 0.97)
        l2.SetLineWidth(2)
        l2.SetBorderSize(0)
        l2.SetFillColor(0)
        l2.SetFillStyle(4000)
        l2.SetTextSize(0.075)
        l2.SetNColumns(2)

        ratio, error = getRatio(d1, allMC, self.xMin, self.xMax, "", self.maxRatioUncert)
        ksScore = d1.KolmogorovTest(allMC)
        chiScore = d1.Chi2Test(allMC, "UWCHI2/NDF")
        print ksScore
        print chiScore
        ratio.SetStats(0)
        ratio.GetXaxis().SetTitle(self.xAxis)
        ratioError = ROOT.TGraphErrors(error)
        ratioError.SetFillColor(ROOT.kGray + 3)
        ratioError.SetFillStyle(3013)
        ratio.Draw("E1")
        if self.doFit:
            fitData = ROOT.TF1("fData", "gaus", 0.7, 1.3)
            fitMC = ROOT.TF1("fMC", "gaus", 0.7, 1.3)
            print "Fit on data"
            d1.Fit(fitData, "R")
            print "Fit on simulation"
            allMC.Fit(fitMC, "R")

        if not self.AddErrors == None:
            self.AddErrors.SetLineColor(1)
            self.AddErrors.SetFillColor(5)
            self.AddErrors.SetFillStyle(3001)
            self.AddErrors.Draw("SAME2")

            l2.AddEntry(self.AddErrors, "MC uncert. (stat. + syst.)", "f")

        l2.AddEntry(ratioError, "MC uncert. (stat.)", "f")

        l2.Draw()

        ratioError.Draw("SAME2")
        ratio.Draw("E1SAME")
        ratio.SetTitle("")
        m_one_line = ROOT.TLine(self.xMin, 1, self.xMax, 1)
        m_one_line.SetLineStyle(ROOT.kSolid)
        m_one_line.Draw("Same")

        if not self.blind:
            # tKsChi = self.myText("#chi_{#nu}^{2} = %.3f K_{s} = %.3f"%(chiScore,ksScore),0.17,0.9,1.5)
            tKsChi = self.myText("#chi^{2}_{ }#lower[0.1]{/^{}#it{dof} = %.2f}" % (chiScore), 0.17, 0.895, 1.55)
        t0 = ROOT.TText()
        t0.SetTextSize(ROOT.gStyle.GetLabelSize() * 2.4)
        t0.SetTextFont(ROOT.gStyle.GetLabelFont())
        if not self.log:
            t0.DrawTextNDC(0.1059, 0.96, "0")
        if not os.path.exists(self.plotDir):
            os.makedirs(os.path.dirname(self.plotDir))
        name = "%s/%s" % (self.plotDir, self.options["pdfName"])
        c.Print(name)
        # print "DATA INTEGRAL: %s" %d1.Integral(d1.GetNbinsX()-2,d1.GetNbinsX())
        # fOut = ROOT.TFile.Open(name.replace('.pdf','.root'),'RECREATE')
        # for theHist in allStack.GetHists():
        #    if not self.AddErrors == None and not theHist.GetName() in ['ZH','WH','VH']:
        # print theHist.GetNbinsX()
        # print self.AddErrors.GetN()
        # print error.GetNbinsX()
        #        for bin in range(0,theHist.GetNbinsX()):
        #            theRelativeTotalError = self.AddErrors.GetErrorY(bin)
        #            if error.GetBinError(bin+1) > 0.:
        #                theRelativeIncrease = theRelativeTotalError/error.GetBinError(bin+1)
        #            else:
        #                theRelativeIncrease = 1.
        # print 'TheTotalRelativeIncrease is: %.2f' %theRelativeIncrease
        # print 'TheTotalStatError is: %.2f' %error.GetBinError(bin+1)
        # print 'TheTotalError is: %.2f' %theRelativeTotalError
        #            theHist.SetBinError(bin,theHist.GetBinError(bin)*theRelativeIncrease)
        #    theHist.SetDirectory(fOut)
        #    if theHist.GetName() == 'ZH' or theHist.GetName() == 'WH':
        #        theHist.SetName('VH')
        #    theHist.Write()
        # d1.SetName('data_obs')
        # d1.SetDirectory(fOut)
        # d1.Write()
        # fOut.Close()
        self.doCompPlot(allStack, l)