Exemple #1
0
def getTrueOmegasPerCat(config, mistagobs, mistag, mistagpdf):
    """
    estimate the per-category mistag (omega_i) as starting value for the fit

    calculate true per-category omegas based on the mistagpdf and the
    calibration that goes into the generation pdf

    config      -- config dictionary
    mistagobs   -- mistag observable (eta)
    mistag      -- calibrated mistag (omega(eta))
    mistagpdf   -- mistag pdf (P(eta))

    returns a pair of average mistag omega, list of per-category mistag
    (omega) averages

    relevant config dictionary keys:
    'MistagCategoryBinBounds':
        list of mistag category bin bounds (one more entry than mistag
        categories)
    """
    from ROOT import RooRealVar, RooCustomizer, RooProduct, RooArgList, RooArgSet
    eta1 = RooRealVar('eta1', 'eta1', mistagobs.getMin(),
            mistagobs.getMin(), mistagobs.getMax())
    eta2 = RooRealVar('eta2', 'eta2', mistagobs.getMax(),
            mistagobs.getMin(), mistagobs.getMax())
    prod = RooProduct('prod', 'prod', RooArgList(mistag, mistagpdf))
    oldmistagobs = mistagobs
    mistagobs = mistagobs.clone(mistagobs.GetName() + '_catclone')
    ROOT.SetOwnership(mistagobs, True)
    mistagobs.setRange(eta1, eta2)
    c = RooCustomizer(prod, 'cust')
    c.replaceArg(oldmistagobs, mistagobs)
    prod = c.build()
    ROOT.SetOwnership(prod, True)
    c = RooCustomizer(mistagpdf, 'cust2')
    c.replaceArg(oldmistagobs, mistagobs)
    pdf = c.build()
    ROOT.SetOwnership(pdf, True)
    if pdf.InheritsFrom('RooHistPdf'): pdf.forceNumInt()
    evnumer = prod.createIntegral(RooArgSet(mistagobs))
    evdenom = pdf.createIntegral(RooArgSet(mistagobs))
    totevdenom = evdenom.getVal()
    avomega = evnumer.getVal() / totevdenom
    omegas = [ ]
    for i in xrange(0, len(config['MistagCategoryBinBounds']) - 1):
        eta1.setVal(config['MistagCategoryBinBounds'][i])
        eta2.setVal(config['MistagCategoryBinBounds'][i + 1])
        omegas.append(evnumer.getVal() / evdenom.getVal())
    print 'INFO: Mistag calibration %s:' % mistag.GetName()
    print 'INFO:                Average omega (PDF): %g' % avomega
    print 'INFO:  Per category average omegas (PDF): %s' % str(omegas)
    return avomega, omegas
