Ejemplo n.º 1
0
 def normalizeSignal(self,S_exp,**kwargs):
     """Calculates normalization for a given expected signal yield."""
     
     verbosity   = kwargs.get('verbosity',0)
     cuts        = [ ("%s && %s" % (baseline, category1)),
                     ("%s && %s" % (baseline, category2)), ]
     cuts        = kwargs.get('cuts',cuts)
     weight      = kwargs.get('weight',"")
     (aa,bb)     = kwargs.get('signalregion',(0,40))
     
     N  = 0; MC = 0
     scale = 1
     for i,cut in enumerate(cuts):
         cut     = combineCuts("m_sv>0", cut)
         name    = "m_sv_for_signal_renormalization_%d" % i
         hist    = self.hist("m_sv",100,aa,bb,name=name,cuts=cut,weight=weight)
         N       += hist.GetSumOfWeights()
         MC      += hist.GetEntries()
         gDirectory.Delete(name)
     
     if N:
         scale = S_exp / N * self.scale
         printVerbose(">>> normalizeSignal: S_exp=%.4f, N=%.4f, MC=%.1f, old scale=%.4f, scale=%.4f" % (S_exp, N, MC, self.scale, scale), verbosity)
         printVerbose(">>> normalizeSignal: signalregion=(%.1f,%.1f)" % (aa,bb),verbosity)
     else: print warning("Could not find normalization for signal: no MC events in given signal region after cuts (%s)!" % cuts)
     self.setAllScales(scale)
     
     return scale
Ejemplo n.º 2
0
 def hist2D(self, var1, nBins1, a1, b1, var2, nBins2, a2, b2, **kwargs):
     """Make a 2D histogram with a tree."""
     
     scale   = kwargs.get('scale', 1.0) * self.scale
     tree    = self.file.Get(self.treeName)
     name    = kwargs.get('name',  makeHistName(self.label, "%s_vs_%s" % (var1,var2)))
     title   = kwargs.get('title', self.label)
     verbosity = kwargs.get('verbosity', 0)
     
     blindcuts = ""
     if var1 in self.blind: blindcuts += self.blind[var1]
     if var2 in self.blind: blindcuts += self.blind[var2]
     weight = combineWeights(self.weight, kwargs.get('weight', ""))
     cuts   = combineCuts(self.cuts, kwargs.get('cuts', ""), blindcuts, weight=weight)
     printVerbose(">>>>\n>>> Sample - %s, %s vs. %s: %s" % (color(name,color="grey"), var1, var2, self.filenameshort),verbosity)
     printVerbose(">>>    scale:  %.4f"    % (scale),verbosity)
     printVerbose(">>>    weight: %s"      % (weight),verbosity)
     printVerbose(">>>    %s" % (cuts),verbosity)
     
     hist2D = TH2F(name, title, nBins2, a2, b2, nBins1, a1, b1)
     out = tree.Draw("%s:%s >> %s" % (var1,var2,name), cuts, "gOff")
     if out < 0: print error("Drawing histogram for %s sample failed!" % (title))
     
     #if scale is not 1.0: hist.Scale(scale)
     #if scale is     0.0: print warning("Scale of %s is 0!" % self.label)
     return hist2D
