Esempio n. 1
0
def get_arglist(args):
    """Return and arglist of the RooFit objects."""
    arglist = RooArgList()
    for arg in args:
        if arg.InheritsFrom(RooAbsArg.Class()): arglist.add(arg)
        else: TypeError('%s should inherit from RooAbsArg' % arg.GetName())
    return arglist
def main ():
    N_bkg1 = 9000
    N_signal = 1000
    N_bkg1_obs = 10000
    N_signal_obs = 2000
    N_data = N_bkg1_obs + N_signal_obs
    mu1, mu2, sigma1, sigma2 = 100, 140, 15, 5
    x1 = mu1 + sigma1 * np.random.randn( N_bkg1 )
    x2 = mu2 + sigma2 * np.random.randn( N_signal )
    x1_obs = mu1 + sigma1 * np.random.randn( N_bkg1_obs )
    x2_obs = mu2 + sigma2 * np.random.randn( N_signal_obs )
    
    h1 = Hist( 100, 40, 200, title = 'Background' )
    h2 = h1.Clone( title = 'Signal' )
    h3 = h1.Clone( title = 'Data' )
    h3.markersize = 1.2
    
    # fill the histograms with our distributions
    map( h1.Fill, x1 )
    map( h2.Fill, x2 )
    map( h3.Fill, x1_obs )
    map( h3.Fill, x2_obs )
    
    histograms_1 = {'signal': h2,
                  'bkg1': h1,
                  'data': h3}
    
    histograms_2 = {'signal': h2,
                  'bkg1': h1,
                  'data': h3}
    
    # roofit_histograms contains RooDataHist
    # model = RooAddPdf
    model1, roofit_histograms_1,fit_variable_1 = get_roofit_model( histograms_1, fit_boundaries = ( 40, 200 ), name = 'm1' )
    model2, roofit_histograms_2, fit_variable_2 = get_roofit_model( histograms_2, fit_boundaries = ( 40, 200 ), name = 'm2' )
    sample = RooCategory( 'sample', 'sample' )
    sample.defineType( 'm1', 1 )
    sample.defineType( 'm2', 2 )
    combined_data = deepcopy( roofit_histograms_1['data'] )
    combined_data.add( roofit_histograms_2['data'] )
    # RooDataHist(const char* name, const char* title, const RooArgList& vars, RooCategory& indexCat, map<std::string,TH1*> histMap, Double_t initWgt = 1.0)
    sim_pdf = RooSimultaneous( "simPdf", "simultaneous pdf", sample )
    sim_pdf.addPdf( model1, 'm1' )
    sim_pdf.addPdf( model2, 'm2' )
    variables = RooArgList()
    variables.add(fit_variable_1)
    variables.add(fit_variable_2)
#     combined_data = RooDataHist('combined_data', 'combined_data',
#                                 variables, RooFit.Index(sample),
#                                 RooFit.Import('m1', roofit_histograms_1['data']),
#                                 RooFit.Import('m2', roofit_histograms_2['data']))
    fitResult = sim_pdf.fitTo( combined_data,
#                    RooFit.Minimizer( "Minuit2", "Migrad" ),
#                    RooFit.NumCPU( 1 ),
#                    RooFit.Extended(),
                    RooFit.Save(), 
                   )
def get_roofit_model( histograms, fit_boundaries, name = 'model' ):
    data_label = 'data'
    samples = sorted( histograms.keys() )
    samples.remove( data_label )
    roofit_histograms = {}
    roofit_pdfs = {}
    roofit_variables = {}
    variables = RooArgList()
    variable_set = RooArgSet()

    fit_variable = RooRealVar( name , name, fit_boundaries[0], fit_boundaries[1] )
    variables.add( fit_variable )
    variable_set.add( fit_variable )
    
    roofit_histograms[data_label] = RooDataHist( data_label,
                                                     data_label,
                                                     variables,
                                                     histograms[data_label] )
    
    pdf_arglist = RooArgList()
    variable_arglist = RooArgList()
    N_total = histograms[data_label].Integral() * 2
    N_min = 0
    for sample in samples:
        roofit_histogram = RooDataHist( sample, sample, variables, histograms[sample] )
        roofit_histograms[sample] = roofit_histogram
        roofit_pdf = RooHistPdf ( 'pdf' + sample, 'pdf' + sample, variable_set, roofit_histogram, 0 )
        roofit_pdfs[sample] = roofit_pdf
        roofit_variable = RooRealVar( sample, "number of " + sample + " events", histograms[sample].Integral(), N_min, N_total, "event" )
        roofit_variables[sample] = roofit_variable
        pdf_arglist.add( roofit_pdf )
        variable_arglist.add( roofit_variable )
        
    model = RooAddPdf( name, name, pdf_arglist, variable_arglist )
    return model, roofit_histograms, fit_variable
Esempio n. 4
0
    def fit(self):
        fit_variable = RooRealVar("fit_variable", "fit_variable", self.fit_boundaries[0], self.fit_boundaries[1])
        fit_variable.setBins(self.histograms[self.data_label].nbins())
        variables = RooArgList()
        variables.add(fit_variable)
        variable_set = RooArgSet()
        variable_set.add(fit_variable)

        roofit_histograms = {}
        roofit_pdfs = {}
        roofit_variables = {}

        N_min = 0.0
        N_max = self.normalisation[self.data_label] * 2.0
        pdf_arglist = RooArgList()
        variable_arglist = RooArgList()

        roofit_histograms[self.data_label] = RooDataHist(
            self.data_label, self.data_label, variables, self.histograms[self.data_label]
        )
        for sample in self.samples:
            roofit_histogram = RooDataHist(sample, sample, variables, self.histograms[sample])
            roofit_histograms[sample] = roofit_histogram
            roofit_pdf = RooHistPdf("pdf" + sample, "pdf" + sample, variable_set, roofit_histogram)
            roofit_pdfs[sample] = roofit_pdf
            roofit_variable = RooRealVar(sample, sample + " events", self.normalisation[sample], N_min, N_max)
            roofit_variables[sample] = roofit_variable
            pdf_arglist.add(roofit_pdf)
            variable_arglist.add(roofit_variable)

        model = RooAddPdf("model", "sum of all known", pdf_arglist, variable_arglist)
        use_model = model
        if self.constraints:
            arg_set = RooArgSet(model)
            constraints = self.get_fit_normalisation_constraints(model, roofit_variables)
            for constraint in constraints:
                arg_set.add(constraint)
            model_with_constraints = RooProdPdf(
                "model_with_constraints", "model  with gaussian constraints", arg_set, RooLinkedList()
            )
            use_model = model_with_constraints

        if self.method == "TMinuit":
            # WARNING: number of cores changes the results!!!
            self.saved_result = use_model.fitTo(
                roofit_histograms[self.data_label],
                RooFit.Minimizer("Minuit2", "Migrad"),
                RooFit.NumCPU(1),
                RooFit.Extended(),
                RooFit.Save(),
            )

        results = {}
        for sample in self.samples:
            results[sample] = (roofit_variables[sample].getVal(), roofit_variables[sample].getError())
        self.results = results
Esempio n. 5
0
def getPdfInRegions(w,sample,region):
    if isinstance(sample,list):
        sampleArgList = RooArgList()
        sample_str="group"
        for s in sample:
            componentTmp = Util.GetComponent(w,s,region,True)
            sample_str=sample_str+"_"+s
            sampleArgList.add(componentTmp)
            pass
        pdfInRegion = RooAddition(sample_str,sample_str,sampleArgList)
    else:
        pdfInRegion  = Util.GetComponent(w,sample,region)
        pass
    return pdfInRegion
def getPdfInRegionsWithRangeName(w,sample,region,rangeName):
    """
    Should be moved to $HF/src/Utils.h -- FIXME
    """
    if isinstance(sample,list):
        sampleArgList = RooArgList()
        sample_str="group"
        for s in sample:
            componentTmp = Util.GetComponent(w,s,region,True,rangeName)
            sample_str=sample_str+"_"+s
            sampleArgList.add(componentTmp)
            pass
        pdfInRegion = RooAddition(sample_str,sample_str,sampleArgList)
    else:
        pdfInRegion  = Util.GetComponent(w,sample,region,False,rangeName)
        pass
    return pdfInRegion
    def addHistData(self, ws, ds_name, item_title, var_set_name, var_set_type, ds_object, sets = None):
        legend = '[exostConfig::addHistData]:'
        
        arg_list = RooArgList()
        if (var_set_type == 'set'):
            #arg_list.add(ws.set(var_set_name))
            arg_list.add(sets[var_set_name])
        elif (var_set_type == 'var'):
            arg_list.add(ws.var(var_set_name))
        else:
            print legend, 'error: unknown var_set_type, cannot create dataset', ds_name
            return -1

        #create the hist dataset
        ds = RooDataHist(ds_name, item_title, arg_list, ds_object, 1)
        
        # import the datahist. Note workaround 'import' being a reserved word
        getattr(ws, 'import')(ds)
Esempio n. 8
0
    def Hist2Pdf(self, hist, pdfName, ws, order = 0):
        if ws.pdf(pdfName):
            return ws.pdf(pdfName)

        try:
            obs = [ self.pars.varNames[x] for x in self.pars.var ]
        except AttributeError:
            obs = self.pars.var

        varList = RooArgList()
        for v in obs:
            varList.add(ws.var(v))
        newHist = RooDataHist(pdfName + '_hist', pdfName + '_hist',
                              varList, hist)
        
        thePdf = RooHistPdf(pdfName, pdfName, RooArgSet(varList), 
                            newHist, order)
        getattr(ws, 'import')(thePdf)

        return ws.pdf(pdfName)
def performFitInLeptonAbsEta(data_histogram, signal_histogram, bkg1_histogram, bkg2_histogram):
    N_Data = data_histogram.Integral()
    N_signal = signal_histogram.Integral()
    N_bkg1 = bkg1_histogram.Integral()
    N_bkg2 = bkg2_histogram.Integral()
    leptonAbsEta = RooRealVar("leptonAbsEta", "leptonAbsEta", 0., 3.)
    variables = RooArgList()
    variables.add(leptonAbsEta)
    variable_set = RooArgSet()
    variable_set.add(leptonAbsEta)
    
    lowerBound = 0
    upperBound = N_Data*2
    
    data_RooDataHist = RooDataHist("data", "dataset with leptonAbsEta", variables, data_histogram)
    signal_RooDataHist =  RooDataHist("rh_signal", "signal", variables, signal_histogram);
    bkg1_RooDataHist =  RooDataHist("rh_bkg1", "bkg1", variables, bkg1_histogram);
    bkg2_RooDataHist =  RooDataHist("rh_bkg2", "bkg2", variables, bkg2_histogram);

    signal_RooHistPdf = RooHistPdf("pdf_signal", "Signal PDF", variable_set, signal_RooDataHist, 0)
    signal_RooHistPdf = RooHistPdf("pdf_signal", "Signal PDF", variable_set, signal_RooDataHist, 0)
Esempio n. 10
0
def getPdfInRegions(w,sample,region):
    """
    Return the PDF in a region for a sample
    Should be moved to $HF/src/Utils.h -- FIXME

    @param sample The sample to find
    @param region The region to use
    """
    if isinstance(sample,list):
        sampleArgList = RooArgList()
        sample_str="group"
        for s in sample:
            componentTmp = Util.GetComponent(w,s,region,True)
            sample_str=sample_str+"_"+s
            sampleArgList.add(componentTmp)
            pass
        pdfInRegion = RooAddition(sample_str,sample_str,sampleArgList)
    else:
        pdfInRegion  = Util.GetComponent(w,sample,region)
        pass
    return pdfInRegion
Esempio n. 11
0
def plotFitModel(model, frame, wksp, myconfigfile, log) :
    if debug :
        model.Print('t')
        frame.Print('v')

    dataset                             = w.data(dataSetToPlot)

    # plot model itself
    fr = model.plotOn(frame,
                      RooFit.LineColor(kBlue+3),RooFit.Name("FullPdf"))

    var = []
    tacc_list = RooArgList()
    numKnots = myconfigfile["Acceptance"]["knots"].__len__()
    for i in range(0,numKnots+1):
        varName = "var%d"%(int(i+1))
        var.append(wksp.var(varName))
        print "[INFO] Load %s with value %0.3lf"%(var[i].GetName(),var[i].getValV())
        tacc_list.add(var[i])

    varAdd = RooAddition(wksp.obj("var%d"%(numKnots+2)))
    #varAdd = RooRealVar(wksp.obj("var%d"%(numKnots+2)))
    print "[INFO] Load %s with value %0.3lf"%(varAdd.GetName(),varAdd.getValV())
    tacc_list.add(varAdd)

    #len = var.__len__()
    #tacc_list.add(var[len])
    spl = RooCubicSplineFun("splinePdf", "splinePdf", time, "splineBinning", tacc_list)
    if log:
        rel = 200
    else:
        rel = 1000
    rel = 40                                                                                                                                                                           
     
    fr = spl.plotOn(frame, RooFit.LineColor(kRed),  RooFit.Normalization(rel, RooAbsReal.Relative),RooFit.Name("sPline"))
    fr = model.plotOn(frame,
                      RooFit.LineColor(kBlue+3), RooFit.Name("FullPdf"))
Esempio n. 12
0
def PlotSignalShapes(Selection):
    f__ = TFile.Open( "datacards/22June/2dPlots.root")
    signal_fname_1 = ("signals/22June/out_{sample:s}_syst.root", "cms_hgg_13TeV" )
    signal_fname_2 = ("signals/22June/out_ctcv_{sample:s}_syst.root" , "ctcv" )
    samples = {"thw":signal_fname_2, "thq":signal_fname_2, "tth":signal_fname_1 , "vh":signal_fname_1 }
    purity_h_name = "{sample:s}/"+Selection+"/h{sample:s}_"+Selection+"_purity_CtCv"
    purities = RooArgList()
    signalshapes = RooArgList()

    ctOverCvs = []

    mVar = None
    ctovercv_vals = None
    for sample in samples :
        purity = CtCvCpInfo("purity_" + sample)
        ctovercv_vals = sorted(purity.AllCtOverCVs.keys())
        purity.FillFrom2DHisto( f__.Get( purity_h_name.format( sample=sample ) ) )
        purity.GetCtOverCv()
        purities.add( purity.CtOverCvDataHistFunc )
        objsToKeep.append( purity )

        sFile = TFile.Open( samples[sample][0].format( sample=sample ) )
        ws = sFile.Get( samples[sample][1] )
        pdf = ws.pdf("RV{sample:s}_mh125".format( sample=sample) )
        objsToKeep.append(sFile)
        objsToKeep.append(ws)
        objsToKeep.append(pdf)
        signalshapes.add( pdf )

        ctOverCvs.append( ws.var( "CtOverCv" ) )
        mVar = ws.var("CMS_hgg_mass")
        
    ret = RooAddPdf("signal" , "signal" , signalshapes , purities )
    objsToKeep.append( ret )
    plot = mVar.frame()
    options = ""
    for ctovercv in ctovercv_vals :
        for var in ctOverCvs:
            var.setVal( ctovercv )
        name = "name%g" % ctovercv
        ret.plotOn( plot , RooFit.DrawOption(options) , RooFit.Name(name) )
        
        c = TCanvas()
        plot.Draw()
        c.SaveAs("a.gif+")

        if not "same" in options :
            options += " same"

    return c
Esempio n. 13
0
theSet = RooArgSet(masskk, dimuonditrk_m_rf_c, dimuonditrk_ctauPV,
                   dimuonditrk_ctauErrPV, dimuon_pt, ditrak_pt, psiPrimeMass)
splotData = RooDataSet("alldata", "alldata", xTuple, theSet)
#
print "Tree entries %d" % (splotData.numEntries())

a0 = RooRealVar("a0", "a0", 7.72274e-02, -10., 10.)
a1 = RooRealVar("a1", "a1", -3.16317e-01, -5.0, 5.0)
a2 = RooRealVar("a2", "a2", 1.08150e-01, -2., 2.)
a3 = RooRealVar("a3", "a3", -1.21839e-02, -0.5, 0.5)
a4 = RooRealVar("a4", "a4", 1.17246e-03, -0.2, 0.2)
a5 = RooRealVar("a5", "a5", 0.0, -0.025, 0.05)
a6 = RooRealVar("a6", "a6", 0.0, -0.001, 0.001)

aset = RooArgList(a0, a1, a2, a3, a4)  #,a5)

sigma = RooRealVar("#sigma", "width of gaussian", 0.00572, 0.00372, 0.00772)
gamma = RooRealVar("#Gamma", "gamma of bw", 0.0042, 0.001, 0.01)
mean = RooRealVar("m", "mean of gaussian", psimean, psimean - 0.1,
                  psimean + 0.1)

nSig = RooRealVar("n_{Sig}", "nSig", 3.5e4, 3.4e4, 3.6e4)
nBkg = RooRealVar("nBkg", "nBkg", 3.96901e+06, 3.76901e+06, 4.16901e+06)
cheb = RooChebychev("cheb", "Background", psiPrimeMass, aset)
gauss = RooGaussian("gauss", "gaussian PDF ", psiPrimeMass, mean, sigma)
#signal = RooVoigtian("signal","signal",psiPrimeMass,mean,gamma,sigma)
signal = gauss

B_1 = RooRealVar("B_{1}", "B_1 ", 0.3, -20, 100)
B_2 = RooRealVar("B_{2}", "B_2", 0.3, -20, 100)
pf.GetYaxis().SetTitle("pull (#sigma)")
pyroot_logon.cmsPrelim(c4, fitterPars.intLumi / 1000)
c4.Print("H{2}_Mjj_{0}_{1}jets_Pull.pdf".format(modeString, opts.Nj, opts.mH))
c4.Print("H{2}_Mjj_{0}_{1}jets_Pull.png".format(modeString, opts.Nj, opts.mH))

if TMath.Prob(chi2Raw, ndf2) < 0.05:
    print "**DANGER** The fit probability is low **DANGER**"
    if opts.debug:
        assert False

# assert(False)

mass.setRange("signal", fitterPars.minTrunc, fitterPars.maxTrunc)
# yields = theFitter.makeFitter().coefList()
finalPars = fr.floatParsFinal()
yields = RooArgList(finalPars)
yields.add(fr.constPars())
sigInt = theFitter.makeFitter().createIntegral(iset, iset, "signal")
sigFullInt = theFitter.makeFitter().createIntegral(iset, iset)
print "allBkg", "sigInt", sigInt.getVal(), "fullInt", sigFullInt.getVal(), "ratio", sigInt.getVal() / sigFullInt.getVal()
dibosonInt = theFitter.makeDibosonPdf().createIntegral(iset, iset, "signal")
dibosonFullInt = theFitter.makeDibosonPdf().createIntegral(iset, iset)
WpJPdf = theFitter.makeWpJPdf()
WpJInt = WpJPdf.createIntegral(iset, iset, "signal")
WpJFullInt = WpJPdf.createIntegral(iset, iset)
# WpJPdf.Print("v")
print "WpJ", "sigInt", WpJInt.getVal(), "fullInt", WpJFullInt.getVal(), "ratio", WpJInt.getVal() / WpJFullInt.getVal()
ttbarInt = theFitter.makettbarPdf().createIntegral(iset, iset, "signal")
ttbarFullInt = theFitter.makettbarPdf().createIntegral(iset, iset)
SingleTopInt = theFitter.makeSingleTopPdf().createIntegral(iset, iset, "signal")
SingleTopFullInt = theFitter.makeSingleTopPdf().createIntegral(iset, iset)
Esempio n. 15
0
funcs = ws.allFunctions()
iter = funcs.createIterator()
var = iter.Next()
while var :
    getattr( newws , "import")( var.Clone() , RooFit.RecycleConflictNodes() )
    var = iter.Next()

data = ws.allData()
for var in data:
# iter = data.createIterator()
# var = iter.Next()
# while var :
    getattr( newws , "import")( var.Clone() , RooFit.RecycleConflictNodes())
    var = iter.Next()

a = RooArgList("pdfs")
cat = RooCategory("pdfindex_THQLeptonicTag_inverted_13TeV" , "title")
cat.Print()
pdfs = ws.allPdfs()
iter = pdfs.createIterator()
var = iter.Next()
while var :
    getattr( newws , "import")( var.Clone() , RooFit.RecycleConflictNodes())
    if var.GetName() in ["env_pdf_0_13TeV_bern1","env_pdf_0_13TeV_exp1","env_pdf_0_13TeV_pow1","env_pdf_0_13TeV_lau1"]:
        a.add( var )
    var = iter.Next()
multipdf = RooMultiPdf("CMS_hgg_THQLeptonicTag_inverted_13TeV_bkgshape" , "title" , cat , a )
getattr( newws , "import")( multipdf, RooFit.RecycleConflictNodes() )

f.Close()
Esempio n. 16
0
from ROOT import TFile, TCanvas, TH1D, TTree, TList
from ROOT import RooWorkspace, RooArgSet, RooArgList, RooFit
from ROOT import gPad, gStyle, kRed, kBlue, kAzure, kGreen, kBlack

gStyle.SetOptStat('nemrou')
canvas = TCanvas('canvas', 'canvas', 800, 600)
canvas.Print('{}['.format(plotfile))

ffile = TFile.Open(rfile, 'read')

if ifpdf:
    workspace = ffile.Get('workspace')

    kfactor = workspace.var('kfactorVar')
    kfactor.setRange(0.9, 1.1)
    pdfs = RooArgList(workspace.allPdfs())

    for i in range(pdfs.getSize()):
        fr = kfactor.frame()
        pdfs[i].plotOn(fr, RooFit.LineColor(kBlack), RooFit.FillColor(kAzure+1),
                       RooFit.DrawOption('lf')) # FIXME: doesn't draw the line!'
        fr.Draw()
        canvas.Print(plotfile)
else:
    modes = {}
    klist = ffile.GetListOfKeys()
    for item in klist:
        name = item.GetName()
        if not name.startswith('mBresn'):
            print 'MSG: Skipping, unknown object: %s' % name
            continue # ntuples are named mBresn_*
Esempio n. 17
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
Esempio n. 18
0
# Create basic model
Mkk = RooRealVar("Mkk", "Mkk", fit_min, fit_max)
mean1 = RooRealVar("mean1", "Mean of Gaussian 1", 1.01944, 1.01, 1.03)
sigma1 = RooRealVar("sigma1", "Width of Gaussian 1", 0.00222, 0.0001, 0.01)
gauss1 = RooGaussian("gauss1", "gauss1(Mkk,mean1,sigma1)", Mkk, mean1, sigma1)

#Signal and bkg model
sigShapePdf = gauss1
bkgShapePdf = None

#Efficinecy
efficiency = RooRealVar("efficiency", "efficiency", 0.67, -1, 1)
nSig = RooRealVar("nSig", "nSig", 1000.0, -10.0, 1000000.0)
nSigpass = RooFormulaVar("nSigpass", "nSig * efficiency",
                         RooArgList(nSig, efficiency))
nSigfail = RooFormulaVar("nSigfail", "nSig * (1.0 - efficiency)",
                         RooArgList(nSig, efficiency))

#Pass
componentspass = RooArgList(sigShapePdf)  #,bkgShapePdf);
yieldspass = RooArgList(nSigpass)  #, nBkgpass);
sumpass = RooAddPdf("sumpass", "fixed extended sum pdf", componentspass,
                    yieldspass)

#Fail
componentsfail = RooArgList(sigShapePdf)  #,bkgShapePdf );
yieldsfail = RooArgList(nSigfail)  #, nBkgfail );
sumfail = RooAddPdf("sumfail", "fixed extended sum pdf", componentsfail,
                    yieldsfail)
Esempio n. 19
0
def fitWPeak():

    # Get histograms from file
    mcHist = 0
    with root_open(inputFile, 'read') as file:
        gROOT.cd()
        mcHist = file.Get(inputHistogram).Clone('histToFit')
        # mcHist = file.Get(inputHistogram).GetStack().Last().Clone('histToFit')

    # Data hist gone out of scope?
    print mcHist

    # Import the data to fit

    # Declare variables x,mean,sigma with associated name, title, initial value and allowed range
    x = RooRealVar("M(jj)", "M(jj)", 40, 180)

    histToFit = RooDataHist('histToFit', 'histToFit', RooArgList(x),
                            RooFit.Import(mcHist))
    frame = x.frame(RooFit.Title("E Plus Jets"))
    histToFit.plotOn(frame)

    # Setup fit function
    fitFunction = None
    print fitFunction
    if whatToFit == 'realLife':
        # Stuff for gauss
        mg = RooRealVar("mean", "mean of gaussian", 86, 50, 120)
        sg = RooRealVar("sigma", "width of gaussian", 10, 0, 50)
        gauss = RooGaussian("gauss", "gaussian PDF", x, mg, sg)

        CBmean = RooRealVar("CBmean", "CBmean", 110, 60, 200)
        CBsigma = RooRealVar("CBsigma", "CBsigma", 40, 20, 100)
        CBalpha = RooRealVar("CBalpha", "CBalpha", -0.5, -20., 0.)
        # CBalpha = RooRealVar("CBalpha", "CBalpha", 10, 0., 20.)
        CBn = RooRealVar("CBn", "CBn", 1., 0., 20.)
        crystalBall = RooCBShape("crystalBall",
                                 "Crystal Ball resolution model", x, CBmean,
                                 CBsigma, CBalpha, CBn)

        fracGauss = RooRealVar("fracGauss", "fracGauss", 0.4, 0, 1)
        gaussPlusCrystalBall = RooAddPdf("gaussPlusCrystalBall",
                                         "Gauss plus Crystal Ball",
                                         RooArgList(gauss, crystalBall),
                                         RooArgList(fracGauss))
        fitFunction = gaussPlusCrystalBall
    elif whatToFit == 'partons':
        mg = RooRealVar("mean", "mean of gaussian", 86, 50, 120)
        sg = RooRealVar("sigma", "width of gaussian", 10, 0, 50)
        breitWigner = RooBreitWigner('bw', 'bw', x, mg, sg)
        fitFunction = breitWigner
    elif whatToFit == 'genJetsFromPartons':
        # mg = RooRealVar("mean","mean of gaussian",86,50,120)
        # sg = RooRealVar("sigma","width of gaussian",10,0,50)
        # breitWigner = RooBreitWigner('bw', 'bw', x, mg, sg)
        # fitFunction = breitWigner
        # mg = RooRealVar("mean","mean of gaussian",86,50,120)
        # sg = RooRealVar("sigma","width of gaussian",1,0,20)
        # width = RooRealVar("width","width of gaussian",5,0,50)
        # voigtian = RooVoigtian("voigt","voigt",x,mg,sg,width);
        # fitFunction = voigtian
        mg = RooRealVar("mean", "mean of gaussian", 86, 50, 120)
        sg = RooRealVar("sigma", "width of gaussian", 10, 0, 50)
        gauss = RooGaussian("gauss", "gaussian PDF", x, mg, sg)
        fitFunction = gauss

    print fitFunction

    # # Fit pdf to data
    fitFunction.fitTo(histToFit)

    # Plot histogram being fitted
    histToFit.plotOn(frame)

    # Plot fit functions and components
    fitFunction.plotOn(frame, RooFit.LineColor(kRed))
    print 'Chi square with 7 : ', frame.chiSquare(7)
    print frame.chiSquare()
    print fitFunction.getParameters(histToFit).selectByAttrib(
        'Constant', kFALSE).getSize()

    toPlot = RooArgSet(crystalBall)
    fitFunction.plotOn(frame, RooFit.Components(toPlot),
                       RooFit.LineStyle(kDashed), RooFit.LineColor(kRed))

    toPlot = RooArgSet(gauss)
    fitFunction.plotOn(frame, RooFit.Components(toPlot),
                       RooFit.LineStyle(kDashed), RooFit.LineColor(kBlue))

    fitFunction.paramOn(frame, RooFit.Layout(0.55, 0.9, 0.9))

    # Print values of mean and sigma (that now reflect fitted values and errors)
    mg.Print()
    sg.Print()
    # CBmean.Print()
    # CBsigma.Print()
    # CBalpha.Print()
    # CBn.Print()
    # fracGauss.Print()

    # # Draw frame on a canvas
    c = TCanvas("WMass", "WMass", 800, 400)
    gPad.SetLeftMargin(0.15)
    frame.GetYaxis().SetTitleOffset(1.6)
    frame.Draw()
    gPad.Update()
    c.Print('EPlusJets_mjj_fit.pdf')
    raw_input()
