Example #1
0
def createSData( **kwargs ) :
    # make sweighted dataset using J/psi phi mass
    Observables = kwargs.pop('Observables')
    Data        = kwargs.pop('Data')
    FitOpts     = kwargs.pop('FitOpts')
    Components  = kwargs.pop('Components')
    Name        = kwargs.pop('Name')
    from P2VV.RooFitWrappers import buildPdf
    pdf = buildPdf( Components, Observables = Observables, Name= Name + '_splot_pdf')
    c_m = pdf.fitTo(Data,**FitOpts)
    c_state = dict( ( p, p.isConstant() ) for p in pdf.Parameters() )
    for p in pdf.Parameters() : p.setConstant( not p.getAttribute('Yield') )
    sdata =  SData(Pdf = pdf, Data = Data, Name = Name + '_sdata')
    for p,c in c_state.iteritems() : p.setConstant(c)
    return sdata
    sigMassArgs['m_sig_alpha_2'] =  2.5
    sigMassArgs['m_sig_n_1']     =  1.5
    sigMassArgs['m_sig_n_2']     =  2.0
else :
    from P2VV.Parameterizations.MassPDFs import DoubleGauss_Signal_Mass as SignalBMass
signalBMass = SignalBMass( **sigMassArgs )
sigMassComps += signalBMass.pdf()

# build the combinatorial background mass PDF
from P2VV.Parameterizations.MassPDFs import LP2011_Background_Mass as BackgroundBMass
backgroundBMass = BackgroundBMass( Name = 'cbkg_m', mass = observables['mass'] )
cbkgMassComps += backgroundBMass.pdf()

# build total mass PDF
from P2VV.RooFitWrappers import buildPdf
massPdf = buildPdf( massComps, Observables = [ observables['mass'] ], Name = 'JpsiKKMass' )

# get splitting categories and parameters
yieldNames  = [ par.GetName() for par in massPdf.Parameters() if par.getAttribute('Yield') ]
allParNames = [ par.GetName() for par in massPdf.Parameters() if not par.getAttribute('Yield') if not par.isConstant() ]
sigParNames = [ par.GetName() for par in signalBMass.parameters() if not par.isConstant() ]
bkgParNames = [ par.GetName() for par in backgroundBMass.parameters() if not par.isConstant() ]
splitCats = {  observables['runPeriod'].GetName() : set( yieldNames + bkgParNames )
             , observables['KKMassCat'].GetName() : set( yieldNames               )
            }
if not biasedOnly :
    splitCats[ observables['hlt2B'].GetName() ] = set( yieldNames + bkgParNames )
if model == 'ipatia2' :
    # split Ipatia 2 signal parameters
    hlt2BName = observables['hlt2B'].GetName()
    KKCatName = observables['KKMassCat'].GetName()
Example #3
0
pdfConfig.readParametersFromFile( filePath = parameterFile )
pdfConfig.setParametersInPdf(pdf)

# Hack to set maximum value
pdf.setMaxVal(0.15)

# Wrong PV shape
from P2VV.Parameterizations.WrongPV import ShapeBuilder
from P2VV.RooFitWrappers import Component, Projection
wpv = ShapeBuilder(time, {'B' : BMass}, UseKeysPdf = True, Weights = 'B',
                   InputFile = "/bfys/raaij/p2vv/data/Bs2JpsiPhiPrescaled_2011.root")
wpv_signal = wpv.shape('B')

# Projection over time of signal PDF
projection = Projection(Name = 'pdf_angles', Original = pdf, ProjectVars = [time])
signal_wpv = Component('signal_wpv', (projection, wpv_signal), Yield = (100, 50, 10000))

signal = pdfBuild._signalComps
signal.setYield(10000, 5000, 50000)

from P2VV.RooFitWrappers import buildPdf
genPdf = buildPdf(Components = [signal_wpv, signal], Observables = angles + [time], Name = 'genPdf')

# run the toy
genPdf.fixAddCoefNormalization(RooArgSet(*gen_observables))

