def findOnePe(hist, ws, name='x', Npe = 1):
    fitPed(hist, ws, name)
    x = ws.var(name)

    ped = ws.pdf('ped')
    pedWidth = ws.var('pedWidth')

    pdfs = RooArgList(ped)
    pdfList = []

    fped = RooRealVar('fped', 'f_{ped}', 0.8, 0., 1.)
    fractions = RooArgList(fped)
    fList = []
    peList = []

    peMean = RooRealVar('peMean', 'mean_{pe}', 6., 0., 20.)
    peWidth = RooRealVar('peWidth', 'width_{pe}', pedWidth.getVal(), 0., 10.)

    for i in range(0, Npe):
        pem = RooFormulaVar('pem{0}'.format(i+1), '@0+{0}*@1'.format(i+1),
                            RooArgList(ws.var('pedMean'), peMean))
        peList.append(pem)
        npepdf = RooGaussian('pe{0}pdf'.format(i+1), 'pe{0}pdf'.format(i+1),
                             x, pem, pedWidth)
        pdfs.add(npepdf)
        pdfList.append(npepdf)

        fnpe = RooRealVar('fpe{0}'.format(i+1), 'fpe{0}'.format(i+1),
                          0.5, -0.1, 1.0)
        fractions.add(fnpe)
        fList.append(fnpe)

    #bgMean = RooRealVar("bgMean", "bgMean", 6.0, x.getMin(), x.getMax())
    bgScale = RooRealVar("bgScale", "bgScale", 0.5, -1.0, Npe + 1.0)
    bgMean = RooFormulaVar("bgMean", "@1+@0*@2",
                           RooArgList(peMean, ws.var('pedMean'), bgScale))
    bgWidthL = RooRealVar("bgWidthL", "bgWidthL", pedWidth.getVal()*2,
                          0., 25.)
    bgWidthR = RooRealVar("bgWidthR", "bgWidthR", pedWidth.getVal()*7,
                          0., 25.)

    bgGauss = RooBifurGauss("bgGauss", "bgGauss", x, bgMean,
                            bgWidthR, bgWidthR)

    if (Npe > 1):
        pdfs.add(bgGauss)
    else:
        fractions.remove(fractions.at(fractions.getSize()-1))

##     pem = RooFormulaVar('pem', '@0+@1', RooArgList(peMean, ws.var('pedMean')))
##     firstPe = RooGaussian('firstPe', 'firstPe', x, pem, peWidth)

##     pdfs.Print("v")
##     fractions.Print("v")
    pedPlusOne = RooAddPdf('pedPlusOne', 'pedPlusOne', pdfs, fractions, True)

    ## pedWidth = ped.GetParameter(2)
    ## pedMean = ped.GetParameter(1)
    ## pedA = ped.GetParameter(0)
    
    secondMax = hist.GetMaximumBin() + 1
    goingDown = True
    maxVal = hist.GetBinContent(secondMax)
    foundMax = False
    while (not foundMax) and (secondMax < hist.GetNbinsX()):
        tmpVal = hist.GetBinContent(secondMax+1)
        if (tmpVal < maxVal):
            if not goingDown:
                foundMax = True
            else:
                goingDown = True
                maxVal = tmpVal
                secondMax += 1
        elif (tmpVal > maxVal):
            goingDown = False
            maxVal = tmpVal
            secondMax += 1
        else:
            maxVal = tmpVal
            secondMax += 1

    secondMaxx = hist.GetBinCenter(secondMax)
    print 'found 2nd maximum in bin',secondMax,'value',secondMaxx

##     peMean.setVal(secondMaxx)
##     bgMean.setVal(secondMaxx*0.6)
    x.setRange('pedPlus_fit', x.getMin(), ws.var('pedMean').getVal()+pedWidth.getVal()*6.*(Npe+0))

    pedPlusOne.fitTo(ws.data('ds'), RooFit.Minos(False),
                     RooFit.Range('pedPlus_fit'),
                     RooFit.PrintLevel(1))

    getattr(ws, 'import')(pedPlusOne)
Beispiel #2
0
del knotbinning, oldbinning, lo, hi

