def banner(self, isData, lumi):
     
      latex = TLatex()
      latex.SetNDC();                         
      latex.SetTextAngle(0);                  
      latex.SetTextColor(r.kBlack);           
      latex.SetTextFont(42);                  
      latex.SetTextAlign(31);                 
      latex.SetTextSize(0.06);                
      latex.DrawLatex(0.25, 0.93, "#bf{CMS}") 
               
      latexb = TLatex()                      
      latexb.SetNDC();
      latexb.SetTextAngle(0);
      latexb.SetTextColor(r.kBlack);
      latexb.SetTextFont(42);
      latexb.SetTextAlign(31);
      latexb.SetTextSize(0.04);            

      if(isData):
         latexb.DrawLatex(0.44, 0.93, "#it{Preliminary}")
      else:
         latexb.DrawLatex(0.44, 0.93, "#it{Simulation}")

      if lumi != '':      
          text_lumi = str(lumi)+" fb^{-1}  (13 TeV)"
          latexc = TLatex()
          latexc.SetNDC();
          latexc.SetTextAngle(0);
          latexc.SetTextColor(r.kBlack);
          latexc.SetTextFont(42);
          latexc.SetTextAlign(31);
          latexc.SetTextSize(0.04);
          latexc.DrawLatex(0.90, 0.93, text_lumi)                
Beispiel #2
0
    def banner3(self, isData, lumi):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.07)
        latex.DrawLatex(0.1, 1.22, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.05)

        #if(isData):
        #  latexb.DrawLatex(0.34, 1.22, "#it{Preliminary}")
        #else:
        #  latexb.DrawLatex(0.34, 1.22, "#it{Simulation}")

        text_lumi = str(lumi) + " fb^{-1} (13 TeV)"
        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.05)
Beispiel #3
0
def plot_phase_space(can, histos, keyword, output_prefix):
    """ Docstring. """

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)

    can.Clear()
    can.Divide(2,2)

    can.cd(1)
    histos['data']['histos_p_ele_theta_ele_'+keyword+'_CTOF'].Draw('colz')
    latex.DrawLatex(0.3, 0.92, 'Data (proton in CTOF)')
    
    can.cd(2)
    histos['data']['histos_p_ele_theta_ele_'+keyword+'_FTOF'].Draw('colz')
    latex.DrawLatex(0.3, 0.92, 'Data (proton in FTOF)')
    
    can.cd(3)
    histos['sim']['histos_p_ele_theta_ele_'+keyword+'_CTOF'].Draw('colz')
    latex.DrawLatex(0.3, 0.92, 'Sim (proton in CTOF)')
    
    can.cd(4)
    histos['sim']['histos_p_ele_theta_ele_'+keyword+'_FTOF'].Draw('colz')
    latex.DrawLatex(0.3, 0.92, 'Sim (proton in FTOF)')

    for ican in range(1, 5):
        can.cd(ican)
        latex.DrawLatex(0.45, 0.02, 'p_{e} (GeV)')
        latex.SetTextAngle(90.0)
        latex.DrawLatex(0.03, 0.45, '#theta_{e} (Deg.)')
        latex.SetTextAngle(0.0)
            
    can.Print('phase_space_' + keyword + '_' + output_prefix + '.pdf')
    can.Clear()
Beispiel #4
0
    def banner2(self, isData, lumi, scy=False):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.06)
        latex.DrawLatex(0.23, 0.93, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.04)

        #if(isData):
        latexb.DrawLatex(0.38, 0.93, "#it{Preliminary}")
        #else:
        #  latexb.DrawLatex(0.38, 0.93, "#it{Simulation}")

        text_lumi = str(lumi) + " fb^{-1} (13 TeV)"
        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.05)
        if lumi != '': latexc.DrawLatex(0.90, 0.93, text_lumi)
def plot_sector_page(canvas, histos1, histos2, config1, config2, title_formatter,
                     save_name, xtitle=None, ytitle=None, title=None, x_range=None):
    """ Compare two distributions in one plot, using root. """
    
    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.045)
    
    canvas.Clear()
    canvas.Divide(3,2)

    for i in range(1,7):
        canvas.cd(i)

        #_, __, values1, errors1 = numpify(histos1.get(title_formatter.format(i), default_histo))
        #_, __, values2, errors2 = numpify(histos2.get(title_formatter.format(i), default_histo))

        #scale = np.sum(values1 * values2) / np.sum(values2**2)
        
        histos1.get(title_formatter.format(i), default_histo).SetLineColor(1)
        histos1.get(title_formatter.format(i), default_histo).Scale(1 / histos1.get(title_formatter.format(i), default_histo).GetMaximum())
        
        histos2.get(title_formatter.format(i), default_histo).SetLineColor(99)
        histos2.get(title_formatter.format(i), default_histo).Scale(1 / histos2.get(title_formatter.format(i), default_histo).GetMaximum())
        #histos2.get(title_formatter.format(i), default_histo).Scale(scale)

        hmax = max(histos1.get(title_formatter.format(i), default_histo).GetMaximum(),
                   histos2.get(title_formatter.format(i), default_histo).GetMaximum())
        
        histos1.get(title_formatter.format(i), default_histo).SetMaximum(hmax * 1.1)
        histos2.get(title_formatter.format(i), default_histo).SetMaximum(hmax * 1.1)

        if x_range:
            histos1.get(title_formatter.format(i), default_histo).GetXaxis().SetRangeUser(x_range[0], x_range[1])
            histos2.get(title_formatter.format(i), default_histo).GetXaxis().SetRangeUser(x_range[0], x_range[1])
        
        histos1.get(title_formatter.format(i), default_histo).Draw('hist')
        histos2.get(title_formatter.format(i), default_histo).Draw('histsame')

        # Annotate the figure with the configuration names.
        caption1 = '#color[1]({0})'.format(config1).replace('(', '{').replace(')', '}')
        caption2 = '#color[99]({0})'.format(config2).replace('(', '{').replace(')', '}')

        label.DrawLatex(0.75, 0.86, caption1)
        label.DrawLatex(0.75, 0.825, caption2)
        
        if title:
            label.DrawLatex(0.1, 0.925, title)

        if xtitle:
            label.DrawLatex(0.45, 0.015, xtitle)

        if ytitle:
            label.SetTextAngle(90)
            label.DrawLatex(0.02, 0.65, ytitle)
            label.SetTextAngle(0)

    canvas.Print(save_name)
def plot_sector_page_single(canvas,
                            histos,
                            title_formatter,
                            save_name,
                            xtitle=None,
                            ytitle=None,
                            title=None,
                            x_range=None,
                            log=False,
                            hline=None):
    """ Plot one histogram for each sector. """

    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.045)

    canvas.Clear()
    canvas.Divide(3, 2)

    root_garbage_can = []
    for i in range(1, 7):
        canvas.cd(i)

        if x_range:
            histos.get(title_formatter.format(i),
                       default_histo2d).GetXaxis().SetRangeUser(
                           x_range[0], x_range[1])

        histos.get(title_formatter.format(i), default_histo2d).Draw('colz')
        if log:
            gPad.SetLogz()

        if title:
            label.DrawLatex(0.1, 0.925, title)

        if xtitle:
            label.DrawLatex(0.45, 0.015, xtitle)

        if ytitle:
            label.SetTextAngle(90)
            label.DrawLatex(0.0325, 0.65, ytitle)
            label.SetTextAngle(0)

        if hline:
            xmin = histos.get(title_formatter.format(i)).GetXaxis().GetXmin()
            xmax = histos.get(title_formatter.format(i)).GetXaxis().GetXmax()
            line = TLine(xmin, hline, xmax, hline)
            line.SetLineColor(1)
            line.SetLineStyle(1)
            line.Draw('same')
            root_garbage_can.append(line)

    canvas.Print(save_name)