Esempio n. 20
0
def fitMC(fulldata, correctTag, ibin):

    print 'now fitting: ', ibin, ' for ', correctTag * 'correctTag ', (
        1 - correctTag) * 'wrongTag'
    cut = cut_base + '&& (mumuMass*mumuMass > %s && mumuMass*mumuMass < %s)' % (
        q2binning[ibin], q2binning[ibin + 1])
    data = fulldata.reduce(RooArgSet(thevarsMC), cut)

    pol_c1 = RooRealVar("p1", "coeff x^0 term", -0.5, -10, 10)
    pol_c2 = RooRealVar("p2", "coeff x^0 term", 0.5, -10, 10)
    bkg_pol = RooChebychev("bkg_pol", "bkg_pol", tagged_mass,
                           RooArgList(pol_c1))
    signalFunction = bkg_pol  ### just a placeholder

    nsig = RooRealVar("Yield", "nsig", 500000, 0, 1E7)
    nbkg = RooRealVar("nbkg", "nbkg", 1000, 0, 1E6)

    doextended = False
    fitrange = "mcrange"
    tag = 'RT' if correctTag else 'WT'
    if correctTag:
        ### double CB, 1 sigma
        mean = RooRealVar("mean_{RT}^{%s}" % ibin, "massRT", B0Mass_, 5, 6,
                          "GeV")
        if ibin < 5:
            sigmaCB = RooRealVar("#sigma_{RT1}^{%s}" % ibin, "sigmaCB", 0.03,
                                 0, 1)
            alpha1 = RooRealVar("#alpha_{RT1}^{%s}" % ibin, "#alpha_{1}", 0.5,
                                0, 10)
            alpha2 = RooRealVar("#alpha_{RT2}^{%s}" % ibin, "#alpha_{2}", 2.5,
                                0, 10)
            n1 = RooRealVar("n_{RT1}^{%s}" % ibin, "n_1", 1, 0, 20)
            n2 = RooRealVar("n_{RT2}^{%s}" % ibin, "n_2", 1, 0, 30)
            doublecb = ROOT.RooDoubleCBFast("doublecb_RT%s" % ibin, "doublecb",
                                            tagged_mass, mean, sigmaCB, alpha1,
                                            n1, alpha2, n2)
            signalFunction = doublecb

        else:
            ### double CB, 2 sigmas
            #             mean = RooRealVar ("mean^{RT}"%ibin, "massRT" ,  B0Mass_ , 5, 6, "GeV")
            crystalBall(mean, initial_sigma1, 1.5, 1, tagged_mass, w, 'RT1',
                        ibin, [0, 10])
            crystalBall(mean, initial_sigma2, -2, 1, tagged_mass, w, 'RT2',
                        ibin, [-10, 0])
            doubleCB(w.pdf("cbshape_RT1_%s" % (ibin)),
                     w.pdf("cbshape_RT2_%s" % ibin), 0.8, tagged_mass, w,
                     "RT%s" % ibin)
            signalFunction = w.pdf("doublecb_RT%s" % ibin)

        fitFunction = signalFunction

    else:
        mean = RooRealVar("mean_{WT}^{%s}" % ibin, "massWT", B0Mass_, 5, 6,
                          "GeV")
        sigmaCB = RooRealVar("#sigma_{WT1}^{%s}" % ibin, "sigmaCB", 0.03, 0, 1)
        alpha1 = RooRealVar("#alpha_{WT1}^{%s}" % ibin, "#alpha_{1}", 0.5, 0,
                            10)
        alpha2 = RooRealVar("#alpha_{WT2}^{%s}" % ibin, "#alpha_{2}", 2.5, 0,
                            10)
        n1 = RooRealVar("n_{WT1}^{%s}" % ibin, "n_1", 1, 0, 60)
        n2 = RooRealVar("n_{WT2}^{%s}" % ibin, "n_2", 1, 0, 60)
        doublecb = ROOT.RooDoubleCBFast("doublecb_%s" % ibin, "doublecb",
                                        tagged_mass, mean, sigmaCB, alpha1, n1,
                                        alpha2, n2)
        signalFunction = doublecb
        fitFunction = doublecb

    getattr(w, "import")(signalFunction)

    r = fitFunction.fitTo(data, RooFit.Extended(doextended), RooFit.Save(),
                          RooFit.Range(fitrange))
    print 'fit status: ', r.status(), r.covQual()

    ## draw everything
    params = signalFunction.getParameters(RooArgSet(tagged_mass))
    w.saveSnapshot("reference_fit_%s_%s" % (tag, ibin), params, ROOT.kTRUE)
    frame = tagged_mass.frame(
        RooFit.Range(fitrange)
    )  #, RooFit.Title('correctly'*correctTag + 'wrongly'*(1-correctTag) + ' tagged events'))
    data.plotOn(frame, RooFit.Binning(nbins), RooFit.MarkerSize(.7))

    drawPdfComponents(fitFunction,
                      frame,
                      ROOT.kGreen if correctTag else ROOT.kViolet,
                      RooFit.NormRange(fitrange),
                      RooFit.Range(fitrange),
                      isData=False)
    fitFunction.plotOn(frame, RooFit.NormRange(fitrange),
                       RooFit.Range(fitrange))
    fitFunction.paramOn(frame, RooFit.Layout(0.62, 0.86, 0.88))

    frame.Draw()
    niceFrame(
        frame, 'correctly' * correctTag + 'wrongly' * (1 - correctTag) +
        ' tagged events')
    frame.addObject(_writeFitStatus(r))

    ## evaluate sort of chi2 and save number of RT/WT events
    observables = RooArgSet(tagged_mass)
    flparams = fitFunction.getParameters(observables)
    nparam = int(flparams.selectByAttrib("Constant", ROOT.kFALSE).getSize())
    pdfstring = ''
    if correctTag:
        #         pdfstring = "doublegaus_RT%s_Norm[tagged_mass]_Comp[doublegaus_RT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin)
        pdfstring = "doublecb_RT%s_Norm[tagged_mass]_Comp[doublecb_RT%s]_Range[mcrange]_NormRange[mcrange]" % (
            ibin, ibin)
        #         pdfstring = "gauscb_RT%s_Norm[tagged_mass]_Comp[gauscb_RT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin)
        #         pdfstring = "expGaussExp_RT%s_Norm[tagged_mass]_Comp[expGaussExp_RT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin)
        if doextended:
            dict_s_rt[ibin] = _getFittedVar(nsig)
        else:
            dict_s_rt[ibin] = ufloat(data.sumEntries(),
                                     math.sqrt(data.sumEntries()))
        nRT = RooRealVar("nRT_%s" % ibin, "yield of RT signal", 0, 1.E6)
        nRT.setVal(dict_s_rt[ibin].n)
        nRT.setError(dict_s_rt[ibin].s)
        print 'setting nRT to ', dict_s_rt[ibin].n
        getattr(w, "import")(nRT)
    else:
        pdfstring = "doublecb_%s_Norm[tagged_mass]_Comp[doublecb_%s]_Range[mcrange]_NormRange[mcrange]" % (
            ibin, ibin)
        #         pdfstring = "doublegaus_WT%s_Norm[tagged_mass]_Comp[doublegaus_WT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin)
        #         pdfstring = "gauscb_WT%s_Norm[tagged_mass]_Comp[gauscb_WT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin)
        #         pdfstring = "expGaussExp_WT%s_Norm[tagged_mass]_Comp[expGaussExp_WT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin)
        dict_s_wt[ibin] = ufloat(data.sumEntries(),
                                 math.sqrt(data.sumEntries()))
        nWT = RooRealVar("nWT_%s" % ibin, "yield of WT signal", 0, 1.E6)
        nWT.setVal(dict_s_wt[ibin].n)
        nWT.setError(dict_s_wt[ibin].s)
        print 'setting nWT to ', dict_s_wt[ibin].n
        getattr(w, "import")(nWT)

    ## eval and save goodness of fit indicators
    chi2s['%s%s' % (tag, ibin)] = frame.chiSquare(pdfstring, "h_fullmc",
                                                  nparam)
    frame.addObject(_writeChi2(chi2s['%s%s' % (tag, ibin)]))
    fitStats['%s%s' % (tag, ibin)] = r.status()
    covStats['%s%s' % (tag, ibin)] = r.covQual()

    c1 = ROOT.TCanvas()
    upperPad = ROOT.TPad('upperPad', 'upperPad', 0., 0.35, 1., 1.)
    lowerPad = ROOT.TPad('lowerPad', 'lowerPad', 0., 0.0, 1., 0.345)
    upperPad.SetBottomMargin(0.012)
    lowerPad.SetTopMargin(0)
    lowerPad.SetBottomMargin(0.2)

    upperPad.Draw()
    lowerPad.Draw()

    upperPad.cd()
    frame.Draw()

    ## add plot of pulls
    lowerPad.cd()
    hpull = frame.pullHist("h_fullmc", pdfstring)
    frame2 = tagged_mass.frame(RooFit.Range(fitrange), RooFit.Title(''))
    frame2.addPlotable(hpull, "P")
    niceFrameLowerPad(frame2, 'pull')
    frame2.Draw()
    line = ROOT.TLine(5.0, 1, 5.6, 1)
    line.SetLineColor(ROOT.kGreen + 3)
    line.Draw()

    ## save to pdf and root files
    for ilog in [True, False]:
        upperPad.SetLogy(ilog)
        c1.SaveAs(
            'fit_results_mass_checkOnMC/save_fit_mc_%s_%s_%s_newSigmaFRT_%s.pdf'
            % (ibin, args.year, tag, '_logScale' * ilog))
    out_f.cd()
    r.Write('results_%s_%s' % (tag, ibin))

    return dict_s_rt[ibin].n if correctTag else dict_s_wt[ibin].n
def fillWorkspace(workspace):

    print ">>> setup model components..."
    x = RooRealVar("x", "x", 0, 10)
    mean = RooRealVar("mean", "mean of gaussians", 5, 0, 10)
    sigma1 = RooRealVar("sigma1", "width of gaussians", 0.5)
    sigma2 = RooRealVar("sigma2", "width of gaussians", 1)
    sig1 = RooGaussian("sig1", "Signal component 1", x, mean, sigma1)
    sig2 = RooGaussian("sig2", "Signal component 2", x, mean, sigma2)
    a0 = RooRealVar("a0", "a0", 0.5, 0., 1.)
    a1 = RooRealVar("a1", "a1", -0.2, 0., 1.)
    bkg = RooChebychev("bkg", "Background", x, RooArgList(a0, a1))

    print ">>> sum model components..."
    sig1frac = RooRealVar("sig1frac", "fraction of component 1 in signal", 0.8,
                          0., 1.)
    sig = RooAddPdf("sig", "Signal", RooArgList(sig1, sig2),
                    RooArgList(sig1frac))
    bkgfrac = RooRealVar("bkgfrac", "fraction of background", 0.5, 0., 1.)
    model = RooAddPdf("model", "g1+g2+a", RooArgList(bkg, sig),
                      RooArgList(bkgfrac))

    print ">>> import model into workspace..."
    getattr(workspace, 'import')(model)  # import model and all its components
    #workspace.import(model) # causes synthax error in python

    print "\n>>> encode definition of parameters and observables in workspace..."
    # Define named sets "parameters" and "observables", which list which variables should
    # be considered parameters and observables by the users convention
    #
    # Variables appearing in sets _must_ live in the workspace already, or the autoImport
    # flag of defineSet must be set to import them on the fly. Named sets contain only
    # references to the original variables, therefore the value of observables in named
    # sets already reflect their 'current' value
    params = model.getParameters(RooArgSet(x))  # RooArgSet
    workspace.defineSet("parameters", RooArgSet(params))
    workspace.defineSet("observables", RooArgSet(x))

    # Encode reference value for parameters in workspace:
    # Define a parameter 'snapshot' in the pdf
    # Unlike a named set, a parameter snapshot stores an independent set of values for
    # a given set of variables in the workspace. The values can be stored and reloaded
    # into the workspace variable objects using the loadSnapshot() and saveSnapshot()
    # methods. A snapshot saves the value of each variable, any errors that are stored
    # with it as well as the 'Constant' flag that is used in fits to determine if a
    # parameter is kept fixed or not.

    print ">>> generate and fit data..."
    # Do a dummy fit to a (supposedly) reference dataset here and store the results
    # of that fit into a snapshot
    refData = model.generate(RooArgSet(x), 10000)  # RooDataSet
    model.fitTo(refData, PrintLevel(-1))

    print "\n>>> save fit results into a snapshot in the workspace..."
    # The kTRUE flag imports the values of the objects in (*params) into the workspace
    # If not set, the present values of the workspace parameters objects are stored
    workspace.saveSnapshot("reference_fit", params, kTRUE)

    print ">>> make another fit with the signal component forced to zero..."
    bkgfrac.setVal(1)
    bkgfrac.setConstant(kTRUE)
    bkgfrac.removeError()
    model.fitTo(refData, PrintLevel(-1))

    print "\n>>> save new fit parameters in different snapshot..."
    workspace.saveSnapshot("reference_fit_bkgonly", params, kTRUE)
Esempio n. 22
0
File: fits.py Progetto: anpicci/Stat
class fitFunc(object):
    pass

fitParam = {}

mT = RooRealVar(  "m_T",    "m_{T}",          1500., 3900., "GeV")





fitBDT0_2016 = fitFunc()
fitBDT0_2016.p1 = RooRealVar("CMS2016_BDT0_p1", "p1", -18.0947, -1000., 1000.)
fitBDT0_2016.p2 = RooRealVar("CMS2016_BDT0_p2", "p2", 22.8504, -10., 10.)
fitBDT0_2016.p3 = RooRealVar("CMS2016_BDT0_p3", "p3", 3.72973, -10., 10.)
fitBDT0_2016.modelBkg = RooGenericPdf("Bkg", "Bkg. fit (3 par.)", "pow(1 - @0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000))", RooArgList(mT, fitBDT0_2016.p1, fitBDT0_2016.p2, fitBDT0_2016.p3))

fitParam["BDT0_2016"] = fitBDT0_2016

fitBDT1_2016 = fitFunc()
fitBDT1_2016.p1 = RooRealVar("CMS2016_BDT1_p1", "p1",-13.1451, -1000., 1000.) 
fitBDT1_2016.p2 = RooRealVar("CMS2016_BDT1_p2", "p2", 13.1451, -10., 10.) 
fitBDT1_2016.p3 = RooRealVar("CMS2016_BDT1_p3", "p3", 2.91787, -10., 10.)
fitBDT1_2016.modelBkg = RooGenericPdf("Bkg", "Bkg. fit (3 par.)", "pow(1 - @0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000))", RooArgList(mT, fitBDT1_2016.p1, fitBDT1_2016.p2, fitBDT1_2016.p3))

fitParam["BDT1_2016"] = fitBDT1_2016

fitBDT2_2016 = fitFunc()
fitBDT2_2016.p1 = RooRealVar("CMS2016_BDT2_p1", "p1", 12.5899, -1000., 1000.)
fitBDT2_2016.p2 = RooRealVar("CMS2016_BDT2_p2", "p2", 6.71091, -10., 10.)
fitBDT2_2016.p3 = RooRealVar("CMS2016_BDT2_p3", "p3", 0.265957, -10., 10.)
Esempio n. 23
0
thevars.add(tagged_mass)
thevars.add(mumuMass)
thevars.add(mumuMassE)
thevars.add(tagB0)

fulldata = RooDataSet('fulldata', 'fulldataset', tData, RooArgSet(thevars))
## add to the data dataset a random variable, in order to scale it to desired stat
nDataEntries = fulldata.sumEntries()
randVar = RooRealVar("rand", "rand", 0, 1)
p0 = RooPolynomial("px", "px", randVar)
rDataset = p0.generate(RooArgSet(randVar), int(nDataEntries))
fulldata.merge(rDataset)

## add to the input tree the combination of the variables, to be used for the cuts on the dimuon mass
deltaB0Mfunc = RooFormulaVar("deltaB0M", "deltaB0M", "@0 - @1",
                             RooArgList(tagged_mass, B0Mass))
deltaJMfunc = RooFormulaVar("deltaJpsiM", "deltaJpsiM", "@0 - @1",
                            RooArgList(mumuMass, JPsiMass))
deltaPMfunc = RooFormulaVar("deltaPsiPM", "deltaPsiPM", "@0 - @1",
                            RooArgList(mumuMass, PsiPMass))
deltaB0M = fulldata.addColumn(deltaB0Mfunc)
deltaJpsiM = fulldata.addColumn(deltaJMfunc)
deltaPsiPM = fulldata.addColumn(deltaPMfunc)

genSignal = RooRealVar("genSignal", "genSignal", 0, 10)
thevarsMC = thevars
thevarsMC.add(genSignal)
fullmc = RooDataSet('fullmc', 'fullmc', tMC, RooArgSet(thevarsMC))
deltaB0M = fullmc.addColumn(deltaB0Mfunc)
deltaJpsiM = fullmc.addColumn(deltaJMfunc)
deltaPsiPM = fullmc.addColumn(deltaPMfunc)
Esempio n. 24
0
def buildAccXRecEffiHist(self):
    """Build two step efficiency histograms for later fitting/plotting"""
    binKey = self.process.cfg['binKey']
    fin = self.process.filemanager.open("buildAccXRecEffiHist", modulePath + "/data/accXrecEffHists_{0}_{1}.root".format(str(self.process.cfg['args'].Year), q2bins[binKey]['label']), "UPDATE")
    # Build acceptance, reco efficiency, and accXrec
    forceRebuild = False

    h2_accXrec = fin.Get("h2_accXrec_{0}".format(binKey))
    if h2_accXrec == None or forceRebuild:
        h2_acc = fin.Get("h2_acc_{0}".format(binKey))
        h2_rec = fin.Get("h2_rec_{0}".format(binKey))

        # Fill histograms
        setupEfficiencyBuildProcedure['acc'].update({
            'ifiles'    : self.process.cfg['genonly']['PhiMuMu'],
            'baseString': re.sub("Q2", "genQ2", q2bins[binKey]['cutString']) + " && genKpPt>0 && genKmPt>0",
            'cutString' : "({0}) && ({1})".format(re.sub("Q2", "genQ2", q2bins[binKey]['cutString']), genSel)})
        setupEfficiencyBuildProcedure['rec'].update({
            'ifiles'    : self.process.cfg['sigMC'],
            'dfiles'    : self.process.cfg['genOff']['PhiMuMu'],
            'baseString': "({0}) && ({1})".format(re.sub("Q2", "genQ2", q2bins[binKey]['cutString']), genSel),
            'cutString' : "({0}) && ({1}) && ({2})".format(cuts_antiResVeto if binKey in ['jpsi', 'psi2s'] else self.process.cfg['cuts'][-1], q2bins[binKey]['cutString'], 1 if ExtraCuts==None else ExtraCuts)})

        LBins=accXEffThetaLBins #if not binKey=="belowJpsiA" else ThetaLBins
        KBins=accXEffThetaKBins #if not binKey=="belowJpsiA" else ThetaKBins
        for h2, label in (h2_acc, 'acc'), (h2_rec, 'rec'):
            if h2 == None or forceRebuild:
                treein = TChain("tree")
                for f in setupEfficiencyBuildProcedure[label]['ifiles']:
                    treein.Add(f)

                treeDen = TChain()
                if label=="rec":
                    for f in setupEfficiencyBuildProcedure[label]['dfiles']:
                        treeDen.Add(f)
                UseDataFrame=True
                if UseDataFrame:
                    if setupEfficiencyBuildProcedure[label]['weight'] is None and label=="acc":
                        df_tot = ROOT.RDataFrame(treein).Define('weight', "1").Filter(setupEfficiencyBuildProcedure[label]['baseString'])
                    elif label=="acc":
                        df_tot = ROOT.RDataFrame(treein).Define('weight', *setupEfficiencyBuildProcedure[label]['weight']).Filter(setupEfficiencyBuildProcedure[label]['baseString'])
                    elif setupEfficiencyBuildProcedure[label]['weight'] is None and label=="rec":
                        df_tot = ROOT.RDataFrame(treeDen).Define('weight', "1").Filter(setupEfficiencyBuildProcedure[label]['baseString'])
                    elif label=="rec":
                        df_tot = ROOT.RDataFrame(treeDen).Define('weight', *setupEfficiencyBuildProcedure[label]['weight']).Filter(setupEfficiencyBuildProcedure[label]['baseString'])
                    df_acc = ROOT.RDataFrame(treein).Define('weight', "1").Filter(setupEfficiencyBuildProcedure[label]['cutString'])

                    fillXY = setupEfficiencyBuildProcedure[label]['fillXY'].split(':')
                    if label=="rec": fillXYDen = setupEfficiencyBuildProcedure[label]['fillXYDen'].split(':')
                    h2_total_config = ("h2_{0}_{1}_total".format(label, binKey), "", len(LBins) - 1, LBins, len(KBins) - 1, KBins)
                    h2_passed_config  = ("h2_{0}_{1}_passed".format(label, binKey), "", len(LBins) - 1, LBins, len(KBins) - 1, KBins)
                    h2_fine_total_config = ("h2_{0}_fine_{1}_total".format(label, binKey), "", 20, -1, 1, 20, -1, 1)
                    h2_fine_passed_config = ("h2_{0}_fine_{1}_passed".format(label, binKey), "", 20, -1, 1, 20, -1, 1)

                    h2ptr_total = df_tot.Histo2D(h2_total_config, fillXY[1], fillXY[0], "weight") if label=="acc" else df_tot.Histo2D(h2_total_config, fillXYDen[1], fillXYDen[0], "weight")
                    h2ptr_passed = df_acc.Histo2D(h2_passed_config, fillXY[1], fillXY[0], "weight")
                    h2ptr_fine_total = df_tot.Histo2D(h2_fine_total_config, fillXY[1], fillXY[0], "weight") if label=="acc" else df_tot.Histo2D(h2_fine_total_config, fillXYDen[1], fillXYDen[0], "weight")
                    h2ptr_fine_passed = df_acc.Histo2D(h2_fine_passed_config, fillXY[1], fillXY[0], "weight")

                    h2_total = h2ptr_total.GetValue()
                    h2_passed = h2ptr_passed.GetValue()
                    h2_fine_total = h2ptr_fine_total.GetValue()
                    h2_fine_passed = h2ptr_fine_passed.GetValue()
                    print("{2}: {0}/{1}".format(df_acc.Count().GetValue(), df_tot.Count().GetValue(), label))
                else:
                    if label=='acc':
                        treein.Draw(">>totEvtList", setupEfficiencyBuildProcedure['acc']['baseString'])
                        totEvtList = ROOT.gDirectory.Get("totEvtList")
                        treein.Draw(">>accEvtList", setupEfficiencyBuildProcedure['acc']['cutString'])
                        accEvtList = ROOT.gDirectory.Get("accEvtList")
                    if label=='rec':
                        treeDen.Draw(">>totEvtList", setupEfficiencyBuildProcedure['rec']['baseString'])
                        totEvtList = ROOT.gDirectory.Get("totEvtList")
                        treein.Draw(">>accEvtList", setupEfficiencyBuildProcedure['rec']['cutString'])
                        accEvtList = ROOT.gDirectory.Get("accEvtList")
                    h2_total = TH2D("h2_{0}_{1}_total".format(label,binKey), "", len(LBins)-1, LBins, len(KBins)-1, KBins)
                    h2_passed = h2_total.Clone("h2_{0}_{1}_passed".format(label, binKey))
                    h2_fine_total = TH2D("h2_{0}_fine_{1}_total".format(label, binKey), "", 20, -1, 1, 20, -1, 1)
                    h2_fine_passed = h2_fine_total.Clone("h2_{0}_fine_{1}_passed".format(label, binKey))
                    
                    treeDen.SetEventList(totEvtList) if label=='rec' else treein.SetEventList(totEvtList)
                    for hist in h2_total, h2_fine_total:
                        if label=='rec':
                            treeDen.Draw("{0}>>{1}".format(setupEfficiencyBuildProcedure['rec']['fillXYDen'], hist.GetName()), "", "goff")
                        else:
                            treein.Draw("{0}>>{1}".format(setupEfficiencyBuildProcedure['acc']['fillXY'], hist.GetName()), "", "goff")
                    treein.SetEventList(accEvtList)
                    for hist in h2_passed, h2_fine_passed:
                        treein.Draw("{0}>>{1}".format(setupEfficiencyBuildProcedure[label]['fillXY'], hist.GetName()), "", "goff")
                    print("{2}: {0}/{1}".format(accEvtList.GetN(), totEvtList.GetN(), label))
                print("Base String: ", setupEfficiencyBuildProcedure[label]['baseString'])
                print("Cut String:  ", setupEfficiencyBuildProcedure[label]['cutString'])
                h2_eff = TEfficiency(h2_passed, h2_total)
                h2_eff_fine = TEfficiency(h2_fine_passed, h2_fine_total)

                fin.cd()
                for proj, var in [("ProjectionX", CosThetaL), ("ProjectionY", CosThetaK)]:
                    proj_fine_total = getattr(h2_fine_total, proj)("{0}_{1}".format(h2_fine_total.GetName(), proj), 0, -1, "e")
                    proj_fine_passed = getattr(h2_fine_passed, proj)("{0}_{1}".format(h2_fine_passed.GetName(), proj), 0, -1, "e")
                    h_eff = TEfficiency(proj_fine_passed, proj_fine_total)
                    h_eff.Write("h_{0}_fine_{1}_{2}".format(label, binKey, proj), ROOT.TObject.kOverwrite)

                h2_eff.Write("h2_{0}_{1}".format(label, binKey), ROOT.TObject.kOverwrite)
                h2_eff_fine.Write("h2_{0}_fine_{1}".format(label, binKey), ROOT.TObject.kOverwrite)
                h2_eff.CreateHistogram().Write("hist2_{0}_{1}".format(label, binKey), ROOT.TObject.kOverwrite)
                h2_eff_fine.CreateHistogram().Write("hist2_{0}_fine_{1}".format(label, binKey), ROOT.TObject.kOverwrite)
                if UseDataFrame: del df_acc, df_tot

        # Merge acc and rec to accXrec
        fin.cd()
        for proj in ["ProjectionX", "ProjectionY"]:
            h_acc_fine = fin.Get("h_acc_fine_{0}_{1}".format(binKey, proj))
            h_rec_fine = fin.Get("h_rec_fine_{0}_{1}".format(binKey, proj))
            hist_acc_fine = h_acc_fine.GetPassedHistogram().Clone("hist_acc_fine_{0}_{1}".format(binKey, proj))
            hist_rec_fine = h_rec_fine.GetPassedHistogram().Clone("hist_rec_fine_{0}_{1}".format(binKey, proj))
            h_accXrec_fine = h_acc_fine.GetPassedHistogram().Clone("h_accXrec_fine_{0}_{1}".format(binKey, proj))
            hist_acc_fine.Reset("ICESM")
            hist_rec_fine.Reset("ICESM")
            h_accXrec_fine.Reset("ICESM")
            for b in range(1, h_accXrec_fine.GetNbinsX() + 1):
                hist_acc_fine.SetBinContent(b, h_acc_fine.GetEfficiency(b))
                hist_acc_fine.SetBinError(b, max(h_acc_fine.GetEfficiencyErrorLow(b), h_acc_fine.GetEfficiencyErrorUp(b)))
                hist_rec_fine.SetBinContent(b, h_rec_fine.GetEfficiency(b))
                hist_rec_fine.SetBinError(b, max(h_rec_fine.GetEfficiencyErrorLow(b), h_rec_fine.GetEfficiencyErrorUp(b)))
                if h_rec_fine.GetTotalHistogram().GetBinContent(b) == 0 or h_rec_fine.GetPassedHistogram().GetBinContent(b) == 0:
                    h_accXrec_fine.SetBinContent(b, 0)
                    h_accXrec_fine.SetBinError(b, 1)
                    print(">> Empty reco eff bin #", b)
                else:
                    h_accXrec_fine.SetBinContent(b, h_acc_fine.GetEfficiency(b) * h_rec_fine.GetEfficiency(b))
                    h_accXrec_fine.SetBinError(b, h_accXrec_fine.GetBinContent(b) * math.sqrt(1 / h_acc_fine.GetTotalHistogram().GetBinContent(b) + 1 / h_acc_fine.GetPassedHistogram().GetBinContent(b) + 1 / h_rec_fine.GetTotalHistogram().GetBinContent(b) + 1 / h_rec_fine.GetPassedHistogram().GetBinContent(b)))
            hist_acc_fine.Write("hist_acc_{0}_{1}".format(binKey, proj), ROOT.TObject.kOverwrite)
            hist_rec_fine.Write("hist_rec_{0}_{1}".format(binKey, proj), ROOT.TObject.kOverwrite)
            h_accXrec_fine.Write("h_accXrec_{0}_{1}".format(binKey, proj), ROOT.TObject.kOverwrite)

        h2_acc = fin.Get("h2_acc_{0}".format(binKey))
        h2_rec = fin.Get("h2_rec_{0}".format(binKey))
        h2_accXrec = h2_acc.GetPassedHistogram().Clone("h2_accXrec_{0}".format(binKey))
        h2_accXrec.Reset("ICESM")
        for iL, iK in itertools.product(range(1, len(LBins)), range(1, len(KBins))):
            if h2_rec.GetTotalHistogram().GetBinContent(iL, iK) == 0 or h2_rec.GetPassedHistogram().GetBinContent(iL, iK) == 0 or h2_acc.GetTotalHistogram().GetBinContent(iL, iK) == 0 or h2_acc.GetPassedHistogram().GetBinContent(iL, iK) == 0:
                h2_accXrec.SetBinContent(iL, iK, 0)
                h2_accXrec.SetBinError(iL, iK, 1)
                print(">> Empty recoORacc eff bin #", iL, iK)
            else:
                iLK = h2_acc.GetGlobalBin(iL, iK)
                h2_accXrec.SetBinContent(iL, iK, h2_acc.GetEfficiency(iLK) * h2_rec.GetEfficiency(iLK))
                h2_accXrec.SetBinError(iL, iK, h2_accXrec.GetBinContent(iL, iK) * math.sqrt(1 / h2_acc.GetTotalHistogram().GetBinContent(iLK) + 1 / h2_acc.GetPassedHistogram().GetBinContent(iLK) + 1 / h2_rec.GetTotalHistogram().GetBinContent(iLK) + 1 / h2_rec.GetPassedHistogram().GetBinContent(iLK)))
        h2_accXrec.SetXTitle("cos#theta_{l}")
        h2_accXrec.SetYTitle("cos#theta_{K}")
        h2_accXrec.SetZTitle("Overall efficiency")

        h2_accXrec.Write("h2_accXrec_{0}".format(binKey), ROOT.TObject.kOverwrite)
        self.logger.logINFO("Overall efficiency is built.")

    # Register the chosen one to sourcemanager
    #  h2_accXrec = fin.Get("h2_accXrec_{0}".format(self.process.cfg['binKey']))
    Year=str(self.process.cfg['args'].Year)
    self.cfg['source'][self.name + '.h2_accXrec.{0}'.format(Year)] = h2_accXrec
    self.cfg['source'][self.name + '.accXrec.{0}'.format(Year)] = RooDataHist("accXrec", "", RooArgList(CosThetaL, CosThetaK), ROOT.RooFit.Import(h2_accXrec))
    self.cfg['source'][self.name + '.h_accXrec_fine_ProjectionX.{0}'.format(Year)] = fin.Get("h_accXrec_{0}_ProjectionX".format(self.process.cfg['binKey']))
    self.cfg['source'][self.name + '.h_accXrec_fine_ProjectionY.{0}'.format(Year)] = fin.Get("h_accXrec_{0}_ProjectionY".format(self.process.cfg['binKey']))
   
    hist2_acc_fine = fin.Get("hist2_acc_fine_{0}".format(binKey))
    self.cfg['source'][self.name + '.hist2_acc_fine.{}'.format(Year)] = hist2_acc_fine
    self.cfg['source'][self.name + '.acc_fine.{0}'.format(Year)] = RooDataHist("acc_fine", "", RooArgList(CosThetaL, CosThetaK), ROOT.RooFit.Import(hist2_acc_fine))
    self.cfg['source'][self.name + '.h_acc_fine_ProjectionX.{0}'.format(Year)] = fin.Get("hist_acc_{0}_ProjectionX".format(self.process.cfg['binKey']))
    self.cfg['source'][self.name + '.h_acc_fine_ProjectionY.{0}'.format(Year)] = fin.Get("hist_acc_{0}_ProjectionY".format(self.process.cfg['binKey']))

    hist2_rec_fine = fin.Get("hist2_rec_fine_{0}".format(binKey))
    self.cfg['source'][self.name + '.hist2_rec_fine.{}'.format(Year)] = hist2_rec_fine
    self.cfg['source'][self.name + '.rec_fine.{0}'.format(Year)] = RooDataHist("rec_fine", "", RooArgList(CosThetaL, CosThetaK), ROOT.RooFit.Import(hist2_rec_fine))
    self.cfg['source'][self.name + '.h_rec_fine_ProjectionX.{0}'.format(Year)] = fin.Get("hist_rec_{0}_ProjectionX".format(self.process.cfg['binKey']))
    self.cfg['source'][self.name + '.h_rec_fine_ProjectionY.{0}'.format(Year)] = fin.Get("hist_rec_{0}_ProjectionY".format(self.process.cfg['binKey']))

    hist2_acc = fin.Get("hist2_acc_{0}".format(binKey))
    self.cfg['source'][self.name + '.hist2_acc.{}'.format(Year)] = hist2_acc
    self.cfg['source'][self.name + '.acc.{0}'.format(Year)] = RooDataHist("acc", "", RooArgList(CosThetaL, CosThetaK), ROOT.RooFit.Import(hist2_acc))
    hist2_rec = fin.Get("hist2_rec_{0}".format(binKey))
    self.cfg['source'][self.name + '.hist2_rec.{}'.format(Year)] = hist2_rec
    self.cfg['source'][self.name + '.rec.{0}'.format(Year)] = RooDataHist("rec", "", RooArgList(CosThetaL, CosThetaK), ROOT.RooFit.Import(hist2_rec))
