def rounded(self):
     "report rounded val +/- stat +/- syst"
     is_data = not self.has_tot_err and not self.has_stat_err
     if is_data:
         return "%d"%self.value
     else:
         max_err = max([self.syst_err, self.stat_err])
         min_err = min([v for v in [self.syst_err, self.stat_err] if v!=0.0])
         err = min_err # not sure whether we want to round on max or min
         value, _    = pdgRound(self.value,    err)
         stat_err, _ = pdgRound(self.stat_err, err)
         syst_err, _ = pdgRound(self.syst_err, err)
         return "%s +/- %s +/- %s"%(value, stat_err, syst_err)
def computeAndPlotHfSf2d(fileIter, fileHf, lepton, variable_name, outdir) :
    eff_da = fileIter.Get(lepton+'_corHFRate_eta')
    eff_mc = buildRate(fileHf, lepton+'_fakeHF_all_l_pt_eta')
    ratio = buildRatioHistogram(eff_da, eff_mc)
    ratio.Print()
    xAx, yAx = ratio.GetXaxis(), ratio.GetYaxis()
    print ratio.GetName(),": bins (%d, %d)"%(ratio.GetNbinsX(), ratio.GetNbinsY())
    nEtaBins = yAx.GetNbins()
    print 'nEtaBins: ',nEtaBins
    xMin, xMax = xAx.GetXmin(), xAx.GetXmax()
    fitFunc = r.TF1('fit_func_const_'+ratio.GetName(), '[0]', xMin, xMax)
    etaBins = range(1, 1+nEtaBins)
    slices = [ratio.ProjectionX("%s_bin%d"%(ratio.GetName(), b), b, b, 'e') for b in etaBins]
    for b, s in zip(etaBins, slices) :
        s.SetTitle(lepton+" data/mc heavyflavor : eta bin %d"%b)
        s.Fit(fitFunc.GetName(), '0RQ') # do not draw, range, quiet
        p0, p0Err, chi2, ndf = fitResults(fitFunc)
        p0, p0Err = pdgRound(p0, p0Err)
        print "bin %d :  %s +/- %s"%(b, p0, p0Err)
        can = r.TCanvas('')
        s.Draw('ep')
        fitFunc.Draw('same')
        tex = r.TLatex()
        tex.SetNDC(True)
        fitParLabel = "Const. fit : %s #pm %s"%(p0, p0Err)
        fitGoodLabel = "#chi^{2}/DOF : %.2f / %d"%(chi2, ndf)
        tex.SetTextSize(yAx.GetTitleSize())
        tex.SetTextFont(yAx.GetTitleFont())
        tex.DrawLatex(0.15, 0.45, s.GetTitle())
        tex.DrawLatex(0.15, 0.40, "#splitline{%s}{%s}"%(fitParLabel, fitGoodLabel))
        can.Update()
        for ext in ['eps','png'] : can.SaveAs(outdir+'/fit_'+lepton+"_heavyflavor_etabin%d.%s"%(b, ext))
    return p0
def computeAndPlotConvSf(fileData, fileMc, lepton, variable_name, outdir):
    "Electron conversion: simplest case, just data/mc"
    eff_da = buildRate(fileData, lepton + '_fakeConv_' + variable_name)
    eff_mc = buildRate(fileMc, lepton + '_fakeConv_' + variable_name)
    ratio = buildRatioHistogram(eff_da, eff_mc)
    fitFunc = fitWithConst(ratio)
    p0, p0Err, chi2, ndf = fitResults(fitFunc)
    p0, p0Err = pdgRound(p0, p0Err)
    print "SF for %s fake conv : %s +/- %s" % (lepton, p0, p0Err)
    graphics = {
        'xtitle': xTitle(lepton, variable_name),
        'ytitle': lepton + ' p(tight | fake conv)',
        'colors': {
            'data': r.kBlack,
            'mc': mcColor(lepton)
        },
        'markers': {
            'data': r.kFullCircle,
            'mc': mcMarker(lepton)
        },
        'labels': {
            'data': 'Data: Conversion CR',
            'mc': 'MC Comb: Conv CR'
        }
    }
    plotHistRatioAndFit({
        'data': eff_da,
        'mc': eff_mc
    }, ratio, fitFunc, outdir + lepton + '_fakeconv', graphics)
