def savePlotAsTable(stackplots=None,spimposeplots=None,dataplots=None,outUrl='table.tex') :
    #tabtex=getPlotAsTable(stackplots,spimposeplots,dataplots)
    
    href=None
    if(stackplots is not None) : href=stackplots.At(0)
    if(href is None  and spimposeplots is not None) : href=spimposeplots.At(0)
    if(href is None  and dataplots is not None) : href=dataplots.At(0)
    if(href is None) : return

    colfmt='l'
    colnames=''
    for ibin in xrange(1,href.GetXaxis().GetNbins()+1) :
        colfmt += 'c'
        colnames += ' & ' + href.GetXaxis().GetBinLabel(ibin)
    
    tabtex =  '\\begin{table}[htp]\n'
    tabtex += '\\begin{center}\n'
    tabtex += '\\caption{}\n'
    tabtex += '\\label{tab:table}\n'
    tabtex += '\\begin{tabular}{'+colfmt+'} \\hline\n'
    tabtex += 'Process ' + colnames + '\\\\ \\hline\\hline\n'    

    #create the sum
    if(stackplots.At(0) is not None) :
        stackSum = stackplots.At(0).Clone("totalstack")
        stackSum.SetTitle('Total expected')
        stackSum.Reset('ICE')
        for p in stackplots: stackSum.Add(p)
        stackplots.Add(stackSum)

    alllists = [stackplots, spimposeplots,dataplots ]
    for ll in alllists :
        for p in ll :
            tabtex += p.GetTitle() 
            for ibin in xrange(1,p.GetXaxis().GetNbins()+1) :
                val = p.GetBinContent(ibin)
                valerr= p.GetBinError(ibin)
                try :
                    tabtex += ' & '
                    fmtValue = toLatexRounded(val,valerr)
                    fmtValue = fmtValue.replace("[","(")
                    fmtValue = fmtValue.replace("]",")")
                    tabtex += fmtValue
                except :
                    tabtex += ' & ' 
            tabtex += '\\\\\n'
        tabtex += '\\hline\n'
    
    tabtex += '\\end{tabular}\n'
    tabtex += '\\end{center}\n'
    tabtex += '\\end{table}\n'
    
    fileObj = open(outUrl,"w")
    #fileObj.write(tabtex.Data())
    fileObj.write(tabtex)
    fileObj.close()
Example #2
0
def savePlotAsTable(stackplots=None,spimposeplots=None,dataplots=None,outUrl='table.tex') :
    #tabtex=getPlotAsTable(stackplots,spimposeplots,dataplots)
    
    href=None
    if(stackplots is not None) : href=stackplots.At(0)
    if(href is None  and spimposeplots is not None) : href=spimposeplots.At(0)
    if(href is None  and dataplots is not None) : href=dataplots.At(0)
    if(href is None) : return

    colfmt='l'
    colnames=''
    for ibin in xrange(1,href.GetXaxis().GetNbins()+1) :
        colfmt += 'c'
        colnames += ' & ' + href.GetXaxis().GetBinLabel(ibin)
    
    tabtex =  '\\begin{table}[htp]\n'
    tabtex += '\\begin{center}\n'
    tabtex += '\\caption{}\n'
    tabtex += '\\label{tab:table}\n'
    tabtex += '\\begin{tabular}{'+colfmt+'} \\hline\n'
    tabtex += 'Process ' + colnames + '\\\\ \\hline\\hline\n'    

    #create the sum
    if(stackplots.At(0) is not None) :
        stackSum = stackplots.At(0).Clone("totalstack")
        stackSum.SetTitle('Total expected')
        stackSum.Reset('ICE')
        for p in stackplots: stackSum.Add(p)
        stackplots.Add(stackSum)

    alllists = [stackplots, spimposeplots,dataplots ]
    for ll in alllists :
        for p in ll :
            tabtex += p.GetTitle() 
            for ibin in xrange(1,p.GetXaxis().GetNbins()+1) :
                val = p.GetBinContent(ibin)
                valerr= p.GetBinError(ibin)
                try :
                    tabtex += ' & '
                    fmtValue = toLatexRounded(val,valerr)
                    fmtValue = fmtValue.replace("[","(")
                    fmtValue = fmtValue.replace("]",")")
                    tabtex += fmtValue
                except :
                    tabtex += ' & ' 
            tabtex += '\\\\\n'
        tabtex += '\\hline\n'
    
    tabtex += '\\end{tabular}\n'
    tabtex += '\\end{center}\n'
    tabtex += '\\end{table}\n'
    
    fileObj = open(outUrl,"w")
    #fileObj.write(tabtex.Data())
    fileObj.write(tabtex)
    fileObj.close()