Ejemplo n.º 3
0
 def hist(self, var, nBins, a, b, **kwargs):
     """Make a histogram with a tree."""
     
     scale   = kwargs.get('scale', 1.0) * self.scale
     tree    = self.file.Get(self.treeName)
     name    = kwargs.get('name',  makeHistName(self.label, var))
     title   = kwargs.get('title', self.label)
     shift   = kwargs.get('shift', 0)
     smear   = kwargs.get('smear', 0)
     verbosity = kwargs.get('verbosity', 0)
     
     if self.isSignal and self.scale is not self.scaleBU and self.scaleBU:
         title += " (#times%d)" % (self.scale/self.scaleBU)
     
     blindcuts = ""
     if var in self.blind: blindcuts = self.blind[var]
     weight = combineWeights(self.weight, kwargs.get('weight', ""))
     cuts   = combineCuts(self.cuts, kwargs.get('cuts', ""), blindcuts, weight=weight)
     
     hist = TH1F(name, title, nBins, a, b)
     out = tree.Draw("%s >> %s" % (var,name), cuts, "gOff")
     
     if shift or smear:
         mean0 = hist.GetMean()
         #smear = min(1,smear)
         #smear = sqrt(smear*smear-1) #*sigma
         #tree.SetAlias("rng","sin(2*pi*rndm)*sqrt(-2*log(rndm))")
         var2 = "%s*%s + %s + %s*%s" % (var,smear,shift,(1-smear),mean0)
         tree.Draw("%s >> %s" % (var2,name), cuts, "gOff")
     if out < 0: print error("Drawing histogram for %s sample failed!" % (title))
     
     if scale is not 1.0: hist.Scale(scale)
     if scale is     0.0: print warning("Scale of %s is 0!" % self.label)
     #print hist.GetEntries()
     #gDirectory.Delete(label)
     
     printVerbose(">>>\n>>> Sample - %s, %s: %s" % (color(name,color="grey"), var, self.filenameshort),verbosity)
     printVerbose(">>>    scale:  %.4f (%.4f)" % (scale,self.scale),verbosity)
     printVerbose(">>>    weight: %s" % (("\n>>>%s*("%(' '*18)).join(weight.rsplit('*(',max(0,weight.count("*(")-1)))),verbosity)
     printVerbose(">>>    %s" % (cuts.replace("*(","\n>>>%s*("%(' '*18))),verbosity)
     return hist
Ejemplo n.º 4
0
    def histAndColor(self, var, nBins, a, b, **kwargs):
        '''Return a list of tuples containing a histogram and a color.
           Return multiple ntuples if a sample need to be split.'''

        split = kwargs.get('split', False) and len(self.split)
        verbosity = kwargs.get('verbosity', 0)

        if split:
            printVerbose(">>> histAndColor: splitting %s" % (self.label),
                         verbosity)
            histsAndColors = []
            cuts0 = kwargs.get('cuts', "")
            for key, (splitlabel, splitcut,
                      splitcolor) in self.split.iteritems():
                kwargs['cuts'] = combineCuts(cuts0, splitcut)
                kwargs['title'] = splitlabel
                kwargs['append_name'] = "_%s" % (key)
                hist = self.hist(var, nBins, a, b, **kwargs)
                histsAndColors.append((hist, splitcolor))
            return histsAndColors
        else:
            printVerbose(">>> histAndColor: not splitting", verbosity, level=2)
            hist = self.hist(var, nBins, a, b, **kwargs)
            return [(hist, self.color)]
Ejemplo n.º 5
0
    def hist(self, var, nBins, a, b, **kwargs):
        """Make a histogram with a tree."""

        scale = kwargs.get('scale', 1.0) * self.scale
        treeName = kwargs.get('treeName', self.treeName)
        name = kwargs.get('name', makeHistName(self.label, var))
        name += kwargs.get('append_name', "")
        title = kwargs.get('title', self.label)
        shift = kwargs.get('shift', 0)
        smear = kwargs.get('smear', 0)
        blind = kwargs.get('blind', self.blind)
        verbosity = kwargs.get('verbosity', 0)

        if self.isSignal and self.scale is not self.scaleBU and self.scaleBU:
            title += " (#times%d)" % (self.scale / self.scaleBU)

        blindcuts = ""
        if var in blind and "SS" not in name:
            blindcuts = blind[
                var]  # TODO: blind by removing bins from hist or rounding? FindBin(a), SetBinContent
        weight = combineWeights(self.weight, kwargs.get('weight', ""))
        cuts = combineCuts(self.cuts,
                           kwargs.get('cuts', ""),
                           blindcuts,
                           weight=weight)

        tree = self.file.Get(treeName)
        if not tree or not isinstance(tree, TTree):
            print error("Could not find tree \"%s\" for %s! Check %s" %
                        (treeName, self.label, self.filenameshort))

        hist = TH1D(name, title, nBins, a, b)
        hist.Sumw2()
        out = tree.Draw("%s >> %s" % (var, name), cuts, "gOff")

        if shift or (smear and smear != 1):
            mean0 = hist.GetMean()
            #smear = min(1,smear)
            #smear = sqrt(smear*smear-1) #*sigma
            #tree.SetAlias("rng","sin(2*pi*rndm)*sqrt(-2*log(rndm))")
            var2 = "%s*%s + %s + %s*%s" % (var, smear, shift,
                                           (1 - smear), mean0)
            tree.Draw("%s >> %s" % (var2, name), cuts, "gOff")
        if out < 0:
            print error("Drawing histogram for %s sample failed!" % (title))

        if scale is not 1.0: hist.Scale(scale)
        if scale is 0.0: print warning("Scale of %s is 0!" % self.label)
        if verbosity > 2: printBinError(hist)
        #print hist.GetEntries()
        #gDirectory.Delete(label)

        printVerbose(
            ">>>\n>>> Sample - %s, %s: %s (%s)" % (color(
                name, color="grey"), var, self.filenameshort, self.treeName),
            verbosity)
        printVerbose(">>>    scale:   %.4f (%.4f)" % (scale, self.scale),
                     verbosity)
        printVerbose(
            ">>>    weight:  %s" % (("\n>>>%s*(" % (' ' * 18)).join(
                weight.rsplit('*(', max(0,
                                        weight.count("*(") - 1)))), verbosity)
        printVerbose(
            ">>>    entries: %d (%.2f integral)" %
            (hist.GetEntries(), hist.Integral()), verbosity)
        printVerbose(
            ">>>    %s" % (cuts.replace("*(", "\n>>>%s*(" % (' ' * 18))),
            verbosity)
        return hist