def computeAndPlotRealSf(file_data, file_mc, lepton, variable_name, outdir):
    "Scale factor from the real control region, Z tag and probe"
    eff_da = buildSideBandSubRate(file_data, lepton, variable_name)
    eff_mc = buildSideBandSubRate(file_mc, lepton, variable_name)
    ratio = buildRatioHistogram(eff_da, eff_mc)
    fitFunc = fitWithConst(ratio)
    p0, p0Err, chi2, ndf = fitResults(fitFunc)
    p0, p0Err = pdgRound(p0, p0Err)
    print "SF for %s real : %s +/- %s" % (lepton, p0, p0Err)
    graphics = {
        'xtitle': xTitle(lepton, variable_name),
        'ytitle': lepton + ' p(tight | real)',
        'colors': {
            'data': r.kBlack,
            'mc': mcColor(lepton)
        },
        'markers': {
            'data': r.kFullCircle,
            'mc': mcMarker(lepton)
        },
        'labels': {
            'data': 'Data: Z Tag and Probe',
            'mc': 'MC Comb: Z Tag and Probe'
        }
    }
    plotHistRatioAndFit({
        'data': eff_da,
        'mc': eff_mc
    }, ratio, fitFunc, outdir + lepton + '_real', graphics)
def computeAndPlotHfSf(fileIter, fileHf, lepton, variable_name, outdir):
    "HF tag and probe; in this case we need to subract out the contamination"
    eff_da = fileIter.Get(lepton + '_corHFRate')
    eff_mc = buildRate(fileHf, lepton + '_fakeHF_' + variable_name)
    ratio = buildRatioHistogram(eff_da, eff_mc)
    fitFunc = fitWithConst(ratio)
    p0, p0Err, chi2, ndf = fitResults(fitFunc)
    p0, p0Err = pdgRound(p0, p0Err)
    print "SF for %s fake HF : %s +/- %s" % (lepton, p0, p0Err)
    graphics = {
        'xtitle': xTitle(lepton, variable_name),
        'ytitle': lepton + ' p(tight | fake hf)',
        'colors': {
            'data': r.kBlack,
            'mc': mcColor(lepton)
        },
        'markers': {
            'data': r.kFullCircle,
            'mc': mcMarker(lepton)
        },
        'labels': {
            'data': 'Data HF Tag and Probe (Iterative Subtraction)',
            'mc': 'b#bar{b}/c#bar{c} MC: HF Tag and Probe'
        }
    }
    plotHistRatioAndFit({
        'data': eff_da,
        'mc': eff_mc
    }, ratio, fitFunc, outdir + lepton + '_fakehf', graphics)
def plotHistRatioAndFit(histos, ratio, fitfunc, outfname, graphics_attributes={}) :
    can = r.TCanvas('can_'+outfname, outfname, 800, 600)
    botPad, topPad = buildBotTopPads(can, splitFraction=0.35)
    can.cd()
    topPad.Draw()
    topPad.cd()
    pm = first(histos)
    pm.Draw('axis')
    xAx, yAx = pm.GetXaxis(), pm.GetYaxis()
    xAx.SetTitle('')
    xAx.SetLabelSize(0)
    yAx.SetRangeUser(0.0, 1.2)
    yAx.SetNdivisions(505) # for some reason some of the inputs are already ratios with -201
    textScaleUp = 1.0/topPad.GetHNDC()
    yAx.SetLabelSize(textScaleUp*0.04)
    yAx.SetTitleSize(textScaleUp*0.04)
    yAx.SetTitle(graphics_attributes['ytitle'])
    yAx.SetTitleOffset(yAx.GetTitleOffset()/textScaleUp)
    for k, h in histos.iteritems() :
        h.SetMarkerStyle(graphics_attributes['markers'][k])
        h.SetMarkerColor(graphics_attributes['colors'][k]) 
        h.SetLineColor(graphics_attributes['colors'][k])
        h.Draw('same')
    labels = graphics_attributes['labels']
    drawLegendWithDictKeys(topPad, dict([(labels[s], histos[s]) for s in histos.keys()]), legWidth=0.4)
    can.cd()
    botPad.Draw()
    botPad.cd()
    ratio.Draw('axis')
    textScaleUp = 1.0/botPad.GetHNDC()
    xAx, yAx = ratio.GetXaxis(), ratio.GetYaxis()
    yAx.SetRangeUser(0.0, 2.0)
    xAx.SetTitle(graphics_attributes['xtitle'])
    yAx.SetNdivisions(-202)
    yAx.SetTitle('Data/Sim')
    yAx.CenterTitle()
    for a in [xAx, yAx] :
        if a.GetLabelSize()>0.04 : continue
        a.SetLabelSize(a.GetLabelSize()*textScaleUp)
        a.SetTitleSize(a.GetTitleSize()*textScaleUp)
        a.SetTitleOffset(a.GetTitleOffset()/textScaleUp)
    ratio.SetMarkerStyle(graphics_attributes['markers']['data'])
    fitfunc.SetLineWidth(2)
    fitfunc.SetLineStyle(2)
    fitfunc.Draw('same')
    ratio.Draw('same')
    tex = r.TLatex()
    tex.SetNDC(True)
    p0, p0Err, chi2, ndf = fitResults(fitfunc)
    fitParLabel = "Const. fit : %s #pm %s"%(pdgRound(p0, p0Err))
    fitGoodLabel = "#chi^{2}/DOF : %.2f / %d"%(chi2, ndf)
    tex.SetTextSize(yAx.GetTitleSize())
    tex.SetTextFont(yAx.GetTitleFont())
    tex.DrawLatex(0.15, 0.40, "#splitline{%s}{%s}"%(fitParLabel, fitGoodLabel))
    can.Update()
    outfname = outfname+'.png'
    rmIfExists(outfname) # avoid root warnings
    can.SaveAs(outfname)
