Esempio n. 1
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
            }
Esempio n. 2
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
    }
Esempio n. 3
0
tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))

# for now, we're in the generation stage
# (for a bigger project, you want separate config dicts for generation and
# fitting)
config['Context'] = 'GEN'

# now build the PDF
from B2DXFitters.timepdfutils import buildBDecayTimePdf
from B2DXFitters.resmodelutils import getResolutionModel
from B2DXFitters.utils import setConstantIfSoConfigured

obs = RooArgSet(qf, qt, time)
acc = None # no acceptance
resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)
genpdf = buildBDecayTimePdf(
    config, 'GEN-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)

# generate 150K events
ds = genpdf.generate(obs, 150000, RooFit.Verbose())

ds.Print('v')
ds.table(qf).Print('v')
ds.table(qt).Print('v')

# use workspace for fit pdf in such a simple fit
Esempio n. 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

    # 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
    }
Esempio n. 5
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
    }
Esempio n. 6
0
# for now, we're in the generation stage
config['Context'] = 'GEN'

# now build the PDF
from B2DXFitters.timepdfutils_Bd import buildBDecayTimePdf
from B2DXFitters.resmodelutils import getResolutionModel
from B2DXFitters.acceptanceutils import buildSplineAcceptance
from B2DXFitters.utils import setConstantIfSoConfigured

acc, accnorm = buildSplineAcceptance(ws, time, 'acceptance_GEN',
    config['SplineAcceptance']['KnotPositions'],
    config['SplineAcceptance']['KnotCoefficients'][config['Context']],
    False, True)
acc = accnorm #use normalised acceptance for generation
resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)

# build generating pdf
genpdf = buildBDecayTimePdf(
    config, 'GEN-time-pdf', ws,
    time, timeerr, qt, qf, mistagobs, mistagcalib,
    Gamma, DGamma, Dm,
    C, D, Dbar, S, Sbar,
    resmodel, acc,
    terrpdf, mistagpdf,
    aprod, adet)

# generate "proto data" for mistag and time error
proto_data = WS(ws, mistagpdf_os.generate(RooArgSet(mistag_os), nevts))
mistag_ss_data = WS(ws, mistagpdf_ss.generate(RooArgSet(mistag_ss), nevts))
terr_data = WS(ws, terrpdf.generate(RooArgSet(timeerr), nevts))
Esempio n. 7
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
            }
Esempio n. 8
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
    }
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')