Esempio n. 1
0
def getProb(yields):
    NTot = yields["NTot"]
    NTotErr = yields["NTotErr"]
    NPass = yields["NPass"]
    NPassErr = yields["NPassErr"]

    P = NPass / NTot
    PErr = NPassErr / NTot
    PErrUp = -1
    PErrDn = -1
    NLimit68Raw = -1

    # Handle the case in which there are a small number of raw events corresponding to NPass.
    if "NTotRaw" in yields:
        NTotRaw = yields["NTotRaw"]
    else:
        NTotRaw = getRawEvts(NTot, NTotErr)
    NPassRaw = getRawEvts(NPass, NPassErr)

    if NPassRaw < 10:  # Crude estimate of when Poisson approximates a binomial, see https://en.wikipedia.org/wiki/Poisson_distribution
        # print "Debug:  NTotRaw = ", NTotRaw
        NPassRawErr = NPassRaw * (NPassErr / NPass) if NPass else 0
        alpha = 0.84  # choose alpha such that 68% of distribution is within +/-1 sigma
        NPassErrUpRaw = math.fabs(
            0.5 * TMath.ChisquareQuantile(alpha, 2 *
                                          (NPassRaw + 1)) - NPassRaw)
        NPassErrDnRaw = math.fabs(
            0.5 * TMath.ChisquareQuantile(1.0 - alpha, 2 *
                                          (NPassRaw)) - NPassRaw)

        P = NPassRaw / NTotRaw
        PErrUp = NPassErrUpRaw / NTotRaw
        PErrDn = NPassErrDnRaw / NTotRaw
        PErr = PErrUp  # Arbitrary choice; usually PErrUp is larger than PErrDn

        # For the case of NPassRaw, use a one-sided 68% confidence interval
        if NPassRaw == 0:
            NLimit68Raw = 0.5 * TMath.ChisquareQuantile(
                0.68, 2 * (NPassRaw + 1)
            )  # 68% CL upper limit, see https://github.com/OSU-CMS/OSUT3Analysis/blob/master/AnaTools/bin/cutFlowLimits.cpp
            PErrUp = NLimit68Raw / NTotRaw
            PErrDn = 0
            PErr = PErrUp  # Arbitrary choice; usually PErrUp is larger than PErrDn

    prob = {}
    prob["P"] = P
    prob["PErr"] = PErr
    prob["PErrUp"] = PErrUp
    prob["PErrDn"] = PErrDn
    prob["NLimit68Raw"] = NLimit68Raw

    return prob
Esempio n. 2
0
    def printNctrl(self):
        metMinusOne = self.plotMetForNctrl()
        if hasattr(self, "TagPt35") or hasattr(self, "TagPt35ForNctrl"):
            n = self.TagPt35ForNctrl["yield"] if hasattr(
                self, "TagPt35ForNctrl") else self.TagPt35["yield"]
            nError = self.TagPt35ForNctrl["yieldError"] if hasattr(
                self, "TagPt35ForNctrl") else self.TagPt35["yieldError"]
            weight = self.TagPt35ForNctrl["weight"] if hasattr(
                self, "TagPt35ForNctrl") else self.TagPt35["weight"]

            n *= self._prescale
            nError *= self._prescale
            weight *= self._prescale

            if not (n == 0.0):
                print "N_ctrl: " + str(n) + " +- " + str(nError) + " (" + str(
                    n / self._luminosityInInvFb) + " +- " + str(
                        nError / self._luminosityInInvFb) + " fb)"
                return (n, nError, metMinusOne)
            else:
                nUpperLimit = 0.5 * TMath.ChisquareQuantile(0.68, 2 *
                                                            (n + 1)) * weight
                print "N_ctrl: " + str(n) + " - 0.0 + " + str(
                    nUpperLimit) + " (" + str(
                        n / self._luminosityInInvFb) + " - 0 + " + str(
                            nUpperLimit / self._luminosityInInvFb) + " fb)"
                return (n, nUpperLimit, metMinusOne)
        else:
            print "Neither TagPt35 nor TagPt35ForNctrl defined. Not printing N_ctrl..."
            return (float("nan"), float("nan"))
Esempio n. 3
0
def getAbsoluteSystematicFromRelative(N, sysRelErr, statAbsErr):
    if N > 0.0:
        return N * sysRelErr
    upperLimit = 0.5 * TMath.ChisquareQuantile(0.68, 2.0 * (N + 1.0))
    # from http://dx.doi.org/10.1016/0168-9002(92)90794-5
    totalAbsErr = upperLimit * (1.0 + (upperLimit - N) *
                                (sysRelErr * sysRelErr) / 2.0)
    return math.sqrt(totalAbsErr * totalAbsErr - statAbsErr * statAbsErr)