Ejemplo n.º 6
0
def renormalizeTT(samples, **kwargs):
    """Helpfunction to renormalize TT."""

    var = kwargs.get('var', "pfmt_1")
    label = kwargs.get('label', "baseline")
    QCD = kwargs.get('QCD', True)
    channel = kwargs.get('channel', "mutau")
    cuts = kwargs.get('cuts', baseline)
    reset = kwargs.get('reset', True)
    shift_QCD = kwargs.get('shift_QCD', 0)  # e.g. 0.30
    prepend = kwargs.get('prepend', "")
    verbosity = kwargs.get('verbosity', 0)
    savedscale = 0
    category = ""
    #print header("%s: TT renormalization" % (channel))
    print ">>>\n>>> renormalizing TT..."

    # GET sample
    sampleTT = getSample(samples, "TT", unique=True)
    if not sampleTT:
        print warning("renormalizeTT: Could not renormalize TT: no TT sample.")
        print ">>>"
        return

    # CHECK category
    if "category 1" in label:
        category = "category 1"
        cuts = combineCuts(cuts,
                           category1TT)  # "%s && %s" % (baseline, category1TT)
    elif "category 2" in label:
        category = "category 2"
        cuts = combineCuts(cuts,
                           category2TT)  # "%s && %s" % (baseline, category2TT)
    else:
        print ">>>   category does not apply for TT renormalization"
        if sampleTT.scale != sampleTT.scaleBU:
            print ">>>   resetting TT scale %.3f back to %.3f" % (
                sampleTT.scale, sampleTT.scaleBU)
            sampleTT.scale = sampleTT.scaleBU
        print ">>>"
        return

    # CHECK is scale is already saved
    savedscale = TTscales[channel][category]
    if savedscale > 0:
        sampleTT.scale = sampleTT.scaleBU * savedscale
        print ">>>   using old TT bar renormalizaion scale %.2f from %s" % (
            savedscale, category)
        print ">>>   TT renormalization scale = %.3f (new total scale = %.3f)" % (
            savedscale, sampleTT.scale)
        print ">>>"
        return

    # CALCULATE and SAVE scale
    name = "%s/%s%s/%s_%s_TTrenormalization.png" % (PLOTS_DIR, channel,
                                                    mylabel, var, label)
    title = "%s: %s" % (channel.replace("tau", "#tau").replace("mu",
                                                               "#mu"), label)
    plot = Plot(samples,
                var,
                200,
                0,
                400,
                cuts=cuts,
                QCD=QCD,
                reset=True,
                shift_QCD=shift_QCD,
                verbosity=verbosity)
    #plot.plot(stack=True, title=title, staterror=True, ratio=True)
    scale = plot.renormalizeTT(prepend=prepend, verbosity=verbosity)
    plot.close()
    #plot.saveAs(name,save=True)

    # SAVE
    TTscales[channel][category] = scale
    print ">>> "