Esempio n. 25
0
def buildTotalEffiHist(self):
    """Build one step efficiency histograms for later fitting/plotting"""
    binKey=self.process.cfg['binKey']
    fin = self.process.filemanager.open("buildAccXRecEffiHist", modulePath + "/data/TotalEffHists_{0}_{1}.root".format(str(self.process.cfg['args'].Year), q2bins[binKey]['label']), "UPDATE")

    # Build acceptance, reco efficiency, and accXrec
    forceRebuild = False
    h2_accXrec = fin.Get("h2_accXrec1_{0}".format(binKey))
    if h2_accXrec == None or forceRebuild:
        # Fill histograms
        setupEfficiencyBuildProcedure['acc'].update({
            'ifiles'    : self.process.cfg['genonly']['PhiMuMu'],
            'baseString': re.sub("Q2", "genQ2", q2bins[binKey]['cutString']) + " && genKpPt>0 && genKmPt>0",
            'cutString' : "({0}) && ({1})".format(re.sub("Q2", "genQ2", q2bins[binKey]['cutString']), genSel)})
        setupEfficiencyBuildProcedure['rec'].update({
            'ifiles'    : self.process.cfg['sigMC'],
            'baseString': "({0}) && ({1})".format(re.sub("Q2", "genQ2", q2bins[binKey]['cutString']), genSel),
            'cutString' : "({0}) && ({1}) && ({2})".format(self.process.cfg['cuts'][-1], q2bins[binKey]['cutString'], 1 if ExtraCuts==None else ExtraCuts)})

        label='accXrec'
        treein = TChain()
        for f in setupEfficiencyBuildProcedure['acc']['ifiles']:
            treein.Add(f)
        treein.Draw(">>totEvtList", setupEfficiencyBuildProcedure['acc']['baseString'])
        totEvtList = ROOT.gDirectory.Get("totEvtList")

        treeinPassed = TChain()
        for f in setupEfficiencyBuildProcedure['rec']['ifiles']:
            treeinPassed.Add(f)
        treeinPassed.Draw(">>accEvtList", setupEfficiencyBuildProcedure['rec']['cutString'])
        accEvtList = ROOT.gDirectory.Get("accEvtList")

        LBins=accXEffThetaLBins #if not binKey=="belowJpsiA" else ThetaLBins
        KBins=accXEffThetaKBins #if not binKey=="belowJpsiA" else ThetaKBins
        h2_total = TH2D("h2_{0}_{1}_total".format(label, binKey), "", len(LBins)-1, LBins, len(KBins)-1, KBins)
        h2_passed = h2_total.Clone("h2_{0}_{1}_passed".format(label, binKey))
        h2_fine_total = TH2D("h2_{0}_fine_{1}_total".format(label, binKey), "", 20, -1, 1, 20, -1, 1)
        h2_fine_passed = h2_fine_total.Clone("h2_{0}_fine_{1}_passed".format(label, binKey))

        treein.SetEventList(totEvtList) 
        for hist in h2_total, h2_fine_total:
            treein.Draw("{0}>>{1}".format(setupEfficiencyBuildProcedure['acc']['fillXY'], hist.GetName()), "", "goff")

        treeinPassed.SetEventList(accEvtList)
        for hist in h2_passed, h2_fine_passed:
            treeinPassed.Draw("{0}>>{1}".format(setupEfficiencyBuildProcedure['rec']['fillXY'], hist.GetName()), "", "goff")

        print("\033[0;34;47m Total: \033[0m", accEvtList.GetN(),"/",totEvtList.GetN())
        print("\033[0;34;47m Base String: \033[0m", setupEfficiencyBuildProcedure['acc']['baseString'])
        print("\033[0;34;47m Cut String : \033[0m", setupEfficiencyBuildProcedure['rec']['cutString'])

        h2_eff = TEfficiency(h2_passed, h2_total)
        h2_eff_fine = TEfficiency(h2_fine_passed, h2_fine_total)

        fin.cd()
        for proj, var in [("ProjectionX", CosThetaL), ("ProjectionY", CosThetaK)]:
            proj_fine_total = getattr(h2_fine_total, proj)("{0}_{1}".format(h2_fine_total.GetName(), proj), 0, -1, "e")
            proj_fine_passed = getattr(h2_fine_passed, proj)("{0}_{1}".format(h2_fine_passed.GetName(), proj), 0, -1, "e")
            h_eff = TEfficiency(proj_fine_passed, proj_fine_total)
            h_eff.Write("h_{0}_fine_{1}_{2}".format(label, binKey, proj), ROOT.TObject.kOverwrite)

        h2_eff.Write("h2Eff_{0}_{1}".format(label, binKey), ROOT.TObject.kOverwrite)           #Binned 2D Eff
        h2_eff_fine.Write("h2_{0}_fine_{1}".format(label, binKey), ROOT.TObject.kOverwrite) #2D Efficiency Total 

        # : Converting TEff to TH1D
        fin.cd()
        for proj in ["ProjectionX", "ProjectionY"]:
            h_accXrec_fineEff = fin.Get("h_accXrec_fine_{0}_{1}".format(binKey, proj))
            h_accXrec_fine = h_accXrec_fineEff.GetPassedHistogram().Clone("h_accXrec_fine_{0}_{1}".format(binKey, proj))
            h_accXrec_fine.Reset("ICESM")
            for b in range(1, h_accXrec_fine.GetNbinsX() + 1):
                h_accXrec_fine.SetBinContent(b, h_accXrec_fineEff.GetEfficiency(b))
                h_accXrec_fine.SetBinError(b, h_accXrec_fine.GetBinContent(b) * math.sqrt(1 / h_accXrec_fineEff.GetTotalHistogram().GetBinContent(b) + 1 / h_accXrec_fineEff.GetPassedHistogram().GetBinContent(b)))
            h_accXrec_fine.Write("h_accXrec_{0}_{1}".format(binKey, proj), ROOT.TObject.kOverwrite)

        h2_accXrecEff1 = fin.Get("h2Eff_accXrec_{0}".format(binKey))        #2D Binned Eff
        h2_accXrec1 = h2_accXrecEff1.GetPassedHistogram().Clone("h2_accXrec1_{0}".format(binKey)) 
        h2_accXrec1.Reset("ICESM")
        for iL, iK in itertools.product(range(1, len(LBins)), range(1, len(KBins))):
            if h2_accXrecEff1.GetTotalHistogram().GetBinContent(iL, iK) == 0:
                h2_accXrec1.SetBinContent(iL, iK, 0)
                h2_accXrec1.SetBinError(iL, iK, 1)
            else:
                iLK = h2_accXrecEff1.GetGlobalBin(iL, iK)
                h2_accXrec1.SetBinContent(iL, iK, h2_accXrecEff1.GetEfficiency(iLK))
                h2_accXrec1.SetBinError(iL, iK, h2_accXrec1.GetBinContent(iL, iK) * math.sqrt(1. / h2_accXrecEff1.GetTotalHistogram().GetBinContent(iLK) + 1. / h2_accXrecEff1.GetPassedHistogram().GetBinContent(iLK)))
        h2_accXrec1.SetXTitle("cos#theta_{l}")
        h2_accXrec1.SetYTitle("cos#theta_{K}")
        h2_accXrec1.SetZTitle("Overall efficiency")
        h2_accXrec1.Write("h2_accXrec1_{0}".format(binKey), ROOT.TObject.kOverwrite)
        self.logger.logINFO("Overall efficiency is built.")

        h2_accXrecEff = fin.Get("h2Eff_accXrec_{0}".format(binKey))        #2D Binned Eff: Same as h2_accXrec1_binKey, but using CreateHistogram()
        h2_accXrec = h2_accXrecEff.CreateHistogram(); h2_accXrec.SetTitle("Created from CreateHistogram() method")
        h2_accXrec.SetXTitle("cos#theta_{l}")
        h2_accXrec.SetYTitle("cos#theta_{K}")
        h2_accXrec.SetZTitle("Overall efficiency")
        h2_accXrec.Write("h2_accXrec_{0}".format(binKey), ROOT.TObject.kOverwrite)  # We are not going to use this as of now
        self.logger.logINFO("Overall efficiency is built.")

    # Register the chosen one to sourcemanager
    h2_accXrec = fin.Get("h2_accXrec1_{0}".format(self.process.cfg['binKey']))
    self.cfg['source']['effiHistReader.h2_accXrec.{0}'.format(str(self.process.cfg['args'].Year))] = h2_accXrec
    self.cfg['source']['effiHistReader.accXrec.{0}'.format(str(self.process.cfg['args'].Year))] = RooDataHist("accXrec", "", RooArgList(CosThetaL, CosThetaK), ROOT.RooFit.Import(h2_accXrec)) # Effi 2D RooDataHist
    self.cfg['source']['effiHistReader.h_accXrec_fine_ProjectionX.{0}'.format(str(self.process.cfg['args'].Year))] = fin.Get("h_accXrec_{0}_ProjectionX".format(self.process.cfg['binKey'])) #Effi of CosThetaL
    self.cfg['source']['effiHistReader.h_accXrec_fine_ProjectionY.{0}'.format(str(self.process.cfg['args'].Year))] = fin.Get("h_accXrec_{0}_ProjectionY".format(self.process.cfg['binKey'])) # Effi of CosThetaK
Esempio n. 26
0
    # binedges1[i] = 10**(log10(2E-4) + i*logwidth/nbins1)
    binedges1[i] = epsilon + i*1E-2/nbins1
    # print '%2d: %e' % (i, binedges1[i])

for i in range(nbins2+1):
    if i <= 15:
        binedges2[i] = epsilon + i*2E-4
    elif i <= 19:
        binedges2[i] = binedges2[15] + (i - 15)*5E-4
    else:
        binedges2[i] = binedges2[19] + (i - 19)*1E-3

# uniformbins = RooBinning(nbins1, binedges, 'uniformbins')

# Decay binned
decayfn = decaywdt.asTF(RooArgList(time), RooArgList(), timeargset)
# decayhist = decay.createHistogram('decayhist', time,
#                                   RooFit.Binning(uniformbins),
#                                   RooFit.ConditionalObservables(dtargset))
# decayhist.Sumw2()

# timehist = decayhist.Clone('timehist')
# timehist.Reset("ICESM")
timehist = TH1F('timehist', 'Lifetime distribution', nbins1, binedges1)
timehist.Sumw2()
timehist.SetLineColor(kAzure)

canvas1 = TCanvas('canvas1', 'Lifetime', 800, 600)
# canvas1.Divide(2, 1)
# canvas1.cd(1)
Esempio n. 27
0
        r = Kf/Kv
        if r in AllCtOverCVs.keys() :
            AllCtOverCVs[r][Kv] = 0.0
        else :
            AllCtOverCVs[r] = {Kv:0.0}

BinToPlot = sys.argv[1]
signals = { "tth":{"color":kRed} , "thq":{"color":kBlue} , "thw":{"color":kGreen} }
fOut = TFile.Open("out.root" , "recreate")
for kvkt in AllCtOverCVs:
    infile = TFile.Open( "ctcv%g/input.root" % (kvkt) )
    ws = infile.Get( "WS%s" % (BinToPlot) )

    mass = ws.var( "CMS_hgg_mass" )
    
    allPdfs = RooArgList()
    allNorms = RooArgList()
    finalNorm = 0.
    norms_ = {}
    for signal in signals :
        pdf = ws.pdf( "RV%s_mh125" % (signal) )
        norm = ws.var( "RV%s_mh125_norm" % (signal) )

        allPdfs.add( pdf )
        allNorms.add( norm )

        signals[signal]["pdf%g" % kvkt ] = pdf
        signals[signal]["norm%g" % kvkt ] = norm
        
        signals[signal]["extendedpdf%g" % kvkt ] = RooExtendPdf( "extended_%s_%g" % ( signal, kvkt ) , "extended_%s_%g" % ( signal, kvkt ) , pdf , norm )
        finalNorm += norm.getValV()
def rooFit501():

    print ">>> setup model for physics sample..."
    x = RooRealVar("x", "x", -8, 8)
    mean = RooRealVar("mean", "mean", 0, -8, 8)
    sigma = RooRealVar("sigma", "sigma", 0.3, 0.1, 10)
    gauss = RooGaussian("gx", "gx", x, mean, sigma)
    a0 = RooRealVar("a0", "a0", -0.1, -1, 1)
    a1 = RooRealVar("a1", "a1", 0.004, -1, 1)
    px = RooChebychev("px", "px", x, RooArgList(a0, a1))
    f = RooRealVar("f", "f", 0.2, 0., 1.)
    model = RooAddPdf("model", "model", RooArgList(gauss, px), RooArgList(f))

    print ">>> setup model for control sample..."
    # NOTE: sigma is shared with the signal sample model
    mean_ctrl = RooRealVar("mean_ctrl", "mean_ctrl", -3, -8, 8)
    gauss_ctrl = RooGaussian("gauss_ctrl", "gauss_ctrl", x, mean_ctrl, sigma)
    a0_ctrl = RooRealVar("a0_ctrl", "a0_ctrl", -0.1, -1, 1)
    a1_ctrl = RooRealVar("a1_ctrl", "a1_ctrl", 0.5, -0.1, 1)
    px_ctrl = RooChebychev("px_ctrl", "px_ctrl", x,
                           RooArgList(a0_ctrl, a1_ctrl))
    f_ctrl = RooRealVar("f_ctrl", "f_ctrl", 0.5, 0., 1.)
    model_ctrl = RooAddPdf("model_ctrl", "model_ctrl",
                           RooArgList(gauss_ctrl, px_ctrl), RooArgList(f_ctrl))

    print ">>> generate events for both samples..."
    data = model.generate(RooArgSet(x), 100)  # RooDataSet
    data_ctrl = model_ctrl.generate(RooArgSet(x), 2000)  # RooDataSet

    print ">>> create index category and join samples..."
    # Define category to distinguish physics and control samples events
    sample = RooCategory("sample", "sample")
    sample.defineType("physics")
    sample.defineType("control")

    print ">>> construct combined dataset in (x,sample)..."
    combData = RooDataSet("combData", "combined data", RooArgSet(x),
                          Index(sample), Import("physics", data),
                          Import("control", data_ctrl))

    print ">>> construct a simultaneous pdf in (x,sample)..."
    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample)

    # Associate model with the physics state and model_ctrl with the control state
    simPdf.addPdf(model, "physics")
    simPdf.addPdf(model_ctrl, "control")

    print ">>> perform a simultaneous fit..."
    # Perform simultaneous fit of model to data and model_ctrl to data_ctrl
    simPdf.fitTo(combData)

    print "\n>>> plot model slices on data slices..."
    frame1 = x.frame(Bins(30), Title("Physics sample"))  # RooPlot
    combData.plotOn(frame1, Cut("sample==sample::physics"))

    # Plot "physics" slice of simultaneous pdf.
    # NBL You _must_ project the sample index category with data using ProjWData
    # as a RooSimultaneous makes no prediction on the shape in the index category
    # and can thus not be integrated
    simPdf.plotOn(frame1, Slice(sample, "physics"),
                  ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(frame1, Slice(sample, "physics"), Components("px"),
                  ProjWData(RooArgSet(sample), combData), LineStyle(kDashed))

    print "\n>>> plot control sample slices..."
    frame2 = x.frame(Bins(30), Title("Control sample"))  # RooPlot
    combData.plotOn(frame2, Cut("sample==sample::control"))
    simPdf.plotOn(frame2, Slice(sample, "control"),
                  ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(frame2, Slice(sample, "control"), Components("px_ctrl"),
                  ProjWData(RooArgSet(sample), combData), LineStyle(kDashed))

    print "\n>>> draw on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 1400, 600)
    canvas.Divide(2)
    canvas.cd(1)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.6)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    canvas.cd(2)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame2.GetYaxis().SetLabelOffset(0.008)
    frame2.GetYaxis().SetTitleOffset(1.6)
    frame2.GetYaxis().SetTitleSize(0.045)
    frame2.GetXaxis().SetTitleSize(0.045)
    frame2.Draw()
    canvas.SaveAs("rooFit501.png")
Esempio n. 29
0
pf.GetYaxis().SetTitle('pull (#sigma)')
pyroot_logon.cmsPrelim(c4, fitterPars.intLumi/1000)
c4.Print('H{2}_Mjj_{0}_{1}jets_Pull.pdf'.format(modeString, opts.Nj, opts.mH))
c4.Print('H{2}_Mjj_{0}_{1}jets_Pull.png'.format(modeString, opts.Nj, opts.mH))

if (TMath.Prob(chi2Raw,  ndf2) < 0.05):
    print '**DANGER** The fit probability is low **DANGER**'
    if opts.debug:
        assert(False)

#assert(False)

mass.setRange('signal', fitterPars.minTrunc, fitterPars.maxTrunc)
#yields = theFitter.makeFitter().coefList()
finalPars = fr.floatParsFinal()
yields = RooArgList(finalPars)
yields.add(fr.constPars())
sigInt = theFitter.makeFitter().createIntegral(iset,iset,'signal')
sigFullInt = theFitter.makeFitter().createIntegral(iset,iset)
print "allBkg","sigInt",sigInt.getVal(),"fullInt",sigFullInt.getVal(),\
      "ratio",sigInt.getVal()/sigFullInt.getVal()
dibosonInt = theFitter.makeDibosonPdf().createIntegral(iset,iset,'signal')
dibosonFullInt = theFitter.makeDibosonPdf().createIntegral(iset,iset)
WpJPdf = theFitter.makeWpJPdf()
WpJInt = WpJPdf.createIntegral(iset, iset, 'signal')
WpJFullInt = WpJPdf.createIntegral(iset, iset)
#WpJPdf.Print("v")
print "WpJ","sigInt",WpJInt.getVal(),"fullInt",WpJFullInt.getVal(),\
      "ratio",WpJInt.getVal()/WpJFullInt.getVal()
ttbarInt = theFitter.makettbarPdf().createIntegral(iset, iset, 'signal')
ttbarFullInt = theFitter.makettbarPdf().createIntegral(iset, iset)
Esempio n. 30
0
def rooFit201():
    
    print ">>> setup model component: gaussian signals and Chebychev polynomial background..."
    x      = RooRealVar("x","x",0,11)
    mean   = RooRealVar("mean","mean of gaussians",5)
    sigma1 = RooRealVar("sigma1","width of gaussians",0.5)
    sigma2 = RooRealVar("sigma2","width of gaussians",1)
    sig1   = RooGaussian("sig1","Signal component 1",x,mean,sigma1)
    sig2   = RooGaussian("sig2","Signal component 2",x,mean,sigma2)
    
    a0  = RooRealVar("a0","a0",0.5,0.,1.)
    a1  = RooRealVar("a1","a1",-0.2,0.,1.)
    bkg = RooChebychev("bkg","Background",x,RooArgList(a0,a1))
    
    
    
    print ">>>\n>>> METHOD 1 - Two RooAddPdfs"
    print ">>> add signal components..."
    # Sum the signal components into a composite signal p.d.f.
    sig1frac = RooRealVar("sig1frac","fraction of component 1 in signal",0.8,0.,1.)
    sig      = RooAddPdf("sig","Signal",RooArgList(sig1,sig2),RooArgList(sig1frac))
    
    print ">>> add signal and background..."
    # Sum the composite signal and background
    bkgfrac = RooRealVar("bkgfrac","fraction of background",0.5,0.,1.)
    model   = RooAddPdf("model","g1+g2+a",RooArgList(bkg,sig),RooArgList(bkgfrac))
    
    print ">>> sample, fit and plot model..."
    data = model.generate(RooArgSet(x),1000) # RooDataSet
    model.fitTo(data)
    frame1 = x.frame(Title("Example of composite pdf=(sig1+sig2)+bkg")) # RooPlot
    data.plotOn(frame1,Binning(50),Name("data"))
    model.plotOn(frame1,Name("model"))
    
    # Overlay the background component of model with a dashed line
    argset1 = RooArgSet(bkg)
    model.plotOn(frame1,Components(argset1),LineWidth(2),Name("bkg")) #,LineStyle(kDashed)
    
    # Overlay the background+sig2 components of model with a dotted line
    argset2 = RooArgSet(bkg,sig2)
    model.plotOn(frame1,Components(argset2),LineWidth(2),LineStyle(kDashed),LineColor(kAzure-4),Name("bkgsig2")) #,LineStyle(kDotted)
    
    print "\n>>> structure of composite pdf:"
    model.Print("t") # "tree" mode
    
    print "\n>>> parameters:"
    params = model.getVariables() # RooArgSet
    params.Print("v")
    params.Print()
    
    print "\n>>> params.find(\"...\").getVal():"
    print ">>>   sigma1  = %.2f"   % params.find("sigma1").getVal()
    print ">>>   sigma2  = %.2f"   % params.find("sigma2").getVal()
    print ">>>   bkgfrac = %5.2f"  % params.find("bkgfrac").getVal()
    print ">>>   sig1frac = %5.2f" % params.find("sig1frac").getVal()
    
    print ">>>\n>>> components:"
    comps   = model.getComponents() # RooArgSet
    sig     = comps.find("sig")     # RooAbsArg
    sigVars = sig.getVariables()    # RooArgSet
    sigVars.Print()
    
    
    
    print ">>>\n>>> METHOD 2 - One RooAddPdf with recursive fractions"
    # Construct sum of models on one go using recursive fraction interpretations
    #   model2 = bkg + (sig1 + sig2)
    model2 = RooAddPdf("model","g1+g2+a",RooArgList(bkg,sig1,sig2),RooArgList(bkgfrac,sig1frac),kTRUE)
    
    # NB: Each coefficient is interpreted as the fraction of the
    # left-hand component of the i-th recursive sum, i.e.
    #   sum4 = A + ( B + ( C + D ) )
    # with fraction fA, fB and fC expands to
    #   sum4 = fA*A + (1-fA)*(fB*B + (1-fB)*(fC*C + (1-fC)*D))
    
    print ">>> plot recursive addition model..."
    argset3 = RooArgSet(bkg,sig2)
    model2.plotOn(frame1,LineColor(kRed),LineStyle(kDashDotted),LineWidth(3),Name("model2"))
    model2.plotOn(frame1,Components(argset3),LineColor(kMagenta),LineStyle(kDashDotted),LineWidth(3),Name("bkgsig22"))
    model2.Print("t")
    
    
    
    print ">>> draw pdfs and fits on canvas..."
    canvas = TCanvas("canvas","canvas",100,100,800,600)
    legend = TLegend(0.57,0.87,0.95,0.65)
    legend.SetTextSize(0.030)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.14); gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data",    "data",                            'LEP')
    legend.AddEntry("model",   "composite model",                 'L')
    legend.AddEntry("model2",  "composite model (method 2)",      'L')
    legend.AddEntry("bkg",     "background only",                 'L')
    legend.AddEntry("bkgsig2", "background + signal 2",           'L')
    legend.AddEntry("bkgsig22","background + signal 2 (method 2)",'L')
    legend.Draw()
    canvas.SaveAs("rooFit201.png")
