예제 #1
0
def make_pdf_with_sixTH2Fs(h2_ntightleps_vs_ntotleps,
                           h2_ntightandIsoleps_vs_ntotleps,
                           h2_ntightleps_vs_ntotleps_perc,
                           h2_ntightandIsoleps_vs_ntotleps_perc,
                           h2_norm_ntightleps_vs_ntotleps_perc,
                           h2_norm_ntightandIsoleps_vs_ntotleps_perc):
    """Make a PDF with all 6 two-D hists.

    Args:
        h2_ntightleps_vs_ntotleps (ROOT.TH2): First TH2.
        h2_ntightandIsoleps_vs_ntotleps (ROOT.TH2): [description]
        h2_ntightleps_vs_ntotleps_perc (ROOT.TH2): [description]
        h2_ntightandIsoleps_vs_ntotleps_perc (ROOT.TH2): [description]
        h2_norm_ntightleps_vs_ntotleps_perc (ROOT.TH2): [description]
        h2_norm_ntightandIsoleps_vs_ntotleps_perc (ROOT.TH2): [description]
    """
    markersize = 0.8  # 0.1, 0.01
    style = setTDRStyle()
    style.cd()
    style.SetPadRightMargin(0.15)

    canv = TCanvas()
    gStyle.SetOptStat(0)

    canv.Print(outpdf_path + "[")
    for h in (h2_ntightleps_vs_ntotleps, h2_ntightandIsoleps_vs_ntotleps):
        gStyle.SetPaintTextFormat(".2g")
        h.UseCurrentStyle()
        h.SetMarkerSize(markersize)
        h.GetZaxis().SetRangeUser(0, 5.5E6)
        h.Draw("colz text")
        pave = make_pave_with_stats(h, xmin=0.15, ymin=0.8, xmax=0.4, ymax=0.9)
        pave.Draw("same")
        canv.Print(outpdf_path)

    for h in (h2_ntightleps_vs_ntotleps_perc,
              h2_ntightandIsoleps_vs_ntotleps_perc):
        gStyle.SetPaintTextFormat(".2g%%")
        h.SetMarkerSize(markersize)
        h.GetZaxis().SetRangeUser(0, 85.0)
        h.Draw("colz text")
        pave = make_pave_with_stats(h, xmin=0.15, ymin=0.8, xmax=0.4, ymax=0.9)
        pave.Draw("same")
        canv.Print(outpdf_path)

    for h in (h2_norm_ntightleps_vs_ntotleps_perc,
              h2_norm_ntightandIsoleps_vs_ntotleps_perc):
        gStyle.SetPaintTextFormat(".2g%%")
        h.SetMarkerSize(markersize)
        h.GetZaxis().SetRangeUser(0, 100.0)
        h.Draw("colz text")
        pave = make_pave_with_stats(h, xmin=0.15, ymin=0.8, xmax=0.4, ymax=0.9)
        pave.Draw("same")
        canv.Print(outpdf_path)
    canv.Print(outpdf_path + "]")
예제 #2
0
def plot2D(year, tagger, wp, tipo = 'B'):
  c = TCanvas('c', 'c', 10, 10, 1600, 1200)
  fname = path[year]
  if isinstance(year, int): year = "%i"%year
  hnameN = "BtagSF%s_%s%s_%s"%(tipo, tagger, wp, year);
  hnameD = "BtagSF%s_%s%s_%s"%(tipo, tagger, 'D', year);
  hnum = Get2D(fname, hnameN)
  hden = Get2D(fname, hnameD)
  h = hnum.Clone()
  h.Divide(hden)
  h.Draw("colz,text")
  h.SetTitle('')
  h.GetXaxis().SetTitle("Jet p_{T} (GeV)")
  h.GetYaxis().SetTitle("Jet |#eta|")
  gStyle.SetOptStat(0);
  gStyle.SetPalette(1);
  gStyle.SetPaintTextFormat("1.2f");

  #mg = TMultiGraph()
  #mg.Add()
  t = GetTLatex("%s %s b tag MC efficiencies for %s jets, %s"%(tagger, wp, tipo, year), 0.12, 0.93)

  c.SaveAs(outpath+hnameN+'.png')
  c.SaveAs(outpath+hnameN+'.pdf')
  h.SetDirectory(0)
  return h
예제 #3
0
def make_pdf_with_twoTH2Fs(th2_first, th2_sec, outpdf_path):
    hist_ls = [th2_first, th2_sec]

    canv = TCanvas()
    style = setTDRStyle(pad_right_margin=0.15)
    gStyle.SetPaintTextFormat(".3g")
    gStyle.SetOptStat(0)

    canv.Print(outpdf_path + "[")
    for h2 in hist_ls:
        h2.GetXaxis().CenterLabels()
        h2.GetYaxis().CenterLabels()
        h2.UseCurrentStyle()
        h2.Draw("colz text")
        gPad.Update()
        pave = make_pave_with_stats(h2,
                                    xmin=0.15,
                                    ymin=0.8,
                                    xmax=0.4,
                                    ymax=0.9)
        pave.Draw("same")
        # statsbox = h2.FindObject("stats")
        # statsbox.SetX1NDC(0.55)
        # statsbox.SetX2NDC(0.8)
        # statsbox.SetY1NDC(0.8)
        # statsbox.SetY2NDC(0.9)
        canv.Print(outpdf_path)
    canv.Print(outpdf_path + "]")
def dm_migration(tree, tau_decayMode_string=None, labels=None, gen_cut='tau_gen_pt>20 && abs(tau_gen_eta)<2.3', title='', formats=[]):
    '''Creates a decay mode migration plot.
    Parameters:
        tree (ROOT TTree): input tree
        tau_decayMode_string (str): draw expression that maps the decay modes onto ints 
                             (-2: undefined, used only for reco axis)
                             (-1 and following: regular decay modes)
        labels (list of str): labels for
        title (str): title used for output plot
        formats (list of str): picture formats used for output plot

    '''
    if not tau_decayMode_string:
        tau_decayMode_string = ('-2'
                         '+ (tau_pt>20 && tau_decayMode>=0 && tau_decayMode <200)*(1 ' # will contain reco DM 5 and 6 and other gen DMs
                            '+ (tau_decayMode==0)'
                            '+ 2*(tau_decayMode==1||tau_decayMode==2)'
                            '+ 3*(tau_decayMode==10)'
                            '+ 4*(tau_decayMode==11))'
            )


    if not labels:
        labels = ['None', 'Other', '#pi', '#pi#pi^{0}s', '#pi#pi#pi', '#pi#pi#pi#pi^{0}s']

    canvas = TCanvas('decay_mode_matrix')

    n_l = len(labels)
    h_migration = TH2F('migration{}'.format(title), '', n_l-1, -1., n_l-2., n_l, -2, n_l-2.)
    tree.Project(h_migration.GetName(), tau_decayMode_string+':'+tau_decayMode_string.replace('tau_', 'tau_gen_'), gen_cut)

    for y_bin in range(1, h_migration.GetYaxis().GetNbins()+1):
        h_migration.GetYaxis().SetBinLabel(y_bin, labels[y_bin-1])
    for x_bin in range(1, h_migration.GetXaxis().GetNbins()+1):
        h_migration.GetXaxis().SetBinLabel(x_bin, labels[x_bin])

    h_migration.GetYaxis().SetTitle('Offline DM')
    h_migration.GetXaxis().SetTitle('Generated DM')

    for x_bin in range(1, h_migration.GetNbinsX()+1):
        int_y = sum(h_migration.GetBinContent(x_bin, y_bin) for y_bin in range(1, h_migration.GetNbinsY()+1))
        if int_y == 0.:
            int_y = 1.
        for y_bin in range(1, h_migration.GetNbinsY()+1):
            h_migration.SetBinContent(x_bin, y_bin, h_migration.GetBinContent(x_bin, y_bin)/int_y)

    h_migration.Draw('TEXT')
    h_migration.SetMarkerColor(1)
    h_migration.SetMarkerSize(2.2)
    gStyle.SetPaintTextFormat("1.2f")

    for f in formats:
        canvas.Print(f'dm_migration_{title}.{f}')

    canvas.keeper = h_migration

    return canvas
예제 #5
0
def plot2D(histname, hist, log=False, year=''):
    """Plot efficiency."""
    dir = ensureDirectory('plots/Efficiency')
    name = "%s/%s" % (dir, histname)
    if log:
        name += "_log"
    xtitle = 'jet p_{T} [GeV]'
    ytitle = 'jet #eta'
    ztitle = 'b tag efficiencies' if '_b_' in histname else 'b miss-tag rate'

    name = name + "_" + str(year)

    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 700)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(0.07)
    canvas.SetBottomMargin(0.13)
    canvas.SetLeftMargin(0.12)
    canvas.SetRightMargin(0.17)
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    if log:
        canvas.SetLogz()
    canvas.cd()

    hist.Draw('COLZTEXT77')
    hist.GetXaxis().SetTitle(xtitle)
    hist.GetYaxis().SetTitle(ytitle)
    hist.GetZaxis().SetTitle(ztitle)
    hist.GetXaxis().SetLabelSize(0.048)
    hist.GetYaxis().SetLabelSize(0.048)
    hist.GetZaxis().SetLabelSize(0.048)
    hist.GetXaxis().SetTitleSize(0.058)
    hist.GetYaxis().SetTitleSize(0.058)
    hist.GetZaxis().SetTitleSize(0.056)
    hist.GetXaxis().SetTitleOffset(1.03)
    hist.GetYaxis().SetTitleOffset(1.04)
    hist.GetZaxis().SetTitleOffset(1.03)
    hist.GetZaxis().SetLabelOffset(-0.005 if log else 0.005)
    hist.SetMinimum(0.01 if log else 0.0)
    hist.SetMaximum(1.0)

    gStyle.SetPaintTextFormat('.2f')
    hist.SetMarkerSize(1.0)
    hist.SetMarkerColor(kRed)
    hist.SetMarkerSize(1)

    canvas.SaveAs(name + '.pdf')
    canvas.SaveAs(name + '.png')
    canvas.Close()
예제 #6
0
def initStyle(config):
    from ROOT import gROOT, gStyle, TStyle, TGaxis
    gROOT.SetBatch(True)        
    gROOT.SetStyle('Plain')
    gStyle.SetOptStat(0)
    gStyle.SetPalette(1)
    gStyle.SetPaintTextFormat(".2g")
    TGaxis.SetMaxDigits(3)
    pageSize = config.get("styleDefaults","pageSize")
    if    pageSize.lower() == "a4":     gStyle.SetPaperSize(TStyle.kA4)
    elif  pageSize.lower() == "letter": gStyle.SetPaperSize(TStyle.kUSLetter)
    else:
      pageSize = [int(i) for i in pageSize.split("x")]
      gStyle.SetPaperSize(pageSize[0],pageSize[1])
    def pretty_up_hist(self):
        """Set other hist configurations for nice format. """
        # self.h2d.SetMarkerColor(kGray+1)
        self.h2d.SetContour(200)   # Number of color divisions.
        self.h2d.GetXaxis().SetTickSize(0)
        self.h2d.GetYaxis().SetTickSize(0)
        self.h2d.GetXaxis().CenterLabels(kTRUE)
        self.h2d.GetYaxis().CenterLabels(kTRUE)

        self.h2d.GetZaxis().SetRangeUser(*color_bar_lim)  # Change color bar limits.
        # gStyle.SetPalette(55)  # The color map. Apparently Rainbow is frowned upon. kBird is default.
        gROOT.SetBatch(kTRUE)  # Do not show plots to screen.
        gStyle.SetPaintTextFormat(r"6.4g%%")  # Pad 6 spaces, use 4 sig figs.
        gStyle.SetOptStat(0)  # Do not show hist stats.
예제 #8
0
def draw_histos(sigvar,bkgvar,signifvar, signifvarsq, foldm, varbin, drawerr=False, sigerr=None, sigerrsq=None, sigrelerr=None):
    c1 = TCanvas( 'c1', 'Dynamic Filling Example', 200,10, 1200, 900 )
    os.system('mkdir -p '+foldm)
    plot_nm=varbin+"-PtmissvsMT2"#+reg+'-'+dm+'.png'

    sigvar.Draw('colz text')
    sigvar.GetYaxis().SetRange(0,400);
    sigvar.GetXaxis().SetRange(0,800);
    c1.SaveAs(foldm+"/"+plot_nm+'_signal.png')

    signifvar.Draw('colz text')
    signifvar.GetYaxis().SetRange(0,400);
    signifvar.GetXaxis().SetRange(0,800);
    c1.SaveAs(foldm+'/'+plot_nm+'_signif.png')

    if drawerr is False:
        

        bkgvar.Draw('colz text')
        bkgvar.GetYaxis().SetRange(0,400);
        bkgvar.GetXaxis().SetRange(0,800);
        c1.SaveAs(foldm+"/"+plot_nm+'_bkg.png')

        signifvarsq.Draw('colz text')
        signifvarsq.GetYaxis().SetRange(0,400);
        signifvarsq.GetXaxis().SetRange(0,800);
        c1.SaveAs(foldm+'/'+plot_nm+'_signifsq.png')
    if drawerr is True:
        sigerr.Draw('colz text')
        sigerr.GetYaxis().SetRange(0,400);
        sigerr.GetXaxis().SetRange(0,800);
        c1.SaveAs(foldm+'/'+plot_nm+'_sigerr.png')

        sigrelerr.Draw('colz text')
        sigrelerr.GetYaxis().SetRange(0,400);
        sigrelerr.GetXaxis().SetRange(0,800);
        c1.SaveAs(foldm+'/'+plot_nm+'_sigrelerr.png')

        paintsq=False
        if paintsq is True:
            gStyle.SetPaintTextFormat("2.3g");
            sigerrsq.Draw('colz text')
            sigerrsq.GetYaxis().SetRange(0,400);
            sigerrsq.GetXaxis().SetRange(0,800);
            c1.SaveAs(foldm+'/'+plot_nm+'_sigerrsq.png')

    
    os.system("cp "+wloc+'/index.php '+foldm)
예제 #9
0
def setStyle():
    gROOT.Reset()
    icol = 0
    # WHITE
    font = 42
    # Helvetica
    tsize = 0.05
    gStyle.SetFrameBorderMode(icol)
    gStyle.SetFrameFillColor(icol)
    gStyle.SetCanvasBorderMode(icol)
    gStyle.SetCanvasColor(icol)
    gStyle.SetPadBorderMode(icol)
    gStyle.SetPadColor(icol)
    gStyle.SetStatColor(icol)
    gStyle.SetPaperSize(20, 26)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.08)
    gStyle.SetPadBottomMargin(0.15)
    gStyle.SetPadLeftMargin(0.12)
    gStyle.SetTitleXOffset(1.05)
    gStyle.SetTitleYOffset(0.95)
    gStyle.SetTextFont(font)
    gStyle.SetTextSize(tsize)
    gStyle.SetLabelFont(font, "x")
    gStyle.SetTitleFont(font, "x")
    gStyle.SetLabelFont(font, "y")
    gStyle.SetTitleFont(font, "y")
    gStyle.SetLabelFont(font, "z")
    gStyle.SetTitleFont(font, "z")
    gStyle.SetLabelSize(tsize * 0.85, "x")
    gStyle.SetTitleSize(tsize * 1.10, "x")
    gStyle.SetLabelSize(tsize * 0.85, "y")
    gStyle.SetTitleSize(tsize * 1.10, "y")
    gStyle.SetLabelSize(tsize * 0.85, "z")
    gStyle.SetTitleSize(tsize * 1.10, "z")
    gStyle.SetMarkerStyle(20)
    gStyle.SetMarkerSize(1.)
    gStyle.SetHistLineWidth(2)
    gStyle.SetLineStyleString(2, "[12 12]")
    # postscript dashes
    gStyle.SetEndErrorSize(0.)
    # gStyle.SetOptTitle(0);
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(0)
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetPaintTextFormat("4.1f")
예제 #10
0
def DrawPlot(fname,
             hname,
             outname,
             outpath="./SFplots/",
             inpath='InputFiles/',
             doErrors=True):
    if not outpath.endswith('/'): outpath += '/'
    if not inpath.endswith('/'): inpath += '/'
    if not fname.endswith('.root'): fname += '.root'
    f = TFile.Open(inpath + fname)
    h = f.Get(hname)
    c = TCanvas("c", "c", 10, 10, 1600, 1200)
    gStyle.SetOptStat(0)
    gStyle.SetPalette(1)
    gStyle.SetPaintTextFormat("1.2f")

    if doErrors: h.Draw("colz, text, errors")
    else: h.Draw("colz, text")
    if not os.path.isdir(outpath): gSystem.mkdir(outpath, 1)
    c.Print(outpath + outname + '.pdf', 'pdf')
    c.Print(outpath + outname + '.png', 'png')