Example #3
0
def getInTableFormat(tit,h,isData=False,addErrors=True):
    tableRow='$'+tit+'$'
    tableRow=tableRow.replace('#','\\')
    tableRow=tableRow.replace(' ','~')
    for ibin in xrange(1,h.GetXaxis().GetNbins()+1) :
        val = h.GetBinContent(ibin)
        valerr= h.GetBinError(ibin)
        try:
            tableRow += ' & '
            fmtValue = str(int(val))
            if(not isData) :
                #fmtValue = '%3.0f' % val
                #fmtValue += '$\\pm$'
                #fmtValue += '%3.0f' % valerr
                fmtValue = '%3.2f' % val
                if(addErrors) :
                    fmtValue = toLatexRounded(val,valerr)
                    fmtValue = fmtValue.replace("[","(")
                    fmtValue = fmtValue.replace("]",")")
            tableRow += fmtValue
        except:
            tableRow += ' & '

    return tableRow
def buildSFbSummary(inF, title, outDir):

    global SUMMARYCTR
    SUMMARYCTR += 1

    #read results from the pickle file
    cachefile = open(inF, 'r')
    fitInfo = pickle.load(cachefile)
    effExpected = pickle.load(cachefile)
    effObserved = pickle.load(cachefile)
    sfbMeasurement = pickle.load(cachefile)
    systUncs = pickle.load(cachefile)
    effsystUncs = pickle.load(cachefile)
    cachefile.close()

    taggerDef = fitInfo['taggerDef']
    taggerName = fitInfo['tagger']
    nOPs = len(taggerDef) - 2

    # see https://twiki.cern.ch/twiki/bin/viewauth/CMS/BTagCalibration#Example_code_in_Python
    sliceVarName = fitInfo['slicevar']
    btvCalib = ROOT.BTagCalibration(title) if sliceVarName == 'jetpt' else None

    #prepare graphs
    summaryGrs = {}
    for summaryType in ['eff', 'sfb']:
        for uncType in ['stat', 'total']:
            for iop in xrange(1, nOPs):
                if not iop in summaryGrs: summaryGrs[iop] = {}
                key = (summaryType, uncType)
                summaryGrs[iop][key] = ROOT.TGraphErrors()
                summaryGrs[iop][key].SetName(
                    '%s_pass%d_%s_%s_%d' %
                    (taggerName, iop, summaryType, uncType, SUMMARYCTR))
                summaryGrs[iop][key].SetTitle(title)
                #print 'COLORS[(SUMMARYCTR-1)%4]: ', COLORS[(SUMMARYCTR-1)%4]
                summaryGrs[iop][key].SetMarkerColor(COLORS[(SUMMARYCTR - 1) %
                                                           4])
                summaryGrs[iop][key].SetLineColor(COLORS[(SUMMARYCTR - 1) % 4])
                if uncType == 'total':
                    summaryGrs[iop][key].SetFillColor(COLORS[(SUMMARYCTR - 1) %
                                                             4])
                    summaryGrs[iop][key].SetFillStyle(3001 + SUMMARYCTR % 4)
                    summaryGrs[iop][key].SetMarkerStyle(1)
                else:
                    summaryGrs[iop][key].SetFillColor(0)
                    summaryGrs[iop][key].SetFillStyle(0)
                    summaryGrs[iop][key].SetLineWidth(2)
                    summaryGrs[iop][key].SetMarkerSize(0.6)
                    summaryGrs[iop][key].SetMarkerStyle(
                        MARKERS[(SUMMARYCTR - 1) % 4])

    #iterate over the results
    table, plotsToInclude = [], []
    for islice in effExpected[1]:
        tablePerOp = {}
        print 'Fit information: ', fitInfo
        sliceVarMin, sliceVarMax = fitInfo['slicebins'][islice][0], fitInfo[
            'slicebins'][islice][1]
        sliceVarMean = 0.5 * (sliceVarMax + sliceVarMin)
        sliceVarDx = 0.5 * (sliceVarMax - sliceVarMin)
        #sliceVarMean = sliceVarMean+((SUMMARYCTR-1)%4-2)*sliceVarDx*0.1
        for iop in xrange(1, len(taggerDef) - 2):
            systTable = []
            effExp, effExpUnc = effExpected[iop][islice]
            effObs, effObsUnc = effObserved[iop][islice][0], effObserved[iop][
                islice][1]
            sfb, sfbStatUnc = sfbMeasurement[iop][islice]
            sfbSystUnc = 0  #sfbStatUnc**2
            effSystUnc = 0
            for syst in systUncs[iop][islice]:
                if len(syst) == 0: continue
                if syst.endswith('dn'): continue
                syst = syst[:-2]
                sfbUncUp = systUncs[iop][islice][syst + 'up']
                sfbUncDn = systUncs[iop][islice][syst + 'dn']
                sfbSystUnc += (0.5 *
                               (math.fabs(sfbUncUp) + math.fabs(sfbUncDn)))**2
                #systTable.append( ('~~~{\\small \\it %s}'%syst,'${\\small %.1g / %.1g }$'%(sfbUncUp,sfbUncDn)) )
                systTable.append(('~~~{\\small \\it %s}' % syst,
                                  '${ %.1g / %.1g }$' % (sfbUncUp, sfbUncDn)))
            sfbSystUnc = math.sqrt(sfbSystUnc)
            sfbTotalUnc = math.sqrt(sfbStatUnc**2 + sfbSystUnc**2)
            #additional_flat_ttbar_sfbsysunc = sfbSystUnc * 1.5
            #sfbTotalUnc=math.sqrt(sfbStatUnc**2+sfbSystUnc**2+additional_flat_ttbar_sfbsysunc**2)

            for syst in effsystUncs[iop][islice]:
                if len(syst) == 0: continue
                if syst.endswith('dn'): continue
                syst = syst[:-2]
                effUncUp = effsystUncs[iop][islice][syst + 'up']
                effUncDn = effsystUncs[iop][islice][syst + 'dn']
                effSystUnc += (0.5 *
                               (math.fabs(effUncUp) + math.fabs(effUncDn)))**2
            effSystUnc = math.sqrt(effSystUnc)
            effTotalUnc = math.sqrt(effObsUnc**2 + effSystUnc**2)
            #additional_flat_ttbar_effsysunc = effSystUnc * 1.5
            #effTotalUnc=math.sqrt(effObsUnc**2+effSystUnc**2+additional_flat_ttbar_effsysunc**2)

            #report
            if sliceVarName == 'jetpt':
                btvCalibParams = ROOT.BTagEntry.Parameters(
                    iop - 1, title, 'central', 0, -2.4, 2.4, sliceVarMin,
                    sliceVarMax, 0, 1)
                entry = ROOT.BTagEntry(str(sfb), btvCalibParams)
                btvCalib.addEntry(entry)
                #btvCalibParams = ROOT.BTagEntry.Parameters(iop-1, title, 'up_total', 0, -2.4, 2.4, sliceVarMin,sliceVarMax,0,1)
                btvCalibParams = ROOT.BTagEntry.Parameters(
                    iop - 1, title, 'up', 0, -2.4, 2.4, sliceVarMin,
                    sliceVarMax, 0, 1)
                entry = ROOT.BTagEntry(str(sfb + sfbTotalUnc), btvCalibParams)
                btvCalib.addEntry(entry)
                #btvCalibParams = ROOT.BTagEntry.Parameters(iop-1, title, 'down_total', 0, -2.4, 2.4, sliceVarMin,sliceVarMax,0,1)
                btvCalibParams = ROOT.BTagEntry.Parameters(
                    iop - 1, title, 'down', 0, -2.4, 2.4, sliceVarMin,
                    sliceVarMax, 0, 1)
                entry = ROOT.BTagEntry(str(sfb - sfbTotalUnc), btvCalibParams)
                btvCalib.addEntry(entry)
                #btvCalibParams = ROOT.BTagEntry.Parameters(iop-1, title, 'up_statistics', 0, -2.4, 2.4, sliceVarMin,sliceVarMax,0,1)
                btvCalibParams = ROOT.BTagEntry.Parameters(
                    iop - 1, title, 'up_statistic', 0, -2.4, 2.4, sliceVarMin,
                    sliceVarMax, 0, 1)
                entry = ROOT.BTagEntry(str(sfb + sfbStatUnc), btvCalibParams)
                btvCalib.addEntry(entry)
                #btvCalibParams = ROOT.BTagEntry.Parameters(iop-1, title, 'down_statistics', 0, -2.4, 2.4, sliceVarMin,sliceVarMax,0,1)
                btvCalibParams = ROOT.BTagEntry.Parameters(
                    iop - 1, title, 'down_statistic', 0, -2.4, 2.4,
                    sliceVarMin, sliceVarMax, 0, 1)
                entry = ROOT.BTagEntry(str(sfb - sfbStatUnc), btvCalibParams)
                btvCalib.addEntry(entry)

            # fill table rows
            tablePerOp[iop] = [('$\\varepsilon_{\\rm b}^{\\rm MC}$',
                                '%s' % toLatexRounded(effExp, effExpUnc)),
                               ('$\\varepsilon_{\\rm b}^{\\rm obs}$',
                                '%s' % toLatexRounded(effObs, effObsUnc)),
                               ('${\\rm SF}_{\\rm b}$', '%s' % toLatexRounded(
                                   sfb, [sfbStatUnc, sfbSystUnc]))] + systTable

            #add points to graphs
            key = ('eff', 'stat')
            np = summaryGrs[iop][key].GetN()

            summaryGrs[iop][key].SetPoint(np, sliceVarMean, effObs)
            summaryGrs[iop][key].SetPointError(np, sliceVarDx, effObsUnc)

            key = ('eff', 'total')
            summaryGrs[iop][key].SetPoint(np, sliceVarMean, effObs)
            summaryGrs[iop][key].SetPointError(np, sliceVarDx, effTotalUnc)

            key = ('sfb', 'stat')
            summaryGrs[iop][key].SetPoint(np, sliceVarMean, sfb)
            summaryGrs[iop][key].SetPointError(np, sliceVarDx, sfbStatUnc)

            key = ('sfb', 'total')
            summaryGrs[iop][key].SetPoint(np, sliceVarMean, sfb)
            summaryGrs[iop][key].SetPointError(np, sliceVarDx, sfbTotalUnc)

        sliceVarRangeText = '$%3.0f<%s<%3.0f$' % (
            sliceVarMin, fitInfo['slicevar'], sliceVarMax)
        table.append((sliceVarRangeText, tablePerOp))
        plotsToInclude.append((
            'Result of the fit to the %s disciminator for events with %s. The left (right) panel shows the pass (fail) category defined for events with %s$>$%s.'
            % (title, sliceVarRangeText, taggerDef[0], taggerDef[iop + 1]),
            '%s/%s_%d_slice%d.pdf' %
            (os.path.dirname(inF), taggerName, iop, islice)))

    #dump to file
    if btvCalib:
        with open('%s/%s_calib.csv' % (outDir, title), 'w') as f:
            f.write(btvCalib.makeCSV())
        #with open('%s/CSVv2_Kin.csv'%(outDir,title), 'w') as f : f.write(btvCalib.makeCSV())

    return sliceVarName, summaryGrs, table, plotsToInclude