Esempio n. 31
0
def fitData(fulldata, ibin, nRT_fromMC, nWT_fromMC):

    cut = cut_base + '&& (mumuMass*mumuMass > %s && mumuMass*mumuMass < %s)' % (
        q2binning[ibin], q2binning[ibin + 1])
    fulldata_v2 = fulldata.reduce(
        RooArgSet(tagged_mass, mumuMass, mumuMassE, randVar), cut)

    ## reduce to data-like statistics
    nDataEntries = fulldata_v2.sumEntries()
    nDesired = n_bin[ibin] / nDataEntries
    cut = 'rand < %f' % nDesired
    data = fulldata_v2.reduce(RooArgSet(tagged_mass, mumuMass, mumuMassE), cut)

    fraction = dict_s_rt[ibin] / (dict_s_rt[ibin] + dict_s_wt[ibin])
    print 'mistag fraction on MC for bin ', ibin, ' : ', fraction.n, '+/-', fraction.s

    ### creating RT component
    w.loadSnapshot("reference_fit_RT_%s" % ibin)
    mean_rt = w.var("mean_{RT}^{%s}" % ibin)
    sigma_rt1 = w.var("#sigma_{RT1}^{%s}" % ibin)

    sigma_rt2 = RooRealVar()
    alpha_rt1 = RooRealVar()
    alpha_rt2 = RooRealVar()
    n_rt1 = RooRealVar()
    n_rt2 = RooRealVar()
    f1rt = RooRealVar()

    ## double cb fast
    if ibin < 4:
        alpha_rt1 = w.var("#alpha_{RT1}^{%s}" % ibin)
        alpha_rt2 = w.var("#alpha_{RT2}^{%s}" % ibin)
        n_rt1 = w.var("n_{RT1}^{%s}" % ibin)
        n_rt2 = w.var("n_{RT2}^{%s}" % ibin)

    ## double cb old
    else:
        sigma_rt2 = w.var("#sigma_{RT2}^{%s}" % ibin)
        alpha_rt1 = w.var("#alpha_{RT1}^{%s}" % ibin)
        alpha_rt2 = w.var("#alpha_{RT2}^{%s}" % ibin)
        n_rt1 = w.var("n_{RT1}^{%s}" % ibin)
        n_rt2 = w.var("n_{RT2}^{%s}" % ibin)
        f1rt = w.var("f^{RT%s}" % ibin)

    theRTgauss = w.pdf("doublecb_RT%s" % ibin)

    ### creating WT component
    w.loadSnapshot("reference_fit_WT_%s" % ibin)
    mean_wt = w.var("mean_{WT}^{%s}" % ibin)
    sigma_wt = w.var("#sigma_{WT1}^{%s}" % ibin)
    alpha_wt1 = w.var("#alpha_{WT1}^{%s}" % ibin)
    alpha_wt2 = w.var("#alpha_{WT2}^{%s}" % ibin)
    n_wt1 = w.var("n_{WT1}^{%s}" % ibin)
    n_wt2 = w.var("n_{WT2}^{%s}" % ibin)
    theWTgauss = w.pdf("doublecb_%s" % ibin)

    ### creating variable for the difference between the two peaks
    deltaPeaks = RooFormulaVar("deltaPeaks", "@0 - @1",
                               RooArgList(mean_rt, mean_wt))
    frt = RooRealVar("F_{RT}", "frt", fraction.n, 0, 1)
    signalFunction = RooAddPdf("sumgaus", "rt+wt",
                               RooArgList(theRTgauss, theWTgauss),
                               RooArgList(frt))

    ### now create background parametrization
    slope = RooRealVar("slope", "slope", 0.5, -10, 10)
    bkg_exp = RooExponential("bkg_exp", "exponential", slope, tagged_mass)
    pol_c1 = RooRealVar("p1", "coeff x^0 term", 0.5, -10, 10)
    pol_c2 = RooRealVar("p2", "coeff x^1 term", 0.5, -10, 10)
    bkg_pol = RooChebychev("bkg_pol", "2nd order pol", tagged_mass,
                           RooArgList(pol_c1))

    nsig = RooRealVar("Yield", "signal frac", nRT_fromMC + nWT_fromMC, 0,
                      1000000)
    nbkg = RooRealVar("nbkg", "bkg fraction", 1000, 0, 550000)

    print nsig.getVal()

    ### creating constraints
    c_vars = RooArgSet()
    c_pdfs = RooArgSet()

    c_sigma_rt1 = _constrainVar(sigma_rt1, 1)
    c_alpha_rt1 = _constrainVar(alpha_rt1, 1)
    c_alpha_rt2 = _constrainVar(alpha_rt2, 1)
    c_n_rt1 = _constrainVar(n_rt1, 1)
    c_n_rt2 = _constrainVar(n_rt2, 1)

    c_sigma_wt = _constrainVar(sigma_wt, 1)
    c_alpha_wt1 = _constrainVar(alpha_wt1, 1)
    c_alpha_wt2 = _constrainVar(alpha_wt2, 1)
    c_n_wt1 = _constrainVar(n_wt1, 1)
    c_n_wt2 = _constrainVar(n_wt2, 1)

    if ibin < 4:
        c_pdfs = RooArgSet(c_sigma_rt1, c_alpha_rt1, c_alpha_rt2, c_n_rt1,
                           c_n_rt2)
        c_vars = RooArgSet(sigma_rt1, alpha_rt1, alpha_rt2, n_rt1, n_rt2)
    else:
        c_sigma_rt2 = _constrainVar(sigma_rt2, 1)
        c_f1rt = _constrainVar(f1rt, 1)
        c_pdfs = RooArgSet(c_sigma_rt1, c_sigma_rt2, c_alpha_rt1, c_alpha_rt2,
                           c_n_rt1, c_n_rt2, c_f1rt)
        c_vars = RooArgSet(sigma_rt1, sigma_rt2, alpha_rt1, alpha_rt2, n_rt1,
                           n_rt2, f1rt)

    c_pdfs.add(c_sigma_wt)
    c_vars.add(sigma_wt)
    c_pdfs.add(c_alpha_wt1)
    c_vars.add(alpha_wt1)
    c_pdfs.add(c_alpha_wt2)
    c_vars.add(alpha_wt2)
    c_pdfs.add(c_n_wt1)
    c_vars.add(n_wt1)
    c_pdfs.add(c_n_wt2)
    c_vars.add(n_wt2)

    ### creating constraints for the difference between the two peaks
    c_deltaPeaks = RooGaussian(
        "c_deltaPeaks",
        "c_deltaPeaks",
        deltaPeaks,
        ROOT.RooFit.RooConst(deltaPeaks.getVal()),
        ROOT.RooFit.RooConst(0.0005)  ## value to be checked
    )
    c_pdfs.add(c_deltaPeaks)
    c_vars.add(deltaPeaks)

    c_frt = RooGaussian("c_frt%s" % ibin, "c_frt", frt,
                        ROOT.RooFit.RooConst(fraction.n),
                        ROOT.RooFit.RooConst(frt_sigma[ibin]))
    c_pdfs.add(c_frt)
    c_vars.add(frt)

    constr_list = RooArgList(c_pdfs)
    constr_list.add(signalFunction)
    c_signalFunction = RooProdPdf("c_signalFunction", "c_signalFunction",
                                  constr_list)

    fitFunction = c_signalFunction

    r = fitFunction.fitTo(
        data,
        #                           RooFit.Extended(True),
        RooFit.Range("full"),
        ROOT.RooFit.Constrain(c_vars),
        ROOT.RooFit.Minimizer("Minuit2", "migrad"),
        ROOT.RooFit.Hesse(True),
        ROOT.RooFit.Strategy(2),
        ROOT.RooFit.Minos(False),
    )
    print 'fit with Hesse strategy 2 done, now Minos'
    r = fitFunction.fitTo(
        data,
        #                           RooFit.Extended(True),
        RooFit.Save(),
        RooFit.Range("full"),
        RooFit.Verbose(False),
        ROOT.RooFit.Constrain(c_vars),
        #                           ROOT.RooFit.Minimizer("Minuit2","migrad"),
        #                           ROOT.RooFit.Hesse(True),
        ROOT.RooFit.Strategy(2),
        ROOT.RooFit.Minos(True),
    )

    r.Print()
    r.correlationMatrix().Print()
    fitStats['data%s' % (ibin)] = r.status()
    covStats['data%s' % (ibin)] = r.covQual()
    frame = tagged_mass.frame(RooFit.Range("full"))
    data.plotOn(frame, RooFit.Binning(nbins), RooFit.MarkerSize(.7))
    fitFunction.plotOn(frame, RooFit.NormRange("full"), RooFit.Range("full"))

    ## evaluate sort of chi2 and save number of RT/WT events
    observables = RooArgSet(tagged_mass)
    flparams = fitFunction.getParameters(observables)
    nparam = int(flparams.selectByAttrib("Constant", ROOT.kFALSE).getSize())
    pdfstring = "c_signalFunction_Norm[tagged_mass]_Range[full]_NormRange[full]"
    chi2s['data%s' % ibin] = frame.chiSquare(pdfstring, "h_fulldata", nparam)
    frame.addObject(_writeChi2(chi2s['data%s' % ibin]))

    drawPdfComponents(fitFunction,
                      frame,
                      ROOT.kAzure,
                      RooFit.NormRange("full"),
                      RooFit.Range("full"),
                      isData=True)

    parList = RooArgSet(nsig, mean_rt, mean_wt, sigma_rt1, sigma_rt2,
                        alpha_rt1, alpha_rt2, mean_wt, sigma_wt)
    parList.add(alpha_wt1)
    parList.add(alpha_wt2)
    parList.add(n_wt1)
    parList.add(n_wt2)
    parList.add(frt)
    fitFunction.paramOn(frame, RooFit.Parameters(parList),
                        RooFit.Layout(0.62, 0.86, 0.89))

    frame.Draw()
    niceFrame(frame, '')
    frame.addObject(_writeFitStatus(r))

    c1 = ROOT.TCanvas()
    upperPad = ROOT.TPad('upperPad', 'upperPad', 0., 0.35, 1., 1.)
    lowerPad = ROOT.TPad('lowerPad', 'lowerPad', 0., 0.0, 1., 0.345)
    upperPad.SetBottomMargin(0.012)
    lowerPad.SetTopMargin(0)
    lowerPad.SetBottomMargin(0.2)

    upperPad.Draw()
    lowerPad.Draw()
    upperPad.cd()
    frame.Draw()
    if not args.year == 'test':
        writeCMS(frame, args.year, [q2binning[ibin], q2binning[ibin + 1]], 1)
    frame.Draw()

    ## add plot of pulls
    lowerPad.cd()
    hpull = frame.pullHist("h_fulldata", pdfstring)
    frame2 = tagged_mass.frame(RooFit.Range("full"), RooFit.Title(''))
    frame2.addPlotable(hpull, "P")
    niceFrameLowerPad(frame2, 'pull')
    frame2.Draw()
    line = ROOT.TLine(5.0, 1, 5.6, 1)
    line.SetLineColor(ROOT.kGreen + 3)
    line.Draw()

    for ilog in [True, False]:
        upperPad.SetLogy(ilog)
        c1.SaveAs(
            'fit_results_mass_checkOnMC/save_fit_data_%s_%s_LMNR_newSigmaFRT_%s.pdf'
            % (ibin, args.year, '_logScale' * ilog))

    out_f.cd()
    r.Write('results_data_%s' % (ibin))

    params = fitFunction.getParameters(RooArgSet(tagged_mass))
    w.saveSnapshot("reference_fit_data_%s" % (ibin), params, ROOT.kTRUE)
    getattr(w, 'import')(fitFunction)
KStMass = RooRealVar("KStMass", "KStMass", KStMass_)

thevars = RooArgSet()
thevars.add(bMass)
thevars.add(bBarMass)
thevars.add(mumuMass)
thevars.add(mumuMassE)
thevars.add(tagB0)

fulldata = RooDataSet('fulldata', 'fulldataset', tree, RooArgSet(thevars))

## add to the input tree the combination of the variables for the B0 arb. mass
theBMassfunc = RooFormulaVar("theBMass",
                             "#mu^{+}#mu^{-}K^{#pm}#pi^{#mp} mass [GeV]",
                             "@0*@1 + (1-@0)*@2",
                             RooArgList(tagB0, bMass, bBarMass))
theBMass = fulldata.addColumn(theBMassfunc)
theBMass.setRange(4.9, 5.7)
## add to the input tree the combination of the variables, to be used for the cuts on the dimuon mass
deltaB0Mfunc = RooFormulaVar("deltaB0M", "deltaB0M", "@0 - @1",
                             RooArgList(theBMass, B0Mass))
deltaB0M = fulldata.addColumn(deltaB0Mfunc)
deltaJMfunc = RooFormulaVar("deltaJpsiM", "deltaJpsiM", "@0 - @1",
                            RooArgList(mumuMass, JPsiMass))
deltaJpsiM = fulldata.addColumn(deltaJMfunc)
deltaPMfunc = RooFormulaVar("deltaPsiPM", "deltaPsiPM", "@0 - @1",
                            RooArgList(mumuMass, PsiPMass))
deltaPsiPM = fulldata.addColumn(deltaPMfunc)