예제 #11
0
			# exclusion2.GetXaxis().SetTitleSize(sizefactor*exclusion2.GetXaxis().GetTitleSize())
			# exclusion2.GetYaxis().SetTitleSize(sizefactor*exclusion2.GetYaxis().GetTitleSize())
			# exclusion2.GetZaxis().SetTitleSize(sizefactor*exclusion2.GetZaxis().GetTitleSize())
			# exclusion2.GetXaxis().SetLabelSize(sizefactor*exclusion2.GetXaxis().GetLabelSize())
			# exclusion2.GetYaxis().SetLabelSize(sizefactor*exclusion2.GetYaxis().GetLabelSize())
			# exclusion2.GetZaxis().SetLabelSize(sizefactor*exclusion2.GetZaxis().GetLabelSize())
			# exclusion2.GetZaxis().SetNoExponent(1)
			# exclusion2.GetZaxis().SetMoreLogLabels(1)
			# #offset=1.2
			# exclusion2.SetStats(0)
			# exclusion2.GetXaxis().SetTitleOffset(offset*exclusion2.GetXaxis().GetTitleOffset())
			# exclusion2.GetYaxis().SetTitleOffset(offset*exclusion2.GetYaxis().GetTitleOffset())
			# exclusion2.GetZaxis().SetTitleOffset(1.4*exclusion2.GetZaxis().GetTitleOffset())
			exclusion2.Draw()

		gStyle.SetPaintTextFormat('4.2f')
		p.SetMarkerSize(0.4)
		#p.SetMarkerColor(14)
		#p.Draw('atext45 same')
		c.SetLogz(1)
		#p.GetZaxis().SetMoreLogLabels(1)
		CMS_lumi.writeExtraText=False
		if tipo=='exp':
			CMS_lumi.writeExtraText=True
		CMS_lumi.CMS_lumi(c, 4, 33)
		latex=TLatex(0.2 ,0.1,signalWB_legendnames[masspoint])
		if tipo=='obs':
			latex=TLatex(0.2 ,0.1,signalWB_legendnames_obs[masspoint])
		latex.SetTextFont(42)
		#latex.SetTextSize(latex.GetTextSize()*0.85)
		#latex.SetTextAlign(11)
from ROOT import TFile, TF1, TUnfold, TUnfoldDensity
from ROOT import gDirectory, TH1F, TH1D, TH2D, TGraph, TSpline3, TH2F
from ROOT import gROOT, TCanvas, gStyle, TPad, TLine, TLegend
from ROOT import TMath, TText, TLatex, gApplication, gPad
from array import *
import math,sys
import ROOT
import subprocess

gStyle.SetOptStat(0)
gStyle.SetPaintTextFormat("5.1f")

### RESPONSE matrix ####
label = sys.argv[1]
print label
if (label=='MC'):
   toyMC = TFile("output-MC-PtHat-1.root")
elif (label=='MCherwig'):
   toyMC = TFile('TTbar-Events-Herwig.root')
elif (label=='MCfxfx'):
   toyMC = TFile('TTbar-Events-CUEP8M2T4-FxFx.root')
elif (label=='MCcuetm2'):
   toyMC = TFile('TTbar-Events-CUETP8M2-UpJER-CentralBTagging.root')
else:
    print 'Allowed arguments are MCcuetm1, MCherwig, MCfxfx, MCcuetm2'
    quit()

dataFile = TFile("hist.root")
global bineta
bineta = ["0.0", "0.5", "1.0", "1.5", "2.0", "2.5"]
numberBinsGen = [16, 16, 15, 14, 13]
예제 #13
0
def plotCorrelation(channel,var,DM,year,*parameters,**kwargs):
    """Calculate and plot correlation between parameters."""
    if DM=='DM0' and 'm_2' in var: return
    print green("\n>>> plotCorrelation %s, %s"%(DM, var))
    if len(parameters)==1 and isinstance(parameters[0],list): parameters = parameters[0]
    parameters  = [p.replace('$CAT',DM).replace('$CHANNEL',channel) for p in list(parameters)]
    
    title       = kwargs.get('title',     ""                )
    name        = kwargs.get('name',      ""                )
    indir       = kwargs.get('indir',     "output_%d"%year  )
    outdir      = kwargs.get('outdir',    "postfit_%d"%year )
    tag         = kwargs.get('tag',       ""                )
    plotlabel   = kwargs.get('plotlabel', ""                )
    order       = kwargs.get('order',     False             )
    era         = "%d-13TeV"%year
    filename    = '%s/higgsCombine.%s_%s-%s%s-%s.MultiDimFit.mH90.root'%(indir,channel,var,DM,tag,era)
    ensureDirectory(outdir)
    print '>>>   file "%s"'%(filename)
    
    # HISTOGRAM
    parlist = getParameters(filename,parameters)
    if order:
      parlist.sort(key=lambda x: -x.sigma)
    N       = len(parlist)     
    hist    = TH2F("corr","corr",N,0,N,N,0,N)
    
    for i in xrange(N): # diagonal
      hist.SetBinContent(i+1,N-i,1.0)
      hist.GetXaxis().SetBinLabel(1+i,parlist[i].title)
      hist.GetYaxis().SetBinLabel(N-i,parlist[i].title)
    for xi, yi in combinations(range(N),2): # off-diagonal
      r = parlist[xi].corr(parlist[yi])
      hist.SetBinContent(1+xi,N-yi,r)
      hist.SetBinContent(1+yi,N-xi,r)
      #print "%20s - %20s: %5.3f"%(par1,par2,r)
      #hist.Fill(par1.title,par2.title,r)
      #hist.Fill(par2.title,par1.title,r)
    
    # SCALE
    canvasH  = 160+64*max(10,N)
    canvasW  = 300+70*max(10,N)
    scaleH   =  800./canvasH
    scaleW   = 1000./canvasW
    scaleF   = 640./(canvasH-160)
    tmargin  = 0.06
    bmargin  = 0.14
    lmargin  = 0.22
    rmargin  = 0.12
    
    canvas = TCanvas('canvas','canvas',100,100,canvasW,canvasH)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(  tmargin ); canvas.SetBottomMargin( bmargin )
    canvas.SetLeftMargin( lmargin ); canvas.SetRightMargin( rmargin )
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    canvas.cd()
    
    frame = hist
    frame.GetXaxis().SetLabelSize(0.054*scaleF)
    frame.GetYaxis().SetLabelSize(0.072*scaleF)
    frame.GetZaxis().SetLabelSize(0.034)
    frame.GetXaxis().SetLabelOffset(0.005)
    frame.GetYaxis().SetLabelOffset(0.003)
    frame.GetXaxis().SetNdivisions(508)
    #gStyle.SetPalette(kBlackBody)
    #frame.SetContour(3);
    gStyle.SetPaintTextFormat(".2f")
    frame.SetMarkerSize(1.5*scaleF)
    #frame.SetMarkerColor(kRed)
    
    hist.Draw('COLZ TEXT')
    
    # TEXT
    if title:
      latex = TLatex()
      latex.SetTextSize(0.045)
      latex.SetTextAlign(33)
      latex.SetTextFont(42)
      latex.DrawLatexNDC(0.96*lmargin,0.80*bmargin,title)
    
    CMS_lumi.relPosX = 0.14
    CMS_lumi.CMS_lumi(canvas,13,0)
    gPad.SetTicks(1,1)
    gPad.Modified()
    frame.Draw('SAMEAXIS')
    
    canvasname = "%s/postfit-correlation_%s_%s%s%s"%(outdir,var,DM,tag,plotlabel)
    canvas.SaveAs(canvasname+".png")
    if args.pdf: canvas.SaveAs(canvasname+".pdf")
    canvas.Close()
예제 #14
0
    def plot(self):
        """ ROOT plotting. """

        # Masses
        name = 'm_gluino'
        title = 'm_{#tilde{g}} [GeV]'
        self._make_plot(name, title, self.m_gluino)

        name = 'm_neutralino1'
        title = 'm_{#chi_{1}^{0}} [GeV]'
        self._make_plot(name, title, self.m_neutralino1)

        name = 'm_neutralino2'
        title = 'm_{#chi_{2}^{0}} [GeV]'
        self._make_plot(name, title, self.m_neutralino2)

        name = 'm_neutralino3'
        title = 'm_{#chi_{3}^{0}} [GeV]'
        self._make_plot(name, title, self.m_neutralino3)

        name = 'm_neutralino4'
        title = 'm_{#chi_{4}^{0}} [GeV]'
        self._make_plot(name, title, self.m_neutralino4)

        name = 'm_chargino1'
        title = 'm_{#chi_{1}^{#pm}} [GeV]'
        self._make_plot(name, title, self.m_chargino1)

        name = 'm_chargino2'
        title = 'm_{#chi_{2}^{#pm}} [GeV]'
        self._make_plot(name, title, self.m_chargino2)

        name = 'm_stop1'
        title = 'm_{#tilde{t_{1}}} [GeV]'
        self._make_plot(name, title, self.m_stop1)

        name = 'm_stop2'
        title = 'm_{#tilde{t_{2}}} [GeV]'
        self._make_plot(name, title, self.m_stop2)

        name = 'm_smhiggs'
        title = 'm_{h^{0}} [GeV]'
        self._make_plot(name, title, self.m_smhiggs)

        name = 'm_sdown_l'
        title = 'm_{#tilde{d}_{L}} [GeV]'
        self._make_plot(name, title, self.m_sdown_l)

        name = 'm_sdown_r'
        title = 'm_{#tilde{d}_{R}} [GeV]'
        self._make_plot(name, title, self.m_sdown_r)

        name = 'm_sup_l'
        title = 'm_{#tilde{u}_{L}} [GeV]'
        self._make_plot(name, title, self.m_sup_l)

        name = 'm_sup_r'
        title = 'm_{#tilde{u}_{R}} [GeV]'
        self._make_plot(name, title, self.m_sup_r)

        name = 'm_sstrange_l'
        title = 'm_{#tilde{s}_{L}} [GeV]'
        self._make_plot(name, title, self.m_sstrange_l)

        name = 'm_sstrange_r'
        title = 'm_{#tilde{s}_{R}} [GeV]'
        self._make_plot(name, title, self.m_sstrange_r)

        name = 'm_scharm_l'
        title = 'm_{#tilde{c}_{L}} [GeV]'
        self._make_plot(name, title, self.m_scharm_l)

        name = 'm_scharm_r'
        title = 'm_{#tilde{c}_{R}} [GeV]'
        self._make_plot(name, title, self.m_scharm_r)

        # Lifetimes
        gStyle.SetPaintTextFormat('3.2g')

        name = 'ct_gluino'
        title = 'c#tau_{#tilde{g}} [mm]'
        self._make_plot(name, title, self.ct_gluino, decimals=99)

        name = 'ct_chargino1'
        title = 'c#tau_{#tilde{#chi}_{1}^{#pm}} [mm]'
        self._make_plot(name, title, self.ct_chargino1, decimals=99)

        name = 'ct_neutralino2'
        title = 'c#tau_{#tilde{#chi}_{2}^{0}} [mm]'
        self._make_plot(name, title, self.ct_neutralino2, decimals=99)

        gStyle.SetPaintTextFormat('g')

        # Mass differences
        name = 'm_gluino-m_chargino1'
        title = 'm_{#tilde{g}} - m_{#chi_{1}^{#pm}} [GeV]'
        self._make_plot(
            name, title,
            [a - b for a, b in zip(self.m_gluino, self.m_chargino1)])

        name = 'm_chargino1-m_neutralino1'
        title = 'm_{#chi_{1}^{#pm}} - m_{#chi_{1}^{0}} [GeV]'
        self._make_plot(
            name, title,
            [a - b for a, b in zip(self.m_chargino1, self.m_neutralino1)])

        name = 'm_neutralino3-m_neutralino1'
        title = 'm_{#chi_{3}^{0}} - m_{#chi_{1}^{0}} [GeV]'
        self._make_plot(
            name, title,
            [a - b for a, b in zip(self.m_neutralino3, self.m_neutralino1)])

        name = 'm_neutralino3-m_neutralino2'
        title = 'm_{#chi_{3}^{0}} - m_{#chi_{2}^{0}} [GeV]'
        self._make_plot(
            name, title,
            [a - b for a, b in zip(self.m_neutralino3, self.m_neutralino2)])

        name = 'm_neutralino2-m_neutralino1'
        title = 'm_{#chi_{2}^{0}} - m_{#chi_{1}^{0}} [GeV]'
        self._make_plot(
            name, title,
            [a - b for a, b in zip(self.m_neutralino2, self.m_neutralino1)])

        name = 'm_neutralino3-m_chargino1'
        title = 'm_{#chi_{3}^{0}} - m_{#chi_{1}^{#pm}} [GeV]'
        self._make_plot(
            name, title,
            [a - b for a, b in zip(self.m_neutralino3, self.m_chargino1)])

        name = 'm_neutralino2-m_chargino1'
        title = 'm_{#chi_{2}^{0}} - m_{#chi_{1}^{#pm}} [GeV]'
        self._make_plot(
            name, title,
            [a - b for a, b in zip(self.m_neutralino2, self.m_chargino1)])

        # Cross-sections
        name = 'xs13_incl'
        title = '#sigma_{inclusive} (13 TeV) [fb]'
        self._make_plot(name, title, self.xs13_incl)

        name = 'xs13_strong'
        title = '#sigma_{strong}/#sigma_{inclusive} (13 TeV)'
        self._make_plot(name, title, self.xs13_strong, True)

        name = 'xs13_gluino_gluino'
        title = '#sigma (pp #rightarrow #tilde{g}#tilde{g})/' \
                '#sigma_{inclusive} (13 TeV)'
        self._make_plot(name, title, self.xs13_gluinos, True)

        name = 'xs8_incl'
        title = '#sigma_{inclusive} (8 TeV) [fb]'
        self._make_plot(name, title, self.xs8_incl)

        name = 'xs8_strong'
        title = '#sigma_{strong}/#sigma_{inclusive} (8 TeV)'
        self._make_plot(name, title, self.xs8_strong, True)

        name = 'xs13_xs8'
        title = '#sigma_{incl} (13 TeV)/#sigma_{incl} (8 TeV)'
        self._make_plot(
            name, title,
            [safe_divide(a, b) for a, b in zip(self.xs13_incl, self.xs8_incl)])

        # Dominant cross section particles
        gStyle.SetPaintTextFormat('7.0f')

        name = 'dom1'
        title = 'Dominant cross section particle 1'
        self._make_plot(name, title, self.dom_id1)

        name = 'dom2'
        title = 'Dominant cross section particle 2'
        self._make_plot(name, title, self.dom_id2)

        gStyle.SetPaintTextFormat('g')

        # Decay channels
        name = 'dc_gluino'
        title = 'Relative decay channels of #tilde{g}'
        self._make_plot_dc(name, title, self.dc_gluino)

        name = 'dc_chargino1'
        title = 'Relative decay channels of #tilde{#chi}_{1}^{#pm}'
        self._make_plot_dc(name, title, self.dc_chargino1)

        name = 'dc_chargino2'
        title = 'Relative decay channels of #tilde{#chi}_{2}^{#pm}'
        self._make_plot_dc(name, title, self.dc_chargino2)

        name = 'dc_neutralino2'
        title = 'Relative decay channels of #tilde{#chi}_{2}^{0}'
        self._make_plot_dc(name, title, self.dc_neutralino2)

        name = 'dc_neutralino3'
        title = 'Relative decay channels of #tilde{#chi}_{3}^{0}'
        self._make_plot_dc(name, title, self.dc_neutralino3)

        name = 'dc_neutralino4'
        title = 'Relative decay channels of #tilde{#chi}_{4}^{0}'
        self._make_plot_dc(name, title, self.dc_neutralino4)

        name = 'dc_sdown_l'
        title = 'Relative decay channels of #tilde{d}_{L}'
        self._make_plot_dc(name, title, self.dc_sdown_l)

        name = 'dc_sdown_r'
        title = 'Relative decay channels of #tilde{d}_{R}'
        self._make_plot_dc(name, title, self.dc_sdown_r)

        name = 'dc_sup_l'
        title = 'Relative decay channels of #tilde{u}_{L}'
        self._make_plot_dc(name, title, self.dc_sup_l)

        name = 'dc_sup_r'
        title = 'Relative decay channels of #tilde{u}_{R}'
        self._make_plot_dc(name, title, self.dc_sup_r)

        name = 'dc_sstrange_l'
        title = 'Relative decay channels of #tilde{s}_{L}'
        self._make_plot_dc(name, title, self.dc_sstrange_l)

        name = 'dc_sstrange_r'
        title = 'Relative decay channels of #tilde{s}_{R}'
        self._make_plot_dc(name, title, self.dc_sstrange_r)

        name = 'dc_scharm_l'
        title = 'Relative decay channels of #tilde{c}_{L}'
        self._make_plot_dc(name, title, self.dc_scharm_l)

        name = 'dc_scharm_r'
        title = 'Relative decay channels of #tilde{c}_{R}'
        self._make_plot_dc(name, title, self.dc_scharm_r)

        # Branching ratios
        for no_leptons in range(len(self.br_leptons)):
            name = 'br_{}_leptons'.format(no_leptons)
            title = 'BR into {} leptons'.format(no_leptons)
            self._make_plot(name, title, self.br_leptons[no_leptons], True)

        for no_leptons in range(len(self.br_leptons)):
            name = 'br_{}_leptons_incl'.format(no_leptons)
            title = 'BR into {}+ leptons'.format(no_leptons)
            self._make_plot(
                name, title,
                [sum(i) for i in zip(*self.br_leptons[no_leptons:])], True)

        for no_jets in range(len(self.br_jets)):
            name = 'br_{}_jets'.format(no_jets)
            title = 'BR into {} jets'.format(no_jets)
            self._make_plot(name, title, self.br_jets[no_jets], True)

        for no_jets in range(len(self.br_jets)):
            name = 'br_{}_jets_incl'.format(no_jets)
            title = 'BR into {}+ jets'.format(no_jets)
            self._make_plot(name, title,
                            [sum(i) for i in zip(*self.br_jets[no_jets:])],
                            True)

        for no_photons in range(len(self.br_photons)):
            name = 'br_{}_photons'.format(no_photons)
            title = 'BR into {} photons'.format(no_photons)
            self._make_plot(name, title, self.br_photons[no_photons], True)

        for no_photons in range(len(self.br_photons)):
            name = 'br_{}_photons_incl'.format(no_photons)
            title = 'BR into {}+ photons'.format(no_photons)
            self._make_plot(
                name, title,
                [sum(i) for i in zip(*self.br_photons[no_photons:])], True)

        # Cross-sections times branching ratio
        for no_leptons in range(len(self.br_leptons)):
            name = 'xs13_x_br_{}_leptons'.format(no_leptons)
            title = '#sigma #times BR(#tilde{{g}}#tilde{{g}} #rightarrow {} ' \
                    'leptons) [fb]'.format(no_leptons)
            self._make_plot(name, title, [
                a * b
                for a, b in zip(self.br_leptons[no_leptons], self.xs13_incl)
            ])

        # Signal strength
        name = 'mu'
        title = '#mu'
        self._make_plot(name, title, self.mu, decimals=2)

        # Close root file
        if self._toolbox.rootfile.IsOpen():
            self._toolbox.rootfile.Close()

        # Move used SLHA template to output folder
        system('cp suspect2_lha.template {}'.format(self._toolbox.directory))
        system('mv susyhit_slha_*.out {}'.format(self._toolbox.directory))
        system('mv suspect2_*.out {}'.format(self._toolbox.directory))

        # Move SModelS output to output folder
        system('mv smodels_summary_*.txt {} 2>/dev/null'.format(
            self._toolbox.directory))