toy.set_fit_opts(**dict(Verbose = False))
toy.run(Observables = gen_observables, Pdf = pdf, GenPdf = genPdf, ProtoData = proto_data)

toy.write_output()
Example #4
0
    dataFile.Close()

print 'build mass PDF'
from P2VV.RooFitWrappers import Component
sigMassComps = Component( 'sigMass', [ ], Yield = ( 85.e3, 0., 2.e5 ) )
bkgMassComps = Component( 'bkgMass', [ ], Yield = (  1.e5, 0., 2.e5 ) )
yields = [ comp.getYield() for comp in [ sigMassComps, bkgMassComps ] ]

from P2VV.Parameterizations.MassPDFs import DoubleGauss_Signal_Mass as SignalBMass
sigMass = SignalBMass( mass = mass )
sigMassComps += sigMass.pdf()
from P2VV.Parameterizations.MassPDFs import LP2011_Background_Mass as BackgroundBMass
bkgMass = BackgroundBMass( mass = mass )
bkgMassComps += bkgMass.pdf()
from P2VV.RooFitWrappers import buildPdf
massPdf = buildPdf( [ sigMassComps, bkgMassComps ], Observables = [ mass ], Name = 'JpsiKKMass' )

ws['N_sigMass'].setVal(123.e3)
ws['m_sig_mean'].setVal(5368.2)
ws['m_sig_sigma_1'].setVal(5.6)
ws['m_sig_sigma_2'].setVal(14.)
ws['m_sig_frac'].setVal(0.65)
ws['m_bkg_exp'].setVal(-0.0015)
massPdf.getVariables().Print('v')

print 'draw mass plots'
from P2VV.Load import LHCbStyle
from ROOT import gStyle, TCanvas, kFullDotLarge, kBlack, kBlue, kGreen, kRed, kYellow
gStyle.SetColorModelPS(1)
colours = dict( none = kBlack, trigger = kBlack, KKPT = kBlue, vertex = kGreen + 3, time = kYellow + 3, all = kRed )
nBins = int( ( massPlotRange[1] - massPlotRange[0] ) / binSize )
Example #5
0
def dilution_bins(data, t_var, sigmat, sigmat_cat, result = None, signal = [], subtract = [], raw = False, calibration = None, n_bins = 512, mean_param = None, t_range = None):
    if calibration:
        assert(sigmat.GetName() in [p.GetName() for p in calibration.getVariables()])
        calibration.redirectServers(data.get())

    assert(t_var.getMin() < 0)

    from ROOT import RooBinning
    if not t_range:
        ft_left = 0
        t_range = ft_left - t_var.getMin()
        diff = t_range / float(n_bins)
        dilution_bounds = array('d', (t_var.getMin() + i * diff for i in range(n_bins + 1)))
        b = diff
        t_max = t_var.getMax()
        while b < t_max:
            dilution_bounds.append(b)
            b += diff
        if dilution_bounds[-1] != t_max:
            dilution_bounds.append(t_max)
    else:
        diff = t_range / float(n_bins)
        ft_left = t_var.getMin()
        dilution_bounds = array('d', (t_var.getMin() + i * diff for i in range(n_bins + 1)))
    dilution_binning = RooBinning(len(dilution_bounds) - 1, dilution_bounds)
    dilution_binning.SetName('dilution_binning')

    if not subtract:
        dilutions = []
        total = 0
        for ct in sigmat_cat:
            bin_data = data.reduce('{0} == {0}::{1}'.format(sigmat_cat.GetName(), ct.GetName()))
            n = bin_data.sumEntries()
            d = dilution_bin(bin_data, t_var, dilution_binning, n_bins = n_bins,
                             st = sigmat, mean_param = mean_param)
            dilutions.append((n, d))
        dt = sum(d[0] * d[1][0] for d in dilutions) / sum(d[0] for d in dilutions)
        de = sum(d[0] * d[1][1] ** 2 for d in dilutions) / sum(d[0] for d in dilutions)
        return dt, sqrt(de)

    subtract_pdf = buildPdf(Components = subtract, Observables = (t_var,),
                            Name='subtract_%s_pdf' % '_'.join(c.GetName() for c in subtract))
    sub_pars = subtract_pdf.getVariables()
    for res_par in result.floatParsFinal():
        sub_par = sub_pars.find(res_par.GetName())
        if sub_par:
            print 'setting value of subtract pdf parameter %s' % sub_par.GetName()
            sub_par.setVal(res_par.getVal())
            sub_par.setError(res_par.getError())

    # Get the signal yields from the fit result
    from itertools import product
    sig_yield_names = [s.getYield().GetName() for s in signal]
    from collections import defaultdict
    signal_yields = defaultdict(list)
    bin_names = [ct.GetName() for ct in sigmat_cat]
    for p in result.floatParsFinal():
        for s, b in product(sig_yield_names, bin_names):
            if p.GetName() == '_'.join((s, b)):
                signal_yields[b].append(p.getVal())
    signal_yield = sum(e[0] for e in signal_yields.itervalues())

    total = 0
    for ct in sigmat_cat:
        bin_data = data.reduce('{0} == {0}::{1}'.format(st_cat.GetName(), ct.GetName()))
        bin_name = ct.GetName()
        d = dilution_bin(t_var, bin_data, result, bin_name, dilution_binning,
                         signal, subtract_pdf, subtract, n_bins = n_bins)
        total += sum(signal_yields[ct.GetName()]) * d ** 2
    total /= signal_yield
    return total
                               , m_sig_sigma_sf = dict( Value = 1.7,    Error = 0.1,  MinMax = ( 0.1,   5.0   ) )
                               , m_sig_alpha_1  = dict( Value = 1.90,   Error = 0.04, MinMax = ( 1.0,   3.0   ) )
                               , m_sig_alpha_sf = dict( Value = 1.4,    Error = 0.3,  MinMax = ( 0.1,   5.0   ), ObjectType = 'RealVar' )
                               , m_sig_n_1      = dict( Value = 2. )
                               , m_sig_n_2      = dict( Value = 2. )
                              )