# knot coefficients
coefflist = RooArgList()
for i, v in enumerate(spline_coeffs):
    coefflist.add(const(v))
i = len(spline_coeffs)
coefflist.add(one)
spline_knots.append(time.getMax())
spline_knots.reverse()
fudge = (spline_knots[0] - spline_knots[1]) / (spline_knots[2] - spline_knots[1])
lastmycoeffs = RooArgList()
lastmycoeffs.add(const(1. - fudge))
lastmycoeffs.add(const(fudge))
polyvar = RooPolyVar('{}_SplineAccCoeff{}'.format(mode, i), '',
                     coefflist.at(coefflist.getSize() - 2), lastmycoeffs)
coefflist.add(polyvar)
del i

# create the spline itself
tacc = RooCubicSplineFun('{}_SplineAcceptance'.format(mode), '', time,
                         '{}_knotbinning'.format(mode), coefflist)
del lastmycoeffs, coefflist

## model with time resolution
# when using a spline acceptance
gres = RooGaussEfficiencyModel('{}_GaussianWithPEDTE'.format(tacc.GetName()),
                               '', time, tacc, const(0.0), const(0.044))
# # otherwise
# gres = RooGaussModel('gres', '', time, const(0.0), const(0.044))
if nokfactor:
totalYield = 0.
sigYield = 0.
sigErrs = {}

sigYieldFilename = 'last_H%i_%s_%iJets_signalYield.txt' % (opts.mH, 
                                                           modeString, opts.Nj)
sigYieldsFile = open(sigYieldFilename, 'w')

WpJNonPoissonError = 0

print
print '-------------------------------'
print 'Yields in signal box'
print '-------------------------------'
for i in range(0, yields.getSize()):
    theName = yields.at(i).GetName()
    if theName[0] == 'n':
        totalYield += yields.at(i).getVal()
        theIntegral = 1.
        if (theName == 'nDiboson'):
            theIntegral = dibosonInt.getVal()/dibosonFullInt.getVal()
        elif (theName == 'nWjets'):
            theIntegral = WpJInt.getVal()/WpJFullInt.getVal()
            if (yields.at(i).getError()**2 > yields.at(i).getVal()):
                WpJNonPoissonError = sqrt(yields.at(i).getError()**2 - \
                                              yields.at(i).getVal())
            else:
                WpJNonPoissonError = 0.
        elif (theName == 'nTTbar'):
            theIntegral = ttbarInt.getVal()/ttbarFullInt.getVal()
        elif (theName == 'nSingleTop'):
totalYield = 0.
sigYield = 0.
sigErrs = {}

sigYieldFilename = 'last_H%i_%s_%iJets_signalYield.txt' % (opts.mH, 
                                                           modeString, opts.Nj)
sigYieldsFile = open(sigYieldFilename, 'w')

WpJNonPoissonError = 0

print
print '-------------------------------'
print 'Yields in signal box'
print '-------------------------------'
for i in range(0, yields.getSize()):
    theName = yields.at(i).GetName()
    if theName[0] == 'n':
        totalYield += yields.at(i).getVal()
        theIntegral = 1.
        if (theName == 'nDiboson'):
            theIntegral = dibosonInt.getVal()/dibosonFullInt.getVal()
        elif (theName == 'nWjets'):
            theIntegral = WpJInt.getVal()/WpJFullInt.getVal()
            if (yields.at(i).getError()**2 > yields.at(i).getVal()):
                WpJNonPoissonError = sqrt(yields.at(i).getError()**2 - \
                                              yields.at(i).getVal())
            else:
                WpJNonPoissonError = 0.
        elif (theName == 'nTTbar'):
            theIntegral = ttbarInt.getVal()/ttbarFullInt.getVal()
        elif (theName == 'nSingleTop'):