예제 #15
0
def coverlay(hists,
             xtitle,
             ytitle,
             name,
             runtype,
             tlabel,
             xlabel,
             xlabel_eta,
             sellabel,
             comparePerReleaseSuffix="",
             norm="",
             ndim=1):

    gStyle.SetOptStat(111110)
    c = TCanvas()
    if ndim == 1:
        c.SetRightMargin(0.10)
    elif ndim == 2:
        c.SetRightMargin(0.15)
    c.SetLeftMargin(0.12)
    c.SetBottomMargin(0.10)
    # Upper plot will be in pad1
    # pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    # pad1.SetBottomMargin(0.03)  # Upper and lower plot are joined
    # pad1.Draw()             # Draw the upper pad: pad1
    # pad1.cd()              # pad1 becomes the current pad
    # c.SetLogy(0)
    # if any(subname in name for subname in ['isoPt', 'outOfConePt', 'IsoRaw', 'deepTau']):
    #     c.SetLogy()
    if ndim == 1:
        c.SetLogy()
    if ndim == 2:
        c.SetLogz()

    ymax = max([hist.GetMaximum() for hist in hists])
    # leg = TLegend(0.65, 0.65, 0.85, 0.9)
    # configureLegend(leg, 1)

    hratios = []
    for i_hist, hist in enumerate(hists):

        hist.SetMaximum(ymax * 1.2)
        hist.SetMinimum(0.)
        # if c.GetLogy > 0:
        if c.GetLogy > 0:
            hist.SetMinimum(0.001)
        hist.GetXaxis().SetTitleSize(0.04)
        hist.GetXaxis().SetLabelSize(0.04)
        hist.GetYaxis().SetTitleSize(0.04)
        hist.GetYaxis().SetLabelSize(0.04)
        hist.GetXaxis().SetTitle(xtitle)
        hist.GetYaxis().SetTitle(ytitle)

        if i_hist == 0:
            if ndim == 1:
                hist.SetMarkerSize(0.)
                hist.Draw('h')
                # gPad.Update()
                hist.SetStats(1)
                # st = hist.GetListOfFunctions().FindObject("stats")
                # # st.SetOptStat(1110)
                # # st = c.GetPrimitive("stats")
                # # st.SetNDC()
                # st.SetX1NDC(0.7)
                # st.SetX2NDC(0.85)
            elif ndim == 2:
                hist.SetMarkerSize(1.2)
                min_bincontent = 0.005
                if norm == "abs":
                    gStyle.SetPaintTextFormat("g")
                else:
                    gStyle.SetPaintTextFormat("4.2f")
                    hist.SetMaximum(100)
                    hist.SetMinimum(0.0049)
                if norm == "global":
                    integral = hist.Integral(1, hist.GetNbinsX(), 1,
                                             hist.GetNbinsY())
                    for i in range(1, hist.GetNbinsX() + 1):
                        for j in range(1, hist.GetNbinsY() + 1):
                            bincontent = hist.GetBinContent(
                                i, j) / integral * 100 if integral > 0 else 0
                            bincontent = min_bincontent if (
                                bincontent > 0 and
                                bincontent < min_bincontent) else bincontent
                            hist.SetBinContent(i, j, bincontent)
                elif norm == "col":
                    for i in range(1, hist.GetNbinsX() + 1):
                        integral = hist.Integral(i, i, 1, hist.GetNbinsY())
                        for j in range(1, hist.GetNbinsY() + 1):
                            bincontent = hist.GetBinContent(
                                i, j) / integral * 100 if integral > 0 else 0
                            bincontent = min_bincontent if (
                                bincontent > 0 and
                                bincontent < min_bincontent) else bincontent
                            hist.SetBinContent(i, j, bincontent)
                elif norm == "row":
                    for j in range(1, hist.GetNbinsY() + 1):
                        integral = hist.Integral(1, hist.GetNbinsX(), j, j)
                        for i in range(1, hist.GetNbinsX() + 1):
                            bincontent = hist.GetBinContent(
                                i, j) / integral * 100 if integral > 0 else 0
                            bincontent = min_bincontent if (
                                bincontent > 0 and
                                bincontent < min_bincontent) else bincontent
                            hist.SetBinContent(i, j, bincontent)
                hist.Draw("COLZ TEXT")
                gPad.RedrawAxis()
        #     hist_TAR = hist.Clone()
        else:
            if ndim == 1:
                hist.Draw('hsame')
            elif ndim == 2:
                hist.Draw("TEXTCOLZsame")
        #     # ihr = hist.Clone()
        #     # ihr.Sumw2()
        #     #ihr.Divide(hists[0])
        #
        #     # ihr = hist_TAR.Clone()
        #     # ihr.Divide(hist)
        #     ihr = hist.Clone()
        #     ihr.Divide(hist_TAR)
        #
        #     ihr.SetStats(0)
        #     ihr.SetLineColor(hist.GetLineColor())
        #     ihr.SetMarkerColor(hist.GetMarkerColor())
        #     ihr.SetMarkerStyle(hist.GetMarkerStyle())
        #     hratios.append(ihr)
        #
        # leg.AddEntry(hist, hist.GetName(), "l")

    # leg.Draw()
    #
    # xshift = 0.0
    # yshift = ymax*1.4
    # if tlabel.find('QCD') != -1:
    #     # pad1.SetTopMargin(0.1)
    #     xshift = 0.0
    #     # yshift = ymax*1.45
    # if runtype.find('TTbarTau') != -1:
    #     xshift = 0.78
    tex2 = TLatex(0.95, 0.96, tlabel)
    tex2.SetNDC()
    tex2.SetTextAlign(32)
    tex2.SetTextFont(42)
    tex2.SetTextSize(0.043)
    tex2.Draw()

    seltex = TLatex(0.02, 0.96, sellabel)
    seltex.SetNDC()
    seltex.SetTextAlign(12)
    seltex.SetTextFont(42)
    seltex.SetTextSize(0.023)
    seltex.Draw()

    #
    # # lower plot will be in pad
    # c.cd()          # Go back to the main canvas before defining pad2
    # pad2 = TPad("pad2", "pad2", 0, 0.0, 1, 0.27)
    # pad2.SetTopMargin(0.03)
    # pad2.SetBottomMargin(0.35)
    # pad2.Draw()
    # pad2.cd()
    # for ii, hist in enumerate(hratios):
    #     hist.GetXaxis().SetTitle(xtitle)
    #     hist.GetXaxis().SetTitleOffset(0.83)
    #     hist.GetXaxis().SetNdivisions(507)
    #     hist.GetYaxis().SetTitle('ratio')
    #     hist.GetYaxis().SetNdivisions(503)
    #     hist.SetMinimum(0.75)
    #     hist.SetMaximum(1.25)
    #     hist.GetYaxis().SetTitleOffset(0.45)
    #     hist.GetYaxis().SetTitleSize(0.16)
    #     hist.GetYaxis().SetLabelSize(0.16)
    #     hist.GetXaxis().SetTitleSize(0.16)
    #     hist.GetXaxis().SetLabelSize(0.16)
    #     if ii == 0:
    #         hist.Draw('ep')
    #     else:
    #         hist.Draw('epsame')

    c.cd()  # Go back to the main canvas
    save(
        c,
        ('compare_' + runtype + comparePerReleaseSuffix +
         '/taumatching/hist_' + name + '_' + norm + 'norm_' + str(ndim) + 'D'))
    c = None
    gStyle.SetOptStat(0)
예제 #16
0
def main():
    ##Both conservative and not conservative will give same efficiency shapes for SM
    get_tot_eff()
    #get_tot_eff_alternate_model(scenario, model_indx, conservative)


if __name__ == '__main__':
    scenario = sys.argv[1]
    model_indx = sys.argv[2]
    variation_range = sys.argv[3]

    conservative = None
    if variation_range == 'large':
        conservative = True
    elif variation_range == 'one_sigma':
        conservative = False
    else:
        raise Exception(
            "The value of variation_range not recognised, only 'large' or 'one_sigma' allowed!"
        )

    print(scenario, model_indx, variation_range, conservative)

    scenarios = ['CVR', 'CSR', 'CSL', 'CT', 'SM']
    if scenario not in scenarios:
        raise Exception('Scenario not in Scenarios')

    gROOT.ProcessLine(".x lhcbStyle2D.C")
    gStyle.SetPaintTextFormat("1.3f")
    main()
def plot2D(histname, hist, year, channel, log=False):
    """Plot 2D efficiency."""
    dir = ensureDirectory('plots/%d' % year)
    name = "%s/%s_%s" % (dir, histname, channel)
    if log:
        name += "_log"
    xtitle = 'jet p_{T} [GeV]'
    ytitle = 'jet #eta'
    ztitle = 'b tag efficiencies' if '_b_' in histname else 'b mistag rate'
    xmin, xmax = 20, hist.GetXaxis().GetXmax()
    zmin, zmax = 5e-3 if log else 0.0, 1.0
    angle = 22 if log else 77

    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 700)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(0.07)
    canvas.SetBottomMargin(0.13)
    canvas.SetLeftMargin(0.12)
    canvas.SetRightMargin(0.17)
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    gStyle.SetOptTitle(0)  #FontSize(0.04)
    if log:
        canvas.SetLogx()
        canvas.SetLogz()
    canvas.cd()

    hist.GetXaxis().SetTitle(xtitle)
    hist.GetYaxis().SetTitle(ytitle)
    hist.GetZaxis().SetTitle(ztitle)
    hist.GetXaxis().SetLabelSize(0.048)
    hist.GetYaxis().SetLabelSize(0.048)
    hist.GetZaxis().SetLabelSize(0.048)
    hist.GetXaxis().SetTitleSize(0.058)
    hist.GetYaxis().SetTitleSize(0.058)
    hist.GetZaxis().SetTitleSize(0.056)
    hist.GetXaxis().SetTitleOffset(1.03)
    hist.GetYaxis().SetTitleOffset(1.04)
    hist.GetZaxis().SetTitleOffset(1.03)
    hist.GetXaxis().SetLabelOffset(-0.004 if log else 0.005)
    hist.GetZaxis().SetLabelOffset(-0.005 if log else 0.005)
    hist.GetXaxis().SetRangeUser(xmin, xmax)
    hist.SetMinimum(zmin)
    hist.SetMaximum(zmax)
    hist.Draw('COLZTEXT%d' % angle)

    gStyle.SetPaintTextFormat('.2f')
    hist.SetMarkerColor(kRed)
    hist.SetMarkerSize(1.8 if log else 1)
    #gPad.Update()
    #gPad.RedrawAxis()

    latex = TLatex()
    latex.SetTextSize(0.048)
    latex.SetTextAlign(23)
    latex.SetTextFont(42)
    latex.SetNDC(True)
    latex.DrawLatex(0.475, 0.99,
                    hist.GetTitle())  # to prevent typesetting issues

    canvas.SaveAs(name + '.pdf')
    canvas.SaveAs(name + '.png')
    canvas.Close()