#mumuBkg = Linear_Background_Mass( Name = 'bkg_mumu', mass = mumuMass, Constant = True )

#Initialize Components
from P2VV.RooFitWrappers import buildPdf, Component
mumuMassSigComp = Component('mumuSig', ( mumuSig.pdf(), ), Yield = ( 27000.,                        0., sigData.sumEntries() ) )
#mumuMassBkgComp = Component('mumuBkg', ( mumuBkg.pdf(), ), Yield = ( sigData.sumEntries() - 27000., 0., sigData.sumEntries() ) )

#Build mumu Mass Pdf
#mumuMassPdf = buildPdf(Components = ( mumuMassSigComp, mumuMassBkgComp ), Observables = (mumuMass, ), Name='mumuMassPdf'  )
mumuMassPdf = buildPdf(Components = ( mumuMassSigComp, ), Observables = (mumuMass, ), Name='mumuMassPdf'  )

#Fit
#ws.var('m_bkg_arg').setRange(-1e-4,.5) 
fitResult = mumuMassPdf.fitTo( sigData, SumW2Error = False, Save = True, **fitOpts )
fitResult.PrintSpecial( text = True )

#Plot
mumuMassPlot = mumuMass.frame(60)

#sigArgs = {'Components':'sig_mumu', 'LineColor':kRed,     'LineStyle':10, 'LineWidth':3}
#bkgArgs = {'Components':'bkg_mumu', 'LineColor':kGreen+3, 'LineStyle': 2, 'LineWidth':3}

if drawTotalDists :
    data.plotOn( mumuMassPlot, MarkerStyle = kFullCircle, MarkerSize = 0.5, MarkerColor = kRed, LineWidth = 2, LineColor = kRed )
sigData.plotOn( mumuMassPlot, MarkerStyle = kFullCircle, MarkerSize = 0.5, LineWidth = 2)