if args.dimusel == 'keepJpsi':
    cut = '(abs(mumuMass - {JPSIM}) < {CUT}*mumuMassE)'.format(
Esempio n. 33
0
#   #   #   #    #  #    #    #
#   ####    #    #  #    #    #
#   #  #    #    #  #    #    #
#   #   #    ####    ####     #
#
##########################################
## Accessing the RootFile

filedata = TFile('RootFilesXbb/Xbb.root', 'READ')
MPruned_Merged = filedata.Get('mass')
hist_integral = MPruned_Merged.Integral()
print MPruned_Merged.Integral()
mean_vaue = MPruned_Merged.GetMean()
rms_value = MPruned_Merged.GetRMS()
print MPruned_Merged.GetNbinsX()
MPruned_hist = RooDataHist('MPruned_hist', 'MPruned_hist', RooArgList(J_Mass),
                           MPruned_Merged)

##########################################
#
#    #####   ####    #####
#    #    #  #   #   #
#    #    #  #   #   #
#    ####    #   #   #####
#    #       #   #   #
#    #       ####    #
#
###########################################

## signal
mean = RooRealVar('mean', 'mean', 85., 0, 250)
Esempio n. 34
0
def fit_mass(data, column, x, sig_pdf=None, bkg_pdf=None, n_sig=None, n_bkg=None,
             blind=False, nll_profile=False, second_storage=None, log_plot=False,
             pulls=True, sPlot=False,
             bkg_in_region=False, importance=3, plot_importance=3):
    """Fit a given pdf to a variable distribution.

    A quite versatile function doing several things connected to fitting.

    Parameters
    ----------
    data : |hepds_type|
        The data containing the variable to fit to
    column : str
        The name of the column to fit the pdf to
    x : RooRealVar
        The RooRealVar to fit to.
    sig_pdf : RooFit pdf
        The signal Probability Density Function. The variable to fit to has
        to be named 'x'.
    bkg_pdf : RooFit pdf
        The background Probability Density Function. The variable to fit to has
        to be named 'x'.
    n_sig : None or numeric
        The number of signals in the data. If it should be fitted, use None.
    n_bkg : None or numeric
        The number of background events in the data.
        If it should be fitted, use None.
    blind : boolean or tuple(numberic, numberic)
        If False, the data is fitted. If a tuple is provided, the values are
        used as the lower (the first value) and the upper (the second value)
        limit of a blinding region, which will be omitted in plots.
        Additionally, no true number of signal will be returned but only fake.
    nll_profile : boolean
        If True, a Negative Log-Likelihood Profile will be generated. Does not
        work with blind fits.
    second_storage : |hepds_type|
        A second data-storage that will be concatenated with the first one.
    importance : |importance_type|
        |importance_docstring|
    plot_importance : |plot_importance_type|
        |plot_importance_docstring|

    Return
    ------
    tuple(numerical, numerical)
        Return the number of signals and the number of backgrounds in the
        signal-region. If a blind fit is performed, the signal will be a fake
        number. If no number of background events is required, -999 will be
        returned.
    """

    import ROOT
    from ROOT import RooRealVar, RooArgList, RooArgSet, RooAddPdf, RooDataSet, RooAbsReal
    from ROOT import RooFit, RooCBShape, RooExponential
    from ROOT import RooGaussian, RooMinuit
    from ROOT import TCanvas  # HACK to prevent not plotting canvas by root_numpy import. BUG.
    from root_numpy import array2tree
    from ROOT import RooCategory, RooUnblindPrecision

    # Python 2/3 compatibility, str
    column = dev_tool.entries_to_str(column)

    if not (isinstance(column, basestring) or len(column) == 1):
        raise ValueError("Fitting to several columns " + str(column) + " not supported.")
    if type(sig_pdf) == type(bkg_pdf) == None:
        raise ValueError("sig_pdf and bkg_pdf are both None-> no fit possible")
    if blind is not False:
        lower_blind, upper_blind = blind
        blind = True

    n_bkg_below_sig = -999
    # create data
    data_name = data.name
    data_array, _t1, _t2 = data.make_dataset(second_storage, columns=column)
    del _t1, _t2

    # double crystalball variables
    min_x, max_x = min(data_array[column]), max(data_array[column])

    #    x = RooRealVar("x", "x variable", min_x, max_x)

    # create data
    data_array = np.array([i[0] for i in data_array.as_matrix()])
    try:
        data_array.dtype = [('x', np.float64)]
    except:
        data_array.dtype = [('x', np.float64)]
        print("hack needed")
    tree1 = array2tree(data_array, "x")
    data = RooDataSet("data", "Data", RooArgSet(x), RooFit.Import(tree1))

    #    # TODO: export somewhere? does not need to be defined inside...
    #    mean = RooRealVar("mean", "Mean of Double CB PDF", 5280, 5100, 5600)#, 5300, 5500)
    #    sigma = RooRealVar("sigma", "Sigma of Double CB PDF", 40, 0.001, 200)
    #    alpha_0 = RooRealVar("alpha_0", "alpha_0 of one side", 5.715)#, 0, 150)
    #    alpha_1 = RooRealVar("alpha_1", "alpha_1 of other side", -4.019)#, -200, 0.)
    #    lambda_0 = RooRealVar("lambda_0", "Exponent of one side", 3.42)#, 0, 150)
    #    lambda_1 = RooRealVar("lambda_1", "Exponent of other side", 3.7914)#, 0, 500)
    #
    #    # TODO: export somewhere? pdf construction
    #    frac = RooRealVar("frac", "Fraction of crystal ball pdfs", 0.479, 0.01, 0.99)
    #
    #    crystalball1 = RooCBShape("crystallball1", "First CrystalBall PDF", x,
    #                              mean, sigma, alpha_0, lambda_0)
    #    crystalball2 = RooCBShape("crystallball2", "Second CrystalBall PDF", x,
    #                              mean, sigma, alpha_1, lambda_1)
    #    doubleCB = RooAddPdf("doubleCB", "Double CrystalBall PDF",
    #                         crystalball1, crystalball2, frac)

    #    n_sig = RooRealVar("n_sig", "Number of signals events", 10000, 0, 1000000)

    # test input
    if n_sig == n_bkg == 0:
        raise ValueError("n_sig as well as n_bkg is 0...")

    if n_bkg is None:
        n_bkg = RooRealVar("n_bkg", "Number of background events", 10000, 0, 500000)
    elif n_bkg >= 0:
        n_bkg = RooRealVar("n_bkg", "Number of background events", int(n_bkg))
    else:
        raise ValueError("n_bkg is not >= 0 or None")

    if n_sig is None:
        n_sig = RooRealVar("n_sig", "Number of signal events", 1050, 0, 200000)

        # START BLINDING
        blind_cat = RooCategory("blind_cat", "blind state category")
        blind_cat.defineType("unblind", 0)
        blind_cat.defineType("blind", 1)
        if blind:
            blind_cat.setLabel("blind")
            blind_n_sig = RooUnblindPrecision("blind_n_sig", "blind number of signals",
                                              "wasistdas", n_sig.getVal(), 10000, n_sig, blind_cat)
        else:
            #            blind_cat.setLabel("unblind")
            blind_n_sig = n_sig

        print("n_sig value " + str(n_sig.getVal()))

    # END BLINDING

    elif n_sig >= 0:
        n_sig = RooRealVar("n_sig", "Number of signal events", int(n_sig))
    else:
        raise ValueError("n_sig is not >= 0")

    # if not blind:
    #        blind_n_sig = n_sig

    #    # create bkg-pdf
    #    lambda_exp = RooRealVar("lambda_exp", "lambda exp pdf bkg", -0.00025, -1., 1.)
    #    bkg_pdf = RooExponential("bkg_pdf", "Background PDF exp", x, lambda_exp)

    if blind:
        comb_pdf = RooAddPdf("comb_pdf", "Combined DoubleCB and bkg PDF",
                             RooArgList(sig_pdf, bkg_pdf), RooArgList(blind_n_sig, n_bkg))
    else:
        comb_pdf = RooAddPdf("comb_pdf", "Combined DoubleCB and bkg PDF",
                             RooArgList(sig_pdf, bkg_pdf), RooArgList(n_sig, n_bkg))

        # create test dataset
    #    mean_gauss = RooRealVar("mean_gauss", "Mean of Gaussian", 5553, -10000, 10000)
    #    sigma_gauss = RooRealVar("sigma_gauss", "Width of Gaussian", 20, 0.0001, 300)
    #    gauss1 = RooGaussian("gauss1", "Gaussian test dist", x, mean_gauss, sigma_gauss)
    #    lambda_data = RooRealVar("lambda_data", "lambda exp data", -.002)
    #    exp_data = RooExponential("exp_data", "data example exp", x, lambda_data)
    #    frac_data = RooRealVar("frac_data", "Fraction PDF of data", 0.15)
    #
    #    data_pdf = RooAddPdf("data_pdf", "Data PDF", gauss1, exp_data, frac_data)
    #    data = data_pdf.generate(RooArgSet(x), 30000)


    #    data.printValue()
    #    xframe = x.frame()
    #    data_pdf.plotOn(xframe)
    #    print "n_cpu:", meta_cfg.get_n_cpu()
    #    input("test")
    #    comb_pdf.fitTo(data, RooFit.Extended(ROOT.kTRUE), RooFit.NumCPU(meta_cfg.get_n_cpu()))
    #     HACK to get 8 cores in testing
    c5 = TCanvas("c5", "RooFit pdf not fit vs " + data_name)
    c5.cd()
    x_frame1 = x.frame()
    #    data.plotOn(x_frame1)
    #    comb_pdf.pdfList()[1].plotOn(x_frame1)

    if __name__ == "__main__":
        n_cpu = 8
    else:
        n_cpu = meta_cfg.get_n_cpu()
        print("n_cpu = ", n_cpu)
        # HACK
    #        n_cpu = 8
    result_fit = comb_pdf.fitTo(data, RooFit.Minos(ROOT.kTRUE),
                                RooFit.Extended(ROOT.kTRUE),
                                RooFit.NumCPU(n_cpu))
    # HACK end
    if bkg_in_region:
        x.setRange("signal", bkg_in_region[0], bkg_in_region[1])
        bkg_pdf_fitted = comb_pdf.pdfList()[1]
        int_argset = RooArgSet(x)
        #        int_argset = x
        #        int_argset.setRange("signal", bkg_in_region[0], bkg_in_region[1])
        integral = bkg_pdf_fitted.createIntegral(int_argset,
                                                 RooFit.NormSet(int_argset),
                                                 RooFit.Range("signal"))
        bkg_cdf = bkg_pdf_fitted.createCdf(int_argset, RooFit.Range("signal"))
        bkg_cdf.plotOn(x_frame1)

        #        integral.plotOn(x_frame1)
        n_bkg_below_sig = integral.getVal(int_argset) * n_bkg.getVal()
        x_frame1.Draw()

    if plot_importance >= 3:
        c2 = TCanvas("c2", "RooFit pdf fit vs " + data_name)
        c2.cd()
        x_frame = x.frame()
        #        if log_plot:
        #            c2.SetLogy()
        #        x_frame.SetTitle("RooFit pdf vs " + data_name)
        x_frame.SetTitle(data_name)
        if pulls:
            pad_data = ROOT.TPad("pad_data", "Pad with data and fit", 0, 0.33, 1, 1)
            pad_pulls = ROOT.TPad("pad_pulls", "Pad with data and fit", 0, 0, 1, 0.33)
            pad_data.SetBottomMargin(0.00001)
            pad_data.SetBorderMode(0)
            if log_plot:
                pad_data.SetLogy()
            pad_pulls.SetTopMargin(0.00001)
            pad_pulls.SetBottomMargin(0.2)
            pad_pulls.SetBorderMode(0)
            pad_data.Draw()
            pad_pulls.Draw()
            pad_data.cd()
        else:
            if log_plot:
                c2.SetLogy()
    if blind:
        # HACK
        column = 'x'
        # END HACK
        x.setRange("lower", min_x, lower_blind)
        x.setRange("upper", upper_blind, max_x)
        range_str = "lower,upper"
        lower_cut_str = str(min_x) + "<=" + column + "&&" + column + "<=" + str(lower_blind)
        upper_cut_str = str(upper_blind) + "<=" + column + "&&" + column + "<=" + str(max_x)
        sideband_cut_str = "(" + lower_cut_str + ")" + "||" + "(" + upper_cut_str + ")"

        n_entries = data.reduce(sideband_cut_str).numEntries() / data.numEntries()
        #        raw_input("n_entries: " + str(n_entries))
        if plot_importance >= 3:
            data.plotOn(x_frame, RooFit.CutRange(range_str), RooFit.NormRange(range_str))
            comb_pdf.plotOn(x_frame, RooFit.Range(range_str),
                            RooFit.Normalization(n_entries, RooAbsReal.Relative),
                            RooFit.NormRange(range_str))
            if pulls:
                #                pull_hist(pull_frame=x_frame, pad_data=pad_data, pad_pulls=pad_pulls)
                x_frame_pullhist = x_frame.pullHist()
    else:
        if plot_importance >= 3:
            data.plotOn(x_frame)
            comb_pdf.plotOn(x_frame)
            if pulls:
                pad_pulls.cd()
                x_frame_pullhist = x_frame.pullHist()
                pad_data.cd()

            comb_pdf.plotOn(x_frame,
                            RooFit.Components(sig_pdf.namePtr().GetName()),
                            RooFit.LineStyle(ROOT.kDashed))
            comb_pdf.plotOn(x_frame,
                            RooFit.Components(bkg_pdf.namePtr().GetName()),
                            RooFit.LineStyle(ROOT.kDotted))
            #            comb_pdf.plotPull(n_sig)

    if plot_importance >= 3:
        x_frame.Draw()

        if pulls:
            pad_pulls.cd()
            x_frame.SetTitleSize(0.05, 'Y')
            x_frame.SetTitleOffset(0.7, 'Y')
            x_frame.SetLabelSize(0.04, 'Y')

            #            c11 = TCanvas("c11", "RooFit\ pulls" + data_name)
            #            c11.cd()
            #            frame_tmp = x_frame
            frame_tmp = x.frame()

            #            frame_tmp.SetTitle("significance")

            frame_tmp.SetTitle(r"Roofit\ pulls\ " + data_name)
            frame_tmp.addObject(x_frame_pullhist)

            frame_tmp.SetMinimum(-5)
            frame_tmp.SetMaximum(5)

            #            frame_tmp.GetYaxis().SetTitle("significance")
            frame_tmp.GetYaxis().SetNdivisions(5)
            frame_tmp.SetTitleSize(0.1, 'X')
            frame_tmp.SetTitleOffset(1, 'X')
            frame_tmp.SetLabelSize(0.1, 'X')
            frame_tmp.SetTitleSize(0.1, 'Y')
            frame_tmp.SetTitleOffset(0.5, 'Y')
            frame_tmp.SetLabelSize(0.1, 'Y')

            frame_tmp.Draw()


            #    raw_input("")

    if not blind and nll_profile:

        #        nll_range = RooRealVar("nll_range", "Signal for nLL", n_sig.getVal(),
        #                               -10, 2 * n_sig.getVal())
        sframe = n_sig.frame(RooFit.Bins(20), RooFit.Range(1, 1000))
        # HACK for best n_cpu
        lnL = comb_pdf.createNLL(data, RooFit.NumCPU(8))
        # HACK end
        lnProfileL = lnL.createProfile(ROOT.RooArgSet(n_sig))
        lnProfileL.plotOn(sframe, RooFit.ShiftToZero())
        c4 = TCanvas("c4", "NLL Profile")
        c4.cd()

        #        input("press ENTER to show plot")
        sframe.Draw()

    if plot_importance >= 3:
        pass

    params = comb_pdf.getVariables()
    params.Print("v")

    #    print bkg_cdf.getVal()

    if sPlot:
        sPlotData = ROOT.RooStats.SPlot("sPlotData", "sPlotData",
                                        data,  # variable fitted to, RooDataSet
                                        comb_pdf,  # fitted pdf
                                        ROOT.RooArgList(n_sig,
                                                        n_bkg,
                                                        #                                                NSigB0s
                                                        ))
        sweights = np.array([sPlotData.GetSWeight(i, 'n_sig') for i in range(data.numEntries())])
        return n_sig.getVal(), n_bkg_below_sig, sweights

    if blind:
        return blind_n_sig.getVal(), n_bkg_below_sig, comb_pdf
    else:
        return n_sig.getVal(), n_bkg_below_sig, comb_pdf
        label = 'Run2016Data_pLbL0'
        fitLabel = 'lbl0Dist_lbl0MC'
        space.factory('x0[-5.498]')
        space.factory('Addition::X({{ {x},x0 }})'.format(x='lbl0Mass'))
        space.factory(
            'Polynomial::pPDF_%s(X,{c1_%s[0.01,-2.,2.],c2_%s[0.01,-3.,3.0],c3_%s[0.01,-1.,3.]})'
            % (label, label, label, label))
        #space.factory('Polynomial::pPDF_%s(lbl0Mass,{c1_%s[0.01,-5.,5.]})' % (label,label) )

        # set resolution issue: Convolute a gaussian.
        space.factory('numCombBkg_{0}[{1},0.,{2}]'.format(
            label, totNum, totNum))
        myPDF = RooAddPdf(
            'totPdf_{0}'.format(label), 'totPdf_{0}'.format(label),
            RooArgList(space.pdf('pPDF_{0}'.format(label)),
                       space.pdf('gPDF_lbl0Dist_lbl0MC')),
            RooArgList(space.var('numCombBkg_{0}'.format(label)),
                       space.var('numLb')), False)
        getattr(space, 'import')(myPDF)

        constrSet = RooArgSet()
        for constredName in constredNames['pLbL0']:
            constrSet.add(space.pdf(constredName))

        fitres = myPDF.fitTo(binData, RooFit.Range('sigShortRange'),
                             RooFit.Save(), RooFit.Minos(True),
                             RooFit.ExternalConstraints(constrSet))
        #fitres=myPDF.fitTo(binData,RooFit.Range('sigShortRange'),RooFit.Save(),RooFit.Minos(True))

        plotframe = massLb.frame(RooFit.Title(label),
                                 RooFit.Range('sigShortRange'))
Esempio n. 36
0
wspace . factory("SUM::model_pdf(s[0,15]*model_pdf_1,b[1,0,2]*model_pdf_2)")
wspace . factory("Lognormal::likelihood_b(b,1,3)")
wspace . factory("PROD::model_likelihood(model_pdf, likelihood_b)")
wspace . factory("Uniform::prior_pdf(s)")
  
# define observables
wspace . defineSet("observables","x")

# define parameters of interest
wspace . defineSet("poi","s")

# define nuisance parameters
wspace . defineSet("nuisance_parameters","b")

# load data
observables = RooArgList( wspace.set("observables") )
data = RooDataSet.read("counting_data_3.ascii", observables)
data . SetName("data")
getattr(wspace, 'import')(data)

# model config
modelConfig = RooStats.ModelConfig("counting_model_config")
modelConfig . SetWorkspace(wspace)
modelConfig . SetPdf(wspace.pdf("model_likelihood"))
modelConfig . SetPriorPdf(wspace.pdf("prior_pdf"))
modelConfig . SetParametersOfInterest(wspace.set("poi"))
modelConfig . SetNuisanceParameters(wspace.set("nuisance_parameters"))
getattr(wspace, 'import')(modelConfig, "counting_model_config")

# Bayesian Calculator
bc = RooStats.BayesianCalculator(data, modelConfig)
Esempio n. 37
0
def getFrame(cat, obsData, simPdf, mc, fit_res, error_band_strategy=1, compute_yields=False):
    """
    Build a frame with the different fit components and their uncertainties

    Parameters
    ----------
    cat    : RooCategory
        Category of the simultaneous PDF we are interested in
    obsData: RooDataHist object (either real data or asimov or PE)
    simPdf : RooSimultaneous PDF
    mc : ModelConfig object
    fit_res: RooFitResult
        Result of the fit (covariance matrix, NLL value, ...)
    error_band_strategy : True/False
        True: Use the linear approximation to extract the error band
        False: Use a sampling method
        See http://root.cern.ch/root/html/RooAbsReal.html#RooAbsReal:plotOnWithErrorBand
    verbose: True/False

    TODO: implement a more generic way to retrieve the binning.
    Currently it has to be put in the workspace with the name binWidth_obs_x_{channel}_0
    """

    hlist = []
    if compute_yields:
        yields = {}
    # --> Get the total (signal+bkg) model pdf
    pdftmp = simPdf.getPdf(cat.GetName())
    if not pdftmp:
        raise RuntimeError('Could not retrieve the total pdf ')
    # --> Get the list of observables
    obstmp  = pdftmp.getObservables(mc.GetObservables())
    if not obstmp:
        raise RuntimeError('Could not retrieve the list of observable')
    # --> Get the first (and only) observable (mmc mass for cut based)
    obs  = obstmp.first()
    log.info('Observable: {0}'.format(obs.GetName()))
    # --> Get the RooDataHist of the given category
    datatmp = obsData.reduce("{0}=={1}::{2}".format(simPdf.indexCat().GetName(), simPdf.indexCat().GetName(), cat.GetName()))
    datatmp.__class__=ROOT.RooAbsData # --> Ugly fix !!!
    # --> Get the binning width of the category (stored as a workspace variable)
    binWidth = pdftmp.getVariables().find('binWidth_obs_x_{0}_0'.format(cat.GetName()))
    if not binWidth:
        raise RuntimeError('Could not retrieve the binWidth')
    # --> parameter of interest (mu=sigma/sigma_sm)
    poi =  mc.GetParametersOfInterest().first()
    poi_fitted_val = poi.getVal()
    log.info('POI: {0} = {1} +/- {2}'.format(poi.GetName(), poi.getVal(), poi.getError()))
            
    # --> Create the data histogram
    hist_data = asrootpy(datatmp.createHistogram("hdata_"+cat.GetName(), obs))
    hist_data.name = "hdata_{0}".format(cat.GetName())
    hist_data.title = ""
    hlist.append(hist_data)
    #--> compute the data yields
    if compute_yields:
        Yield_data = hist_data.Integral()
        yields['Data'] = (Yield_data, 0)

    # --> Create the frame structure from the observable
    frame = obs.frame()
    frame.SetName(cat.GetName())
    datatmp.plotOn(frame,
                   ROOT.RooFit.DataError(ROOT.RooAbsData.Poisson),
                   ROOT.RooFit.Name("Data"),
                   ROOT.RooFit.MarkerSize(1))

    # --> Create the signal histogram template
    hist_sig = hist_data.Clone('h_TotalSignal_{0}'.format(cat.GetName()))
    hist_sig.Reset()
    signal_comps = RooArgList()
    bkg_comps = RooArgList()
    # --> get the list of components (hadhad HSG4: QCD,Other,Ztautau, Signal_Z, Signal_W, Signal_gg, Signal_VBF)
    # --> and iterate over 
    pdfmodel = pdftmp.getComponents().find(cat.GetName()+'_model')
    funcListIter = pdfmodel.funcList().iterator()
    while True:
        comp = funcListIter.Next()
        if not comp:
            break

        name = comp.GetName().replace('L_x_', '').split('_')[0]
        log.info('Scan component {0}'.format(comp.GetName()))
        hist_comp = asrootpy(comp.createHistogram(cat.GetName()+"_"+comp.GetName(), obs, ROOT.RooFit.Extended(False)))
        hist_comp.name = 'h_{0}_{1}'.format(name, cat.GetName())
        hist_comp.title = ''
        hlist.append(hist_comp)

        if 'Signal' in comp.GetName():
            signal_comps.add(comp)
            hist_sig.Add(hist_comp)
        else:
            bkg_comps.add(comp)
        Integral_comp = comp.createIntegral(RooArgSet(obs))
        Yield_comp = Integral_comp.getVal() * binWidth.getVal()
        log.info('Integral = {0}'.format(Yield_comp))
        #         if Yield_comp==0:
        #             raise RuntimeError('Yield integral is wrong !!')


        # --> Add the components to the frame but in an invisible way
        pdfmodel.plotOn(frame,
                        ROOT.RooFit.Components(comp.GetName()),
                        ROOT.RooFit.Normalization(Yield_comp, ROOT.RooAbsReal.NumEvent),
                        ROOT.RooFit.Name("NoStacked_"+comp.GetName()),
                        ROOT.RooFit.Invisible())
        if fit_res:
            # --> Add the components uncertainty band 
            comp.plotOn(frame,
                        ROOT.RooFit.Normalization(1, ROOT.RooAbsReal.RelativeExpected),
                        ROOT.RooFit.VisualizeError(fit_res, 1, error_band_strategy),
                        ROOT.RooFit.Name("FitError_AfterFit_"+comp.GetName()),
                        ROOT.RooFit.Invisible())
            if compute_yields:
                if Yield_comp==0:
                    Yield_comp_err=0.
                else:
                    Yield_comp_err = Integral_comp.getPropagatedError(fit_res)* binWidth.getVal()
                yields[comp.GetName()] = (Yield_comp, Yield_comp_err)

    hlist.append(hist_sig)
    # --> total signal yields
    if compute_yields:
        signal_tot_comp = RooAddition('pdf_sum_sig', 'pdf_sum_sig', signal_comps)
        Integral_signal = signal_tot_comp.createIntegral(RooArgSet(obs))
        yields_sig_tot = Integral_signal.getVal()*binWidth.getVal()
        yields_sig_tot_err = Integral_signal.getPropagatedError(fit_res)* binWidth.getVal()
        yields['TotalSignal'] = (yields_sig_tot, yields_sig_tot_err)
        bkg_tot_comp = RooAddition('pdf_sum_bkg', 'pdf_sum_bkg', bkg_comps)
        Integral_bkg = bkg_tot_comp.createIntegral(RooArgSet(obs))
        yields_bkg_tot = Integral_bkg.getVal()*binWidth.getVal()
        yields_bkg_tot_err = Integral_bkg.getPropagatedError(fit_res)* binWidth.getVal()
        yields['bkg'] = (yields_bkg_tot, yields_bkg_tot_err)
        log.info('Bkg Total Yield: {0}'.format(yields_bkg_tot))

    # --> bkg+signal PDF central value and error
    Integral_total = pdfmodel.createIntegral(RooArgSet(obs))
    Yield_total = Integral_total.getVal() * binWidth.getVal()
    log.info('Postfit Total Yield: {0}'.format(Yield_total))
    hist_bkg_plus_sig = asrootpy(pdfmodel.createHistogram("hbkg_plus_sig_"+cat.GetName(), obs, ROOT.RooFit.Extended(False)))
    hist_bkg_plus_sig.name = 'hbkg_plus_sig_'+cat.GetName()
    hist_bkg_plus_sig.title = ''
    hist_bkg_plus_sig.Scale(Yield_total)
    hlist.append(hist_bkg_plus_sig)

    # --> Add the components to the frame but in an invisible way
    pdftmp.plotOn(frame,
                   ROOT.RooFit.Normalization(Yield_total, ROOT.RooAbsReal.NumEvent),
                   ROOT.RooFit.Name("Bkg_plus_sig"))

    if fit_res:
        pdftmp.plotOn(frame,
                      ROOT.RooFit.VisualizeError(fit_res, 1, error_band_strategy),
                      ROOT.RooFit.Normalization(1, ROOT.RooAbsReal.RelativeExpected),
                      ROOT.RooFit.Name("FitError_AfterFit"),
                      ROOT.RooFit.FillColor(ROOT.kOrange),
                      ROOT.RooFit.LineWidth(2),
                      ROOT.RooFit.LineColor(ROOT.kBlue))

    # --> bkg only PDF central value and error
    poi.setVal(0.)
    Integral_bkg_total = pdfmodel.createIntegral(RooArgSet(obs))
    Yield_bkg_total = Integral_bkg_total.getVal() * binWidth.getVal()

    hist_bkg = pdfmodel.createHistogram("hbkg_"+cat.GetName(), obs, ROOT.RooFit.Extended(False))
    hist_bkg.Scale(Yield_bkg_total)
    hist_bkg.SetName("hbkg_"+cat.GetName())
    hist_bkg.SetTitle("")
    hlist.append(hist_bkg)
    pdftmp.plotOn(frame,
                  ROOT.RooFit.Normalization(Yield_bkg_total, ROOT.RooAbsReal.NumEvent),
                  ROOT.RooFit.Name("Bkg"),
                  ROOT.RooFit.LineStyle(ROOT.kDashed))
    if fit_res:
        pdftmp.plotOn(frame,
                      ROOT.RooFit.VisualizeError(fit_res, 1, error_band_strategy),
                      ROOT.RooFit.Normalization(1, ROOT.RooAbsReal.RelativeExpected),
                      ROOT.RooFit.Name("FitError_AfterFit_Mu0"),
                      ROOT.RooFit.FillColor(ROOT.kOrange),
                      ROOT.RooFit.LineWidth(2),
                      ROOT.RooFit.LineColor(ROOT.kBlue))
        #if compute_yields:
            # Yield_bkg_total_err = Integral_bkg_total.getPropagatedError(fit_res)*binWidth.getVal()
            # yields['bkg'] = (Yield_bkg_total, Yield_bkg_total_err)

    poi.setVal(poi_fitted_val)
    if compute_yields:
        return frame, hlist, yields
    else:
        return frame, hlist
Esempio n. 38
0
def plot_rel_pt_diff(rel_diff_regressed,rel_diff,style=False,n_bins=50,outString=None,option='caterina'):  

    if style==True:
        gROOT.SetBatch(True)
        gROOT.ProcessLineSync(".x /mnt/t3nfs01/data01/shome/nchernya/HHbbgg_ETH_devel/scripts/setTDRStyle.C")
        gROOT.ForceStyle()
        gStyle.SetPadTopMargin(0.06)
        gStyle.SetPadRightMargin(0.04)
        gStyle.SetPadLeftMargin(0.15)
    
    
   #### rel_diff_regressed = (predictions - true)/true
   #### rel_diff = (recoPt - true)/true
#    rel_diff_regressed = true/predictions
 #   rel_diff = true/recoPt
    
    c_min = min(min(rel_diff_regressed),min(rel_diff))
    c_max = max(max(rel_diff_regressed),max(rel_diff))
    c_min=0
    c_max=2.
    
    Histo_rel_diff = np.histogram(rel_diff,bins=n_bins,range=(c_min,c_max))
    Histo_rel_diff_reg = np.histogram(rel_diff_regressed,bins=n_bins,range=(c_min,c_max))
    
    h_rel_diff = TH1F("hrel_diff", "hrel_diff", n_bins, c_min, c_max)
    for i in range(len(rel_diff)): 
        h_rel_diff.Fill(rel_diff[i])
    h_rel_diff_reg = TH1F("hrel_diff_reg", "hrel_diff_reg", n_bins, c_min, c_max)
    for i in range(len(rel_diff_regressed)): 
        h_rel_diff_reg.Fill(rel_diff_regressed[i])
    h_rel_diff.SetLineColor(ROOT.kBlue)
    h_rel_diff.SetMarkerColor(ROOT.kBlue)
    h_rel_diff.SetLineWidth(2)
    h_rel_diff_reg.SetLineColor(ROOT.kRed)
    h_rel_diff_reg.SetMarkerColor(ROOT.kRed)
    h_rel_diff_reg.SetLineWidth(2)
   

    
    AllHistos= [Histo_rel_diff, Histo_rel_diff_reg]
    h_max = max([histo[0].max() for histo in AllHistos])*1.2
    h_min = min([histo[0].min() for histo in AllHistos])
    
    c = ROOT.TCanvas("c","c",900,900)
    c.cd()
    frame = TH1F("hframe", "hframe", n_bins, c_min, c_max)
    frame.SetStats(0)
    frame.GetXaxis().SetTitleOffset(0.91);
    frame.GetYaxis().SetTitle("Events")
  #  frame.GetXaxis().SetTitle("(p_{T}^{Reco}-p_{T}^{gen})/p_{T}^{gen}")
    frame.GetXaxis().SetTitle("p_{T}^{gen}/p_{T}^{reco}")
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetRangeUser(h_min,h_max)
    
    frame.Draw()
    h_rel_diff.Draw("samePE")
    h_rel_diff_reg.Draw("samePE")
    print('Nominal : mean, RMS :',h_rel_diff.GetMean(), h_rel_diff.GetRMS())
    print('Regresesd : mean, RMS : ',h_rel_diff_reg.GetMean(), h_rel_diff_reg.GetRMS())

  

    
    
    
    leg = ROOT.TLegend(0.55,0.75,0.9,0.9)
    leg.SetFillStyle(-1)
    leg.SetBorderSize(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.03)
  #  leg.Draw()
    

    h_names = ['nom','reg']
    datahists = [h_rel_diff,h_rel_diff_reg]
    x=[]
    datahist=[]
    m=[]
    m_initial=[1.0103e+00,9.5381e-01]
    s=[]
    s_initial=[ 1.3210e-01,1.3967e-01]
    a=[]
    a_initial=[-7.7802e-01,-1.1260e+00]
    n=[]
    n_initial=[ 6.0149e+00,5.5622e+00]
    
    Ap,Xp,sigp,xi,rho1,rho2 = [],[],[],[],[],[]
    Xp_initial,sigp_initial,xi_initial,rho1_initial,rho2_initial =  9.8545e-01, 1.3118e-01,2.2695e-01, 6.4189e-02,  9.0282e-02 
    meanr, sigmaL, sigmaR, alphaL, alphaR = [],[],[],[],[]   
 
    fsig=[]
    sig=[]
    model=[]
    res=[]
    integral=[]
    formula=[]
    scale_factors=[]
    scaled_cb=[]
    func=[]
    colors=[ROOT.kBlue,ROOT.kRed]
    chi_squares=[]
    fwhm_bukin=[]
    fwhm=[]
    fwhm.append( -1 *(h_rel_diff.GetBinCenter( h_rel_diff.FindFirstBinAbove(h_rel_diff.GetMaximum()/2.)  )  - h_rel_diff.GetBinCenter( h_rel_diff.FindLastBinAbove(h_rel_diff.GetMaximum()/2.) ) )  )
    fwhm.append( -1 *(h_rel_diff_reg.GetBinCenter( h_rel_diff_reg.FindFirstBinAbove(h_rel_diff_reg.GetMaximum()/2.)  )  - h_rel_diff_reg.GetBinCenter( h_rel_diff_reg.FindLastBinAbove(h_rel_diff_reg.GetMaximum()/2.) ) )  )

    for num,h in enumerate(h_names):
        x.append(RooRealVar("x_%s"%h,"x_%s"%h,c_min,c_max))
        datahist.append(RooDataHist("roohist_%s"%h,"roohist_%s"%h,RooArgList(x[num]),datahists[num]))
       #######################Crystal ball################ 
        m.append(RooRealVar("mean_%s"%h,"mean_%s"%h,m_initial[num],0.5,1.5))
        s.append(RooRealVar("sigma_%s"%h,"sigma_%s"%h,s_initial[num],0.01,0.3))
        a.append(RooRealVar("alpha_%s"%h,"alpha_%s"%h,a_initial[num],-10,0.))
        n.append(RooRealVar("exp_%s"%h,"exp_%s"%h,n_initial[num],1.,100.))
      #  sig.append(RooCBShape("signal_gauss_%s"%h,"signal_gauss_%s"%h,x[num],m[num],s[num],a[num],n[num]))

      #######################Bukin function ################## 
    
        Xp.append(RooRealVar("Xp_%s"%h,"Xp_%s"%h,Xp_initial,0.,3.))
        sigp.append(RooRealVar("sigp_%s"%h,"sigp_%s"%h,sigp_initial,0.01,0.3))
        xi.append(RooRealVar("xi_%s"%h,"xi_%s"%h,xi_initial,-1,1))
        rho1.append(RooRealVar("rho1_%s"%h,"rho1_%s"%h,rho1_initial,-1,1)) #left
        rho2.append(RooRealVar("rho2_%s"%h,"rho2_%s"%h,rho2_initial,-1,1)) #right
        sig.append(RooBukinPdf("signal_bukin_%s"%h,"signal_bukin_%s"%h,x[num],Xp[num],sigp[num],xi[num],rho1[num],rho2[num]))

###########################RooCruijff##################

        meanr.append(RooRealVar("meanr_%s"%h,"meanr_%s"%h,m_initial[num],0.5,1.5))
        sigmaL.append(RooRealVar("sigmaL_%s"%h,"sigmaL_%s"%h,s_initial[num],0.01,0.3))
        sigmaR.append(RooRealVar("sigmaR_%s"%h,"sigmaR_%s"%h,s_initial[num],0.01,0.3))
        alphaL.append(RooRealVar("alphaL_%s"%h,"alphaL_%s"%h,0.01,0,2.))
        alphaR.append(RooRealVar("alphaR_%s"%h,"alphaR_%s"%h,0.1,0.,2.))
#  RooGenericPdf genpdf("genpdf","genpdf","(1+0.1*abs(x)+sin(sqrt(abs(x*alpha+0.1))))",RooArgSet(x,alpha)) ;
        formula_rooCruijff = "( ( (x_%s-meanr_%s)<0) ? (exp( -1*pow((x_%s-meanr_%s),2)/(2*pow(sigmaL_%s,2)+alphaL_%s*pow((x_%s-meanr_%s),2) ))) : (exp( -1*pow((x_%s-meanr_%s),2)/(2*pow(sigmaR_%s,2)+alphaR_%s*pow((x_%s-meanr_%s),2) )))  )"%(h,h,h,h,h,h,h,h,h,h,h,h,h,h) 
    #    sig.append(RooGenericPdf("signal_cruijff_%s"%h,"signal_cruijjff_%s"%h,formula_rooCruijff,RooArgList(x[num],meanr[num],sigmaL[num],sigmaR[num],alphaL[num],alphaR[num])))
    #    sig.append(RooBifurGauss("signal_cruijff_%s"%h,"signal_cruijjff_%s"%h,x[num],meanr[num],sigmaL[num],sigmaR[num]))

     #   fit_range_min = h_rel_diff.GetMean()-fwhm[num]
     #   fit_range_max = h_rel_diff.GetMean()+fwhm[num]
     #   print 'range of the fit : ', fit_range_min, fit_range_max
     #   res.append(sig[num].fitTo(datahist[num],ROOT.RooFit.Save(ROOT.kTRUE),ROOT.RooFit.Range(fit_range_min,fit_range_max))) # take Mean of each histogram and add 1/2 of the RMS  ? -> try that

        res.append(sig[num].fitTo(datahist[num],ROOT.RooFit.Save(ROOT.kTRUE)))
        res[num].Print()

       # chi_squares.append((x[num].frame()).chiSquare())
        x[num].setRange("integralRange%s"%h, c_min,c_max)  
        integral.append(sig[num].createIntegral(RooArgSet(x[num]), ROOT.RooFit.Range("integralRange%s"%h)))

        scale_factors.append(datahists[num].Integral()*datahists[num].GetBinWidth(1)/integral[num].getVal())
        scale_factors.append(datahists[num].Integral()*datahists[num].GetBinWidth(1)/integral[num].getVal())
      #  formula.append("%f *signal_gauss_%s"%(scale_factors[num],h))
        formula.append("%f *signal_bukin_%s"%(scale_factors[num],h))
     #   formula.append("%f *signal_cruijff_%s"%(scale_factors[num],h))
       # create a scaled  function = scale * function
        scaled_cb.append(RooFormulaVar("scaled_cb_%s"%h,formula[num],RooArgList(sig[num])))
        func.append(scaled_cb[num].asTF(RooArgList(x[num])))
        func[num].SetLineColor(colors[num])
        datahists[num].SetMarkerColor(colors[num])
        fwhm_bukin.append(sigp[num].getVal()*2*math.sqrt(2*math.log(2)))
      
      #  chi_squares.append(RooChi2Var("chi2_%s"%h,"chi2_%s"%h,sig[num],datahist[num]))

    
    fitfunc='Bukin'
  #  fitfunc='Bifurgaus'
    fit_result_file = std.ofstream(utils.IO.plotFolder+"../fitResults/fitResult_%s"%(fitfunc)+str(outString)+'.txt')
    res[0].floatParsFinal().printMultiline(fit_result_file, 1111, True)
    res[1].floatParsFinal().printMultiline(fit_result_file, 1111, True)
    fit_result_file.close()

    
    if option=='caterina' :
        leg.AddEntry(h_rel_diff,"HIG-16-044, FWHM=%.3f"%fwhm[0] ,"P")
        leg.AddEntry(h_rel_diff,"FWHM Bukin =%.3f"%fwhm_bukin[0] ,"P")
        leg.AddEntry(h_rel_diff_reg,"XGboost, FWHM=%.3f"%fwhm[1],"P")
        leg.AddEntry(h_rel_diff_reg,"FWHM Bukin =%.3f"%fwhm_bukin[1],"P")
    else : 
        leg.AddEntry(h_rel_diff,"Nominal" ,"P")
        leg.AddEntry(h_rel_diff_reg,"Regressed" ,"P")

	
    c2 = ROOT.TCanvas("c2","c2",900,900)
    c2.cd()
    frame.Draw()
    func[0].Draw("same")
    func[1].Draw("same")
    h_rel_diff.Draw("PEHISTsame")
    h_rel_diff_reg.Draw("PEHISTsame")    
    leg.Draw()
  
   # c2.SaveAs(utils.IO.plotFolder+"pt_rel_fitCruijff_"+str(outString)+'.png')
  #  c2.SaveAs(utils.IO.plotFolder+"pt_rel_noFit_"+str(outString)+'.png')
    c2.SaveAs(utils.IO.plotFolder+"pt_rel_fit%s_"%(fitfunc)+str(outString)+'.png')
    c2.SaveAs(utils.IO.plotFolder+"pt_rel_fit%s_"%(fitfunc)+str(outString)+'.pdf')
    c2.Draw()
Esempio n. 39
0
def plotFitModel(model, frame, wksp, myconfigfile, log, debug) :
    if debug :
        model.Print('t')
        frame.Print('v')

    fr = model.plotOn(frame,
                      RooFit.LineColor(kBlue+3),RooFit.Name("FullPdf"))

    if "Acceptance" in myconfigfile.keys():
        var = []
        tacc_list = RooArgList()
        numKnots = myconfigfile["Acceptance"]["knots"].__len__()
        for i in range(0,numKnots+1):
            varName = "var%d"%(int(i+1))
            var.append(wksp.var(varName))
            print "[INFO] Load %s with value %0.3lf"%(var[i].GetName(),var[i].getValV())
            tacc_list.add(var[i])

        varAdd = RooAddition(wksp.obj("var%d"%(numKnots+2)))
        print "[INFO] Load %s with value %0.3lf"%(varAdd.GetName(),varAdd.getValV())
        tacc_list.add(varAdd)

    elif "ResolutionAcceptance" in myconfigfile.keys():
        #Create acceptance
        var = []
        tacc_list = RooArgList()
        numKnots = myconfigfile["ResolutionAcceptance"]["Signal"]["Acceptance"]["KnotPositions"].__len__()
        print "[INFO] Number of knots: "+str(numKnots)
        for i in range(0,numKnots+1):
            if i!=6:
                varName = "Acceptance_SplineAccCoeff%d"%(int(i))
                var.append(wksp.obj(varName))
                print "[INFO] Load %s with value %0.3lf"%(var[i].GetName(),var[i].getValV())
            else:
                var.append( RooConstVar("one","one",1.0) )
                print "[INFO] Load one as coefficient no. 6"
                            
            tacc_list.add(var[i])

        varName = "Acceptance_SplineAccCoeff%d"%(int(numKnots+1))
        var.append(wksp.obj(varName))
        print "[INFO] Load %s with value %0.3lf"%(var[numKnots+1].GetName(),var[numKnots+1].getValV())
        tacc_list.add(var[numKnots+1])

        #Create binning
        binning = RooBinning(time.getMin(), time.getMax(), 'splineBinning')
        for kn in myconfigfile["ResolutionAcceptance"]["Signal"]["Acceptance"]["KnotPositions"]:
            binning.addBoundary(kn)
        binning.removeBoundary(time.getMin())
        binning.removeBoundary(time.getMax())
        binning.removeBoundary(time.getMin())
        binning.removeBoundary(time.getMax())
        oldBinning, lo, hi = time.getBinning(), time.getMin(), time.getMax()
        time.setBinning(binning, 'splineBinning')
        time.setBinning(oldBinning)
        time.setRange(lo, hi)

    spl = RooCubicSplineFun("splinePdf", "splinePdf", time, "splineBinning", tacc_list)
    if log:
        rel = 200
    else:
        #rel = 1000
        rel = 2000
        
    fr = spl.plotOn(frame, RooFit.LineColor(kRed),  RooFit.Normalization(rel, RooAbsReal.Relative),RooFit.Name("sPline"))
    fr = model.plotOn(frame,
                          RooFit.LineColor(kBlue+3), RooFit.Name("FullPdf"))
Esempio n. 40
0
def plot_regions(X_region,names,style=True,n_bins=50,outString=None,log=False,title='',titleName=''):  
    if style==True:
        gROOT.SetBatch(True)
        gROOT.ProcessLineSync(".x ~/HHbbgg_ETH/scripts/setTDRStyle.C")
        gROOT.ForceStyle()
        gStyle.SetPadTopMargin(0.06)
        gStyle.SetPadRightMargin(0.04)
        gStyle.SetPadLeftMargin(0.15)
    

    h_names = [ 'region'+str(t) for t in range(0,len(X_region))]

    c_min=0
    c_max=2.
    if log : c_max=4.
    c = TCanvas("canv","canv",900,900)
    c.cd()
    frame = TH1F("hframe", "hframe", n_bins, c_min, c_max)
    frame.SetStats(0)
    frame.GetXaxis().SetTitleOffset(0.91);
    frame.GetYaxis().SetTitle("Events")
    frame.GetXaxis().SetTitle("p_{T}^{gen}/p_{T}^{reco}")
    frame.GetYaxis().SetLabelSize(0.04)
    leg = ROOT.TLegend(0.12,0.75,0.6,0.9)
    leg.SetFillStyle(-1)
    leg.SetBorderSize(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.025)
    if titleName!='' :  leg.AddEntry(frame,titleName,"")
    if title!='' :  leg.AddEntry(frame,title,"")

    hist_list=[]
    func_list=[]
    max_list=[]
    x=[]
    datahist=[]
    datahists=[]
    meanr, sigmaL, sigmaR, alphaL, alphaR = [],[],[],[],[]   
    Ap,Xp,sigp,xi,rho1,rho2 = [],[],[],[],[],[]
    meanv, widthv, sigmav = [] , [] , []
    Xp_initial,sigp_initial,xi_initial,rho1_initial,rho2_initial =  9.8545e-01, 1.3118e-01,2.2695e-01, 6.4189e-02,  9.0282e-02 
    fsig=[]
    sig=[]
    model=[]
    res=[]
    integral=[]
    formula=[]
    scale_factors=[]
    scaled=[]
    func=[]
    colors=[ROOT.kBlue+1,ROOT.kAzure+5,ROOT.kCyan-1, ROOT.kGreen, ROOT.kSpring+8, ROOT.kOrange, ROOT.kPink+10]
 
 
    for j in range(len(X_region)):
        if isinstance(X_region[j], np.ndarray) : data = X_region[j]
        else : data =((X_region[j]).as_matrix()).ravel()
      #  print len(data)
        h_rel_diff = TH1F("hrel_diff_%s"%h_names[j], "hrel_diff_%s"%h_names[j], n_bins, c_min, c_max)
        h_rel_diff.Sumw2(ROOT.kTRUE)
        for i in range(len(data)): 
            h_rel_diff.Fill(data[i])
  #      h_rel_diff.Scale(1./h_rel_diff.Integral())
        h_rel_diff.SetLineColor(colors[j])
        h_rel_diff.SetMarkerColor(colors[j])
        h_rel_diff.SetLineWidth(2)
        h_rel_diff.SetLineStyle(1+j)
    
    #    if (log==True) : max_list.append(h_rel_diff.GetMaximum()*1.3)
        max_list.append(h_rel_diff.GetMaximum()*1.4)
        datahists.append(h_rel_diff)


        num=j
        h = h_names[j]
        x.append(RooRealVar("x_%s"%h,"x_%s"%h,c_min,c_max))
        datahist.append(RooDataHist("roohist_%s"%h,"roohist_%s"%h,RooArgList(x[num]),datahists[num]))
        #######################Bukin function ################## 
        if ('mse' in names[j]) or ('HybridLoss' in names[j])  : Xp.append(RooRealVar("Xp_%s"%h,"Xp_%s"%h,0.96,0.7,1.1))
        else : Xp.append(RooRealVar("Xp_%s"%h,"Xp_%s"%h,Xp_initial,0.,3.))
        if ('unweighted' in names[j]) and ('Jet_mcPt>=300' in outString)  : sigp.append(RooRealVar("sigp_%s"%h,"sigp_%s"%h,0.06,0.01,0.2))
        elif ('No regression' in names[j]) and ('Jet_mcPt>=600' in outString)  : sigp.append(RooRealVar("sigp_%s"%h,"sigp_%s"%h,0.06,0.01,0.2))
        elif ('mse' in names[j]) or ('HybridLoss' in names[j])  : sigp.append(RooRealVar("sigp_%s"%h,"sigp_%s"%h,0.06,0.01,0.15))
        else  : sigp.append(RooRealVar("sigp_%s"%h,"sigp_%s"%h,sigp_initial,0.01,0.3))
        xi.append(RooRealVar("xi_%s"%h,"xi_%s"%h,xi_initial,-1,1))
        rho1.append(RooRealVar("rho1_%s"%h,"rho1_%s"%h,rho1_initial,-1,1)) #left
        rho2.append(RooRealVar("rho2_%s"%h,"rho2_%s"%h,rho2_initial,-1,1)) #right
        sig.append(RooBukinPdf("signal_bukin_%s"%h,"signal_bukin_%s"%h,x[num],Xp[num],sigp[num],xi[num],rho1[num],rho2[num]))
###########################RooCruijff##################
        meanr.append(RooRealVar("meanr_%s"%h,"meanr_%s"%h,Xp_initial,0.5,1.5))
        sigmaL.append(RooRealVar("sigmaL_%s"%h,"sigmaL_%s"%h,sigp_initial,0.01,0.3))
        sigmaR.append(RooRealVar("sigmaR_%s"%h,"sigmaR_%s"%h,sigp_initial,0.01,0.3))
        alphaL.append(RooRealVar("alphaL_%s"%h,"alphaL_%s"%h,0.01,0,2.))
        alphaR.append(RooRealVar("alphaR_%s"%h,"alphaR_%s"%h,0.1,0.,2.))
        formula_rooCruijff = "( ( (x_%s-meanr_%s)<0) ? (exp( -1*pow((x_%s-meanr_%s),2)/(2*pow(sigmaL_%s,2)+alphaL_%s*pow((x_%s-meanr_%s),2) ))) : (exp( -1*pow((x_%s-meanr_%s),2)/(2*pow(sigmaR_%s,2)+alphaR_%s*pow((x_%s-meanr_%s),2) )))  )"%(h,h,h,h,h,h,h,h,h,h,h,h,h,h) 
     #   sig.append(RooGenericPdf("signal_cruijff_%s"%h,"signal_cruijff_%s"%h,formula_rooCruijff,RooArgList(x[num],meanr[num],sigmaL[num],sigmaR[num],alphaL[num],alphaR[num])))
      #  sig.append(RooBifurGauss("signal_bifurgaus_%s"%h,"signal_bifurgaus_%s"%h,x[num],meanr[num],sigmaL[num],sigmaR[num]))
############################VOigt##########################
        meanv.append(RooRealVar("meanv_%s"%h,"meanv_%s"%h,Xp_initial,0.5,1.5))
        widthv.append(RooRealVar("widthv_%s"%h,"widthv_%s"%h,sigp_initial,0.01,0.7))
        sigmav.append(RooRealVar("sigmav_%s"%h,"sigmav_%s"%h,sigp_initial,0.01,0.7))
   #     sig.append(RooVoigtian("signal_voigt_%s"%h,"signal_voigt_%s"%h,x[num],meanv[num],widthv[num],sigmav[num]))

###########################################################


        res.append(sig[num].fitTo(datahist[num],ROOT.RooFit.Strategy(2),ROOT.RooFit.Save(ROOT.kTRUE),ROOT.RooFit.SumW2Error(ROOT.kTRUE)))
        #res.append(sig[num].chi2FitTo(datahist[num]))
        fit_range_min = h_rel_diff.GetMean()-h_rel_diff.GetRMS()/2
        fit_range_max = h_rel_diff.GetMean()+h_rel_diff.GetRMS()/2
       # print 'range of the fit : ', fit_range_min, fit_range_max
   #     res.append(sig[num].fitTo(datahist[num],ROOT.RooFit.Save(ROOT.kTRUE),ROOT.RooFit.Range(fit_range_min,fit_range_max))) # take Mean of each histogram and add 1/2 of the RMS  ? -> try that
        res[num].Print()
        x[num].setRange("integralRange%s"%h, c_min,c_max)  
        integral.append(sig[num].createIntegral(RooArgSet(x[num]), ROOT.RooFit.Range("integralRange%s"%h)))

        scale_factors.append(datahists[num].Integral()*datahists[num].GetBinWidth(1)/integral[num].getVal())
        formula.append("%f *signal_bukin_%s"%(scale_factors[num],h))
       # formula.append("%f *signal_bifurgaus_%s"%(scale_factors[num],h))
      #  formula.append("%f *signal_voigt_%s"%(scale_factors[num],h))
      #  formula.append("%f *signal_cruijff_%s"%(scale_factors[num],h))
       # create a scaled  function = scale * function
        scaled.append(RooFormulaVar("scaled_%s"%h,formula[num],RooArgList(sig[num])))
        func_list.append(scaled[num].asTF(RooArgList(x[num])))
        func_list[num].SetLineColor(colors[num])
        hist_list.append(h_rel_diff)
   

    fitfunc='Bukin'
    fit_result_file = std.ofstream(utils.IO.plotFolder+"../fitResults/fitResultRegions_%s"%(fitfunc)+str(outString)+'.txt')
    fit_result_file.write('mean Xp\n',8)
    for fitnum in range(len(X_region)):
       Xp[fitnum].writeToStream(fit_result_file,False)
       fit_result_file.write('\n',1)
    fit_result_file.write('sigp\n',5)
    for fitnum in range(len(X_region)):
       sigp[fitnum].writeToStream(fit_result_file,False)
       fit_result_file.write('\n',1)
    fit_result_file.close()
    outString = outString.replace('/','_').replace(':','_').replace('(','_').replace(')','_').replace('+','_').replace('>=','_').replace('<','_').replace('>','_').replace(' & ','and').replace(' ','')

    c.cd()
    frame.GetYaxis().SetRangeUser(1e-06,max(max_list))
 #   frame.GetYaxis().SetRangeUser(1e-06,0.28)
    log_name=''
    if log==True : 
        c.SetLogy()
        log_name='log'
    frame.Draw()
    for j in range(len(X_region)):
        func_list[j].Draw("same")
        hist_list[j].Draw("PEsame")
        leg.AddEntry(hist_list[j],names[j]+',Xp=%.2f,sigp=%.2f'%(Xp[j].getVal(),sigp[j].getVal()) ,"PE")
        print(j,' Sigma plus error : ',sigp[j].getVal(), ' +- ',sigp[j].getError())
    leg.Draw('same')
  #  save_name=utils.IO.plotFolder+"pt_regions_fitBukin_"+str(outString)+'.png'
  #  c.SaveAs("pt_region.png")
    c.SaveAs(utils.IO.plotFolder+"fitBukin_regions_"+str(outString)+log_name+'.png')
    c.SaveAs(utils.IO.plotFolder+"fitBukin_regions_"+str(outString)+log_name+'.pdf')
Esempio n. 41
0
# - turnon
formula = "((1.-1./(1. + ([3]*x)**[1] - [2]))*(1 - [0]*x))"
acceptance = TF1("acceptance", formula, tfloor, tceil)
acceptance.SetMinimum(0.5)
acceptance.SetMaximum(1.5)

# (1) DsK, (2) DsPi
accfns = []
accfnerrs = []
xbincs = numpy.linspace(tfloor + 0.05, tceil - 0.05, nbins)

for mode, fitresult in enumerate(fitresults):
    parlist = fitresult.floatParsFinal()
    cmatrix = fitresult.covarianceMatrix()

    veclist = RooArgList()
    for i in range(parlist.getSize()):
        name = "%s_%d" % (parlist[i].GetName(), i)
        veclist.add(parlist[i].clone(name))

    multigauss = RooMultiVarGaussian("multigauss", "multigauss", veclist, parlist, cmatrix)
    dset = multigauss.generate(RooArgSet(veclist), 1000)

    fns = []
    for entry in range(dset.numEntries()):
        vecset = dset.get(entry)
        veclist = RooArgList(vecset)
        for pars in range(veclist.getSize()):
            acceptance.SetParameter(pars, veclist[pars].getVal())
        fns += [acceptance.Clone("%s_%d" % (acceptance.GetName(), entry))]
Esempio n. 42
0
                          RooFit.CutRange('onlydsk')).reduce(
                              RooFit.SelectVars(argset))