Beispiel #7
0
    def banner(self, isData, lumi, scy, inProgress=False):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.06)
        if not scy:
            latex.DrawLatex(0.25, 0.93, "#bf{CMS}")
        else:
            latex.DrawLatex(0.34, 0.93, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.04)

        if (isData):
            if not scy:
                latexb.DrawLatex(0.43, 0.93, "#it{Preliminary}")
            else:
                latexb.DrawLatex(0.52, 0.93, "#it{Preliminary}")
        else:
            if not inProgress:
                if not scy:
                    latexb.DrawLatex(0.43, 0.93, "#it{Simulation}")
                else:
                    latexb.DrawLatex(0.52, 0.93, "#it{Simulation}")
            else:
                if not scy:
                    latexb.DrawLatex(0.54, 0.93, "#it{Work in progress}")
                else:
                    latexb.DrawLatex(0.63, 0.93, "#it{Work in progress}")

        text_lumi = ''
        #if isData:
        #    text_lumi = str(lumi)+" fb^{-1}  (13 TeV)"
        if lumi: text_lumi = str(lumi) + " fb^{-1}  (13 TeV)"

        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.04)
        latexc.DrawLatex(0.90, 0.93, text_lumi)
    def bannerRatio(self, isData, lumi, scy=False, inProgress=False):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.068)

        if not scy:
            latex.DrawLatex(0.23, 0.88, "#bf{CMS}")
        else:
            latex.DrawLatex(0.30, 0.88, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.045)

        if (isData):
            if not scy:
                latexb.DrawLatex(0.39, 0.88, "#it{Preliminary}")
            else:
                latexb.DrawLatex(0.46, 0.88, "#it{Preliminary}")
        else:
            if not inProgress:
                if not scy:
                    latexb.DrawLatex(0.37, 0.88, "#it{Simulation}")
                else:
                    latexb.DrawLatex(0.44, 0.88, "#it{Simulation}")
            else:
                if not scy:
                    latexb.DrawLatex(0.37, 0.88, "#it{Work in progress}")
                else:
                    latexb.DrawLatex(0.44, 0.88, "#it{Work in progress}")

        text_lumi = str(lumi) + " fb^{-1} (13 TeV)"
        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.05)
        if lumi != '': latexc.DrawLatex(0.90, 0.88, text_lumi)
Beispiel #9
0
def setUpPalette(histo2D, plot) :

    # Configure Palette for 2D Histos

    minX = 1.03*histo2D.GetXaxis().GetXmin();
    maxX = 1.03*histo2D.GetXaxis().GetXmax();
    minY = 1.03*histo2D.GetYaxis().GetXmin();
    maxY = 1.03*histo2D.GetYaxis().GetXmax();

    palette = histo2D.GetListOfFunctions().FindObject("palette")
    if palette:
        palette.__class__ = TPaletteAxis
        palette.SetX1NDC(0.945)
        palette.SetY1NDC(gPad.GetBottomMargin())
        palette.SetX2NDC(0.96)
        palette.SetY2NDC(1-gPad.GetTopMargin())
        palette.GetAxis().SetTickSize(.01)
        palette.GetAxis().SetTitle("")
        if plots[plot].zLog:
            palette.GetAxis().SetLabelOffset(-0.01)
            if histo2D.GetMaximum()/histo2D.GetMinimum() < 1e3 :
                palette.GetAxis().SetMoreLogLabels(True)
                palette.GetAxis().SetNoExponent(True)

    paletteTitle = TLatex(1.12*maxX, maxY, plots[plot].quotaName)
    paletteTitle.SetTextAngle(90.)
    paletteTitle.SetTextSize(0.05)
    paletteTitle.SetTextAlign(31)
    paletteTitle.Draw()

    histo2D.GetXaxis().SetTickLength(histo2D.GetXaxis().GetTickLength()/4.)
    histo2D.GetYaxis().SetTickLength(histo2D.GetYaxis().GetTickLength()/4.)
    histo2D.SetTitleOffset(0.5,'Y')
    histo2D.GetXaxis().SetNoExponent(True)
    histo2D.GetYaxis().SetNoExponent(True)
Beispiel #10
0
def drawCMSHeader( pad, lumi_text, extra_text ):

    pad.cd()

    top_margin = pad.GetTopMargin();
    header_offset = top_margin * 0.2

    left_margin = pad.GetLeftMargin();
    header = TLatex( left_margin, 1 + header_offset * top_margin, 'CMS' )
    header.SetNDC()
    header.SetTextAngle( 0 )
    header.SetTextColor( ROOT.kBlack )
    header.SetTextFont( 61 )
    header.SetTextAlign( 11 )
    cmsLabelSize = top_margin * 0.8
    header.SetTextSize( cmsLabelSize )
    cms_x_position = header.GetXsize()
    header.DrawLatex( left_margin, 1 - top_margin + header_offset, 'CMS' )


    extra_text_size = cmsLabelSize * 0.76
    header.SetTextFont( 52 )
    header.SetTextSize( extra_text_size )
    header.DrawLatex( left_margin + 1.2 * cms_x_position, 1 - top_margin + header_offset, extra_text )
    

    lumi_text_size = top_margin * 0.6
    header.SetTextFont(42);
    header.SetTextAlign(31);
    header.SetTextSize( lumi_text_size )
    right_margin = pad.GetRightMargin();
    header.DrawLatex( 1. - right_margin, 1. - top_margin + header_offset, lumi_text )
Beispiel #11
0
def drawCMS2(myC, energy, lumi):

	myC.cd()

        tlatex = TLatex()
        baseSize = 25
        tlatex.SetNDC()
        tlatex.SetTextAngle(0)
        tlatex.SetTextColor(1)
        tlatex.SetTextFont(63)
        tlatex.SetTextAlign(11)
        tlatex.SetTextSize(25)
        tlatex.DrawLatex(0.16, 0.95, "CMS")
        tlatex.SetTextFont(53)
        tlatex.DrawLatex(0.23, 0.95, "Preliminary")
        tlatex.SetTextFont(43)
        tlatex.SetTextSize(23)
	lumiString = "%.2f" % lumi
        Lumi = "" + lumiString + " pb^{-1} ("+str(energy)+" TeV)"
        if lumi > 1000:
		lumiString = "%.2f" % (lumi/1000.0)
                Lumi = "" + lumiString + " fb^{-1} ("+str(energy)+" TeV)"
        tlatex.SetTextAlign(31)
        tlatex.DrawLatex(0.9, 0.95, Lumi)
        tlatex.SetTextAlign(11)
Beispiel #12
0
def drawCMS3_supp(myC, energy, lumi):
        myC.cd()

        tlatex = TLatex()
        baseSize = 25
        tlatex.SetNDC()
        tlatex.SetTextAngle(0)
        tlatex.SetTextColor(1)
        tlatex.SetTextFont(61)
        tlatex.SetTextAlign(11)
        tlatex.SetTextSize(0.0375)
        tlatex.DrawLatex(0.18, 0.96, "CMS")
        tlatex.SetTextFont(52)
        tlatex.SetTextSize(0.0285)
        tlatex.DrawLatex(0.26, 0.96, "Supplementary")
        tlatex.SetTextFont(43)
        tlatex.SetTextSize(23)
        lumiString = "%.1f" % lumi
        Lumi = "" + lumiString + " pb^{-1} ("+str(energy)+" TeV)"
        if lumi > 1000:
                lumiString = "%.1f" % (lumi/1000.0)
                Lumi = "" + lumiString + " fb^{-1} ("+str(energy)+" TeV)"
        tlatex.SetTextAlign(31)
        tlatex.DrawLatex(0.85, 0.96, Lumi)
        tlatex.SetTextAlign(11)
Beispiel #13
0
def draw_disclaimer():
    # disclaimer
    t = TLatex()
    t.SetNDC()
    t.SetTextSize(0.1)
    t.SetTextAlign(22)
    t.SetTextAngle(45)
    t.DrawText(0.5, 0.5, "FAKE VALUES")