def computeAndPlotHfSf(fileIter, fileHf, lepton, variable_name, outdir) :
    "HF tag and probe; in this case we need to subract out the contamination"
    eff_da = fileIter.Get(lepton+'_corHFRate')
    eff_mc = buildRate(fileHf, lepton+'_fakeHF_'+variable_name)
    ratio = buildRatioHistogram(eff_da, eff_mc)
    fitFunc = fitWithConst(ratio)
    p0, p0Err, chi2, ndf = fitResults(fitFunc)
    p0, p0Err = pdgRound(p0, p0Err)
    print "SF for %s fake HF : %s +/- %s"%(lepton, p0, p0Err)
    graphics = {'xtitle' : xTitle(lepton, variable_name),
                'ytitle' : lepton+' p(tight | fake hf)',
                'colors' : {'data' : r.kBlack, 'mc' : mcColor(lepton)},
                'markers': {'data' : r.kFullCircle, 'mc' : mcMarker(lepton)},
                'labels' : {'data' : 'Data HF Tag and Probe (Iterative Subtraction)',
                            'mc'   : 'b#bar{b}/c#bar{c} MC: HF Tag and Probe'}}
    plotHistRatioAndFit({'data':eff_da, 'mc':eff_mc}, ratio, fitFunc, outdir+lepton+'_fakehf',
                        graphics)
def computeAndPlotConvSf(fileData, fileMc, lepton, variable_name, outdir) :
    "Electron conversion: simplest case, just data/mc"
    eff_da = buildRate(fileData, lepton+'_fakeConv_'+variable_name)
    eff_mc = buildRate(fileMc,   lepton+'_fakeConv_'+variable_name)
    ratio  = buildRatioHistogram(eff_da, eff_mc)
    fitFunc = fitWithConst(ratio)
    p0, p0Err, chi2, ndf = fitResults(fitFunc)
    p0, p0Err = pdgRound(p0, p0Err)
    print "SF for %s fake conv : %s +/- %s"%(lepton, p0, p0Err)
    graphics = {'xtitle' : xTitle(lepton, variable_name),
                'ytitle' : lepton+' p(tight | fake conv)',
                'colors' : {'data' : r.kBlack, 'mc' : mcColor(lepton)},
                'markers': {'data' : r.kFullCircle, 'mc' : mcMarker(lepton)},
                'labels' : {'data' : 'Data: Conversion CR',
                            'mc'   : 'MC Comb: Conv CR'}}
    plotHistRatioAndFit({'data':eff_da, 'mc':eff_mc}, ratio, fitFunc, outdir+lepton+'_fakeconv',
                        graphics)