Beispiel #5
0
def findOnePe(hist, ws, name='x', Npe=1):
    fitPed(hist, ws, name)
    x = ws.var(name)

    ped = ws.pdf('ped')
    pedWidth = ws.var('pedWidth')

    pdfs = RooArgList(ped)
    pdfList = []

    fped = RooRealVar('fped', 'f_{ped}', 0.8, 0., 1.)
    fractions = RooArgList(fped)
    fList = []
    peList = []

    peMean = RooRealVar('peMean', 'mean_{pe}', 6., 0., 20.)
    peWidth = RooRealVar('peWidth', 'width_{pe}', pedWidth.getVal(), 0., 10.)

    for i in range(0, Npe):
        pem = RooFormulaVar('pem{0}'.format(i + 1), '@0+{0}*@1'.format(i + 1),
                            RooArgList(ws.var('pedMean'), peMean))
        peList.append(pem)
        npepdf = RooGaussian('pe{0}pdf'.format(i + 1),
                             'pe{0}pdf'.format(i + 1), x, pem, pedWidth)
        pdfs.add(npepdf)
        pdfList.append(npepdf)

        fnpe = RooRealVar('fpe{0}'.format(i + 1), 'fpe{0}'.format(i + 1), 0.5,
                          -0.1, 1.0)
        fractions.add(fnpe)
        fList.append(fnpe)

    #bgMean = RooRealVar("bgMean", "bgMean", 6.0, x.getMin(), x.getMax())
    bgScale = RooRealVar("bgScale", "bgScale", 0.5, -1.0, Npe + 1.0)
    bgMean = RooFormulaVar("bgMean", "@1+@0*@2",
                           RooArgList(peMean, ws.var('pedMean'), bgScale))
    bgWidthL = RooRealVar("bgWidthL", "bgWidthL",
                          pedWidth.getVal() * 2, 0., 25.)
    bgWidthR = RooRealVar("bgWidthR", "bgWidthR",
                          pedWidth.getVal() * 7, 0., 25.)

    bgGauss = RooBifurGauss("bgGauss", "bgGauss", x, bgMean, bgWidthR,
                            bgWidthR)

    if (Npe > 1):
        pdfs.add(bgGauss)
    else:
        fractions.remove(fractions.at(fractions.getSize() - 1))


##     pem = RooFormulaVar('pem', '@0+@1', RooArgList(peMean, ws.var('pedMean')))
##     firstPe = RooGaussian('firstPe', 'firstPe', x, pem, peWidth)

##     pdfs.Print("v")
##     fractions.Print("v")
    pedPlusOne = RooAddPdf('pedPlusOne', 'pedPlusOne', pdfs, fractions, True)

    ## pedWidth = ped.GetParameter(2)
    ## pedMean = ped.GetParameter(1)
    ## pedA = ped.GetParameter(0)

    secondMax = hist.GetMaximumBin() + 1
    goingDown = True
    maxVal = hist.GetBinContent(secondMax)
    foundMax = False
    while (not foundMax) and (secondMax < hist.GetNbinsX()):
        tmpVal = hist.GetBinContent(secondMax + 1)
        if (tmpVal < maxVal):
            if not goingDown:
                foundMax = True
            else:
                goingDown = True
                maxVal = tmpVal
                secondMax += 1
        elif (tmpVal > maxVal):
            goingDown = False
            maxVal = tmpVal
            secondMax += 1
        else:
            maxVal = tmpVal
            secondMax += 1

    secondMaxx = hist.GetBinCenter(secondMax)
    print 'found 2nd maximum in bin', secondMax, 'value', secondMaxx

    ##     peMean.setVal(secondMaxx)
    ##     bgMean.setVal(secondMaxx*0.6)
    x.setRange('pedPlus_fit', x.getMin(),
               ws.var('pedMean').getVal() + pedWidth.getVal() * 6. * (Npe + 0))

    pedPlusOne.fitTo(ws.data('ds'), RooFit.Minos(False),
                     RooFit.Range('pedPlus_fit'), RooFit.PrintLevel(1))

    getattr(ws, 'import')(pedPlusOne)
usig2 = 0.0
totalYield = 0.0
sigYield = 0.0
sigErrs = {}

sigYieldFilename = "last_H%i_%s_%iJets_signalYield.txt" % (opts.mH, modeString, opts.Nj)
sigYieldsFile = open(sigYieldFilename, "w")

WpJNonPoissonError = 0

