Example #1
0
 def fit(self, inputFitFile=None):
     """Fits the razor pdf to the data"""
     if inputFitFile is None:
         self.setDefaultFitParams()
     else:
         self.loadFitParamsFromFile(inputFitFile)
     extRazorPdf = self.workspace.pdf('extRazorPdf')
     datahist = self.workspace.data('data_obs')
     self.sideband = convertSideband(self.fitRegion, self.workspace, 
             self.x, self.y, self.z)
     result = binnedFit(extRazorPdf, datahist, self.sideband,
             box=self.analysis.region, w=self.workspace)
     result.Print('v')
     self.addToWorkspace(result, tobject=True)
Example #2
0
 def fit(self, inputFitFile=None):
     """Fits the razor pdf to the data"""
     if inputFitFile is None:
         self.setDefaultFitParams()
     else:
         self.loadFitParamsFromFile(inputFitFile)
     extRazorPdf = self.workspace.pdf('extRazorPdf')
     datahist = self.workspace.data('data_obs')
     self.sideband = convertSideband(self.fitRegion, self.workspace, self.x,
                                     self.y, self.z)
     result = binnedFit(extRazorPdf,
                        datahist,
                        self.sideband,
                        box=self.analysis.region,
                        w=self.workspace)
     result.Print('v')
     self.addToWorkspace(result, tobject=True)
Example #3
0
    y = array('d', cfg.getBinning(box)[1])  # Rsq binning
    z = array('d', cfg.getBinning(box)[2])  # nBtag binning
    nBins = (len(x) - 1) * (len(y) - 1) * (len(z) - 1)

    xFine = array('d',
                  [x[0] + i * (x[-1] - x[0]) / 100.
                   for i in range(0, 101)])  # MR binning fine
    yFine = array('d',
                  [y[0] + i * (y[-1] - y[0]) / 100.
                   for i in range(0, 101)])  # Rsq binning fine
    zFine = array('d', cfg.getBinning(box)[2])  # nBtag binning fine
    nBinsFine = (len(xFine) - 1) * (len(yFine) - 1) * (len(zFine) - 1)

    th1x = w.var('th1x')

    sideband = convertSideband(fitRegion, w, x, y, z)
    plotband = convertSideband(plotRegion, w, x, y, z)

    myTH1 = convertDataset2TH1(data, cfg, box, w, options.useWeight)

    signalDs = None
    doSignalInj = (options.signalFileName != "None") and (options.r > -1)
    if doSignalInj:
        sigRootFile = rt.TFile(options.signalFileName)
        #sigWorkspace = sigRootFile.Get('w'+box)
        #signalDs = sigWorkspace.data('RMRTree')
        model = options.signalFileName.split('.root')[0].split('-')[1].split(
            '_')[0]
        massPoint = '_'.join(
            options.signalFileName.split('.root')[0].split('_')[1:3])
        #sigTH1 = convertDataset2TH1(signalDs, cfg, box, w,"signal")