예제 #18
0
def eff_2D(cutlist, labellist=[], zmax=30, pal=109):

    basecut = BASECUT
    print "basecut considered: ", basecut
    signame = ""
    ncuts = len(cutlist)
    if labellist == []:
        labellist = cutlist
        gStyle.SetPalette(
            87
        )  #87:light temperature #104 temperature map #69:beach(!) #70:black body #86:lake #109:cool(!)
    else:
        gStyle.SetPalette(
            pal
        )  #87:light temperature #104 temperature map #69:beach(!) #70:black body #86:lake #109:cool(!)

    file = {}
    nevt = {}
    tree = {}
    effs = {}
    eff_dict = {k: {} for k in cutlist}
    #print eff_dict
    sign = sign_ctau
    XSEC = 0

    for i, s in enumerate(sign):
        if 'WplusH' in samples[s]['files'][0]:
            signame = "WplusH"
            XSEC = WpluslnuHXSEC
        elif 'WminusH' in samples[s]['files'][0]:
            signame = "WminusH"
            XSEC = WminuslnuHXSEC
        elif 'ZH' in samples[s]['files'][
                0] and not 'ggZH' in samples[s]['files'][0]:
            signame = "ZH"
            XSEC = ZllHXSEC
        elif 'ggZH' in samples[s]['files'][0]:
            signame = "ggZH"
            XSEC = ggZHXSEC
        elif 'VBF' in samples[s]['files'][0]:
            signame = "VBFH"
            XSEC = VBFXSEC
        file[s] = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root",
                        "READ")  # Read TFile

        if EFFICIENCY or FIDUCIAL_ONLY or TRIGGER_TOP_FIDUCIAL:
            XSEC = 100. / LUMI
        #print file[s]
        ##nevt[s] = (file[s].Get('counter/c_nEvents')).GetBinContent(1)
        tree[s] = file[s].Get("reconstruction/tree")  # Read TTree
        nevt[s] = file[s].Get("reconstruction/tree").GetEntriesFast()
        if verbose:
            print "nevt: ", tree[s].GetEntries()
            print "nevt after basecut: ", tree[s].GetEntries(basecut)
        effs[s] = [0] * (ncuts + 1)
        for j, c in enumerate(cutlist):
            br = 1.
            if FIDUCIAL_ONLY:
                tot_gen = tree[s].GetEntries()
                n = tree[s].GetEntries(basecut)
                if verbose:
                    print "den: ", tot_gen
                    print "num: ", n
            elif TRIGGER_TOP_FIDUCIAL:
                tot_gen = tree[s].GetEntries(basecut)
                n = tree[s].GetEntries("(" + cutlist[j] + ")" + " && " +
                                       basecut)
                if verbose:
                    print "den: ", tree[s].GetEntries(basecut)
                    print "evt passing trigger: ", tree[s].GetEntries(
                        cutlist[j])
                    print "num: ", tree[s].GetEntries("(" + cutlist[j] + ")" +
                                                      " && " + basecut)
            else:
                tot_gen = tree[s].GetEntries()
                n = tree[s].GetEntries("(" + cutlist[j] + ")" + " && " +
                                       basecut)
                if verbose:
                    print "den: ", tot_gen
                    print "num: ", n
            #exit()
            #d = tree[s].GetEntries(basecut)#nevt[s]#d = sample[samples[s]['files'][0]]['nevents']#
            effs[s][j] = (float(n) / (tot_gen)) * XSEC * LUMI
            #ctau_ind = samples[s]['ctau']
            #m_ind = samples[s]['mass']
            #eff_dict[c][s] = {'mass' : samples[s]['mass'], 'ctau' : samples[s]['ctau'], 'eff' :effs[s][j]*100}
            ##print "WARNING! USING MASS + CTAU AS INDEX IS DANGEROUS BECAUSE THEY ARE OVERWRITTEN!"
            #print "c_tau: ", ctau_ind
            #print "mass: ", m_ind
            #print s
            #print effs[s][j]
            ##print ctau_ind + m_ind
            eff_dict[c][s] = {
                'mass': samples[s]['mass'],
                'ctau': samples[s]['ctau'],
                'eff': effs[s][j]
            }
            ###########
#############################
#######################
### WARNING! USING MASS + CTAU AS INDEX IS DANGEROUS!
#############################
#######################
#exit()
#print "Filled eff_dict:"
#print eff_dict

    x_array = [50000]
    y_array = [10]
    for j, c in enumerate(cutlist):
        for i, s in enumerate(sign):
            x_val = (samples[s]['ctau'])
            y_val = float(samples[s]['mass'])
            if x_val not in x_array: x_array.append(x_val)
            if y_val not in y_array: y_array.append(y_val)

        #print x_array
        np_x_array = np.array(x_array)
        np_y_array = np.array(y_array)
        np_x_array.sort()
        np_y_array.sort()
        #print np_x_array
        #print np_y_array
        ###hist = TH1F("try", "try", len(np_x_array)-1, min(np_x_array), max(np_x_array))
        ###hist = hist.Rebin(len(np_x_array)-1,"try",np_x_array)
        h = TH2F("try", labellist[j],
                 len(np_x_array) - 1, np_x_array,
                 len(np_y_array) - 1, np_y_array + 2.5)
        for b in np_y_array:  #[1:]:
            for a in np_x_array:
                #print "ctau looping on: ", a
                #print "mass looping on: ", b
                #print "bin with those ctau and mass: ", h.FindBin(a,b)
                la = str(a)
                lb = str(int(b))
                if la == "0.001":
                    st = signame + "_M" + str(lb) + "_ctau0"
                elif la == "0.05" or la == "0.1":
                    st = signame + "_M" + str(lb) + "_ctau" + str(
                        la.replace("0.", "0p"))
                else:
                    st = signame + "_M" + str(lb) + "_ctau" + str(int(a))
                if st in eff_dict[c].keys():
                    h.SetBinContent(
                        h.FindBin(a, b),
                        float("{0:.4f}".format(eff_dict[c][st]['eff'])))
                    if eff_dict[c][st]['eff'] == 0:
                        h.SetBinContent(h.FindBin(a, b),
                                        float("{0:.4f}".format(0.0001)))
                else:
                    h.SetBinContent(h.FindBin(a, b), float(0.))
                h.GetXaxis().SetTitle("c #tau (mm)")
                h.GetYaxis().SetTitle("m_{#pi} (GeV)")
                h.GetXaxis().SetTitleSize(0.045)
                h.GetYaxis().SetTitleSize(0.045)
                h.GetYaxis().SetNdivisions(len(np_y_array))

        c1 = TCanvas("c1", "Signals", 1200, 600)
        c1.SetLogx()
        c1.cd()
        #c1.GetPad(0).SetTopMargin(0.06)
        #c1.GetPad(0).SetRightMargin(0.05)
        c1.GetPad(0).SetTicks(1, 1)
        ###TGaxis.SetMaxDigits(2)
        h.SetMarkerColor(10)
        if EFFICIENCY:
            h.GetZaxis().SetRangeUser(0., 32)
            h.SetMarkerSize(1.7)
        elif FIDUCIAL_ONLY:
            h.GetZaxis().SetRangeUser(0., 60)
            h.SetMarkerSize(1.7)
        elif TRIGGER_TOP_FIDUCIAL:
            h.GetZaxis().SetRangeUser(0., 70)
            h.SetMarkerSize(1.7)
        else:
            h.GetZaxis().SetRangeUser(0., zmax)
            h.SetMarkerSize(1.35)
            #RATE: max 16500
        #print h.GetZaxis().GetLabelOffset()
        #print h.GetZaxis().GetLabelSize()
        #print h.GetZaxis().SetLabelOffset(1)
        if EFFICIENCY or FIDUCIAL_ONLY or TRIGGER_TOP_FIDUCIAL:
            gStyle.SetPaintTextFormat(".1f")  #(".1e")
        else:
            gStyle.SetPaintTextFormat(".0f")
        stri = h.GetTitle()
        if EFFICIENCY:
            h.SetTitle(
                signame +
                " trigger efficiency times fiducial cut efficiency in " +
                options.dataera + ": " + stri)
        elif FIDUCIAL_ONLY:
            h.SetTitle(signame + " fiducial cut efficiency in " +
                       options.dataera + ": " + stri)
        elif TRIGGER_TOP_FIDUCIAL:
            h.SetTitle(
                signame +
                " trigger efficiency on top of fiducial cut efficiency in " +
                options.dataera + ": " + stri)
        else:
            h.SetTitle(signame + " number of events in " + options.dataera +
                       ": " + stri)
        h.Draw("COLZTEXT")
        if EFFICIENCY:
            c1.Print(
                "$CMSSW_BASE/src/Analyzer/LongLivedReco/macro/Efficiency/Eff_2D_"
                + options.dataera + "_" + str(labellist[j]) + "_" + signame +
                "_v8.pdf")
            c1.Print(
                "$CMSSW_BASE/src/Analyzer/LongLivedReco/macro/Efficiency/Eff_2D_"
                + options.dataera + "_" + str(labellist[j]) + "_" + signame +
                "_v8.png")
        elif FIDUCIAL_ONLY:
            c1.Print(
                "$CMSSW_BASE/src/Analyzer/LongLivedReco/macro/Efficiency/FiducialEff_2D_"
                + options.dataera + "_" + signame + "_v8.pdf")
            c1.Print(
                "$CMSSW_BASE/src/Analyzer/LongLivedReco/macro/Efficiency/FiducialEff_2D_"
                + options.dataera + "_" + signame + "_v8.png")
        elif TRIGGER_TOP_FIDUCIAL:
            c1.Print(
                "$CMSSW_BASE/src/Analyzer/LongLivedReco/macro/Efficiency/TriggerTopFiducialEff_2D_"
                + options.dataera + "_" + str(labellist[j]) + "_" + signame +
                "_v8.pdf")
            c1.Print(
                "$CMSSW_BASE/src/Analyzer/LongLivedReco/macro/Efficiency/TriggerTopFiducialEff_2D_"
                + options.dataera + "_" + str(labellist[j]) + "_" + signame +
                "_v8.png")
        else:
            c1.Print(
                "$CMSSW_BASE/src/Analyzer/LongLivedReco/macro/Efficiency/Rate_2D_"
                + options.dataera + "_" + str(labellist[j]) + "_" + signame +
                "_v8.pdf")
            c1.Print(
                "$CMSSW_BASE/src/Analyzer/LongLivedReco/macro/Efficiency/Rate_2D_"
                + options.dataera + "_" + str(labellist[j]) + "_" + signame +
                "_v8.png")
        c1.Close()
        h.Clear()