print
print "-------------------------------"
print "Yields in signal box"
print "-------------------------------"
for i in range(0, yields.getSize()):
    theName = yields.at(i).GetName()
    if theName[0] == "n":
        totalYield += yields.at(i).getVal()
        theIntegral = 1.0
        if theName == "nDiboson":
            theIntegral = dibosonInt.getVal() / dibosonFullInt.getVal()
        elif theName == "nWjets":
            theIntegral = WpJInt.getVal() / WpJFullInt.getVal()
            if yields.at(i).getError() ** 2 > yields.at(i).getVal():
                WpJNonPoissonError = sqrt(yields.at(i).getError() ** 2 - yields.at(i).getVal())
            else:
                WpJNonPoissonError = 0.0
        elif theName == "nTTbar":
            theIntegral = ttbarInt.getVal() / ttbarFullInt.getVal()
        elif theName == "nSingleTop":
            theIntegral = SingleTopInt.getVal() / SingleTopFullInt.getVal()
def accbuilder(time, knots, coeffs):
    # build acceptance function
    from copy import deepcopy
    myknots = deepcopy(knots)
    mycoeffs = deepcopy(coeffs)
    from ROOT import (RooBinning, RooArgList, RooPolyVar,
            RooCubicSplineFun)
    if (len(myknots) != len(mycoeffs) or 0 >= min(len(myknots), len(mycoeffs))):
        raise ValueError('ERROR: Spline knot position list and/or coefficient'
                'list mismatch')
    # create the knot binning
    knotbinning = WS(ws, RooBinning(time.getMin(), time.getMax(), 'knotbinning'))
    for v in myknots:
        knotbinning.addBoundary(v)
    knotbinning.removeBoundary(time.getMin())
    knotbinning.removeBoundary(time.getMax())
    knotbinning.removeBoundary(time.getMin())
    knotbinning.removeBoundary(time.getMax())
    oldbinning, lo, hi = time.getBinning(), time.getMin(), time.getMax()
    time.setBinning(knotbinning, 'knotbinning')
    time.setBinning(oldbinning)
    time.setRange(lo, hi)
    del knotbinning
    del oldbinning
    del lo
    del hi
    # create the knot coefficients
    coefflist = RooArgList()
    i = 0
    for v in mycoeffs:
        coefflist.add(WS(ws, RooRealVar('SplineAccCoeff%u' % i,
            'SplineAccCoeff%u' % i, v)))
        i = i + 1
    del mycoeffs
    coefflist.add(one)
    i = i + 1
    myknots.append(time.getMax())
    myknots.reverse()
    fudge = (myknots[0] - myknots[1]) / (myknots[2] - myknots[1])
    lastmycoeffs = RooArgList(
            WS(ws, RooConstVar('SplineAccCoeff%u_coeff0' % i,
                'SplineAccCoeff%u_coeff0' % i, 1. - fudge)),
            WS(ws, RooConstVar('SplineAccCoeff%u_coeff1' % i,
                'SplineAccCoeff%u_coeff1' % i, fudge)))
    del myknots
    coefflist.add(WS(ws, RooPolyVar(
        'SplineAccCoeff%u' % i, 'SplineAccCoeff%u' % i,
        coefflist.at(coefflist.getSize() - 2), lastmycoeffs)))
    del i
    # create the spline itself
    tacc = WS(ws, RooCubicSplineFun('SplineAcceptance', 'SplineAcceptance', time,
        'knotbinning', coefflist))
    del lastmycoeffs
    # make sure the acceptance is <= 1 for generation
    m = max([coefflist.at(j).getVal() for j in
        xrange(0, coefflist.getSize())])
    from ROOT import RooProduct
    c = WS(ws, RooConstVar('SplineAccNormCoeff', 'SplineAccNormCoeff', 0.99 / m))
    tacc_norm = WS(ws, RooProduct('SplineAcceptanceNormalised',
        'SplineAcceptanceNormalised', RooArgList(tacc, c)))
    del c
    del m
    del coefflist
    return tacc, tacc_norm
print 'sig2:', sig2
usig2 = 0.
totalYield = 0.
sigYield = 0.
sigErrs = {}

sigYieldsFile = open('lastSigYield.txt', 'w')