Example #4
0
def runToys(w, options, cfg, seed):

    setStyle()
    rt.RooRandom.randomGenerator().SetSeed(seed)

    extRazorPdf = w.pdf('extRazorPdf')
    dataHist = w.data("data_obs")
    if w.obj("fitresult_extRazorPdf_data_obs") != None:
        fr = w.obj("fitresult_extRazorPdf_data_obs")
    elif w.obj("nll_extRazorPdf_data_obs") != None:
        fr = w.obj("nll_extRazorPdf_data_obs")
    elif w.obj("fitresult_extRazorPdf_data_obs_with_constr") != None:
        fr = w.obj("fitresult_extRazorPdf_data_obs_with_constr")
    elif w.obj("nll_extRazorPdf_data_obs_with_constr") != None:
        fr = w.obj("nll_extRazorPdf_data_obs_with_constr")

    fr.Print("V")
    if options.r > -1:
        extSpBPdf = w.pdf('extSpBPdf')

    #nll = w.function('nll_extRazorPdf_data_obs')
    th1x = w.var("th1x")

    params = extRazorPdf.getParameters(dataHist)
    paramsToRemove = []
    for p in rootTools.RootIterator.RootIterator(params):
        if p.isConstant(): paramsToRemove.append(p)

    [params.remove(p) for p in paramsToRemove]
    paramNames = [
        p.GetName() for p in rootTools.RootIterator.RootIterator(params)
    ]
    paramNames.sort()
    if options.r > -1: paramNames.append('r')

    x = array('d', cfg.getBinning(options.box)[0])  # MR binning
    y = array('d', cfg.getBinning(options.box)[1])  # Rsq binning
    z = array('d', cfg.getBinning(options.box)[2])  # nBtag binning
    nBins = (len(x) - 1) * (len(y) - 1) * (len(z) - 1)

    th1x.setBins(nBins)

    if seed > -1:
        output = rt.TFile.Open(
            options.outDir + '/genfittoys_Freq_s%i_%s.root' %
            (seed, options.box), 'recreate')
    else:
        output = rt.TFile.Open(
            options.outDir + '/genfittoys_Freq_%s.root' % (options.box),
            'recreate')

    output.cd()
    myTree = rt.TTree("myTree", "myTree")

    s1 = getTree(myTree, paramNames, nBins, options.box, z)

    pSet = fr.floatParsFinal()
    for p in rootTools.RootIterator.RootIterator(pSet):
        w.var(p.GetName()).setVal(p.getVal())
        w.var(p.GetName()).setError(p.getError())
        asimov = extRazorPdf.generateBinned(rt.RooArgSet(th1x),
                                            rt.RooFit.Name('true'),
                                            rt.RooFit.Asimov())

        value = setattr(
            s1, 'toy_num',
            -1)  #save the toy number (for differentiating from true pdf)
        iBinX = -1
        for i in range(1, len(x)):
            for j in range(1, len(y)):
                for k in range(1, len(z)):
                    iBinX += 1
                    th1x.setVal(iBinX + 0.5)
                    expected = extRazorPdf.getValV(
                        rt.RooArgSet(th1x)) * extRazorPdf.expectedEvents(
                            rt.RooArgSet(th1x))
                    toy = float(asimov.weight(rt.RooArgSet(th1x)))
                    value = setattr(s1, 'b%i_ff' % iBinX,
                                    expected)  #save predicted fit yield
                    value = setattr(s1, 'b%i_sf' % iBinX,
                                    expected)  #save predicted fit yield
                    value = setattr(s1, 'b%i_toy' % iBinX,
                                    toy)  #save toy yield

    myTree.Fill()
    iToy = 0

    widgets = [
        'Running Freq toys ',
        Percentage(), ' ',
        Bar(marker=RotatingMarker()), ' ',
        ETA(), ' ',
        FileTransferSpeed()
    ]
    pbar = ProgressBar(widgets=widgets, max_value=options.nToys).start()
    while iToy < options.nToys:
        pSet = fr.floatParsFinal()
        for p in rootTools.RootIterator.RootIterator(pSet):
            w.var(p.GetName()).setVal(p.getVal())
            w.var(p.GetName()).setError(p.getError())
            if 'Ntot' in p.GetName():
                w.var(p.GetName()).setVal(options.scaleFactor * p.getVal())
            #print "%s = %f +- %f"%(p.GetName(),p.getVal(),p.getError())

        #print "good pars"
        errorCountBefore = rt.RooMsgService.instance().errorCount()

        asimov = extRazorPdf.generateBinned(rt.RooArgSet(th1x),
                                            rt.RooFit.Name('toy'))

        errorCountAfter = rt.RooMsgService.instance().errorCount()
        if errorCountAfter > errorCountBefore:
            #print "can't generate toy=%i"%iToy
            continue

        #print "SUCCESS: generated toy=%i"%iToy

        pSetSave = pSet
        migrad_status_sf = -1
        hesse_status_sf = -1
        minos_status_sf = -1
        migrad_status_ff = -1
        hesse_status_ff = -1
        minos_status_ff = -1

        sideband = convertSideband('LowMR,LowRsq', w, x, y, z)

        nll_func_toy_ff = extRazorPdf.createNLL(asimov,
                                                rt.RooFit.Extended(True))
        nll_func_toy_sf = extRazorPdf.createNLL(asimov,
                                                rt.RooFit.Extended(True),
                                                rt.RooFit.Range(sideband))
        m = rt.RooMinimizer(nll_func_toy_ff)
        m.setStrategy(0)
        m.setPrintLevel(-1)
        m.setPrintEvalErrors(-1)
        migrad_status_ff = m.minimize('Minuit2', 'migrad')
        #hesse_status_ff = m.minimize('Minuit2','hesse')
        fr_ff = m.save()
        covQual_ff = fr_ff.covQual()

        value = setattr(
            s1, 'toy_num',
            iToy)  #save the toy number (for differentiating from true pdf)
        value = setattr(s1, 'migrad_ff',
                        migrad_status_ff)  #save migrad status full fit
        value = setattr(s1, 'hesse_ff',
                        hesse_status_ff)  #save hesse status full fit
        value = setattr(s1, 'covQual_ff', covQual_ff)  #save cov qual full fit
        iBinX = -1
        for i in range(1, len(x)):
            for j in range(1, len(y)):
                for k in range(1, len(z)):
                    iBinX += 1
                    th1x.setVal(iBinX + 0.5)
                    expected = extRazorPdf.getValV(
                        rt.RooArgSet(th1x)) * extRazorPdf.expectedEvents(
                            rt.RooArgSet(th1x))
                    toy = float(asimov.weight(rt.RooArgSet(th1x)))
                    value = setattr(s1, 'b%i_ff' % iBinX,
                                    expected)  #save predicted full fit yield
                    value = setattr(s1, 'b%i_toy' % iBinX,
                                    toy)  #save toy yield

        # save full fit parameters
        for p in rootTools.RootIterator.RootIterator(fr_ff.floatParsFinal()):
            value = setattr(s1, p.GetName() + "_ff", p.getVal())
            value = setattr(s1, p.GetName() + "_ff_error", p.getError())

        m = rt.RooMinimizer(nll_func_toy_sf)
        m.setStrategy(0)
        m.setPrintLevel(-1)
        m.setPrintEvalErrors(-1)
        migrad_status_sf = m.minimize('Minuit2', 'migrad')
        #hesse_status_sf = m.minimize('Minuit2','hesse')
        fr_sf = m.save()
        covQual_sf = fr_sf.covQual()

        value = setattr(s1, 'migrad_sf',
                        migrad_status_sf)  #save migrad status sideband fit
        value = setattr(s1, 'hesse_sf',
                        hesse_status_sf)  #save hesse status sideband fit
        value = setattr(s1, 'covQual_sf',
                        covQual_sf)  #save cov qual sideband fit
        iBinX = -1
        for i in range(1, len(x)):
            for j in range(1, len(y)):
                for k in range(1, len(z)):
                    iBinX += 1
                    th1x.setVal(iBinX + 0.5)
                    expected = extRazorPdf.getValV(
                        rt.RooArgSet(th1x)) * extRazorPdf.expectedEvents(
                            rt.RooArgSet(th1x))
                    value = setattr(
                        s1, 'b%i_sf' % iBinX,
                        expected)  #save predicted sideband fit yield

        # save sideband fit parameters
        for p in rootTools.RootIterator.RootIterator(fr_sf.floatParsFinal()):
            value = setattr(s1, p.GetName() + "_sf", p.getVal())
            value = setattr(s1, p.GetName() + "_sf_error", p.getError())

        pbar.update(iToy)
        myTree.Fill()
        iToy += 1
    rt.RooMsgService.instance().reset()
    pbar.finish()

    w.Print('v')
    output.cd()
    myTree.Write()
    w.Write()
    output.Close()
    return output.GetName()