def makeLabel(label_text, xposition, yposition, taglias):
    label = TLatex(xposition, yposition, label_text)
    #label.SetNDC()
    label.SetTextAlign(21)
    label.SetTextFont(42)
    label.SetTextColor(ROOT.kBlack)
    label.SetTextSize(taglias)
    label.SetTextAngle(0)
    return label
Beispiel #15
0
def drawOverflow():
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextAngle(90)
    latex.SetTextSize(0.03)
    #latex.SetTextColor(1)
    latex.SetTextFont(42)
    #latex.SetTextAlign(33)
    latex.DrawLatex(0.97, 0.02, "Overflow")
Beispiel #16
0
 def drawAnnotation(self):
     from ROOT import TLatex
     latex = TLatex()
     latex.SetTextSize(float(self.__config.get("styleDefaults","annotationSize")))
     latex.SetTextColor(int(self.__config.get("styleDefaults","annotationColor")))
     if self.__config.has_option("styleDefaults","annotationAngle"):
         latex.SetTextAngle(float(self.__config.get("styleDefaults","annotationAngle")))
     for label in self.__labels:
         latex.DrawLatex(*label)
Beispiel #17
0
def makeLabel(label_text):

    label = TLatex(0.65, 0.62, label_text)
    label.SetNDC()
    label.SetTextAlign(21)
    label.SetTextFont(42)
    label.SetTextColor(ROOT.kBlack)
    label.SetTextSize(0.04)
    label.SetTextAngle(0)
    return label
Beispiel #18
0
 def addAxis(self, canvas, chanindex, chanlist, runlist, lboffset, lbtot):
     from ROOT import TLatex
     txt = TLatex()
     txt.SetNDC()
     txt.SetTextAngle(90.)
     txt.SetTextSize(0.012)
     for chan in chanlist:
         txt.DrawLatex(
             0.11 + 0.8 * float(chanindex[chan]) / (len(chanindex) + 1),
             0.06, self.namelookup.name(chan))
     txt.SetTextAngle(0.)
     txt.SetTextSize(0.02)
     ndiv = 1 + len(lboffset) / 20
     j = 0
     for run in runlist:
         lb = lboffset[run]
         j += 1
         if (j == ndiv):
             txt.DrawLatex(0.91, 0.11 + 0.8 * float(lb) / lbtot, str(run))
             j = 0
Beispiel #19
0
 def gen_line_90(x, ymin, ymax, text):
     from ROOT import TLine, TLatex
     ymax = 1.05 * ymax
     l = TLine(x, ymin, x, ymax)
     l.SetLineStyle(2)
     l.Draw()
     txt = TLatex()
     txt.SetTextFont(12)
     txt.SetTextAngle(90)
     txt.SetTextSize(0.04)
     txt.DrawLatex(x - 1, (ymax - ymin) / 2., text)
     return l, txt
Beispiel #20
0
 def draw(self, canvas=None):
     if canvas is None:
         canvas = self
     canvas.Divide(1, 2)
     canvas.cd(1).SetMargin(0.1, 0.1, 0.05, 0.2)
     self._rad.Draw()
     canvas.cd(2).SetMargin(0.1, 0.1, 0.2, 0.05)
     self._ang.Draw()
     canvas.cd()
     canvas.Update()
     for c, axis in [('r', self._rad.GetXaxis()),
                     ('y1', self._rad.GetYaxis()),
                     ('p', self._ang.GetXaxis()),
                     ('y2', self._ang.GetYaxis())]:
         axis.SetLabelSize(0.05)
         axis.SetTitleSize(0.07)
         axis.SetLabelOffset(0.01)
         rng = getattr(self, '_{0}range'.format(c))
         if rng is not None:
             axis.SetRangeUser(rng[0], rng[1])
         ttl = getattr(self, '_{0}title'.format(c))
         if c.startswith('y') and ttl is not None:
             axis.SetTitle(ttl)
         if c.startswith('y'):
             axis.SetTitleOffset(0.6)
             axis.SetNdivisions(505)
     canvas.cd()
     self._pad = TPad('newpad', '', 0, 0, 1, 1)
     self._pad.SetFillStyle(4000)
     self._pad.Draw()
     self._pad.cd()
     if self._drawCMS:
         self.draw_cms()
     text = TLatex()
     text.SetNDC()
     text.SetTextFont(42)
     text.SetTextSize(0.035)
     text.SetTextAlign(13)
     text.SetTextAngle(90)
     if self._rtitle is not None:
         text.DrawLatexNDC(0.905, 0.54, self._rtitle)
     if self._ptitle is not None:
         text.DrawLatexNDC(0.905, 0.115, self._ptitle)
     for obj in self._container_draw:
         obj.Draw('SAME')
     for c in (canvas.cd(1), canvas.cd(2), canvas):
         c.Modified()
         c.Update()
     canvas.cd()
Beispiel #21
0
    def draw(self, yLabelSize=0.055):

        self.multigraph.SetMinimum(self.ylow)
        self.multigraph.SetMaximum(self.yhigh)
        self.multigraph.Draw(self.drawOption)

        self.multigraph.GetXaxis().SetNdivisions(405)
        self.multigraph.GetYaxis().SetNdivisions(405)

        self.multigraph.GetXaxis().SetLimits(self.xlow, self.xhigh)
        #self.multigraph.GetYaxis().SetTitle("")

        self.multigraph.GetYaxis().SetLabelSize(yLabelSize)
        self.multigraph.GetXaxis().SetLabelSize(yLabelSize)

        latex = TLatex()
        latex.SetNDC()
        #latex.SetTextSize(0.04)
        latex.SetTextSize(yLabelSize)
        latex.SetTextAlign(31)  # align right

        latex.DrawLatex(0.95, 0.01, self.xlabel)

        latex.SetTextAngle(90)

        latex.DrawLatex(0.03, 0.9, self.ylabel)

        self.legend.SetFillStyle(0)
        self.legend.SetBorderSize(0)
        #self.legend.SetTextSize(0.04)
        #self.legend.SetTextSize(yLabelSize)
        self.legend.SetTextSize(yLabelSize * 0.7)
        self.legend.SetTextFont(42)
        self.legend.SetTextAlign(11)
        self.legend.Draw()

        return self.multigraph
Beispiel #22
0
def AddText(txt_x=0.50, txt_y=0.50, txt="dummy", txt_size=0.045, txt_angle=0, Alignment="left", UseNormalizedSize=1, txt_color=1):
	txt_align=12

	if Alignment == "left":
		txt_align = 12
	if Alignment == "right":
		txt_align = 32
	if Alignment == "center":
		txt_align = 22

	t1 = TLatex(txt_x, txt_y, txt ) 
	
	if UseNormalizedSize: 
		t1.SetNDC(kTRUE)

	#canvas.cd()
	
	t1.SetTextSize(txt_size)
	t1.SetTextAlign(txt_align)
	t1.SetTextAngle(txt_angle)
	t1.SetTextColor(txt_color)
	t1.Draw()

	return
extraText = "Preliminary"
extraTextFont = 52
extraOverCmsTextSize = 0.76

relPosX = 0.045
relPosY = 0.035
relExtraDY = 1.2

alignY_ = 3
alignX_ = 1
align_ = 10 * alignX_ + alignY_
cv.cd()
latex = TLatex()
latex.SetNDC()
latex.SetTextAngle(0)
latex.SetTextColor(1)

latex.SetTextFont(42)
latex.SetTextAlign(31)
latex.SetTextSize(lumiTextSize * t)

posX_ = 0
posY_ = 1 - t - relPosY * (1 - t - b)
latex.SetTextFont(cmsTextFont)
latex.SetTextSize(0.8 * cmsTextSize * t)
latex.SetTextAlign(align_)