예제 #19
0
def main():
    ## print "hello"
    gROOT.SetBatch(1)
    gStyle.SetPaintTextFormat('1.1f')
    output = TFile('diffratio.root', 'recreate')
    c1 = TCanvas('c1', 'c1', 1600, 1200)
    h_MhpassProfile = []
    h_MhfailProfile = []
    h_MhdifProfile = []
    h_MZppassProfile = []
    h_MZpfailProfile = []
    h_MZpdifProfile = []
    for i in range(4):
        h_MhpassProfile.append(
            TH1F('h_MhpassProfile_' + str(i), 'h_MhpassProfile_' + str(i), 25,
                 100, 150))
        h_MhfailProfile.append(
            TH1F('h_MhfailProfile_' + str(i), 'h_MhfailProfile_' + str(i), 25,
                 100, 150))
        h_MhdifProfile.append(
            TH1F('h_MhdifProfile_' + str(i), 'h_MhdifProfile_' + str(i), 25,
                 100, 150))
        h_MhpassProfile[i].Sumw2()
        h_MhfailProfile[i].Sumw2()
        h_MZppassProfile.append(
            TH1F('h_MZppassProfile_' + str(i), 'h_MZppassProfile_' + str(i),
                 20, 500, 2500))
        h_MZpfailProfile.append(
            TH1F('h_MZpfailProfile_' + str(i), 'h_MZpfailProfile_' + str(i),
                 20, 500, 2500))
        h_MZpdifProfile.append(
            TH1F('h_MZpdifProfile_' + str(i), 'h_MZpdifProfile_' + str(i), 20,
                 500, 2500))
        h_MZppassProfile[i].Sumw2()
        h_MZpfailProfile[i].Sumw2()
    h_pass = TH2F('h_MhMZp_pass', 'h_MhMZp_pass', 25, 100, 150, 20, 500, 2500)
    h_pass.Sumw2()
    h_alphabet = TH2F('h_MhMZp_alphabet', 'h_MhMZp_alphabet', 25, 100, 150, 20,
                      500, 2500)
    h_alphabet.Sumw2()
    h_dif_alphabet = TH2F('h_dif_alphabet', 'h_dif_alphabet', 25, 100, 150, 20,
                          500, 2500)
    h_dif_alphabet.Sumw2()
    h_SB = TH2F('h_MA0hPt_SB', 'h_MA0hPt_SB', 20, 200, 1000, 25, 0,
                500)  ## MA0 vs hPt
    h_SB.Sumw2()
    h_bk = TH2F('h_MA0hPt_bk', 'h_MA0hPt_bk', 20, 200, 1000, 25, 0, 500)
    h_bk.Sumw2()
    h_dif = TH2F('h_dif', 'h_dif', 20, 200, 1000, 25, 0, 500)
    h_dif.Sumw2()
    h_SB_MhPt = TH2F('h_SB_MhPt', 'h_SB_MhPt', 25, 100, 150, 25, 0, 500)
    h_SB_MhPt.Sumw2()
    h_bk_MhPt = TH2F('h_bk_MhPt', 'h_bk_MhPt', 25, 100, 150, 25, 0, 500)
    h_bk_MhPt.Sumw2()
    h_dif_MhPt = TH2F('h_dif_MhPt', 'h_dif_MhPt', 25, 100, 150, 25, 0, 500)
    h_dif_MhPt.Sumw2()
    h_SB_MhMA0 = TH2F('h_SB_MhMA0', 'h_SB_MhMA0', 25, 100, 150, 20, 200, 1000)
    h_SB_MhMA0.Sumw2()
    h_bk_MhMA0 = TH2F('h_bk_MhMA0', 'h_bk_MhMA0', 25, 100, 150, 20, 200, 1000)
    h_bk_MhMA0.Sumw2()
    h_dif_MhMA0 = TH2F('h_dif_MhMA0', 'h_dif_MhMA0', 25, 100, 150, 20, 200,
                       1000)
    h_dif_MhMA0.Sumw2()
    h_SB_Mh = TH1F('h_SB_Mh', 'h_SB_Mh', 25, 100, 150)
    h_SB_Mh.Sumw2()
    h_bk_Mh = TH1F('h_bk_Mh', 'h_bk_Mh', 25, 100, 150)
    h_bk_Mh.Sumw2()
    h_SB_MA0 = TH1F('h_SB_MA0', 'h_SB_MA0', 40, 200, 1000)
    h_SB_MA0.Sumw2()
    h_bk_MA0 = TH1F('h_bk_MA0', 'h_bk_MA0', 40, 200, 1000)
    h_bk_MA0.Sumw2()
    h_SB_MZp = TH1F('h_SB_MZp', 'h_SB_MZp', 20, 500, 2500)
    h_SB_MZp.Sumw2()
    h_bk_MZp = TH1F('h_bk_MZp', 'h_bk_MZp', 20, 500, 2500)
    h_bk_MZp.Sumw2()
    h_SB_hPt = TH1F('h_SB_hPt', 'h_SB_hPt', 50, 0, 500)
    h_SB_hPt.Sumw2()
    h_bk_hPt = TH1F('h_bk_hPt', 'h_bk_hPt', 50, 0, 500)
    h_bk_hPt.Sumw2()
    h_dif_MA0 = TH1F('h_dif_MA0', 'h_dif_MA0', 40, 200, 1000)
    h_dif_MA0.Sumw2()
    h_dif_Mh = TH1F('h_dif_Mh', 'h_dif_Mh', 25, 100, 150)
    h_dif_Mh.Sumw2()
    h_dif_MZp = TH1F('h_dif_MZp', 'h_dif_MZp', 20, 500, 2500)
    h_dif_MZp.Sumw2()
    h_dif_hPt = TH1F('h_dif_hPt', 'h_dif_hPt', 50, 0, 500)
    h_dif_hPt.Sumw2()
    f = TFile('../data/ALLBTagCSV-Run2016_tree.root')
    myTree = f.tree
    # print myTree.GetEntries()
    for en in range(myTree.GetEntries()):
        if (not en % 10000): print en, 'of ', myTree.GetEntries()
        myTree.GetEntry(en)
        # print en, myTree.Mh, myTree.MZp
        #print en, myTree.isTag, myTree.isAntiTag
        if (en >= 1000 and len(sys.argv) >= 2): break
        ## skip signal
        np = int((myTree.MZp - 500) // 500)
        if (myTree.Mh > 136): nq = 3
        elif (myTree.Mh < 114): nq = 0
        if (myTree.isTag and myTree.Mh < 136 and myTree.Mh > 114): continue
        elif (myTree.isTag):
            h_SB.Fill(myTree.MZp, myTree.hPt)
            h_pass.Fill(myTree.Mh, myTree.MZp)
            h_SB_MhPt.Fill(myTree.Mh, myTree.hPt)
            h_SB_MhMA0.Fill(myTree.Mh, myTree.MA0)
            h_SB_MA0.Fill(myTree.MA0)
            h_SB_hPt.Fill(myTree.hPt)
            h_SB_Mh.Fill(myTree.Mh)
            h_SB_MZp.Fill(myTree.MZp)
            if (np < 4 and np >= 0): h_MhpassProfile[np].Fill(myTree.Mh)
            if (nq < 4 and nq >= 0): h_MZppassProfile[nq].Fill(myTree.MZp)
        elif (myTree.isAntiTag):
            weight = R_pass_fail(MhTrans(myTree.Mh), ZpTrans(myTree.MZp))
            if (weight < 0): print 'error', en, weight
            h_bk.Fill(myTree.MZp, myTree.hPt, weight)
            h_alphabet.Fill(myTree.Mh, myTree.MZp, weight)
            h_bk_MhPt.Fill(myTree.Mh, myTree.hPt, weight)
            h_bk_MhMA0.Fill(myTree.Mh, myTree.MA0, weight)
            h_bk_MA0.Fill(myTree.MA0, weight)
            h_bk_Mh.Fill(myTree.Mh, weight)
            h_bk_MZp.Fill(myTree.MZp, weight)
            h_bk_hPt.Fill(myTree.hPt, weight)
            if (np < 4 and np >= 0):
                h_MhfailProfile[np].Fill(myTree.Mh, weight)
            if (nq < 4 and nq >= 0):
                h_MZpfailProfile[nq].Fill(myTree.MZp, weight)

    h_dif_alphabet.Divide(h_alphabet, h_pass)
    h_dif.Divide(h_bk, h_SB)
    h_dif_MA0.Divide(h_bk_MA0, h_SB_MA0)
    h_dif_Mh.Divide(h_bk_Mh, h_SB_Mh)
    h_dif_MZp.Divide(h_bk_MZp, h_SB_MZp)
    h_dif_hPt.Divide(h_bk_hPt, h_SB_hPt)
    h_dif_MhPt.Divide(h_bk_MhPt, h_SB_MhPt)
    h_dif_MhMA0.Divide(h_bk_MhMA0, h_SB_MhMA0)
    for i in range(4):
        h_MhdifProfile[i].Divide(h_MhpassProfile[i], h_MhfailProfile[i])
    for i in range(4):
        h_MZpdifProfile[i].Divide(h_MZppassProfile[i], h_MZpfailProfile[i])
    pdfName = 'diff.pdf'
    c1.Print(pdfName + '[')
    ## gPad.SetLogz()
    h_dif_alphabet.SetMaximum(5.)
    h_dif_alphabet.SetMinimum(0.1)
    h_dif_alphabet.GetZaxis().SetRangeUser(0.1, 10)
    h_dif_alphabet.Draw('colz text')
    c1.Print(pdfName)
    h_dif_alphabet.Draw('surf2z')
    c1.Print(pdfName)
    h_dif.Draw('colz text')
    c1.Print(pdfName)
    h_dif.Draw('surf2z')
    c1.Print(pdfName)
    h_dif_MhPt.Draw('colz text')
    c1.Print(pdfName)
    h_dif_MhPt.Draw('surf2z')
    c1.Print(pdfName)
    h_dif_MhMA0.Draw('colz text')
    c1.Print(pdfName)
    h_dif_MhMA0.Draw('surf2z')
    c1.Print(pdfName)
    gPad.SetLogz(0)
    h_dif_Mh.Draw('e')
    c1.Print(pdfName)
    h_SB_MA0.Draw('e')
    c1.Print(pdfName)
    h_bk_MA0.Draw('e')
    c1.Print(pdfName)
    h_dif_MA0.Draw('e')
    c1.Print(pdfName)
    h_SB_MZp.Draw('e')
    c1.Print(pdfName)
    h_bk_MZp.Draw('e')
    c1.Print(pdfName)
    h_dif_MZp.Draw('e')
    c1.Print(pdfName)
    h_SB_hPt.Draw('e')
    c1.Print(pdfName)
    h_bk_hPt.Draw('e')
    c1.Print(pdfName)
    h_dif_hPt.Draw('e')
    c1.Print(pdfName)
    for i in range(4):
        h_MhdifProfile[i].Draw('e')
        c1.Print(pdfName)

    for i in range(4):
        h_MZpdifProfile[i].Draw('e')
        c1.Print(pdfName)
    output.Write()

    c1.Print(pdfName + ']')
    print "event", h_bk_Mh.Integral(), h_SB_Mh.Integral()
    print "Mh  event ratio: ", h_bk_Mh.Integral() / h_SB_Mh.Integral()
예제 #20
0
def eff_2D(cutlist, labellist=[], zmax=30, pal=109):
    print "Ntuples:\n"
    print NTUPLEDIR

    basecut = BASECUT
    if not EFFICIENCY:
        print "basecut considered: ", basecut
    signame = ""
    ncuts = len(cutlist)
    if labellist == []:
        labellist=cutlist
        gStyle.SetPalette(87)#87:light temperature #104 temperature map #69:beach(!) #70:black body #86:lake #109:cool(!)
    else:
        gStyle.SetPalette(pal)#87:light temperature #104 temperature map #69:beach(!) #70:black body #86:lake #109:cool(!)

    file = {}
    nevt = {}
    tree = {}
    effs = {}
    eff_dict = { k:{} for k in cutlist}
    #print eff_dict
    sign = sign_ctau
    XSEC = 0

    for i, s in enumerate(sign):
        if 'WplusH' in samples[s]['files'][0]:
            signame = "WplusH"
            XSEC = WpluslnuHXSEC
        elif 'WminusH' in samples[s]['files'][0]:
            signame = "WminusH"
            XSEC = WminuslnuHXSEC
        elif 'ZH' in samples[s]['files'][0] and not 'ggZH' in samples[s]['files'][0]:
            signame = "ZH"
            XSEC = ZllHXSEC
        elif 'ggZH' in samples[s]['files'][0]:
            signame = "ggZH"
            XSEC = ggZHXSEC
        elif 'VBF' in samples[s]['files'][0]:
            signame = "VBFH"
            XSEC = VBFXSEC
        elif 'QCD' in samples[s]['files'][0]:
            signame = "QCD"
            XSEC = samples[s]['xsec']
            #print s, samples[s]['xsec']
        elif 'GluGlu' in samples[s]['files'][0]:
            signame = "ggH"
            XSEC = 1.
            #print s, samples[s]['xsec']
        file[s] = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ") # Read TFile

        if EFFICIENCY or FIDUCIAL_ONLY or TRIGGER_TOP_FIDUCIAL or TRIGGER_TIMES_FIDUCIAL:
            XSEC = 100./LUMI
        #print file[s]
        ##nevt[s] = (file[s].Get('counter/c_nEvents')).GetBinContent(1)
        #tree[s] = file[s].Get("reconstruction/tree") # Read TTree
        #nevt[s] = file[s].Get("reconstruction/tree").GetEntriesFast()
        tree[s] = file[s].Get("ntuple/tree") # Read TTree
        nevt[s] = (file[s].Get('counter/c_nEvents')).GetBinContent(1)
        if verbose:
            print "nevt: ", tree[s].GetEntries()
            print "nevt after basecut: ", tree[s].GetEntries(basecut)
        effs[s] = [0]*(ncuts+1)
        for j, c in enumerate(cutlist):
            br = 1.
            if FIDUCIAL_ONLY:
                tot_gen = (file[s].Get('counter/c_nEvents')).GetBinContent(1)
                n = tree[s].GetEntries(basecut)
                if verbose:
                    print "den: ", tot_gen
                    print "num: ", n
            elif TRIGGER_TOP_FIDUCIAL: 
                tot_gen = tree[s].GetEntries(basecut)
                n = tree[s].GetEntries("(" + cutlist[j] + ")" + " && " + basecut)
                if verbose:
                    print "den: ", tree[s].GetEntries(basecut)
                    print "evt passing trigger: ", tree[s].GetEntries(cutlist[j])
                    print "num: ", tree[s].GetEntries("(" + cutlist[j] + ")" + " && " + basecut)
            elif TRIGGER_TIMES_FIDUCIAL:
                tot_gen = (file[s].Get('counter/c_nEvents')).GetBinContent(1)
                n = tree[s].GetEntries("(" + cutlist[j] + ")" + " && " + basecut)
                if verbose:
                    print "den: ", tot_gen
                    print "num: ", n
            elif EFFICIENCY:
                tot_gen = (file[s].Get('counter/c_nEvents')).GetBinContent(1)
                n = tree[s].GetEntries("(" + cutlist[j] + ")")
                if verbose:
                    print "den: ", tot_gen
                    print "num: ", n
            else:
                tot_gen = (file[s].Get('counter/c_nEvents')).GetBinContent(1)
                n = tree[s].GetEntries("(" + cutlist[j] + ")" + " && " + basecut)
                if verbose:
                    print "den: ", tot_gen
                    print "num: ", n
            #exit()
            #d = tree[s].GetEntries(basecut)#nevt[s]#d = sample[samples[s]['files'][0]]['nevents']#
            effs[s][j] = (float(n)/(tot_gen)) * XSEC * LUMI
            eff_dict[c][s] = {'mass' : samples[s]['mass'], 'ctau' : samples[s]['ctau'], 'eff' :effs[s][j]}
            ###########
    x_array = [50000]
    y_array = [10]
    if options.mode == "QCD":
        y_array=[300]
    for j, c in enumerate(cutlist):
        for i, s in enumerate(sign):
            x_val = (samples[s]['ctau'])
            y_val = float(samples[s]['mass'])
            if x_val not in x_array: x_array.append(x_val)
            if y_val not in y_array: y_array.append(y_val)
        #if 35 not in y_array:
        #    print "FIXME! Just because we have few mass points!!!"
        #    y_array.append(35)

        #print x_array
        np_x_array = np.array(x_array)
        np_y_array = np.array(y_array)
        np_x_array.sort()
        np_y_array.sort()
        if options.mode == "VBFH":
            h = TH2F("try", labellist[j], len(np_x_array)-1,np_x_array, len(np_y_array)-1,np_y_array+2.5)
        elif options.mode == "ggH":
            h = TH2F("try", labellist[j], len(np_x_array)-1,np_x_array, len(np_y_array)-1,np_y_array+2.5)
        else:
            h = TH2F("try", labellist[j], len(np_x_array)-1,np_x_array, len(np_y_array)-1,np_y_array)
        for b in np_y_array:#[1:]:
            for a in np_x_array:
                #print "ctau looping on: ", a
                #print "mass looping on: ", b
                #print "bin with those ctau and mass: ", h.FindBin(a,b)
                la=str(a)
                lb=str(int(b))
                if signame=="VBFH":
                    if la== "0.001":
                        st = signame+"_M"+str(lb)+"_ctau0"
                    elif la=="0.05" or la=="0.1":
                        st = signame+"_M"+str(lb)+"_ctau"+str(la.replace("0.","0p"))
                    else:
                        st = signame+"_M"+str(lb)+"_ctau"+str(int(a))
                elif signame=="ggH":
                    if la== "0.001":
                        st = signame+"_M"+str(lb)+"_ctau0"
                    elif la=="0.05" or la=="0.1":
                        st = signame+"_M"+str(lb)+"_ctau"+str(la.replace("0.","0p"))
                    else:
                        st = signame+"_M"+str(lb)+"_ctau"+str(int(a))
                elif signame=="QCD":
                    if b==50:
                        st = "QCD_HT50to100"
                    elif b==100:
                        st = "QCD_HT100to200"
                    elif b==200:
                        st = "QCD_HT200to300"
                if st in eff_dict[c].keys():
                    h.SetBinContent(h.FindBin(a,b),float("{0:.4f}".format(eff_dict[c][st]['eff'])))
                    if eff_dict[c][st]['eff'] == 0:
                        h.SetBinContent(h.FindBin(a,b),float("{0:.4f}".format(0.0001)))
                else:
                    h.SetBinContent(h.FindBin(a,b),float(0.))
                h.GetXaxis().SetTitle("c #tau (mm)")
                h.GetYaxis().SetTitle("m_{#pi} (GeV)")
                h.GetXaxis().SetTitleSize(0.045)
                h.GetYaxis().SetTitleSize(0.045)
                if not options.mode=="QCD":
                    h.GetYaxis().SetNdivisions(len(np_y_array));
                if options.mode=="QCD":
                    h.GetXaxis().SetTitle("")
                    h.GetYaxis().SetTitle("H_{T} (GeV)")
                    h.GetXaxis().SetTitleSize(0)
                    h.GetXaxis().SetLabelSize(0)
                    h.GetYaxis().SetRangeUser(50,300)

        c1 = TCanvas("c1", "Signals", 1200, 600)
        if not options.mode=="QCD":
            c1.SetLogx()
        c1.cd()
        #c1.GetPad(0).SetTopMargin(0.06)
        #c1.GetPad(0).SetRightMargin(0.05)
        c1.GetPad(0).SetTicks(1, 1)
        ###TGaxis.SetMaxDigits(2)
        h.SetMarkerColor(10)
        if EFFICIENCY or TRIGGER_TIMES_FIDUCIAL:
            h.GetZaxis().SetRangeUser(0., 32)
            h.SetMarkerSize(1.7)
        elif FIDUCIAL_ONLY:
            h.GetZaxis().SetRangeUser(0., 60)
            h.SetMarkerSize(1.7)
        elif TRIGGER_TOP_FIDUCIAL:
            h.GetZaxis().SetRangeUser(0., 70)
            h.SetMarkerSize(1.7)
        else:
            h.GetZaxis().SetRangeUser(0., zmax)
            h.SetMarkerSize(1.35)
            #RATE: max 16500
        #print h.GetZaxis().GetLabelOffset()
        #print h.GetZaxis().GetLabelSize()
        #print h.GetZaxis().SetLabelOffset(1)
        if EFFICIENCY or FIDUCIAL_ONLY or TRIGGER_TOP_FIDUCIAL or TRIGGER_TIMES_FIDUCIAL:
            gStyle.SetPaintTextFormat(".1f")#(".1e")
            if options.mode == "QCD":
                gStyle.SetPaintTextFormat(".3f")#(".1e")
        else:
            gStyle.SetPaintTextFormat(".0f")
        stri = h.GetTitle()
        if EFFICIENCY:
            h.SetTitle(signame+" trigger efficiency in " +options.dataera+ ": "+stri)
        elif TRIGGER_TIMES_FIDUCIAL:
            h.SetTitle(signame+" trigger efficiency times fiducial cut efficiency in " +options.dataera+ ": "+stri)
        elif FIDUCIAL_ONLY:
            h.SetTitle(signame+" fiducial cut efficiency in " +options.dataera+ ": "+stri)
        elif TRIGGER_TOP_FIDUCIAL:
            h.SetTitle(signame+" trigger efficiency on top of fiducial cut efficiency in " +options.dataera+ ": "+stri)
        else:
            h.SetTitle(signame+" number of events in " +options.dataera+ ": "+stri)
        h.Draw("COLZTEXT")
        if EFFICIENCY:
            c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/EffStandalone_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.pdf")
            c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/EffStandalone_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.png")
        elif TRIGGER_TIMES_FIDUCIAL:
            c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/Eff_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.pdf")
            c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/Eff_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.png")
        elif FIDUCIAL_ONLY:
            c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/FiducialEff_2D_"+options.dataera+"_"+plot_label+"_v5.pdf")
            c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/FiducialEff_2D_"+options.dataera+"_"+plot_label+"_v5.png")
        elif TRIGGER_TOP_FIDUCIAL:
            c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/TriggerTopFiducialEff_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.pdf")
            c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/TriggerTopFiducialEff_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.png")
        else:
            if BASECUT == "isMC":
                c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/RateNoFiducial_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.pdf")
                c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/RateNoFiducial_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.png")
            else:
                if "isVBF" in BASECUT:
                    c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/RateVBF_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.pdf")
                    c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/RateVBF_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.png")
                else:
                    c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/Rate_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.pdf")
                    c1.Print("$CMSSW_BASE/src/Analyzer/LLP/macro/Efficiency/Rate_2D_"+options.dataera+"_"+str(labellist[j])+"_"+plot_label+"_v5.png")
        c1.Close()
        h.Clear()
def plot_2D():

  myfile = TFile(args.inputFile)

  mytree = gDirectory.Get("physics")
  mytree_weight = mytree.GetWeight()/1e3

  trig_dec  = "( passHLT == 1 )"
  lep_tag_trigmatch = "( lep_tag_isTrigMatched[0] == 1 && ( ( lep_tag_flavour[0] == 11 && lep_tag_pt[0] > 25e3 ) || ( lep_tag_flavour[0] == 13 && lep_tag_pt[0] > 22e3 ) ) )"
  lep_probe_trigmatch = "( lep_probe_isTrigMatched[0] == 1 && ( ( lep_probe_flavour[0] == 11 && lep_probe_pt[0] > 25e3 ) || ( lep_probe_flavour[0] == 13 && lep_probe_pt[0] > 22e3 ) ) )"
  el_tag_eta   = "( TMath::Abs(el_tag_eta[0]) < 1.37 )"
  nbjets       = "( njets_mv2c20_Fix77 > 0 )"
  njets        = "( njets > 0 && njets < 4 )"
  nleptons     = "( nlep == 2 && ( lep_pt[0] > 20e3 && lep_pt[1] > 20e3 ) )"
  same_sign    = "( isSS01 == 1 )"
  # veto charge flips
  #
  ch_flip_veto = "( 1 )"
  if args.doChFlipVeto:
     ch_flip_veto = "( lep_isChFlip[0] == 0 && lep_isChFlip[1] == 0 )"
  # require at least 1 !prompt lepton
  #
  non_prompt   = "( ( lep_truthType[0] != 6 && lep_truthType[0] != 2 ) || ( lep_truthType[1] != 6 && lep_truthType[1] != 2 ) )"
  # require at least one T lepton in the event
  #
  is_tight_event = "1" #"( isNonTightEvent == 0 )"
  # require tag lepton to be T
  #
  tight_tag   = "( lep_tag_isTightSelected[0] == 1 )"

  hist_list_tag_MUPROBEEVT = {}
  hist_list_tag_ELPROBEEVT = {}

  set_fancy_2D_style()

  gStyle.SetPaintTextFormat("2.1f")

  # -----------------------------------------------------

  dirname = "OutputPlots_TRUTH"
  if args.outdirname:
     dirname += ( "_" + args.outdirname )

  try:
      os.makedirs(dirname)
  except:
      pass

  # -----------------------------------------------------

  # ----------------
  #    Muon probe
  # ----------------

  sel_FAKE_MUPROBEEVT_T = None

  # look only at OF region
  if args.channel == "OF":
    sel_FAKE_MUPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( (nmuon == 1 && nel == 1) && ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 1 ) )" + " && " + el_tag_eta + " && " + nbjets + " && " + njets  + " && " + ch_flip_veto + " && " + non_prompt + ")"
  # look only at SF region
  elif args.channel == "SF":
    sel_FAKE_MUPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( ( nmuon == 2 ) && ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 1 ) )" + " && " + nbjets + " && " + njets + " && " + ch_flip_veto + " && " + non_prompt + ")"

  print "sel_FAKE_MUPROBEEVT_T: \n", sel_FAKE_MUPROBEEVT_T

  # histograms for tag (passing T: default)
  #
  h_taglep_FAKE_MUPROBEEVT_T_pt = TH2D("taglep_FAKE_MUPROBEEVT_T_pt", "taglep_FAKE_MUPROBEEVT_T_pt", 30, 20.0, 200.0, 30, 20.0, 200.0)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_pt] = ["T","pt"]
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt = TH2D("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", 20, 0.0, 0.1, 20, 0.0, 0.1)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt] = ["T","ptvarcone30_over_pt"]
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt = TH2D("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", 20, 0.0, 0.1, 20, 0.0, 0.1)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt] = ["T","ptvarcone20_over_pt"]
  h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt = TH2D("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", 20, -0.1, 0.1, 20, -0.1, 0.1)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt] = ["T","topoetcone20_over_pt"]

  h_taglep_FAKE_MUPROBEEVT_T_pt.GetXaxis().SetTitle("REAL pT [GeV]")
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt.GetXaxis().SetTitle("REAL ptvarcone30/pT")
  h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt.GetXaxis().SetTitle("REAL topoetcone20/pT")
  h_taglep_FAKE_MUPROBEEVT_T_pt.GetYaxis().SetTitle("FAKE pT [GeV]")
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt.GetYaxis().SetTitle("FAKE ptvarcone30/pT")
  h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt.GetYaxis().SetTitle("FAKE topoetcone20/pT")

  if args.channel == "OF":
     # probe is muon, tag is electron
     #
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_pt", "muon_probe_pt[0]/1e3:el_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "muon_probe_ptvarcone30[0]/muon_probe_pt[0]:el_tag_ptvarcone30[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "muon_probe_ptvarcone20[0]/muon_probe_pt[0]:el_tag_ptvarcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "muon_probe_topoetcone20[0]/muon_probe_pt[0]:el_tag_topoetcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
  elif args.channel == "SF":
     # probe is muon, tag is muon
     #
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_pt", "muon_probe_pt[0]/1e3:muon_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "muon_probe_ptvarcone30[0]/muon_probe_pt[0]:muon_tag_ptvarcone30[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
#     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "muon_probe_ptvarcone20[0]/muon_probe_pt[0]:muon_tag_ptvarcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "muon_probe_topoetcone20[0]/muon_probe_pt[0]:muon_tag_topoetcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )


  # Normalise to unity
  if args.doNorm:
     for hist in hist_list_tag_MUPROBEEVT.keys():
	if hist.Integral() == 0:
	  continue
        hist.Scale(1/hist.Integral())

  # now plot
  #
  print "\tLooking at events where the PROBE is: {0} and the channel is {1}\n".format("MUON", args.channel)
  for  hist_tag in hist_list_tag_MUPROBEEVT.keys():

     c = TCanvas("c","Temp",50,50,900,900)

     legend_T = TLegend(0.4,0.8,0.6,0.85); # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
     legend_T.SetHeader("2 Lep SS Fake CR - T probe")
     legend_T.SetBorderSize(0)  # no border
     legend_T.SetFillColor(0) # Legend background should be white
     legend_T.SetTextSize(0.04) # Increase entry font size!
     legend_T.SetTextFont(42) # Helvetica

     var_tag    = hist_list_tag_MUPROBEEVT[hist_tag][1]
     type_tag   = hist_list_tag_MUPROBEEVT[hist_tag][0]

     print "\tPlotting variable: {0}\n".format(var_tag)

     print "\ttag histogram name: {0}\n".format(hist_tag.GetName())

     hist_tag.Draw("colz")

     legend_T.Draw()
     plotname = dirname + "/FAKE_MUPROBEEVT_" + var_tag
     c.SaveAs(plotname+".png")

     del c

  # -----------------------------------------------------

  # ---------------------
  #    Electron probe
  # ---------------------

  sel_FAKE_ELPROBEEVT_T = None

  # look only at OF region
  if args.channel == "OF":
    sel_FAKE_ELPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( (nmuon == 1 && nel == 1) && ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 1 ) )" + " && " + nbjets + " && " + njets + " && "  + ch_flip_veto + " && " + non_prompt + ")"
  # look only at SF region
  elif args.channel == "SF":
    sel_FAKE_ELPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( ( nel == 2 ) && ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 1 ) )" + " && " + el_tag_eta + " && " + nbjets + " && " + njets + " && "  + ch_flip_veto + " && " + non_prompt + ")"

  print "sel_FAKE_ELPROBEEVT_T: \n", sel_FAKE_ELPROBEEVT_T

  # histograms for tag (passing T: default)
  #
  h_taglep_FAKE_ELPROBEEVT_T_pt = TH2D("taglep_FAKE_ELPROBEEVT_T_pt", "taglep_FAKE_ELPROBEEVT_T_pt", 30, 20.0, 200.0, 30, 20.0, 200.0)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_pt] = ["T","pt"]
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt = TH2D("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", 20, 0.0, 0.1, 20, 0.0, 0.1)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt] = ["T","ptvarcone30_over_pt"]
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt = TH2D("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", 20, 0.0, 0.1, 20, 0.0, 0.1)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt] = ["T","ptvarcone20_over_pt"]
  h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt = TH2D("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", 20, -0.1, 0.1, 20, -0.1, 0.1)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt] = ["T","topoetcone20_over_pt"]

  h_taglep_FAKE_ELPROBEEVT_T_pt.GetXaxis().SetTitle("REAL pT [GeV]")
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt.GetXaxis().SetTitle("REAL ptvarcone20/pT")
  h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt.GetXaxis().SetTitle("REAL topoetcone20/pT")
  h_taglep_FAKE_ELPROBEEVT_T_pt.GetYaxis().SetTitle("FAKE pT [GeV]")
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt.GetYaxis().SetTitle("FAKE ptvarcone20/pT")
  h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt.GetYaxis().SetTitle("FAKE topoetcone20/pT")

  if args.channel == "OF":
     # probe is el, tag is muon
     #
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_pt", "el_probe_pt[0]/1e3:muon_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "el_probe_ptvarcone30[0]/el_probe_pt[0]:muon_tag_ptvarcone30[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "el_probe_ptvarcone20[0]/el_probe_pt[0]:muon_tag_ptvarcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "el_probe_topoetcone20[0]/el_probe_pt[0]:muon_tag_topoetcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
  elif args.channel == "SF":
     # probe is el, tag is el
     #
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_pt", "el_probe_pt[0]/1e3:el_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     #mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "el_probe_ptvarcone30[0]/el_probe_pt[0]:el_tag_ptvarcone30[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "el_probe_ptvarcone20[0]/el_probe_pt[0]:el_tag_ptvarcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "el_probe_topoetcone20[0]/el_probe_pt[0]:el_tag_topoetcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )


  # Normalise to unity
  if args.doNorm:
     for hist in hist_list_tag_ELPROBEEVT.keys():
	if hist.Integral() == 0:
	  continue
        hist.Scale(1/hist.Integral())

  # now plot
  #
  print "\tLooking at events where the PROBE is: {0} and the channel is {1}\n".format("ELECTRON", args.channel)
  for  hist_tag in hist_list_tag_ELPROBEEVT.keys():

     c = TCanvas("c","Temp",50,50,900,900)

     legend_T = TLegend(0.4,0.8,0.6,0.85); # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
     legend_T.SetHeader("2 Lep SS Fake CR - T probe")
     legend_T.SetBorderSize(0)  # no border
     legend_T.SetFillColor(0) # Legend background should be white
     legend_T.SetTextSize(0.04) # Increase entry font size!
     legend_T.SetTextFont(42) # Helvetica

     var_tag    = hist_list_tag_ELPROBEEVT[hist_tag][1]
     type_tag   = hist_list_tag_ELPROBEEVT[hist_tag][0]

     print "\tPlotting variable: {0}\n".format(var_tag)

     print "\ttag histogram name: {0}\n".format(hist_tag.GetName())

     hist_tag.Draw("colz")

     legend_T.Draw()
     plotname = dirname + "/FAKE_ELPROBEEVT_" + var_tag
     c.SaveAs(plotname+".png")

     del c
