def divideEtaTH1Ds(etaHist,
                   numCat,
                   sourceFileName=None,
                   categoryList=None,
                   drawHist=False):
    # etaHist - the TH1D to split into categories
    # numCat - number of tagging categories
    # categoryList - list of tagging category names
    # drawHist - whether or not to display each category-split histogram
    # sourceFileName - name of etaHist root file

    #normalize etaHist
    etaHist.Scale(1.0 / etaHist.Integral())

    #create default category names if none are given
    if categoryList == None:
        categoryList = []
        for i in range(numCat):
            categoryList += ["Cat" + str(i)]

    histSum = etaHist.Integral()

    #get list of limits
    limList = [-1]

    for i in range(1, numCat):
        start = limList[i - 1] + 1
        targetVal = histSum / numCat
        left = start
        right = etaHist.GetNbinsX()
        #print "\n\n\n",etaHist.Integral(start,start+1),"\n\n\n\n";
        while abs(left - right) > 1:
            if etaHist.Integral(start, int((left + right) / 2)) > targetVal:
                right = (left + right) / 2
            else:
                left = (left + right) / 2
            #print start, left, right, etaHist.Integral(start,int((left+right)/2)),targetVal,",",

        if abs(etaHist.Integral(start, left) -
               targetVal) > abs(etaHist.Integral(start, right) - targetVal):
            limList += [right]
        else:
            limList += [left]

    limList[0] = 0
    limList += [etaHist.GetNbinsX()]

    print limList

    #rangeFit is a 4-element TList containing:
    # - the sourceFileName as element 0
    # - a RooThresholdCategory as element 2, and its RooRealVar as element 1
    # - a tList of tFitResult as element 3
    rangeFit = TList()
    rangeFit.AddLast(TObjString(sourceFileName))
    rangeFit.AddLast(RooRealVar('x', 'x', 0.0, 1.0))
    rangeFit.AddLast(
        RooThresholdCategory("tageffRegion", "region of tageff",
                             rangeFit.At(1), "Cat" + str(numCat)))
    rangeFit.AddLast(TList())

    #plot each category-split histogram, if necessary
    if drawHist == True:

        ROOT.gStyle.SetPalette(ROOT.kOcean)

        #create stack to contain the category TH1Ds
        etaHistStack = THStack("etaHistStack", "Stack of TH1Ds")

        #create category-masking function for TH1D clones
        histCutterFunc = TF1("histCutterFunc",
                             "((x>=[0])?((x<[1])?1.0:0.0):0.0)", 0.0, 1.0)

        for i in range(len(limList) - 1):

            etaHistClone = etaHist.Clone()
            histCutterFunc.SetParameter(
                0,
                etaHist.GetXaxis().GetBinCenter(limList[i]))
            histCutterFunc.SetParameter(
                1,
                etaHist.GetXaxis().GetBinCenter(limList[i + 1]))
            #histCutterFunc.Draw();
            #raw_input("Press Enter to continue to next hisCutterFunc");
            etaHistClone.Multiply(histCutterFunc)
            etaHistClone.SetFillColor(38 + i)
            etaHistStack.Add(etaHistClone)

        etaHistClone = etaHist.Clone()
        etaHistClone.SetFillColor(38 + len(limList))
        #etaHistStack.Add(etaHistClone);

        import time

        os.chdir(os.environ['B2DXFITTERSROOT'] + '/tutorial')

        if (not (os.path.isdir('fits'))):
            os.mkdir('fits')

        os.chdir('fits')
        histCanvas = TCanvas()
        etaHistStack.Draw("hist PFC")
        #etaHistClone.Draw("hist PFC");
        #histCanvas.SaveAs('tagRegionFitList_%f.pdf' % time.time());

    #create thresholds and fitting functions (all linear, but with different ranges corresponding to the categories)

    currentRangeTF1List = TList()

    for i in range(1, numCat + 1):
        if (i <= numCat):
            rangeFit.At(2).addThreshold(
                etaHist.GetXaxis().GetBinCenter(limList[i]),
                categoryList[i - 1])
        currentRangeTF1List.AddLast(
            TF1(
                "fitFuncEtaset", "[0]+[1]*(x-" + str(
                    etaHist.Integral(limList[i - 1], limList[i]) /
                    (limList[i] - limList[i - 1])) + ")",
                etaHist.GetXaxis().GetBinCenter(limList[i - 1]),
                etaHist.GetXaxis().GetBinCenter(limList[i])))
        #currentRangeTF1 = TF1("fitFuncEtaset","[0]+[1]*x",etaHist.GetXaxis().GetBinCenter(limList[i-1]),etaHist.GetXaxis().GetBinCenter(limList[i]));
        rangeFit.Last().AddLast(
            etaHist.Fit(currentRangeTF1List.Last(), "R0S").Get().Clone())
        if (drawHist == True):
            currentRangeTF1List.Last().DrawCopy('same')
        #raw_input('Press Enter to continue to next fit function');
        #currentRangeTF1.IsA().Destructor(currentRangeTF1);
        #print "P0, P1 = ",rangeFit.Last().Last().Parameter(0), rangeFit.Last().Last().Parameter(1);

    histCanvas.SaveAs('tagRegionFitList_%f.pdf' % time.time())
    currentRangeTF1List.Delete()
    #for i in range(1,numCat+1):
    #currentRangeTF1List.Last().IsA().Destructor(currentRangeTF1List.Last());

    #s = raw_input("Press Enter to continue...");

    return rangeFit
Exemple #2
0
from ROOT import RooDataSet, RooArgSet

from ROOT import TList

mistagresultList = TList();
etaAvgList = TList();
print "**** ADDING CATEGORIES ****"
ds = ds.reduce("qt!=qt::Untagged");
xRegions = createCategoryHistogram(ds,ds.get().find('eta'),NUMCAT);
ds.addColumn(xRegions)
ds.table(xRegions).Print("v")

keepvars = [ds.get().find(name) for name in ['qt', 'qf', 'tageffRegion', 'time']]

for i in xrange(NUMCAT):
    etaAvgList.AddLast(ds.reduce("tageffRegion == tageffRegion::Cat%u" % (i + 1,)).meanVar(ds.get().find('eta')));

etaAvg = ds.meanVar(ds.get().find('eta'));

dspercat = [ ds.reduce(RooArgSet(*keepvars),"tageffRegion == tageffRegion::Cat%u" % (i + 1,)) for i in xrange(NUMCAT) ]

i = 0
for dspc in dspercat:
    print "**** CAT %u ****" % i
    i = i + 1
    dspc.Print("v")

#drawDsPlot(ds)

from math import sqrt
import random
#number of tagging categories
numTagCat = 5

#parse etaHist directory for .root files
for i in fileList[:1]:
    if (i[-5:] != '.root'):
        continue
    print i
    inFile = TFile(i)
    inFile.GetListOfKeys().Print()
    inFile.ls()
    #s = raw_input("Press Enter to continue");
    theTH1DHist = TH1F()
    inFile.GetObject("etaHist", theTH1DHist)
    mainResultList.AddLast(
        divideEtaTH1Ds(theTH1DHist, numTagCat, i, None, True))

from ROOT import TFile
import time

os.chdir(os.environ['B2DXFITTERSROOT'] + '/tutorial')

if (not (os.path.isdir('fits'))):
    os.mkdir('fits')

os.chdir('fits')

mainResultList.Print("", 5)

f = TFile('tagRegionFitList_%f.root' % time.time(), 'recreate')
f.WriteTObject(mainResultList, 'tagRegionFitList_%f' % time.time())