def computeAndPlotRealSf(file_data, file_mc, lepton, variable_name, outdir) :
    "Scale factor from the real control region, Z tag and probe"
    eff_da = buildSideBandSubRate(file_data, lepton, variable_name)
    eff_mc = buildSideBandSubRate(file_mc,   lepton, variable_name)
    ratio = buildRatioHistogram(eff_da, eff_mc)
    fitFunc = fitWithConst(ratio)
    p0, p0Err, chi2, ndf = fitResults(fitFunc)
    p0, p0Err = pdgRound(p0, p0Err)
    print "SF for %s real : %s +/- %s"%(lepton, p0, p0Err)
    graphics = {'xtitle' : xTitle(lepton, variable_name),
                'ytitle' : lepton+' p(tight | real)',
                'colors' : {'data' : r.kBlack, 'mc' : mcColor(lepton)},
                'markers': {'data' : r.kFullCircle, 'mc' : mcMarker(lepton)},
                'labels' : {'data' : 'Data: Z Tag and Probe',
                            'mc'   : 'MC Comb: Z Tag and Probe'}}
    plotHistRatioAndFit({'data':eff_da, 'mc':eff_mc}, ratio, fitFunc, outdir+lepton+'_real',
                        graphics)
def computeAndPlotConvSf(fileData, fileMc, lepton, variable_name, outdir, outfile=None) :
    "Electron conversion: simplest case, just data/mc"
    eff_da = buildRate(fileData, lepton+'_fakeConv_'+variable_name)
    eff_mc = buildRate(fileMc,   lepton+'_fakeConv_'+variable_name)
    ratio  = buildRatioHistogram(eff_da, eff_mc)
    print ratio.GetName(),' : ',["%.3f"%ratio.GetBinContent(b) for b in range(1, 1+ratio.GetNbinsX())]
    fitFunc = fitWithConst(ratio)
    p0, p0Err, chi2, ndf = fitResults(fitFunc)
    p0, p0Err = pdgRound(p0, p0Err)
    print "SF for %s fake conv : %s +/- %s"%(lepton, p0, p0Err)
    graphics = {'xtitle' : xTitle(lepton, variable_name),
                'ytitle' : lepton+' p(tight | fake conv)',
                'colors' : {'data' : r.kBlack, 'mc' : mcColor(lepton)},
                'markers': {'data' : r.kFullCircle, 'mc' : mcMarker(lepton)},
                'labels' : {'data' : 'Data: Conversion CR',
                            'mc'   : 'MC Comb: Conv CR'}}
    plotHistRatioAndFit({'data':eff_da, 'mc':eff_mc}, ratio, fitFunc, outdir+'/fit_'+lepton+'_conv', graphics)
    if outfile : saveObject(outfile, ratio, 'elec_convSF_pt')
    return p0
def computeAndPlotConvSf2d(fileData, fileMc, lepton, variable_name, outdir) :
    "Electron conversion: simplest case, just data/mc"
    histoname = 'elec_fakeConv_all_l_pt_eta'
    eff_da = buildRate(fileData, histoname)
    eff_mc = buildRate(fileMc,   histoname)
    print 'SF conversion: using histo ',histoname
    ratio  = buildRatioHistogram(eff_da, eff_mc)
    ratio.Print()
    xAx, yAx = ratio.GetXaxis(), ratio.GetYaxis()
    #pt_eta : check that x is pt, y is eta
    nEtaBins = yAx.GetNbins()
    xMin, xMax = xAx.GetXmin(), xAx.GetXmax()
    fitFunc = r.TF1('fit_func_const_'+ratio.GetName(), '[0]', xMin, xMax)
    etaBins = range(1, 1+nEtaBins)
    slices = [ratio.ProjectionX("%s_bin%d"%(ratio.GetName(), b), b, b, 'e') for b in etaBins]
    for b, s in zip(etaBins, slices) :
        s.SetTitle("data/mc conversion : eta bin %d"%b)
        s.Fit(fitFunc.GetName(), '0RQ') # do not draw, range, quiet
        p0, p0Err, chi2, ndf = fitResults(fitFunc)
        p0, p0Err = pdgRound(p0, p0Err)
        print "bin %d :  %s +/- %s"%(b, p0, p0Err)
        can = r.TCanvas('')
        s.Draw('ep')
        fitFunc.Draw('same')
        tex = r.TLatex()
        tex.SetNDC(True)
        fitParLabel = "Const. fit : %s #pm %s"%(p0, p0Err)
        fitGoodLabel = "#chi^{2}/DOF : %.2f / %d"%(chi2, ndf)
        tex.SetTextSize(yAx.GetTitleSize())
        tex.SetTextFont(yAx.GetTitleFont())
        tex.DrawLatex(0.15, 0.45, s.GetTitle())
        tex.DrawLatex(0.15, 0.40, "#splitline{%s}{%s}"%(fitParLabel, fitGoodLabel))
        can.Update()
        for ext in ['eps','png'] : can.SaveAs(outdir+"/fit_el_conv_etabin%d.%s"%(b, ext))