print '=' * 5, ' Datasets retrieved ', '=' * 5
for dset in (dataset, dspi_data, dsk_data):
    dset.Print('v')


## Dynamic bin merging
dspihist = TH1D('dspihist', 'Ds#pi decay time', nbins, tmin, tmax)
dskhist = TH1D('dskhist', 'DsK decay time', nbins, tmin, tmax)

for hist in (dspihist, dskhist):
    hist.Sumw2()

dspihist = dspi_data.fillHistogram(dspihist, RooArgList(time))
dskhist = dsk_data.fillHistogram(dskhist, RooArgList(time))

# old binning
obins = numpy.zeros(nbins, dtype=float)
dspihist.GetLowEdge(obins)

# bin content and bin error arrays
dspicons = numpy.zeros(nbins, dtype=float)
dspierrs = numpy.zeros(nbins, dtype=float)
dskcons = numpy.zeros(nbins, dtype=float)
dskerrs = numpy.zeros(nbins, dtype=float)

# fill arrays
for i in range(nbins):
    dspicons[i] = dspihist.GetBinContent(i + 1)
Esempio n. 43
0
  fullUnbDataSet.Print("v")
  
  varList = r.floatParsFinal()
  it = varList.createIterator()
  setconst=[]
  while True:
    var = it.Next()
    if not var:
      break
    if var.isConstant():
      continue
    setconst.append(var.GetName())
    var.setConstant(True)
    
  splot_vars = RooArgList()
  for v in config["splot_vars"]:
    splot_vars.add(w.obj(v))
    
  #normTree
  
  sData = RooStats.SPlot("sData","An SPlot", fullUnbDataSet, Final_PDF, splot_vars )
  sData.Print()
    
  for v in config["splot_vars"]:
    print v,"Fitted value: %.2f sPlot value: %.2f"%(w.obj(v).getVal(), sData.GetYieldFromSWeight(v))
    
  for v in setconst:
    w.obj(v).setConstant(False)

  fullUnbDataSet.Print("v")
Esempio n. 44
0
thevars = RooArgSet()
thevars.add(bMass)
thevars.add(l1_pt)
thevars.add(l2_pt)
thevars.add(k_pt)
thevars.add(b_pt)
thevars.add(l1_mvaId)
thevars.add(l2_mvaId)
thevars.add(cos2D)
thevars.add(l_xy_sig)
thevars.add(svprob)

fulldata = RooDataSet('fulldata', 'fulldata', tree, RooArgSet(thevars))

theBMassfunc = RooFormulaVar("theBMass", "theBMass", "@0", RooArgList(bMass))
theBMass = fulldata.addColumn(theBMassfunc)
theBMass.setRange(lowRange, highRange)
thevars.add(theBMass)

cut = ''

print cut
data = fulldata.reduce(thevars, cut)

## mass model
mean = RooRealVar("mass", "mean", B0Mass_, 5, 5.5, "GeV")
sigma = RooRealVar("sigma", "sigma", 9.0e-2, 1.0e-4, 1.0, "GeV")
alpha = RooRealVar("alpha", "alpha", 1.0, 0.0, 1.0e+4)
n = RooRealVar("n", "n", 5, 1, 100)
signalCB = RooCBShape("signalCB", "signal cb", theBMass, mean, sigma, alpha, n)
REBIN = 20
n_signal = n_ttbar + n_stop
temp_VPlusJets.Rebin(REBIN)
temp_tt.Rebin(REBIN)
temp_wj.Rebin(REBIN)
temp_zj.Rebin(REBIN)
temp_stop.Rebin(REBIN)
temp_qcd.Rebin(REBIN)
temp_qcd2.Rebin(REBIN)
temp_qcd.Scale(n_qcd / temp_qcd.Integral())
temp_qcd2.Scale(n_qcd/temp_qcd2.Integral())
temp_signal = temp_tt.Clone('signal')
temp_signal.Add(temp_stop)

leptonAbsEta = RooRealVar("leptonAbsEta", "leptonAbsEta", 0., 3.)
variables = RooArgList()
variables.add(leptonAbsEta)
vars_set = RooArgSet()
vars_set.add(leptonAbsEta)
n_event_obs = h_data.Integral();
lowerBound = -10 * sqrt(n_event_obs);
lowerBound = 0
upperBound = n_event_obs + 10 * sqrt(n_event_obs);
upperBound = n_event_obs
n_init = n_event_obs / 2.;
data = RooDataHist("data", "dataset with leptonAbsEta", variables, h_data)
rh_tt = RooDataHist("rh_tt", "tt", variables, temp_tt);
rh_wj = RooDataHist("rh_wj", "wj", variables, temp_wj);
rh_zj = RooDataHist("rh_zj", "zj", variables, temp_zj);
rh_VJ = RooDataHist("rh_VJ", "VJ", variables, temp_VPlusJets);
rh_qcd = RooDataHist("rh_qcd", "qcd", variables, temp_qcd);
temp_tt.Rebin(20)
temp_wj.Rebin(20)
temp_zj.Rebin(20)
temp_stop.Rebin(20)
temp_qcd.Rebin(20)
temp_qcd.Scale(800/temp_qcd.Integral())
temp_signal = temp_tt.Clone('signal')
temp_signal.Add(temp_stop)
#temp_tt.Scale(1/temp_tt.Integral())
#temp_wj.Scale(1/temp_wj.Integral())
#temp_zj.Scale(1/temp_zj.Integral())
#temp_stop.Scale(1/temp_stop.Integral())
#temp_qcd.Scale(1/temp_qcd.Integral())
leptonAbsEta = RooRealVar("leptonAbsEta", "leptonAbsEta", 0., 3.)
vars = RooArgList()
vars.add(leptonAbsEta)
vars_set = RooArgSet()
vars_set.add(leptonAbsEta)
n_event_obs = h_m3_data.GetEntries();
lowerBound = -10 * sqrt(n_event_obs); 
upperBound = n_event_obs + 10 * sqrt(n_event_obs);
n_init = n_event_obs / 2.;
data = RooDataHist("data", "dataset with leptonAbsEta", vars, h_m3_data)
rh_tt = RooDataHist("rh_tt", "tt", vars, temp_tt);
rh_wj = RooDataHist("rh_wj", "wj", vars, temp_wj);
rh_zj = RooDataHist("rh_zj", "zj", vars, temp_zj);
rh_qcd = RooDataHist("rh_qcd", "qcd", vars, temp_qcd);
rh_stop = RooDataHist("rh_stop", "singletop", vars, temp_stop);
rh_signal = RooDataHist("rh_signal", "signal", vars, temp_signal);
Esempio n. 47
0
event = 2

xTuple.SetBranchAddress("event", AddressOf(milk, 'price5'))
newfile = TFile("small.root", "recreate")
newtree = xTuple.CloneTree()
newtree.CopyEntries(xTuple)

newtree.Write()

sys.exit()

# In[16]:

file = TFile("newFile.root", "RECREATE")
canvas = TCanvas("canvas", "canvas", 1200, 1000)
mass = RooRealVar("xM", "M(#mu#mu#mu#mu)[GeV]", 5.15, 5.55)
trigger = RooRealVar("trigger", "trigger", 0.0, 10000)
vProb = RooRealVar("vProb", "vProb", -1.0, 1.0)
alldata = RooDataSet("alldata", "alldata", xTuple, RooArgSet(mass),
                     RooFormulaVar("vProb", "vProb", "vProb>0.01",
                                   RooArgList(vProb)))  #,cutFormula)
frame = mass.frame(Range(5.15, 5.55))
alldata.plotOn(frame, RooLinkedList())
alldata.Write()
frame.Draw()

# In[ ]:

canvas.SaveAs("testCanvas.eps")
Esempio n. 48
0
def doubleGausCB(cbshape, doublegaus, f3_, tagged_mass, w):
    f4           = RooRealVar ("f4"            , "f4"            ,  f4_  ,     0.,   1.)
    doublegauscb = RooAddPdf  ("doublegauscb"  , "doublegauscb"  ,  RooArgList(doublegaus,cbshape), RooArgList(f4))
    _import(w,doublegauscb)
Esempio n. 49
0
File: fits.py Progetto: xshi/dhad
def mbc_single_3s(evtfile, mc, setMres, setGamma, setR, sp1, sp2, sp3, fa,
                  fb, setmd, setp, setxi, setN1, setN2, setNbkgd1, setNbkgd2,
                  title1, title2, epsfile, txtfile, ymin=0.5,
                  cuts=None, err_type='SYMM', test=False):

    from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet,
                      RooFit, RooGaussian, RooArgList, RooAddPdf, RooSimultaneous,
                      RooArgusBG, RooFormulaVar, RooDLineShape, RooAbsData,
                      RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta,
                      TPaveText)
    set_root_style(stat=1, grid=0)
    
    # // sp1 = sigma of signal
    # // sp2 = ratio of sigmas betwwen sigma2 sigma 1
    # // sp3 = ratio of sigmas betwwen sigma3 sigma 2
    # // fa, fb, - fractions
    # // xi_side - slope of argus
    # // p_side - power of argus

    # mc = 1  Monte Carlo Model: EvtGenModels/Class/EvtVPHOtoVISR.cc
    # mc = 3  Data Model: with BES 2007 paper (BES2006 lineshape hepex/0612056) 

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV')

    dflav = RooCategory('dflav','D flavor')
    dflav.defineType('dflav', 1)
    dflav.defineType('dbarflav', -1)

    if cuts != None:
        if 'kkmass' in cuts:
            kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90, 'GeV')
            ras = RooArgSet(mbc, ebeam, kkmass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        elif 'kpimass' in cuts:
            kpimass = RooRealVar('kpimass', 'Kpi invariant mass', 0.6, 1.4, 'GeV')
            ras = RooArgSet(mbc, ebeam, kpimass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        else:
            raise NameError(cuts)

        sys.stdout.write('Using cuts: %s...' %cuts)
        dataset = dataset.reduce(cuts)
        sys.stdout.write(' selected %s events.\n' % dataset.numEntries())
    else:
        ras = RooArgSet(mbc, ebeam, dflav)
        dataset = RooDataSet.read(evtfile, ras)

    res = RooRealVar("datares", "datares", mc)
    mres = RooRealVar("mres","mres", setMres)
    gamma = RooRealVar('gamma', 'gamma', setGamma)

    r = RooRealVar('r', 'r', setR)
    sigmaE = RooRealVar("sigmaE","sigmaE", 0.0021)

    sigmap1 = RooRealVar("sigmap1","sigmap1", sp1, 0.002, 0.040)

    scalep2 = RooRealVar("scalep2","scalep2",2.00,1.500,5.500)
    scalep3 = RooRealVar("scalep3","scalep3",5.00,3.00,10.000)
   
    scalep2.setVal(sp2)
    scalep2.setConstant(1)
    scalep3.setVal(sp3)
    scalep3.setConstant(1)

    as12 = RooArgList(sigmap1,scalep2)
    sigmap2 = RooFormulaVar("sigmap2","sigma2","sigmap1*scalep2", as12)

    as123 = RooArgList(sigmap1,scalep2,scalep3)
    sigmap3 = RooFormulaVar("sigmap3","sigma3","sigmap1*scalep2*scalep3",
                            as123)
    
    md = RooRealVar("md","md", setmd,1.863,1.875)

    f2 = RooRealVar("f2","f2", fa)
    f3 = RooRealVar("f3","f3", fb)
    al23 = RooArgList(f2,f3)
    f1 = RooFormulaVar("f1","f1","1.0-f2-f3", al23)

    # Construct signal shape

    fcn1_1 = RooDLineShape("DLineshape1_1","DLineShape1_1",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap1,md,res)
    fcn1_2 = RooDLineShape("DLineshape1_2","DLineShape1_2",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap2,md,res)
    fcn1_3 = RooDLineShape("DLineshape1_3","DLineShape1_3",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap3,md,res)

    fcn2_1 = RooDLineShape("DLineshape2_1","DLineShape2_1",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap1,md,res)
    fcn2_2 = RooDLineShape("DLineshape2_2","DLineShape2_2",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap2,md,res)
    fcn2_3 = RooDLineShape("DLineshape2_3","DLineShape2_3",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap3,md,res)


    alf1_123 = RooArgList(fcn1_1,fcn1_2,fcn1_3)
    af12 = RooArgList(f1,f2) 
    signal1_3 = RooAddPdf("signal1_3","signal1_3", alf1_123, af12)

    alf2_123 = RooArgList(fcn2_1,fcn2_2,fcn2_3)
    
    signal2_3 = RooAddPdf("signal2_3","signal2_3", alf2_123, af12)

    p = RooRealVar("p","p", setp, 0.1, 1.5)
    xi= RooRealVar("xi","xi",setxi,-100.0,-0.1)

    Bkgd1 = RooArgusBG("argus1","argus1",mbc,ebeam,xi,p)
    Bkgd2 = RooArgusBG("argus2","argus2",mbc,ebeam,xi,p)

    shapes1 = RooArgList(signal1_3)
    shapes1.add(signal1_3)
    shapes1.add(Bkgd1)    

    shapes2 = RooArgList(signal2_3)
    shapes2.add(signal2_3)
    shapes2.add(Bkgd2)

    N1 = RooRealVar("N1","N1",setN1,0.0,200000000.0)
    N2 = RooRealVar("N2","N2",setN2,0.0,200000000.0)

    Nbkgd1 = RooRealVar("Nbkgd1","Nbkgd1",setNbkgd1, 0.0, 200000000.0)
    Nbkgd2 = RooRealVar("Nbkgd2","Nbkgd2",setNbkgd2, 0.0, 200000000.0)

    yields1 = RooArgList(N1)
    yields1.add(N1)
    yields1.add(Nbkgd1)

    yields2 = RooArgList(N2)
    yields2.add(N2)
    yields2.add(Nbkgd2)

    
    totalPdf1 = RooAddPdf("totalPdf1","totalPdf1", shapes1,yields1)
    totalPdf2 = RooAddPdf("totalPdf2","totalPdf2", shapes2,yields2)

    totalPdf = RooSimultaneous("totalPdf","totalPdf",dflav)
    totalPdf.addPdf(totalPdf1,"dflav")
    totalPdf.addPdf(totalPdf2,"dbarflav")

    # Check fitTo options at:
    # http://root.cern.ch/root/html512/RooAbsPdf.html#RooAbsPdf:fitTo
    #
    # Available fit options:
    #  "m" = MIGRAD only, i.e. no MINOS
    #  "s" = estimate step size with HESSE before starting MIGRAD
    #  "h" = run HESSE after MIGRAD
    #  "e" = Perform extended MLL fit
    #  "0" = Run MIGRAD with strategy MINUIT 0
    #  (no correlation matrix calculation at end)
    #   Does not apply to HESSE or MINOS, if run afterwards.

    #  "q" = Switch off verbose mode
    #  "l" = Save log file with parameter values at each MINUIT step
    #  "v" = Show changed parameters at each MINUIT step
    #  "t" = Time fit
    #  "r" = Save fit output in RooFitResult object 
    # Available optimizer options
    #  "c" = Cache and precalculate components of PDF that exclusively
    #  depend on constant parameters
    #  "2" = Do NLL calculation in multi-processor mode on 2 processors
    #  "3" = Do NLL calculation in multi-processor mode on 3 processors
    #  "4" = Do NLL calculation in multi-processor mode on 4 processors

    MINUIT = 'ermh4'

    if err_type == 'ASYM':
        MINUIT = 'erh4'
        
    if test:
        sys.stdout.write('Will save epsfile as: %s \n' %epsfile)
        sys.stdout.write('Will save txtfile as: %s \n' %txtfile)
        return
    
    if dataset.numEntries() == 0:
        N1.setVal(0)
        N2.setVal(0)
    else:
        # Start Fitting
        fitres = totalPdf.fitTo(dataset, MINUIT)
        fitres.Print('v')

    # Save plots
    canvas = TCanvas('canvas','mbc', 1200, 400);
    canvas.Divide(3,1)

    canvas_1 = canvas.GetListOfPrimitives().FindObject('canvas_1')
    canvas_2 = canvas.GetListOfPrimitives().FindObject('canvas_2')
    canvas_1.SetLogy(1) 
    canvas_2.SetLogy(1)

    LineColorRed = RooFit.LineColor(kRed)
    LineColorBlue = RooFit.LineColor(kBlue)
    LineWidth = RooFit.LineWidth(1) #0.6)

    # Plot the D 
    canvas.cd(1)
    mbcFrame=mbc.frame()
    mbcFrame=mbc.frame(60)

    dflav.setLabel('dflav')
    ebas = RooArgSet(ebeam, dflav)
    ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset)
    
    dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dflav"))
    mbcFrame.getAttMarker().SetMarkerSize(0.6)
    mbcFrame.Draw()

    Slice = RooFit.Slice(dflav)
    ProjWData = RooFit.ProjWData(ebas, ebeamdata)
    
    totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData)
    chisq1 = mbcFrame.chiSquare()*mbcFrame.GetNbinsX()
    mbcFrame.Draw()

    as_bkg1 = RooArgSet(Bkgd1)
    cp_bkg1 = RooFit.Components(as_bkg1)

    totalPdf.plotOn(mbcFrame, cp_bkg1, Slice, LineColorBlue, LineWidth, ProjWData)

    mbcFrame.SetTitle(title1)
    mbcFrame.SetMinimum(ymin)

    mbcFrame.Draw()

    # Plot the D bar
    canvas.cd(2)
    mbcFrame=mbc.frame()
    mbcFrame=mbc.frame(60)

    dflav.setLabel('dbarflav')
    ebas = RooArgSet(ebeam, dflav)
    ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset)
    
    dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dbarflav"))
    mbcFrame.getAttMarker().SetMarkerSize(0.6)
    mbcFrame.Draw()

    Slice = RooFit.Slice(dflav)
    ProjWData = RooFit.ProjWData(ebas, ebeamdata)
    
    totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData)
    chisq2 = mbcFrame.chiSquare()*mbcFrame.GetNbinsX()
    mbcFrame.Draw()

    as_bkg2 = RooArgSet(Bkgd2)
    cp_bkg2 = RooFit.Components(as_bkg2)

    totalPdf.plotOn(mbcFrame, cp_bkg2, Slice, LineColorBlue, LineWidth, ProjWData)

    mbcFrame.SetTitle(title2)
    mbcFrame.SetMinimum(ymin)

    mbcFrame.Draw()

    # Plot Statistics Box
    canvas.cd(3)
    mbcFrame = mbc.frame()

    paramWin1 = totalPdf.paramOn(mbcFrame,dataset, "",2,"NELU",0.1,0.9,0.9)

    mbcFrame.GetXaxis().SetLabelSize(0) 
    mbcFrame.GetXaxis().SetTickLength(0) 
    mbcFrame.GetXaxis().SetLabelSize(0) 
    mbcFrame.GetXaxis().SetTitle("") 
    mbcFrame.GetXaxis().CenterTitle() 
    
    mbcFrame.GetYaxis().SetLabelSize(0) 
    mbcFrame.GetYaxis().SetTitleSize(0.03) 
    mbcFrame.GetYaxis().SetTickLength(0) 

    paramWin1.getAttText().SetTextSize(0.06) 
  
    mbcFrame.Draw() 
    mbcFrame.SetTitle("Fit Parameters") 
    ATextBox = TPaveText(.1, .1, .8, .2,"BRNDC") 

    tempString = "#chi^{2}_{1} = %.1f, #chi^{2}_{2} = %.1f" % (chisq1,chisq2)  
    ATextBox.AddText(tempString) 
    ATextBox.SetFillColor(0)
    ATextBox.SetBorderSize(1)

    mbcFrame.addObject(ATextBox) 
    mbcFrame.Draw() 
    canvas.Print(epsfile)
    rootfile = epsfile.replace('.eps', '.root')
    canvas.Print(rootfile)

    # Save fitting parameters
    pars = [N1, N2, Nbkgd1, Nbkgd2, md, p, sigmap1, xi]
    save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