Esempio n. 4
0
    def printPpassVetoTagProbe(self):
        self.plotPpassVetoPtDependence()
        if math.isnan(self._pPassVeto[0]) or math.isnan(self._pPassVeto[1]):
            if hasattr(self, "TagProbe") and hasattr(self, "TagProbePass"):
                total = self.TagProbe["yield"]
                totalError = self.TagProbe["yieldError"]
                passes = self.TagProbePass["yield"]
                passesError = self.TagProbePass[
                    "yieldError"] if passes > 0.0 else 0.5 * TMath.ChisquareQuantile(
                        0.68, 2 * (0.0 + 1)) * self.TagProbePass["weight"]

                passes1 = 0.0
                passes1Error = 0.0

                if hasattr(self, "TagProbe1") and hasattr(
                        self, "TagProbePass1"):
                    total += self.TagProbe1["yield"]
                    totalError = math.hypot(totalError,
                                            self.TagProbe1["yieldError"])

                    passes1 = self.TagProbePass1["yield"]
                    passes1Error = self.TagProbePass1["yieldError"]

                scaledPasses = passes * self._tagProbePassScaleFactor + passes1 * self._tagProbePass1ScaleFactor
                scaledPassesError = math.hypot(
                    passesError * self._tagProbePassScaleFactor,
                    passes1Error * self._tagProbePass1ScaleFactor)

                eff = scaledPasses / (2.0 * total - scaledPasses)
                effError = 2.0 * math.hypot(scaledPassesError * total,
                                            scaledPasses * totalError) / (
                                                (2.0 * total - scaledPasses) *
                                                (2.0 * total - scaledPasses))

                if eff > 0.0:
                    print "P (pass lepton veto) in tag-probe sample: " + str(
                        eff) + " +- " + str(effError)
                else:
                    print "P (pass lepton veto) in tag-probe sample: " + str(
                        eff) + " - 0 + " + str(effError)
                return (eff, effError, passes, passesError, passes1,
                        passes1Error, total, totalError)
            else:
                print "TagProbe and TagProbePass not both defined.  Not printing lepton veto efficiency..."
                return (float("nan"), float("nan"), float("nan"), float("nan"),
                        float("nan"), float("nan"), float("nan"), float("nan"))
        else:
            print "P (pass lepton veto) from user input: " + str(
                self._pPassVeto[0]) + " +- " + str(self._pPassVeto[1])
            return (self._pPassVeto[0], self._pPassVeto[1], float("nan"),
                    float("nan"), float("nan"), float("nan"), float("nan"),
                    float("nan"))
def calcPoissonCLLower(obs, q=0.68269):
    """
    Calculate lower confidence limit
    e.g. to calculate the 68% lower limit for 2 observed events:
    calcPoissonCLLower(2.)
    """
    LL = 0.

    if q == 0.68269 and obs > 1000:
        LL = obs - sqrt(obs + 0.25) + 0.5
        return LL

    if obs >= 0.:
        a = (1. - q) / 2.  # = 0.025 for 95% confidence interval
        LL = TMath.ChisquareQuantile(a, 2. * obs) / 2.
        pass
    return LL
def calcPoissonCLUpper(obs, q=0.68269):
    """
    Calculate upper confidence limit
    e.g. to calculate the 68% upper limit for 2 observed events:
    calcPoissonCLUpper(2.)
    """
    UL = 0.

    if q == 0.68269 and obs > 1000:
        UL = obs + sqrt(obs + 0.25) + 0.5
        return UL

    if obs >= 0.:
        a = 1. - (1. - q) / 2.  # = 0.025 for 95% confidence interval
        UL = TMath.ChisquareQuantile(a, 2. * (obs + 1.)) / 2.
        pass

    return UL
Esempio n. 7
0
    def printPfakeTrack(self):
        if hasattr(self, "ZtoLL") and hasattr(self, "ZtoLLdisTrk"):
            total = self.ZtoLL["yield"]
            totalError = self.ZtoLL["yieldError"]
            passes = self.ZtoLLdisTrk["yield"]
            passesError = self.ZtoLLdisTrk[
                "yieldError"] if passes > 0.0 else 0.5 * TMath.ChisquareQuantile(
                    0.68, 2 * (0.0 + 1)) * self.ZtoLLdisTrk["weight"]

            eff = passes / total
            effError = math.hypot(total * passesError,
                                  totalError * passes) / (total * total)
            if eff > 0.0:
                print "P (fake track): " + str(eff) + " +- " + str(effError)
            else:
                print "P (fake track): " + str(eff) + " - 0.0 + " + str(
                    effError)
            return (eff, effError, passes, passesError, total, totalError)
        else:
            print "ZtoLL and ZtoLLdisTrk not both defined. Not printing P (fake track)..."
            return (float("nan"), float("nan"))