#     graphics = {'xtitle' : xTitle(lepton, variable_name),
#                 'ytitle' : lepton+' p(tight | fake conv)',
#                 'colors' : {'data' : r.kBlack, 'mc' : mcColor(lepton)},
#                 'markers': {'data' : r.kFullCircle, 'mc' : mcMarker(lepton)},
#                 'labels' : {'data' : 'Data: Conversion CR',
#                             'mc'   : 'MC Comb: Conv CR'}}
#     plotHistRatioAndFit({'data':eff_da, 'mc':eff_mc}, ratio, fitFunc, outdir+lepton+'_fakeconv',
#                         graphics)
    return p0
def plotHistRatioAndFit(histos,
                        ratio,
                        fitfunc,
                        outfname,
                        graphics_attributes={}):
    can = r.TCanvas('can_' + outfname, outfname, 800, 600)
    botPad, topPad = buildBotTopPads(can, splitFraction=0.35)
    can.cd()
    topPad.Draw()
    topPad.cd()
    pm = first(histos)
    pm.Draw('axis')
    xAx, yAx = pm.GetXaxis(), pm.GetYaxis()
    xAx.SetTitle('')
    xAx.SetLabelSize(0)
    yAx.SetRangeUser(0.0, 1.2)
    yAx.SetNdivisions(
        505)  # for some reason some of the inputs are already ratios with -201
    textScaleUp = 1.0 / topPad.GetHNDC()
    yAx.SetLabelSize(textScaleUp * 0.04)
    yAx.SetTitleSize(textScaleUp * 0.04)
    yAx.SetTitle(graphics_attributes['ytitle'])
    yAx.SetTitleOffset(yAx.GetTitleOffset() / textScaleUp)
    for k, h in histos.iteritems():
        h.SetMarkerStyle(graphics_attributes['markers'][k])
        h.SetMarkerColor(graphics_attributes['colors'][k])
        h.SetLineColor(graphics_attributes['colors'][k])
        h.Draw('same')
    labels = graphics_attributes['labels']
    drawLegendWithDictKeys(topPad,
                           dict([(labels[s], histos[s])
                                 for s in histos.keys()]),
                           legWidth=0.4)
    can.cd()
    botPad.Draw()
    botPad.cd()
    ratio.Draw('axis')
    textScaleUp = 1.0 / botPad.GetHNDC()
    xAx, yAx = ratio.GetXaxis(), ratio.GetYaxis()
    yAx.SetRangeUser(0.0, 2.0)
    xAx.SetTitle(graphics_attributes['xtitle'])
    yAx.SetNdivisions(-202)
    yAx.SetTitle('Data/Sim')
    yAx.CenterTitle()
    for a in [xAx, yAx]:
        if a.GetLabelSize() > 0.04: continue
        a.SetLabelSize(a.GetLabelSize() * textScaleUp)
        a.SetTitleSize(a.GetTitleSize() * textScaleUp)
        a.SetTitleOffset(a.GetTitleOffset() / textScaleUp)
    ratio.SetMarkerStyle(graphics_attributes['markers']['data'])
    fitfunc.SetLineWidth(2)
    fitfunc.SetLineStyle(2)
    fitfunc.Draw('same')
    ratio.Draw('same')
    tex = r.TLatex()
    tex.SetNDC(True)
    p0, p0Err, chi2, ndf = fitResults(fitfunc)
    fitParLabel = "Const. fit : %s #pm %s" % (pdgRound(p0, p0Err))
    fitGoodLabel = "#chi^{2}/DOF : %.2f / %d" % (chi2, ndf)
    tex.SetTextSize(yAx.GetTitleSize())
    tex.SetTextFont(yAx.GetTitleFont())
    tex.DrawLatex(0.15, 0.40,
                  "#splitline{%s}{%s}" % (fitParLabel, fitGoodLabel))
    can.Update()
    outfname = outfname + '.png'
    rmIfExists(outfname)  # avoid root warnings
    can.SaveAs(outfname)