Example #5
0
    def plot(self, filename=None, unblind=False, toysFile=None, sysFile=None):
        """Plots the fit results"""
        options = self.getPlottingOptions()
        if unblind:
            plotRegion = 'Full'
        else:
            plotRegion = self.fitRegion
        if filename is None:
            filename = self.filename.replace('.root', '_Plots.root')
        f = rt.TFile(filename, 'UPDATE')
        toyTree = self.getToyTree(toysFile)
        sysTree = self.getToyTree(sysFile)
        if toyTree is not None and sysTree is not None:
            dirName = "WithToys"
            computeErrors = True
        else:
            dirName = "BeforeToys"
            computeErrors = False
        tdirectory = f.GetDirectory(dirName)
        if tdirectory == None:
            f.mkdir(dirName)
            tdirectory = f.GetDirectory(dirName)
        c = rt.TCanvas('c', 'c', 500, 400)
        rt.SetOwnership(c, False)
        rt.TH1D.SetDefaultSumw2()
        rt.TH2D.SetDefaultSumw2()
        rt.TH3D.SetDefaultSumw2()
        plotband = convertSideband(plotRegion, self.workspace, self.x, self.y,
                                   self.z)

        # Get the 1D and 2D histograms for each b-tag bin
        h_data_nBtagRsqMR, h_nBtagRsqMR = self.get3DFitHistos(plotband)
        h_data_MR, h_data_Rsq, h_data_RsqMR = make3DHistProjections(
            h_data_nBtagRsqMR)
        h_MR, h_Rsq, h_RsqMR = make3DHistProjections(h_nBtagRsqMR)
        if computeErrors:
            h_MR = getErrors1D(h_MR, h_data_MR, sysTree, options, "x", 0,
                               len(self.x) - 1, 0,
                               len(self.y) - 1, 0,
                               len(self.z) - 1, self.x, self.y, self.z)
            h_Rsq = getErrors1D(h_Rsq, h_data_Rsq, sysTree, options, "y", 0,
                                len(self.x) - 1, 0,
                                len(self.y) - 1, 0,
                                len(self.z) - 1, self.x, self.y, self.z)
            h_RsqMR = getErrors2D(h_RsqMR, h_data_RsqMR, sysTree, options,
                                  "yx", 0,
                                  len(self.x) - 1, 0,
                                  len(self.y) - 1, 0,
                                  len(self.z) - 1, self.x, self.y, self.z)
            h_nBtagRsqMR = getErrors3D(h_nBtagRsqMR, h_data_nBtagRsqMR,
                                       sysTree, options, "zyx", 0,
                                       len(self.x) - 1, 0,
                                       len(self.y) - 1, 0,
                                       len(self.z) - 1, self.x, self.y, self.z)
        for h in [
                h_data_MR, h_data_Rsq, h_data_RsqMR, h_data_nBtagRsqMR, h_MR,
                h_Rsq, h_RsqMR, h_nBtagRsqMR
        ]:
            tdirectory.cd()
            h.Write()
        if len(self.z) > 1:
            h_MR_components = []
            h_Rsq_components = []
            h_RsqMR_components = []
            h_data_RsqMR_components = []
            h_sig_RsqMR_components = []
            h_th1x_components = []
            h_data_th1x_components = []
            h_sig_th1x_components = []
            h_labels = []
            h_colors = [
                rt.kOrange, rt.kViolet, rt.kRed, rt.kGreen, rt.kGray + 2
            ]
            for k in range(1, len(self.z)):
                h_MR_components.append(
                    h_nBtagRsqMR.ProjectionX("MR_%ibtag" % self.z[k - 1], 0,
                                             -1, k, k, ""))
                h_Rsq_components.append(
                    h_nBtagRsqMR.ProjectionY("Rsq_%ibtag" % self.z[k - 1], 0,
                                             -1, k, k, ""))
                h_nBtagRsqMR.GetZaxis().SetRange(k, k)
                h_RsqMR_components.append(
                    h_nBtagRsqMR.Project3D("%ibtag_yx" % self.z[k - 1]))
                h_data_nBtagRsqMR.GetZaxis().SetRange(k, k)
                h_data_RsqMR_components.append(
                    h_data_nBtagRsqMR.Project3D("%ibtag_yx" % self.z[k - 1]))
                if computeErrors:
                    h_RsqMR_components[-1] = getErrors2D(
                        h_RsqMR_components[-1], h_data_RsqMR_components[-1],
                        sysTree, options, "yx", 0,
                        len(self.x) - 1, 0,
                        len(self.y) - 1, k, k, self.x, self.y, self.z)
                h_th1x_components.append(
                    get1DHistoFrom2D(h_RsqMR_components[-1], self.x, self.y,
                                     'h_th1x_%ibtag' % (self.z[k - 1])))
                h_data_th1x_components.append(
                    get1DHistoFrom2D(h_data_RsqMR_components[-1], self.x,
                                     self.y,
                                     'h_th1x_data_%ibtag' % (self.z[k - 1])))
                if self.z[k - 1] == 3 and self.z[-1] == 4:
                    h_labels.append("#geq %i b-tag" % self.z[k - 1])
                elif self.z[k - 1] == 1 and self.z[-1] == 4 and len(
                        self.z) == 2:
                    h_labels.append("#geq %i b-tag" % self.z[k - 1])
                else:
                    h_labels.append("%i b-tag" % self.z[k - 1])

        # Create the nsigma histograms
        h_RsqMR_statnsigma_components = []
        h_RsqMR_nsigma_components = []
        if len(self.z) > 1:
            for k in range(1, len(self.z)):
                h_RsqMR_statnsigma_components.append(
                    getStatNSigmaHist(
                        h_RsqMR_components[k - 1],
                        h_data_RsqMR_components[k - 1],
                        "h_RsqMR_statnsigma_%ibtag" % self.z[k - 1]))
                h_RsqMR_nsigma_btag = h_RsqMR.Clone("h_RsqMR_nsigma_%ibtag" %
                                                    self.z[k - 1])
                if computeErrors:
                    h_RsqMR_nsigma_btag = getNsigma2D(
                        h_RsqMR_nsigma_btag, h_data_RsqMR_components[k - 1],
                        toyTree, options, "yx", 0,
                        len(self.x) - 1, 0,
                        len(self.y) - 1, k, k, self.x, self.y, self.z)
                    self.blindSideband(h_RsqMR_nsigma_btag, plotRegion)
                    h_RsqMR_nsigma_components.append(h_RsqMR_nsigma_btag)

        # Print everything out to pdf files
        btagLabel = getBtagLabel(self.z)
        lumiLabel = "%.1f fb^{-1} (13 TeV)" % (self.analysis.lumi / 1000.)
        boxLabel = "razor %s %s %s Fit" % (self.analysis.region, btagLabel,
                                           self.fitRegion.replace(
                                               'LowMR,LowRsq', 'Sideband'))
        plotLabel = ""
        eventsLabel = "Events"
        sidebandFit = self.getSidebandMax()
        for h in h_RsqMR_components:
            tdirectory.cd()
            h.Write()
        print1DProj(c, tdirectory, h_MR, h_data_MR,
                    self.dirname + "/h_MR_%s.pdf" % self.analysis.region,
                    "M_{R} [GeV]", eventsLabel, lumiLabel, boxLabel, plotLabel,
                    self.isData, False, None, None, h_MR_components, h_colors,
                    h_labels)
        print1DProj(c, tdirectory, h_Rsq, h_data_Rsq,
                    self.dirname + "/h_Rsq_%s.pdf" % self.analysis.region,
                    "R^{2}", eventsLabel, lumiLabel, boxLabel, plotLabel,
                    self.isData, False, None, None, h_Rsq_components, h_colors,
                    h_labels)
        #if len(self.z)>2:
        if len(self.z) > 1:
            for k in range(0, len(self.z) - 1):
                newBoxLabel = "razor %s %s %s Fit" % (
                    self.analysis.region, h_labels[k],
                    self.fitRegion.replace('LowMR,LowRsq', 'Sideband'))
                if computeErrors:
                    print1DProjNs(c,
                                  tdirectory,
                                  h_th1x_components[k],
                                  h_data_th1x_components[k],
                                  h_RsqMR_nsigma_components[k],
                                  self.dirname + "/h_th1x_ns_%ibtag_%s.pdf" %
                                  (self.z[k], self.analysis.region),
                                  "Bin Number",
                                  eventsLabel,
                                  lumiLabel,
                                  newBoxLabel,
                                  plotLabel,
                                  self.isData,
                                  False,
                                  options,
                                  cfg=self.config)
                    print2DResiduals(
                        c, tdirectory, h_RsqMR_nsigma_components[k],
                        self.dirname + "/h_RsqMR_nsigma_log_%ibtag_%s.pdf" %
                        (self.z[k], self.analysis.region), "M_{R} [GeV]",
                        "R^{2}", "Stat.+Sys. n#sigma", lumiLabel, newBoxLabel,
                        plotLabel, self.x, self.y, self.isData, sidebandFit,
                        False, options)
                else:
                    print1DProj(
                        c, tdirectory, h_th1x_components[k],
                        h_data_th1x_components[k],
                        self.dirname + "/h_th1x_%ibtag_%s.pdf" %
                        (self.z[k], self.analysis.region), "Bin Number",
                        eventsLabel, lumiLabel, newBoxLabel, plotLabel,
                        self.isData, False, options)
                    print2DResiduals(
                        c, tdirectory, h_RsqMR_statnsigma_components[k],
                        self.dirname +
                        "/h_RsqMR_statnsigma_log_%ibtag_%s.pdf" %
                        (self.z[k], self.analysis.region), "M_{R} [GeV]",
                        "R^{2}", "Stat. n#sigma (Data - Fit)/sqrt(Fit)",
                        lumiLabel, newBoxLabel, plotLabel, self.x, self.y,
                        self.isData, sidebandFit, False, options)
        f.Close()