extraTextSize = extraOverCmsTextSize * cmsTextSize
latex.SetTextFont(extraTextFont)
latex.SetTextAlign(align_)
Beispiel #24
0
def createCompoundPlots(detector, plot, geometry):
    """Produce the requested plot for the specified detector.

       Function that will plot the requested @plot for the specified
       @detector. The specified detector could either be a real
       detector or a compound one. The list of available plots are the
       keys of plots dictionary (imported from plot_utils.

    """
    setTDRStyle()
    
    theDirname = 'Images'
    if not checkFile_(theDirname):
        os.mkdir(theDirname)

    goodToGo, theDetectorFilename = paramsGood_(detector, plot, geometry)
    if not goodToGo:
        return

    hist_X0_elements = OrderedDict()

    # stack
    stackTitle = "%s;%s;%s" % (detector,
                                               plots[plot].abscissa,
                                               plots[plot].ordinate)
    stack_X0 = THStack("stack_X0", stackTitle);
    theLegend = TLegend(0.50, 0.70, 0.70, 0.90);

    def setRanges(h):
        legendSpace = 1. + 0.3 # 30%
        minY = h.GetYaxis().GetXmin()
        maxY = h.GetBinContent(h.GetMaximumBin()) * legendSpace
        h.GetYaxis().SetRangeUser(minY, maxY)

    for label, [num, color, leg] in six.iteritems(hist_label_to_num):
        # We don't want the sum to be added as part of the stack
        if label is 'SUM':
            continue
        hist_X0_elements[label] = get1DHisto_(detector,
                                              num + plots[plot].plotNumber,
                                              geometry)
        hist_X0_elements[label].SetFillColor(color)
        hist_X0_elements[label].SetLineColor(kBlack)
        stack_X0.Add(hist_X0_elements[label])
        if hist_X0_elements[label].Integral() > 0.: theLegend.AddEntry(hist_X0_elements[label], leg, "f")

    # canvas
    canname = "MBCan_1D_%s_%s"  % (detector, plot)
    can = TCanvas(canname, canname, 800, 800)
    can.Range(0,0,25,25)
    gStyle.SetOptTitle(0)

    # Draw
    setRanges(stack_X0.GetStack().Last())
    stack_X0.Draw("HIST");
    stack_X0.GetXaxis().SetLabelSize(0.035)
    stack_X0.GetYaxis().SetLabelSize(0.035)
    theLegend.Draw();

    cmsMark = TLatex()
    cmsMark.SetNDC();
    cmsMark.SetTextAngle(0);
    cmsMark.SetTextColor(kBlack);    
    cmsMark.SetTextFont(61)
    cmsMark.SetTextSize(5e-2)
    cmsMark.SetTextAlign(11)
    cmsMark.DrawLatex(0.16,0.86,"CMS")

    simuMark = TLatex()
    simuMark.SetNDC();
    simuMark.SetTextAngle(0);
    simuMark.SetTextColor(kBlack);    
    simuMark.SetTextSize(3e-2)
    simuMark.SetTextAlign(11)
    simuMark.DrawLatex(0.16,0.82,"#font[52]{Simulation Internal}")
 
    # Store
    can.Update();
    can.SaveAs( "%s/%s_%s_%s.pdf" 
                % (theDirname, detector, plot, geometry))
    can.SaveAs( "%s/%s_%s_%s.png" 
                % (theDirname, detector, plot, geometry))
Beispiel #25
0
def showme(figure, data, theory, ratio, X, Y, YB):
    """A function to draw and and theory as well as their ratio. S.Chekanov
   @param  figure Figure file
   @param: data   Histogram with data 
   @param: theory Histogram with theory
   @param: ratio  TGraph or Histogram with for bottom plot
   @param: X      X-axis attributes (Min,Max,Name,IsLog) 
   @param: Y      Y-axis attributes (Min,Max,Name,IsLog)  
   @param: YB     Bottom (lower) panel attributes (Min,Max,Name,IsLog)  
   @author S.Chekanov (ANL)
  """

    if (X[0] > X[1]):
        print("X min larger than X max")
        return
    if (Y[0] > Y[1]):
        print("X min larger than X mas")
        return
    if (YB[0] > YB[1]):
        print("X min larger than X mas")
        return

    inp = "plot"
    if (len(sys.argv) == 2):
        inp = sys.argv[1]
    print "Mode=", inp

    c1 = TCanvas("cv", "", 600, 500)
    c1.Divide()
    c1.SetTickx()
    c1.SetTicky()
    gROOT.SetStyle("Plain")
    gStyle.SetOptStat(0)

    cv1 = TPad("cv_a", "", 0.0, 0.20, 1.0, 1.0)
    cv1.SetTickx()
    cv1.SetTicky()
    cv1.SetTopMargin(0.05)
    cv1.SetBottomMargin(0.001)
    cv1.SetLeftMargin(0.12)
    cv1.SetRightMargin(0.05)
    cv1.Draw()
    cv2 = TPad("cv_b", "", 0.0, 0.0, 1.0, 0.275)
    cv2.SetTopMargin(0.0)
    cv2.SetTickx()
    cv2.SetTicky()
    cv2.SetLeftMargin(0.12)
    cv2.SetRightMargin(0.05)
    cv2.SetBottomMargin(0.35)
    cv2.Draw()

    if (Y[3] == 1): cv1.cd().SetLogy()
    if (X[3] == 1): cv1.cd().SetLogx()
    if (YB[3] == 1): cv2.cd().SetLogy()

    h1 = gPad.DrawFrame(X[0], Y[0], X[1], Y[1])
    h1.Draw()
    ay = h1.GetYaxis()
    ay.SetTitleOffset(1.1)
    ay.SetTitle(Y[2])

    data.Draw("same pe")
    theory.Draw("histo same")

    #########################################
    #cv2.cd().SetGridy()
    cv2.cd().SetGridx()
    h2 = gPad.DrawFrame(X[0], YB[0], X[1], YB[1])
    h2.Draw()
    ax = h2.GetXaxis()
    ax.SetTitleOffset(0.8)
    ax.SetTitle(X[2])
    ax.SetLabelSize(0.12)
    ax.SetTitleSize(0.14)
    ay = h2.GetYaxis()
    #ay.SetTitle("OOOO" )
    ay.SetNdivisions(505)
    ay.SetLabelSize(0.12)
    ay.SetTitleSize(0.14)
    ax.SetTitleOffset(1.1)
    ay.SetTitleOffset(0.0)
    ax.Draw("same")
    ay.Draw("same")

    ratio.SetMarkerColor(1)
    ratio.SetMarkerStyle(20)
    ratio.SetMarkerSize(1.0)
    ratio.SetMarkerColor(2)

    # plot depending on style
    if (type(ratio) == TGraphErrors or type(ratio) == TGraph
            or type(ratio) == TGraphAsymmErrors):
        ratio.Draw("P same")
    elif (type(ratio) == TH1F or type(ratio) == TH1D):
        ratio.SetFillColor(2)
        ratio.SetLineWidth(1)
        ratio.SetLineColor(1)
        ratio.Draw("same histo ][")
    else:
        ratio.Draw("P same")

    l1 = TLatex()
    l1.SetTextAngle(90)
    l1.SetTextSize(0.12)
    l1.SetNDC()
    l1.SetTextColor(1)
    l1.DrawLatex(0.06, 0.5, YB[2])

    # draw line
    x1 = c1.XtoPad(X[0])
    x2 = c1.XtoPad(X[1])
    ar5 = TLine(x1, 0, x2, 0)
    ar5.SetLineWidth(2)
    ar5.SetLineStyle(2)
    ar5.Draw("same")

    c1.Print(figure)

    if (inp != "-b"):
        if (raw_input("Press any key to exit") != "-9999"):
            c1.Close()
            sys.exit(1)