Esempio n. 50
0
def fit_mbc():
    from tools import normalizedRooFitIntegral, RooFitIntegral
    from ROOT import RooRealVar, RooDataSet, RooArgList, RooArgSet, \
         RooGaussian, RooArgusBG, RooCBShape, RooAddPdf, RooPolynomial, \
         RooDataHist, RooFit, kTRUE, kFALSE

    signal_margins = [1.86, 1.87]
    sb_margins = [1.84, 1.85]

    # Right here we compute background yield
    mbc = RooRealVar('mbc', 'mbc', 1.83, 1.89, 'GeV')
    arg_cutoff = RooRealVar('arg_cutoff', 'Argus cutoff', 1.8869, 1.885, 1.888,
                            'GeV')
    arg_slope = RooRealVar('arg_slope', 'Argus slope', -13, -100, -1)
    mbc_d0 = RooRealVar('mbc_d0', 'D0 Mbc', 1.8647, 'GeV')
    mbc_dp = RooRealVar('mbc_dp', 'D+ Mbc', 1.8694, 'GeV')
    mbc_float = RooRealVar('mbc_float', 'Floating D mass', 1.869, 1.855, 1.875,
                           'GeV')
    sigma = RooRealVar('sigma', 'D width', 0.00145, 0.0001, 0.0025, 'GeV')
    sigma2 = RooRealVar('sigma2', 'CB width', 0.00145, 0.0001, 0.005, 'GeV')
    alpha = RooRealVar('alpha', 'CB shape cutoff', -1.515, -2., 2)
    n = RooRealVar('n', 'CB tail parameter', 6, 0, 20)
    gauss_d0 = RooGaussian('gauss_d0', 'D0 gaussian', mbc, mbc_d0, sigma2)
    gauss_dp = RooGaussian('gauss_dp', 'D+ gaussian', mbc, mbc_dp, sigma2)
    gauss_float = RooGaussian('gauss_float', 'Floating gaussian', mbc,
                              mbc_float, sigma2)
    cb_d0 = RooCBShape('cb_d0', 'D0 Crystal Barrel', mbc, mbc_d0, sigma, alpha,
                       n)
    cb_dp = RooCBShape('cb_dp', 'D+ Crystal Barrel', mbc, mbc_dp, sigma, alpha,
                       n)
    cb_float = RooCBShape('cb_float', 'Floating Crystal Barrel', mbc,
                          mbc_float, sigma, alpha, n)
    argus = RooArgusBG('argus', 'Argus BG', mbc, arg_cutoff, arg_slope)
    yld = RooRealVar('yield', 'D yield', 25700, 0, 100000)
    yld2 = RooRealVar('yield2', '2nd yield', 100, 0, 2000)
    bkg = RooRealVar('bkg', 'Background', 1300, 0, 40000)
    a = RooRealVar('a', 'Norm', 1)
    poly = RooPolynomial('poly', 'poly PDF', mbc, RooArgList(a), 0)
    sumpdf_d0 = RooAddPdf('sumpdf_d0', 'D0 sum pdf', RooArgList(cb_d0, argus),
                          RooArgList(yld, bkg))
    sumpdf_dp = RooAddPdf('sumpdf_dp', 'Dp sum pdf', RooArgList(cb_dp, argus),
                          RooArgList(yld, bkg))
    sumpdf_float = RooAddPdf('sumpdf_float', 'Generic D sum pdf',
                             RooArgList(cb_float, argus), RooArgList(yld, bkg))

    width_modes = {
        '0': 0.00150,
        '1': 0.001831,
        '3': 0.001426,
        '200': 0.001387,
        '202': 0.001407
    }

    n_modes = {'0': 2.68, '1': 4.06, '3': 4.34, '200': 4.05, '202': 5.26}
    alpha_modes = {
        '0': -1.6145,
        '1': -1.4562,
        '3': -1.5834,
        '200': -1.6538,
        '202': -1.5598
    }

    pdf = sumpdf_float

    sigma.setVal(width_modes['1'])  # sigma.setConstant()

    n.setVal(n_modes['1'])  #n.setConstant()

    alpha.setVal(alpha_modes['1'])  #alpha.setConstant()
    #sigma.setConstant()
    #arg_cutoff.setVal(1.8865); #arg_cutoff.setConstant()

    c1.Divide(1, 2)
    c1.cd(1)
    dset = RooDataHist('dsetmc', 'title', RooArgList(mbc), h_mbc['mc'])

    #pdf.fitTo(dset, 'eq')
    Extended = RooFit.Extended(kTRUE)  # e
    Verbose = RooFit.Verbose(kFALSE)  #q

    pdf.fitTo(dset, Extended, Verbose)

    # xframe = mbc.frame()
    # dset.plotOn(xframe)
    # pdf.plotOn(xframe)
    # pdf.paramOn(xframe,dset)
    # xframe.SetTitle('Fake type 1, MC')
    # xframe.Draw()
    c1.cd(2)
    dset = RooDataHist('dsetdata', 'title', RooArgList(mbc), h_mbc['data'])
    #pdf.fitTo(dset, 'eq')
    pdf.fitTo(dset, Extended, Verbose)
    # xframe = mbc.frame()
    # dset.plotOn(xframe)
    # pdf.plotOn(xframe)
    # pdf.paramOn(xframe,dset)
    # xframe.SetTitle('Fake type 1, data')
    # xframe.Draw()
    sb_scale = (
        normalizedRooFitIntegral(argus, mbc, signal_margins[0],
                                 signal_margins[1]) /
        normalizedRooFitIntegral(argus, mbc, sb_margins[0], sb_margins[1]))
Esempio n. 51
0
from ROOT import RooRealVar, RooGaussian, RooChebychev, RooAddPdf, RooArgList, RooArgSet, RooFit

x = RooRealVar("x", "x", -1, 1)

# Use RooGaussian in the generation
mean = RooRealVar("mean", "mean of gaussian", 0, -1, 1)
sigma = RooRealVar("sigma", "sigma of gaussian", 0.1, -1, 1)
sig = RooGaussian("gauss", "gaussian PDF", x, mean, sigma)

# Background
a0 = RooRealVar("a0", "a0", 0.5, 0., 1.)
a1 = RooRealVar("a1", "a1", -0.2, 0., 1.)
bkg = RooChebychev("bkg", "Background", x, RooArgList(a0, a1))

bkgfrac = RooRealVar("bkgfrac", "fraction of background", 0.5, 0., 1.)
model = RooAddPdf("model", "g+a", RooArgList(bkg, sig), RooArgList(bkgfrac))

data = model.generate(RooArgSet(x), 10000)

model.fitTo(data)
Esempio n. 52
0
                        phimean + 0.007)

    # B_1     = RooRealVar ( "B_1"    , "B_1 "    , 0.3  , -20   , 100   )
    # B_2     = RooRealVar ( "B_2"    , "B_2"    , 0.3  , -20   , 100   )
    # B_3     = RooRealVar ( "B_3"    , "B_3"    , 0.3  , -20   , 100   )
    # B_4     = RooRealVar ( "B_4"    , "B_4"    , 0.3  , -20   , 100   )
    # B_5     = RooRealVar ( "B_5"    , "B_5"    , 0.3  , -20   , 100   )
    # B_6     = RooRealVar ( "B_6"    , "B_6"    , 0.3  , -20   , 100   )

    a0 = RooRealVar("p0", "p0", 0.001, -2., 2.)
    a1 = RooRealVar("p1", "p1", 0.001, -2., 2.)
    a2 = RooRealVar("p2", "p2", -0.00001, -2., 2.)
    a3 = RooRealVar("p3", "p3", -0.000001, -2, 2.)
    a4 = RooRealVar("p4", "p4", -0.000001, -2., 2.)
    # a5 = RooRealVar("a5","a5",-0.000001,-2.,2.)
    poliset = RooArgList(a0, a1, a2, a3, a4)

    # gaussFrac = RooRealVar("s","fraction of component 1 in kkSig",0.3,0.0,1.0)
    nSigKK = RooRealVar("nSig", "nSig", 1E5, 0., 10E6)
    nBkgKK = RooRealVar("nBkg", "nBkg", 5E5, 0., 10E6)

    kkSig = RooVoigtian("kkSig", "kkSig", tt_mass, kkMean, kkGamma, kkSigma)
    #kkBkg = RooBernstein("kkBkg" , "kkBkg", tt_mass, RooArgList(B_1, B_2,B_3,B_4))#,B_5) )#,B_6))
    kkBkg = RooChebychev("kkBkg", "Background", tt_mass, poliset)
    kkTot = RooAddPdf("kkTot", "kkTot", RooArgList(kkSig, kkBkg),
                      RooArgList(nSigKK, nBkgKK))

    kkGamma.setConstant(ROOT.kTRUE)
    kkMean.setConstant(ROOT.kTRUE)

    nfit = 0
Esempio n. 53
0
def findOnePe(hist, ws, name='x', Npe = 1):
    fitPed(hist, ws, name)
    x = ws.var(name)

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

    pdfs = RooArgList(ped)
    pdfList = []

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

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

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

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

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

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

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

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

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

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

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

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

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

    getattr(ws, 'import')(pedPlusOne)
Esempio n. 54
0
                  RooBinning, RooPolyVar, RooProduct)

# globals, and aliases
from ROOT import gPad, gStyle, gSystem, kRed, kBlue, kAzure, kGreen, kBlack
const = RooRealConstant.value

# setup
gStyle.SetOptStat('nemrou')
canvas = TCanvas('canvas', 'canvas', 800, 600)
canvas.Print('{}['.format(plotfile))

# read workspace
ffile = TFile.Open(rfile, 'read')
workspace = ffile.Get('workspace')

pdfs = RooArgList(workspace.allPdfs())
for i in range(pdfs.getSize()):
    name = pdfs[i].GetName()
    if name.find(mode) >= 0:
        mykpdf = pdfs[i]
assert(mykpdf)

## variables
time = RooRealVar('time', 'Time [ps]', 0.2, 15.0)
time.setBins(bins)
time.setBins(bins*3, 'cache')

kfactor = workspace.var('kfactorVar')
kfactor.setRange(0.85, 1.05)
gamma = RooRealVar('gamma', 'gamma', 0.661, 0., 3.)
kgamma = RooProduct('kgamma', 'kgamma', RooArgList(gamma, kfactor))
Esempio n. 55
0
def buildAccXRecEffiHist(self):
    """Build efficiency histogram for later fitting/plotting"""
    fin = self.process.filemanager.open(
        "buildAccXRecEffiHist",
        modulePath + "/data/accXrecEffHists_Run2012.root", "UPDATE")

    # Build acceptance, reco efficiency, and accXrec
    forceRebuild = False
    for binKey in q2bins.keys():
        if binKey not in [
                'belowJpsi', 'betweenPeaks', 'abovePsi2s', 'summary'
        ]:
            continue
        h2_accXrec = fin.Get("h2_accXrec_{0}".format(binKey))
        if h2_accXrec == None or forceRebuild:
            h2_acc = fin.Get("h2_acc_{0}".format(binKey))
            h2_rec = fin.Get("h2_rec_{0}".format(binKey))

            # Fill histograms
            setupEfficiencyBuildProcedure = {}
            setupEfficiencyBuildProcedure['acc'] = {
                'ifiles': [
                    "/eos/cms/store/user/pchen/BToKstarMuMu/dat/sel/v3p5/unfilteredSIG_genonly/*.root",
                ],
                'baseString':
                re.sub("Mumumass", "sqrt(genQ2)", q2bins[binKey]['cutString']),
                'cutString':
                "fabs(genMupEta)<2.3 && fabs(genMumEta)<2.3 && genMupPt>2.8 && genMumPt>2.8",
                'fillXY':
                "genCosThetaK:genCosThetaL"  # Y:X
            }
            setupEfficiencyBuildProcedure['rec'] = {
                'ifiles':
                sigMCReader.cfg['ifile'],
                'baseString':
                "{0}".format(
                    setupEfficiencyBuildProcedure['acc']['baseString']),
                'cutString':
                "Bmass > 0.5 && ({0})".format(cuts[-1]),
                'fillXY':
                "genCosThetaK:genCosThetaL"  # Y:X
            }
            for h2, label in (h2_acc, 'acc'), (h2_rec, 'rec'):
                if h2 == None or forceRebuild:
                    treein = TChain("tree")
                    for f in setupEfficiencyBuildProcedure[label]['ifiles']:
                        treein.Add(f)

                    treein.Draw(
                        ">>totEvtList",
                        setupEfficiencyBuildProcedure[label]['baseString'])
                    totEvtList = ROOT.gDirectory.Get("totEvtList")
                    treein.SetEventList(totEvtList)
                    treein.Draw(
                        ">>accEvtList",
                        setupEfficiencyBuildProcedure[label]['cutString'])
                    accEvtList = ROOT.gDirectory.Get("accEvtList")

                    h2_total = TH2D("h2_{0}_{1}_total".format(label,
                                                              binKey), "",
                                    len(accXEffThetaLBins) - 1,
                                    accXEffThetaLBins,
                                    len(accXEffThetaKBins) - 1,
                                    accXEffThetaKBins)
                    h2_passed = h2_total.Clone("h2_{0}_{1}_passed".format(
                        label, binKey))

                    h2_fine_total = TH2D(
                        "h2_{0}_fine_{1}_total".format(label, binKey), "", 20,
                        -1, 1, 20, -1, 1)
                    h2_fine_passed = h2_fine_total.Clone(
                        "h2_{0}_fine_{1}_passed".format(label, binKey))

                    treein.SetEventList(totEvtList)
                    for hist in h2_total, h2_fine_total:
                        treein.Draw(
                            "{0}>>{1}".format(
                                setupEfficiencyBuildProcedure[label]['fillXY'],
                                hist.GetName()), "", "goff")

                    treein.SetEventList(accEvtList)
                    for hist in h2_passed, h2_fine_passed:
                        treein.Draw(
                            "{0}>>{1}".format(
                                setupEfficiencyBuildProcedure[label]['fillXY'],
                                hist.GetName()), "", "goff")

                    h2_eff = TEfficiency(h2_passed, h2_total)
                    h2_eff_fine = TEfficiency(h2_fine_passed, h2_fine_total)

                    fin.cd()
                    for proj, var in [("ProjectionX", CosThetaL),
                                      ("ProjectionY", CosThetaK)]:
                        proj_fine_total = getattr(h2_fine_total,
                                                  proj)("{0}_{1}".format(
                                                      h2_fine_total.GetName(),
                                                      proj), 0, -1, "e")
                        proj_fine_passed = getattr(h2_fine_passed, proj)(
                            "{0}_{1}".format(h2_fine_passed.GetName(),
                                             proj), 0, -1, "e")
                        h_eff = TEfficiency(proj_fine_passed, proj_fine_total)
                        h_eff.Write(
                            "h_{0}_fine_{1}_{2}".format(label, binKey, proj),
                            ROOT.TObject.kOverwrite)

                    h2_eff.Write("h2_{0}_{1}".format(label, binKey),
                                 ROOT.TObject.kOverwrite)
                    h2_eff_fine.Write("h2_{0}_fine_{1}".format(label, binKey),
                                      ROOT.TObject.kOverwrite)

            # Merge acc and rec to accXrec
            fin.cd()
            for proj in ["ProjectionX", "ProjectionY"]:
                h_acc_fine = fin.Get("h_acc_fine_{0}_{1}".format(binKey, proj))
                h_rec_fine = fin.Get("h_rec_fine_{0}_{1}".format(binKey, proj))
                h_accXrec_fine = h_acc_fine.GetPassedHistogram().Clone(
                    "h_accXrec_fine_{0}_{1}".format(binKey, proj))
                h_accXrec_fine.Reset("ICESM")
                for b in range(1, h_accXrec_fine.GetNbinsX() + 1):
                    h_accXrec_fine.SetBinContent(
                        b,
                        h_acc_fine.GetEfficiency(b) *
                        h_rec_fine.GetEfficiency(b))
                    h_accXrec_fine.SetBinError(
                        b,
                        h_accXrec_fine.GetBinContent(b) * math.sqrt(
                            1 /
                            h_acc_fine.GetTotalHistogram().GetBinContent(b) +
                            1 /
                            h_acc_fine.GetPassedHistogram().GetBinContent(b) +
                            1 /
                            h_rec_fine.GetTotalHistogram().GetBinContent(b) +
                            1 /
                            h_rec_fine.GetPassedHistogram().GetBinContent(b)))
                h_accXrec_fine.Write("h_accXrec_{0}_{1}".format(binKey, proj),
                                     ROOT.TObject.kOverwrite)

            h2_acc = fin.Get("h2_acc_{0}".format(binKey))
            h2_rec = fin.Get("h2_rec_{0}".format(binKey))
            h2_accXrec = h2_acc.GetPassedHistogram().Clone(
                "h2_accXrec_{0}".format(binKey))
            h2_accXrec.Reset("ICESM")
            for iL, iK in itertools.product(range(1, len(accXEffThetaLBins)),
                                            range(1, len(accXEffThetaKBins))):
                if h2_rec.GetTotalHistogram().GetBinContent(
                        iL,
                        iK) == 0 or h2_rec.GetPassedHistogram().GetBinContent(
                            iL, iK) == 0:
                    h2_accXrec.SetBinContent(iL, iK, 0)
                    h2_accXrec.SetBinError(iL, iK, 1)
                else:
                    iLK = h2_acc.GetGlobalBin(iL, iK)
                    h2_accXrec.SetBinContent(
                        iL, iK,
                        h2_acc.GetEfficiency(iLK) * h2_rec.GetEfficiency(iLK))
                    h2_accXrec.SetBinError(
                        iL, iK,
                        h2_accXrec.GetBinContent(iL, iK) * math.sqrt(
                            1 / h2_acc.GetTotalHistogram().GetBinContent(iLK) +
                            1 /
                            h2_acc.GetPassedHistogram().GetBinContent(iLK) +
                            1 / h2_rec.GetTotalHistogram().GetBinContent(iLK) +
                            1 / h2_rec.GetPassedHistogram().GetBinContent(iLK))
                    )
            h2_accXrec.SetXTitle("cos#theta_{l}")
            h2_accXrec.SetYTitle("cos#theta_{K}")
            h2_accXrec.SetZTitle("Overall efficiency")

            h2_accXrec.Write("h2_accXrec_{0}".format(binKey),
                             ROOT.TObject.kOverwrite)
            self.logger.logINFO("Overall efficiency is built.")

    # Register the chosen one to sourcemanager
    h2_accXrec = fin.Get("h2_accXrec_{0}".format(self.process.cfg['binKey']))
    self.cfg['source']['effiHistReader.h2_accXrec'] = h2_accXrec
    self.cfg['source']['effiHistReader.accXrec'] = RooDataHist(
        "accXrec", "", RooArgList(CosThetaL, CosThetaK),
        ROOT.RooFit.Import(h2_accXrec))
    self.cfg['source']['effiHistReader.h_accXrec_fine_ProjectionX'] = fin.Get(
        "h_accXrec_{0}_ProjectionX".format(self.process.cfg['binKey']))
    self.cfg['source']['effiHistReader.h_accXrec_fine_ProjectionY'] = fin.Get(
        "h_accXrec_{0}_ProjectionY".format(self.process.cfg['binKey']))