Example #6
0
    def plot(self, filename=None, unblind=False, 
            toysFile=None, sysFile=None):
        """Plots the fit results"""
        options = self.getPlottingOptions()
        if unblind:
            plotRegion = 'Full'
        else:
            plotRegion = self.fitRegion
        if filename is None:
            filename = self.filename.replace('.root','_Plots.root')
        f = rt.TFile(filename, 'UPDATE')
        toyTree = self.getToyTree(toysFile)
        sysTree = self.getToyTree(sysFile)
        if toyTree is not None and sysTree is not None:
            dirName = "WithToys"
            computeErrors = True
        else:
            dirName = "BeforeToys"
            computeErrors = False
        tdirectory = f.GetDirectory(dirName)
        if tdirectory==None:
            f.mkdir(dirName)
            tdirectory = f.GetDirectory(dirName)
        c = rt.TCanvas('c','c',500,400)
        rt.SetOwnership(c, False)
        rt.TH1D.SetDefaultSumw2()
        rt.TH2D.SetDefaultSumw2()
        rt.TH3D.SetDefaultSumw2()
        plotband = convertSideband(plotRegion, self.workspace,
                self.x, self.y, self.z)

        # Get the 1D and 2D histograms for each b-tag bin
        h_data_nBtagRsqMR, h_nBtagRsqMR = self.get3DFitHistos(plotband)
        h_data_MR,h_data_Rsq,h_data_RsqMR = make3DHistProjections(
                h_data_nBtagRsqMR)
        h_MR,h_Rsq,h_RsqMR = make3DHistProjections(h_nBtagRsqMR)
        if computeErrors:
            h_MR = getErrors1D(h_MR,h_data_MR,sysTree,options,"x",0,
                    len(self.x)-1,0,len(self.y)-1,0,len(self.z)-1,
                    self.x,self.y,self.z)
            h_Rsq = getErrors1D(h_Rsq,h_data_Rsq,sysTree,options,"y",0,
                    len(self.x)-1,0,len(self.y)-1,0,len(self.z)-1,
                    self.x,self.y,self.z)
            h_RsqMR = getErrors2D(h_RsqMR,h_data_RsqMR,sysTree,options,"yx",0,
                    len(self.x)-1,0,len(self.y)-1,0,len(self.z)-1,
                    self.x,self.y,self.z)
            h_nBtagRsqMR = getErrors3D(h_nBtagRsqMR,h_data_nBtagRsqMR,sysTree,
                    options,"zyx",0,len(self.x)-1,0,len(self.y)-1,0,
                    len(self.z)-1,self.x,self.y,self.z)
        for h in [h_data_MR,h_data_Rsq,h_data_RsqMR,h_data_nBtagRsqMR,
                h_MR,h_Rsq,h_RsqMR,h_nBtagRsqMR]:
            tdirectory.cd()
            h.Write()
        if len(self.z)>1:
            h_MR_components = []
            h_Rsq_components = []
            h_RsqMR_components = []
            h_data_RsqMR_components = []
            h_sig_RsqMR_components = []
            h_th1x_components = []
            h_data_th1x_components = []
            h_sig_th1x_components = []
            h_labels = []        
            h_colors = [rt.kOrange,rt.kViolet,rt.kRed,rt.kGreen,rt.kGray+2]
            for k in range(1,len(self.z)):
                h_MR_components.append(h_nBtagRsqMR.ProjectionX(
                    "MR_%ibtag"%self.z[k-1],0,-1,k,k,""))
                h_Rsq_components.append(h_nBtagRsqMR.ProjectionY(
                    "Rsq_%ibtag"%self.z[k-1],0,-1,k,k,""))
                h_nBtagRsqMR.GetZaxis().SetRange(k,k)
                h_RsqMR_components.append(h_nBtagRsqMR.Project3D(
                    "%ibtag_yx"%self.z[k-1]))
                h_data_nBtagRsqMR.GetZaxis().SetRange(k,k)
                h_data_RsqMR_components.append(h_data_nBtagRsqMR.Project3D(
                    "%ibtag_yx"%self.z[k-1]))
                if computeErrors:
                    h_RsqMR_components[-1] = getErrors2D(h_RsqMR_components[-1],
                            h_data_RsqMR_components[-1],sysTree,options,
                            "yx",0,len(self.x)-1,0,len(self.y)-1,k,k,
                            self.x,self.y,self.z)
                h_th1x_components.append(get1DHistoFrom2D(
                    h_RsqMR_components[-1],self.x,self.y,
                    'h_th1x_%ibtag'%(self.z[k-1])))
                h_data_th1x_components.append(get1DHistoFrom2D(
                    h_data_RsqMR_components[-1],self.x,self.y,
                    'h_th1x_data_%ibtag'%(self.z[k-1])))
                if self.z[k-1]==3 and self.z[-1]==4:
                    h_labels.append("#geq %i b-tag" % self.z[k-1] )
                elif self.z[k-1]==1 and self.z[-1]==4 and len(self.z)==2:
                    h_labels.append("#geq %i b-tag" % self.z[k-1] )
                else:            
                    h_labels.append("%i b-tag" % self.z[k-1] )

        # Create the nsigma histograms
        h_RsqMR_statnsigma_components = []
        h_RsqMR_nsigma_components = []
        if len(self.z)>1:
            for k in range(1,len(self.z)):
                h_RsqMR_statnsigma_components.append( 
                        getStatNSigmaHist(h_RsqMR_components[k-1], 
                            h_data_RsqMR_components[k-1],
                            "h_RsqMR_statnsigma_%ibtag"%self.z[k-1]))
                h_RsqMR_nsigma_btag = h_RsqMR.Clone(
                        "h_RsqMR_nsigma_%ibtag"%self.z[k-1])
                if computeErrors:
                    h_RsqMR_nsigma_btag = getNsigma2D(h_RsqMR_nsigma_btag,
                            h_data_RsqMR_components[k-1],toyTree,options,
                            "yx",0,len(self.x)-1,0,len(self.y)-1,k,k,
                            self.x,self.y,self.z)
                    self.blindSideband(h_RsqMR_nsigma_btag, plotRegion)
                    h_RsqMR_nsigma_components.append(h_RsqMR_nsigma_btag)

        # Print everything out to pdf files
        btagLabel = getBtagLabel(self.z)
        lumiLabel = "%.1f fb^{-1} (13 TeV)" % (self.analysis.lumi/1000.)
        boxLabel = "razor %s %s %s Fit" % (self.analysis.region,
                btagLabel,self.fitRegion.replace('LowMR,LowRsq','Sideband'))
        plotLabel = ""
        eventsLabel = "Events"
        sidebandFit = self.getSidebandMax()
        for h in h_RsqMR_components:
            tdirectory.cd()
            h.Write()
        print1DProj(c,tdirectory,h_MR,h_data_MR,
                self.dirname+"/h_MR_%s.pdf"%self.analysis.region,"M_{R} [GeV]",
                eventsLabel,lumiLabel,boxLabel,plotLabel,self.isData,False,None,
                None,h_MR_components,h_colors,h_labels)
        print1DProj(c,tdirectory,h_Rsq,h_data_Rsq,
                self.dirname+"/h_Rsq_%s.pdf"%self.analysis.region,"R^{2}",
                eventsLabel,lumiLabel,boxLabel,plotLabel,self.isData,False,None,
                None,h_Rsq_components,h_colors,h_labels)
        #if len(self.z)>2:
        if len(self.z)>1:
            for k in range(0,len(self.z)-1):
                newBoxLabel = "razor %s %s %s Fit"%(self.analysis.region,
                    h_labels[k],self.fitRegion.replace('LowMR,LowRsq','Sideband'))
                if computeErrors:
                    print1DProjNs(c,tdirectory,h_th1x_components[k],
                            h_data_th1x_components[k],
                            h_RsqMR_nsigma_components[k],
                            self.dirname+"/h_th1x_ns_%ibtag_%s.pdf"%(
                                self.z[k],self.analysis.region),
                            "Bin Number",eventsLabel,lumiLabel,newBoxLabel,
                            plotLabel,self.isData,False,options,cfg=self.config) 
                    print2DResiduals(c,tdirectory,h_RsqMR_nsigma_components[k],
                            self.dirname+"/h_RsqMR_nsigma_log_%ibtag_%s.pdf"%(
                            self.z[k],self.analysis.region),"M_{R} [GeV]", 
                            "R^{2}","Stat.+Sys. n#sigma",lumiLabel,newBoxLabel,
                            plotLabel, self.x,self.y,self.isData,sidebandFit,
                            False,options)
                else:
                    print1DProj(c,tdirectory,h_th1x_components[k],
                        h_data_th1x_components[k], 
                        self.dirname+"/h_th1x_%ibtag_%s.pdf"%(self.z[k],
                            self.analysis.region),"Bin Number",
                            eventsLabel,lumiLabel,newBoxLabel,plotLabel,self.isData,
                            False, options)
                    print2DResiduals(c,tdirectory,h_RsqMR_statnsigma_components[k],
                        self.dirname+"/h_RsqMR_statnsigma_log_%ibtag_%s.pdf"%(self.z[k],
                        self.analysis.region), "M_{R} [GeV]", "R^{2}", 
                        "Stat. n#sigma (Data - Fit)/sqrt(Fit)",
                        lumiLabel,newBoxLabel,plotLabel,self.x,self.y,self.isData,
                        sidebandFit,False,options)
        f.Close()