Beispiel #26
0
def create2DPlots(detector, plot, plotnum, plotmat, dosingledetector=True):
    """Produce the requested plot for the specified detector.

       Function that will plot the requested 2D-@plot for the
       specified @detector. The specified detector could either be a
       real detector or a compound one. The list of available plots
       are the keys of plots dictionary imported from plot_utils.
    """

    #gStyle.Reset()
    #Better to use an underscore.
    plotmat = plotmat.replace(" ", "_")

    if plotmat != "":
        theDirname = ('Images/%s' % plotmat).replace(" ", "")
    else:
        theDirname = 'Images'

    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    if not os.path.isdir(('Images/%s/ZPlusZoom' % plotmat).replace(" ", "")):
        os.mkdir(('Images/%s/ZPlusZoom' % plotmat).replace(" ", ""))
    if not os.path.isdir(('Images/%s/ZMinusZoom' % plotmat).replace(" ", "")):
        os.mkdir(('Images/%s/ZMinusZoom' % plotmat).replace(" ", ""))

    goodToGo, theDetectorFilename = paramsGood_(detector, plot)
    if not goodToGo:
        return

    theDetectorFile = TFile(theDetectorFilename)

    prof2d_X0_det_total = TProfile2D()
    prof2d_X0_det_total.Reset()

    # get TProfiles
    #prof2d_X0_det_total = theDetectorFile.Get('%s' % plots[plot].plotNumber)
    prof2d_X0_det_total = theDetectorFile.Get('%s' % plotnum)
    print "=================================================================="
    print plotnum

    # histos
    prof2d_X0_det_total.__class__ = TProfile2D
    hist_X0_total = prof2d_X0_det_total.ProjectionXY()

    # keep files live forever
    files = []
    if detector in COMPOUNDS.keys() and not dosingledetector:
        #When the loop was:
        #for subDetector in COMPOUNDS[detector][1:]:
        #and the detector was single it never went in the loop and read the single file
        #from above. I alter this to COMPOUNDS[detector] to do the multi material budget plot.
        #This won't effect the single detector due to the alter in the if above
        for subDetector in COMPOUNDS[detector]:
            # filenames of single components
            subDetectorFilename = "matbdg_%s.root" % subDetector

            # open file
            if not checkFile_(subDetectorFilename):
                print("Error, missing file %s" % subDetectorFilename)
                continue

            subDetectorFile = TFile(subDetectorFilename)
            files.append(subDetectorFile)
            print("*** Open file... %s" % subDetectorFilename)

            # subdetector profiles
            prof2d_X0_det_total = subDetectorFile.Get('%s' %
                                                      plots[plot].plotNumber)
            prof2d_X0_det_total.__class__ = TProfile2D

            # add to summary histogram
            hist_X0_total.Add(
                prof2d_X0_det_total.ProjectionXY(
                    "B_%s" % prof2d_X0_det_total.GetName()), +1.000)

    # # properties
    #gStyle.SetPalette(1)
    gStyle.SetStripDecimals(False)
    # #

    # Create "null" histo
    minX = 1.03 * prof2d_X0_det_total.GetXaxis().GetXmin()
    maxX = 1.03 * prof2d_X0_det_total.GetXaxis().GetXmax()
    minY = 1.03 * prof2d_X0_det_total.GetYaxis().GetXmin()
    maxY = 1.03 * prof2d_X0_det_total.GetYaxis().GetXmax()

    frame = TH2F("frame", "", 10, minX, maxX, 10, minY, maxY)
    frame.SetMinimum(0.1)
    frame.SetMaximum(10.)
    frame.GetXaxis().SetTickLength(frame.GetXaxis().GetTickLength() * 0.50)
    frame.GetYaxis().SetTickLength(frame.GetXaxis().GetTickLength() / 4.)

    # Ratio
    if plots[plot].iRebin:
        prof2d_X0_det_total.Rebin2D()

    # stack
    hist2dTitle = ('%s %s;%s;%s;%s' %
                   (plots[plot].quotaName, detector, plots[plot].abscissa,
                    plots[plot].ordinate, plots[plot].quotaName))

    if dosingledetector:
        hist2d_X0_total = prof2d_X0_det_total
    else:
        hist2d_X0_total = hist_X0_total
    hist2d_X0_total.SetTitle(hist2dTitle)
    frame.SetTitle(hist2dTitle)
    frame.SetTitleOffset(0.5, "Y")

    #If here you put different histomin,histomaxin plot_utils you won't see anything
    #for the material plots.
    if plots[plot].histoMin != -1.:
        hist2d_X0_total.SetMinimum(plots[plot].histoMin)
    if plots[plot].histoMax != -1.:
        hist2d_X0_total.SetMaximum(plots[plot].histoMax)

    #
    can2name = "MBCan_2D_%s_%s_%s" % (detector, plot, plotmat)
    can2 = TCanvas(can2name, can2name, 2480 + 248, 580 + 58 + 58)
    can2.SetTopMargin(0.1)
    can2.SetBottomMargin(0.1)
    can2.SetLeftMargin(0.04)
    can2.SetRightMargin(0.06)
    can2.SetFillColor(kWhite)
    gStyle.SetOptStat(0)
    gStyle.SetTitleFillColor(0)
    gStyle.SetTitleBorderSize(0)

    #hist2d_X0_total.SetMaximum(hist2d_X0_total.GetMaximum())
    # Color palette
    # gStyle.SetPalette()#1
    acustompalette()
    ex1 = TExec("ex1", "acustompalette();")
    ex1.Draw()

    #for i in range(100): MyPaletteArray.append(i+1)

    #gStyle.SetPalette(first_color_number);

    # Log?
    can2.SetLogz(plots[plot].zLog)

    # Draw in colors
    #frame.Draw()
    #hist2d_X0_total.Draw("COLZsame") #Dummy draw to create the palette object
    hist2d_X0_total.Draw("COLZ")  #Dummy draw to create the palette object

    # Store
    can2.Update()

    #Aesthetic
    palette = hist2d_X0_total.GetListOfFunctions().FindObject("palette")
    if palette:
        palette.__class__ = TPaletteAxis
        palette.SetX1NDC(0.945)
        palette.SetX2NDC(0.96)
        palette.SetY1NDC(0.1)
        palette.SetY2NDC(0.9)
        palette.GetAxis().SetTickSize(.01)
        palette.GetAxis().SetTitle("")
        if plots[plot].zLog:
            palette.GetAxis().SetLabelOffset(-0.01)
    paletteTitle = TLatex(1.12 * maxX, maxY, plots[plot].quotaName)
    paletteTitle.SetTextAngle(90.)
    paletteTitle.SetTextSize(0.05)
    paletteTitle.SetTextAlign(31)
    paletteTitle.Draw()
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.SetTitleOffset(0.5, "Y")
    hist2d_X0_total.GetYaxis().SetTitleOffset(0.45)
    #hist2d_X0_total.GetXaxis().SetTitleOffset(1.15);
    #hist2d_X0_total.GetXaxis().SetNoExponent(True)
    #hist2d_X0_total.GetYaxis().SetNoExponent(True)

    #Add eta labels
    keep_alive = []
    if plots[plot].iDrawEta:
        keep_alive.extend(drawEtaValues())

    can2.Modified()
    hist2d_X0_total.SetContour(255)

    # Store
    can2.Update()
    can2.Modified()

    can2.SaveAs("%s/%s_%s%s.pdf" % (theDirname, detector, plot, plotmat))
    can2.SaveAs("%s/%s_%s%s.png" % (theDirname, detector, plot, plotmat))
    #can2.SaveAs( "%s/%s_%s%s.root" % (theDirname, detector, plot, plotmat))

    #Zoom in a little bit
    if plot == "x_vs_z_vs_Rsum" or plot == "l_vs_z_vs_Rsum" or plot == "x_vs_z_vs_Rsumcos" or plot == "l_vs_z_vs_Rsumcos" or plot == "x_vs_z_vs_Rloc" or plot == "l_vs_z_vs_Rloc" or plot == "x_vs_z_vs_Rloccos" or plot == "l_vs_z_vs_Rloccos":
        #Z+
        #hist2d_X0_total.GetXaxis().SetLimits( 3100., 5200.)
        if dosingledetector:
            hist2d_X0_total.GetXaxis().SetRangeUser(3100., 5400.)
        else:
            hist2d_X0_total.GetXaxis().SetRangeUser(0., 7000.)
        #Do not draw eta values in the zoom case
        keep_alive = []
        #hist2d_X0_total.Draw("COLZ")
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s/%s_%s%s_ZplusZoom.pdf" %
                    (theDirname, "ZPlusZoom", detector, plot, plotmat))
        can2.SaveAs("%s/%s/%s_%s%s_ZplusZoom.png" %
                    (theDirname, "ZPlusZoom", detector, plot, plotmat))
        #Z-
        #hist2d_X0_total.GetXaxis().SetLimits( 3100., 5200.)
        if dosingledetector:
            hist2d_X0_total.GetXaxis().SetRangeUser(-5400., -3100.)
        else:
            hist2d_X0_total.GetXaxis().SetRangeUser(0., -7000.)
        #Do not draw eta values in the zoom case
        keep_alive = []
        #hist2d_X0_total.Draw("COLZ")
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s/%s_%s%s_ZminusZoom.pdf" %
                    (theDirname, "ZMinusZoom", detector, plot, plotmat))
        can2.SaveAs("%s/%s/%s_%s%s_ZminusZoom.png" %
                    (theDirname, "ZMinusZoom", detector, plot, plotmat))

    gStyle.SetStripDecimals(True)