Example #5
0
            topRescaleFactor.GetXaxis().SetBinLabel(ipoint,reg[0])

        if(otherYields[0][0]>0):
            kOther=otherYields[1][0]/otherYields[0][0]
            kOtherError=sqrt(pow(otherYields[1][0]*otherYields[0][1],2)
                           +pow(otherYields[0][0]*otherYields[1][1],2))/pow(otherYields[0][0],2)
            otherRescaleFactor.SetBinContent(ipoint,kOther);
            otherRescaleFactor.SetBinError(ipoint,kOtherError)
            otherRescaleFactor.GetXaxis().SetBinLabel(ipoint,reg[0])


    print '********* ' + reg[0] + ' *************'
    print topRescaleFactor.GetXaxis().GetNbins()
    topRescaleFactor.Fit(fitfunc,'RQ+')
    try :
        fmtValue = toLatexRounded(fitfunc.GetParameter(0),fitfunc.GetParError(0))
        fmtValue = fmtValue.replace("[","(")
        fmtValue = fmtValue.replace("]",")")
        print 'top: ' + fmtValue,
    except :
        print 'top: n/a'
    topRescalingHistos.Add(topRescaleFactor)

    try :
        otherRescaleFactor.Fit(fitfunc,'RQ+')
        fmtValue = toLatexRounded(fitfunc.GetParameter(0),fitfunc.GetParError(0))
        fmtValue = fmtValue.replace("[","(")
        fmtValue = fmtValue.replace("]",")")
        print '  others: ' + fmtValue
    except:
        print '  others: n/a'