Exemple #2
0
def rooFit207():
    
    print ">>> setup model signal components: gaussians..."
    x     = RooRealVar("x","x",0,10)
    mean  = RooRealVar("mean","mean of gaussians",5)
    sigma = RooRealVar("sigma","width of gaussians",0.5)
    sig   = RooGaussian("sig","Signal",x,mean,sigma)
    
    print ">>> setup model background components: Chebychev polynomial plus exponential..."
    a0    = RooRealVar("a0","a0",0.5,0.,1.)
    a1    = RooRealVar("a1","a1",-0.2,0.,1.)
    bkg1  = RooChebychev("bkg1","Background 1",x,RooArgList(a0,a1))
    alpha = RooRealVar("alpha","alpha",-1)
    bkg2  = RooExponential("bkg2","Background 2",x,alpha)
    bkg1frac = RooRealVar("bkg1frac","fraction of component 1 in background",0.2,0.,1.)
    bkg      = RooAddPdf("bkg","Signal",RooArgList(bkg1,bkg2),RooArgList(bkg1frac))
    
    print ">>> sum signal and background component..."
    bkgfrac = RooRealVar("bkgfrac","fraction of background",0.5,0.,1.)
    model   = RooAddPdf("model","g1+g2+a",RooArgList(bkg,sig),RooArgList(bkgfrac))
    
    # Create dummy dataset that has more observables than the above pdf
    y    = RooRealVar("y","y",-10,10)
    data = RooDataSet("data","data",RooArgSet(x,y))
    
    # Basic information requests:"
    print ">>> get list of observables of pdf in context of a dataset..."
    # Observables are define each context as the variables
    # shared between a model and a dataset. In this case
    # that is the variable 'x'
    model_obs = model.getObservables(data) # RooArgSet
    model_obs.Print('v')
    
    print "\n>>> get list of parameters..."
    # Get list of parameters, given list of observables
    model_params = model.getParameters(RooArgSet(x)) # RooArgSet
    print ">>> model_params.getStringValue(\"a0\") = %s" % (model_params.getStringValue("a0"))
    print ">>> model_params.getRealValue(\"a0\")   = %s" % (model_params.getRealValue("a0"))
    print ">>> model_params.find(\"a0\").GetName() = %s" % (model_params.find("a0").GetName())
    print ">>> model_params.find(\"a0\").getVal()  = %s" % (model_params.find("a0").getVal())