Beispiel #27
0
def setCMSLumiStyle(pad, iPosX, **kwargs):
    global outOfFrame, lumiTextSize, lumiText
    if iPosX / 10 == 0:
        outOfFrame = True
    lumiTextSize_ = lumiTextSize
    relPosX_ = kwargs.get('relPosX', relPosX)
    lumiText_ = kwargs.get('lumiText', lumiText)
    if outOfFrame:
        lumiTextSize_ *= 0.90

    if 'era' in kwargs:  # one era
        era = kwargs.get('era')
        setCMSEra(era, **kwargs)
    elif 'eras' in kwargs:  # list of multiple eras
        eras = kwargs.get('eras')
        setCMSEra(*eras, **kwargs)

    #if lumiText=="":
    #  if iPeriod==1:
    #    lumiText += lumi_7TeV
    #    lumiText += " (7 TeV)"
    #  elif iPeriod==2:
    #    lumiText += lumi_8TeV
    #    lumiText += " (8 TeV)"
    #  elif iPeriod==3:
    #    lumiText = lumi_8TeV
    #    lumiText += " (8 TeV)"
    #    lumiText += " + "
    #    lumiText += lumi_7TeV
    #    lumiText += " (7 TeV)"
    #  elif iPeriod==4:
    #    lumiText += lumi_13TeV
    #    lumiText += " (13 TeV)"
    #  elif iPeriod==7:
    #    if outOfFrame: lumiTextSize_ *= 0.85
    #    lumiText += lumi_13TeV
    #    lumiText += " (13 TeV)"
    #    lumiText += " + "
    #    lumiText += lumi_8TeV
    #    lumiText += " (8 TeV)"
    #    lumiText += " + "
    #    lumiText += lumi_7TeV
    #    lumiText += " (7 TeV)"
    #  elif iPeriod==12:
    #    lumiText += "8 TeV"
    #  else:
    #    if outOfFrame: lumiTextSize_ *= 0.90
    #    if iPeriod==13:
    #      lumiText += lumi_13TeV
    #      lumiText += " (13 TeV)"
    #    elif iPeriod==2016:
    #      lumiText += lumi_2016
    #      lumiText += " (13 TeV)"
    #    elif iPeriod==2017:
    #      lumiText += lumi_2017
    #      lumiText += " (13 TeV)"
    #    elif iPeriod==2018:
    #      lumiText += lumi_2018
    #      lumiText += " (13 TeV)"
    #    elif iPeriod==14:
    #      lumiText += lumi_14TeV
    #      lumiText += " (14 TeV, 200 PU)"
    ##print lumiText

    alignY_ = 3
    alignX_ = 2
    if iPosX == 0: alignY_ = 1
    if iPosX / 10 == 0: alignX_ = 1
    elif iPosX / 10 == 1: alignX_ = 1
    elif iPosX / 10 == 2: alignX_ = 2
    elif iPosX / 10 == 3: alignX_ = 3
    align = 10 * alignX_ + alignY_
    extraTextSize = extraOverCmsTextSize * cmsTextSize

    H = pad.GetWh() * pad.GetHNDC()
    W = pad.GetWw() * pad.GetWNDC()
    l = pad.GetLeftMargin()
    t = pad.GetTopMargin()
    r = pad.GetRightMargin()
    b = pad.GetBottomMargin()
    e = 0.025
    scale = float(H) / W if W > H else 1  # float(W)/H
    pad.cd()

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextAngle(0)
    latex.SetTextColor(kBlack)
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(lumiTextSize_ * t)

    if lumiText_:
        latex.DrawLatex(1 - r, 1 - t + lumiTextOffset * t, lumiText_)

    if iPosX == 0:
        relPosX_ = relPosX_ * (50 * t * scale) * (cmsTextSize / 0.84)
        posX = l + relPosX_ * (1 - l - r)
        posY = 1 - t + lumiTextOffset * t
    else:
        posX = 0
        posY = 1 - t - relPosY * (1 - t - b)
        if iPosX % 10 <= 1:
            posX = l + relPosX_ * (1 - l - r)  # left aligned
        elif iPosX % 10 == 2:
            posX = l + 0.5 * (1 - l - r)  # centered
        elif iPosX % 10 == 3:
            posX = 1 - r - relPosX_ * (1 - l - r)  # right aligned

    if outOfFrame:
        TGaxis.SetExponentOffset(-0.12 * float(H) / W, 0.015, 'y')
        latex.SetTextFont(cmsTextFont)
        latex.SetTextAlign(11)
        latex.SetTextSize(cmsTextSize * t)
        latex.DrawLatex(l, 1 - t + lumiTextOffset * t, cmsText)
        if writeExtraText:
            latex.SetTextFont(extraTextFont)
            latex.SetTextSize(extraTextSize * t)
            latex.SetTextAlign(align)
            latex.DrawLatex(posX, posY, extraText)
    elif drawLogo:
        posX = l + 0.045 * (1 - l - r) * W / H
        posY = 1 - t - 0.045 * (1 - t - b)
        xl_0 = posX
        yl_0 = posY - 0.15
        xl_1 = posX + 0.15 * H / W
        yl_1 = posY
        CMS_logo = TASImage("CMS-BW-label.png")
        pad_logo = TPad("logo", "logo", xl_0, yl_0, xl_1, yl_1)
        pad_logo.Draw()
        pad_logo.cd()
        CMS_logo.Draw('X')
        pad_logo.Modified()
        pad.cd()
    else:
        latex.SetTextFont(cmsTextFont)
        latex.SetTextSize(cmsTextSize * t)
        latex.SetTextAlign(align)
        latex.DrawLatex(posX, posY, cmsText)
        if writeExtraText:
            latex.SetTextFont(extraTextFont)
            latex.SetTextAlign(align)
            latex.SetTextSize(extraTextSize * t)
            latex.DrawLatex(posX, posY - relExtraDY * cmsTextSize * t,
                            extraText)

    pad.Update()