Example #7
0
            w.var(p.GetName()).setError(p.getError())
            
    
    x = array('d', cfg.getBinning(box)[0]) # MR binning
    y = array('d', cfg.getBinning(box)[1]) # Rsq binning
    z = array('d', cfg.getBinning(box)[2]) # nBtag binning
    nBins = (len(x)-1)*(len(y)-1)*(len(z)-1)
    
    xFine = array('d', [x[0]+i*(x[-1]-x[0])/100. for i in range(0,101)]) # MR binning fine
    yFine = array('d', [y[0]+i*(y[-1]-y[0])/100. for i in range(0,101)]) # Rsq binning fine
    zFine = array('d', cfg.getBinning(box)[2]) # nBtag binning fine
    nBinsFine = (len(xFine)-1)*(len(yFine)-1)*(len(zFine)-1)
    
    th1x = w.var('th1x')
    
    sideband = convertSideband(fitRegion,w,x,y,z)
    plotband = convertSideband(plotRegion,w,x,y,z)
    
    myTH1 = convertDataset2TH1(data, cfg, box, w, options.useWeight)

    signalDs = None
    doSignalInj = (options.signalFileName != "None") and (options.r > -1)
    if doSignalInj:
        sigRootFile = rt.TFile(options.signalFileName)
        #sigWorkspace = sigRootFile.Get('w'+box)
        #signalDs = sigWorkspace.data('RMRTree')
        model = options.signalFileName.split('.root')[0].split('-')[1].split('_')[0]
        massPoint = '_'.join(options.signalFileName.split('.root')[0].split('_')[1:3])
        #sigTH1 = convertDataset2TH1(signalDs, cfg, box, w,"signal")
        #sigTH1.Scale(lumi/lumi_in)
        sigTH1 = sigRootFile.Get('%s_%s'%(box,model)).Clone('hist_%s_%s'%(box,model))