예제 #22
0
def plot_2D(sign,
            var,
            nbins=50,
            minimum=0,
            maximum=2000,
            bins=np.array([]),
            filename="",
            string="",
            part_var="GenBquarks",
            particle="#pi",
            norm=False):
    chain = {}
    hist = {}
    r_ecal = 129
    r_hcal = 179
    r_magnet = 295
    r_mb1 = 402
    r_mb4 = 738

    z_ecal = 300
    z_hcal = 376
    z_magnet = 0
    z_mb1 = 560

    if var == "radius2D":
        v_ecal = TLine(r_ecal, minimum, r_ecal, maximum)
        v_hcal = TLine(r_hcal, minimum, r_hcal, maximum)
        v_magnet = TLine(r_magnet, minimum, r_magnet, maximum)
        v_mb1 = TLine(r_mb1, minimum, r_mb1, maximum)
        v_mb4 = TLine(r_mb4, minimum, r_mb4, maximum)
        h_ecal = TLine(minimum, r_ecal, maximum, r_ecal)
        h_hcal = TLine(minimum, r_hcal, maximum, r_hcal)
        h_magnet = TLine(minimum, r_magnet, maximum, r_magnet)
        h_mb1 = TLine(minimum, r_mb1, maximum, r_mb1)
        h_mb4 = TLine(minimum, r_mb4, maximum, r_mb4)
    elif var == "z":
        v_ecal = TLine(z_ecal, minimum, z_ecal, maximum)
        v_hcal = TLine(z_hcal, minimum, z_hcal, maximum)
        v_magnet = TLine(z_magnet, minimum, z_magnet, maximum)
        v_mb1 = TLine(z_mb1, minimum, z_mb1, maximum)
        h_ecal = TLine(minimum, z_ecal, maximum, z_ecal)
        h_hcal = TLine(minimum, z_hcal, maximum, z_hcal)
        h_magnet = TLine(minimum, z_magnet, maximum, z_magnet)
        h_mb1 = TLine(minimum, z_mb1, maximum, z_mb1)
    else:
        v_ecal = TLine(r_ecal, minimum, r_ecal, maximum)
        v_hcal = TLine(r_hcal, minimum, r_hcal, maximum)
        v_magnet = TLine(r_magnet, minimum, r_magnet, maximum)
        v_mb1 = TLine(r_mb1, minimum, r_mb1, maximum)
        v_mb4 = TLine(r_mb4, minimum, r_mb4, maximum)
        h_ecal = TLine(minimum, r_ecal, maximum, r_ecal)
        h_hcal = TLine(minimum, r_hcal, maximum, r_hcal)
        h_magnet = TLine(minimum, r_magnet, maximum, r_magnet)
        h_mb1 = TLine(minimum, r_mb1, maximum, r_mb1)
        h_mb4 = TLine(minimum, r_mb4, maximum, r_mb4)

    v_ecal.SetLineColor(2)
    h_ecal.SetLineColor(2)
    v_hcal.SetLineColor(881)
    h_hcal.SetLineColor(881)
    v_magnet.SetLineColor(1)
    h_magnet.SetLineColor(1)
    v_mb1.SetLineColor(801)
    v_mb4.SetLineColor(4)
    h_mb1.SetLineColor(801)
    h_mb4.SetLineColor(4)

    v_ecal.SetLineWidth(4)
    h_ecal.SetLineWidth(4)
    v_hcal.SetLineWidth(4)
    h_hcal.SetLineWidth(4)
    v_magnet.SetLineWidth(4)
    h_magnet.SetLineWidth(4)
    v_mb1.SetLineWidth(4)
    h_mb1.SetLineWidth(4)
    v_mb4.SetLineWidth(3)
    h_mb4.SetLineWidth(3)

    v_ecal.SetLineStyle(3)
    h_ecal.SetLineStyle(3)
    v_hcal.SetLineStyle(2)
    h_hcal.SetLineStyle(2)
    v_magnet.SetLineStyle(4)
    h_magnet.SetLineStyle(4)
    v_mb1.SetLineStyle(8)
    h_mb1.SetLineStyle(8)
    v_mb4.SetLineStyle(9)
    h_mb4.SetLineStyle(9)

    leg = TLegend(1 - 0.9, 0.75, 1 - 0.75, 0.9)
    leg.AddEntry(v_ecal, "ECAL", "L")
    leg.AddEntry(v_hcal, "HCAL", "L")
    leg.AddEntry(v_magnet, "solenoid", "L")
    leg.AddEntry(v_mb1, "MB1", "L")
    leg.AddEntry(v_mb4, "MB4", "L")

    #pal= 68 #kAvocado
    #pal= 64 #kAquamarine, very readable
    #pal= 75 #kCherry 75, awful
    #pal= 85 #kIsland 85, not beautiful but readable
    #pal= 86 #kLake 86, too violet
    #pal= 87 #kLightTemperature 87, used for trigger
    #pal= 91 #kPastel 91, too purple
    #pal= 100 #kSolar 100, very red and orange
    pal = 98  #kSandyTerrain 98, quite fine
    #pal= 99 #kSienna 99, a bit hard to read
    gStyle.SetPalette(pal)
    gStyle.SetPaintTextFormat(".f")

    if part_var == "GenBquarks":
        cutstring = "isMC"
        cutstring = "(EventWeight * PUReWeight) * ( (HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v) && nMuonsPassing==0 && nElectronsPassing==0 && nPhotonsPassing==0 && nTausPassing==0 && MEt.pt>200 )"
        #cutstring = "(EventWeight * PUReWeight) * (HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v && MEt.pt>200 && nMuonsPassing==0 && nElectronsPassing==0 && nPhotonsPassing==0 && nTausPassing==0)"
        #cutstring = "(EventWeight * PUReWeight)"
    #else:
    #    cutstring = "(EventWeight * PUReWeight) * ( (HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v && Flag2_globalSuperTightHalo2016Filter && Flag2_goodVertices && Flag2_EcalDeadCellTriggerPrimitiveFilter && Flag2_HBHENoiseFilter && Flag2_HBHEIsoNoiseFilter && Flag2_ecalBadCalibFilter && Flag2_eeBadScFilter && Flag2_BadPFMuonFilter) && nMuonsPassing==0 && nElectronsPassing==0 && nPhotonsPassing==0 && nTausPassing==0 && MEt.pt>200 )"

    for i, s in enumerate(sign):
        chain[s] = TChain("tree")
        if filename == "":
            for p, ss in enumerate(samples[s]['files']):
                chain[s].Add(NTUPLEDIR + ss + ".root")
        else:
            chain[s].Add(NTUPLEDIR + filename + ".root")
        print "Entries: ", chain[s].GetEntries()
        #filename[s] = TFile("VBFH_HToSSTobbbb_MH-125_MS-30_ctauS-1000.root", "READ")
        if len(bins) == 0:
            hist[s] = TH2F(s, "", nbins, minimum, maximum, nbins, minimum,
                           maximum)
        else:
            hist[s] = TH2F(s, "", len(bins) - 1, bins, len(bins) - 1, bins)
        hist[s].Sumw2()
        if var == "z":
            #sign of eta for getting the right z value!
            chain[s].Project(
                s, "sqrt(pow(" + part_var + "[0].radius,2) - pow(" + part_var +
                "[0].radius2D,2)):sqrt(pow(" + part_var +
                "[2].radius,2) - pow(" + part_var + "[2].radius2D,2))",
                cutstring)
        else:
            if part_var == "GenBquarks":
                chain[s].Project(
                    s, "" + part_var + "[0]." + var + ":" + part_var + "[2]." +
                    var + "", cutstring)
            else:
                chain[s].Project(
                    s, "" + part_var + "[0]." + var + ":" + part_var + "[1]." +
                    var + "", cutstring)
        hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast())
        if norm:
            hist[s].Scale(100. / hist[s].Integral())
            gStyle.SetPaintTextFormat('5.1f')
        c1 = TCanvas("c1", "c1", 1000, 1000)
        c1.cd()
        #c1.SetGrid()
        #c1.SetLogz()
        c1.SetLogx()
        c1.SetLogy()
        hist[s].GetYaxis().SetTitle(
            "Leading " + particle +
            " transverse decay length (cm)")  #(""+part_var+"[0] "+var+" (cm)")
        hist[s].GetYaxis().SetTitleOffset(1.4)
        hist[s].GetXaxis().SetTitle(
            "Sub-leading " + particle +
            " transverse decay length (cm)")  #(""+part_var+"[2] "+var+" (cm)")
        hist[s].SetTitle(samples[s]['label'] if filename == "" else filename)
        hist[s].SetMarkerColor(0)  #(2)#
        hist[s].Draw("colz")  #()#
        v_ecal.Draw("sames")
        h_ecal.Draw("sames")
        v_hcal.Draw("sames")
        h_hcal.Draw("sames")
        v_magnet.Draw("sames")
        h_magnet.Draw("sames")
        v_mb1.Draw("sames")
        h_mb1.Draw("sames")
        v_mb4.Draw("sames")
        h_mb4.Draw("sames")
        hist[s].SetMarkerSize(1.2)  #(2)#
        hist[s].Draw("text,sames")  #()#
        leg.Draw("sames")
        c1.Print(OUTPUTDIR + "2D_gen_b_quark_" + var + "_" +
                 (s if filename == "" else filename) + string + ".png")
        c1.Print(OUTPUTDIR + "2D_gen_b_quark_" + var + "_" +
                 (s if filename == "" else filename) + string + ".pdf")

        if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
        c1.Close()