Beispiel #28
0
def makePosteriorPlot(infile,
                      outfile = 'posterior.png',
                      mass = 1000,
                      label_size = 0.05,
                      xlabel = "", ylabel = "",
                      xLegend = .65, yLegend = .30,
                      legendWidth = 0.30, legendHeight = 0.35,
                      fillStyle = 3395,
                      drawOption = 'APL3'):

    _legend = '[makePosteriorPlot()]:'

    gROOT.SetStyle('Plain')

    tf = TFile(infile, 'read')
    c1 = tf.Get('c1')

    _h = c1.GetListOfPrimitives().First()#Get('MCMCposterior_hist')
    _h2 = c1.GetListOfPrimitives().At(1)#Get('MCMCposterior_hist')

    _h.GetXaxis().SetRangeUser(0,0.5)
    _h2.GetXaxis().SetRangeUser(0,0.5)

    _h.SetFillStyle(1001)
    _h.SetFillColor(ROOT.kYellow-9)

    c = TCanvas("c", "c", 600, 400)
    c.SetFrameLineWidth(1)
    c.SetRightMargin(0.05)
    c.cd()

    c.SetFrameFillColor(19)
    #c.SetFrameBorderMode(0)
    c.SetTickx(1)
    c.SetTicky(1)
    
    ROOT.gPad.SetLogy(setlogscale)

    _h.Draw()
    _h2.Draw('same')

    #CmsPrel(40.0, 0.89, 0.90)
    #CmsPrel(0.89, 0.90)

    latex = TLatex()
    latex.SetNDC()
    #latex.SetTextAlign(31) # align right
    latex.SetTextAlign(5) # align left
    latex.SetTextSize(0.055)
    latex.DrawLatex(0.30, 0.70, "#font[62]{Combined #mu^{+}#mu^{-} and e^{+}e^{-}} channels")
    latex.DrawLatex(0.30, 0.60, "#font[62]{M=}"+'%g'%mass+"GeV")

    #c.Draw()

    # axes labels
    _h.GetXaxis().SetTitle('')
    _h.GetYaxis().SetTitle('')
    _h.GetXaxis().SetNdivisions(407)
    _h.GetYaxis().SetNdivisions(405)
    _h.GetYaxis().SetLabelSize(label_size)
    _h.GetXaxis().SetLabelSize(label_size)
    latex.SetTextSize(label_size)
    latex.SetTextAlign(31) # align right
    latex.DrawLatex(0.93,0.02, xlabel)
    latex.SetTextAngle(90)
    latex.DrawLatex(0.05,0.95, ylabel)


    c.Modified()
    #c.GetListOfPrimitives().Print()
    c.RedrawAxis()

    c.SaveAs(outfile)
Beispiel #29
0
    def show(self, outDir):
        if len(self.mc) == 0:
            print '%s has no MC!' % self.name
            return

        htype = self.mc[0].ClassName()
        if htype.find('TH2') >= 0:
            print 'Skipping TH2'
            return

        ROOT.gStyle.SetOptTitle(0)
        ROOT.gStyle.SetOptStat(0)
        ROOT.gROOT.SetBatch(1)

        canvas = TCanvas('c_' + self.name, 'C', 800, 800)
        canvas.cd()
        t1 = TPad("t1", "t1", 0.0, 0.20, 1.0, 1.0)
        t1.SetBottomMargin(0)
        t1.Draw()
        t1.cd()
        self._garbageList.append(t1)

        frame = None
        # Decide which backgrounds are visible
        maxint = max([x.Integral() for x in self.mc])
        hists_to_add = [h for h in self.mc if h.Integral() > 0.005 * maxint]

        # Make the legend with the correct size
        leg = TLegend(0.75, 0.74 - 0.04 * max(len(hists_to_add) - 2, 0), .89,
                      0.89)
        leg.SetBorderSize(0)
        leg.SetFillStyle(0)
        leg.SetTextFont(43)
        leg.SetTextSize(20)
        nlegCols = 0

        maxY = 1.0
        if self.data is not None:
            leg.AddEntry(self.data, self.data.GetTitle(), 'p')
            frame = self.dataH.Clone('frame')
            self._garbageList.append(frame)
            maxY = self.dataH.GetMaximum()
            frame.Reset('ICE')
        elif self.dataH is not None:
            leg.AddEntry(self.dataH, self.dataH.GetTitle(), 'p')
            frame = self.dataH.Clone('frame')
            self._garbageList.append(frame)
            maxY = self.dataH.GetMaximum()
            frame.Reset('ICE')

        # Add the legend entries for the visible backgrounds
        for h in sorted(hists_to_add, key=lambda x: x.Integral(),
                        reverse=True):
            leg.AddEntry(h, h.GetTitle(), 'f')
            nlegCols = nlegCols + 1

        # Build the stack to plot from all backgrounds
        totalMC = None
        stack = THStack('mc', 'mc')
        for h in sorted(self.mc, key=lambda x: x.Integral()):
            stack.Add(h, 'hist')
            if totalMC is None:
                totalMC = h.Clone('totalmc')
                self._garbageList.append(totalMC)
                totalMC.SetDirectory(0)
            else:
                totalMC.Add(h)

        if totalMC is not None:
            maxY = max(totalMC.GetMaximum(), maxY)
            if frame is None:
                frame = totalMC.Clone('frame')
                frame.Reset('ICE')
                self._garbageList.append(frame)

        if self.data is not None or self.dataH is not None:
            nlegCols = nlegCols + 1
        if nlegCols == 0:
            print '%s is empty' % self.name
            return

        frame.GetYaxis().SetTitleSize(0.045)
        frame.GetYaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetRangeUser(0.5, 1.2 * maxY)
        frame.GetYaxis().SetNoExponent()
        frame.SetDirectory(0)
        frame.Draw()
        frame.GetYaxis().SetTitleOffset(1.6)
        stack.Draw('hist same')
        if self.data is not None:
            self.data.Draw('P')
        elif self.dataH is not None:
            self.dataH.Draw('e1same')

        # leg.SetNColumns(nlegCols)
        leg.Draw()
        # redrawBorder(t1)

        ## Draw CMS Preliminary label
        CMS_lumi(pad=t1, iPeriod=2, iPosX=0, extraText='')  #Work in Progress')

        if self.normalizedToData:
            txt = TLatex()
            txt.SetNDC(True)
            txt.SetTextFont(42)
            txt.SetTextColor(ROOT.kGray + 1)
            txt.SetTextSize(0.035)
            txt.SetTextAngle(90)
            txt.SetTextAlign(12)
            txt.DrawLatex(0.05, 0.05, '#it{Normalized to data}')

        if totalMC is None or (self.data is None and self.dataH is None):
            t1.SetPad(0, 0, 1, 1)
            t1.SetBottomMargin(0.12)
        else:
            canvas.cd()
            t2 = TPad("t2", "t2", 0.0, 0.0, 1.0, 0.2)
            self._garbageList.append(t2)
            t2.SetTopMargin(0)
            t2.SetBottomMargin(0.4)
            t2.SetGridy()
            t2.Draw()
            t2.cd()

            ratioframe = self.dataH.Clone('ratioframe')
            ratioframe.Reset('ICE')
            ratioframe.Draw()
            ratioframe.GetYaxis().SetRangeUser(self.ratiorange[0],
                                               self.ratiorange[1])
            ratioframe.GetYaxis().SetTitle('Obs./Exp.')
            ratioframe.GetYaxis().SetNdivisions(5)
            ratioframe.GetYaxis().SetLabelSize(0.15)
            ratioframe.GetXaxis().SetLabelSize(0.15)
            ratioframe.GetYaxis().SetTitleSize(0.18)
            ratioframe.GetXaxis().SetLabelSize(0.18)
            ratioframe.GetXaxis().SetTitleSize(0.18)
            ratioframe.GetYaxis().SetTitleOffset(0.4)
            ratioframe.GetXaxis().SetTitleOffset(0.9)

            gr = ROOT.TGraphAsymmErrors()
            gr.SetName("data2bkg")
            gr.SetMarkerStyle(self.dataH.GetMarkerStyle())
            gr.SetMarkerSize(0.7 * self.dataH.GetMarkerSize())
            gr.SetMarkerColor(self.dataH.GetMarkerColor())
            gr.SetLineColor(self.dataH.GetLineColor())
            gr.SetLineWidth(self.dataH.GetLineWidth())
            bkgUncGr = ROOT.TGraphErrors()
            bkgUncGr.SetName('bkgunc')
            bkgUncGr.SetMarkerColor(920)
            bkgUncGr.SetMarkerStyle(1)
            bkgUncGr.SetLineColor(920)
            bkgUncGr.SetFillColor(920)
            bkgUncGr.SetFillStyle(3001)
            for xbin in xrange(1, self.dataH.GetXaxis().GetNbins() + 1):
                x = self.dataH.GetXaxis().GetBinCenter(xbin)
                dx = self.dataH.GetXaxis().GetBinWidth(xbin)
                dataCts = self.dataH.GetBinContent(xbin)
                if self.data:
                    data_err_low = self.data.GetErrorYlow(
                        xbin - 1)  #get errors from the graph
                    data_err_up = self.data.GetErrorYhigh(xbin - 1)
                else:
                    data_err_low = self.dataH.GetBinError(xbin)
                    data_err_up = data_err_low
                bkgCts = totalMC.GetBinContent(xbin)
                bkgCts_err = totalMC.GetBinError(xbin)
                if bkgCts == 0: continue
                errLo = math.sqrt(
                    math.pow(data_err_low * bkgCts, 2) +
                    math.pow(dataCts * bkgCts_err, 2)) / math.pow(bkgCts, 2)
                errHi = math.sqrt(
                    math.pow(data_err_up * bkgCts, 2) +
                    math.pow(dataCts * bkgCts_err, 2)) / math.pow(bkgCts, 2)
                np = gr.GetN()
                gr.SetPoint(np, x, dataCts / bkgCts)
                gr.SetPointError(np, 0, 0, errLo, errHi)
                bkgUncGr.SetPoint(np, x, 1)
                bkgUncGr.SetPointError(np, dx, bkgCts_err / bkgCts)
            bkgUncGr.Draw('2')
            gr.Draw('p')
            # redrawBorder(t2)

        canvas.cd()
        canvas.Modified()
        canvas.Update()

        for ext in self.plotformats:
            canvas.SaveAs(os.path.join(outDir, self.name + '.' + ext))
        if self.savelog:
            t1.cd()
            t1.SetLogy()
            frame.GetYaxis().SetRangeUser(70, 2 * maxY)
            # frame.GetYaxis().SetRangeUser(1000,10*maxY)
            canvas.cd()
            for ext in self.plotformats:
                canvas.SaveAs(os.path.join(outDir, self.name + '_log.' + ext))
Beispiel #30
0
def plot_map(out_file_path, hist):
    map_name = out_file_path if '/' not in out_file_path else out_file_path.split(
        '/')[-1]
    map_name = map_name.replace('.pdf', '')
    rho_min = -6.0
    rho_max = -2.6
    pt_min = 500.
    pt_max = 1200.
    # rho_min = -10
    # rho_max = 0
    # pt_min = 200
    # pt_max = 5000
    disc_min = 0.12
    disc_max = 0.3
    left_margin = 0.14
    right_margin = 0.16
    top_margin = 0.08
    bottom_margin = 0.12

    gStyle.SetPadTickY(1)
    gStyle.SetPadTickX(1)
    gStyle.SetLegendBorderSize(0)

    gROOT.SetBatch(True)
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(0)
    gStyle.SetTitleOffset(0.86, "X")
    gStyle.SetTitleOffset(1.6, "Y")
    gStyle.SetPadLeftMargin(left_margin)
    gStyle.SetPadBottomMargin(bottom_margin)
    gStyle.SetPadTopMargin(top_margin)
    gStyle.SetPadRightMargin(right_margin)

    gStyle.SetMarkerSize(0.5)
    gStyle.SetHistLineWidth(1)
    gStyle.SetTitleSize(0.05, "XYZ")
    gStyle.SetLabelSize(0.04, "XYZ")
    gStyle.SetNdivisions(506, "XYZ")
    gStyle.SetNumberContours(25)
    gStyle.SetLegendBorderSize(0)

    hist.GetXaxis().SetTitle("#rho")
    hist.GetYaxis().SetTitle("p_{T} [GeV]")
    if ('n2' in map_name.lower()):
        hist.GetZaxis().SetTitle("N2^{DDT} X% quantile")
    else:
        hist.GetZaxis().SetTitle("DeepBoosted WvsQCD X% quantile")
        disc_max = 1
    hist.GetXaxis().SetRangeUser(rho_min, rho_max)
    hist.GetYaxis().SetRangeUser(pt_min, pt_max)
    # if(disc_max>hist.GetMaximum()):
    #     hist.GetZaxis().SetRangeUser(disc_min, disc_max)

    Font = 43
    TitleSize = 24.0
    TitleOffset = 1.3
    LabelSize = 18.0
    hist.GetYaxis().SetTitleFont(Font)
    hist.GetYaxis().SetTitleSize(TitleSize)
    hist.GetYaxis().SetTitleOffset(TitleOffset)
    hist.GetYaxis().SetLabelFont(Font)
    hist.GetYaxis().SetLabelSize(LabelSize)

    hist.GetXaxis().SetTitleFont(Font)
    hist.GetXaxis().SetTitleSize(TitleSize)
    hist.GetXaxis().SetTitleOffset(TitleOffset)
    hist.GetXaxis().SetLabelFont(Font)
    hist.GetXaxis().SetLabelSize(LabelSize)

    hist.GetZaxis().SetTitleFont(Font)
    hist.GetZaxis().SetTitleSize(TitleSize)
    hist.GetZaxis().SetTitleOffset(TitleOffset)
    hist.GetZaxis().SetLabelFont(Font)
    hist.GetZaxis().SetLabelSize(LabelSize)

    # hist.GetZaxis().SetNdivisions(20)

    hist.SetTitle(map_name.replace('_', ' '))
    hist.SetTitleFont(43)
    hist.SetTitleSize(18.0)

    # isomasses = [20,55,80,120,200]
    # isomasses = [20,65,80,125,200]
    # isomasses = range(40,200,20)
    isomasses = [40, 80, 110, 120, 200]
    str_isomass = "%.2f*TMath::Exp(-x/2)"
    tf1_isomasses = []
    for i in range(len(isomasses)):
        msd = isomasses[i]
        new_isomass = TF1('isomass_%i' % int(msd), str_isomass % msd, rho_min,
                          rho_max)
        # new_isomass.SetLineColor(920+i)
        new_isomass.SetLineColorAlpha(1, 0.4)
        tf1_isomasses.append(new_isomass)

    c1 = TCanvas("c1", "c1", 700, 600)
    c1.cd()
    hist.Draw("colz")
    latex_border = TLatex()
    latex_border.SetNDC(1)
    latex_border.SetTextColor(1)
    latex_border.SetTextFont(43)
    latex_border.SetTextSize(15.5)
    latex_border.SetTextAngle(297)
    latex = TLatex()
    latex.SetNDC(1)
    latex.SetTextColor(920)
    latex.SetTextFont(43)
    latex.SetTextSize(15)
    # latex.SetTextAngle(297)
    for i in range(len(isomasses)):
        x_pitch = (1 - left_margin - right_margin) / (rho_max - rho_min)
        y_pitch = (1 - bottom_margin - top_margin) / (pt_max - pt_min)
        msd = isomasses[i]
        pt = msd * np.exp(-rho_min / 2)
        pt = 800 if pt > pt_max else pt
        angle = ((180 / np.pi) * np.arctan(2 * x_pitch / (pt * y_pitch))) + 272
        latex.SetTextAngle(angle)
        latex_border.SetTextAngle(angle)
        tf1_isomass = tf1_isomasses[i]
        tf1_isomass.Draw('SAME')
        x_pos = left_margin + (
            (2 * np.log(msd / pt) - rho_min)) * x_pitch + 0.01
        y_pos = bottom_margin + (pt - pt_min) * y_pitch + 0.01
        latex_border.DrawLatex(x_pos, y_pos, 'm_{SD} = %.1f GeV' % msd)
        # latex.DrawLatex(x_pos,y_pos,'m_{SD} = %.1f GeV'%msd)
    c1.SaveAs(out_file_path + ".pdf")
    c1.SaveAs(out_file_path + ".png")
    c1.SaveAs(out_file_path + ".C")
    del c1