#     print ">>> for param in model_params:"
#     for param in model_params.():
#     print ">>>   %s"%(model_params.first())
#     print ">>>   %s"%(model_params.first())
#     model_params.selectByName("a*").Print('v')
    model_params.Print('v')
    
    print "\n>>> get list of parameters of a dataset..."
    # Gives identical results to operation above
    model_params2 = model.getParameters(data) # RooArgSet
    model_params2.Print()
    
    print "\n>>> get list of components..."
    # Get list of component objects, including top-level node
    model_comps = model.getComponents() # RooArgSet
    model_comps.Print('v')
    
    
    
    print "\n>>> modifications to structure of composites..."
    sigma2 = RooRealVar("sigma2","width of gaussians",1)
    sig2   = RooGaussian("sig2","Signal component 1",x,mean,sigma2)
    sig1frac = RooRealVar("sig1frac","fraction of component 1 in signal",0.8,0.,1.)
    sigsum   = RooAddPdf("sigsum","sig+sig2",RooArgList(sig,sig2),RooArgList(sig1frac))
    
    print ">>> construct a customizer utility to customize model..."
    cust = RooCustomizer(model,"cust")
    
    print ">>> instruct the customizer to replace node 'sig' with node 'sigsum'..."
    cust.replaceArg(sig,sigsum)

    # Build a clone of the input pdf according to the above customization
    # instructions. Each node that requires modified is clone so that the
    # original pdf remained untouched. The name of each cloned node is that
    # of the original node suffixed by the name of the customizer object  
    #
    # The returned head node own all nodes that were cloned as part of
    # the build process so when cust_clone is deleted so will all other
    # nodes that were created in the process.
    cust_clone = cust.build(kTRUE) # RooAbsPdf
    
    # Print structure of clone of model with sig->sigsum replacement.
    cust_clone.Print("t")
    
    # delete clone
    del cust_clone
        {{mmgMassShifted, phoMean, phoWidth}}
        )""".format(
        mcscale=phoEScaleMC
    )
)

# phoEResFuncOfMMGMass = w.factory('FormulaVar::phoEResFuncOfMMGMass2("mmgMass ", {mmgMass})')

## Plug in the mass smering mean and width into the smearing shape
phoSmear = RooHistPdf(
    "phoSmear", "phoSmear", RooArgList(phoEResFuncOfMMGMassShifted), RooArgList(phoERes), phoEResDataHist, 2
)
## TODO: use RooCustomizer to transform phoEResShape
## Define the transform such that the phoEResShape is always evaluated
## inside of it's boundaries.
cust = RooCustomizer(phoEResShape, "transformed")
cust.replaceArg(phoERes, phoEResFuncOfMMGMassShifted)
phoSmear2 = cust.build()

w.Import(phoSmear)

## Apply photon smearing to the theory
mmgMassShifted.setRange(-30, 30)
mmgMassShifted.setBins(10000, "fft")
theoryXphoSmear = w.factory("FCONV::theoryXphoSmear(mmgMassShifted, phoSmear, theory)")
## mmgMassPhoGenEFunc = w.factory('FormulaVar::mmgMassPhoGenEFunc("mmgMass", {mmgMass})')
## theoryXphoSmear = RooFFTConvPdf('theoryXphoSmear', 'theoryXphoSmear',
##                                 mmgMassPhoGenEFunc, mmgMassPhoGenE, theory, phoSmear)

## Fit Smeared theory to data
# theoryXphoSmear.fitTo(mmgData, Range(70,110))
#from P2VV.Utilities.DataHandling import correctWeights
#fitData = correctWeights( dataSet, [ 'runPeriod', 'KKMassCat' ] )
#fitResult = pdf.fitTo( fitData, SumW2Error = False, Save = True, NumCPU = 8, Optimize = 2, Timer = True, Minimizer = 'Minuit2'
#                      , Strategy = 1, Offset = True )
#from P2VV.Imports import parNames, parValues
#fitResult.PrintSpecial( text = True, ParNames = parNames, ParValues = parValues )


###########################################################################################################################################
## build PDF for plotting ##
############################

if plotComp in [ 'phi', 'even', 'odd', 'S' ] :
    from ROOT import RooRealVar, RooConstVar, RooCustomizer
    from P2VV.RooFitWrappers import __dref__
    pdfCust = RooCustomizer( __dref__(pdf), plotComp )
    zeroCust = RooConstVar( 'zeroCust', 'zeroCust', 1.e-6 )

    if plotComp == 'even' :
        AparMag2Cust = RooRealVar( 'AparMag2Cust', 'AparMag2Cust', ws[ parDict['AparMag2'] ].getVal(), 0., 1. )
        pdfCust.replaceArg( ws[ parDict['AparMag2'] ], AparMag2Cust )
        pdfCust.replaceArg( ws[ parDict['AperpMag2'] ], zeroCust )

    elif plotComp == 'odd' :
        pdfCust.replaceArg( ws[ parDict['AparMag2'] ], zeroCust )
        pdfCust.replaceArg( ws[ parDict['A0Mag2'] ], zeroCust )

    if plotComp == 'S' :
        pdfCust.replaceArg( ws[ parDict['AparMag2'] ], zeroCust )
        pdfCust.replaceArg( ws[ parDict['AperpMag2'] ], zeroCust )
        pdfCust.replaceArg( ws[ parDict['A0Mag2'] ], zeroCust )
Exemple #5
0
        assert(len(split_cats[0]) == 1)

        ## The idea is to create a simultaneous PDF, split using the
        ## placeholder which was put in place when the resolution
        ## model was constructed and then in each bin set the created
        ## split parameter to: (mean_in_bin - overall_mean.

        ## Set the value to the mean sigmat already here, even if it is changed
        ## later.
        placeholder = sig_tres.sfPlaceHolder()
        placeholder.setVal(split_obs_mean)

        ## Customize the PDF to be split using the placeholder and any other
        ## pars which need to be split.
        from ROOT import RooCustomizer
        customizer = RooCustomizer(time_pdf._target_(), split_cat, splitLeaves)
        to_split = RooArgSet(*(split_pars[0]))
        ## CAREFULL: when do we need this?
        ## to_split.add(placeholder._target_())
        customizer.splitArgs(to_split, split_cat)
        states = dict([(s.GetName(), customizer.build(s.GetName())) for s in split_cat])
        time_pdf = SimultaneousPdf(time_pdf.GetName() + '_simul',
                                   SplitCategory = split_cat, ExternalConstraints = time_pdf.ExternalConstraints(),
                                   States = states, ConditionalObservables = time_pdf.ConditionalObservables())
        
        ## Set the split parameters to their calculated value and make
        ## them constant.
        st_mean = lambda st: 0.04921 + st * 1.220
        st_sigma = lambda st: 0.012 + st * 0.165

        pars = time_pdf.getParameters(RooArgSet())
moments.Print(  Scale = 1. / 2. / sqrt(pi)
              , Names = '|'.join( 'p2vvab_%d0%d%s%d' % ( moms[0], moms[1], 'm' if moms[2] < 0 else '', moms[2] ) for moms in signMoms )
             )
moments.Print( Scale = 1. / 2. / sqrt(pi), MinSignificance = 2.5 )

momFuncTerms = moments.buildPDFTerms( CoefNamePrefix = 'transC_' if transAngles else 'helC_'
                                     , Names = '|'.join( 'p2vvab_%d0%d%s%d' % ( moms[0], moms[1], 'm' if moms[2] < 0 else '', moms[2] )\
                                                        for moms in signMoms )
                                    )
momFunc = momFuncTerms.buildAddition( 'efficiency' + ( 'Trans' if transAngles else 'Hel' ) )

# create efficiency functions with alternative angular values for slices
from ROOT import RooRealVar, RooCustomizer
angles1 = [ RooRealVar(ang._var) for ang in angles ]
angles2 = [ RooRealVar(ang._var) for ang in angles ]
momFuncCust1 = RooCustomizer( momFunc._var, '_1' )
momFuncCust2 = RooCustomizer( momFunc._var, '_2' )
for ang, ang1, ang2 in zip( angles, angles1, angles2 ) :
    momFuncCust1.replaceArg( ang._var, ang1 )
    momFuncCust2.replaceArg( ang._var, ang2 )
momFunc1 = momFuncCust1.build()
momFunc2 = momFuncCust2.build()

for ang, val in zip( angles,  (  0.,  0., 0. ) ) : ang.setVal(val)
for ang, val in zip( angles1, ( +1., +1., 0. ) ) : ang.setVal(val)
for ang, val in zip( angles2, ( -1., +1., 0. ) ) : ang.setVal(val)

print
momFunc.getVariables().Print('v')
print
momFunc1.getVariables().Print('v')
Exemple #7
0
def readTemplate1D(
    fromfile,           # file to read from
    fromws,             # workspace to read from
    fromvarname,        # variable name in fromws
    objname,            # object to ask for
    ws,                 # workspace to import into
    variable,           # variable
    pfx,                # prefix of imported objects
    binIfPDF = False    # bin if the template comes as Pdf
    ):
    """
    read a 1D template from a file (either PDF,data set, or plain 1D TH1)

    fromfile --     name of file to read from
    fromws --       name of workspace to read from (or None for plain TH1)
    fromvarname --  name of dependent variable in workspace
    objname --      name of pdf, data set, or histogram
    ws --           workspace into which to import template
    variable --     dependent variable of template after import into ws
    pfx --          name prefix for imported objects
    binIfPDF --     if True and the object is a pdf, bin upon import

    This routine is a generic 1D template importer. It will read PDFs and
    RooDataSets from RooWorkspaces, or read a plain TH1*. It will then import
    this object into the workspace given by ws, and "connect" it to the
    variable given in variable (this can be used to "rename" variables when
    the original template in the file does not have the right name).
    """
    from ROOT import ( TFile, RooWorkspace, RooKeysPdf, RooHistPdf,
        RooArgList, RooDataHist, RooArgSet )
    ff = TFile(fromfile, 'READ')
    if (None == ff or ff.IsZombie()):
        print 'ERROR: Unable to open %s to get template for %s' % (fromfile,
                variable.GetName())
    workspace = ff.Get(fromws)
    if None != workspace and workspace.InheritsFrom('RooWorkspace'):
        # ok, we're reading from a ROOT file which contains a RooWorkspace, so
        # we try to get a PDF of a RooAbsData from it
        ROOT.SetOwnership(workspace, True)
        var = workspace.var(fromvarname)
        if (None == var):
            print ('ERROR: Unable to read %s variable %s from '
                    'workspace %s (%s)') % (variable.GetName(), fromvarname,
                            fromws, fromfile)
            return None
        pdf = workspace.pdf(objname)
        if (None == pdf):
            # try to get a data sample of that name
            data = workspace.data(objname)
            if None == data:
                print ('ERROR: Unable to read %s pdf/data %s from '
                        'workspace %s (%s)') % (variable.GetName(),
                                fromvarname, fromws, fromfile)
                return None
            if data.InheritsFrom('RooDataSet'):
                # if unbinned data set, first create a binned version
                argset = RooArgSet(var)
                data = data.reduce(RooFit.SelectVars(argset))
                ROOT.SetOwnership(data, True)
                data = data.binnedClone()
                ROOT.SetOwnership(data, True)
            # get underlying histogram
            hist = data.createHistogram(var.GetName())
            del data
        else:
            # we need to jump through a few hoops to rename the dataset and variables
            # get underlying histogram
            if (pdf.InheritsFrom('RooHistPdf')):
                hist = pdf.dataHist().createHistogram(var.GetName())
            else:
                if binIfPDF:
                    hist = pdf.createHistogram(var.GetName(), var)
                else:
                    # ok, replace var with variable
                    from ROOT import RooCustomizer
                    c = RooCustomizer(pdf, '%sPdf' % pfx);
                    c.replaceArg(var, variable)
                    pdf = c.build()
                    ROOT.SetOwnership(pdf, True)
                    pdf.SetName('%sPdf' % pfx)
                    pdf = WS(ws, pdf)
                    del var
                    del workspace
                    ff.Close()
                    del ff
                    return pdf
    else:
        # no workspace found, try to find a TH1 instead
        hist = None
        for tmp in (fromws, objname):
            hist = ff.Get(tmp)
            if (None != tmp and hist.InheritsFrom('TH1') and
                    1 == hist.GetDimension()):
                break
        if (None == hist or not hist.InheritsFrom('TH1') or
                1 != hist.GetDimension()):
            print ('ERROR: Utterly unable to find any kind of %s '
                    'variable/data in %s') % (variable.GetName(), fromfile)
            return None
    ROOT.SetOwnership(hist, True)
    hist.SetNameTitle('%sPdf_hist' % pfx, '%sPdf_hist' % pfx)
    hist.SetDirectory(None)
    if hist.Integral() < 1e-15:
        raise ValueError('Histogram empty!')
    variable.setRange(
            max(variable.getMin(),
                hist.GetXaxis().GetBinLowEdge(1)),
            min(variable.getMax(),
                hist.GetXaxis().GetBinUpEdge(hist.GetNbinsX())))
    from ROOT import RooBinning, std
    bins = std.vector('double')()
    bins.push_back(hist.GetXaxis().GetBinLowEdge(1))
    for ibin in xrange(1, 1 + hist.GetNbinsX()):
        bins.push_back(hist.GetXaxis().GetBinUpEdge(ibin))
    binning = RooBinning(bins.size() - 1, bins.data() if ROOT.gROOT.GetVersionCode() > 0x53600 else bins.begin().base())
    del bins
    del ibin
    variable.setBinning(binning)
    # recreate datahist
    dh = RooDataHist('%sPdf_dhist' % pfx, '%sPdf_dhist' % pfx,
            RooArgList(variable), hist)
    del hist
    del pdf
    del var
    del workspace
    ff.Close()
    del ff
    # and finally use dh to create our pdf
    pdf = WS(ws, RooHistPdf('%sPdf' % pfx, '%sPdf' % pfx, RooArgSet(variable), dh))
    del dh
    return pdf