예제 #23
0
파일: prepare.py 프로젝트: chekanov/Map2RMM
    for i in range(1, maxNumber + 1):
        Names1.append(names[h] + "_{" + str(i) + "}")
Names2 = []
for i in range(len(Names1)):
    Names2.append(Names1[i])
Names1 = Names1[::-1]
print Names1
for h in range(mSize):
    for w in range(mSize):
        i1 = h
        i2 = w
        hhD.Fill(Names2[i1], Names1[i2], 0)
hhD.SetTitle("")
hhD.SetStats(0)
hhD.GetZaxis().SetRangeUser(ZSmin, ZSmax)
gStyle.SetPaintTextFormat(".0e")

for event in rfile[IND].inputNN:
    NN = (event.proj).size()
    a = event.proj
    inx1 = event.proj_index1
    inx2 = event.proj_index2
    data = []

    emptyMatrix = numpy.zeros(shape=(mSize, mSize))
    for i3 in range(NN):
        d1 = inx1[i3]
        d2 = inx2[i3]
        emptyMatrix[d1][d2] = float(a[i3])  # remove energy related mass cell

    # flattern
예제 #24
0
 def _makeup(self):
     self.hist.Draw("COLZ TEXT")
     gStyle.SetPaintTextFormat(".3f")
예제 #25
0
def GeneralSettings(paintformat="4.2f"):
    gROOT.SetBatch(True)
    gStyle.SetOptStat(0)
    tdr.setTDRStyle()
    gStyle.SetPaintTextFormat(paintformat)
    gROOT.ProcessLine("gErrorIgnoreLevel = 1001;")
예제 #26
0
def make_histos(signal, com, cutflows, stage):

    N2s = []
    N1s = []
    N2mN1s = []
    nTots = []
    nTotErrs = []
    nEnds = []
    nEndErrs = []
    paveTitle = '?'
    paveTitle2 = ''

    for cutflow in glob(cutflows):
        N2 = cutflow.split('_')[7]
        N1 = cutflow.split('_')[8]
        with open(cutflow, 'r') as f:
            for line in f:
                if line.split()[0] == 'entry' and line.split()[1] == 'point':
                    nTot = line.split()[2]
                    nTotErr = line.split()[3]
                elif line.split()[0] == 'dR-Lep1-Lep2-smaller-2':
                    nEnd = line.split()[1]
                    nEndErr = line.split()[2]

        N2s.append(float(N2))
        N1s.append(float(N1))
        N2mN1s.append(float(N2) - float(N1))
        nTots.append(float(nTot))
        nTotErrs.append(float(nTotErr))
        nEnds.append(float(nEnd))
        nEndErrs.append(float(nEndErr))

    if signal == 'N2N1' and com == '13':
        N2bins = [90., 110., 130., 150., 170., 190., 210., 230., 250.]
        N2mN1bins = [6.5, 8.5, 12.5, 17.5, 25., 35., 45.]
    elif signal == 'N2C1' and com == '13':
        N2bins = [
            87.5, 112.5, 137.5, 162.5, 187.5, 212.5, 237.5, 262.5, 287.5, 312.5
        ]
        N2mN1bins = [6.5, 8.5, 12.5, 17.5, 25., 35., 45.]
    elif signal == 'N2C1' and com == '14':
        N2bins = [75., 125., 175., 225., 275., 325., 375., 425.]
        N2mN1bins = [2.5, 7.5, 12.5, 17.5, 22.5, 27.5, 32.5, 37.5, 42.5]
    N2bina = array('d', sorted(set(N2bins)))
    N2mN1bina = array('d', sorted(set(N2mN1bins)))

    # Histogram
    h = TH2D('', '', len(N2bina) - 1, N2bina, len(N2mN1bina) - 1, N2mN1bina)
    for idx in range(0, len(N2s)):
        N2 = N2s[idx]
        N1 = N1s[idx]
        N2mN1 = N2mN1s[idx]
        nTot = nTots[idx]
        nTotErr = nTotErrs[idx]
        nEnd = nEnds[idx]
        nEndErr = nEndErrs[idx]
        #print 'Foo01', N2, N2mN1, nEnd
        if stage == 'nTot':
            paveTitle = 'Total events'
            h.Fill(N2, N2mN1, nTot)
        elif stage == 'nEnd':
            paveTitle = 'Events in SR'
            h.Fill(N2, N2mN1, nEnd)
        elif stage == 'Acc':
            paveTitle = 'Acceptance'
            paveTitle2 = '(*1000)'
            try:
                h.Fill(N2, N2mN1, 1000. * nEnd / nTot)
            except ZeroDivisionError:
                pass

    # Style
    gStyle.SetOptStat(0)
    gStyle.SetPaintTextFormat('.2f')
    h.GetXaxis().SetTitle('N2')
    h.GetYaxis().SetTitle('dM')
    set_palette()

    # Pave Text
    t1 = TPaveText(.1, .906, .2, 1., 'NDC')
    t1.SetTextSize(.039)
    t1.SetFillColor(0)
    t1.SetFillStyle(0)
    t1.SetLineWidth(0)
    t1.SetTextAlign(12)
    t1.AddText('CMS')
    t2 = TPaveText(.13, .9, .9, 1., 'NDC')
    t2.SetTextSize(.033)
    t2.SetFillColor(0)
    t2.SetFillStyle(0)
    t2.SetLineWidth(0)
    t2.SetTextAlign(12)
    t2.SetTextFont(42)
    t2.AddText('Phase-2 Simulation Preliminary   {} {} at {}TeV {}'.format(
        signal, paveTitle, com, paveTitle2))

    # Plot
    c = TCanvas()
    #c.SetLogy()
    h.Draw('colz|text')
    t1.Draw('same')
    t2.Draw('same')
    c.Print('{}_{}_{}TeV.pdf'.format(stage, signal, com))
    c.Print('{}_{}_{}TeV.png'.format(stage, signal, com))
예제 #27
0
    gStyle.SetTitleSize(0.045, "X")
    gStyle.SetTitleSize(0.045, "Y")

    gStyle.SetTitleOffset(1.4, "X")
    gStyle.SetTitleOffset(1.4, "Y")

    gStyle.SetTextSize(0.055)
    gStyle.SetTextFont(42)

    gStyle.SetOptStat(0)


setStyle()

gStyle.SetPaintTextFormat("3g")
gStyle.SetPadBottomMargin(0.20)
gStyle.SetPadLeftMargin(0.22)
gStyle.SetPadRightMargin(0.10)


def printSeparations(infilename, option="twiki"):
    separations = {}
    fileNameMatch = re.match("TMVA_(.+)_(.+).root", infilename)
    infile = root.TFile(infilename)
    for fileKey in infile.GetListOfKeys():
        fileKeyName = fileKey.GetName()
        #match = re.match("Method_(.+)",fileKeyName)
        match = re.match("Method_BDT", fileKeyName)
        if match:
            folder1 = fileKey.ReadObj()