WpJNonPoissonError = 0

print
print '-------------------------------'
print 'Yields in signal box'
print '-------------------------------'
for i in range(0, yields.getSize()):
    theName = yields.at(i).GetName()
    if theName[0] == 'n':
        totalYield += yields.at(i).getVal()
        theIntegral = 1.
        if (theName == 'nDiboson'):
            theIntegral = dibosonInt.getVal()/dibosonFullInt.getVal()
        elif (theName == 'nWjets'):
            theIntegral = WpJInt.getVal()/WpJFullInt.getVal()
            WpJNonPoissonError = 0
        elif (theName == 'nTTbar'):
            theIntegral = ttbarInt.getVal()/ttbarFullInt.getVal()
        elif (theName == 'nSingleTop'):
            theIntegral = SingleTopInt.getVal()/SingleTopFullInt.getVal()
        elif (theName == 'nQCD'):
            theIntegral = QCDInt.getVal()/QCDFullInt.getVal()
        elif (theName == 'nZjets'):
Beispiel #9
0
# knot coefficients
coefflist = RooArgList()
for i, v in enumerate(spline_coeffs):
    coefflist.add(const(v))
i = len(spline_coeffs)
coefflist.add(one)
spline_knots.append(time.getMax())
spline_knots.reverse()
fudge = (spline_knots[0] - spline_knots[1]) / (spline_knots[2] -
                                               spline_knots[1])
lastmycoeffs = RooArgList()
lastmycoeffs.add(const(1. - fudge))
lastmycoeffs.add(const(fudge))
polyvar = RooPolyVar('{}_SplineAccCoeff{}'.format(mode, i), '',
                     coefflist.at(coefflist.getSize() - 2), lastmycoeffs)
coefflist.add(polyvar)
del i

# create the spline itself
tacc = RooCubicSplineFun('{}_SplineAcceptance'.format(mode), '', time,
                         '{}_knotbinning'.format(mode), coefflist)
#del lastmycoeffs, coefflist

from ROOT import TCanvas, TLine

#tacc.DrawClass();

aCanvas = canvas

import sys
    inFile.ls()
    #s = raw_input("Press Enter to continue");
    theTH1DHist = TH1F()
    inFile.GetObject("etaHist", theTH1DHist)
    #rooRealVarList += [RooRealVar('x','x',0.0,1.0)];
    x = RooRealVar('x', 'x', 0.0, 1.0)
    xRegions, x = divideEtaTH1Ds(theTH1DHist, x, 5, fNum)
    fNum += 1
    #xList += [RooAbsReal(x)]
    xRegionsList.add(xRegions.clone(xRegions.GetName() + "_clone"))
    #etasetDataset.add();

import sys
#sys.exit(0);

for i in range(xRegionsList.getSize()):
    xRegionsList.at(0).Print()
    #.Print();#writeToStream(ROOT.cout,True);

print "\n\nNOCRASH2\n\n"

from ROOT import TFile
import time

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

f = TFile('xRegionsList_%f.root' % time.time(), 'recreate')
f.WriteTObject(xRegionsList, 'xRegionsList_%f' % time.time())
f.Close()
del f
Beispiel #11
0
def buildSplineAcceptance(
        ws,     # workspace into which to import
        time,   # time variable
        pfx,    # prefix to be used in names
        knots,  # knots
        coeffs, # acceptance coefficients
        floatParams = False, # float acceptance parameters
        debug = False # debug printout
        ): 
    """
    build a spline acceptance function

    ws          -- workspace into which to import acceptance functions
    time        -- time observable
    pfx         -- prefix (mode name) from which to build object names
    knots       -- list of knot positions
    coeffs      -- spline coefficients
    floatParams -- if True, spline acceptance parameters will be floated
    debug       -- if True, print some debugging output

    returns a pair of acceptance functions, first the unnormalised one for
    fitting, then the normalised one for generation

    The minimum and maximum of the range of the time variable implicitly
    defines the position of the first and last knot. The other knot positions
    are passed in knots. Conversely, the coeffs parameter records the height
    of the sline at all but the last two knot positions. The next to last knot
    coefficient is fixed to 1.0, thus fixing the overall scale of the
    acceptance function. The spline coefficient for the last knot is fixed by
    extrapolating linearly from the two knots before; this prevents
    statistical fluctuations at the low stats high lifetime end of the
    spectrum to curve the spline.
    """
    # build acceptance function
    from copy import deepcopy
    myknots = deepcopy(knots)
    mycoeffs = deepcopy(coeffs)
    from ROOT import (RooBinning, RooArgList, RooPolyVar, RooCubicSplineFun,
            RooConstVar, RooProduct, RooRealVar)
    if (len(myknots) != len(mycoeffs) or 0 >= min(len(myknots), len(mycoeffs))):
        raise ValueError('ERROR: Spline knot position list and/or coefficient'
                'list mismatch')
    one = WS(ws, RooConstVar('one', '1', 1.0))
    # create the knot binning
    knotbinning = WS(ws, RooBinning(time.getMin(), time.getMax(),
        '%s_knotbinning' % pfx))
    for v in myknots:
        knotbinning.addBoundary(v)
    knotbinning.removeBoundary(time.getMin())
    knotbinning.removeBoundary(time.getMax())
    knotbinning.removeBoundary(time.getMin())
    knotbinning.removeBoundary(time.getMax())
    oldbinning, lo, hi = time.getBinning(), time.getMin(), time.getMax()
    time.setBinning(knotbinning, '%s_knotbinning' % pfx)
    time.setBinning(oldbinning)
    time.setRange(lo, hi)
    del knotbinning
    del oldbinning
    del lo
    del hi
    # create the knot coefficients
    coefflist = RooArgList()
    i = 0
    for v in mycoeffs:
        if floatParams:
            coefflist.add(WS(ws, RooRealVar('%s_SplineAccCoeff%u' % (pfx, i),
                'v_{%u}' % (i+1), v, 0., 3.)))
        else:
            coefflist.add(WS(ws, RooConstVar('%s_SplineAccCoeff%u' % (pfx, i),
                'v_{%u}' % (i+1), v)))
        i = i + 1
    del mycoeffs
    coefflist.add(one)
    i = i + 1
    myknots.append(time.getMax())
    myknots.reverse()
    fudge = (myknots[0] - myknots[1]) / (myknots[2] - myknots[1])
    lastmycoeffs = RooArgList(
            WS(ws, RooConstVar('%s_SplineAccCoeff%u_coeff0' % (pfx, i),
                '%s_SplineAccCoeff%u_coeff0' % (pfx, i), 1. - fudge)),
            WS(ws, RooConstVar('%s_SplineAccCoeff%u_coeff1' % (pfx, i),
                '%s_SplineAccCoeff%u_coeff1' % (pfx, i), fudge)))
    del myknots
    coefflist.add(WS(ws, RooPolyVar(
        '%s_SplineAccCoeff%u' % (pfx, i), 'v_{%u}' % (i+1),
        coefflist.at(coefflist.getSize() - 2), lastmycoeffs)))
    del i
    if debug:
        print 'DEBUG: Spline Coeffs: %s' % str([
            coefflist.at(i).getVal() for i in xrange(0, coefflist.getSize())
            ])
    # create the spline itself
    tacc = WS(ws, RooCubicSplineFun('%s_SplineAcceptance' % pfx,
        '%s_SplineAcceptance' % pfx, time, '%s_knotbinning' % pfx,
        coefflist))
    del lastmycoeffs
    if not floatParams:
        # make sure the acceptance is <= 1 for generation
        m = max([coefflist.at(j).getVal() for j in
            xrange(0, coefflist.getSize())])
        c = WS(ws, RooConstVar('%s_SplineAccNormCoeff' % pfx,
            '%s_SplineAccNormCoeff' % pfx, 0.99 / m))
        tacc_norm = WS(ws, RooProduct('%s_SplineAcceptanceNormalised' % pfx,
            '%s_SplineAcceptanceNormalised' % pfx, RooArgList(tacc, c)))
        del c
        del m
    else:
        tacc_norm = None # not supported when floating
    del coefflist
    return tacc, tacc_norm