Esempio n. 56
0
def buildPolarizationPDF(ws,options):

    foldname = ''
    if not options.folded:
        foldname=''
        
    accMaps = TFile.Open(options.acceptanceMap)
    #effMaps = TFile.Open(options.efficiencyMap)

    ws.factory('lambda_theta_'+options.fitFrame+'_p[0,-1,1]')
    ws.factory('lambda_phi_'+options.fitFrame+'_p[0,-1,1]')
    ws.factory('lambda_thetaphi_'+options.fitFrame+'_p[0,-1,1]')

    ws.factory('lambda_theta_'+options.fitFrame+'_np[0,-1,1]')
    ws.factory('lambda_phi_'+options.fitFrame+'_np[0,-1,1]')
    ws.factory('lambda_thetaphi_'+options.fitFrame+'_np[0,-1,1]')

    ws.factory('nPromptinP[500,0,1000000]')
    ws.factory('sum::nPromptinNP(1*nPromptSignal,-1*nPromptinP)')

    ws.factory('nNonPromptinNP[100,0,1000000]')
    ws.factory('sum::nNonPromptinP(1*nNonPromptSignal,-1*nNonPromptinNP)')
    
    ws.factory('nBackgroundinP[50,0,1000000]')
    ws.factory('sum::nBackgroundinNP(1*nBackgroundSignal,-1*nBackgroundinP)')

    ws.factory('RooPolarizationConstraint::promptConstr('+
               'lambda_theta_'+options.fitFrame+'_p,'+
               'lambda_phi_'+options.fitFrame+'_p,'+
               'lambda_thetaphi_'+options.fitFrame+'_p)')
    ws.factory('RooPolarizationConstraint::nonPromptConstr('+
               'lambda_theta_'+options.fitFrame+'_np,'+
               'lambda_phi_'+options.fitFrame+'_np,'+
               'lambda_thetaphi_'+options.fitFrame+'_np)')
      
    #for each rap/pt cell make a unique simultaneous fit of prompt,non-prompt, background
    for rap_bin in range(1,len(jpsi.pTRange)):
        for pt_bin in range(len(jpsi.pTRange[rap_bin])):

            accMapHist = accMaps.Get('hAcc2D_'+options.fitFrame+'_pT'+str(pt_bin+1)+'_rap'+str(rap_bin))
            for effMap in options.efficiencyMap.split(','):
                effMaps = TFile.Open(effMap)
                effMapHist = effMaps.Get('hAcc2D_'+options.fitFrame+'_pT'+str(pt_bin+1)+'_rap'+str(rap_bin))
                accMapHist.Multiply(effMapHist)
                effMaps.Close()
            
            getattr(ws,'import')(accMapHist)

            accMap = RooDataHist('accMap'+options.fitFrame+'Data_'+str(rap_bin)+'_'+str(pt_bin+1),
                                 'acceptance map',
                                 RooArgList(ws.var('costh_'+options.fitFrame+foldname),ws.var('phi_'+options.fitFrame+foldname)),
                                 ROOT.RooFit.Import(accMapHist,False))
            getattr(ws,'import')(accMap)
                        
            accMapFunc = RooHistFunc('accMapFunc'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1),
                                     'acceptance map',
                                     RooArgSet(ws.var('costh_'+options.fitFrame+foldname),ws.var('phi_'+options.fitFrame+foldname)),
                                     ws.data('accMap'+options.fitFrame+'Data_'+str(rap_bin)+'_'+str(pt_bin+1)),1)
            getattr(ws,'import')(accMapFunc)

            #make a *real* hist pdf :-)
            ws.factory('RooGenericPdf::accMap'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '("@0",{accMapFunc'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+'})')
            
            #create datahist for L and R sidebands
            getattr(ws,'import')(accMap.Clone('bkgShape'+options.fitFrame+'DataL_'+str(rap_bin)+'_'+str(pt_bin+1)))
            getattr(ws,'import')(accMap.Clone('bkgShape'+options.fitFrame+'DataR_'+str(rap_bin)+'_'+str(pt_bin+1)))
            ws.data('bkgShape'+options.fitFrame+'DataL_'+str(rap_bin)+'_'+str(pt_bin+1)).reset()
            ws.data('bkgShape'+options.fitFrame+'DataR_'+str(rap_bin)+'_'+str(pt_bin+1)).reset()

            #fill them
            ws.data('bkgShape'+options.fitFrame+'DataL_'+str(rap_bin)+'_'+str(pt_bin+1)).add(ws.data('data_rap'+str(rap_bin)+'_pt'+str(pt_bin+1)),
                                                                                             'massRegion == massRegion::leftMassSideBand')
            ws.data('bkgShape'+options.fitFrame+'DataR_'+str(rap_bin)+'_'+str(pt_bin+1)).add(ws.data('data_rap'+str(rap_bin)+'_pt'+str(pt_bin+1)),
                                                                                             'massRegion == massRegion::rightMassSideBand')

            #make histpdfs and combination
            ws.factory('RooHistPdf::bkgShape'+options.fitFrame+'L_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '({costh_'+options.fitFrame+foldname+',phi_'+options.fitFrame+foldname+'},'+
                       'bkgShape'+options.fitFrame+'DataL_'+str(rap_bin)+'_'+str(pt_bin+1)+')')
            ws.factory('RooHistPdf::bkgShape'+options.fitFrame+'R_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '({costh_'+options.fitFrame+foldname+',phi_'+options.fitFrame+foldname+'},'+
                       'bkgShape'+options.fitFrame+'DataR_'+str(rap_bin)+'_'+str(pt_bin+1)+')')
            ws.factory('SUM::bkgShape'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(fBkgLR*bkgShape'+options.fitFrame+'L_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       ',bkgShape'+options.fitFrame+'R_'+str(rap_bin)+'_'+str(pt_bin+1)+')')

            #test new polarization pdf
            ws.factory('RooPolarizationPdf::basePolPdf'+options.fitFrame+'Prompt_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(costh_'+options.fitFrame+foldname+',phi_'+options.fitFrame+foldname+
                       ',lambda_theta_'+options.fitFrame+'_p,lambda_phi_'+options.fitFrame+'_p,lambda_thetaphi_'+options.fitFrame+'_p)')
            ws.factory('RooPolarizationPdf::basePolPdf'+options.fitFrame+'NonPrompt_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(costh_'+options.fitFrame+foldname+',phi_'+options.fitFrame+foldname+
                       ',lambda_theta_'+options.fitFrame+'_np,lambda_phi_'+options.fitFrame+'_np,lambda_thetaphi_'+options.fitFrame+'_np)')

            #should add back *(3+@2) ?
            #sin(2theta) = 2sin(theta)cos(theta) = 2*sqrt(1 - cos(theta)*cos(theta))*cos(theta)
            #ws.factory('RooGenericPdf::basePolPdf'+options.fitFrame+'Prompt_'+str(rap_bin)+'_'+str(pt_bin+1)+
            #           '("1+@2*pow(@0,2.)+@3*(1-pow(@0,2.))*cos(2*@1*pi/180)+@4*sin(2*acos(@0))*cos(@1*pi/180)"'+
            #           ',{costh_'+options.fitFrame+foldname+',phi_'+options.fitFrame+foldname+',lambda_theta_'+options.fitFrame+
            #           '_p,lambda_phi_'+options.fitFrame+'_p,lambda_thetaphi_'+options.fitFrame+'_p})')
            
            #ws.factory('RooGenericPdf::basePolPdf'+options.fitFrame+'NonPrompt_'+str(rap_bin)+'_'+str(pt_bin+1)+
            #           '("1+@2*@0*@0+@3*(1-@0*@0)*cos(2*@1*pi/180)+@4*sin(2*acos(@0))*cos(@1*pi/180)"'+
            #           ',{costh_'+options.fitFrame+foldname+',phi_'+options.fitFrame+foldname+',lambda_theta_'+options.fitFrame+
            #           '_np,lambda_phi_'+options.fitFrame+'_np,lambda_thetaphi_'+options.fitFrame+'_np})')    

            ws.factory('PROD::polPdf'+options.fitFrame+'Prompt_'+str(rap_bin)+'_'+str(pt_bin+1)
                       +'(basePolPdf'+options.fitFrame+'Prompt_'+str(rap_bin)+'_'+str(pt_bin+1)
                       +',accMap'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+')')
            
            ws.factory('PROD::polPdf'+options.fitFrame+'NonPrompt_'+str(rap_bin)+'_'+str(pt_bin+1)
                       +'(basePolPdf'+options.fitFrame+'NonPrompt_'+str(rap_bin)+'_'+str(pt_bin+1)
                       +',accMap'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+')')
            
            ws.factory('RooExtendPdf::promptPolExtinP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(polPdf'+options.fitFrame+'Prompt_'+str(rap_bin)+'_'+str(pt_bin+1)+',nPromptinP)')

            ws.factory('RooExtendPdf::promptPolExtinNP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(polPdf'+options.fitFrame+'Prompt_'+str(rap_bin)+'_'+str(pt_bin+1)+',nPromptinNP)')

            ws.factory('RooExtendPdf::nonPromptPolExtinNP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(polPdf'+options.fitFrame+'NonPrompt_'+str(rap_bin)+'_'+str(pt_bin+1)+',nNonPromptinNP)')
            
            ws.factory('RooExtendPdf::nonPromptPolExtinP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(polPdf'+options.fitFrame+'NonPrompt_'+str(rap_bin)+'_'+str(pt_bin+1)+',nNonPromptinP)')
            
            ws.factory('RooExtendPdf::bkgPolExtinP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(bkgShape'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+',nBackgroundinP)')

            ws.factory('RooExtendPdf::bkgPolExtinNP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+
                       '(bkgShape'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+',nBackgroundinNP)')

            promptPOLArgList = RooArgList(ws.pdf('promptPolExtinP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)))

            nonPromptPOLArgList = RooArgList(ws.pdf('promptPolExtinNP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)),
                                             ws.pdf('nonPromptPolExtinNP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1))
                                             )
            
            if options.doNonPrompt:
                promptPOLArgList.add(ws.pdf('nonPromptPolExtinP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)))
            if options.doBackground:        
                promptPOLArgList.add(ws.pdf('bkgPolExtinP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)))
                nonPromptPOLArgList.add(ws.pdf('bkgPolExtinNP'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)))
            
            promptP = RooAddPdf('promptPol'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1),
                                'prompt',
                                promptPOLArgList
                                )
            
            nonpromptP = RooAddPdf('nonpromptPol'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1),
                                   'nonprompt',
                                   nonPromptPOLArgList
                                   )
    
            getattr(ws,'import')(promptP)
            getattr(ws,'import')(nonpromptP)

            polConfig = 'SIMUL::PPdf'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+'(mlRegion,'
             
            if options.doPrompt:
                polConfig += 'promptSignal=promptPol'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+','
            if options.doNonPrompt:
                polConfig += 'nonPromptSignal=nonpromptPol'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+','
            #if options.doBackground:       
            #    polConfig += ('prompt;leftMassSideBand=bkgPolExtL'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+','
            #                  'prompt;rightMassSideBand=bkgPolExtR'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1))
            #    polConfig += ('nonPrompt;leftMassSideBand=bkgPolExtL'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1)+','
            #                  'nonPrompt;rightMassSideBand=bkgPolExtR'+options.fitFrame+'_'+str(rap_bin)+'_'+str(pt_bin+1))
                 

            polConfig += ')'
            
            #simultaneous
            ws.factory(polConfig)

    accMaps.Close()
Esempio n. 57
0
def buildMassAndLifetimePDF(ws):
    
    #define mass shape
    ws.factory('RooCBShape::massCBShape(JpsiMass,CBmass[3.1,3.05,3.15],CBsigma[0.02,0.0001,1],CBalpha[1,.0001,5],CBn[10,.0001,50])')
    #ws.factory('RooGaussian::massCBShape(JpsiMass,CBmass[3.1,3.05,3.15],CBsigma[0.02,0.0001,1])')
    ws.factory('RooExponential::bkgMassShape(JpsiMass,bkgLambda[0,-5,5])')
    #ws.factory('RooChebychev::bkgMassShape(JpsiMass,{p0[1,-10,10],p1[1,-10,10],p2[1,-10,10]})')    
    #lifetime
    ws.factory('RooGaussModel::promptLifetimeRaw(Jpsict,promptMean[0,-1,1],ctResolution[1,.001,5],1,JpsictErr)')    
    ws.pdf('promptLifetimeRaw').advertiseFlatScaleFactorIntegral(True)
    
    ws.factory('RooDecay::nonPromptSSDRaw(Jpsict,nonPromptTau[.3,.01,3],promptLifetimeRaw,RooDecay::SingleSided)')
    
    ws.factory('RooDecay::backgroundSSDRawL(Jpsict,bkgTauSSDL[.3,0,3],promptLifetimeRaw,RooDecay::SingleSided)')
    #ws.factory('RooDecay::backgroundFDRaw(Jpsict,bkgTauFD[.3,.0001,3],promptLifetimeRaw,RooDecay::Flipped)')
    ws.factory('RooDecay::backgroundDSDRawL(Jpsict,bkgTauDSDL[.3,0,3],promptLifetimeRaw,RooDecay::DoubleSided)')    
    ws.factory('SUM::backgroundRawL(fBkgSSDL[.5,0,1]*backgroundSSDRawL,backgroundDSDRawL)')
    
    ws.factory('RooDecay::backgroundSSDRawR(Jpsict,bkgTauSSDR[.3,0,3],promptLifetimeRaw,RooDecay::SingleSided)')
    #ws.factory('RooDecay::backgroundFDRaw(Jpsict,bkgTauFD[.3,.0001,3],promptLifetimeRaw,RooDecay::Flipped)')
    ws.factory('RooDecay::backgroundDSDRawR(Jpsict,bkgTauDSDR[.3,0,3],promptLifetimeRaw,RooDecay::DoubleSided)')    
    ws.factory('SUM::backgroundRawR(fBkgSSDR[.5,0,1]*backgroundSSDRawR,backgroundDSDRawR)')

    ws.factory('SUM::backgroundRaw(fBkgLR[.5]*backgroundRawL,backgroundDSDRawR)')
    
    ws.factory('PROD::promptRawMass(massCBShape)') #,promptLifetimeRaw|JpsictErr
    ws.factory('PROD::nonpromptRawMass(massCBShape)') #,nonPromptSSDRaw|JpsictErr
    ws.factory('PROD::backgroundRawMass(bkgMassShape)') #,backgroundDSDRaw|JpsictErr

    ws.factory('PROD::promptRawCTau(promptLifetimeRaw|JpsictErr)') 
    ws.factory('PROD::nonpromptRawCTau(nonPromptSSDRaw|JpsictErr)') 
    ws.factory('PROD::backgroundRawCTauL(backgroundRawL|JpsictErr)') 
    ws.factory('PROD::backgroundRawCTauR(backgroundRawR|JpsictErr)') 
    ws.factory('PROD::backgroundRawCTau(backgroundRaw|JpsictErr)')
        
    #extended pdfs    
    ws.factory('RooExtendPdf::promptExtMass(promptRawMass,sum::nPrompt(nPromptSignal[1000,0,1000000]))') #,nPromptL[1000,0,1000000],nPromptR[1000,0,1000000]
    ws.factory('RooExtendPdf::nonpromptExtMass(nonpromptRawMass,sum::nNonPrompt(nNonPromptSignal[500,0,1000000]))')
    #[500,0,1000000],,nNonPromptL[500,0,1000000],nNonPromptR[500,0,1000000]
    ws.factory('RooExtendPdf::backgroundExtMass(backgroundRawMass,sum::nBackground(nBackgroundSignal[100,0,1000000],nBackgroundL[100,0,1000000],nBackgroundR[100,0,1000000]))') #

    ws.factory('RooExtendPdf::promptExtCTauL(promptRawCTau,0)') #nPromptL[1,0,1000000]
    ws.factory('RooExtendPdf::promptExtCTauR(promptRawCTau,0)')#nPromptR[1,0,1000000]
    ws.factory('RooExtendPdf::nonpromptExtCTauL(nonpromptRawCTau,0)') #nNonPromptL[1,0,1000000]
    ws.factory('RooExtendPdf::nonpromptExtCTauR(nonpromptRawCTau,0)') #nNonPromptR[1,0,1000000]
    ws.factory('RooExtendPdf::backgroundExtCTauL(backgroundRawCTauL,nBackgroundL)')
    ws.factory('RooExtendPdf::backgroundExtCTauR(backgroundRawCTauR,nBackgroundR)')

    ws.factory('RooExtendPdf::promptExtCTau(promptRawCTau,nPromptSignal)')
    ws.factory('RooExtendPdf::nonpromptExtCTau(nonpromptRawCTau,nNonPromptSignal)')
    ws.factory('RooExtendPdf::backgroundExtCTau(backgroundRawCTau,nBackgroundSignal)')
    
    
    #final AddPdfs
    promptMArgList = RooArgList(ws.pdf('promptExtMass'))
    nonPromptMArgList = RooArgList(ws.pdf('promptExtMass'),
                                   ws.pdf('nonpromptExtMass'))
    
    if options.doNonPrompt:
        promptMArgList.add(ws.pdf('nonpromptExtMass'))
    if options.doBackground:        
        promptMArgList.add(ws.pdf('backgroundExtMass'))
        nonPromptMArgList.add(ws.pdf('backgroundExtMass'))
    
    promptM = RooAddPdf('promptMass','prompt',promptMArgList)
    nonpromptM = RooAddPdf('nonpromptMass','nonprompt',nonPromptMArgList)
    backgroundM = RooAddPdf('backgroundMass','background',RooArgList(ws.pdf('promptExtMass'),
                                                                     ws.pdf('nonpromptExtMass'),
                                                                     ws.pdf('backgroundExtMass')))
    
    promptCTArgList = RooArgList(ws.pdf('promptExtCTau'))
    nonPromptCTArgList = RooArgList(ws.pdf('promptExtCTau'),
                                    ws.pdf('nonpromptExtCTau'))
    
    if options.doNonPrompt:
        promptCTArgList.add(ws.pdf('nonpromptExtCTau'))        
    if options.doBackground:        
        promptCTArgList.add(ws.pdf('backgroundExtCTau'))
        nonPromptCTArgList.add(ws.pdf('backgroundExtCTau'))

    promptCT = RooAddPdf('promptCTau','prompt',promptCTArgList)
    nonpromptCT = RooAddPdf('nonpromptCTau','nonprompt',nonPromptCTArgList)
    backgroundCT = RooAddPdf('backgroundCTau','background',RooArgList(ws.pdf('promptExtCTau'),
                                                                      ws.pdf('nonpromptExtCTau'),
                                                                      ws.pdf('backgroundExtCTau')))
    #playing around with signal in left sideband
    backgroundCTL = RooAddPdf('backgroundCTauL','background',RooArgList(ws.pdf('promptExtCTauL'),
                                                                        ws.pdf('nonpromptExtCTauL'),
                                                                        ws.pdf('backgroundExtCTauL')))
    backgroundCTR = RooAddPdf('backgroundCTauR','background',RooArgList(ws.pdf('promptExtCTauR'),
                                                                        ws.pdf('nonpromptExtCTauR'),
                                                                        ws.pdf('backgroundExtCTauR')))   

    getattr(ws,'import')(promptM)
    getattr(ws,'import')(nonpromptM)
    getattr(ws,'import')(backgroundM)

    getattr(ws,'import')(promptCT)
    getattr(ws,'import')(nonpromptCT)
    getattr(ws,'import')(backgroundCT)
    getattr(ws,'import')(backgroundCTL)
    getattr(ws,'import')(backgroundCTR)

    massConfig = 'SIMUL::MPdf(ctauRegion,'
    ctConfig = 'SIMUL::LPdf(massRegion,'
    
    if options.doPrompt:
        massConfig += 'prompt=promptMass,'
        ctConfig += 'signal=promptCTau,'
    if options.doNonPrompt:
        massConfig += 'nonPrompt=promptMass'
    if options.doBackground:               
        ctConfig += 'leftMassSideBand=backgroundCTauL,rightMassSideBand=backgroundCTauR'

    massConfig += ')'
    ctConfig += ')'
    
    #simultaneous
    ws.factory(massConfig)
    ws.factory(ctConfig)
Esempio n. 58
0
binWidth = 50.  #GeV

# DAS_EX_2.1
# Define a RooRealVar object for the ST variable
st = RooRealVar("st", "st", ranges["fit", "lo"], ranges["fit", "hi"])

############################################
# Get data and models
############################################

#
print "Reading Files"
# DAS_EX_2.2
# Read data from file into RooDataSet using the RooDataSet.read() method.
#rdata = RooDataSet.add(files["dat"], RooArgList(st))
rdata = RooDataSet.read(files["dat"], RooArgList(st))

###################################
# Set up fit PDFs with information
# from fitFuncs dictionary
###################################

# Declare a few dictionaries
pdfs = {}
pars = {}
aset = {}

for func in ["f2", "f1", "f3"]:

    # DAS_EX_2.3
    # Define and initialize (with your ST RooRealVar) a RooArgSet for use in the pdf
Esempio n. 59
0
    def stackedPlot(self, var, logy = False, pdfName = None, Silent = False):
        if not pdfName:
            pdfName = 'total'

        xvar = self.ws.var(var)
        nbins = xvar.getBins()
        # if hasattr(self.pars, 'plotRanges') and not xvar.hasRange('plotRange'):
        #     xvar.setRange('plotRange', self.pars.plotRanges[var][1],
        #                   self.pars.plotRanges[var][2])
        #     xvar.setBins(self.pars.plotRanges[var][0], 'plotBins')
        # elif not xvar.hasRange('plotRange'):
        #     xvar.setRange('plotRange', xvar.getMin(), xvar.getMax())
        #     xvar.setBins(nbins, 'plotBins')

        sframe = xvar.frame(RooFit.Range('plotRange'),
                            RooFit.Bins(xvar.getBins('plotBins')))
        sframe.SetName("%s_stacked" % var)
        pdf = self.ws.pdf(pdfName)

        if isinstance(pdf, RooAddPdf):
            compList = RooArgList(pdf.pdfList())
        else:
            compList = None

        data = self.ws.data('data_obs')
        nexp = pdf.expectedEvents(self.ws.set('obsSet'))

        if not Silent:
            print pdf.GetName(),'expected: %.0f' % (nexp)
            print 'data events: %.0f' % (data.sumEntries())

        if nexp < 1:
            nexp = data.sumEntries()
        theComponents = [] 
        if self.pars.includeSignal:
            theComponents += self.pars.signals
        theComponents += self.pars.backgrounds
        data.plotOn(sframe, RooFit.Invisible(),
                    RooFit.Binning('plotBins'))
        # dataHist = RooAbsData.createHistogram(data,'dataHist_%s' % var, xvar,
        #                                       RooFit.Binning('%sBinning' % var))
        # #dataHist.Scale(1., 'width')
        # invData = RooHist(dataHist, 1., 1, RooAbsData.SumW2, 1.0, False)
        # #invData.Print('v')
        # sframe.addPlotable(invData, 'pe', True, True)
        for (idx,component) in enumerate(theComponents):
            if not Silent:
                print 'plotting',component,'...',
            if hasattr(self.pars, '%sPlotting' % (component)):
                plotCharacteristics = getattr(self.pars, '%sPlotting' % \
                                                  (component))
            else:
                plotCharacteristics = {'color' : colorwheel[idx%6],
                                       'title' : component }

            compCmd = RooCmdArg.none()
            if compList:
                compSet = RooArgSet(compList)
                if compSet.getSize() > 0:
                    compCmd = RooFit.Components(compSet)
                removals = compList.selectByName('%s*' % component)
                compList.remove(removals)

            if not Silent:
                print 'events', self.ws.function('f_%s_norm' % component).getVal()
                sys.stdout.flush()
            if abs(self.ws.function('f_%s_norm' % component).getVal()) >= 1.:
                pdf.plotOn(sframe, #RooFit.ProjWData(data),
                           RooFit.DrawOption('LF'), RooFit.FillStyle(1001),
                           RooFit.FillColor(plotCharacteristics['color']),
                           RooFit.LineColor(plotCharacteristics['color']),
                           RooFit.VLines(),
                           RooFit.Range('plotRange'),
                           RooFit.NormRange('plotRange'),
                           RooFit.Normalization(nexp, RooAbsReal.NumEvent),
                           compCmd
                           )
                tmpCurve = sframe.getCurve()
                tmpCurve.SetName(component)
                tmpCurve.SetTitle(plotCharacteristics['title'])
                if 'visible' in plotCharacteristics:
                    sframe.setInvisible(component, 
                                        plotCharacteristics['visible'])

        data.plotOn(sframe, RooFit.Name('theData'),
                    RooFit.Binning('plotBins'))
        sframe.getHist('theData').SetTitle('data')
        # theData = RooHist(dataHist, 1., 1, RooAbsData.SumW2, 1.0, True)
        # theData.SetName('theData')
        # theData.SetTitle('data')
        # sframe.addPlotable(theData, 'pe')

        if (logy):
            sframe.SetMinimum(0.01)
            sframe.SetMaximum(1.0e6)
        else:
            sframe.SetMaximum(sframe.GetMaximum()*1.35)
            pass

        excluded = (var in self.pars.exclude)
        bname = var
        if not excluded:
            for v in self.pars.exclude:
                if hasattr(self.pars, 'varNames') and \
                       (self.pars.varNames[v] == var):
                    excluded = True
                    bname = v
        if excluded:
            blinder = TBox(self.pars.exclude[bname][0], sframe.GetMinimum(),
                           self.pars.exclude[bname][1], sframe.GetMaximum())
            # blinder.SetName('blinder')
            # blinder.SetTitle('signal region')
            blinder.SetFillColor(kBlack)
            if self.pars.blind:  
                blinder.SetFillStyle(1001)
            else:
                blinder.SetFillStyle(0)
            blinder.SetLineStyle(2)
            sframe.addObject(blinder)
        elif self.pars.blind:
            if not Silent:
                print "blind but can't find exclusion region for", var
                print 'excluded',excluded,self.pars.exclude
                print 'hiding data points'
            sframe.setInvisible('theData', True)
        else:
            sframe.setInvisible('theData', False)

        #sframe.GetYaxis().SetTitle('Events / GeV')
        # dataHist.IsA().Destructor(dataHist)
        if not Silent:
            print

        xvar.setBins(nbins)

        return sframe
Esempio n. 60
0
def PeakFit_likelihood(Likelihood_cut: pd.DataFrame,
                       mass_energy: pd.DataFrame,
                       cutval,
                       plots=True,
                       constant_mean=True,
                       constant_width=True,
                       classifier_name='Likelihood',
                       CB=True,
                       Gauss=False,
                       bkg_comb=True,
                       bkg_exp=False,
                       bkg_cheb=False):
    print('Starting fit...')
    matplotlib.use('Agg')
    # Check if we have mass in MeV or GeV
    if np.mean(mass_energy) > 1000:
        normalization_mass = 1000
    else:
        normalization_mass = 1
    sns.set_style("whitegrid")  # White background on plot
    prediction = Likelihood_cut  # rename to prediction
    # Set range
    mZmin = 60.0
    mZmax = 130.0
    # Number of bins
    NbinsZmass = 100

    #Initiate the mass variable
    m_ee = ROOT.RooRealVar("m_ee", "Invariant mass (GeV/c^{2})", mZmin, mZmax)
    m_ee.setRange("MC_mZfit_range", mZmin, mZmax)

    # =============================================================================
    #    fit signal
    # =============================================================================

    # Make a mask in the signal range. Prediction is 0 or 1, so above 0.5 is signal
    mask_mass = (mass_energy / normalization_mass > mZmin) & (
        mass_energy / normalization_mass < mZmax) & (prediction > 0.5)
    Z_mass_signal = np.array(mass_energy[mask_mass] / normalization_mass)
    #Make np.array

    # Initiate 1D histogram
    h_mZ_all = ROOT.TH1D("h_mZ_all", "Histogram of Z mass", NbinsZmass, mZmin,
                         mZmax)

    for isample in range(Z_mass_signal.shape[0]):
        score = Z_mass_signal[isample]
        h_mZ_all.Fill(score)

    # Constructs histogram with m_ee as argument from the 1d histogram h_mZ_all
    mc_Zee_mZ = ROOT.RooDataHist("mc_Zee_mZ", "Dataset with Zee m_ee",
                                 RooArgList(m_ee), h_mZ_all)

    # Define variables for the fits.
    # BW: Breit-Wigner. CB: Crystal-Ball
    meanBW = ROOT.RooRealVar("meanBW", "meanBW", 91.1876, 60.0, 120.0)
    #91.1876
    meanBW.setConstant(True)
    # this is a theoretical constant

    sigmaBW = ROOT.RooRealVar("sigmaBW", "sigmaBW", 2.4952, 2.0, 20.0)
    #2.4952
    sigmaBW.setConstant(True)
    # this is a theoretical constant
    # if constant_mean:

    func_BW = ROOT.RooBreitWigner("func_BW", "Breit-Wigner", m_ee, meanBW,
                                  sigmaBW)
    # Make the function from the constants

    # Crystal ball
    if CB:
        meanCB = RooRealVar("meanCB", "meanCB", -0.0716, -10.0, 10.0)
        # meanCB.setConstant(True) #if commented out, it can float between the minimum and maximum
        sigmaCB = RooRealVar("sigmaCB", "sigmaCB", 0.193, 0, 15)
        # sigmaCB.setConstant(True)
        alphaCB = RooRealVar("alphaCB", "alphaCB", 1.58, 0.0, 10.0)
        # alphaCB.setConstant(True)
        nCB = RooRealVar("nCB", "nCB", 0.886, -10, 50.0)
        # nCB.setConstant(True)
        func_sig_CB = RooCBShape("func_CB", "Crystal Ball", m_ee, meanCB,
                                 sigmaCB, alphaCB, nCB)
        # Define Crystal-Ball function
    # Gaussian
    elif Gauss:  # Use Gaussian if True in function call
        meanGA = RooRealVar("meanGA", "meanGA", 10.0, -10.0, 10.0)
        sigmaGA = RooRealVar("sigmaGA", "sigmaGA", 3.0, 0.01, 10.0)
        if constant_width:
            sigmaGA.setConstant(True)

        nGA = RooRealVar("nGA", "nGA", 1.5, 0.0, 20.0)
        func_GA = RooGaussian("func_GA", "Gaussian", m_ee, meanGA, sigmaGA)
        #, nGA);

    if CB:  # Convolute Breit-Wigner and Crystal-Ball
        print("Convoluting a Crystal-Ball and Breit-Wigner for signal")
        func_BWxCB_unextended = RooFFTConvPdf("func_BWxCB_unextended",
                                              "Breit-Wigner (X) Crystal Ball",
                                              m_ee, func_BW, func_sig_CB)

    elif Gauss:  # Convolute Breit-Wigner and Gauss
        print("Convoluting a Gauss and Breit-Wigner for signal")
        func_BWxCB_unextended = RooFFTConvPdf("func_BWxCB_unextended",
                                              "Breit-Wigner (X) Gaussian",
                                              m_ee, func_BW, func_GA)

    else:  # only Breit-Wigner fit on the signal
        print("Fitting only with Breit-Wigner for signal")
        func_BWxCB_unextended = func_BW

    m_ee.setRange("MC_mZfit_range", 85, 97)
    # Set the fit range for the signal

    nsig = RooRealVar("ntotal", "ntotal", 1000, 0, 10e6)
    # Define the variable for the number of signal
    func_BWxCB = ROOT.RooExtendPdf("signal_func_Zee", "signal_func_Zee",
                                   func_BWxCB_unextended, nsig)
    # Adding the nsig term to the pdf

    func_BWxCB.fitTo(mc_Zee_mZ, RooFit.Range("MC_mZfit_range"))
    # Fit the signal

    if plots:  # Plots the signal using the function "root_plot" defined above
        mc_Zee_signal = root_plot(m_ee=m_ee,
                                  distribution=mc_Zee_mZ,
                                  fit=func_BWxCB,
                                  mZmin=mZmin,
                                  mZmax=mZmax,
                                  title=f'signal for cut {cutval}')
#cut {cutval}
# =============================================================================
#    background
# =============================================================================

    nbkg = RooRealVar("nbkg", "nbkg", 1000, 0, 10e6)
    # Define the variable for the number of background

    #if True:
    m_ee.setRange("MC_mZfit_range", mZmin, mZmax)
    # Set range for fit as defined in the beginning
    c_bkg_mZ = ROOT.TCanvas("c_bkg_mZ", "", 0, 0, 1000, 500)
    # Make the canvas for plotting

    Z_mass_background = np.array(mass_energy[mask_mass] / normalization_mass)
    # Mask for background
    h_mZWenu_all = ROOT.TH1D("h_mZ_all", "Histogram of Z mass", NbinsZmass,
                             mZmin, mZmax)
    # Initiate 1D histogram

    for isample in range(Z_mass_background.shape[0]):
        score = Z_mass_background[isample]
        h_mZWenu_all.Fill(score)

    # Create the lin + exponential fit
    lam = RooRealVar("lambda", "Exponent", -0.04, -5.0, 0.0)
    func_expo = ROOT.RooExponential("func_expo", "Exponential PDF", m_ee, lam)

    #coef_pol1 =  RooRealVar("coef_pol1", "Slope of background", 0.0, -10.0, 10.0);
    #func_pol1 = ROOT.RooPolynomial("func_pol1", "Linear PDF", m_ee, RooArgList(coef_pol1));

    # Create Chebychev polymonial
    a0 = RooRealVar("a0", "a0", -0.4, -5.0, 5.0)
    a1 = RooRealVar("a1", "a1", -0.03, -5.0, 5.0)
    a2 = RooRealVar("a2", "a2", 0.02, -5.0, 5.0)
    a3 = RooRealVar("a3", "a3", 0.02, -5.0, 5.0)

    # Polynomials with different order
    func_Cpol1 = RooChebychev("func_Cpol1",
                              "Chebychev polynomial of 1st order", m_ee,
                              RooArgList(a0, a1))
    func_Cpol2 = RooChebychev("func_Cpol2",
                              "Chebychev polynomial of 2nd order", m_ee,
                              RooArgList(a0, a1, a2))
    func_Cpol3 = RooChebychev("func_Cpol3",
                              "Chebychev polynomial of 3rd order", m_ee,
                              RooArgList(a0, a1, a2, a3))
    f_exp_mZ = RooRealVar("N_lin_mZ", "CLinear fraction", 0.50, 0, 1)

    m_ee.setRange("low", 60, 70)
    m_ee.setRange("high", 110, 130)

    # Adding exponential and Chebychev if comb:
    if bkg_comb:
        func_ExpLin_mZ_unextended = ROOT.RooAddPdf(
            "func_ExpLin_mZ_unextended", "Exponential and Linear PDF",
            RooArgList(func_Cpol3, func_expo), RooArgList(f_exp_mZ))
    elif bkg_exp:
        func_ExpLin_mZ_unextended = func_expo
    elif bkg_cheb:
        func_ExpLin_mZ_unextended = func_Cpol3
    else:
        print("No background fit called. Exiting")
        return None

    func_ExpLin_mZ = ROOT.RooExtendPdf("func_ExpLin_mZ", "func_ExpLin_mZ",
                                       func_ExpLin_mZ_unextended, nbkg)
    # Adding the nbkg term to the pdf
    # Constructs histogram with m_ee as argument from the 1d histogram h_mZ_all
    mc_Wenu_mZ = ROOT.RooDataHist("mc_Zee_mZ", "Dataset with Zee m_ee",
                                  RooArgList(m_ee), h_mZWenu_all)
    func_ExpLin_mZ.fitTo(mc_Wenu_mZ, RooFit.Range("MC_mZfit_range"))
    #ROOT.RooFit.Range("low,high")); # Fits background

    #Plotting background
    residue = root_plot(m_ee=m_ee,
                        distribution=mc_Wenu_mZ,
                        fit=func_ExpLin_mZ,
                        mZmin=mZmin,
                        mZmax=mZmax,
                        title=f'Background for cut {cutval}')
    #
    # =============================================================================
    #    Combining signal and background
    # =============================================================================

    m_ee.setRange("MC_mZfit_range", mZmin, mZmax)

    Z_mass = np.array(mass_energy[mask_mass] / normalization_mass)
    h_mZWenu = ROOT.TH1D("h_mZ_all", "Histogram of Z mass", NbinsZmass, mZmin,
                         mZmax)

    for isample in range(Z_mass.shape[0]):
        score = Z_mass[isample]
        h_mZWenu.Fill(score)

    # Constructs histogram with m_ee as argument from the 1d hist ogram h_mZ_all
    mc_ZeeWenu_mZ = ROOT.RooDataHist("mc_Zee_mZ", "Dataset with Zee m_ee",
                                     RooArgList(m_ee), h_mZWenu)

    ## Fits the data and returns the fraction of background
    f_bkg_mZ = RooRealVar("f_bkg_mZ", "Signal fraction",
                          nbkg.getVal() / nsig.getVal(), 0.0, 1)

    ## Combining the signal and background fits
    func_SigBkg_mZ_unextended = ROOT.RooAddPdf(
        "func_SigBkg_mZ", "Signal and Background PDF",
        RooArgList(func_ExpLin_mZ_unextended, func_BWxCB_unextended),
        RooArgList(f_bkg_mZ))
    # func_SigBkg_mZ_unextended = func_BWxCB_unextended;#ROOT.RooAddPdf("func_SigBkg_mZ", "Signal and Background PDF", RooArgList(func_BWxCB_unextended, func_BWxCB_unextended), RooArgList(f_bkg_mZ));
    ntotal = RooRealVar("ntotal", "ntotal", 10000, 0, 10e6)
    func_SigBkg_mZ = ROOT.RooExtendPdf("func_ExpLin_mZ", "func_ExpLin_mZ",
                                       func_SigBkg_mZ_unextended, ntotal)

    func_SigBkg_mZ.fitTo(mc_ZeeWenu_mZ)
    # Fits the full data set

    if plots:
        mc_ZeeWenu_mZ_resid = root_plot(m_ee=m_ee,
                                        distribution=mc_ZeeWenu_mZ,
                                        fit=func_SigBkg_mZ,
                                        mZmin=mZmin,
                                        mZmax=mZmax,
                                        title=f'Bkg+Sig for cut {cutval}')

    # Baseline ntotal = 41231 (Data)
    # fraction 0.9333
    # Baseline ntotal = 74747 (MC)
    # fraction 0.4427
    # Malte script len(Z_mass)
    bkg = len(Z_mass) * f_bkg_mZ.getVal()
    sig = len(Z_mass) * (1 - f_bkg_mZ.getVal())
    print(f_bkg_mZ.getVal())
    #DATA
    #BL_sig = 41231*(1-0.9333) # BL = baseline, the number is the fraction of bkg in baseline
    #BL_bkg = 41231*0.9333     # BL = baseline

    # DATA OS
    # BL_sig = 22276 * (1-0.853) # BL = baseline, the number is the fraction of bkg in baseline
    # BL_bkg = 22276 * 0.853    # BL = baseline

    # DATA SS
    # BL_sig = 18925 * (1-0.993552)#74747 * (1-0.4427)#41054
    # BL_bkg = 18925 - BL_sig

    #MC OS
    # exp
    BL_sig = 46547 * (1 - 0.0350)  #74747 * (1-0.4427)#41054
    BL_bkg = 46547 * 0.0350

    #comb
    #BL_sig = 74747*(1-0.4427) # BL = baseline, the number is the fraction of bkg in baseline
    #BL_bkg = 74747*0.4427     # BL = baseline

    bkg_ratio = bkg / BL_bkg
    sig_ratio = sig / BL_sig

    max_residue = max(abs(mc_ZeeWenu_mZ_resid.getYAxisMax()),
                      abs(mc_ZeeWenu_mZ_resid.getYAxisMin()))
    print(max_residue)
    print(bkg_ratio)
    print(sig_ratio)

    if (bkg_ratio < 1.009) & (sig_ratio < 1.009) & (abs(
            mc_ZeeWenu_mZ_resid.getYAxisMin()) < 4) & (abs(
                mc_ZeeWenu_mZ_resid.getYAxisMax()) < 4):
        # input('....')

        return BL_sig, BL_bkg, sig_ratio, bkg_ratio  #max_residue, ntotal.getVal(), nsig.getVal(), nbkg.getVal()return sigmaCB if CB else sigmaGA #sig_ratio, sigma_sig, bkg_ratio, sigma_bkg
    else:
        return 0, 0, 0, 0