Esempio n. 8
0
 def printNback(self):
     self.plotMetForNback()
     if hasattr(self, "CandTrkIdPt35"):
         n = self.CandTrkIdPt35["yield"]
         nError = self.CandTrkIdPt35["yieldError"]
         weight = self.CandTrkIdPt35["weight"]
         if not (n == 0.0):
             print "N_back: " + str(n) + " +- " + str(nError) + " (" + str(
                 n / self._luminosityInInvFb) + " +- " + str(
                     nError / self._luminosityInInvFb) + " fb)"
             return (n, nError)
         else:
             nUpperLimit = 0.5 * TMath.ChisquareQuantile(0.68, 2 *
                                                         (n + 1)) * weight
             print "N_back: " + str(n) + " - 0.0 + " + str(
                 nUpperLimit) + " (" + str(
                     n / self._luminosityInInvFb) + " +- " + str(
                         nUpperLimit / self._luminosityInInvFb) + " fb)"
             return (n, nUpperLimit)
     else:
         print "CandTrkIdPt35 not defined. Not printing N_back..."
         return (float("nan"), float("nan"))
Esempio n. 9
0
import sys
import math
import functools

from ROOT import gROOT, gStyle, TCanvas, TFile, TGraphAsymmErrors, TH1D, TH3D, TMath, TPaveText, TObject

from OSUT3Analysis.Configuration.Measurement import Measurement
from OSUT3Analysis.Configuration.ProgressIndicator import ProgressIndicator
from DisappTrks.StandardAnalysis.plotUtilities import *

setTDRStyle()

gROOT.SetBatch()
gStyle.SetOptStat(0)

up68 = 0.5 * TMath.ChisquareQuantile(0.68, 2)


class LeptonBkgdEstimate:
    _Flavor = ""
    _flavor = ""
    _fout = None
    _canvas = None
    _metCut = 100.0
    _phiCut = 0.5
    _eCaloCut = 10.0
    _pPassVeto = float("nan")
    _prescale = 1.0
    _tagProbePassScaleFactor = 1.0
    _tagProbePass1ScaleFactor = 1.0
    _luminosityInInvFb = float("nan")
def makeplot_single(
    h1_sig=None,
    h1_bkg=None,
    h1_data=None,
    sig_legends_=None,
    bkg_legends_=None,
    sig_colors_=None,
    bkg_colors_=None,
    hist_name_=None,
    sig_scale_=1.0,
    dir_name_="plots",
    output_name_=None,
    extraoptions=None
    ):

    if h1_sig ==  None or h1_bkg == None:
        print("nothing to plot...")
        return
    os.system("mkdir -p "+dir_name_)
    os.system("cp index.php "+dir_name_)
    s_color = [632, 617, 839, 800, 1]
    b_color = [920, 2007, 2005, 2003, 2001, 2011]
    if sig_colors_:
        s_color = sig_colors_
    if bkg_colors_:
        b_color = bkg_colors_
    for idx in range(len(h1_sig)):
        h1_sig[idx].SetLineWidth(3)
        h1_sig[idx].SetLineColor(s_color[idx])
    for idx in range(len(h1_bkg)):
        h1_bkg[idx].SetLineWidth(2)
        h1_bkg[idx].SetLineColor(b_color[idx])
        h1_bkg[idx].SetFillColorAlpha(b_color[idx], 1)
    if h1_data:
        h1_data.SetBinErrorOption(1)
        h1_data.SetLineColor(1)
        h1_data.SetLineWidth(2)
        h1_data.SetMarkerColor(1)
        h1_data.SetMarkerStyle(20)

    myC = r.TCanvas("myC","myC", 600, 600)
    myC.SetTicky(1)
    pad1 = r.TPad("pad1","pad1", 0.05, 0.33,0.95, 0.97)
    pad1.SetBottomMargin(0.027)
    pad1.SetRightMargin( rightMargin )
    pad1.SetLeftMargin( leftMargin )
    pad2 = r.TPad("pad2","pad2", 0.05, 0.04, 0.95, 0.31)
    pad2.SetBottomMargin(0.4)
    pad2.SetTopMargin(0.05)
    pad2.SetRightMargin( rightMargin )
    pad2.SetLeftMargin( leftMargin )

    pad2.Draw()
    pad1.Draw()

    pad1.cd()

    for idx in range(len(h1_sig)):
        print("before signal scaling",h1_sig[idx].Integral())
        h1_sig[idx].Scale(sig_scale_)
        print("after signal scaling",h1_sig[idx].Integral())
        
    stack = r.THStack("stack", "stack")
    nS = np.zeros(h1_bkg[0].GetNbinsX())
    eS = np.zeros(h1_bkg[0].GetNbinsX())
    #hist_all is used to make the data/mc ratio. remove signal for the moment due to signal is scaled right now
    hist_all = h1_sig[0].Clone("hist_all")
    hist_all.Scale(0.0)
    hist_s = h1_sig[0].Clone("hist_s")
    hist_b = h1_bkg[0].Clone("hist_b")
    for idx in range(len(h1_bkg)):
        stack.Add(h1_bkg[idx])
        for ib in range(h1_bkg[0].GetNbinsX()):
            nS[ib] += h1_bkg[idx].GetBinContent(ib+1)
            eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_bkg[idx].GetBinError(ib+1)*h1_bkg[idx].GetBinError(ib+1))
        hist_all.Add(h1_bkg[idx]) 
        if idx > 0:
            hist_b.Add(h1_bkg[idx]) 
            
    for idx in range(len(h1_sig)):
        print("ggH signal yield: ", hist_s.Integral())
        if idx > 0:
            hist_temp = h1_sig[idx].Clone(h1_sig[idx].GetName()+"_temp")
            #hist_all.Add(hist_temp)
            hist_s.Add(h1_sig[idx])
        print("all signal yield: ", hist_s.Integral())

    stack.SetTitle("")
    
    maxY = 0.0
    if "stack_signal" in extraoptions and extraoptions["stack_signal"]:
        for idx in range(len(h1_sig)):
            h1_sig[idx].SetFillColorAlpha(s_color[idx], 1)
            stack.Add(h1_sig[idx])
            for ib in range(h1_bkg[0].GetNbinsX()):
                nS[ib] += h1_sig[idx].GetBinContent(ib+1)
                eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_sig[idx].GetBinError(ib+1)*h1_sig[idx].GetBinError(ib+1))
        if stack.GetMaximum() > maxY:
            maxY = stack.GetMaximum()
        #if "SR" in h.GetTitle(): 
        stack.Draw("hist")
    else:
        stack.Draw("hist")
        if stack.GetMaximum() > maxY:
            maxY = stack.GetMaximum()
        for idx in range(len(h1_sig)):
            if h1_sig[idx].GetMaximum() > maxY:
                maxY = h1_sig[idx].GetMaximum()
            if "SR" in h1_bkg[0].GetTitle():
                #h1_sig[idx].Draw("samehist")
                hist_s.Draw("samehist")

    ##draw  stack total unc on top of total histogram
    box = r.TBox(0,0,1,1,)
    box.SetFillStyle(3002)
    box.SetLineWidth(0)
    box.SetFillColor(r.kBlack)
    for idx in range(h1_bkg[0].GetNbinsX()):
        box.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]-eS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]+eS[idx])

    if h1_data:
        if h1_data.GetMaximum() > maxY:
            maxY = h1_data.GetMaximum()+np.sqrt(h1_data.GetMaximum())
        #if not "SR" in h1_data.GetTitle() or "fail" in h1_data.GetTitle():  
        if True:
            #print("debug h1_data.GetName()",h1_data.GetName(), h1_data.GetTitle())           
            TGraph_data = TGraphAsymmErrors(h1_data)
            for i in range(TGraph_data.GetN()):
                #data point
                var_x, var_y = Double(0.), Double(0.)
                TGraph_data.GetPoint(i,var_x,var_y)    
                if np.fabs(var_y) < 1e-5:
                    TGraph_data.SetPoint(i,var_x,-1.0)
                    TGraph_data.SetPointEYlow(i,-1)
                    TGraph_data.SetPointEYhigh(i,-1)
                    #print("zero bins in the data TGraph: bin",i+1)
                else:
                    TGraph_data.SetPoint(i,var_x,var_y)
                    err_low = var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y))
                    TGraph_data.SetPointEYlow(i, var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)))
                    TGraph_data.SetPointEYhigh(i, (0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y)
        
            TGraph_data.SetMarkerColor(1)
            TGraph_data.SetMarkerSize(1)
            TGraph_data.SetMarkerStyle(20)
            TGraph_data.Draw("same P")

    stack.GetYaxis().SetTitle("Events")
    stack.GetYaxis().SetTitleOffset(1.05)
    stack.GetYaxis().SetTitleSize(0.08)
    stack.GetYaxis().SetLabelSize(0.06)
    #stack.GetYaxis().CenterTitle()
    stack.GetXaxis().SetLabelSize(0.)
    #stack.GetXaxis().SetLabelOffset(0.013)
    #if "xaxis_range" in extraoptions:
    #    stack.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1]))

    leg = r.TLegend(0.2, 0.60, 0.9, 0.88)
    leg.SetNColumns(3)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.05)
    for idx in range(len(h1_bkg)):
        leg.AddEntry(h1_bkg[idx], bkg_legends_[idx], "F")
    if "SR" in hist_s.GetTitle():
        leg.AddEntry(hist_s, 'HH #times {:1.2}'.format(sig_scale_), "L")

    leg.AddEntry(box, "Total  unc", "F")
    if h1_data:
        leg.AddEntry(h1_data, "Data", "ep")
    leg.Draw()

    pad2.cd()
    pad2.SetGridy(1)
    
    ratio = None
    ratio_Low  = 0.0
    ratio_High  = 4
    
    if h1_data:      
        ratio = TGraphAsymmErrors(h1_data)
        for i in range(ratio.GetN()):
            
            #bkg prediction
            imc = Double(hist_all.GetBinContent(i+1))
            #data point
            var_x, var_y = Double(0.), Double(0.)
            if not ("SR" in h1_data.GetTitle() and (i>5 and i<9)):
            	ratio.GetPoint(i,var_x,var_y)    
            if var_y == 0.:
                ratio.SetPoint(i,var_x,-1.0)
                ratio.SetPointEYlow(i,-1)
                ratio.SetPointEYhigh(i,-1)
                continue
            ratio.SetPoint(i,var_x,var_y/imc)
            err_low = (var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)))/imc
            err_high = ((0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y)/imc
            ratio.SetPointEYlow(i, err_low)
            ratio.SetPointEYhigh(i, err_high)
        
        ratio.SetMarkerColor(1)
        ratio.SetMarkerSize(1)
        ratio.SetMarkerStyle(20)
        ratio.GetXaxis().SetTitle("j_{2} regressed mass [GeV]")
        #myC.Update()
        
        if "ratio_range" in extraoptions:
            ratio_Low = extraoptions["ratio_range"][0]
            ratio_High = extraoptions["ratio_range"][1]
        ratio.GetYaxis().SetTitle("data/mc")
        ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High)
        ratio.GetXaxis().SetRangeUser(50, 220)
        ratio.SetTitle("")
        ratio.Draw("same AP")
        pad2.Update()
        
        print(ratio.GetTitle(),ratio.GetName(),"debug")
    else:
        ratio = h1_sig[0].Clone("ratio")
        ratio_High = 0.0
        for ibin in range(1,ratio.GetNbinsX()+1):
            s = hist_s.GetBinContent(ibin) 
            b = hist_b.GetBinContent(ibin)
            L = 0.0
            if b > 0.0:
                L = s/math.sqrt(b)
                if L > ratio_High:
                    ratio_High = L
            ratio.SetBinContent(ibin, L)
        if ratio_High > 1.0:
            ratio_High = 1.0
        ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High*1.2)
        ratio.GetYaxis().SetTitle("S/#sqrt{B}")
        ratio.Draw("samehist")
    ratio.SetLineColor(1)
    ratio.SetLineWidth(2)
    ratio.SetMarkerStyle(20)
    ratio.SetMarkerColor(1)
    ratio.SetFillColorAlpha(1, 0)
    ratio.GetXaxis().SetTitleOffset(0.94)
    ratio.GetXaxis().SetTitleSize(0.18)
    ratio.GetXaxis().SetLabelSize(0.12)
    ratio.GetXaxis().SetLabelOffset(0.013)
    ratio.GetYaxis().SetTitleOffset(0.40)
    ratio.GetYaxis().SetTitleSize(0.17)
    ratio.GetYaxis().SetLabelSize(0.13)
    ratio.GetYaxis().SetTickLength(0.01)
    ratio.GetYaxis().SetNdivisions(505)
    #if "xaxis_range" in extraoptions:
    #    ratio.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1]))

    #draw  stack total unc on the ratio plot to present the background uncertainty
    box_ratio = r.TBox(0,0,1,1,)
    box_ratio.SetFillStyle(3002)
    box_ratio.SetLineWidth(0)
    box_ratio.SetFillColor(r.kBlack)
    for idx in range(h1_bkg[0].GetNbinsX()):
        if np.fabs(nS[idx])> 1e-06: 
            box_ratio.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]-eS[idx])/nS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]+eS[idx])/nS[idx])
        else:
            print("blinded Higgs peak region") 
    
    if "xaxis_label" in extraoptions and extraoptions["xaxis_label"] != None:
        x_title = extraoptions["xaxis_label"]
        ratio.GetXaxis().SetTitle(x_title)
    ratio.GetYaxis().CenterTitle()

    ##########draw CMS preliminary
    pad1.cd()
    tex1 = r.TLatex(leftMargin, 0.91, "CMS")
    tex1.SetNDC()
    tex1.SetTextFont(61)
    tex1.SetTextSize(0.070)
    tex1.SetLineWidth(2)
    tex1.Draw()
    tex2 = r.TLatex(leftMargin+0.12,0.912,"Internal")
    tex2.SetNDC()
    tex2.SetTextFont(52)
    tex2.SetTextSize(0.055)
    tex2.SetLineWidth(2)
    tex2.Draw()

    lumi_value = 137
    if "lumi_value" in extraoptions:
        lumi_value = extraoptions["lumi_value"]
    tex3 = r.TLatex(0.72,0.912,"%d"%lumi_value+" fb^{-1} (13 TeV)")
    tex3.SetNDC()
    tex3.SetTextFont(42)
    tex3.SetTextSize(0.055)
    tex3.SetLineWidth(2)
    tex3.Draw()
    outFile = dir_name_
    if output_name_:
        outFile = outFile + "/" +output_name_
    else:
        outFile = outFile + "/" + hist_name_

    #print("maxY = "+str(maxY))
    stack.SetMaximum(maxY*1.7)

    #print everything into txt file
    text_file = open(outFile+"_linY.txt", "w")
    text_file.write("bin    |   x    ")
    for idx in range(len(h1_bkg)):
        text_file.write(" | %21s"%bkg_legends_[idx])
    text_file.write(" | %21s"%("total B"))
    for idx in range(len(sig_legends_)):
        text_file.write(" | %25s"%sig_legends_[idx])
    if h1_data:
        text_file.write(" | data | data/mc")
    text_file.write("\n-------------")
    for idx in range(24*(len(h1_bkg) + 1)+ 29*len(sig_legends_)):
        text_file.write("-")
    if h1_data:
        text_file.write("-------")
    text_file.write("\n")
    for ibin in range(0,h1_sig[0].GetNbinsX()+1):
        text_file.write("%3d"%ibin+"   ")
        text_file.write(" | %6.3f"%h1_data.GetBinCenter(ibin)+" ")
        for idx in range(len(h1_bkg)):
            text_file.write(" | %7.3f "%h1_bkg[idx].GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%h1_bkg[idx].GetBinError(ibin))
        text_file.write(" | %7.3f "%hist_b.GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%hist_b.GetBinError(ibin))
        for idx in range(len(sig_legends_)):
            text_file.write(" | %9.3f "%h1_sig[idx].GetBinContent(ibin)+"$\\pm$"+ " %9.3f"%h1_sig[idx].GetBinError(ibin))
        if h1_data:
            text_file.write(" | %d"%h1_data.GetBinContent(ibin) +  " | %7.3f "%h1_data.GetBinContent(ibin) +"$\\pm$"+ " %7.3f"%h1_data.GetBinError(ibin))
        text_file.write("\n\n")
        
    #print yield table for AN
    text_file.write("print yield table for AN\n")
    bkg_all = 0
    bkg_all_errsq = 0
    for idx in range(len(h1_bkg)):
        bkg_tmp = h1_bkg[idx].GetBinContent(7)+h1_bkg[idx].GetBinContent(8)+h1_bkg[idx].GetBinContent(9)
        bkg_errsq_tmp = h1_bkg[idx].GetBinError(7)*h1_bkg[idx].GetBinError(7)+h1_bkg[idx].GetBinError(8)*h1_bkg[idx].GetBinError(8)+h1_bkg[idx].GetBinError(9)*h1_bkg[idx].GetBinError(9)
        bkg_all += bkg_tmp
        bkg_all_errsq += bkg_errsq_tmp
        text_file.write("%s"%(bkg_legends_[idx])+"& %7.2f"%(bkg_tmp)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_errsq_tmp)+"\n")
    text_file.write("total background & %7.2f"%(bkg_all)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_all_errsq)+"\n")
    
    text_file.write("\ggHH SM ($\kapl=1$) & %7.2f"%((h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9)))+"\n")
    text_file.write("\VBFHH SM ($\kapl=1$) & %7.2f"%((h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9)))+"\n")
    
    text_file.write("HH bin 8 value %s"%h1_sig[0].GetBinContent(8)+"\n")
    text_file.write("HH bin 9 value %s"%h1_sig[0].GetBinContent(9)+"\n")
    text_file.write("HH bin 7 value %s"%h1_sig[0].GetBinContent(7)+"\n")

    text_file.write("HH bin 8 error %s"%h1_sig[0].GetBinError(8)+"\n")
    text_file.write("HH bin 9 error %s"%h1_sig[0].GetBinError(9)+"\n")
    text_file.write("HH bin 7 error %s"%h1_sig[0].GetBinError(7)+"\n")
    
    text_file.write("total & %7.2f"%(bkg_all+(h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9)+h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.2f"%(np.sqrt((h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9))/(sig_scale_*sig_scale_)+(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9))/(sig_scale_*sig_scale_)+bkg_all_errsq))+"\n")
    
    text_file.close()
    os.system("cp "+outFile+"_linY.txt "+outFile+"_logY.txt")

    pad1.RedrawAxis()
    myC.SaveAs(outFile+"_linY.png")
    myC.SaveAs(outFile+"_linY.pdf")
    myC.SaveAs(outFile+"_linY.C")
    pad1.cd()
    stack.SetMaximum(maxY*100.0)
    stack.SetMinimum(0.5)
    pad1.SetLogy()
    pad1.RedrawAxis()
    myC.SaveAs(outFile+"_logY.png")
    myC.SaveAs(outFile+"_logY.pdf")
    myC.SaveAs(outFile+"_logY.C")
    #save histogram and ratio to root file
    outFile_root = r.TFile(outFile+".root", "recreate")
    outFile_root.cd()
    for idx in range(len(h1_bkg)):
        h1_bkg[idx].Write()
    for idx in range(len(sig_legends_)):
        h1_sig[idx].Write()
    if  h1_data:
        h1_data.Write()
        ratio.Write()
    #outFile_root.Write()
    outFile_root.Close()
    def printNctrl(self):
        if hasattr(self, "DisTrkInvertD0"):
            n, nError = getHistIntegral(
                self.DisTrkInvertD0["sample"],
                self.DisTrkInvertD0["condorDir"],
                self.DisTrkInvertD0["name"] + "Plotter",
                "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                self._maxD0 - 0.001)
            n = Measurement(n, (nError if n != 0.0 else 0.5 *
                                TMath.ChisquareQuantile(0.68, 2 * (n + 1))))
            n.isPositive()

            if self._minHits < 7:
                n6, n6Error = getHistIntegral(
                    self.DisTrkInvertD0NHits6["sample"],
                    self.DisTrkInvertD0NHits6["condorDir"],
                    self.DisTrkInvertD0NHits6["name"] + "Plotter",
                    "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                    self._maxD0 - 0.001)
                n6 = Measurement(n6,
                                 (n6Error if n6 != 0.0 else 0.5 *
                                  TMath.ChisquareQuantile(0.68, 2 * (n6 + 1))))
                n6.isPositive()
                n += n6
            if self._minHits < 6:
                n5, n5Error = getHistIntegral(
                    self.DisTrkInvertD0NHits5["sample"],
                    self.DisTrkInvertD0NHits5["condorDir"],
                    self.DisTrkInvertD0NHits5["name"] + "Plotter",
                    "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                    self._maxD0 - 0.001)
                n5 = Measurement(n5,
                                 (n5Error if n5 != 0.0 else 0.5 *
                                  TMath.ChisquareQuantile(0.68, 2 * (n5 + 1))))
                n5.isPositive()
                n += n5
            if self._minHits < 5:
                n4, n4Error = getHistIntegral(
                    self.DisTrkInvertD0NHits4["sample"],
                    self.DisTrkInvertD0NHits4["condorDir"],
                    self.DisTrkInvertD0NHits4["name"] + "Plotter",
                    "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                    self._maxD0 - 0.001)
                n4 = Measurement(n4,
                                 (n4Error if n4 != 0.0 else 0.5 *
                                  TMath.ChisquareQuantile(0.68, 2 * (n4 + 1))))
                n4.isPositive()
                n += n4
            if self._minHits < 4:
                n3, n3Error = getHistIntegral(
                    self.DisTrkInvertD0NHits3["sample"],
                    self.DisTrkInvertD0NHits3["condorDir"],
                    self.DisTrkInvertD0NHits3["name"] + "Plotter",
                    "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                    self._maxD0 - 0.001)
                n3 = Measurement(n3,
                                 (n3Error if n3 != 0.0 else 0.5 *
                                  TMath.ChisquareQuantile(0.68, 2 * (n3 + 1))))
                n3.isPositive()
                n += n3

            pFake = float("nan")
            norm = 1.0

            # For ZtoMuMu control regions, need to normalize to BasicSelection
            if hasattr(self, "ZtoLL") and hasattr(self, "Basic"):
                norm = self.Basic["yield"] / self.ZtoLL["yield"]
                pFake = n / self.ZtoLL["yield"]
            elif hasattr(self, "Basic"):
                pFake = n / self.Basic["yield"]

            nRaw = n
            n *= norm
            n *= self._prescale

            print "N_ctrl: " + str(n) + " (" + str(
                n / self._luminosityInInvFb) + " fb)"
            print "P_fake^raw: " + str(pFake)
            return (n, nRaw, norm, pFake)
        else:
            print "DisTrkInvertD0 is not defined. Not printing N_ctrl..."
            return (float("nan"), float("nan"))
Esempio n. 12
0
    # (NCtrlEE, NCtrlErrEE)   = getYield("SingleElectron", ztoEEDir,        "ZtoEE")
    # (NYieldEE, NYieldErrEE) = getYield("SingleElectron", ztoEEFakeTrkDir, "ZtoEEFakeTrk")

    # NYield = NYieldMuMu + NYieldEE
    # NCtrl = NCtrlEE + NCtrlMuMu
    NYield = NYieldMuMu
    NCtrl = NCtrlMuMu

    # NYieldErr = math.sqrt(math.pow(NYieldErrEE, 2) + math.pow(NYieldErrMuMu, 2))
    # NCtrlErr = math.sqrt(math.pow(NCtrlErrEE, 2) + math.pow(NCtrlErrMuMu, 2))
    NYieldErr = NYieldErrMuMu
    NCtrlErr = NCtrlErrMuMu

    if NYieldErr == 0:
        NYieldErr = 0.5 * TMath.ChisquareQuantile(0.68, 2 * (NYield + 1))

    NYieldRaw = round(
        math.pow(NYield, 2) / math.pow(NYieldErr, 2)
    ) if NYieldErr else 0  # done for consistency with muon case, but since it's data, there are no weight factors so NYieldRaw = NYield
    NfakeRaw = NYieldRaw  # Used for bkgd estimate table
    NYieldRawErr = NYieldRaw * (NYieldErr / NYield) if NYield else 0
    NLimitRaw = 0.5 * TMath.ChisquareQuantile(
        0.68, 2 * (NYieldRaw + 1)
    )  # 68% CL upper limit, see https://github.com/OSU-CMS/OSUT3Analysis/blob/master/AnaTools/bin/cutFlowLimits.cpp
    alpha = 0.84
    NYieldErrUpRaw = math.fabs(0.5 *
                               TMath.ChisquareQuantile(alpha, 2 *
                                                       (NYieldRaw + 1)) -
                               NYieldRaw)
    NYieldErrDnRaw = math.fabs(0.5 *
Esempio n. 13
0
    def printNctrl(self):
        if hasattr(self, "DisTrkInvertD0"):
            n, nError = getHistIntegral(
                self.DisTrkInvertD0["sample"],
                self.DisTrkInvertD0["condorDir"],
                self.DisTrkInvertD0["name"] + "Plotter",
                "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                self._maxD0 - 0.001)
            if self._minHits < 7:
                n6, n6Error = getHistIntegral(
                    self.DisTrkInvertD0NHits6["sample"],
                    self.DisTrkInvertD0NHits6["condorDir"],
                    self.DisTrkInvertD0NHits6["name"] + "Plotter",
                    "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                    self._maxD0 - 0.001)
                n += n6
                nError = math.hypot(nError, n6Error)
            if self._minHits < 6:
                n5, n5Error = getHistIntegral(
                    self.DisTrkInvertD0NHits5["sample"],
                    self.DisTrkInvertD0NHits5["condorDir"],
                    self.DisTrkInvertD0NHits5["name"] + "Plotter",
                    "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                    self._maxD0 - 0.001)
                n += n5
                nError = math.hypot(nError, n5Error)
            if self._minHits < 5:
                n4, n4Error = getHistIntegral(
                    self.DisTrkInvertD0NHits4["sample"],
                    self.DisTrkInvertD0NHits4["condorDir"],
                    self.DisTrkInvertD0NHits4["name"] + "Plotter",
                    "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                    self._maxD0 - 0.001)
                n += n4
                nError = math.hypot(nError, n4Error)
            if self._minHits < 4:
                n3, n3Error = getHistIntegral(
                    self.DisTrkInvertD0NHits3["sample"],
                    self.DisTrkInvertD0NHits3["condorDir"],
                    self.DisTrkInvertD0NHits3["name"] + "Plotter",
                    "Track-eventvariable Plots/trackd0WRTPVMag", self._minD0,
                    self._maxD0 - 0.001)
                n += n3
                nError = math.hypot(nError, n3Error)
            if n == 0.0:
                nError = 0.5 * TMath.ChisquareQuantile(0.68, 2 * (n + 1))

            pFake = pFakeError = float("nan")

            # For ZtoMuMu control regions, need to normalize to BasicSelection
            if hasattr(self, "ZtoLL") and hasattr(self, "Basic"):
                norm = self.Basic["yield"] / self.ZtoLL["yield"]
                normError = norm * math.hypot(
                    self.Basic["yieldError"] / self.Basic["yield"],
                    self.ZtoLL["yieldError"] / self.ZtoLL["yield"])

                pFake = n / self.ZtoLL["yield"]
                pFakeError = math.hypot(
                    n * self.ZtoLL["yieldError"],
                    nError * self.ZtoLL["yield"]) / (self.ZtoLL["yield"] *
                                                     self.ZtoLL["yield"])

                n = n * norm
                nError = math.hypot(n * normError, nError * norm)
            elif hasattr(self, "Basic"):
                pFake = n / self.Basic["yield"]
                pFakeError = math.hypot(
                    n * self.Basic["yieldError"],
                    nError * self.Basic["yield"]) / (self.Basic["yield"] *
                                                     self.Basic["yield"])

            n *= self._prescale
            nError *= self._prescale

            if n > 0.0:
                print "N_ctrl: " + str(n) + " +- " + str(nError) + " (" + str(
                    n / self._luminosityInInvFb) + " +- " + str(
                        nError / self._luminosityInInvFb) + " fb)"
            else:
                print "N_ctrl: " + str(n) + " - 0.0 + " + str(
                    nError) + " (" + str(
                        n / self._luminosityInInvFb) + " - 0 + " + str(
                            nError / self._luminosityInInvFb) + " fb)"
            return (n, nError, pFake, pFakeError)
        else:
            print "DisTrkInvertD0 is not defined. Not printing N_ctrl..."
            return (float("nan"), float("nan"), float("nan"), float("nan"))