Example #6
0
        if (otherYields[0][0] > 0):
            kOther = otherYields[1][0] / otherYields[0][0]
            kOtherError = sqrt(
                pow(otherYields[1][0] * otherYields[0][1], 2) +
                pow(otherYields[0][0] * otherYields[1][1], 2)) / pow(
                    otherYields[0][0], 2)
            otherRescaleFactor.SetBinContent(ipoint, kOther)
            otherRescaleFactor.SetBinError(ipoint, kOtherError)
            otherRescaleFactor.GetXaxis().SetBinLabel(ipoint, reg[0])

    print '********* ' + reg[0] + ' *************'
    print topRescaleFactor.GetXaxis().GetNbins()
    topRescaleFactor.Fit(fitfunc, 'RQ+')
    try:
        fmtValue = toLatexRounded(fitfunc.GetParameter(0),
                                  fitfunc.GetParError(0))
        fmtValue = fmtValue.replace("[", "(")
        fmtValue = fmtValue.replace("]", ")")
        print 'top: ' + fmtValue,
    except:
        print 'top: n/a'
    topRescalingHistos.Add(topRescaleFactor)

    try:
        otherRescaleFactor.Fit(fitfunc, 'RQ+')
        fmtValue = toLatexRounded(fitfunc.GetParameter(0),
                                  fitfunc.GetParError(0))
        fmtValue = fmtValue.replace("[", "(")
        fmtValue = fmtValue.replace("]", ")")
        print '  others: ' + fmtValue
    except: