Example #1
0
def applyBinnedAcceptance(config, ws, time, timeresmodel, acceptance):
    """
    apply a (binned) acceptance to a decay time pdf

    config          -- configuration dictionary
    ws              -- workspace to import generated objects into
    time            -- decay time observable
    timeresmodel    -- decay time resolution model (not acceptance corrected)
    acceptance      -- acceptance function

    returns acceptance-corrected resolution model

    relevant configuration dictionary keys:
    'NBinsAcceptance':
        0 for unbinnned acceptance, > 0 to bin acceptance to speed up
        evaluation (keep at 0 for spline acceptance!)
    """
    if None == acceptance or 0 >= config['NBinsAcceptance']:
        return timeresmodel
    from ROOT import RooArgSet, RooBinnedPdf, RooEffResModel
    # bin the acceptance if not already binned
    if not acceptance.isBinnedDistribution(RooArgSet(time)):
        acceptance = WS(ws, RooBinnedPdf(
            "%sBinnedAcceptance" % acceptance.GetName(),
            "%sBinnedAcceptance" % acceptance.GetName(),
            time, 'acceptanceBinning', acceptance))
        acceptance.setForceUnitIntegral(True)
    # create the acceptance-corrected resolution model
    effresmodel = WS(ws, RooEffResModel(
        '%s_timeacc_%s' % (timeresmodel.GetName(), acceptance.GetName()),
        '%s plus time acceptance %s' % (timeresmodel.GetTitle(),
            acceptance.GetTitle()), timeresmodel, acceptance))
    return effresmodel
Example #2
0
def getDataSet(ws, cuts, files):
    from ROOT import TChain, TTree
    import ctypes
    c = TChain('DecayTree')
    for fname in files:
        print 'DEBUG: ADDING FILE %s' % fname
        c.AddFile(fname)
    print 'DEBUG: CUTS: %s' % cuts
    t = c.CopyTree(cuts)
    ROOT.SetOwnership(t, True)
    del c
    print 'DEBUG: ENTRIES AFTER APPLYING CUTS: %u' % t.GetEntries()
    time = ws.var('time')
    timeerr = ws.var('timeerr')
    ds = WS(ws, RooDataSet('ds', 'ds', RooArgSet(time, timeerr)), [])
    for i in xrange(0, t.GetEntries()):
        t.GetEntry(i)
        variables = [ timeConv * t.GetBranch(name).GetLeaf(name).GetValue(0) for name in
                ('lab0_LifetimeFit_ctau', 'lab0_LifetimeFit_ctauErr') ]
        time.setVal(variables[0])
        timeerr.setVal(variables[1])
        ds.add(RooArgSet(time, timeerr))
    del t
    ds.Print('v')
    return ds
Example #3
0
def buildTimePdf(config):
    """
    build time pdf, return pdf and associated data in dictionary
    """
    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])
    
    # start building the fit
    ws = RooWorkspace('ws_%s' % config['Context'])
    one = WS(ws, RooConstVar('one', '1', 1.0))
    zero = WS(ws, RooConstVar('zero', '0', 0.0))
    
    # start by defining observables
    time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
    qf = WS(ws, RooCategory('qf', 'final state charge'))
    qf.defineType('h+', +1)
    qf.defineType('h-', -1)
    qt = WS(ws, RooCategory('qt', 'tagging decision'))
    qt.defineType(      'B+', +1)
    qt.defineType('Untagged',  0)
    qt.defineType(      'B-', -1)
    
    # now other settings
    Gamma  = WS(ws, RooRealVar( 'Gamma',  'Gamma',  0.661)) # ps^-1
    DGamma = WS(ws, RooRealVar('DGamma', 'DGamma',  0.106)) # ps^-1
    Dm     = WS(ws, RooRealVar(    'Dm',     'Dm', 17.719)) # ps^-1
    
    mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))
    
    
    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance
    
    obs = [ qf, qt, time ]
    acc, accnorm = buildSplineAcceptance(ws, time, 'Bs2DsPi_accpetance',
            config['SplineAcceptance']['KnotPositions'],
            config['SplineAcceptance']['KnotCoefficients'][config['Context']],
            'FIT' in config['Context']) # float for fitting
    if 'GEN' in config['Context']:
        acc = accnorm # use normalised acceptance for generation
    # get resolution model
    resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)
    # build the time pdf
    pdf = buildBDecayTimePdf(
        config, 'Bs2DsPi', ws,
        time, timeerr, qt, qf, [ [ mistag ] ], [ tageff ],
        Gamma, DGamma, Dm,
        C = one, D = zero, Dbar = zero, S = zero, Sbar = zero,
        timeresmodel = resmodel, acceptance = acc)
    return { # return things
            'ws': ws,
            'pdf': pdf,
            'obs': obs
            }
Example #4
0
def buildTimePdf(config):
    """
    build time pdf, return pdf and associated data in dictionary
    """
    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])

    # start building the fit
    ws = RooWorkspace('ws_%s' % config['Context'])
    one = WS(ws, RooConstVar('one', '1', 1.0))
    zero = WS(ws, RooConstVar('zero', '0', 0.0))

    # start by defining observables
    time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
    qf = WS(ws, RooCategory('qf', 'final state charge'))
    qf.defineType('h+', +1)
    qf.defineType('h-', -1)
    qt = WS(ws, RooCategory('qt', 'tagging decision'))
    qt.defineType('B+', +1)
    qt.defineType('Untagged', 0)
    qt.defineType('B-', -1)

    # now other settings
    Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661))  # ps^-1
    DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106))  # ps^-1
    Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719))  # ps^-1

    mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))

    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance

    obs = [qf, qt, time]
    acc, accnorm = buildSplineAcceptance(
        ws, time, 'Bs2DsPi_accpetance',
        config['SplineAcceptance']['KnotPositions'],
        config['SplineAcceptance']['KnotCoefficients'][config['Context']],
        'FIT' in config['Context'])  # float for fitting
    if 'GEN' in config['Context']:
        acc = accnorm  # use normalised acceptance for generation
    # get resolution model
    resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)
    # build the time pdf
    pdf = buildBDecayTimePdf(config,
                             'Bs2DsPi',
                             ws,
                             time,
                             timeerr,
                             qt,
                             qf, [[mistag]], [tageff],
                             Gamma,
                             DGamma,
                             Dm,
                             C=one,
                             D=zero,
                             Dbar=zero,
                             S=zero,
                             Sbar=zero,
                             timeresmodel=resmodel,
                             acceptance=acc)
    return {  # return things
        'ws': ws,
        'pdf': pdf,
        'obs': obs
    }
Example #5
0
    'RooAdaptiveGaussKronrodIntegrator1D').setRealValue('maxSeg', 1000)
RooAbsReal.defaultIntegratorConfig().method1D().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')
RooAbsReal.defaultIntegratorConfig().method1DOpen().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')

# seed the Random number generator
rndm = TRandom3(SEED + 1)
RooRandom.randomGenerator().SetSeed(int(rndm.Uniform(4294967295)))
del rndm

# define some useful constants
from B2DXFitters.WS import WS

ws = RooWorkspace('ws')
one = WS(ws, RooConstVar('one', '1', 1.0))
zero = WS(ws, RooConstVar('zero', '0', 0.0))

# number of events to generate
nevts = 10000

# define time and its per-event uncertainty
time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0)) 
timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.001, 0.100))

# define final state charge
qf = WS(ws, RooCategory('qf', 'final state charge'))
qf.defineType('h+', +1)
qf.defineType('h-', -1)

# define list of tagging decision categories
Example #6
0
def buildTimePdf(config):
    """
    build time pdf, return pdf and associated data in dictionary
    """
    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])
    
    # start building the fit
    ws = RooWorkspace('ws_%s' % config['Context'])
    one = WS(ws, RooConstVar('one', '1', 1.0))
    zero = WS(ws, RooConstVar('zero', '0', 0.0))
    
    # start by defining observables
    time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
    qf = WS(ws, RooCategory('qf', 'final state charge'))
    qf.defineType('h+', +1)
    qf.defineType('h-', -1)
    qt = WS(ws, RooCategory('qt', 'tagging decision'))
    qt.defineType(      'B+', +1)
    qt.defineType('Untagged',  0)
    qt.defineType(      'B-', -1)
    
    # now other settings
    Gamma  = WS(ws, RooRealVar( 'Gamma',  'Gamma',  0.661)) # ps^-1
    DGamma = WS(ws, RooRealVar('DGamma', 'DGamma',  0.106)) # ps^-1
    Dm     = WS(ws, RooRealVar(    'Dm',     'Dm', 17.719)) # ps^-1
    
    # HACK (1/2): be careful about lower bound on eta, since mistagpdf below
    # is zero below a certain value - generation in accept/reject would get
    # stuck
    eta = WS(ws, RooRealVar('eta', 'eta', 0.35,
        0.0 if 'FIT' in config['Context'] else (1. + 1e-5) * max(0.0,
        config['TrivialMistagParams']['omega0']), 0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))
    
    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance
    
    obs = [ qf, qt, time, eta ]
    acc, accnorm = buildSplineAcceptance(ws, time, 'Bs2DsPi_accpetance',
            config['SplineAcceptance']['KnotPositions'],
            config['SplineAcceptance']['KnotCoefficients'][config['Context']],
            'FIT' in config['Context']) # float for fitting
    if 'GEN' in config['Context']:
        acc = accnorm # use normalised acceptance for generation
    # get resolution model
    resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)
    # build a (mock) mistag distribution
    mistagpdfparams = {} # start with parameters of mock distribution
    for sfx in ('omega0', 'omegaavg', 'f'):
        mistagpdfparams[sfx] = WS(ws, RooRealVar(
            'Bs2DsPi_mistagpdf_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx,
            config['TrivialMistagParams'][sfx]))
    # build mistag pdf itself
    mistagpdf = WS(ws, MistagDistribution(
        'Bs2DsPi_mistagpdf', 'Bs2DsPi_mistagpdf',
        eta, mistagpdfparams['omega0'], mistagpdfparams['omegaavg'],
        mistagpdfparams['f']))
    # build mistag calibration
    mistagcalibparams = {} # start with parameters of calibration
    for sfx in ('p0', 'p1', 'etaavg'):
        mistagcalibparams[sfx] = WS(ws, RooRealVar(
            'Bs2DsPi_mistagcalib_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx,
            config['MistagCalibParams'][sfx]))
    for sfx in ('p0', 'p1'): # float calibration paramters
        mistagcalibparams[sfx].setConstant(False)
        mistagcalibparams[sfx].setError(0.1)
    # build mistag pdf itself
    omega = WS(ws, MistagCalibration(
        'Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib',
        eta, mistagcalibparams['p0'], mistagcalibparams['p1'],
        mistagcalibparams['etaavg']))

    # build the time pdf
    pdf = buildBDecayTimePdf(
        config, 'Bs2DsPi', ws,
        time, timeerr, qt, qf, [ [ omega ] ], [ tageff ],
        Gamma, DGamma, Dm,
        C = one, D = zero, Dbar = zero, S = zero, Sbar = zero,
        timeresmodel = resmodel, acceptance = acc, timeerrpdf = None,
        mistagpdf = [ mistagpdf ], mistagobs = eta)
    return { # return things
            'ws': ws,
            'pdf': pdf,
            'obs': obs
            }
Example #7
0
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
def runBdGammaFitterOnToys(debug, wsname, 
                           pereventterr, year,
                           toys,pathName,
                           treeName, fileNamePull, configName, configNameMD,
                           sWeightsCorr,
                           noresolution, noacceptance, notagging,
                           noprodasymmetry, nodetasymmetry, notagasymmetries,
                           nosWeights, noUntagged,
                           singletagger) :
    
    if not Blinding and not toys :
        print "RUNNING UNBLINDED!"
        really = input('Do you really want to unblind? ')
        if really != "yes" :
            exit(-1)

    if sWeightsCorr and nosWeights:
        print "ERROR: cannot have sWeightsCorr and nosWeights at the same time!"
        exit(-1)

    if notagging and not singletagger:
        print "ERROR: having more perfect taggers is meaningless! Please check your options"
        exit(-1)
         
    # Get the configuration file
    myconfigfilegrabber = __import__(configName,fromlist=['getconfig']).getconfig
    myconfigfile = myconfigfilegrabber()

    print "=========================================================="
    print "FITTER IS RUNNING WITH THE FOLLOWING CONFIGURATION OPTIONS"
    for option in myconfigfile :
        if option == "constParams" :
            for param in myconfigfile[option] :
                print param, "is constant in the fit"
        else :
            print option, " = ", myconfigfile[option] 
    print "=========================================================="

    if debug:
        myconfigfile['Debug'] = True
    else:
        myconfigfile['Debug'] = False

    #Choosing fitting context
    myconfigfile['Context'] = 'FIT'
 
    # tune integrator configuration
    print "---> Setting integrator configuration"
    RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-7)
    RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-7)
    RooAbsReal.defaultIntegratorConfig().getConfigSection('RooIntegrator1D').setCatLabel('extrapolation','Wynn-Epsilon')
    RooAbsReal.defaultIntegratorConfig().getConfigSection('RooIntegrator1D').setCatLabel('maxSteps','1000')
    RooAbsReal.defaultIntegratorConfig().getConfigSection('RooIntegrator1D').setCatLabel('minSteps','0')
    RooAbsReal.defaultIntegratorConfig().getConfigSection('RooAdaptiveGaussKronrodIntegrator1D').setCatLabel('method','21Points')
    RooAbsReal.defaultIntegratorConfig().getConfigSection('RooAdaptiveGaussKronrodIntegrator1D').setRealValue('maxSeg', 1000)
    # since we have finite ranges, the RooIntegrator1D is best suited to the job
    RooAbsReal.defaultIntegratorConfig().method1D().setLabel('RooIntegrator1D')

    # Reading data set
    #-----------------------

    lumRatio = RooRealVar("lumRatio","lumRatio", myconfigfile["LumRatio"][year])
    
    print "=========================================================="
    print "Getting configuration"
    print "=========================================================="

    config = TString("../data/")+TString(configName)+TString(".py")
    from B2DXFitters.MDFitSettingTranslator import Translator
    mdt = Translator(myconfigfile,"MDSettings",False)
    
    MDSettings = mdt.getConfig()
    MDSettings.Print("v")

    bound = 1
    Bin = [TString("BDTGA")]

    from B2DXFitters.WS import WS as WS
    ws = RooWorkspace("intWork","intWork")

    workspace =[]
    workspaceW = []
    mode = "Bd2DPi"

    print "=========================================================="
    print "Getting sWeights"
    print "=========================================================="
    for i in range (0,bound):
        workspace.append(SFitUtils.ReadDataFromSWeights(TString(pathName),
                                                        TString(treeName),
                                                        MDSettings,
                                                        TString(mode),
                                                        TString(year),
                                                        TString(""),
                                                        TString("both"),
                                                        False, toys, False, sWeightsCorr, singletagger, debug))
        workspaceW.append(SFitUtils.ReadDataFromSWeights(TString(pathName),
                                                         TString(treeName),
                                                         MDSettings,
                                                         TString(mode),
                                                         TString(year),
                                                         TString(""),
                                                         TString("both"),
                                                         True, toys, False, sWeightsCorr, singletagger, debug))
    if nosWeights:
        workspace[0].Print("v")
    else:
        workspaceW[0].Print("v")
    zero = RooConstVar('zero', '0', 0.)
    half = RooConstVar('half','0.5',0.5)
    one = RooConstVar('one', '1', 1.)
    minusone = RooConstVar('minusone', '-1', -1.)
    two = RooConstVar('two', '2', 2.)
      
    nameData = TString("dataSet_time_")+part 
    data  = [] 
    dataW = []

    print "=========================================================="
    print "Getting input dataset"
    print "=========================================================="
    for i in range(0, bound):
        data.append(GeneralUtils.GetDataSet(workspace[i],   nameData, debug))
        dataW.append(GeneralUtils.GetDataSet(workspaceW[i],   nameData, debug))

    dataWA = dataW[0]
    dataA = data[0]

    if nosWeights:
        nEntries = dataA.numEntries()
        dataA.Print("v")
    else:
        nEntries = dataWA.numEntries()    
        dataWA.Print("v")        

    print "=========================================================="
    print "Getting observables"
    print "=========================================================="
    if nosWeights:
        obs = dataA.get()
    else:
        obs = dataWA.get()
        
    obs.Print("v")

    print "=========================================================="
    print "Creating variables"
    print "=========================================================="
    time = WS(ws,obs.find(MDSettings.GetTimeVarOutName().Data()))
    time.setRange(myconfigfile["BasicVariables"]["BeautyTime"]["Range"][0],
                  myconfigfile["BasicVariables"]["BeautyTime"]["Range"][1])
    print "==> Time"
    time.Print("v")
    terr = WS(ws,obs.find(MDSettings.GetTerrVarOutName().Data()))
    terr.setRange(myconfigfile["BasicVariables"]["BeautyTimeErr"]["Range"][0],
                  myconfigfile["BasicVariables"]["BeautyTimeErr"]["Range"][1])
    print "==> Time error"
    terr.Print("v")
    if noresolution:
        terr.setMin(0.0)
        terr.setVal(0.0)
        terr.setConstant(True)
    id = WS(ws,obs.find(MDSettings.GetIDVarOutName().Data()))

    print "==> Bachelor charge (to create categories; not really a variable!)"
    id.Print("v")
    if singletagger:
        tag = WS(ws,RooCategory("tagDecComb","tagDecComb"))
        tag.defineType("Bbar_1",-1)
        tag.defineType("Untagged",0)
        tag.defineType("B_1",+1)
    else:
        tag = WS(ws,obs.find("tagDecComb"))
        
    print "==> Tagging decision"
    tag.Print("v")
    
    mistag = WS(ws,obs.find("tagOmegaComb"))
    mistag.setRange(0,0.5)
    if notagging:
        mistag.setVal(0.0)
        mistag.setConstant(True)
    print "==> Mistag"
    mistag.Print("v")
    observables = RooArgSet(time,tag)

    # Physical parameters
    #-----------------------

    print "=========================================================="
    print "Setting physical parameters"
    print "=========================================================="
    
    gammad = WS(ws,RooRealVar('Gammad', '%s average lifetime' % bName, myconfigfile["DecayRate"]["Gammad"], 0., 5., 'ps^{-1}'))
    #setConstantIfSoConfigured(ws.obj('Gammad'),myconfigfile)
    
    deltaGammad = WS(ws,RooRealVar('deltaGammad', 'Lifetime difference', myconfigfile["DecayRate"]["DeltaGammad"], -1., 1., 'ps^{-1}'))
    #setConstantIfSoConfigured(ws.obj('deltaGammad'),myconfigfile)
    
    deltaMd = WS(ws,RooRealVar('deltaMd', '#Delta m_{d}', myconfigfile["DecayRate"]["DeltaMd"], 0.0, 1.0, 'ps^{-1}'))
    #setConstantIfSoConfigured(ws.obj('deltaMd'),myconfigfile)

    
    # Decay time acceptance model
    # ---------------------------
    
    print "=========================================================="
    print "Defining decay time acceptance model"
    print "=========================================================="

    if noacceptance:
        print '==> Perfect acceptance ("straight line")'
        tacc = None
        taccNorm = None
    else:
        print '==> Time-dependent acceptance'
        tacc, taccNorm = buildSplineAcceptance(ws,
                                               ws.obj('BeautyTime'),
                                               "splinePDF",
                                               myconfigfile["AcceptanceKnots"],
                                               myconfigfile["AcceptanceValues"],
                                               False,
                                               debug)
        print tacc
        print taccNorm
        
    # Decay time resolution model
    # ---------------------------

    print "=========================================================="
    print "Defining decay time resolution model"
    print "=========================================================="

    if noresolution:
        print '===> Using perfect resolution'
        trm = None
        terrpdf = None
    else:
        if not pereventterr:
            print '===> Using a mean resolution model'
            myconfigfile["DecayTimeResolutionModel"] = myconfigfile["DecayTimeResolutionMeanModel"]
            terrpdf = None
        else:
            print '===> Using a per-event time resolution'
            myconfigfile["DecayTimeResolutionModel"] = myconfigfile["DecayTimeResolutionPEDTE"]

            observables.add( terr )
            terrWork = GeneralUtils.LoadWorkspace(TString(myconfigfile["Toys"]["fileNameTerr"]), TString(myconfigfile["Toys"]["Workspace"]), debug)
            terrpdf = []
            for i in range(0,bound):
                terrtemp = WS(ws,Bs2Dsh2011TDAnaModels.GetRooHistPdfFromWorkspace(terrWork, TString(myconfigfile["Toys"]["TerrTempName"]), debug))
                #Dirty, nasty but temporary workaround to cheat RooFit strict requirements (changing dependent RooRealVar) 
                lab0_LifetimeFit_ctauErr = WS(ws,RooRealVar("lab0_LifetimeFit_ctauErr",
                                                      "lab0_LifetimeFit_ctauErr",
                                                      myconfigfile["BasicVariables"]["BeautyTimeErr"]["Range"][0],
                                                      myconfigfile["BasicVariables"]["BeautyTimeErr"]["Range"][1]))
                terrHist = WS(ws,terrtemp.createHistogram("terrHist",lab0_LifetimeFit_ctauErr))
                terrDataHist = WS(ws,RooDataHist("terrHist","terrHist",RooArgList(terr),terrHist))
                terrpdf.append(WS(ws,RooHistPdf(terrtemp.GetName(),terrtemp.GetTitle(),RooArgSet(terr),terrDataHist)))
                print terrpdf[i]
                
        trm, tacc = getResolutionModel(ws, myconfigfile, time, terr, tacc)
        print trm
        print tacc
    
    # Per-event mistag
    # ---------------------------

    print "=========================================================="
    print "Defining tagging and mistag"
    print "=========================================================="

    p0B = []
    p0Bbar = []
    p1B = []
    p1Bbar = []
    avB = []
    avBbar = []
    
    constList = RooArgSet()
    mistagCalibB = []
    mistagCalibBbar = []
    tagOmegaList = []
    
    if notagging:
        print '==> No tagging: <eta>=0'
        mistag.setVal(0.0)
        mistag.setConstant(True)
        tagOmegaList += [ [mistag] ]
    else:
        print '==> Non-trivial tagging'
        if singletagger:
            print '==> Single tagger'
            p0B.append(WS(ws,RooRealVar('p0_B_OS', 'p0_B_OS', myconfigfile["TaggingCalibration"]["OS"]["p0"], 0.0, 0.5)))
            p1B.append(WS(ws,RooRealVar('p1_B_OS', 'p1_B_OS', myconfigfile["TaggingCalibration"]["OS"]["p1"], 0.5, 1.5)))
            avB.append(WS(ws,RooRealVar('av_B_OS', 'av_B_OS', myconfigfile["TaggingCalibration"]["OS"]["average"])))
            #setConstantIfSoConfigured(p0B[0],myconfigfile)
            #setConstantIfSoConfigured(p1B[0],myconfigfile)
            mistagCalibB.append(WS(ws,MistagCalibration("mistagCalib_B_OS", "mistagCalib_B_OS", mistag, p0B[0], p1B[0], avB[0])))

            p0Bbar.append(WS(ws,RooRealVar('p0_Bbar_OS', 'p0_B_OS', myconfigfile["TaggingCalibration"]["OS"]["p0Bar"], 0.0, 0.5)))
            p1Bbar.append(WS(ws,RooRealVar('p1_Bbar_OS', 'p1_B_OS', myconfigfile["TaggingCalibration"]["OS"]["p1Bar"], 0.5, 1.5)))
            avBbar.append(WS(ws,RooRealVar('av_Bbar_OS', 'av_B_OS', myconfigfile["TaggingCalibration"]["OS"]["averageBar"])))
            #setConstantIfSoConfigured(p0Bbar[0],myconfigfile)
            #setConstantIfSoConfigured(p1Bbar[0],myconfigfile)
            mistagCalibBbar.append(WS(ws,MistagCalibration("mistagCalib_Bbar_OS", "mistagCalib_Bbar_OS", mistag, p0Bbar[0], p1Bbar[0], avBbar[0])))

            tagOmegaList += [ [mistagCalibB[0],mistagCalibBbar[0]] ]
        else:
            print '==> Combining more taggers'
            i=0
            for tg in ["OS","SS","OS+SS"]:
                p0B.append(WS(ws,RooRealVar('p0_B_'+tg, 'p0_B_'+tg, myconfigfile["TaggingCalibration"][tg]["p0"], 0., 0.5 )))
                p1B.append(WS(ws,RooRealVar('p1_B_'+tg, 'p1_B_'+tg, myconfigfile["TaggingCalibration"][tg]["p1"], 0.5, 1.5 )))
                avB.append(WS(ws,RooRealVar('av_B_'+tg, 'av_B_'+tg, myconfigfile["TaggingCalibration"][tg]["average"])))
                #setConstantIfSoConfigured(p0B[i],myconfigfile)
                #setConstantIfSoConfigured(p1B[i],myconfigfile)
                mistagCalibB.append(WS(ws,MistagCalibration("mistagCalib_B_"+tg, "mistagCalib_B_"+tg, mistag, p0B[i], p1B[i], avB[i])))
                
                p0Bbar.append(WS(ws,RooRealVar('p0_Bbar_'+tg, 'p0_Bbar_'+tg, myconfigfile["TaggingCalibration"][tg]["p0Bar"], 0., 0.5 )))
                p1Bbar.append(WS(ws,RooRealVar('p1_Bbar_'+tg, 'p1_Bbar_'+tg, myconfigfile["TaggingCalibration"][tg]["p1Bar"], 0.5, 1.5 )))
                avBbar.append(WS(ws,RooRealVar('av_Bbar_'+tg, 'av_Bbar_'+tg, myconfigfile["TaggingCalibration"][tg]["averageBar"])))
                #setConstantIfSoConfigured(p0Bbar[i],myconfigfile)
                #setConstantIfSoConfigured(p1Bbar[i],myconfigfile)
                mistagCalibBbar.append(WS(ws,MistagCalibration("mistagCalib_Bbar_"+tg, "mistagCalib_Bbar_"+tg, mistag, p0Bbar[i], p1Bbar[i], avBbar[i])))

                tagOmegaList += [ [mistagCalibB[i],mistagCalibBbar[i]] ]
                
                i = i+1

    print '==> Tagging calibration lists:'
    print tagOmegaList

    mistagWork = GeneralUtils.LoadWorkspace(TString(myconfigfile["Toys"]["fileNameMistag"]), TString(myconfigfile["Toys"]["Workspace"]), debug)
    mistagPDF = []
    mistagPDFList = []
    if notagging:
        mistagPDFList = None
    else:
        for i in range(0,3):
            mistagPDF.append(WS(ws,Bs2Dsh2011TDAnaModels.GetRooHistPdfFromWorkspace(mistagWork, TString(myconfigfile["Toys"]["MistagTempName"][i]), debug)))
            if not singletagger:
                mistagPDFList.append(mistagPDF[i])

        if singletagger:
            mistagPDFList.append(mistagPDF[0])
            
        observables.add( mistag )

    print "=========================================================="
    print "Summary of observables"
    print "=========================================================="

    observables.Print("v")
        
    # Total time PDF
    # ---------------------------

    print "=========================================================="
    print "Creating time PDF"
    print "=========================================================="

    timePDFplus = []
    timePDFminus = []
    timePDF = []

    adet_plus = WS(ws,RooConstVar('adet_plus','+1',1.0))
    id_plus = WS(ws, RooCategory('id_plus','Pi+'))
    id_plus.defineType('h+',1)

    adet_minus = WS(ws,RooConstVar('adet_minus','-1',-1.0))
    id_minus = WS(ws, RooCategory('id_minus','Pi-'))
    id_minus.defineType('h-',-1)
    
    for i in range(0,bound):
        utils = GenTimePdfUtils(myconfigfile,
                                ws,
                                gammad,
                                deltaGammad,
                                deltaMd,
                                singletagger,
                                notagging,
                                noprodasymmetry,
                                notagasymmetries,
                                debug)
        
        timePDFplus.append(buildBDecayTimePdf(myconfigfile,
                                              "Signal_DmPip",
                                              ws,
                                              time, terr, tag, id_plus,
                                              tagOmegaList,
                                              utils['tagEff'],
                                              gammad,
                                              deltaGammad,
                                              deltaMd,
                                              utils['C'],
                                              utils['D'],
                                              utils['Dbar'],
                                              utils['S'],
                                              utils['Sbar'],
                                              trm,
                                              tacc,
                                              terrpdf[i] if terrpdf != None else terrpdf,
                                              mistagPDFList,
                                              mistag,
                                              None,
                                              None,
                                              utils['aProd'],
                                              adet_plus,
                                              utils['aTagEff']))

        timePDFminus.append(buildBDecayTimePdf(myconfigfile,
                                               "Signal_DpPim",
                                               ws,
                                               time, terr, tag, id_minus,
                                               tagOmegaList,
                                               utils['tagEff'],
                                               gammad,
                                               deltaGammad,
                                               deltaMd,
                                               utils['C'],
                                               utils['D'],
                                               utils['Dbar'],
                                               utils['S'],
                                               utils['Sbar'],
                                               trm,
                                               tacc,
                                               terrpdf[i] if terrpdf != None else terrpdf,
                                               mistagPDFList,
                                               mistag,
                                               None,
                                               None,
                                               utils['aProd'],
                                               adet_minus,
                                               utils['aTagEff']))

        timePDF.append(WS(ws,RooSimultaneous("Signal", "Signal", id)))
        timePDF[i].addPdf(timePDFplus[i],"h+")
        timePDF[i].addPdf(timePDFminus[i],"h-")
        
                                          
    totPDF = []
    for i in range(0,bound):
        totPDF.append(timePDF[i]) 

    # Fitting
    # ---------------------------

    print "=========================================================="
    print "Fixing what is required for the fit"
    print "=========================================================="
    from B2DXFitters.utils import setConstantIfSoConfigured
    setConstantIfSoConfigured(myconfigfile, totPDF[0])

    print "=========================================================="
    print "Fitting"
    print "=========================================================="
    if not Blinding and toys: #Unblind yourself
        if nosWeights:
            myfitresult = totPDF[0].fitTo(dataA, RooFit.Save(1), RooFit.Optimize(2), RooFit.Strategy(2),\
                                          RooFit.Verbose(True), RooFit.SumW2Error(False), RooFit.Timer(True), RooFit.Offset(True))#,
            #RooFit.ExternalConstraints(constList))
        else:
            myfitresult = totPDF[0].fitTo(dataWA, RooFit.Save(1), RooFit.Optimize(2), RooFit.Strategy(2), RooFit.Timer(True),\
                                          RooFit.Verbose(True), RooFit.SumW2Error(True), RooFit.Timer(True), RooFit.Offset(True))#, 
            #RooFit.ExternalConstraints(constList))
        qual = myfitresult.covQual()
        status = myfitresult.status()
        print 'MINUIT status is ', myfitresult.status()
        print "---> Fit done; printing results"
        myfitresult.Print("v")
        myfitresult.correlationMatrix().Print()
        myfitresult.covarianceMatrix().Print()
        floatpar = myfitresult.floatParsFinal()
        initpar = myfitresult.floatParsInit()
        
    else :    #Don't
        myfitresult = totPDF[0].fitTo(dataWA, RooFit.Save(1), RooFit.Optimize(2), RooFit.Strategy(2),\
                                      RooFit.SumW2Error(True), RooFit.PrintLevel(-1), RooFit.Offset(True), #RooFit.ExternalConstraints(constList),
                                      RooFit.Timer(True))     

    print "=========================================================="
    print "Fit done; saving output workspace"
    print "=========================================================="
    workout = RooWorkspace("workspace","workspace")
        
    if nosWeights:
        getattr(workout,'import')(dataWA)
    else:
        getattr(workout,'import')(dataWA)
    getattr(workout,'import')(totPDF[0])
    getattr(workout,'import')(myfitresult)
    saveNameTS = TString(wsname)
    workout.Print()
    GeneralUtils.SaveWorkspace(workout,saveNameTS, debug)

    #Save fit results for pull plots
    if not Blinding and toys:
        from B2DXFitters.FitResultGrabberUtils import CreatePullTree as CreatePullTree
        CreatePullTree(fileNamePull, myfitresult, 'status')
Example #9
0
                       tree1.GetBranch(varName).GetTitle(),
                       tree1.GetMinimum(varName), tree1.GetMaximum(varName))
        ]
        varRenamedList += [RooFit.RenameVariable(varName, tupleDict[varName])]
        #RooFit.RenameVariable(varName, tupleDict[varName]);
        #varList[i].SetName(tupleDict.keys()[i]);

    #tupleDataSet = RooDataSet("treeData","treeData",tree1,RooArgSet(*varList));

    weightvar = RooRealVar("weight", "weight", -1e7, 1e7)
    tupleDataSet = RooDataSet("tupleDataSet", "tupleDataSet",
                              RooArgSet(*varList), RooFit.Import(tree1),
                              RooFit.WeightVar(weightvar))

    ws = RooWorkspace('ws_FIT')
    tupleDataSet = WS(ws, tupleDataSet, varRenamedList)

    tupleDataSet.Print()
    sys.exit(0)
    #qt needs to be a category?
    # Manuel's shit...
    #weightvar = RooRealVar("weight", "weight", -1e7, 1e7)
    #tupleDataSet = RooDataSet("tupleDataSet", "tupleDataSet",
    #    RooArgSet(treetime, treeqt, treeqf, treeeta),
    #    RooFit.Import(tree1), RooFit.WeightVar(weightvar))
    #tupleDS = WS(ws, tupleDS, [
    #    RooFit.RenameVariable("Bs_ctau", "time"), ... ])
    # # note: do not forget to add to fitTo options: RooFit.SumW2Error(True)
    #ROOT.SetOwnership(tupleDataSet,False);

    #tupleDataSet.get().find(varName).Print();
Example #10
0
import random
#random.seed(SEED);

genEtaList = TList();

for i in xrange(NUMCAT):
    
    # use workspace for fit pdf in such a simple fit
    fitconfig = copy.deepcopy(config1)
    fitconfig['Context'] = 'FIT%u' % i
    fitconfig['NBinsAcceptance'] = 0

    fitpdf = buildTimePdf(fitconfig)
    #ds = WS(fitpdf['ws'],ds);
    # add data set to fitting workspace
    ds1 = WS(fitpdf['ws'], dspercat[i])

    print 72 * "#"
    print "WS:" + str(fitpdf["ws"])
    print "PDF:" + str(fitpdf["pdf"])
    print "OBS:" + str(fitpdf["obs"])
    print "DS:" + str(ds1)
    fitpdf['ws'].Print("v")
    fitpdf['pdf'].Print("v")
    ds1.Print("v")
    mistag = fitpdf['ws'].obj("mistag")
    aveta = etaAvgList.At(i).getValV();
    mistag.setVal(aveta);
    mistag.setError(min([0.5 / NUMCAT / sqrt(12), abs(aveta) * 0.5, abs(aveta - 0.5) * 0.5]))
    mistag.Print("v")
    print 72 * "#"
Example #11
0
def buildTimePdf(config):
    """
    build time pdf, return pdf and associated data in dictionary
    """
    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])

    # start building the fit
    ws = RooWorkspace('ws_%s' % config['Context'])
    one = WS(ws, RooConstVar('one', '1', 1.0))
    zero = WS(ws, RooConstVar('zero', '0', 0.0))

    # start by defining observables
    time = WS(ws, RooRealVar('time', 'time [ps]', 0.3, 15.0))
    qf = WS(ws, RooCategory('qf', 'final state charge'))
    qf.defineType('h+', +1)
    qf.defineType('h-', -1)
    qt = WS(ws, RooCategory('qt', 'tagging decision'))
    qt.defineType('B+', +1)
    qt.defineType('Untagged', 0)
    qt.defineType('B-', -1)

    # now other settings
    Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661))  # ps^-1
    DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106))  # ps^-1
    Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719))  # ps^-1

    # HACK (1/2): be careful about lower bound on eta, since mistagpdf below
    # is zero below a certain value - generation in accept/reject would get
    # stuck
    eta = WS(ws, RooRealVar('eta', 'eta', 0.35, 0., 0.5))

    mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 1.0))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr',
                                0.039))  #CHANGE THIS LATER
    # fit average mistag
    # add mistagged
    #ge rid of untagged events by putting restriction on qf or something when reduceing ds
    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance

    if 'GEN' in config['Context']:
        obs = [qf, qt, time, eta]
    else:
        obs = [qf, qt, time]
    acc, accnorm = buildSplineAcceptance(
        ws, time, 'Bs2DsPi_accpetance',
        config['SplineAcceptance']['KnotPositions'],
        config['SplineAcceptance']['KnotCoefficients'][config['Context'][0:3]],
        'FIT' in config['Context'])  # float for fitting
    if 'GEN' in config['Context']:
        acc = accnorm  # use normalised acceptance for generation
    # get resolution model
    resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)
    if 'GEN' in config['Context']:
        # build a (mock) mistag distribution
        mistagpdfparams = {}  # start with parameters of mock distribution
        for sfx in ('omega0', 'omegaavg', 'f'):
            mistagpdfparams[sfx] = WS(
                ws,
                RooRealVar('Bs2DsPi_mistagpdf_%s' % sfx,
                           'Bs2DsPi_mistagpdf_%s' % sfx,
                           config['TrivialMistagParams'][sfx]))
        # build mistag pdf itself
        mistagpdf = WS(
            ws,
            MistagDistribution('Bs2DsPi_mistagpdf', 'Bs2DsPi_mistagpdf', eta,
                               mistagpdfparams['omega0'],
                               mistagpdfparams['omegaavg'],
                               mistagpdfparams['f']))
        mistagcalibparams = {}  # start with parameters of calibration
        for sfx in ('p0', 'p1', 'etaavg'):
            mistagcalibparams[sfx] = WS(
                ws,
                RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx,
                           'Bs2DsPi_mistagpdf_%s' % sfx,
                           config['MistagCalibParams'][sfx]))

        for sfx in ('p0', 'p1'):  # float calibration paramters
            mistagcalibparams[sfx].setConstant(False)
            mistagcalibparams[sfx].setError(0.1)

        # build mistag pdf itself
        omega = WS(
            ws,
            MistagCalibration('Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib',
                              eta, mistagcalibparams['p0'],
                              mistagcalibparams['p1'],
                              mistagcalibparams['etaavg']))

    # build the time pdf
    if 'GEN' in config['Context']:
        pdf = buildBDecayTimePdf(config,
                                 'Bs2DsPi',
                                 ws,
                                 time,
                                 timeerr,
                                 qt,
                                 qf, [[omega]], [tageff],
                                 Gamma,
                                 DGamma,
                                 Dm,
                                 C=one,
                                 D=zero,
                                 Dbar=zero,
                                 S=zero,
                                 Sbar=zero,
                                 timeresmodel=resmodel,
                                 acceptance=acc,
                                 timeerrpdf=None,
                                 mistagpdf=[mistagpdf],
                                 mistagobs=eta)
    else:
        adet = WS(ws, RooRealVar('adet', 'adet', 0., -.15, .15))
        aprod = WS(ws, RooRealVar('aprod', 'aprod', 0., -.15, .15))
        adet.setError(0.005)
        aprod.setError(0.005)
        pdf = buildBDecayTimePdf(config,
                                 'Bs2DsPi',
                                 ws,
                                 time,
                                 timeerr,
                                 qt,
                                 qf, [[eta]], [tageff],
                                 Gamma,
                                 DGamma,
                                 Dm,
                                 C=one,
                                 D=zero,
                                 Dbar=zero,
                                 S=zero,
                                 Sbar=zero,
                                 timeresmodel=resmodel,
                                 acceptance=acc,
                                 timeerrpdf=None,
                                 aprod=aprod,
                                 adet=adet)

    return {  # return things
        'ws': ws,
        'pdf': pdf,
        'obs': obs
    }
Example #12
0
import copy
# FIXME: need to deep-copy the config dictionary, and need to disable a few
# tweaks that speed up fitting during generation (because they waste time there)
genconfig = copy.deepcopy(config)
genconfig['Context'] = 'GEN'
genconfig['NBinsAcceptance'] = 0
genconfig['NBinsProperTimeErr'] = 0
genconfig['ParameteriseIntegral'] = False
genpdf = buildTimePdf(genconfig)

# generate 150K events
#print '150K'
#ds = genpdf['pdf'].generate(RooArgSet(*genpdf['obs']), 150000, RooFit.Verbose())
from B2DXFitters import datasetio

weight = WS(genpdf['ws'], RooRealVar(weightVarName, 'weight', -1e9, 1e9))

weight.Print()

for v in genpdf['obs']:
    v.Print('v')
obsset = RooArgSet(weight, *genpdf['obs'])
ds = datasetio.readDataSet(genconfig, genpdf['ws'], obsset)
#ds.Print();
#sys.exit(0);
#saveEta(ds);

# HACK (2/2): restore correct eta range after generation
ds.get().find('eta').setRange(0.0, 0.5)

ds.Print('v')
Example #13
0
    RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-9)
    RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-9)
    RooAbsReal.defaultIntegratorConfig().getConfigSection(
        'RooAdaptiveGaussKronrodIntegrator1D').setCatLabel(
            'method', '15Points')
    RooAbsReal.defaultIntegratorConfig().getConfigSection(
        'RooAdaptiveGaussKronrodIntegrator1D').setRealValue('maxSeg', 1000)
    RooAbsReal.defaultIntegratorConfig().method1D().setLabel(
        'RooAdaptiveGaussKronrodIntegrator1D')
    RooAbsReal.defaultIntegratorConfig().method1DOpen().setLabel(
        'RooAdaptiveGaussKronrodIntegrator1D')

    from B2DXFitters.WS import WS

    ws = RooWorkspace('ws_FIT')
    tupleDataSet = WS(ws, tupleDataSet, varRenamedList)

    #tupleDataSet =

    tupleDataSet.Print()

    config['Context'] = 'FIT'
    fitpdf = buildTimePdf1(config)
    #ws = fitpdf['ws'];
    tupleDataSet = WS(ws, tupleDataSet)
    tupleDataSet = WS(fitpdf['ws'], tupleDataSet)

    # set constant what is supposed to be constant
    from B2DXFitters.utils import setConstantIfSoConfigured
    setConstantIfSoConfigured(config, fitpdf['pdf'])
Example #14
0
def readDataSet(
    config,             # configuration dictionary
    ws,                 # workspace to which to add data set
    observables,        # observables
    rangeName = None    # name of range to clip dataset to
    ):
    """
    read data set from given Ntuple (or a RooDataSet inside a workspace) into
    a RooDataSet

    arguments:
    config      -- configuration dictionary (see below for relevant keys)
    ws          -- workspace into which to import data from tuple
    observables -- RooArgSet containing the observables to be read
    rangeName   -- optional, can be the name of a range of one observable, if
                   the data read from the tuple needs to be explicitly clipped
                   to that range for some reason

    the routine returns the data set that has been read in and stored inside
    ws.

    relevant configuration dictionary keys:
    'DataFileName' -- file name of data file from which to read ntuple or data
                      set
    'DataSetNames' -- name (TTree or RooDataSet) of the data set to be read;
                      more than one can be given in a dictionary, providing a
                      mapping between the sample name and the data set to be
                      read (see below for an explanation)
    'DataWorkSpaceName'
                   -- name of workspace to read data from (if any - leave None
                      for reading tuples)
    'DataSetCuts' --  cuts to apply to data sets on import - anything that
                      RooDataSet.reduce will understand is permissible here
                      (set to None to not apply any cuts on import)
    'DataSetVarNameMapping'
                   -- mapping from variable names in set of observables to
                      what these variable names are called in the
                      tuple/workspace to be imported

    "special" observable names:
    The routine treats some variable names special on import based on their
    likely meaning:
    'weight' -- this variable name must be used to read in (s)weighted events
    'qf'     -- final state charge (e.g. +1 for K+ vs -1 for K-); only the
                sign is important here, and the import code enforces that
    'qt'     -- tagging decision; this can be any integer number (positive or
                negative); if the tuple should contain a float/double with
                that information, it is rounded appropriately
    'mistag' -- predicted mistag; the import code makes sure that events with
                qt == 0 have mistag = 0.5
    'sample' -- if more than one final state is studied (e.g. Ds final states
                phipi, kstk, nonres, kpipi, pipipi), the events for these
                subsamples often reside in different samples; therefore the
                config dictionary entry 'DataSetNames' can contain a
                dictionary which maps the category labels (phipi etc) to the
                names of the data samples in the ROOT file/workspace

    The config dict key 'DataSetVarNameMapping' contains a useful feature:
    Instead of providing a one-to-one-mapping of observables to tuple/data set
    names, an observable can be calculated from more than one tuple column.
    This is useful e.g. to convert a tuple that's stored the tagging decision
    as untagged/mixed/unmixed, or to sum up sweights for the different
    samples. Most simple formulae should be supported, but constants in
    scientific notation (1.0E+00) are not for now (until someone write a
    better parser for this).

    Example:
    @code
    seed = 42 # it's easy to modify the filename depending on the seed number
    configdict = {
        # file to read from
        'DataFileName': '/some/path/to/file/with/toy_%04d.root' % seed,
        # data set is in a workspace already
        'DataWorkSpaceName':    'FitMeToolWS',
        # name of data set inside workspace
        'DataSetNames':         'combData',
        # mapping between observables and variable name in data set
        'DataSetVarNameMapping': {
            'sample':  'sample',
            'mass':    'lab0_MassFitConsD_M',
            'pidk':    'lab1_PIDK',
            'dsmass':  'lab2_MM',
            'time':    'lab0_LifetimeFit_ctau',
            'timeerr': 'lab0_LifetimeFit_ctauErr',
            'mistag':  'tagOmegaComb',
            'qf':      'lab1_ID',
            'qt': '    tagDecComb',
            # sweights need to be combined from different branches in this
            # case, only one of the branches is ever set to a non-zero value,
            # depending on which subsample the event is in
            'weight': ('nSig_both_nonres_Evts_sw+nSig_both_phipi_Evts_sw+'
                       'nSig_both_kstk_Evts_sw+nSig_both_kpipi_Evts_sw+'
                       'nSig_both_pipipi_Evts_sw')
            }
        }
    # define all observables somewhere, and put the into a RooArgSet called obs
    # import observables in to a workspace saved in ws

    # now read the data set
    data = readDataSet(configdict, ws, observables)
    @endcode
    """
    from ROOT import ( TFile, RooWorkspace, RooRealVar, RooCategory,
        RooBinningCategory, RooUniformBinning, RooMappedCategory,
        RooDataSet, RooArgSet, RooArgList )
    import sys, math
    # local little helper routine
    def round_to_even(x):
        xfl = int(math.floor(x))
        rem = x - xfl
        if rem < 0.5: return xfl
        elif rem > 0.5: return xfl + 1
        else:
            if xfl % 2: return xfl + 1
            else: return xfl
    # another small helper routine
    def tokenize(s, delims = '+-*/()?:'):
        # FIXME: this goes wrong for numerical constants like 1.4e-3
        # proposed solution: regexp for general floating point constants,
        # replace occurences of matches with empty string
        delims = [ c for c in delims ]
        delims.insert(0, None)
        for delim in delims:
            tmp = s.split(delim)
            tmp = list(set(( s + ' ' for s in tmp)))
            s = ''.join(tmp)
        tmp = list(set(s.split(None)))
        return tmp
    # figure out which names from the mapping we need - look at the observables
    names = ()
    for n in config['DataSetVarNameMapping'].keys():
        if None != observables.find(n):
            names += (n,)
    # build RooArgSets and maps with source and destination variables
    dmap = { }
    for k in names: dmap[k] = observables.find(k)
    if None in dmap.values():
        raise NameError('Some variables not found in destination: %s' % str(dmap))
    dset = RooArgSet()
    for v in dmap.values(): dset.add(v)
    if None != dset.find('weight'):
        # RooFit insists on weight variable being first in set
        tmpset = RooArgSet()
        tmpset.add(dset.find('weight'))
        it = dset.fwdIterator()
        while True:
            obj = it.next()
            if None == obj: break
            if 'weight' == obj.GetName(): continue
            tmpset.add(obj)
        dset = tmpset
        del tmpset
        ddata = RooDataSet('agglomeration', 'of positronic circuits', dset, 'weight')
    else:
        ddata = RooDataSet('agglomeration', 'of positronic circuits', dset)
    # open file with data sets
    f = TFile(config['DataFileName'], 'READ')
    # get workspace
    fws = f.Get(config['DataWorkSpaceName'])
    ROOT.SetOwnership(fws, True)
    if None == fws or not fws.InheritsFrom('RooWorkspace'):
        # ok, no workspace, so try to read a tree of the same name and
        # synthesize a workspace
        from ROOT import RooWorkspace, RooDataSet, RooArgList
        fws = RooWorkspace(config['DataWorkSpaceName'])
        iset = RooArgSet()
        addiset = RooArgList()
        it = observables.fwdIterator()
        while True:
            obj = it.next()
            if None == obj: break
            name = config['DataSetVarNameMapping'][obj.GetName()]
            vnames = tokenize(name)
            if len(vnames) > 1 and not obj.InheritsFrom('RooAbsReal'):
                print 'Error: Formulae not supported for categories'
                return None
            if obj.InheritsFrom('RooAbsReal'):
                if 1 == len(vnames):
                    # simple case, just add variable
                    var = WS(fws, RooRealVar(name, name, -sys.float_info.max,
                        sys.float_info.max))
                    iset.addClone(var)
                else:
                    # complicated case - add a bunch of observables, and
                    # compute something in a RooFormulaVar
                    from ROOT import RooFormulaVar
                    args = RooArgList()
                    for n in vnames:
                        try:
                            # skip simple numerical factors
                            float(n)
                        except:
                            var = iset.find(n)
                            if None == var:
                                var = WS(fws, RooRealVar(n, n, -sys.float_info.max,
                                    sys.float_info.max))
                                iset.addClone(var)
                                args.add(iset.find(n))
                    var = WS(fws, RooFormulaVar(name, name, name, args))
                    addiset.addClone(var)
            else:
                for dsname in ((config['DataSetNames'], )
                        if type(config['DataSetNames']) == str else
                        config['DataSetNames']):
                    break
                leaf = f.Get(dsname).GetLeaf(name)
                if None == leaf:
                    leaf = f.Get(dsname).GetLeaf(name + '_idx')
                if leaf.GetTypeName() in (
                        'char', 'unsigned char', 'Char_t', 'UChar_t',
                        'short', 'unsigned short', 'Short_t', 'UShort_t',
                        'int', 'unsigned', 'unsigned int', 'Int_t', 'UInt_t',
                        'long', 'unsigned long', 'Long_t', 'ULong_t',
                        'Long64_t', 'ULong64_t', 'long long',
                        'unsigned long long'):
                    var = WS(fws, RooCategory(name, name))
                    tit = obj.typeIterator()
                    ROOT.SetOwnership(tit, True)
                    while True:
                        tobj = tit.Next()
                        if None == tobj: break
                        var.defineType(tobj.GetName(), tobj.getVal())
                else:
                    var = WS(fws, RooRealVar(name, name, -sys.float_info.max,
                        sys.float_info.max))
                iset.addClone(var)
        for dsname in ((config['DataSetNames'], )
               if type(config['DataSetNames']) == str else
               config['DataSetNames']):
            tmpds = WS(fws, RooDataSet(dsname, dsname,f.Get(dsname), iset), [])
            if 0 != addiset.getSize():
                # need to add columns with RooFormulaVars
                tmpds.addColumns(addiset)
            del tmpds
    # local data conversion routine
    def doIt(config, rangeName, dsname, sname, names, dmap, dset, ddata, fws):
        sdata = fws.obj(dsname)
        if None == sdata: return 0
        if None != config['DataSetCuts']:
            # apply any user-supplied cuts
            newsdata = sdata.reduce(config['DataSetCuts'])
            ROOT.SetOwnership(newsdata, True)
            del sdata
            sdata = newsdata
            del newsdata
        sset = sdata.get()
        smap = { }
        for k in names:
            smap[k] = sset.find(config['DataSetVarNameMapping'][k])
        if 'sample' in smap.keys() and None == smap['sample'] and None != sname:
            smap.pop('sample')
            dmap['sample'].setLabel(sname)
        if None in smap.values():
            raise NameError('Some variables not found in source: %s' % str(smap))
        # # additional complication: toys save decay time in ps, data is in nm
        # # figure out which time conversion factor to use
        # timeConvFactor = 1e9 / 2.99792458e8
        # meantime = sdata.mean(smap['time'])
        # if ((dmap['time'].getMin() <= meantime and
        #         meantime <= dmap['time'].getMax() and config['IsToy']) or
        #         not config['IsToy']):
        #     timeConvFactor = 1.
        # print 'DEBUG: Importing data sample meantime = %f, timeConvFactor = %f' % (
        #         meantime, timeConvFactor)
        timeConvFactor = 1.
        # loop over all entries of data set
        ninwindow = 0
        if None != sname:
            sys.stdout.write('Dataset conversion and fixup: %s: progress: ' % sname)
        else:
            sys.stdout.write('Dataset conversion and fixup: progress: ')
        for i in xrange(0, sdata.numEntries()):
            sdata.get(i)
            if 0 == i % 128:
                sys.stdout.write('*')
            vals = { }
            for vname in smap.keys():
                obj = smap[vname]
                if obj.InheritsFrom('RooAbsReal'):
                    val = obj.getVal()
                    vals[vname] = val
                else:
                    val = obj.getIndex()
                    vals[vname] = val
            # first fixup: apply time/timeerr conversion factor
            if 'time' in dmap.keys():
                vals['time'] *= timeConvFactor
            if 'timeerr' in dmap.keys():
                vals['timeerr'] *= timeConvFactor
            # second fixup: only sign of qf is important
            if 'qf' in dmap.keys():
                vals['qf'] = 1 if vals['qf'] > 0.5 else (-1 if vals['qf'] <
                        -0.5 else 0.)
            # third fixup: untagged events are forced to 0.5 mistag
            if ('qt' in dmap.keys() and 'mistag' in dmap.keys() and 0 ==
                    vals['qt']):
                vals['mistag'] = 0.5
            # apply cuts
            inrange = True
            for vname in dmap.keys():
                if not dmap[vname].InheritsFrom('RooAbsReal'): continue
                # no need to cut on untagged events
                if 'mistag' == vname and 0 == vals['qt']: continue
                if None != rangeName and dmap[vname].hasRange(rangeName):
                    if (dmap[vname].getMin(rangeName) > vals[vname] or
                            vals[vname] >= dmap[vname].getMax(rangeName)):
                        inrange = False
                        break
                else:
                    if (dmap[vname].getMin() > vals[vname] or
                            vals[vname] >= dmap[vname].getMax()):
                        inrange = False
                        break
            # skip cuts which are not within the allowed range
            if not inrange: continue
            # copy values over, doing real-category conversions as needed
            for vname in smap.keys():
                dvar, svar = dmap[vname], vals[vname]
                if dvar.InheritsFrom('RooAbsRealLValue'):
                    if float == type(svar): dvar.setVal(svar)
                    elif int == type(svar): dvar.setVal(svar)
                elif dvar.InheritsFrom('RooAbsCategoryLValue'):
                    if int == type(svar): dvar.setIndex(svar)
                    elif float == type(svar):
                        dvar.setIndex(round_to_even(svar))
            if 'weight' in dmap:
                ddata.add(dset, vals['weight'])
            else:
                ddata.add(dset)
            ninwindow = ninwindow + 1
        del sdata
        sys.stdout.write(', done - %d events\n' % ninwindow)
        return ninwindow
    ninwindow = 0
    if type(config['DataSetNames']) == str:
        ninwindow += doIt(config, rangeName, config['DataSetNames'],
                None, names, dmap, dset, ddata, fws)
    else:
        for sname in config['DataSetNames'].keys():
            ninwindow += doIt(config, rangeName, config['DataSetNames'][sname],
                    sname, names, dmap, dset, ddata, fws)
    # free workspace and close file
    del fws
    f.Close()
    del f
    # put the new dataset into our proper workspace
    ddata = WS(ws, ddata, [])
    # for debugging
    if config['Debug']:
        ddata.Print('v')
        if 'qt' in dmap.keys():
            data.table(dmap['qt']).Print('v')
        if 'qf' in dmap.keys():
            data.table(dmap['qf']).Print('v')
        if 'qf' in dmap.keys() and 'qt' in dmap.keys():
            data.table(RooArgSet(dmap['qt'], dmap['qf'])).Print('v')
        if 'sample' in dmap.keys():
            data.table(dmap['sample']).Print('v')
    # all done, return Data to the bridge
    return ddata
Example #15
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
Example #16
0
ds = genpdf['pdf'].generate(RooArgSet(*genpdf['obs']), 150000,
                            RooFit.Verbose())
# HACK (2/2): restore correct eta range after generation
ds.get().find('eta').setRange(0.0, 0.5)

ds.Print('v')
for o in genpdf['obs']:
    if not o.InheritsFrom('RooAbsCategory'): continue
    ds.table(o).Print('v')

# use workspace for fit pdf in such a simple fit
config['Context'] = 'FIT'
config['NBinsAcceptance'] = 0
fitpdf = buildTimePdf(config)
# add data set to fitting workspace
ds = WS(fitpdf['ws'], ds)

# set constant what is supposed to be constant
from B2DXFitters.utils import setConstantIfSoConfigured
setConstantIfSoConfigured(config, fitpdf['pdf'])

# set up fitting options
fitopts = [
    RooFit.Timer(),
    RooFit.Save(),
    RooFit.Strategy(config['FitConfig']['Strategy']),
    RooFit.Optimize(config['FitConfig']['Optimize']),
    RooFit.Offset(config['FitConfig']['Offset']),
    RooFit.NumCPU(config['FitConfig']['NumCPU'])
]
Example #17
0
def buildTimePdf(config):
    """
    build time pdf, return pdf and associated data in dictionary
    """
    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])

    # start building the fit
    ws = RooWorkspace('ws_%s' % config['Context'])
    one = WS(ws, RooConstVar('one', '1', 1.0))
    zero = WS(ws, RooConstVar('zero', '0', 0.0))

    # start by defining observables
    time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
    qf = WS(ws, RooCategory('qf', 'final state charge'))
    qf.defineType('h+', +1)
    qf.defineType('h-', -1)
    qt = WS(ws, RooCategory('qt', 'tagging decision'))
    qt.defineType('B+', +1)
    qt.defineType('Untagged', 0)
    qt.defineType('B-', -1)

    # now other settings
    Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661))  # ps^-1
    DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106))  # ps^-1
    Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719))  # ps^-1

    # HACK (1/2): be careful about lower bound on eta, since mistagpdf below
    # is zero below a certain value - generation in accept/reject would get
    # stuck
    eta = WS(
        ws,
        RooRealVar(
            'eta', 'eta', 0.35, 0.0 if 'FIT' in config['Context'] else
            (1. + 1e-5) * max(0.0, config['TrivialMistagParams']['omega0']),
            0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))

    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance

    obs = [qt, qf, time, eta, timeerr]

    acc, accnorm = buildSplineAcceptance(
        ws, time, 'Bs2DsPi_accpetance',
        config['SplineAcceptance']['KnotPositions'],
        config['SplineAcceptance']['KnotCoefficients'][config['Context']],
        'FIT' in config['Context'])  # float for fitting
    if 'GEN' in config['Context']:
        acc = accnorm  # use normalised acceptance for generation
    # get resolution model
    resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)

    # build a (mock) mistag distribution
    mistagpdfparams = {}  # start with parameters of mock distribution
    for sfx in ('omega0', 'omegaavg', 'f'):
        mistagpdfparams[sfx] = WS(
            ws,
            RooRealVar('Bs2DsPi_mistagpdf_%s' % sfx,
                       'Bs2DsPi_mistagpdf_%s' % sfx,
                       config['TrivialMistagParams'][sfx]))
    # build mistag pdf itself
    mistagpdf = WS(
        ws,
        MistagDistribution('Bs2DsPi_mistagpdf', 'Bs2DsPi_mistagpdf', eta,
                           mistagpdfparams['omega0'],
                           mistagpdfparams['omegaavg'], mistagpdfparams['f']))
    # build mistag calibration
    mistagcalibparams = {}  # start with parameters of calibration
    for sfx in ('p0', 'p1', 'etaavg'):
        mistagcalibparams[sfx] = WS(
            ws,
            RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx,
                       'Bs2DsPi_mistagpdf_%s' % sfx,
                       config['MistagCalibParams'][sfx]))
    for sfx in ('p0', 'p1'):  # float calibration paramters
        mistagcalibparams[sfx].setConstant(False)
        mistagcalibparams[sfx].setError(0.1)
    # build mistag pdf itself
    omega = WS(
        ws,
        MistagCalibration('Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib', eta,
                          mistagcalibparams['p0'], mistagcalibparams['p1'],
                          mistagcalibparams['etaavg']))
    # build mock decay time error distribution (~ timeerr^6 * exp(-timerr /
    # (timerr_av / 7))
    terrpdf_shape = WS(
        ws,
        RooConstVar('timeerr_ac', 'timeerr_ac',
                    config['DecayTimeResolutionAvg'] / 7.))
    terrpdf_truth = WS(
        ws, RooTruthModel('terrpdf_truth', 'terrpdf_truth', timeerr))
    terrpdf_i0 = WS(
        ws,
        RooDecay('terrpdf_i0', 'terrpdf_i0', timeerr, terrpdf_shape,
                 terrpdf_truth, RooDecay.SingleSided))
    terrpdf_i1 = WS(
        ws,
        RooPolynomial('terrpdf_i1', 'terrpdf_i1', timeerr,
                      RooArgList(zero, zero, zero, zero, zero, zero, one), 0))
    terrpdf = WS(ws, RooProdPdf('terrpdf', 'terrpdf', terrpdf_i0, terrpdf_i1))

    # build the time pdf
    pdf = buildBDecayTimePdf(config,
                             'Bs2DsPi',
                             ws,
                             time,
                             timeerr,
                             qt,
                             qf, [[omega]], [tageff],
                             Gamma,
                             DGamma,
                             Dm,
                             C=one,
                             D=zero,
                             Dbar=zero,
                             S=zero,
                             Sbar=zero,
                             timeresmodel=resmodel,
                             acceptance=acc,
                             timeerrpdf=terrpdf,
                             mistagpdf=[mistagpdf],
                             mistagobs=eta)
    return {  # return things
        'ws': ws,
        'pdf': pdf,
        'obs': obs
    }
Example #18
0
    'RooAdaptiveGaussKronrodIntegrator1D').setRealValue('maxSeg', 1000)
RooAbsReal.defaultIntegratorConfig().method1D().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')
RooAbsReal.defaultIntegratorConfig().method1DOpen().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')

# seed the Random number generator
rndm = TRandom3(SEED + 1)
RooRandom.randomGenerator().SetSeed(int(rndm.Uniform(4294967295)))
del rndm

# start building the fit
from B2DXFitters.WS import WS

ws = RooWorkspace('ws')
one = WS(ws, RooConstVar('one', '1', 1.0))
zero = WS(ws, RooConstVar('zero', '0', 0.0))

# start by defining observables
time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
qf = WS(ws, RooCategory('qf', 'final state charge'))
qf.defineType('h+', +1)
qf.defineType('h-', -1)
qt = WS(ws, RooCategory('qt', 'tagging decision'))
qt.defineType(      'B+', +1)
qt.defineType('Untagged',  0)
qt.defineType(      'B-', -1)

# now other settings
Gamma  = WS(ws, RooRealVar( 'Gamma',  'Gamma',  0.661)) # ps^-1
DGamma = WS(ws, RooRealVar('DGamma', 'DGamma',  0.106)) # ps^-1
Example #19
0
# seed the Random number generator
rndm = TRandom3(SEED + 1)
RooRandom.randomGenerator().SetSeed(int(rndm.Uniform(4294967295)))
del rndm

# start building the fit
from B2DXFitters.WS import WS

ws = RooWorkspace('ws')
one = WS(ws, RooConstVar('one', '1', 1.0))
zero = WS(ws, RooConstVar('zero', '0', 0.0))

# start by defining observables
time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
qf = WS(ws, RooCategory('qf', 'final state charge'))
qf.defineType('h+', +1)
qf.defineType('h-', -1)
qt = WS(ws, RooCategory('qt', 'tagging decision'))
qt.defineType(      'B+', +1)
qt.defineType('Untagged',  0)
qt.defineType(      'B-', -1)

# now other settings
Gamma  = WS(ws, RooRealVar( 'Gamma',  'Gamma',  0.661)) # ps^-1
DGamma = WS(ws, RooRealVar('DGamma', 'DGamma',  0.106)) # ps^-1
Dm     = WS(ws, RooRealVar(    'Dm',     'Dm', 17.719)) # ps^-1

mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5))
tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))
Example #20
0
    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

results = []
for tag in xrange(0, 4):
    ws = RooWorkspace('ws')

    gamma =         WS(ws, RooRealVar('Gamma',      'Gamma',        1.0, 0.1, 2.5))
    dGamma =        WS(ws, RooRealVar('dGamma',     'dGamma',       0.5, 0.0, 2.5))
    SF =            WS(ws, RooConstVar('SF',        'SF',           1.37))
    tau = WS(ws, Inverse('tau', 'tau', gamma))

    one =           WS(ws, RooConstVar('one',      'one',          1.))
    zero =          WS(ws, RooConstVar('zero',     'zero',         0.))

    # observable
    time = WS(ws, RooRealVar('time', '#tau(combinatorial) [ps]', *TimeRange))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', *TimeErrRange))

    tacc, tacc_norm = accbuilder(time, knots[BDTGRange[0:2]], coeffs[isDsK][BDTGRange])

    ds = getDataSet(ws,
            '%s && %u == abs(lab0_TAGDECISION_OS) && '
Example #21
0
def buildTimePdf(config, tupleDataSet, tupleDict):

    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])

    ws = RooWorkspace('ws_%s' % config['Context'])
    one = WS(ws, RooConstVar('one', '1', 1.0))
    zero = WS(ws, RooConstVar('zero', '0', 0.0))
    ###USE FIT CONTEXT
    """
    build time pdf, return pdf and associated data in dictionary
    """
    # start by defining observables
    time = WS(ws,
              tupleDataSet.get().find('ct'))
    #qt = WS(ws, tupleDataSet.get().find('ssDecision'));
    '''
    time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
    '''
    qf = WS(ws, RooCategory('qf', 'final state charge'))
    qf.defineType('h+', +1)
    qf.defineType('h-', -1)

    qt = WS(ws, RooCategory('qt', 'tagging decision'))
    qt.defineType('B+', +1)
    qt.defineType('Untagged', 0)
    qt.defineType('B-', -1)

    # now other settings
    Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661))  # ps^-1
    DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106))  # ps^-1
    Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719))  # ps^-1

    # HACK (1/2): be careful about lower bound on eta, since mistagpdf below
    # is zero below a certain value - generation in accept/reject would get
    # stuck
    if 'GEN' in config['Context'] or 'FIT' in config['Context']:
        eta = WS(
            ws,
            RooRealVar(
                'eta', 'eta', 0.35, 0.0 if 'FIT' in config['Context'] else
                (1. + 1e-5) *
                max(0.0, config['TrivialMistagParams']['omega0']), 0.5))

    mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
    terrpdf = WS(ws,
                 tupleDataSet.get().find('cterr'))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))
    #MISTAGPDF
    # fit average mistag
    # add mistagged
    #ge rid of untagged events by putting restriction on qf or something when reduceing ds
    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance

    obs = [qf, qt, time]
    acc, accnorm = buildSplineAcceptance(
        ws, time, 'Bs2DsPi_accpetance',
        config['SplineAcceptance']['KnotPositions'],
        config['SplineAcceptance']['KnotCoefficients'][config['Context'][0:3]],
        'FIT' in config['Context'])  # float for fitting
    # get resolution model
    resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)
    mistagpdf = WS(
        ws,
        RooArgList(tupleDataSet.get().find('ssMistag'),
                   tupleDataSet.get().find('osMistag')))
    #???
    '''
    if 'GEN' in config['Context']:
        # build a (mock) mistag distribution
        mistagpdfparams = {} # start with parameters of mock distribution
        for sfx in ('omega0', 'omegaavg', 'f'):
            mistagpdfparams[sfx] = WS(ws, RooRealVar(
                    'Bs2DsPi_mistagpdf_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx,
                    config['TrivialMistagParams'][sfx]))
        # build mistag pdf itself
        mistagpdf = WS(ws, [tupleDataSet.reduce('ssMistag'), tupleDataSet.reduce('osMistag')]);
        mistagcalibparams = {} # start with parameters of calibration
        for sfx in ('p0', 'p1', 'etaavg'):
            mistagcalibparams[sfx] = WS(ws, RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx,config['MistagCalibParams'][sfx]));
        
        
        for sfx in ('p0', 'p1'): # float calibration paramters
            mistagcalibparams[sfx].setConstant(False)
            mistagcalibparams[sfx].setError(0.1)
        
        # build mistag pdf itself
        omega = WS(ws, MistagCalibration(
            'Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib',
            eta, mistagcalibparams['p0'], mistagcalibparams['p1'],
            mistagcalibparams['etaavg']))
    
    # build the time pdf
    if 'GEN' in config['Context']:
        pdf = buildBDecayTimePdf(
            config, 'Bs2DsPi', ws,
            time, timeerr, qt, qf, [ [ omega ] ], [ tageff ],
            Gamma, DGamma, Dm,
            C = one, D = zero, Dbar = zero, S = zero, Sbar = zero,
            timeresmodel = resmodel, acceptance = acc, timeerrpdf,
            mistagpdf = [mistagpdf], mistagobs = eta)
    else:
        pdf = buildBDecayTimePdf(
            config, 'Bs2DsPi', ws,
            time, timeerr, qt, qf, [ [ eta ] ], [ tageff ],
            Gamma, DGamma, Dm,
            C = one, D = zero, Dbar = zero, S = zero, Sbar = zero,
            timeresmodel = resmodel, acceptance = acc, timeerrpdf = None)
    '''

    pdf = buildBDecayTimePdf(config,
                             'Bs2DsPi',
                             ws,
                             time,
                             timeerr,
                             qt,
                             qf, [[eta]], [tageff],
                             Gamma,
                             DGamma,
                             Dm,
                             C=one,
                             D=zero,
                             Dbar=zero,
                             S=zero,
                             Sbar=zero,
                             timeresmodel=resmodel,
                             acceptance=acc,
                             timeerrpdf=terrpdf,
                             mistagpdf=[mistagpdf],
                             mistagobs=eta)

    return {  # return things
        'ws': ws,
        'pdf': pdf,
        'obs': obs
    }
def GenTimePdfUtils(configfile,
                    workspace,
                    Gamma,
                    DeltaGamma,
                    DeltaM,
                    singletagger,
                    notagging,
                    noprodasymmetry,
                    notagasymmetries,
                    debug) :
    print ""
    print "================================================================"
    print " Utilities for building signal time PDF..."
    print "================================================================"
    print ""

    #CP observables
    print "=> Defining CP observables..."

    ACPobs = cpobservables.AsymmetryObservables(configfile["DecayRate"]["ArgLf_d"], configfile["DecayRate"]["ArgLbarfbar_d"], configfile["DecayRate"]["ModLf_d"])
    ACPobs.printtable()

    C     = WS(workspace,RooRealVar('C','C',ACPobs.Cf(),param_limits["lower"], param_limits["upper"]))
    S     = WS(workspace,RooRealVar('S','S',ACPobs.Sf(),param_limits["lower"], param_limits["upper"]))
    D     = WS(workspace,RooRealVar('D','D',ACPobs.Df(),param_limits["lower"], param_limits["upper"]))
    Sbar  = WS(workspace,RooRealVar('Sbar','Sbar',ACPobs.Sfbar(),param_limits["lower"], param_limits["upper"]))
    Dbar  = WS(workspace,RooRealVar('Dbar','Dbar',ACPobs.Dfbar(),param_limits["lower"], param_limits["upper"]))

    #C     = WS(workspace,RooRealVar('C','C',0.0))
    #S     = WS(workspace,RooRealVar('S','S',0.0))
    #D     = WS(workspace,RooRealVar('D','D',0.0))
    #Sbar  = WS(workspace,RooRealVar('Sbar','Sbar',0.0))
    #Dbar  = WS(workspace,RooRealVar('Dbar','Dbar',0.0))

    #setConstantIfSoConfigured(C,configfile)
    #setConstantIfSoConfigured(S,configfile)
    #setConstantIfSoConfigured(D,configfile)
    #setConstantIfSoConfigured(Sbar,configfile)
    #setConstantIfSoConfigured(Dbar,configfile)

    #Tagging efficiency
    print "=> Getting tagging efficiency..."
    tagEff = []
    tagEffList = []
    if notagging:
        print "=> Perfect tagging"
        if singletagger:
            print "=> Single tagger"
            tagEff.append(WS(workspace,RooRealVar('tagEff_'+str(1), 'Tagging efficiency', 1.0)))
            printifdebug(debug,tagEff[0].GetName()+": "+str(tagEff[0].getVal()) )
            tagEffList.append(tagEff[0])
        else:
            print "=> More taggers"
            for i in range(0,3):
                tagEff.append(WS(workspace,RooRealVar('tagEff_'+str(i+1), 'Tagging efficiency', 1.0)))
                printifdebug(debug,tagEff[i].GetName()+": "+str(tagEff[i].getVal()) )
                tagEffList.append(tagEff[i])
    else:
        print "=> Non-trivial tagging"
        if singletagger:
            print "=> Single tagger"
            tagEff.append(WS(workspace,RooRealVar('tagEff_'+str(1), 'Tagging efficiency', configfile["TagEff"]["Signal"][0])))
            printifdebug(debug,tagEff[0].GetName()+": "+str(tagEff[0].getVal()) )
            tagEffList.append(tagEff[0])
        else:
            print "=> More taggers"
            for i in range(0,3):
                tagEff.append(WS(workspace,RooRealVar('tagEff_'+str(i+1), 'Tagging efficiency', configfile["TagEff"]["Signal"][i])))
                printifdebug(debug,tagEff[i].GetName()+": "+str(tagEff[i].getVal()) )
                tagEffList.append(tagEff[i])

    #Asymmetries
    print "=> Getting production asymmetry..."
    if noprodasymmetry:
        print "=> No asymmetries"
        aProd = None
    else:
        print "=> Non-zero asymmetry"                        
        aProd   = WS(workspace,RooRealVar('aprod',   'aprod',   configfile["AProd"]["Signal"], -1.0, 1.0))
        #setConstantIfSoConfigured(aProd,configfile)
        printifdebug(debug,aProd.GetName()+": "+str(aProd.getVal()) )
        
    print "=> Getting tagging asymmetries..."
    if notagasymmetries:
        print "=> No asymmetries"
        aTagEffList = None
    else:
        aTagEff = []
        aTagEffList = []
        print "=> Non-zero asymmetries"
        if singletagger:
            aTagEff.append(WS(workspace,RooRealVar('aTagEff_'+str(1), 'atageff', configfile["ATagEff"]["Signal"][0])))
            printifdebug(debug,aTagEff[0].GetName()+": "+str(aTagEff[0].getVal()) )
            aTagEffList.append(aTagEff[0])
        else:
            for i in range(0,3):
                aTagEff.append(WS(workspace,RooRealVar('aTagEff_'+str(i+1), 'atageff', configfile["ATagEff"]["Signal"][i])))
                printifdebug(debug,aTagEff[i].GetName()+": "+str(aTagEff[i].getVal()) )
                aTagEffList.append(aTagEff[i])

    #Summary of memory location
    if debug:
        print "==> Memory location of returned objects:"
        print "C: "
        print C
        print C.getVal()
        print "D: "
        print D
        print D.getVal()
        print "Dbar: "
        print Dbar
        print Dbar.getVal()
        print "S: "
        print S
        print S.getVal()
        print "Sbar: "
        print Sbar
        print Sbar.getVal()
        print "aProd: "
        print aProd
        if None != aProd: print aProd.getVal()
        print "tagEff: "
        print tagEff
        print "aTagEff: "
        print aTagEffList
        
    #Return things
    return { 'C': C,
             'D': D,
             'Dbar': Dbar,
             'S': S,
             'Sbar': Sbar,
             'aProd': aProd,
             'tagEff': tagEffList,
             'aTagEff': aTagEffList }