예제 #28
0
def plot_2D(var, nbins=50, minimum=0, maximum=2000, filename=""):
    chain = {}
    hist = {}
    r_ecal = 129
    r_hcal = 179
    r_magnet = 295
    r_mb1 = 402

    z_ecal = 300
    z_hcal = 376
    z_magnet = 0
    z_mb1 = 560

    if var == "radius2D":
        v_ecal = TLine(r_ecal, minimum, r_ecal, maximum)
        v_hcal = TLine(r_hcal, minimum, r_hcal, maximum)
        v_magnet = TLine(r_magnet, minimum, r_magnet, maximum)
        v_mb1 = TLine(r_mb1, minimum, r_mb1, maximum)
        h_ecal = TLine(minimum, r_ecal, maximum, r_ecal)
        h_hcal = TLine(minimum, r_hcal, maximum, r_hcal)
        h_magnet = TLine(minimum, r_magnet, maximum, r_magnet)
        h_mb1 = TLine(minimum, r_mb1, maximum, r_mb1)
    elif var == "z":
        v_ecal = TLine(z_ecal, minimum, z_ecal, maximum)
        v_hcal = TLine(z_hcal, minimum, z_hcal, maximum)
        v_magnet = TLine(z_magnet, minimum, z_magnet, maximum)
        v_mb1 = TLine(z_mb1, minimum, z_mb1, maximum)
        h_ecal = TLine(minimum, z_ecal, maximum, z_ecal)
        h_hcal = TLine(minimum, z_hcal, maximum, z_hcal)
        h_magnet = TLine(minimum, z_magnet, maximum, z_magnet)
        h_mb1 = TLine(minimum, z_mb1, maximum, z_mb1)
    else:
        v_ecal = TLine(r_ecal, minimum, r_ecal, maximum)
        v_hcal = TLine(r_hcal, minimum, r_hcal, maximum)
        v_magnet = TLine(r_magnet, minimum, r_magnet, maximum)
        v_mb1 = TLine(r_mb1, minimum, r_mb1, maximum)
        h_ecal = TLine(minimum, r_ecal, maximum, r_ecal)
        h_hcal = TLine(minimum, r_hcal, maximum, r_hcal)
        h_magnet = TLine(minimum, r_magnet, maximum, r_magnet)
        h_mb1 = TLine(minimum, r_mb1, maximum, r_mb1)

    v_ecal.SetLineColor(2)
    h_ecal.SetLineColor(2)
    v_hcal.SetLineColor(881)
    h_hcal.SetLineColor(881)
    v_magnet.SetLineColor(1)
    h_magnet.SetLineColor(1)
    v_mb1.SetLineColor(801)
    h_mb1.SetLineColor(801)

    v_ecal.SetLineWidth(4)
    h_ecal.SetLineWidth(4)
    v_hcal.SetLineWidth(4)
    h_hcal.SetLineWidth(4)
    v_magnet.SetLineWidth(4)
    h_magnet.SetLineWidth(4)
    v_mb1.SetLineWidth(4)
    h_mb1.SetLineWidth(4)

    v_ecal.SetLineStyle(3)
    h_ecal.SetLineStyle(3)
    v_hcal.SetLineStyle(2)
    h_hcal.SetLineStyle(2)
    v_magnet.SetLineStyle(4)
    h_magnet.SetLineStyle(4)
    v_mb1.SetLineStyle(8)
    h_mb1.SetLineStyle(8)

    leg = TLegend(0.75, 0.75, 0.9, 0.9)
    leg.AddEntry(v_ecal, "ECAL", "L")
    leg.AddEntry(v_hcal, "HCAL", "L")
    leg.AddEntry(v_magnet, "solenoid", "L")
    leg.AddEntry(v_mb1, "MB1", "L")

    #pal= 68 #kAvocado
    #pal= 64 #kAquamarine, very readable
    #pal= 75 #kCherry 75, awful
    #pal= 85 #kIsland 85, not beautiful but readable
    #pal= 86 #kLake 86, too violet
    #pal= 87 #kLightTemperature 87, used for trigger
    #pal= 91 #kPastel 91, too purple
    #pal= 100 #kSolar 100, very red and orange
    pal = 98  #kSandyTerrain 98, quite fine
    #pal= 99 #kSienna 99, a bit hard to read
    gStyle.SetPalette(pal)
    gStyle.SetPaintTextFormat(".0f")
    for i, s in enumerate(sign):
        chain[s] = TChain("ntuple/tree")
        if filename == "":
            for p, ss in enumerate(samples[s]['files']):
                chain[s].Add(NTUPLEDIR + ss + ".root")
        else:
            chain[s].Add(filename + ".root")
        #filename[s] = TFile("VBFH_HToSSTobbbb_MH-125_MS-30_ctauS-1000.root", "READ")
        hist[s] = TH2F(s, "", nbins, minimum, maximum, nbins, minimum, maximum)
        hist[s].Sumw2()
        cutstring = "(fabs(GenBquarks[0].eta)<2.4 && fabs(GenBquarks[3].eta)<2.4)*(EventWeight)"
        cutstring = "(fabs(GenBquarks[0].eta)<2.4 && fabs(GenBquarks[3].eta)<2.4 && HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v)*(EventWeight)"
        #cutstring = "(fabs(GenBquarks[0].eta)<2.4 && fabs(GenBquarks[3].eta)<2.4 && HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v && MEt.pt>200)*(EventWeight)"
        #cutstring = "(fabs(GenBquarks[0].eta)<2.4 && fabs(GenBquarks[3].eta)<2.4 && HLT_VBF_DisplacedJet40_VTightID_Hadronic_v)*(EventWeight)"
        #cutstring = "(fabs(GenBquarks[0].eta)<2.4 && fabs(GenBquarks[3].eta)<2.4 && HLT_HT350_DisplacedDijet80_Tight_DisplacedTrack_v)*(EventWeight)"
        if var == "z":
            #chain[s].Project(s, "sqrt(pow(GenBquarks[0].radius,2) - pow(GenBquarks[0].radius2D,2)) * GenBquarks[0].eta/abs(GenBquarks[0].eta):sqrt(pow(GenBquarks[3].radius,2) - pow(GenBquarks[3].radius2D,2)) * GenBquarks[0].eta/abs(GenBquarks[0].eta)", cutstring)
            #sign of eta for getting the right z value!
            chain[s].Project(
                s,
                "sqrt(pow(GenBquarks[0].radius,2) - pow(GenBquarks[0].radius2D,2)):sqrt(pow(GenBquarks[3].radius,2) - pow(GenBquarks[3].radius2D,2))",
                cutstring)
        else:
            chain[s].Project(
                s, "GenBquarks[0]." + var + ":GenBquarks[3]." + var + "",
                cutstring)
        hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast())
        c1 = TCanvas("c1", "c1", 1000, 1000)
        c1.cd()
        c1.SetGrid()
        #c1.SetLogx()
        #c1.SetLogy()
        hist[s].GetYaxis().SetTitle("GenBquarks[0] " + var + " (cm)")
        hist[s].GetYaxis().SetTitleOffset(1.4)
        hist[s].GetXaxis().SetTitle("GenBquarks[3] " + var + " (cm)")
        hist[s].SetTitle(samples[s]['label'] if filename == "" else filename)
        hist[s].SetMarkerColor(0)
        hist[s].Draw("colztext")
        v_ecal.Draw("sames")
        h_ecal.Draw("sames")
        v_hcal.Draw("sames")
        h_hcal.Draw("sames")
        v_magnet.Draw("sames")
        h_magnet.Draw("sames")
        v_mb1.Draw("sames")
        h_mb1.Draw("sames")
        leg.Draw("sames")
        c1.Print("macro/2D_gen_b_quark_" + var + "_" +
                 (s if filename == "" else filename) + ".png")
        c1.Print("macro/2D_gen_b_quark_" + var + "_" +
                 (s if filename == "" else filename) + ".pdf")

        raw_input("Press Enter to continue...")
        c1.Close()
예제 #29
0
from ROOT import TH1F, TH2F, TFile, TTree
from ROOT import gROOT, gStyle
from ROOT import TCanvas

gROOT.SetBatch(1)
gROOT.Reset()
gStyle.SetCanvasColor(0)
gStyle.SetFrameBorderMode(0)
gStyle.SetOptStat(0)
gStyle.SetTitleX(0.5) # title X location
gStyle.SetTitleY(0.96) # title Y location 
gStyle.SetPaintTextFormat(".2f")

def draw_underflow_overflow(h1):
    h1.GetXaxis().SetRange(0, h1.GetNbinsX() + 1)
    h1.Draw()
    return h1

def fill_underflow_overflow(h1):
    nbin = h1.GetNbinsX()
    h1.Fill(h1.GetBinCenter(1),h1.GetBinContent(0))
    h1.Fill(h1.GetBinCenter(nbin),h1.GetBinContent(nbin+1)) 
    h1.Draw()
    return h1



Canv = TCanvas("c1","c1",0,0,800,600)
f_out = TFile(filename,"recreate")

for sample in sampleName:
예제 #30
0
def fit(infile="", label="", output=""):

    tfout = TFile.Open("%s.root" % output, "RECREATE")

    ## read data and fill a histogram
    hist = read_data(infile)

    xoffset = 0.5
    xmin = 0 + xoffset
    xmax = 45 + xoffset
    ymin = 0
    ymax = hist.GetMaximum()

    ## do fit
    fun1 = TF1("fun1", "expo", xmin, xmax)
    fun1.SetLineColor(ROOT.kRed)
    hist.Fit("fun1")

    fun2 = TF1("fun2", "[0]*exp([1]*x+[2]*1./x)", xmin, xmax)
    #fun2=TF1("fun2", "[0]*exp([1]*x+[2]*1./x+[3]*x*x)", xmin, xmax)
    fun2.SetLineColor(ROOT.kBlue)
    fun2.SetParameter(0, fun1.GetParameter(0))
    fun2.SetParameter(1, fun1.GetParameter(1))
    hist.Fit("fun2")

    fun2.SetParameter(0, fun2.GetParameter(0))
    fun2.SetParameter(1, fun2.GetParameter(1))
    fun2.SetParameter(2, fun2.GetParameter(2))
    #fun2.SetParameter(3, fun2.GetParameter(3))
    hist.Fit("fun2")

    prob = fun2.GetProb()
    chi2 = fun2.GetChisquare()
    print "prob:", prob
    print "chi2:", chi2

    gROOT.SetStyle("ATLAS")

    yscale = 2.5

    doRatio = 1  # compare and plot the observed and predicted

    ## plot
    canvas_w, canvas_h = 800, 600
    fraction = 1.
    ratio = 0.2
    if doRatio:
        canvas_w, canvas_h = 800, int(600 * (1 + ratio))
        fraction = ratio + 0.2

    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetPadRightMargin(0.10)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.15)
    MyC = TCanvas('MyC', 'MyC', canvas_w, canvas_h)
    MyC.SetTicks(1, 1)
    ymax *= yscale

    if doRatio:
        Pad1 = TPad("p1", "p1", 0, fraction * 1.0 / (fraction + 1), 1, 1, 0,
                    0)  # x1,y1,x2,y2
        Pad1.SetMargin(0.15, 0.10, 0.03, 0.05)
        Pad2 = TPad("p2", "p2", 0, 0, 1, fraction * 1.0 / (fraction + 1), 0, 0)
        Pad2.SetMargin(0.15, 0.10, 0.15 / fraction, 0.08)
        Pad1.Draw()
        Pad2.Draw()

    ## draw data and fitted lines
    hist.SetMarkerStyle(20)
    hist.SetMarkerSize(1.8)
    hist.SetLineWidth(2)
    hist.GetXaxis().SetTitle("Days")
    hist.GetYaxis().SetTitle("Cases")
    hist.GetYaxis().SetTitleOffset(1.1 * hist.GetYaxis().GetTitleOffset())
    hist.GetXaxis().SetTitleOffset(1.1 * hist.GetXaxis().GetTitleOffset())
    hist.GetXaxis().SetRangeUser(xmin, xmax)
    hist.SetMaximum(ymax)

    if doRatio:
        Pad1.cd()
    else:
        MyC.cd()

    gStyle.SetPaintTextFormat("      g")
    hist.Draw("petext")

    fun1.Draw("same")
    fun2.Draw("same")

    ## plot predictions
    hpred = get_pred(hist, fun2)
    hpred.SetMarkerColor(ROOT.kBlue)
    hpred.Draw("petextsame")
    hist.Draw("petextsame")

    ## Legend
    l = TLegend(0.20, 0.67, 0.35, 0.92)
    l.SetFillColor(10)
    l.SetBorderSize(0)
    l.SetTextSize(0.04)

    l.AddEntry(hist, label, "p")
    l.AddEntry(hpred, "Predicted", "p")
    flabel1 = "Fit: %.2fexp( %.2f*t)" % (fun1.GetParameter(0),
                                         fun1.GetParameter(1))
    l.AddEntry(fun1, flabel1, "l")
    flabel2 = "Fit: %.2fexp( %.2f*t + %.2f/t)" % (
        fun2.GetParameter(0), fun2.GetParameter(1), fun2.GetParameter(2))
    #flabel2="Fit: %.2fexp( %.2f*t + %.2f/t + %.2f/t^{2})" % (fun2.GetParameter(0), fun2.GetParameter(1), fun2.GetParameter(2), fun2.GetParameter(3))
    l.AddEntry(fun2, flabel2, "l")

    l.Draw()

    ## show fit quality
    """
  tl=TPaveText(0.30, 0.57, 0.50, 0.62, "NDC")
  tl.SetFillColor(10)
  tl.SetBorderSize(0)
  tl.SetTextSize(0.04)
  tl.AddText("p-value: %.3f" % prob)
  tl.Draw()
  """

    ## compare predicted and observed
    if doRatio:
        hres = get_diff(hist, fun2)
        hres.GetXaxis().SetTitle(hist.GetXaxis().GetTitle())
        hres.GetYaxis().SetTitle("Data-Pred.")
        hres.GetXaxis().SetTitleOffset(1.0)
        hres.GetYaxis().SetTitleOffset(0.4)
        hres.GetXaxis().SetLabelOffset(hres.GetXaxis().GetLabelOffset() * 2.0)
        hres.GetXaxis().SetTitleSize(hist.GetXaxis().GetTitleSize() * 2.5)
        hres.GetYaxis().SetTitleSize(hist.GetYaxis().GetTitleSize() * 2.5)
        hres.GetXaxis().SetLabelSize(hist.GetXaxis().GetLabelSize() * 2.5)
        hres.GetYaxis().SetLabelSize(hist.GetYaxis().GetLabelSize() * 2)
        hres.GetXaxis().SetTitleOffset(2. * hist.GetXaxis().GetTitleOffset())

        hist.GetXaxis().SetTitle("")
        hist.GetXaxis().SetLabelSize(0)

        Pad2.cd()
        hres.GetFunction("fun2").SetBit(ROOT.TF1.kNotDraw)
        dymin = hres.GetMinimum()
        dymax = hres.GetMaximum()
        dy = max(fabs(dymin), fabs(dymax)) * 1.1
        dy = min(dy, 2000)
        hres.GetYaxis().SetRangeUser(-dy, dy)
        hres.Draw()

    MyC.SaveAs("%s_linear.png" % output)
    hist.SetMinimum(11)
    hist.SetMaximum(hist.GetMaximum() * 2.)
    if doRatio:
        Pad1.SetLogy(1)
    else:
        MyC.SetLogy(1)
    MyC.SaveAs("%s_log.png" % output)

    tfout.cd()
    hist.Write()
    fun1.Write()
    fun2.Write()
    tfout.Close()