Example #1
0
def showENC():
    fname1 = '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat'

    tree1 = TTree()
    tree1.ReadFile(
        '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat',
        'idX/i:vL/F:vH:A:D/i:R:W')
    tree1.ReadFile(
        '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan2_mod.dat'
    )

    tree1.Show(500)

    p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', 50, 0.12, 0.2)
    tree1.Draw("D:(vH-vL)>>p1", "", "profE")

    ### change it to tgraph
    g1 = TGraphErrors()
    for i in range(p1.GetNbinsX() + 2):
        N = p1.GetBinEntries(i)
        if N > 0:
            print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(
                i), p1.GetBinError(i)
            n = g1.GetN()
            g1.SetPoint(n, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i))
            g1.SetPointError(n, 0, p1.GetBinError(i))


#     g1.SetMarkerColor(3)
#     g1.SetLineColor(3)

    p1.Draw("axis")
    g1.Draw('Psame')

    fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))',
               0.05, 0.3)
    fun1.SetParameter(0, 0.155)
    fun1.SetParameter(1, 0.005)

    g1.Fit(fun1)
    fun1a = g1.GetFunction('fun1')

    #     p1.Fit(fun1)
    #     fun1a = p1.GetFunction('fun1')
    fun1a.SetLineColor(2)

    #     p1.Draw("Esame")

    v0 = fun1a.GetParameter(0)
    e0 = fun1a.GetParError(0)
    v1 = fun1a.GetParameter(1)
    e1 = fun1a.GetParError(1)

    print v0, v1

    fUnit = 1000.
    lt = TLatex()
    lt.DrawLatexNDC(
        0.185, 0.89,
        '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit))
    lt.DrawLatexNDC(
        0.185, 0.84,
        '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit))

    print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)
    fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1))
    fun2.SetLineColor(4)
    fun2.SetLineStyle(2)
    fun2.Draw('same')

    lg = TLegend(0.7, 0.4, 0.95, 0.5)
    lg.SetFillStyle(0)
    lg.AddEntry(p1, 'Measurement', 'p')
    lg.AddEntry(fun1a, 'Fit', 'l')
    lg.AddEntry(fun2, 'Gaus', 'l')
    lg.Draw()

    waitRootCmdX()
Example #2
0
def limitCompare(method):
    signal, particle, particleP = "XVH", "V", "V'"

    channels = [
        "ah", "wrhpbb", "wrhpb", "wrlpbb", "wrlpb", "zrhpbb", "zrhpb",
        "zrlpbb", "zrlpb"
    ]
    colors = [
        1, 610 + 4, 632, 800 + 7, 800, 416 + 1, 860 + 10, 600, 616, 921, 922
    ]
    masses, vals, graphs = {}, {}, {}
    for j, c in enumerate(channels):
        masses[c], vals[c] = fillValues("./combine/" + method + "/" + signal +
                                        c + "_M%d.txt")
        graphs[c] = TGraph()
        n = 0
        #print vals[c]
        for i, m in enumerate(masses[c]):
            #if not signals[i] >= 1000: continue
            graphs[c].SetPoint(n, m, vals[c][m][3])
            n = n + 1
        graphs[c].SetLineColor(colors[j])
        graphs[c].SetLineWidth(3)
        graphs[c].Draw("SAME, L")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    c1.GetPad(0).SetLogy()
    for c in channels:
        graphs[c].Draw("AL" if 'ah' in c else "SAME, L")
    graphs[channels[0]].GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])
    graphs[channels[0]].GetYaxis().SetRangeUser(0.25, 2.5e4)
    graphs[channels[0]].GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    graphs[channels[0]].GetYaxis().SetTitle(
        "#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP +
        " #rightarrow " + particle +
        "H) #bf{#it{#Beta}}(H #rightarrow bb) (fb)")
    drawAnalysis(signal)
    #drawRegion(signal, True)
    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)

    # legend
    top = 0.9
    leg = TLegend(0.4, top - len(channels) * 0.2 / 5., 0.99, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL expected limits")
    for c in channels:
        leg.AddEntry(graphs[c], getChannel(c), "l")
    leg.Draw()

    c1.Update()

    c1.Print("plotsLimit/Multi.png")
    c1.Print("plotsLimit/Multi.pdf")
Example #3
0
hps_event = HpsEvent()
b_hps_event = dst_tree.GetBranch("Event")
b_hps_event.SetAddress(AddressOf(hps_event))

canvas = TCanvas("canvas", "Extrapolation Analysis", 800, 800)

h_track_d0 = TH1F("h_track_d0", "Track D0", 100, -1.5, 1.5)
h_track_d0.SetLineColor(kAzure + 2)
h_track_d0.SetMarkerColor(kAzure + 2)
h_gbl_track_d0 = TH1F("h_gbl_track_d0", "GBL Track D0", 100, -1.5, 1.5)
h_gbl_track_d0.SetLineColor(kRed + 1)
h_gbl_track_d0.SetMarkerColor(kRed + 1)

legend = TLegend(0.7, 0.8, 0.9, 0.9, "", "brNDC")
legend.SetBorderSize(0)
legend.SetFillStyle(0)

legend.AddEntry(h_track_d0, "Seed Tracker", "lp")
legend.AddEntry(h_gbl_track_d0, "GBL Track", "lp")

h_gbl_target_residuals_bp_vs_p_5hit = TH2F(
    "h_gbl_target_residuals_bp_vs_p_5hit",
    "Bend Plane Residuals at the Target - 5 Hit Tracks", 10, 0, 2.5, 240, -30,
    30)
h_gbl_target_residuals_bp_vs_p_6hit = TH2F(
    "h_gbl_target_residuals_bp_vs_p_6hit",
    "Bend Plane Residuals at the Target - 6 Hit Tracks", 10, 0, 2.5, 240, -30,
    30)
h_gbl_sp_residuals_bp_vs_p_5hit = TH2F(
    "h_gbl_sp_residuals_bp_vs_p_5hit",
    "Bend Plane Residuals at Scoring Plane vs Momentum - 5 Hit Tracks", 10, 0,
Example #4
0
class DataMCPlot(object):

    '''Handles a Data vs MC plot.

    Features a list of histograms (some of them being stacked),
    and several Drawing functions.
    '''
    _f_keeper = {}
    _t_keeper = {}

    def __init__(self, name, signal2show):
        self.histosDict = {}
        self.histos = []
        self.supportHist = None
        self.name = name
        self.stack = None
        self.legendOn = True
        self.legend = None
        self.legendBorders = 0.20, 0.43, 0.44, 0.86
        self.legendPos = 'left'
        # self.lastDraw = None
        # self.lastDrawArgs = None
        self.nostack = None
        self.blindminx = None
        self.blindmaxx = None
        self.groups = {}
        self.axisWasSet = False
        self.histPref = histPref
        self.signal2show = signal2show

    def __contains__(self, name):
        return name in self.histosDict

    def __getitem__(self, name):        
#        if name in self.histosDict:
        return self.histosDict[name]

    def readTree(self, file_name, tree_name='tree'):
        '''Cache files/trees'''
        if file_name in self.__class__._t_keeper:
            ttree = self.__class__._t_keeper[file_name]
        else:
            tfile = self.__class__._f_keeper[file_name] = TFile.Open(file_name)
            ttree = self.__class__._t_keeper[file_name] = tfile.Get(tree_name)

        gROOT.cd()

        return ttree

    def Blind(self, minx, maxx, blindStack):
        self.blindminx = minx
        self.blindmaxx = maxx
        if self.stack and blindStack:
            self.stack.Blind(minx, maxx)
        if self.nostack:
            for hist in self.nostack:
                hist.Blind(minx, maxx)

    def AddHistogram(self, name, histo, layer=0, legendLine=None, stack=True):
        '''Add a ROOT histogram, with a given name.

        Histograms will be drawn by increasing layer.'''
        tmp = Histogram(name, histo, layer, legendLine, stack=stack)
        self.histos.append(tmp)
        self.histosDict[name] = tmp
        return tmp

    def Group(self, groupName, namesToGroup, layer=None, style=None):
        '''Group all histos with names in namesToGroup into a single
        histo with name groupName. All histogram properties are taken
        from the first histogram in namesToGroup.
        See UnGroup as well
        '''
        groupHist = None
        realNames = []
        actualNamesInGroup = []
        for name in namesToGroup:
            hist = self.histosDict.get(name, None)
            if hist is None:
                print 'warning, no histo with name', name
                continue
            if groupHist is None:
                groupHist = hist.Clone(groupName)
                self.histos.append(groupHist)
                self.histosDict[groupName] = groupHist
            else:
                groupHist.Add(hist)
            actualNamesInGroup.append(name)
            realNames.append(hist.realName)
            hist.on = False
        if groupHist:
            self.groups[groupName] = actualNamesInGroup
            groupHist.realName = ','.join(realNames)
            if style is not None:
                groupHist.SetStyle(style)
            self._ApplyPrefs()

    def UnGroup(self, groupName):
        '''Ungroup groupName, recover the histograms in the group'''
        group = self.groups.get(groupName, None)
        if group is None:
            print groupName, 'is not a group in this plot.'
            return
        for name in group:
            self.histosDict[name].on = True
        self.histosDict[groupName].on = False

    def Replace(self, name, pyhist):
        '''Not very elegant... should have a clone function in Histogram...'''
        oldh = self.histosDict.get(name, None)
        if oldh is None:
            print 'histogram', name, 'does not exist, cannot replace it.'
            return

        pythist = copy.deepcopy(pyhist)
        pythist.layer = oldh.layer
        pythist.stack = oldh.stack
        pythist.name = oldh.name
        pythist.legendLine = oldh.legendLine
        pythist.SetStyle(oldh.style)
        pythist.weighted.SetFillStyle(oldh.weighted.GetFillStyle())

        index = self.histos.index(oldh)
        self.histosDict[name] = pythist
        self.histos[index] = pythist

    def _SortedHistograms(self, reverse=False):
        '''Returns the histogram dictionary, sorted by increasing layer,
        excluding histograms which are not "on".

        This function is used in all the Draw functions.'''
        byLayer = sorted(self.histos, key=attrgetter('layer'))
        byLayerOn = [hist for hist in byLayer if (hist.on is True)]
        if reverse:
            byLayerOn.reverse()
        return byLayerOn

    def Hist(self, histName):
        '''Returns a histogram.

        Print the DataMCPlot object to see which histograms are available.'''
        if self.histosDict.has_key(histName):
            return self.histosDict[histName]
        else:
            return None

    def DrawNormalized(self, opt=''):
        '''All histograms are drawn as PDFs, even the stacked ones'''
        same = ''
        for hist in self._SortedHistograms():
            hist.obj.DrawNormalized(same + opt)
            if same == '':
                same = 'same'
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalized'
        # self.lastDrawArgs = [ opt ]

    def Draw(self, opt=''):
        '''All histograms are drawn.'''
        same = ''
        self.supportHist = None
        for hist in self._SortedHistograms():
            if self.supportHist is None:
                self.supportHist = hist
            hist.Draw(same + opt)
            if same == '':
                same = 'same'
        yaxis = self.supportHist.GetYaxis()
        yaxis.SetRangeUser(0.01, ymax(self._SortedHistograms()))
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'Draw'
        # self.lastDrawArgs = [ opt ]

    def CreateLegend(self, ratio=False, print_norm=False):
        if self.legend is None:
            self.legend = TLegend(*self.legendBorders)
            self.legend.SetFillColor(0)
            self.legend.SetFillStyle(0)
            self.legend.SetLineColor(0)
        else:
            self.legend.Clear()
        hists = self._SortedHistograms(reverse=True)
        if ratio:
            hists = hists[:-1]  # removing the last histo.
        for index, hist in enumerate(hists):
            if print_norm:
                if not hist.legendLine:
                    hist.legendLine = hist.name
                hist.legendLine += ' ({norm:.1f})'.format(norm=hist.Yield())

            if hist.name.find('LQ')!=-1 or hist.name.find('Zprime')!=-1:
                if hist.name in self.signal2show:
                    hist.AddEntry(self.legend)
            else:
                hist.AddEntry(self.legend)

    def DrawLegend(self, ratio=False, print_norm=False):
        '''Draw the legend.'''
        if self.legendOn:
            self.CreateLegend(ratio=ratio, print_norm=print_norm)
            self.legend.Draw('same')

    def DrawRatio(self, opt=''):
        '''Draw ratios : h_i / h_0.

        h_0 is the histogram with the smallest layer, and h_i, i>0 are the other histograms.
        if the DataMCPlot object contains N histograms, N-1 ratio plots will be drawn.
        To take another histogram as the denominator, change the layer of this histogram by doing:
        dataMCPlot.Hist("histName").layer = -99 '''
        same = ''
        denom = None
        self.ratios = []
        for hist in self._SortedHistograms():
            if denom == None:
                denom = hist
                continue
            ratio = copy.deepcopy(hist)
            ratio.obj.Divide(denom.obj)
            ratio.obj.Draw(same)
            self.ratios.append(ratio)
            if same == '':
                same = 'same'
        self.DrawLegend(ratio=True)
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawRatio'
        # self.lastDrawArgs = [ opt ]

    def DrawDataOverMCMinus1(self, ymin=-0.5, ymax=0.5):
        stackedHists = []
        dataHist = None
        for hist in self._SortedHistograms():
            if hist.stack is False:
                dataHist = hist
                continue
            stackedHists.append(hist)
        self._BuildStack(stackedHists, ytitle='Data/MC')
        mcHist = self.stack.totalHist
        self.dataOverMCHist = copy.deepcopy(dataHist)
        # self.dataOverMCHist.Add(mcHist, -1)
        self.dataOverMCHist.Divide(mcHist)
        self.dataOverMCHist.Draw()
        yaxis = self.dataOverMCHist.GetYaxis()
        yaxis.SetRangeUser(ymin + 1., ymax + 1.)
        yaxis.SetTitle('Data/MC')
        yaxis.SetNdivisions(5)
        fraclines = 0.2
        if ymax <= 0.2 or ymin >= -0.2:
            fraclines = 0.1
        self.DrawRatioLines(self.dataOverMCHist, fraclines, 1.)
        if TPad.Pad():
            TPad.Pad().Update()

    def DrawRatioStack(self, opt='',
                       xmin=None, xmax=None, ymin=None, ymax=None):
        '''Draw ratios.

        The stack is considered as a single histogram.'''
        denom = None
        # import pdb; pdb.set_trace()
        histForRatios = []
        denom = None
        for hist in self._SortedHistograms():
            if hist.stack is False:
                # if several unstacked histograms, the highest layer is used
                denom = hist
                continue
            histForRatios.append(hist)
        self._BuildStack(histForRatios, ytitle='MC/Data')
        self.stack.Divide(denom.obj)
        if self.blindminx and self.blindmaxx:
            self.stack.Blind(self.blindminx, self.blindmaxx)
        self.stack.Draw(opt,
                        xmin=xmin, xmax=xmax,
                        ymin=ymin, ymax=ymax)
        self.ratios = []
        for hist in self.nostack:
            if hist is denom:
                continue
            ratio = copy.deepcopy(hist)
            ratio.obj.Divide(denom.obj)
            ratio.obj.Draw('same')
            self.ratios.append(ratio)
        self.DrawLegend(ratio=True)
        self.DrawRatioLines(denom, 0.2, 1)
        if TPad.Pad():
            TPad.Pad().Update()

    def DrawNormalizedRatioStack(self, opt='',
                                 xmin=None, xmax=None,
                                 ymin=None, ymax=None):
        '''Draw ratios.

        The stack is considered as a single histogram.
        All histograms are normalized before computing the ratio'''
        denom = None
        histForRatios = []
        for hist in self._SortedHistograms():
            # taking the first histogram (lowest layer)
            # as the denominator histogram.
            if denom == None:
                denom = copy.deepcopy(hist)
                continue
            # other histograms will be divided by the denominator
            histForRatios.append(hist)
        self._BuildStack(histForRatios, ytitle='MC p.d.f. / Data p.d.f.')
        self.stack.Normalize()
        denom.Normalize()
        self.stack.Divide(denom.weighted)
        self.stack.Draw(opt,
                        xmin=xmin, xmax=xmax,
                        ymin=ymin, ymax=ymax)
        self.ratios = []
        for hist in self.nostack:
            # print 'nostack ', hist
            ratio = copy.deepcopy(hist)
            ratio.Normalize()
            ratio.obj.Divide(denom.weighted)
            ratio.obj.Draw('same')
            self.ratios.append(ratio)
        self.DrawLegend(ratio=True)
        self.DrawRatioLines(denom, 0.2, 1)
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalizedRatioStack'
        # self.lastDrawArgs = [ opt ]

    def DrawRatioLines(self, hist, frac=0.2, y0=1.):
        '''Draw a line at y = 1, at 1+frac, and at 1-frac.

        hist is used to get the x axis range.'''
        xmin = hist.obj.GetXaxis().GetXmin()
        xmax = hist.obj.GetXaxis().GetXmax()
        line = TLine()
        line.DrawLine(xmin, y0, xmax, y0)
        line.SetLineStyle(2)
        line.DrawLine(xmin, y0+frac, xmax, y0+frac)
        line.DrawLine(xmin, y0-frac, xmax, y0-frac)

    def GetStack(self):
        '''Returns stack; builds stack if not there yet'''
        if not self.stack:
            self._BuildStack(self._SortedHistograms(), ytitle='Events')
        return self.stack

    def returnTotal(self):
        return self.stack.totalHist

    def DrawStack(self, opt='',
                  xmin=None, xmax=None, ymin=None, ymax=None, factor=None, print_norm=False):
        '''Draw all histograms, some of them in a stack.

        if Histogram.stack is True, the histogram is put in the stack.'''
        self._BuildStack(self._SortedHistograms(), ytitle='Events')
        same = 'same'
        if len(self.nostack) == 0:
            same = ''
        self.supportHist = None
        for hist in self.nostack:
#            hist.Draw()
            if not self.supportHist:
                self.supportHist = hist
        self.stack.Draw(opt+same,
                        xmin=xmin, xmax=xmax,
                        ymin=ymin, ymax=ymax, factor=factor)
        if self.supportHist is None:
            self.supportHist = self.stack.totalHist
        if not self.axisWasSet:
            mxsup = self.supportHist.weighted.GetBinContent(
                self.supportHist.weighted.GetMaximumBin()
            )
            mxstack = self.stack.totalHist.weighted.GetBinContent(
                self.stack.totalHist.weighted.GetMaximumBin()
            )
            mx = max(mxsup, mxstack)
            if ymin is None:
                ymin = 0.01
            if ymax is None:
                ymax = mx*1.3
            self.supportHist.GetYaxis().SetRangeUser(ymin, ymax)
            self.axisWasSet = True
        for hist in self.nostack:

#            import pdb; pdb.set_trace()


            if self.blindminx:
                hist.Blind(self.blindminx, self.blindmaxx)

#            hist.Draw('same')

#            print 'Check', hist.name, self.signal2show

            if hist.name.find('LQ')!=-1 or hist.name.find('Zprime')!=-1:
                if hist.name in self.signal2show:
#                    print 'PASS!!!!!!!!!!!!!!!!!!!!!!!'
                    hist.Draw('same')
            else:
                hist.Draw('same')


        if self.supportHist.weighted.GetMaximumBin() < self.supportHist.weighted.GetNbinsX()/2:
#            self.legendBorders = 0.62, 0.46, 0.88, 0.89
            self.legendPos = 'right'

        self.DrawLegend(print_norm=print_norm)
        if TPad.Pad():
            TPad.Pad().Update()

    def DrawNormalizedStack(self, opt='',
                            xmin=None, xmax=None, ymin=0.001, ymax=None):
        '''Draw all histograms, some of them in a stack.

        if Histogram.stack is True, the histogram is put in the stack.
        all histograms out of the stack, and the stack itself, are shown as PDFs.'''
        self._BuildStack(self._SortedHistograms(), ytitle='p.d.f.')
        self.stack.DrawNormalized(opt,
                                  xmin=xmin, xmax=xmax,
                                  ymin=ymin, ymax=ymax)
        for hist in self.nostack:
            hist.obj.DrawNormalized('same')
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalizedStack'
        # self.lastDrawArgs = [ opt ]

    def Rebin(self, factor):
        '''Rebin, and redraw.'''
        # the dispatching technique is not too pretty,
        # but keeping a self.lastDraw function initialized to one of the Draw functions
        # when calling it creates a problem in deepcopy.
        for hist in self.histos:
            hist.Rebin(factor)
        self.axisWasSet = False

    def NormalizeToBinWidth(self):
        '''Normalize each Histograms bin to the bin width.'''
        for hist in self.histos:
            hist.NormalizeToBinWidth()

    def WriteDataCard(self, filename=None, verbose=True, 
                      mode='RECREATE', dir=None):
        '''Export current plot to datacard'''
        if not filename:
            filename = self.name+'.root'

        outf = TFile(filename, mode)
        if dir:
            outf_dir = outf.mkdir(dir)
            outf_dir.cd()

        for hist in self._SortedHistograms():
            'Writing', hist, 'as', hist.name
            # blinding ! 
#            if hist.name != 'data_obs':
            hist.weighted.Write(hist.name)
        outf.Write()

    def _BuildStack(self, hists, ytitle=None):
        '''build a stack from a list of Histograms.

        The histograms for which Histogram.stack is False are put in self.nostack'''
        self.stack = None
        self.stack = Stack(self.name+'_stack', ytitle=ytitle)
        self.nostack = []
        for hist in hists:
            if hist.stack:
                self.stack.Add(hist)
            else:
                self.nostack.append(hist)

    def _GetHistPref(self, name):
        '''Return the preference dictionary for a given component'''
        thePref = None
        for prefpat, pref in self.histPref.iteritems():
            if fnmatch.fnmatch(name, prefpat):
                if thePref is not None:
                    print 'several matching preferences for', name
                thePref = pref
        if thePref is None:
            print 'cannot find preference for hist', name
            thePref = {'style': Style(), 'layer': 999}
        return thePref

    def _ApplyPrefs(self):
        for hist in self.histos:
            pref = self._GetHistPref(hist.name)
            hist.layer = pref['layer']
            hist.SetStyle(pref['style'])
#            print hist.name
            hist.legendLine = pref['legend']

    def __str__(self):
        if self.stack is None:
            self._BuildStack(self._SortedHistograms(), ytitle='Events')
        tmp = [' '.join(['DataMCPlot: ', self.name])]
        tmp.append('Histograms:')
        for hist in self._SortedHistograms(reverse=True):
            tmp.append(' '.join(['\t', str(hist)]))
        tmp.append('Stack yield = {integ:7.1f}'.format(integ=self.stack.integral))
        return '\n'.join(tmp)
Example #5
0
def limit():
    method = ''
    channel = "bb"
    if INCLUDEACC:
        particleP = "X"
    else:
        particleP = "Z'"
    particle = 'b#bar{b}'
    multF = ZPTOBB
    THEORY = ['A1', 'B3']
    if INCLUDEACC: THEORY.append('SSM')

    mass_dict = {}
    val_dict = {}

    for BTAGGING in BTAGGING_WPS:
        suffix = "_" + BTAGGING
        if ISMC: suffix += "_MC"
        if SY: suffix += "_comb"
        #if method=="cls": suffix="_CLs"
        if INCLUDEACC: suffix += "_acc"

        if SY:
            filename = "./combine/limits/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt"
        else:
            filename = "./combine/limits/" + BTAGGING + "/" + YEAR + "_M%d.txt"
        if CATEGORY != "":
            if SY:
                if CATEGORY == 'bb_bq':
                    filename = filename.replace(
                        BTAGGING + "/combined_run2/",
                        BTAGGING + "/combined_run2/" + CATEGORY + "_combined_")
                else:
                    filename = filename.replace(
                        BTAGGING + "/combined_run2/", BTAGGING +
                        "/single_category/combined_run2/" + CATEGORY + "_")
            else:
                filename = filename.replace(
                    BTAGGING + "/",
                    BTAGGING + "/single_category/" + CATEGORY + "_")
            suffix += "_" + CATEGORY
        if ISMC: filename = filename.replace(".txt", "_MC.txt")
        mass_dict[BTAGGING], val_dict[BTAGGING] = fillValues(filename)

    #Obs0s = TGraph()
    #Exp0s = TGraph()
    #Exp1s = TGraphAsymmErrors()
    #Exp2s = TGraphAsymmErrors()
    #Sign = TGraph()
    #pVal = TGraph()
    #Best = TGraphAsymmErrors()
    Theory = {}
    Exp0s = {}
    for BTAGGING in BTAGGING_WPS:
        Exp0s[BTAGGING] = TGraph()

        for i, m in enumerate(mass_dict[BTAGGING]):
            if not m in val_dict[BTAGGING]:
                print "Key Error:", m, "not in value map"
                continue

            if INCLUDEACC:
                acc_factor = ACCEPTANCE[m]
            else:
                acc_factor = 1.

            n = Exp0s[BTAGGING].GetN()
            #Obs0s.SetPoint(n, m, val[m][0]*multF*acc_factor)
            Exp0s[BTAGGING].SetPoint(
                n, m, val_dict[BTAGGING][m][3] * multF * acc_factor)
            #Exp1s.SetPoint(n, m, val[m][3]*multF*acc_factor)
            #Exp1s.SetPointError(n, 0., 0., (val[m][3]-val[m][2])*multF*acc_factor, (val[m][4]-val[m][3])*multF*acc_factor)
            #Exp2s.SetPoint(n, m, val[m][3]*multF*acc_factor)
            #Exp2s.SetPointError(n, 0., 0., (val[m][3]-val[m][1])*multF*acc_factor, (val[m][5]-val[m][3])*multF*acc_factor)
            #if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6])
            #if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7])
            #if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8])
            #if len(val[m]) > 10: Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10])
            #print "m =", m, " --> Xsec*Br =", val[m][3]
        Exp0s[BTAGGING].SetLineStyle(1)
        Exp0s[BTAGGING].SetLineWidth(3)
        Exp0s[BTAGGING].SetLineColor(COLORS[BTAGGING])

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        Xs_dict = HVT[t]['Z']['XS'] if t != 'SSM' else SSM['Z']
        for m in sorted(Xs_dict.keys()):
            if INCLUDEACC and t != 'SSM':
                acc_factor = ACCEPTANCE[m]
            else:
                acc_factor = 1.
            if m < SIGNALS[0] or m > SIGNALS[-1]: continue
            #if m < mass[0] or m > mass[-1]: continue
            #if t!= 'SSM' and m>4500: continue ## I don't have the higher mass xs
            if m > 4500: continue
            XsZ, XsZ_Up, XsZ_Down = 0., 0., 0.
            if t != 'SSM':
                XsZ = 1000. * HVT[t]['Z']['XS'][m] * SSM["BrZ"][
                    m]  #assuming the same BR as the SSM Z' one
                XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1.,
                                                HVT[t]['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT[t]['Z']['QCD'][m][0],
                                             1. - HVT[t]['Z']['PDF'][m][0]))
            else:
                XsZ = 1000. * SSM['Z'][m] * SSM["BrZ"][m]
                XsZ_Up = XsZ * (1. +
                                math.hypot(HVT['A1']['Z']['QCD'][m][0] - 1.,
                                           HVT['A1']['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT['A1']['Z']['QCD'][m][0],
                                             1. - HVT['A1']['Z']['PDF'][m][0]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsZ * acc_factor)
            Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down) * acc_factor,
                                    (XsZ_Up - XsZ) * acc_factor)

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)

    #Exp2s.SetLineWidth(2)
    #Exp2s.SetLineStyle(1)
    #Obs0s.SetLineWidth(3)
    #Obs0s.SetMarkerStyle(0)
    #Obs0s.SetLineColor(1)
    #Exp0s.SetLineStyle(2)
    #Exp0s.SetLineWidth(3)
    #Exp1s.SetFillColor(417) #kGreen+1
    #Exp1s.SetLineColor(417) #kGreen+1
    #Exp2s.SetFillColor(800) #kOrange
    #Exp2s.SetLineColor(800) #kOrange
    Exp0s[BTAGGING_WPS[0]].GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Exp0s[BTAGGING_WPS[0]].GetXaxis().SetTitleSize(
        Exp0s[BTAGGING_WPS[0]].GetXaxis().GetTitleSize() * 1.25)
    Exp0s[BTAGGING_WPS[0]].GetXaxis().SetNoExponent(True)
    Exp0s[BTAGGING_WPS[0]].GetXaxis().SetMoreLogLabels(True)
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetTitle(
        "#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP +
        " #rightarrow " + particle +
        "){} (fb)".format(" #times #Alpha" if INCLUDEACC else ""))
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetTitleOffset(1.5)
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetNoExponent(True)
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetMoreLogLabels()

    #Sign.SetLineWidth(2)
    #Sign.SetLineColor(629)
    #Sign.GetXaxis().SetTitle("m_{"+particleP+"} (GeV)")
    #Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize()*1.1)
    #Sign.GetYaxis().SetTitle("Significance")

    #pVal.SetLineWidth(2)
    #pVal.SetLineColor(629)
    #pVal.GetXaxis().SetTitle("m_{"+particleP+"} (GeV)")
    #pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize()*1.1)
    #pVal.GetYaxis().SetTitle("local p-Value")

    #Best.SetLineWidth(2)
    #Best.SetLineColor(629)
    #Best.SetFillColor(629)
    #Best.SetFillStyle(3003)
    #Best.GetXaxis().SetTitle("m_{"+particleP+"} (GeV)")
    #Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize()*1.1)
    #Best.GetYaxis().SetTitle("Best Fit (pb)")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    #Exp2s.Draw("A3")
    #Exp1s.Draw("SAME, 3")
    for i, BTAGGING in enumerate(BTAGGING_WPS):
        if i == 0:
            Exp0s[BTAGGING].Draw("AL")
            #if not options.blind: Obs0s.Draw("SAME, L")
        else:
            Exp0s[BTAGGING].Draw("SAME, L")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s[BTAGGING_WPS[0]].GetXaxis().SetTitleSize(0.050)
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetTitleSize(0.050)
    Exp0s[BTAGGING_WPS[0]].GetXaxis().SetLabelSize(0.045)
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetLabelSize(0.045)
    Exp0s[BTAGGING_WPS[0]].GetXaxis().SetTitleOffset(0.90)
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetTitleOffset(1.25)
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetMoreLogLabels(True)
    Exp0s[BTAGGING_WPS[0]].GetYaxis().SetNoExponent(True)
    if INCLUDEACC:
        Exp0s[BTAGGING_WPS[0]].GetYaxis().SetRangeUser(0.05, 5.e3)
    else:
        Exp0s[BTAGGING_WPS[0]].GetYaxis().SetRangeUser(0.1, 5.e3)
    Exp0s[BTAGGING_WPS[0]].GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])

    #Exp0s.Draw("SAME, L")
    #if not options.blind: Obs0s.Draw("SAME, L")
    #Exp2s.GetXaxis().SetTitleSize(0.050)
    #Exp2s.GetYaxis().SetTitleSize(0.050)
    #Exp2s.GetXaxis().SetLabelSize(0.045)
    #Exp2s.GetYaxis().SetLabelSize(0.045)
    #Exp2s.GetXaxis().SetTitleOffset(0.90)
    #Exp2s.GetYaxis().SetTitleOffset(1.25)
    #Exp2s.GetYaxis().SetMoreLogLabels(True)
    #Exp2s.GetYaxis().SetNoExponent(True)
    #if INCLUDEACC:
    #    Exp2s.GetYaxis().SetRangeUser(0.05, 5.e3)
    #else:
    #    Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3)
    #Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])
    drawAnalysis("")
    drawRegion("", True)
    if CATEGORY == "":
        #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
        drawCMS(LUMI, "Preliminary")
        #drawCMS(LUMI, "", suppressCMS=True)
    else:
        #drawCMS(LUMI, "Work in Progress, "+CAT_LABELS[CATEGORY], suppressCMS=True)
        drawCMS(LUMI, "Preliminary   " + CAT_LABELS[CATEGORY])
        #drawCMS(LUMI, CAT_LABELS[CATEGORY], suppressCMS=True)

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top)
    #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    for BTAGGING in BTAGGING_WPS:
        leg.AddEntry(Exp0s[BTAGGING], "Expected {}".format(BTAGGING), "l")
    #leg.AddEntry(Obs0s, "Observed", "l")
    #leg.AddEntry(Exp0s, "Expected", "l")
    #leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    #leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY:
        leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)  #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()

    leg2.Draw()
    #if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR +
             "_WP_comparison.png")
    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR +
             "_WP_comparison.pdf")
    #if 'ah' in channel or 'sl' in channel:
    #    c1.Print("combine/plotsLimit/ExclusionLimits/"+YEAR+suffix+".C")
    #    c1.Print("combine/plotsLimit/ExclusionLimits/"+YEAR+suffix+".root")

    #for t in THEORY:
    #    print "Model", t, ":",
    #    for m in range(mass[0], mass[-1], 1):
    #        if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (Theory[t].Eval(m+1) > Obs0s.Eval(m+1)): print m, "(obs)",
    #        if not (Theory[t].Eval(m) > Exp0s.Eval(m)) == (Theory[t].Eval(m+1) > Exp0s.Eval(m+1)): print m, "(exp)",
    #    print ""

    return  ##FIXME

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".png")
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".pdf")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".root")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".C")

    # ---------- p-Value ----------
    c3 = TCanvas("c3", "p-Value", 800, 600)
    c3.cd()
    c3.GetPad(0).SetTopMargin(0.06)
    c3.GetPad(0).SetRightMargin(0.05)
    c3.GetPad(0).SetTicks(1, 1)
    c3.GetPad(0).SetGridx()
    c3.GetPad(0).SetGridy()
    c3.GetPad(0).SetLogy()
    pVal.Draw("AL3")
    pVal.GetYaxis().SetRangeUser(2.e-7, 0.5)

    ci = [
        1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303,
        0.000000001973
    ]
    line = TLine()
    line.SetLineColor(922)
    line.SetLineStyle(7)
    text = TLatex()
    text.SetTextColor(922)
    text.SetTextSize(0.025)
    text.SetTextAlign(12)
    for i in range(1, len(ci) - 1):
        line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2,
                      pVal.GetXaxis().GetXmax(), ci[i] / 2)
        text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2,
                       "%d #sigma" % i)

    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".png")
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".pdf")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".root")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".C")

    # --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".png")
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".pdf")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".root")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".C")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    if 'ah' in channel:
        outFile = TFile("bands.root", "RECREATE")
        outFile.cd()
        pVal.Write("graph")
        Best.Write("best")
        outFile.Close()
Example #6
0
def plot_signal( var, cut, norm=False ):

    colors = [ 616+4 , 800 , 416+1 , 800+7 , 860+10 , 600 , 616 , 921 , 922 ]

    if cut in selection: plotdir = cut
    pathname = PLOTDIR+"/signals/"+plotdir
    if not os.path.exists(pathname): os.system('mkdir -p %s'%pathname)

    histlist={}
    plt.cfg.register(sign) #sign is grouptag
    samples = plt.cfg.getModule('samples')
    
    CUT = ' '.join(filter( None , selection[cut].split(" ") ))
    signlist = plt.cfg.getGroupPlot()['Higgs']['samples']
    for i,isample in enumerate(signlist):
        WEIGHTS = "%s*(%s)" %( str(float(LUMI)/1000.) , expressAliases(samples[isample]['weight']) )
        filelist = [ x for x in samples[isample]['name'] ]
        files = makeVectorList(filelist)
        df = ROOT.RDataFrame("Events", files); gROOT.cd()
        histlist[isample] = makeHisto( df , var , CUT , WEIGHTS , isample )
        histlist[isample] = histlist[isample].GetPtr()
        histlist[isample].Sumw2()
        histlist[isample].SetLineWidth(2)
        histlist[isample].SetLineColor(colors[i])
    #######################################################################################################
    # add total histograms
    histlist['Higgs']=None
    for i, ihist in enumerate(histlist):
        if i==0:
            histlist['Higgs'] = histlist[ihist].Clone('totsignal')
            histlist['Higgs'].Sumw2()
        histlist['Higgs'].Add(histlist[ihist])
    
    leg = TLegend( 0.7 if not options.Statebox else 0.4 , 0.9-0.035*len(signlist), 0.9, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(1001) #1001                                                                                                                                    
    leg.SetFillColor(0)
    for s in signlist : leg.AddEntry(histlist[s], '%s [%.1f]' %( s , histlist[s].Integral() ) , "l")

    c1 = TCanvas("c1", "Signals", 800, 600)
    c1.cd().SetLogy() if options.logy else c1.cd()
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)

    hmax = 0.
    for i, s in enumerate(signlist):
        if histlist[s].GetMaximum() > hmax: hmax = histlist[s].GetMaximum()
    if not options.logy:
        histlist[signlist[0]].SetMaximum(hmax*1.2)
        histlist[signlist[0]].SetMinimum(0.)
    else:
        histlist[signlist[0]].SetMaximum(hmax*4)

    c1.cd()
    for i, s in enumerate(signlist):
        histlist[s].Draw("HIST" if i==0 else "SAMES, HIST")
        if options.Statebox:
            c1.GetPad(0).Update()
            if i==1:
                lof = histlist[s].GetListOfFunctions()
                statbox = lof.FindObject('stats')
                statbox.SetX1NDC(0.779026); statbox.SetX2NDC(0.979401)
                statbox.SetY1NDC(0.593168); statbox.SetY2NDC(0.754658)
    leg.Draw()

    drawCMS(LUMI, "Simulation")
    printTable_signal( histlist , pathname , '%s_%s.txt' %(plotdir,var) , signlist , histplease=True )
    ### fitting mass shape?
    ########################

    if gROOT.IsBatch():
        c1.Print(pathname+"/"+var.replace('.', '_')+".png")
        #c1.Print(pathname+"/"+var.replace('.', '_')+".pdf")
        
    #print col.WARNING+"PURGE OBJECTS IN MEMORY"+col.ENDC
    #for process in histlist:
    #    histlist[process].Delete()
    pass
Example #7
0
def draw(hist,
         channel,
         data,
         back,
         sign,
         snorm=1,
         lumi=-1,
         ratio=0,
         log=False):
    # If not present, create BkgSum
    if not 'BkgSum' in hist.keys():
        hist['BkgSum'] = hist['data_obs'].Clone(
            "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
        hist['BkgSum'].Reset("MICES")
        for i, s in enumerate(back):
            hist['BkgSum'].Add(hist[s])
    hist['BkgSum'].SetMarkerStyle(0)

    # Set Poisson error bars
    #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work

    alpha = 1 - 0.6827
    hist['data_obs'].SetBinErrorOption(TH1.kPoisson)
    data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX())
    data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle())
    data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize())
    res_graph = data_graph.Clone()
    for i in range(hist['data_obs'].GetNbinsX()):
        N = hist['data_obs'].GetBinContent(i + 1)
        B = hist['BkgSum'].GetBinContent(i + 1)
        L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.)
        U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1)
        data_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                            N if not N == 0 else -1.e99)
        data_graph.SetPointError(
            i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N)
        res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                           N / B if not B == 0 and not N == 0 else -1.e99)
        res_graph.SetPointError(
            i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            (N - L) / B if not B == 0 else -1.e99,
            (U - N) / B if not B == 0 else -1.e99)

    # Create stack
    bkg = THStack("Bkg",
                  ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    n = len([x for x in data + back + ['BkgSum'] + sign if sample[x]['plot']])
    leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pl")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            leg.AddEntry(hist[s],
                         sample[s]['label'].replace("m_{#Chi}=1 GeV",
                                                    ""), "fl")

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if ratio else 600)

    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)
    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.06)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if log:
        c1.GetPad(bool(ratio)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    #if len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data
    data_graph.Draw("SAME, PE")
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST",
                                   hist[s].Integral() * snorm)  # signals

    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075)
    bkg.SetMaximum((2. if log else 1.2) * max(
        bkg.GetMaximum(),
        hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)

    #if log: bkg.SetMinimum(1)
    leg.Draw()
    drawCMS(lumi, "Preliminary")
    drawRegion(channel)
    drawAnalysis(channel)

    #if nm1 and not cutValue is None: drawCut(cutValue, bkg.GetMinimum(), bkg.GetMaximum()) #FIXME
    if len(sign) > 0:
        if channel.startswith('X') and len(sign) > 0:
            drawNorm(0.9 - 0.04 * (n + 1),
                     "#sigma(X) #times B(X #rightarrow Vh) = %.1f pb" % snorm)
            #elif "SR" in channel: drawNorm(0.9-0.04*(n+1), "DM+bb/tt, scaled by %.0f" % snorm, "m_{#chi}=1 GeV, scalar mediator")
        elif "SR" in channel:
            drawNorm(0.9 - 0.04 * (n + 1), "DM+bb/tt, m_{#chi}=1 GeV",
                     "scalar mediator")

    setHistStyle(bkg, 1.2 if ratio else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1)

    if ratio:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        res = hist['data_obs'].Clone("Residues")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                res.SetBinContent(
                    i,
                    res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                res.SetBinError(
                    i,
                    res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
        setBotStyle(res)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if len(data) > 0:
            #res.Draw("SAME, PE0")
            res_graph.Draw("SAME, PE0")


#            if len(err.GetXaxis().GetBinLabel(1))==0: # Bin labels: not a ordinary plot
#                drawRatio(hist['data_obs'], hist['BkgSum'])
#                drawKolmogorov(hist['data_obs'], hist['BkgSum'])

    c1.Update()

    # return list of objects created by the draw() function
    return [c1, bkg, leg, err, errLine, res, data_graph, res_graph]
Example #8
0
def DrawOverlap(fileVec,
                histVec,
                titleVec,
                legendtext,
                pngname,
                logstatus=[0, 0],
                xRange=[-99999, 99999, 1]):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    gStyle.SetTitleOffset(1.1, "Y")
    #gStyle.SetTitleOffset(1.9,"X");
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3)

    i = 0

    histList_ = []
    histList = []
    histList1 = []
    maximum = []
    minimum = []

    ## Legend
    leg = TLegend(0.1, 0.80, 0.89, 0.89)  #,NULL,"brNDC");
    leg.SetBorderSize(0)
    leg.SetNColumns(3)
    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.05)

    c = TCanvas("c1", "c1", 0, 0, 500, 500)
    c.SetBottomMargin(0.15)
    c.SetLogy(logstatus[1])
    c.SetLogx(logstatus[0])
    print("you have provided " + str(len(fileVec)) + " files and " +
          str(len(histVec)) + " histograms to make a overlapping plot")
    print "opening rootfiles"
    c.cd()

    ii = 0
    inputfile = {}
    print str(fileVec[(len(fileVec) - 1)])

    for ifile_ in range(len(fileVec)):
        print("opening file  " + fileVec[ifile_])
        inputfile[ifile_] = TFile(fileVec[ifile_])
        print "fetching histograms"
        for ihisto_ in range(len(histVec)):
            print("printing histo " + str(histVec[ihisto_]))
            histo = inputfile[ifile_].Get(histVec[ihisto_])
            #status_ = type(histo) is TGraphAsymmErrors
            histList.append(histo)
            # for ratio plot as they should nt be normalize
            histList1.append(histo)
            #print histList[ii].Integral()
            #histList[ii].Rebin(xRange[2])
            #histList[ii].Scale(1.0/histList[ii].Integral())
            maximum.append(histList[ii].GetMaximum())
            minimum.append(histList[ii].GetMinimum())
            maximum.sort()
            ii = ii + 1

    print histList
    print maximum, "  ", max(maximum)
    print minimum, "  ", min(minimum)
    for ih in range(len(histList)):
        tt = type(histList[ih])
        if logstatus[1] is 1:
            histList[ih].SetMaximum(1.5)  #1.4 for log
            histList[ih].SetMinimum(0.1)  #1.4 for log
        if logstatus[1] is 0:
            maxi = max(maximum)
            mini = min(minimum)
            if maxi == 0.0: maxi = 0.001
            if mini == 0.0: mini = -0.001
            histList[ih].SetMaximum(maxi * 3)  #1.4 for log
            histList[ih].SetMinimum(mini * 3)  #1.4 for log
#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0:
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("APL")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("P hist")
        if ih > 0:
            #histList[ih].SetLineWidth(2)
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("PL same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("P hist same")

        if tt is TGraphAsymmErrors:
            histList[ih].SetMaximum(100)
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(2)
            histList[ih].SetMarkerStyle(markerStyle[ih])
            histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih], legendtext[ih], "PL")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
            histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetMarkerStyle(20)
            histList[ih].SetMarkerSize(1.0)
            histList[ih].SetLineWidth(3)
            leg.AddEntry(histList[ih], legendtext[ih], "P")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.052)
        histList[ih].GetYaxis().SetTitleOffset(0.98)
        histList[ih].GetYaxis().SetTitleFont(42)
        histList[ih].GetYaxis().SetLabelFont(42)
        histList[ih].GetYaxis().SetLabelSize(.052)
        histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1])
        #     histList[ih].GetXaxis().SetLabelSize(0.0000);

        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        #histList[ih].GetXaxis().SetTitleOffset(1.14)
        histList[ih].GetXaxis().SetTitleFont(42)

        histList[ih].GetXaxis().SetLabelFont(42)
        histList[ih].GetYaxis().SetLabelFont(42)
        histList[ih].GetXaxis().SetNdivisions(507)
        #histList[ih].GetXaxis().SetMoreLogLabels();
        #histList[ih].GetXaxis().SetNoExponent();
        #histList[ih].GetTGaxis().SetMaxDigits(3);

        i = i + 1
    pt = TPaveText(0.01, 0.92, 0.95, 0.96, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.SetTextSize(0.046)
    #text = pt.AddText(0.12,0.35,"CMS Internal                     36 fb^{-1} (2016) ")
    text = pt.AddText(0.12, 0.35,
                      "CMS Internal                     41.5 fb^{-1} (2017) ")
    #text = pt.AddText(0.12,0.35,"CMS Internal                     59.6 fb^{-1} (2018) ")
    #text = pt.AddText(0.6,0.5,"41.5 fb^{-1} (2017) ")
    pt.Draw()

    leg.Draw()
    outputdirname = 'UncPlots/'
    histname = outputdirname + pngname
    c.SaveAs(histname + '.png')
    c.SaveAs(histname + '.pdf')
Example #9
0
def makePlot1D(filepath, foutname, plottitle='', masstitle=''):
    br = 1 if 'Resonant' in plottitle else 0.68
    limits = parseLimitFiles2D(filepath, br)

    xaxis = []
    xseclist = []
    xsecerr = []
    cent = []
    obs = []
    up1 = []
    up2 = []
    down1 = []
    down2 = []
    maxval = 0
    minval = 999
    for m in sorted(limits):
        l = limits[m]
        xaxis.append(m)
        xseclist.append(l.xsec)
        xsecerr.append(l.xsec * .2)
        cent.append(l.cent)
        up1.append(l.up1 - l.cent)
        up2.append(l.up2 - l.cent)
        down1.append(l.cent - l.down1)
        down2.append(l.cent - l.down2)
        obs.append(l.obs)
        maxval = max(maxval, l.up2)
        minval = min(minval, l.down2)

    N = len(xaxis)

    up1Sigma = array('f', up1)
    up2Sigma = array('f', up2)
    down1Sigma = array('f', down1)
    down2Sigma = array('f', down2)
    cent = array('f', cent)
    obs = array('f', obs)
    xarray = array('f', xaxis)
    xsecarray = array('f', xseclist)
    xsecerrarray = array('f', xsecerr)
    zeros = array('f', [0 for i in xrange(N)])

    graphXsec = TGraphErrors(N, xarray, xsecarray, zeros, xsecerrarray)

    graphCent = TGraph(N, xarray, cent)
    graphObs = TGraph(N, xarray, obs)
    graph1Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down1Sigma,
                                    up1Sigma)
    graph2Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down2Sigma,
                                    up2Sigma)

    c = TCanvas('c', 'c', 700, 600)
    c.SetLogy()
    c.SetLeftMargin(.15)

    graph2Sigma.GetXaxis().SetTitle(masstitle + ' [GeV]')
    graph2Sigma.GetYaxis().SetTitle(
        '95% C.L. upper limit [#sigma/#sigma_{theory}]')
    c2 = root.kOrange
    c1 = root.kGreen + 1
    graph2Sigma.SetLineColor(c2)
    graph1Sigma.SetLineColor(c1)
    graph2Sigma.SetFillColor(c2)
    graph1Sigma.SetFillColor(c1)
    graph2Sigma.SetMinimum(0.5 * minval)
    graph2Sigma.SetMaximum(10 * maxval)
    graphCent.SetLineWidth(2)
    graphCent.SetLineStyle(2)
    graphObs.SetLineColor(1)
    graphObs.SetLineWidth(3)
    graphObs.SetMarkerStyle(20)
    graphObs.SetMarkerSize(1)
    graphObs.SetMarkerColor(1)
    graph1Sigma.SetLineStyle(0)
    graph2Sigma.SetLineStyle(0)

    leg = TLegend(0.55, 0.7, 0.9, 0.9)
    leg.AddEntry(graphCent, 'Expected', 'L')
    if not BLIND:
        leg.AddEntry(graphObs, 'Observed', 'Lp')
    leg.AddEntry(graph1Sigma, '1 std. dev.', 'F')
    leg.AddEntry(graph2Sigma, '2 std. dev.', 'F')
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    graph2Sigma.Draw('A3')
    graph1Sigma.Draw('3 same')
    graphCent.Draw('same L')
    if not BLIND:
        graphObs.Draw('same Lp')

    subscript = 'SR' if 'Resonant' in plottitle else 'FC'
    coupling = '0.1' if 'Resonant' in plottitle else '0.25'

    graphXsec.SetLineColor(2)
    graphXsec.SetLineWidth(2)
    graphXsec.SetLineStyle(2)
    graphXsec.SetFillColor(2)
    graphXsec.SetFillStyle(3005)
    graphXsec.Draw('same L3')
    '''
  if not scale:
    if 'Resonant' in plottitle:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=100 GeV}'%(subscript,subscript,coupling),'l')
    else:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=10 GeV}'%(subscript,subscript,coupling),'l')
  '''
    if not BLIND:
        findIntersect1D(graphObs, graphXsec, xaxis[0], xaxis[-1])
    findIntersect1D(graphCent, graphXsec, xaxis[0], xaxis[-1])

    leg.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.8 * c.GetTopMargin())
    label.SetTextFont(62)
    label.SetTextAlign(11)
    label.DrawLatex(0.15, 0.94, "CMS")
    label.SetTextFont(52)
    label.SetTextSize(0.6 * c.GetTopMargin())
    #  label.DrawLatex(0.25,0.94,"Preliminary")
    label.SetTextFont(42)
    label.SetTextSize(0.7 * c.GetTopMargin())
    label.DrawLatex(0.19, 0.83, plottitle)
    if 'Resonant' in plottitle:
        label.DrawLatex(0.19, 0.75, "a_{SR} = b_{SR} = %s" % coupling)
        label.DrawLatex(0.19, 0.68, "m_{#chi}=100 GeV")
    else:
        label.DrawLatex(0.19, 0.75, "g_{DM}^{V}=1,g_{q}^{V}=0.25")
        label.DrawLatex(0.19, 0.68, "m_{#chi}=1 GeV")
    label.SetTextSize(0.6 * c.GetTopMargin())
    label.SetTextFont(42)
    label.SetTextAlign(31)  # align right
    label.DrawLatex(0.95, 0.94, "%.1f fb^{-1} (13 TeV)" % (plotConfig.lumi))

    c.SaveAs(foutname + '.pdf')
    c.SaveAs(foutname + '.png')
Example #10
0
def plotUpperLimits(model, lambdas, helicity, Mmin):

    N = len(lambdas)
    yellow = TGraph(2 * N)  # yellow band
    green = TGraph(2 * N)  # green band
    median = TGraph(N)  # median line

    up2s = []
    xseclist = [1.0] * N

    for i in range(N):
        file_name = "./%sshapeCards/ee_limit_min%d%s/higgsCombineTest.AsymptoticLimits.mH%d.root" % (
            model, Mmin, helicity, lambdas[i])
        limit = getLimits(file_name)
        up2s.append(limit[4])
        if model == "ADD":
            yellow.SetPoint(i, lambdas[i] / 1000,
                            limit[4] * xseclist[i])  # + 2 sigma
            green.SetPoint(i, lambdas[i] / 1000,
                           limit[3] * xseclist[i])  # + 1 sigma
            median.SetPoint(i, lambdas[i] / 1000,
                            limit[2] * xseclist[i])  # median
            green.SetPoint(2 * N - 1 - i, lambdas[i] / 1000,
                           limit[1] * xseclist[i])  # - 1 sigma
            yellow.SetPoint(2 * N - 1 - i, lambdas[i] / 1000,
                            limit[0] * xseclist[i])  # - 2 sigma
        else:
            yellow.SetPoint(i, lambdas[i], limit[4] * xseclist[i])  # + 2 sigma
            green.SetPoint(i, lambdas[i], limit[3] * xseclist[i])  # + 1 sigma
            median.SetPoint(i, lambdas[i], limit[2] * xseclist[i])  # median
            green.SetPoint(2 * N - 1 - i, lambdas[i],
                           limit[1] * xseclist[i])  # - 1 sigma
            yellow.SetPoint(2 * N - 1 - i, lambdas[i],
                            limit[0] * xseclist[i])  # - 2 sigma
        print "Lambda = %d, Median = %f" % (lambdas[i], limit[2])

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()
    if model == "ADD": frame = c.DrawFrame(4, 0.01, 10, 10)
    else: frame = c.DrawFrame(16, 0.1, 40, 8)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{}")
    if model == "ADD":
        frame.GetYaxis().SetTitle("95% CL limit on #sigma / #sigma_{ADD}")
        frame.GetXaxis().SetTitle("#Lambda_{T} [ADD]")
    else:
        frame.GetYaxis().SetTitle("95% CL limit on #sigma / #sigma_{CI}")
        frame.GetXaxis().SetTitle("#Lambda [CI]")
    frame.SetMinimum(0)
    #frame.SetMaximum(max(up2s)*1.05)
    #frame.GetXaxis().SetLimits(min(values),max(values))

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen + 1)
    green.SetLineColor(ROOT.kGreen + 1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')

    CMS_lumi.CMS_lumi(c, 13, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.76
    y1 = 0.60
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    legend.AddEntry(median,
                    "Asymptotic CL_{s} expected %s%s" % (model, helicity), 'L')
    legend.AddEntry(green, "#pm 1 std. deviation", 'f')
    legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
    legend.Draw()

    c.SaveAs("%slimits/%sLimit_ee_ShapeMin%d%s_201678.png" %
             (model, model, Mmin, helicity))
    c.Close()
    X_axis = "NPU"
print "X_axis= ", X_axis

for obj in (1, 2):
    if (obj == 1):
        Prefix += "_LCT"
    if (obj == 2):
        Prefix = Prefix.replace("LCT", "SEG")

    c1 = TCanvas("c1", "c1", 600, 600)
    c2 = TCanvas("c2", "c2", 600, 600)
    leg = TLegend(0.45, 0.25, 0.95, 0.36)

    leg.SetNColumns(2)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(132)
    leg.SetTextSize(0.04)

    leg_ME1 = TLegend(0.45, 0.25, 0.95, 0.36)

    leg_ME1.SetNColumns(2)
    leg_ME1.SetFillColor(0)
    leg_ME1.SetFillStyle(0)
    leg_ME1.SetShadowColor(0)
    leg_ME1.SetBorderSize(0)
    leg_ME1.SetTextFont(132)
    leg_ME1.SetTextSize(0.04)
    color = 0
Example #12
0
def makeBiasPlot(output,
                 muFile,
                 chan,
                 interference,
                 printStats=False,
                 obs2="",
                 ratioLabel=""):

    mu = open(muFile, 'r')

    limits = {}
    mux = []
    muy = []
    mu1SigLow = []
    mu1SigHigh = []
    mu2SigLow = []
    mu2SigHigh = []
    for entry in mu:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        mux.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        muy.append(limits[massPoint][medianNr])
        mu1SigLow.append(limits[massPoint][lower1Sig])
        mu1SigHigh.append(limits[massPoint][upper1Sig])
        mu2SigLow.append(limits[massPoint][lower2Sig])
        mu2SigHigh.append(limits[massPoint][upper2Sig])

    muX = numpy.array(mux)
    muY = numpy.array(muy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of mux: ", len(mux)
    if printStats: print "length of mu1SigLow: ", len(mu1SigLow)
    if printStats: print "length of mu1SigHigh: ", len(mu1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(mux)):
        values2.append(mu2SigLow[x])
        xPointsForValues2.append(mux[x])
    for x in range(len(mux) - 1, 0 - 1, -1):
        values2.append(mu2SigHigh[x])
        xPointsForValues2.append(mux[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(mux)):
        values.append(mu1SigLow[x])
        xPointsForValues.append(mux[x])
    for x in range(len(mux) - 1, 0 - 1, -1):
        values.append(mu1SigHigh[x])
        xPointsForValues.append(mux[x])
    if printStats: print "length of values: ", len(values)

    mu2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    mu1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "mu2Sig: ", mu2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "mu1Sig: ", mu1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, mu2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kYellow + 1)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, mu1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    plotPad.Draw()
    plotPad.cd()

    muX = numpy.array(mux)
    muY = numpy.array(muy)
    GraphMU = TGraph(len(muX), muX, muY)
    GraphMU.SetLineWidth(3)
    GraphMU.SetLineStyle(2)
    GraphMU.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    DummyGraph = TH1F("DummyGraph", "", 100, 10, 40)
    DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]")
    DummyGraph.GetYaxis().SetTitle("#hat{#mu}")
    gStyle.SetOptStat(0)
    if "Des" in output:
        DummyGraph.GetXaxis().SetRangeUser(10, 28)
    else:
        DummyGraph.GetXaxis().SetRangeUser(10, 40)

    DummyGraph.SetMinimum(-2)
    DummyGraph.SetMaximum(10)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    DummyGraph.SetLineColor(ROOT.kWhite)
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphMU.Draw("lpsame")
    else:
        GraphMU.Draw("lp")
    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    leg.AddEntry(GraphMU, "median value", "l")
    if (FULL):
        leg.AddEntry(GraphErr1Sig, "1#sigma quantile", "f")
        leg.AddEntry(GraphErr2Sig, "2#sigma quantile", "f")

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()
    maxX = 40
    if "Des" in output:
        maxX = 28
    line = ROOT.TLine(10, 0, maxX, 0)
    if "mu1" in output:
        line = ROOT.TLine(10, 1, maxX, 1)
    line.SetLineStyle(ROOT.kDashed)
    line.Draw("same")

    plotPad.RedrawAxis()

    cCL.Update()
    printPlots(cCL, output)
Example #13
0
def addSys(var, cut, sys):
    binLow = ""
    binHigh = ""
    binName = ""
    if "binned" in cut:
        binLow = cut[cut.find("LowVal") + 6:cut.find("HighVal") - 1]
        binHigh = cut[cut.find("HighVal") + 7:]
        binName = "bin_" + binLow + "_" + binHigh
        cut = cut[:cut.find("binned")]

    channel = cut
    weight = "eventWeightLumi"  #+ ("*stitchWeight" if any([x for x in back if x.endswith('b')]) else "")
    cut = selection[cut]
    if not binLow == "":
        cut = cut + " && " + var + " > " + binLow + " && " + var + " < " + binHigh

    weightUp = weightDown = weight
    varUp = varDown = var
    cutUp = cutDown = cut

    # Systematics
    if sys == 'CMS_scale_j':
        if var != "MET_sign": varUp = var.replace('pt', 'ptScaleUp')
        else: varUp = var.replace('sign', 'signScaleUp')
        if var != "MET_sign": varDown = var.replace('pt', 'ptScaleDown')
        else: varDown = var.replace('sign', 'signScaleDown')

        cutUp = cut.replace('MET_pt', 'MET_ptScaleUp')
        cutUp = cutUp.replace('Jets', 'JetsScaleUp')
        cutUp = cutUp.replace('12', '12ScaleUp')
        cutUp = cutUp.replace('mT>', 'mTScaleUp>')
        cutUp = cutUp.replace('mT2', 'mT2ScaleUp')

        cutDown = cut.replace('MET_pt', 'MET_ptScaleDown')
        cutDown = cutDown.replace('Jets', 'JetsScaleDown')
        cutDown = cutDown.replace('12', '12ScaleDown')
        cutDown = cutDown.replace('mT>', 'mTScaleDown>')
        cutDown = cutDown.replace('mT2', 'mT2ScaleDown')
    elif sys == 'CMS_res_j':
        if var != "MET_sign": varUp = var.replace('pt', 'ptResUp')
        else: varUp = var.replace('sign', 'signResUp')
        if var != "MET_sign": varDown = var.replace('pt', 'ptResDown')
        else: varDown = var.replace('sign', 'signResDown')

        cutUp = cut.replace('MET_pt', 'MET_ptResUp')
        cutUp = cutUp.replace('Jets', 'JetsResUp')
        cutUp = cutUp.replace('12', '12ResUp')
        cutUp = cutUp.replace('mT>', 'mTResUp>')
        cutUp = cutUp.replace('mT2', 'mT2ResUp')
        cutDown = cut.replace('MET_pt', 'MET_ptResDown')
        cutDown = cutDown.replace('Jets', 'JetsResDown')
        cutDown = cutDown.replace('12', '12ResDown')
        cutDown = cutDown.replace('mT>', 'mTResDown>')
        cutDown = cutDown.replace('mT2', 'mT2ResDown')

    elif sys == 'CMS_WqcdWeightRen':
        weightUp += "*WqcdWeightRenUp/WqcdWeight"
        weightDown += "*WqcdWeightRenDown/WqcdWeight"
    elif sys == 'CMS_WqcdWeightFac':
        weightUp += "*WqcdWeightFacUp/WqcdWeight"
        weightDown += "*WqcdWeightFacDown/WqcdWeight"
    elif sys == 'CMS_ZqcdWeightRen':
        weightUp += "*ZqcdWeightRenUp/ZqcdWeight"
        weightDown += "*ZqcdWeightRenDown/ZqcdWeight"
    elif sys == 'CMS_ZqcdWeightFac':
        weightUp += "*ZqcdWeightFacUp/ZqcdWeight"
        weightDown += "*ZqcdWeightFacDown/ZqcdWeight"
    elif sys == 'CMS_WewkWeight':
        weightUp += "/WewkWeight"
        weightDown += ""
    elif sys == 'CMS_ZewkWeight':
        weightUp += "/ZewkWeight"
        weightDown += ""

    elif sys == 'CMS_pdf':
        weightUp += "*PDFWeightUp/eventWeight"
        weightDown += "*PDFWeightDown/eventWeight"
    elif sys == 'CMS_HF':
        weightUp += "*1.20"
        weightDown += "*0.8"

    elif sys == 'CMS_eff_b':
        weightUp += "*bTagWeightUp/bTagWeight"
        weightDown += "*bTagWeightDown/bTagWeight"
    elif sys == 'CMS_scale_pu':
        weightUp += "*puWeightUp/puWeight"
        weightDown += "*puWeightDown/puWeight"
    elif sys == 'CMS_scale_top':
        weightUp += "/TopWeight"
        weightDown += ""
    elif sys == 'CMS_eff_trigger':
        weightUp += "*triggerWeightUp/triggerWeight"
        weightDown += "*triggerWeightDown/triggerWeight"
    elif sys == 'CMS_eff_e' and '2e' in cut or '1e' in channel:
        weightUp += "*leptonWeightUp/leptonWeight"
        weightDown += "*leptonWeightDown/leptonW\
eight"

    elif sys == 'CMS_eff_m' and '2m' in cut or '1m' in channel:
        weightUp += "*leptonWeightUp/leptonWeight"
        weightDown += "*leptonWeightDown/leptonW\
eight"

    elif sys == 'QCDscale_ren':
        weightUp += "*QCDRenWeightUp"
        weightDown += "*QCDRenWeightDown"
    elif sys == 'QCDscale_fac':
        weightUp += "*QCDFacWeightUp"
        weightDown += "*QCDFacWeightDown"
        # elif sys=='EWKscale_Z': weightDown += "/ZewkWeight"
        # elif sys=='EWKscale_W': weightDown += "/WewkWeight"
    else:
        print "Systematic", sys, "not applicable or not recognized."
    ### Create and fill MC histograms ###
    file = {}
    tree = {}
    hist = {}
    histUp = {}
    histDown = {}
    isBlind = BLIND and 'SR' in channel
    for i, s in enumerate(back + sign):
        tree[s] = TChain("tree")
        for j, ss in enumerate(sample[s]['files']):
            tree[s].Add(NTUPLEDIR + ss + ".root")
        if not binLow == "":
            hist[s] = TH1F(
                s, ";" + variable[var]['title'] + ";Events;" +
                ('log' if variable[var]['log'] else ''), 1, float(binLow),
                float(binHigh))
        elif binLow == "" and variable[var]['nbins'] > 0:
            hist[s] = TH1F(
                s, ";" + variable[var]['title'] + ";Events;" +
                ('log' if variable[var]['log'] else ''),
                variable[var]['nbins'], variable[var]['min'],
                variable[var]['max'])
        else:
            hist[s] = TH1F(s, ";" + variable[var]['title'],
                           len(variable[var]['bins']) - 1,
                           array('f', variable[var]['bins']))
        hist[s].Sumw2()
        histUp[s] = hist[s].Clone(s + 'Up')
        histDown[s] = hist[s].Clone(s + 'Down')
        redFactorString = ""
        redFactorValue = ""
        #if isBlind and 'data' not in s and options.limit:
        if isBlind and 'data' not in s:
            redFactorValue = " / 15"
        cutstring = ("*(" + cut + ")" if len(cut) > 0 else "")
        cutstringUp = ("*(" + cutUp + ")" if len(cut) > 0 else "")
        cutstringDown = ("*(" + cutDown + ")" if len(cut) > 0 else "")
        if '-' in s:
            cutstring = cutstring.replace(
                cut, cut + "&& nBQuarks==" + s.split('-')[1][0])
        tree[s].Project(s, var,
                        "(" + weight + redFactorValue + ")" + cutstring)

        if 'HF' not in sys or 'QCDscale' not in sys:
            tree[s].Project(s + 'Up', varUp,
                            "(" + weightUp + redFactorValue + ")" + cutstring)
            tree[s].Project(
                s + 'Down', varDown,
                "(" + weightDown + redFactorValue + ")" + cutstring)

        if 'HF' in sys:
            if s.startswith('WJ') or s.startswith('ZJ') or s.startswith(
                    'DYJets'):
                tree[s].Project(
                    s + 'Up', varUp,
                    "(" + weightUp + redFactorValue + ")" + cutstringUp)
                tree[s].Project(
                    s + 'Down', varDown,
                    "(" + weightDown + redFactorValue + ")" + cutstringDown)
            else:
                tree[s].Project(
                    s + 'Up', varUp,
                    "(" + weight + redFactorValue + ")" + cutstringUp)
                tree[s].Project(
                    s + 'Down', varDown,
                    "(" + weight + redFactorValue + ")" + cutstringDown)

        if 'QCDscale' in sys:
            if s.startswith('WJ') or s.startswith('ZJ') or s.startswith(
                    'DYJets'):
                tree[s].Project(
                    s + 'Up', varUp,
                    "(" + weight + redFactorValue + ")" + cutstringUp)
                tree[s].Project(
                    s + 'Down', varDown,
                    "(" + weight + redFactorValue + ")" + cutstringDown)
            else:
                tree[s].Project(
                    s + 'Up', varUp,
                    "(" + weightUp + redFactorValue + ")" + cutstringUp)
                tree[s].Project(
                    s + 'Down', varDown,
                    "(" + weightDown + redFactorValue + ")" + cutstringDown)

        hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0)
        hist[s].SetLineWidth(2)
        histUp[s].SetLineWidth(2)
        histDown[s].SetLineWidth(2)
        hist[s].SetLineColor(1)
        histUp[s].SetLineColor(629)
        histDown[s].SetLineColor(602)

    # Rescale normalization for QCD scales FIXME
    if 'QCDscale' in sys:
        for s in back + sign:  #['TTbar', 'TTbarSL', 'ST']:
            if s in hist and histUp[s].Integral(
            ) > 0. and histDown[s].Integral() > 0.:
                histUp[s].Scale(hist[s].Integral() / histUp[s].Integral())
                histDown[s].Scale(hist[s].Integral() / histDown[s].Integral())

    hist['BkgSum'] = hist[back[0]].Clone("BkgSum")
    hist['BkgSum'].Reset()
    histUp['BkgSum'] = hist['BkgSum'].Clone("BkgSumUp")
    histUp['BkgSum'].SetLineColor(629)
    histUp['BkgSum'].Reset()
    histDown['BkgSum'] = hist['BkgSum'].Clone("BkgSumDown")
    histDown['BkgSum'].SetLineColor(602)
    histDown['BkgSum'].Reset()

    for i, s in enumerate(back):
        hist['BkgSum'].Add(hist[s], 1)
        histUp['BkgSum'].Add(histUp[s], 1)
        histDown['BkgSum'].Add(histDown[s], 1)

    for i, s in enumerate(back + sign + ['BkgSum']):
        addOverflow(hist[s], False)
        addOverflow(histUp[s], False)
        addOverflow(histDown[s], False)

    c1 = TCanvas("c1", "Signals", 800, 600)
    c1.cd()
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)

    if RATIO:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), RATIO)
        setBotPad(c1.GetPad(2), RATIO)

    c1.cd(1)
    c1.GetPad(bool(RATIO)).SetTopMargin(0.06)
    c1.GetPad(bool(RATIO)).SetRightMargin(0.06)
    c1.GetPad(bool(RATIO)).SetTicks(1, 1)
    c1.GetPad(bool(RATIO)).SetLogy()

    histUp['BkgSum'].SetMaximum(histUp['BkgSum'].GetMaximum() * 5)
    histUp['BkgSum'].Draw("HIST")
    histDown['BkgSum'].Draw("SAME, HIST")
    hist['BkgSum'].Draw("SAME, HIST")
    drawCMS(-1, "Simulation", False)

    setHistStyle(histUp['BkgSum'], 1.2 if RATIO else 1.1)

    if RATIO:
        c1.cd(2)
        errUp = histUp['BkgSum'].Clone("BkgUp;")
        errUp.Add(hist['BkgSum'], -1)
        errUp.Divide(hist['BkgSum'])
        errUp.SetTitle("")
        errUp.GetYaxis().SetTitle("#frac{shifted-central}{central}")
        errUp.GetYaxis().SetNdivisions(503)
        setBotStyle(errUp)
        errUp.GetYaxis().SetRangeUser(-0.3, 0.3)
        errUp.Draw("HIST")

        errDown = histDown['BkgSum'].Clone("BkgDown;")
        errDown.Add(hist['BkgSum'], -1)
        errDown.Divide(hist['BkgSum'])
        errDown.Draw("SAME, HIST")

        f1 = TF1("myfunc", "[0]", -100000, 10000)
        f1.SetLineColor(1)
        f1.SetLineStyle(7)
        f1.SetLineWidth(1)
        f1.SetParameter(0, 0)
        f1.Draw("same")

    leg = TLegend(0.65, 0.80, 0.95, 0.80)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetHeader(sys.replace('CMS', '').replace('_', ' '))
    leg.AddEntry(histUp['BkgSum'], "Up", "l")
    leg.AddEntry(hist['BkgSum'], "Central", "l")
    leg.AddEntry(histDown['BkgSum'], "Down", "l")
    leg.SetY1(0.75 - leg.GetNRows() * 0.045)
    c1.cd(1)
    leg.Draw()

    if options.saveplots:
        if not os.path.exists("plotsSys_" + options.name + "/" + channel +
                              binName):
            os.makedirs("plotsSys_" + options.name + "/" + channel + binName)
        c1.Print("plotsSys_" + options.name + "/" + channel + binName + "/" +
                 sys + ".png")
        c1.Print("plotsSys_" + options.name + "/" + channel + binName + "/" +
                 sys + ".pdf")

    for i, s in enumerate(back + sign):
        c2 = TCanvas(s + "canvas", "Signals", 800, 600)
        c2.cd()
        gStyle.SetOptStat(0)
        gStyle.SetOptTitle(0)
        c2.GetPad(0).SetTopMargin(0.06)
        c2.GetPad(0).SetRightMargin(0.06)
        c2.GetPad(0).SetTicky(2)
        c2.GetPad(0).SetLogy()
        histUp[s].SetMaximum(histUp[s].GetMaximum() * 5)
        histUp[s].Draw("HIST")
        histDown[s].Draw("SAME, HIST")
        hist[s].Draw("SAME, HIST")
        drawCMS(-1, "Simulation", False)
        if options.saveplots:
            c2.Print("plotsSys_" + options.name + "/" + channel + binName +
                     "/" + sys + "_" + s + ".png")
            c2.Print("plotsSys_" + options.name + "/" + channel + binName +
                     "/" + sys + "_" + s + ".pdf")

    saveHist(histUp, channel + binName, sys + 'Up')
    saveHist(histDown, channel + binName, sys + 'Down')

    print "Added systematic", sys, "to channel", channel
Example #14
0
def plot(var, cut, norm=False, nm1=False):
    ### Preliminary Operations ###
    doBinned = False
    if options.mode == "binned": doBinned = True

    fileRead = os.path.exists("combinedCards_" + options.name +
                              "/fitDiagnostics_" + options.file + ".root")
    treeRead = not any(
        x == cut
        for x in ['0l', '1e', '1m', '2e', '2m', '1e1m', 'Gen', 'Trigger'
                  ])  #(var in variable.keys()) # Read from tree

    #signal definition
    if fileRead:
        sign = ['ttDM_MChi1_MPhi200_scalar',
                'tDM_MChi1_MPhi200_scalar']  #for postfit plot
    if not fileRead and not options.limit:
        sign = ['ttDM_MChi1_MPhi100_scalar',
                'tDM_MChi1_MPhi100_scalar']  #for normal plotting
    #bkg definition
    if fileRead or options.limit:
        back = [
            "QCD", "DYJetsToNuNu_HT", "DYJetsToLL_HT", "VV", "ST",
            "WJetsToLNu_HT", "TTbarSL"
        ]  #for postfit or limit
    if (cut).find('>250') or (cut).startswith('AH'):  #for hadronic selections
        back = [
            "QCD", "DYJetsToLL_HT", "VV", "ST", "WJetsToLNu_HT", "TTbarV",
            "TTbar2L", "TTbar1L", "DYJetsToNuNu_HT"
        ]
        if fileRead or options.limit:
            back = [
                "QCD", "DYJetsToLL_HT", "VV", "ST", "WJetsToLNu_HT", "TTbarSL",
                "DYJetsToNuNu_HT"
            ]  #for postfit or limit

    binLow = ""
    binHigh = ""
    binName = ""
    if "binned" in cut:
        binLow = cut[cut.find("LowVal") + 6:cut.find("HighVal") - 1]
        binHigh = cut[cut.find("HighVal") + 7:]
        binName = "bin_" + binLow + "_" + binHigh
        cut = cut[:cut.find("binned")]
    useformula = False
    if 'formula' in variable[var]:
        useformula = True
    channel = cut
    plotdir = cut
    plotname = var
    weight = "eventWeightLumi"  #*(2.2/35.9)
    isBlind = BLIND and ('SR' in channel or 'ps' in channel)
    if fileRead:
        isBlind = False
        options.saveplots = True
        RESIDUAL = True
    elif isBlind:
        RATIO = 0
        SIGNAL = 20
    else:
        RATIO = 4
        SIGNAL = 1
        RESIDUAL = False
    showSignal = True  #('SR' in channel)
    cutSplit = cut.split()
    for s in cutSplit:
        if s in selection.keys():
            plotdir = s
            cut = cut.replace(s, selection[s])
            if not binLow == "":
                cut = cut + " && " + var + " > " + binLow + " && " + var + " < " + binHigh
#if treeRead and cut in selection: cut  = cut.replace(cut, selection[cut])

# Determine Primary Dataset
    pd = []
    if any(w in cut
           for w in ['1l', '1m', '2m', 'isWtoMN', 'isZtoMM', 'isTtoEM']):
        pd += [x for x in sample['data_obs']['files'] if 'SingleMuon' in x]
    if any(w in cut for w in ['1l', '1e', '2e', 'isWtoEN', 'isZtoEE']):
        pd += [x for x in sample['data_obs']['files'] if 'SingleElectron' in x]
    if any(w in cut for w in ['0l', 'isZtoNN']):
        pd += [x for x in sample['data_obs']['files'] if 'MET' in x]
    if len(pd) == 0:
        raw_input("Warning: Primary Dataset not recognized, continue?")

    print "Plotting from", ("tree" if treeRead else
                            "file"), var, "in", channel, "channel with:"
    print "  dataset:", pd
    print "  cut    :", cut
    print "  cut    :", weight

    ### Create and fill MC histograms ###
    # Create dict
    file = {}
    tree = {}
    hist = {}

    ### Create and fill MC histograms ###
    for i, s in enumerate(data + back + sign):
        if fileRead:
            var = 'MET_pt'
            if channel.startswith('SL'): var = 'MET_sign'
            if channel.endswith('ZR'): var = 'FakeMET_pt'
            plotname = var

            hist[s] = TH1F(
                s, ";" + variable[var]['title'] + ";Events;" +
                ('log' if variable[var]['log'] else ''),
                variable[var]['nbins'], variable[var]['min'],
                variable[var]['max'])

            if doBinned:
                bins = np.array([])
                if 'bins' in variable[var].keys():
                    bins = np.array(variable[var]['bins'])
                else:
                    binsize = (variable[var]['max'] -
                               variable[var]['min']) / variable[var]['nbins']
                    bins = np.arange(variable[var]['min'],
                                     variable[var]['max'] + binsize, binsize)
                bins = np.append(bins, 10000)

                for i in range(0, len(bins) - 1):
                    rbin = str(bins[i]) + "_" + str(bins[i + 1])
                    fileName = "combinedCards_" + options.name + "/fitDiagnostics_" + options.file + ".root" if not any(
                        t in s for t in ['data', 'tDM']
                    ) else "rootfiles_" + options.name + "/" + channel + "bin_" + rbin + ".root"
                    histName = "shapes_fit_b/" + channel + "bin_" + rbin + "/" + s if not any(
                        t in s for t in ['data', 'tDM']) else s
                    file[s] = TFile(fileName, "READ")
                    tmphist = file[s].Get(histName)

                    if 'data' not in s: hist[s].SetMarkerSize(0)
                    if tmphist:
                        hist[s].SetBinContent(i + 1, tmphist.GetBinContent(1))
                        hist[s].SetBinError(i + 1, tmphist.GetBinError(1))
                    else:
                        hist[s].SetBinContent(i + 1, 0.)
                        hist[s].SetBinError(i + 1, 0.)
            else:
                fileName = "combinedCards_" + options.name + "/fitDiagnostics_" + options.file + ".root" if not s == 'data_obs' else "rootfiles_" + options.name + "/" + channel + binName + ".root"
                histName = "shapes_fit_b/" + channel + "/" + s if not s == 'data_obs' else s
                file[s] = TFile(fileName, "READ")
                tmphist = file[s].Get(histName)

                if tmphist == None:
                    tmphist = hist[back[0]].Clone(s)
                    tmphist.Reset("MICES")
                    print "Histogram", histName, "not found in file", fileName

                if s == 'data_obs': hist[s] = tmphist
                else:
                    hist[s] = hist['data_obs'].Clone(s)
                    hist[s].SetMarkerSize(0)
                    for i in range(tmphist.GetNbinsX() + 1):
                        hist[s].SetBinContent(i + 1,
                                              tmphist.GetBinContent(i + 1))

        elif treeRead:  # Project from tree
            tree[s] = TChain("tree")
            for j, ss in enumerate(sample[s]['files']):
                if not 'data' in s or ('data' in s and ss in pd):
                    tree[s].Add(NTUPLEDIR + ss + ".root")
            if not binLow == "":
                hist[s] = TH1F(
                    s, ";" + variable[var]['title'] + ";Events;" +
                    ('log' if variable[var]['log'] else ''), 1, float(binLow),
                    float(binHigh))
            elif binLow == "" and variable[var]['nbins'] > 0:
                hist[s] = TH1F(
                    s, ";" + variable[var]['title'] + ";Events;" +
                    ('log' if variable[var]['log'] else ''),
                    variable[var]['nbins'], variable[var]['min'],
                    variable[var]['max'])
            else:
                hist[s] = TH1F(
                    s, ";" + variable[var]['title'] + ";Events;" +
                    ('log' if variable[var]['log'] else ''),
                    len(variable[var]['bins']) - 1,
                    array('f', variable[var]['bins']))
            hist[s].Sumw2()
            redFactorString = ""
            redFactorValue = ""
            #if isBlind and 'data' in s:
            if isBlind and 'data' in s and options.limit:
                redFactorString = " && Entry$ % 15 == 1"
            #if isBlind and 'data' not in s:
            if isBlind and 'data' not in s and options.limit:
                redFactorValue = " / 15"
            cutstring = "(" + weight + redFactorValue + ")" + (
                "*(" + cut + redFactorString + ")" if len(cut) > 0 else "")
            if '-' in s:
                cutstring = cutstring.replace(
                    cut, cut + "&& nBQuarks==" + s.split('-')[1][0])
            if useformula == True:
                tree[s].Project(s, variable[var]['formula'], cutstring)
            else:
                tree[s].Project(s, var, cutstring)
            if not tree[s].GetTree() == None:
                hist[s].SetOption("%s" % tree[s].GetTree().GetEntriesFast())
        else:  # Histogram written to file
            for j, ss in enumerate(sample[s]['files']):
                if not 'data' in s or ('data' in s and ss in pd):
                    file[ss] = TFile(NTUPLEDIR + ss + ".root", "R")
                    if file[ss].IsZombie():
                        print "WARNING: file", NTUPLEDIR + ss + ".root", "does not exist"
                        continue
                    tmphist = file[ss].Get(cut + "/" + var)
                    if tmphist == None: continue
                    if not s in hist.keys(): hist[s] = tmphist
                    else: hist[s].Add(tmphist)
        if hist[s].Integral() < 0: hist[s].Scale(0)
        hist[s].SetFillColor(sample[s]['fillcolor'])
        hist[s].SetFillStyle(sample[s]['fillstyle'])
        hist[s].SetLineColor(sample[s]['linecolor'])
        hist[s].SetLineStyle(sample[s]['linestyle'])
        #if 'WJetsToLNu' in s and 'SL' in channel and 'WR' in channel: hist[s].Scale(1.30)
        #if 'TTbar' in s and 'SL' in channel and 'TR' in channel: hist[s].Scale(0.91)

    hist['BkgSum'] = hist[back[0]].Clone("BkgSum")
    hist['BkgSum'].Reset("MICES")
    for i, s in enumerate(back):
        hist['BkgSum'].Add(hist[s], 1)

    if fileRead:
        hist['PreFit'] = hist['BkgSum'].Clone("PreFit")
        if doBinned:
            for i in range(0, len(bins) - 1):
                rbin = str(bins[i]) + "_" + str(bins[i + 1])
                tmphist = file[back[0]].Get("shapes_prefit/" + channel +
                                            "bin_" + rbin + "/" +
                                            "total_background")

                if tmphist:
                    hist['PreFit'].SetBinContent(i + 1,
                                                 tmphist.GetBinContent(1))
                else:
                    hist['PreFit'].SetBinContent(i + 1, 0.)
        else:
            tmphist = file[back[0]].Get("shapes_prefit/" + channel + "/" +
                                        "total_background")
            for i in range(tmphist.GetNbinsX() + 1):
                hist['PreFit'].SetBinContent(i + 1,
                                             tmphist.GetBinContent(i + 1))
        addOverflow(hist['PreFit'], False)
        hist['PreFit'].SetLineStyle(2)
        hist['PreFit'].SetLineColor(617)  #923
        hist['PreFit'].SetLineWidth(3)
        hist['PreFit'].SetFillStyle(0)
    hist['BkgSum'].SetFillStyle(3002)
    hist['BkgSum'].SetFillColor(1)

    # Create data and Bkg sum histograms
    #    if options.blind or 'SR' in channel:
    #        hist['data_obs'] = hist['BkgSum'].Clone("data_obs")
    #        hist['data_obs'].Reset("MICES")
    # Set histogram style
    hist[data[0]].SetMarkerStyle(20)
    hist[data[0]].SetMarkerSize(1.25)

    for i, s in enumerate(data + back + sign + ['BkgSum']):
        addOverflow(hist[s], False)  # Add overflow
    for i, s in enumerate(sign):
        hist[s].SetLineWidth(3)
    #for i, s in enumerate(sign): sample[s]['plot'] = True#sample[s]['plot'] and s.startswith(channel[:2])

    if norm:
        for i, s in enumerate(sign):
            hist[s].Scale(hist['BkgSum'].Integral() / hist[s].Integral())
#        for i, s in enumerate(back):
#            hist[s].SetFillStyle(3005)
#            hist[s].SetLineWidth(2)
#        #for i, s in enumerate(sign):
#        #    hist[s].SetFillStyle(0)
#        if not var=="Events":
#            sfnorm = hist[data[0]].Integral()/hist['BkgSum'].Integral()
#            print "Applying SF:", sfnorm
#            for i, s in enumerate(back+['BkgSum']): hist[s].Scale(sfnorm)

    if SIGNAL > 1:
        if not var == "Events":
            for i, s in enumerate(sign):
                hist[s].Scale(SIGNAL)

    # Create stack
    bkg = THStack("Bkg",
                  ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    #leg = TLegend(0.65, 0.6, 0.95, 0.9)
    leg = TLegend(0.45, 0.63, 0.93, 0.92)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetNColumns(3)
    leg.SetTextFont(42)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe")
    for i, s in reversed(list(enumerate(back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    if 'PreFit' not in hist:
        leg.AddEntry(hist['BkgSum'], sample['BkgSum']['label'], "f")
    else:
        leg.AddEntry(hist['BkgSum'], 'MC unc.', "l")
        leg.AddEntry(hist['PreFit'], sample['PreFit']['label'], "l")
    if showSignal:
        for i, s in enumerate(sign):
            if SIGNAL > 1:
                if sample[s]['plot']:
                    leg.AddEntry(hist[s],
                                 '%s (x%d)' % (sample[s]['label'], SIGNAL),
                                 "l")
            else:
                if sample[s]['plot']:
                    leg.AddEntry(hist[s], sample[s]['label'], "l")

    leg.SetY1(0.9 - leg.GetNRows() * 0.05)

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if RATIO else 600)

    if RATIO:
        if RESIDUAL:
            c1.Divide(1, 3)
            setFitTopPad(c1.GetPad(1), RATIO)
            setFitBotPad(c1.GetPad(2), RATIO)
            setFitResPad(c1.GetPad(3), RATIO)
        else:
            c1.Divide(1, 2)
            setTopPad(c1.GetPad(1), RATIO)
            setBotPad(c1.GetPad(2), RATIO)
    c1.cd(1)
    c1.GetPad(bool(RATIO)).SetTopMargin(0.06)
    c1.GetPad(bool(RATIO)).SetRightMargin(0.05)
    c1.GetPad(bool(RATIO)).SetTicks(1, 1)

    log = ("log" in hist['BkgSum'].GetZaxis().GetTitle())
    if log: c1.GetPad(bool(RATIO)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    if not isBlind and len(data) > 0:
        graph = fixData(hist[data[0]], USEGARWOOD)
        graph.Draw("SAME, PE")
    #data_graph.Draw("SAME, PE")
    if 'PreFit' in hist: hist['PreFit'].Draw("SAME, HIST")
    if showSignal:
        for i, s in enumerate(sign):
            if sample[s]['plot']:
                hist[s].Draw(
                    "SAME, HIST"
                )  # signals Normalized, hist[s].Integral()*sample[s]['weight']
    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075)
    bkg.SetMaximum((5. if log else 1.25) * max(
        bkg.GetMaximum(),
        hist[data[0]].GetBinContent(hist[data[0]].GetMaximumBin()) +
        hist[data[0]].GetBinError(hist[data[0]].GetMaximumBin())))
    if len(sign) > 0 and bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(),
                                                hist[sign[-1]].GetMaximum()):
        bkg.SetMaximum(
            max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()) *
            1.25)
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist[data[0]].GetMinimum()), 5.e-1) if log else 0.)
    if log:
        #bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e3)
        bkg.GetYaxis().SetMoreLogLabels(True)
    else:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e3)

    leg.Draw()
    if fileRead and 'SR' in channel:
        drawCMS(LUMI / 15., "Preliminary")
    else:
        drawCMS(LUMI, "Preliminary")
    drawRegion(channel, True)
    drawAnalysis("DM" + channel[:2])
    drawOverflow()

    setHistStyle(bkg, 1.2 if RATIO else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1)

    if RATIO:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        if RESIDUAL: setFitBotStyle(err)
        else: setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        res = hist[data[0]].Clone("Residues")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                res.SetBinContent(
                    i,
                    res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                res.SetBinError(
                    i,
                    res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
        if RESIDUAL: setFitBotStyle(res)
        else: setBotStyle(res)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        if 'PreFit' in hist:
            respre = hist[data[0]].Clone("ResiduesPreFit")
            respre.Divide(hist['PreFit'])
            respre.SetLineStyle(2)
            respre.SetLineColor(617)  #923
            respre.SetLineWidth(3)
            respre.SetFillStyle(0)
            respre.Draw("SAME, HIST")
        errLine.Draw("SAME, HIST")
        if not isBlind and len(data) > 0:
            res.Draw("SAME, PE0")
            #res_graph.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(hist['data_obs'], hist['BkgSum'])
                drawStat(hist['data_obs'], hist['BkgSum'])

    c1.Update()

    if RATIO and RESIDUAL:
        c1.cd(3)
        c1.SetGrid(1, 0)
        resFit = hist[data[0]].Clone("Residues")
        resFit.Reset("MICES")
        resFit.SetTitle("")
        #resFit.GetYaxis().SetTitle("Residuals")
        resFit.GetYaxis().SetTitle(
            "#frac{Data - Bkg}{#sqrt{#sigma_{Data}^{2}+#sigma_{Bkg}^{2}}}")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                resFit.SetBinContent(
                    i, (hist[data[0]].GetBinContent(i) -
                        hist['BkgSum'].GetBinContent(i)) / (math.sqrt(
                            math.pow(hist['BkgSum'].GetBinError(i), 2) +
                            math.pow(hist[data[0]].GetBinError(i), 2))))
        setFitResStyle(resFit)
        resFit.SetLineColor(15)
        resFit.SetFillColor(15)
        resFit.SetFillStyle(1001)
        resFit.Draw("HIST")

        resFitLine = resFit.Clone("resFitLine")
        resFitLine.SetLineWidth(1)
        resFitLine.SetFillStyle(0)
        resFitLine.Draw("SAME, HIST")

    c1.Update()

    if gROOT.IsBatch(
    ) and options.saveplots:  # and (treeRead and channel in selection.keys()):
        AddString = ""
        if not os.path.exists("plots_" + options.name + "/" + plotdir):
            os.makedirs("plots_" + options.name + "/" + plotdir)
        if fileRead:
            if RESIDUAL: AddString = "_PostFit_Residual"
            else: AddString = "_PostFit"
        #c1.Print("plots_"+options.name+"/"+plotdir+"/"+plotname+binName+AddString+".png")
        c1.Print("plots_" + options.name + "/" + plotdir + "/" + plotname +
                 binName + AddString + ".pdf")

    # Print table
    printTable(hist, sign)

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    if gROOT.IsBatch() and not fileRead and (
            var == 'MET_pt' or
        (channel.startswith('SL') and var == 'MET_sign') or
        (channel.endswith('ZR') and var == 'FakeMET_pt')):
        saveHist(hist, channel + binName)
Example #15
0
def plotPostFitValues(channel,var,DM,year,*parameters,**kwargs):
    """Draw post-fit values for parameter using MultiDimFit and FitDiagnostics output."""
    if DM=='DM0' and 'm_2' in var: return
    print green("\n>>> plotPostFitValues %s, %s"%(DM, var))
    if len(parameters)==1 and isinstance(parameters[0],list): parameters = parameters[0]
    
    parameters  = [p.replace('$CAT',DM).replace('$CHANNEL',channel) for p in list(parameters)]
    title       = kwargs.get('title',     ""    )
    name        = kwargs.get('name',      ""    )
    indir       = kwargs.get('indir',     "output_%d"%year  )
    outdir      = kwargs.get('outdir',    "postfit_%d"%year )
    tag         = kwargs.get('tag',       ""    )
    plotlabel   = kwargs.get('plotlabel', ""    )
    compareFD   = kwargs.get('compareFD', False ) and N==1
    era         = "%d-13TeV"%year
    isBBB       = any("_bin_" in p for p in parameters)
    filename    = '%s/higgsCombine.%s_%s-%s%s-%s.MultiDimFit.mH90.root'%(indir,channel,var,DM,tag,era)
    filenamesFD = '%s/fitDiagnostics.%s_%s-%s%s-%s_TES*p*.root'%(indir,channel,var,DM,tag,era)
    ensureDirectory(outdir)
    if not name:
      name = formatParameter(parameters[0]).replace('_'+DM,'')
    if len(parameters)>1:
      name = "comparison_%s"%(name) #re.sub(r"bin_\d+","bin",name)
    canvasname = "%s/postfit-%s_%s_%s%s%s"%(outdir,name,var,DM,tag,plotlabel)
    print '>>>   file "%s"'%(filename)
    
    
    graphs      = [ ]
    graphsFD    = [ ]
    tvals       = [ ]
    pvals       = [ -2.2, +2.2 ]
    tes         = measureTES(filename)
    for parameter in parameters[:]:
      graph = getTGraphOfParameter(filename,'tes',parameter,xvals=tvals,yvals=pvals)
      if graph:
        graphs.append(graph)
      else:
        parameters.remove(parameter)
      if compareFD:
        graphFD = getTGraphOfParameter_FD(filenamesFD,parameter,xvals=tvals,yvals=pvals)
        if graphFD: graphsFD.append(graphFD)
    if len(parameters)!=len(graphs):
      warning("plotPostFitValues: len(parameters) = %d != %d = len(graphs)"%(len(parameters),len(graphs)))
      exit(1)
    N           = len(parameters)
    compareFD   = compareFD and len(graphsFD)>0
    parameters  = [formatParameter(p).replace('_'+DM,'') for p in parameters]
    graphsleg   = columnize(graphs,3)     if N>6 else columnize(graphs,2)     if N>3 else graphs # reordered for two columns
    paramsleg   = columnize(parameters,3) if N>6 else columnize(parameters,2) if N>3 else parameters # reordered for two columns
    
    xtitle  = 'tau energy scale'
    ytitle  = "%s post-fit value"%(parameters[0] if N==1 else "MultiDimFit")
    xmin, xmax = min(tvals), max(tvals)
    ymin, ymax = min(pvals), max(pvals)
    colors  = [ kBlack, kBlue, kRed, kGreen, kMagenta, kOrange, kTeal, kAzure+2, kYellow-3 ]
    
    canvas = TCanvas("canvas","canvas",100,100,800,650)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(  0.07 ); canvas.SetBottomMargin( 0.13 )
    canvas.SetLeftMargin( 0.11 ); canvas.SetRightMargin(  0.05 )
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    canvas.cd()
    
    maxmargin = 0.18*abs(ymax-ymin)
    minmargin = 0.20*abs(ymax-ymin) #(0.20 if N<5 else 0.10*ceil(N/2))
    ymin   = 0.0 if ymin>=0 else ymin-minmargin
    ymax   = ymax + minmargin
    
    textsize   = 0.045 if N==1 else 0.036
    lineheight = 0.055 if N==1 else 0.045
    x1, width  = 0.42, 0.25
    y1, height = 0.15, lineheight*(ceil(N/3.) if N>6 else ceil(N/2.) if N>3 else N)
    if title:     height += lineheight
    if compareFD: height += lineheight
    if   N>6:
      if isBBB: width = 0.62; x1 = 0.25
      else:     width = 0.70; x1 = 0.20
    elif N>3:   width = 0.52; x1 = 0.36
    legend = TLegend(x1,y1,x1+width,y1+height)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    if title:
      legend.SetTextFont(62)
      legend.SetHeader(title) 
    legend.SetTextFont(42)
    if N>6:
      legend.SetNColumns(3)
      legend.SetColumnSeparation(0.02)
    elif N>3:
      legend.SetNColumns(2)
      legend.SetColumnSeparation(0.03)
    
    frame = canvas.DrawFrame(xmin,ymin,xmax,ymax)
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetLabelSize(0.050)
    frame.GetYaxis().SetLabelSize(0.050)
    frame.GetXaxis().SetLabelOffset(0.01)
    frame.GetYaxis().SetLabelOffset(0.01)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(0.84)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    
    for i, (parameter,graph) in enumerate(zip(parameters,graphs)):
      graph.SetLineColor(colors[i%len(colors)])
      graph.SetLineWidth(2)
      graph.SetLineStyle(1)
      graph.Draw('LSAME')
    
    for parameter,graph in zip(paramsleg,graphsleg):
      if N==1:
        legend.AddEntry(graph, "MultiDimFit", 'l')
      else:
        legend.AddEntry(graph, parameter, 'l')
    
    line = TLine(tes, ymin, tes, ymax)
    #line.SetLineWidth(1)
    line.SetLineStyle(7)
    line.Draw('SAME')
    latex = TLatex()
    latex.SetTextSize(0.045)
    latex.SetTextAlign(13)
    latex.SetTextFont(42)
    latex.DrawLatex(tes+0.02*(xmax-xmin),ymax-0.04*(ymax-ymin),"tes = %.3f"%tes)
    
    if compareFD:
      graphFD.SetLineColor(kBlue)
      graphFD.SetLineWidth(2)
      graphFD.SetLineStyle(2)
      graphFD.Draw('LSAME')
      legend.AddEntry(graphFD, "FitDiagnostics", 'l')
    
    legend.Draw()
    
    CMS_lumi.relPosX = 0.12
    CMS_lumi.CMS_lumi(canvas,13,0)
    gPad.SetTicks(1,1)
    gPad.Modified()
    frame.Draw('SAMEAXIS')
    
    canvas.SaveAs(canvasname+".png")
    if args.pdf: canvas.SaveAs(canvasname+".pdf")
    canvas.Close()
Example #16
0
def plotInputComparison(files, runs, processes, path):

    #clear memory
    gROOT.Reset()
    #make canvas to save plots to
    c1 = TCanvas('c1')
    c1.SetLogy()
    i = 0
    Tfiles = []
    while i < len(files):
        print "Adding file: %s to list of files to run with Run Number: %s and Process Name: %s" % (
            files[i], runs[i], processes[i])
        Tfiles.append(TFile(files[i]))
        i += 1

    j = 0
    Thists = []
    while j < len(Tfiles):
        dirname = "DQMData/Run %s/HLT/Run summary/TimerService/Running 1 processes/process %s/Paths/%s_module_counter" % (
            runs[j], processes[j], path)
        print dirname
        hist = Tfiles[j].Get(dirname)

        Thists.append(hist)
        j += 1

    k = 0
    leg = TLegend(0.4, 0.6, 0.9, 0.9, "")
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    while k < len(Thists):
        if k == 0:
            Thists[k].Scale(1.0 / Thists[k].Integral())
            Thists[k].GetYaxis().SetRangeUser(0.000008, 0.2)
            print "lower bound of bin 100: %i" % Thists[k].GetBinCenter(100)
            print "percentage of events running particle flow: %i " % Thists[
                k].Integral(100, 500)
            Thists[k].SetLineWidth(2)
            Thists[k].SetLineColor(k + 1)
            if args.ext:
                Thists[k].GetXaxis().SetRangeUser(0, 2000)
            else:
                Thists[k].GetXaxis().SetRangeUser(0, 400)
            Thists[k].Draw()

        else:
            Thists[k].Scale(1.0 / Thists[k].Integral())
            Thists[k].SetLineWidth(2)
            Thists[k].SetLineColor(k + 1)
            Thists[k].Draw("same")
        #write name in full
        name = "Mean: %f" % Thists[k].GetMean()
        if args.ext:
            Thists[k].GetXaxis().SetRangeUser(0, 2000)
        else:
            Thists[k].GetXaxis().SetRangeUser(0, 400)

        leg.AddEntry(Thists[k], name, "l")
        k += 1

    leg.Draw("same")

    filename = 'ModuleCounter_%s.pdf' % path
    c1.Print(filename)
Example #17
0
def plot_histograms(histos,
                    use_log_y=False,
                    ratio_=False,
                    legend_titles=None,
                    title="",
                    x_label="",
                    y_label_up="",
                    y_label_ratio="",
                    save_path="./plot.eps",
                    **kwargs):
    """
    Throws all given histograms into one canvas. If desired, a ratio plot will be added.
    """
    gStyle.SetOptStat(0)
    justratioplot = False
    yrange = None
    if isinstance(ratio_, list):
        ratio = ratio_[0]
        justratioplot = ratio_[1]
        yrange = ratio_[2]
    else:
        justratioplot = ratio_
        ratio = ratio_

    linestyles = kwargs.get("linestyles", None)
    markerstyles = kwargs.get("markerstyles", None)
    colors = kwargs.get("colors", None)
    draw_options = kwargs.get("draw_options", None)
    linewidths = kwargs.get("linewidths", None)
    fillstyles = kwargs.get("fillstyles", None)
    fillcolors = kwargs.get("fillcolors", None)
    canvas_name = kwargs.get("canvas_name", "Canvas")
    style_histograms(histos, linestyles, markerstyles, colors, linewidths,
                     fillstyles, fillcolors)

    canvas = TCanvas('canvas', canvas_name, 800, 800)
    pad_up_start = 0.4 if ratio else 0.

    pad_up = TPad("pad_up", "", 0., pad_up_start, 1., 1.)
    if ratio:
        pad_up.SetBottomMargin(0.)
    pad_up.Draw()

    x_label_up_tmp = x_label if not ratio else ""
    put_in_pad(pad_up,
               use_log_y,
               histos,
               title,
               x_label_up_tmp,
               y_label_up,
               yrange,
               draw_options=draw_options)

    pad_up.cd()
    legend = None
    if legend_titles is not None:
        if justratioplot:
            legend = TLegend(.2, .65, .6, .85)
        else:
            legend = TLegend(.45, .65, .85, .85)
        legend.SetBorderSize(0)
        legend.SetFillColor(0)
        legend.SetFillStyle(0)
        legend.SetTextFont(42)
        legend.SetTextSize(0.02)
        for h, l in zip(histos, legend_titles):
            if l is not None:
                legend.AddEntry(h, l)
        legend.Draw()

    canvas.cd()
    pad_ratio = None
    histos_ratio = None

    if ratio and justratioplot is False:
        histos_ratio = divide_all_by_first(histos)
        pad_ratio = TPad("pad_ratio", "", 0., 0.05, 1., pad_up_start)
        pad_ratio.SetTopMargin(0.)
        pad_ratio.SetBottomMargin(0.3)
        pad_ratio.Draw()

        put_in_pad(pad_ratio, False, histos_ratio, "", x_label, y_label_ratio)

    canvas.SaveAs(save_path)

    index = save_path.rfind(".")

    # Save also everything into a ROOT file
    root_save_path = save_path[:index] + ".root"
    root_file = TFile.Open(root_save_path, "RECREATE")
    for h in histos:
        h.Write()
    canvas.Write()
    root_file.Close()

    canvas.Close()
Example #18
0
def comp_fit_pars(do_ratio=False):  #pylint: disable-msg=too-many-statements
    inputdir = './'
    input_files = [
        '../ML_DsAnalysis/QM_prel/outputs/3050/raw_yields/RawYieldsDs_3050_pt2_36.root',
        'outputs/3_24bin_merge/raw_yields/RawYieldsDs_3050_100419cuts.root'
    ]
    input_files_MC = [
        '../ML_DsAnalysis/QM_prel/outputs/3050/raw_yields/RawYieldsDs_3050_MC_pt2_36.root'
    ]
    colors = [kBlack, kGreen + 3, kRed]
    markers = [kFullCircle, kFullDiamond, kFullSquare]
    legendnames = ['ML', 'Std', 'ML - MC']
    suffix = 'compMCStd'
    min_pt = 2.
    max_pt = 36.

    set_style()
    hMean, hSigma = [], []
    input_files = input_files + input_files_MC

    lineMass = TLine(min_pt, 1.96850, max_pt, 1.96850)
    lineMass.SetLineWidth(2)
    lineMass.SetLineColor(kBlack)
    lineMass.SetLineStyle(9)

    legSigma = TLegend(0.2, 0.78, 0.8, 0.93)
    legSigma.SetFillStyle(0)
    legSigma.SetBorderSize(0)
    legSigma.SetTextSize(0.04)

    legMean = TLegend(0.4, 0.73, 0.7, 0.93)
    legMean.SetFillStyle(0)
    legMean.SetBorderSize(0)
    legMean.SetTextSize(0.04)
    legMean.AddEntry(lineMass, "PDG", 'l')

    for file_path, color, marker, legend_name in zip(input_files, colors,
                                                     markers, legendnames):
        input_file = TFile(f'{inputdir}/{file_path}')
        histo_mean = input_file.Get('hRawYieldsMean')
        histo_sigma = input_file.Get('hRawYieldsSigma')
        histo_mean.SetDirectory(0)
        histo_mean.SetLineColor(color)
        histo_mean.SetLineWidth(2)
        histo_mean.SetMarkerColor(color)
        histo_mean.SetMarkerStyle(marker)
        histo_sigma.SetDirectory(0)
        histo_sigma.SetLineColor(color)
        histo_sigma.SetLineWidth(2)
        histo_sigma.SetMarkerColor(color)
        histo_sigma.SetMarkerStyle(marker)
        legMean.AddEntry(histo_mean, legend_name, 'p')
        legSigma.AddEntry(histo_sigma, legend_name, 'p')
        hMean.append(histo_mean)
        hSigma.append(histo_sigma)

    if do_ratio:
        mean_num_list = list(hMean)
        mean_num_list.pop()
        mean_den_hist = hMean[-1]
        mean_ratio_list = create_ratio_hist(mean_num_list, mean_den_hist)
        cMeanRatio = TCanvas('cMeanRatio', '', 800, 800)
        cMeanRatio.DrawFrame(
            min_pt, 0.99, max_pt, 1.01,
            ';#it{p}_{T} (GeV/#it{c}); peak mean / peak mean MC')
        lineRatio = TLine(min_pt, 1., max_pt, 1.)
        lineRatio.SetLineWidth(2)
        lineRatio.SetLineColor(kBlack)
        lineRatio.SetLineStyle(9)
        legMeanRatio = TLegend(0.4, 0.73, 0.7, 0.93)
        legMeanRatio.SetFillStyle(0)
        legMeanRatio.SetBorderSize(0)
        legMeanRatio.SetTextSize(0.04)
        for hist, color, marker, legend_name in zip(mean_ratio_list,
                                                    colors[:-1], markers[:-1],
                                                    legendnames[:-1]):
            hist.SetLineColor(color)
            hist.SetLineWidth(2)
            hist.SetMarkerColor(color)
            hist.SetMarkerStyle(marker)
            hist.Draw('same')
            legMeanRatio.AddEntry(hist, legend_name, 'p')
        lineRatio.Draw()
        legMeanRatio.Draw()

        sigma_num_list = list(hSigma)
        sigma_num_list.pop()
        sigma_den_hist = hSigma[-1]
        sigma_ratio_list = create_ratio_hist(sigma_num_list, sigma_den_hist)
        cSigmaRatio = TCanvas('cSigmaRatio', '', 800, 800)
        cSigmaRatio.DrawFrame(
            min_pt, 0.6, max_pt, 1.8,
            ';#it{p}_{T} (GeV/#it{c}); peak width / peak width MC')
        legSigmaRatio = TLegend(0.4, 0.73, 0.7, 0.93)
        legSigmaRatio.SetFillStyle(0)
        legSigmaRatio.SetBorderSize(0)
        legSigmaRatio.SetTextSize(0.04)
        for hist, color, marker, legend_name in zip(sigma_ratio_list,
                                                    colors[:-1], markers[:-1],
                                                    legendnames[:-1]):
            hist.SetLineColor(color)
            hist.SetLineWidth(2)
            hist.SetMarkerColor(color)
            hist.SetMarkerStyle(marker)
            hist.Draw('same')
            legSigmaRatio.AddEntry(hist, legend_name, 'p')
        lineRatio.Draw()
        legSigmaRatio.Draw()
        cMeanRatio.SaveAs(f'{inputdir}/MeanRatio_{suffix}.pdf')
        cSigmaRatio.SaveAs(f'{inputdir}/SigmaRatio_{suffix}.pdf')

    cMean = TCanvas('cMean', '', 800, 800)
    cMean.DrawFrame(min_pt, 1.9641, max_pt, 1.9759,
                    ';#it{p}_{T} (GeV/#it{c}); peak mean (GeV/#it{c}^{2})')
    lineMass.Draw("same")
    for histo_mean in hMean:
        histo_mean.Draw('same')
    legMean.Draw()

    cSigma = TCanvas('cSigma', '', 800, 800)
    cSigma.DrawFrame(min_pt, 0., max_pt, 0.025,
                     ';#it{p}_{T} (GeV/#it{c}); peak width (GeV/#it{c}^{2})')
    for histo_sigma in hSigma:
        histo_sigma.Draw('same')
    legSigma.Draw()

    cMean.SaveAs(f'{inputdir}/Mean_{suffix}.pdf')
    cSigma.SaveAs(f'{inputdir}/Sigma_{suffix}.pdf')
        else:
            h2.GetYaxis().SetRangeUser(0, 0.7)
            h2.GetXaxis().SetLimits(0, 0.1)
        h2.SetTitle("#DeltaR_" + str(list_PT_T[j]))
        h2.SetTitle("#DeltaR_" + str(list_PT_T[j]))
        h2.SetXTitle("#DeltaR")
        h2.SetXTitle("#DeltaR")
        h2.SetYTitle("Arbitrary number")
        h2.SetYTitle("Arbitrary number")
        h2.SetTitle("")
        #       leg.AddEntry(h1,"Z'("+str(energy[E])+"TeV)#rightarrowq#bar{q}#rightarrow1 subjet","l")
        #       leg.AddEntry(h2,"Z'("+str(energy[E])+"TeV)#rightarrowW^{+}W^{-}#rightarrow2 subjets","l")

        leg = TLegend(0.25, 0.5, 0.45, 0.9)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)
        leg.SetTextSize(0.04)
        leg.SetBorderSize(0)
        leg.SetTextFont(22)
        leg.Draw()
        leg.AddEntry("", "Z'#rightarrowq#bar{q}", "")
        leg.AddEntry(h1, "Trailing^{1}", "l")
        leg.AddEntry(h3, "Trailing^{2}", "l")
        leg.AddEntry(h5, "Trailing^{3}", "l")
        leg.AddEntry(h7, "Trailing^{4}", "l")
        leg.AddEntry(h9, "Trailing^{5}", "l")

        leg1 = TLegend(0.55, 0.5, 0.85, 0.9)
        leg1.SetFillColor(0)
        leg1.SetFillStyle(0)
        leg1.SetTextSize(0.04)
def plotDataOverMCEff(hist_mc_tight,
                      hist_mc_loose,
                      hist_data_tight,
                      hist_data_loose,
                      plot_name='fakerate.pdf'):

    g = TGraphAsymmErrors(hist_mc_tight)
    g.Divide(hist_mc_tight, hist_mc_loose)
    g.GetYaxis().SetTitle('Fake rate')
    g.GetXaxis().SetTitle(hist_mc_tight.GetXaxis().GetTitle())
    g.GetYaxis().SetTitleOffset(1.2)
    g.GetYaxis().SetTitleOffset(1.3)

    g.SetLineColor(2)
    g.SetMarkerColor(2)

    g_data = TGraphAsymmErrors(hist_data_tight)
    g_data.Divide(hist_data_tight, hist_data_loose)
    g_data.GetYaxis().SetTitle('Fake rate')
    g_data.GetXaxis().SetTitle(hist_data_tight.GetXaxis().GetTitle())
    g_data.GetYaxis().SetTitleOffset(1.2)
    g_data.GetYaxis().SetTitleOffset(1.3)
    g_data.SetMarkerColor(1)

    g_vals = g.GetY()
    g_data_vals = g_data.GetY()

    g_ratio = g_data.Clone('ratio')

    for i in xrange(g_data.GetN()):
        ratio = g_data_vals[i] / g_vals[i] if g_vals[i] else 0.
        g_ratio.SetPoint(i, g.GetX()[i], ratio)

        rel_y_low = math.sqrt((g_data.GetErrorYlow(i) / g_data_vals[i])**2 + (
            g.GetErrorYlow(i) /
            g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYlow(i, rel_y_low * ratio)

        rel_y_high = math.sqrt(
            (g_data.GetErrorYhigh(i) / g_data_vals[i])**2 +
            (g.GetErrorYhigh(i) /
             g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYhigh(i, rel_y_high * ratio)

    # Gymnastics to get same label sizes etc in ratio and main plot
    ytp_ratio = 2.
    xtp_ratio = 2.

    # hr.GetYaxis().SetNdivisions(4)

    g_ratio.GetYaxis().SetTitleSize(g.GetYaxis().GetTitleSize() * xtp_ratio)
    g_ratio.GetXaxis().SetTitleSize(g.GetXaxis().GetTitleSize() * ytp_ratio)

    g_ratio.GetYaxis().SetTitleOffset(g.GetYaxis().GetTitleOffset() /
                                      xtp_ratio)
    g_ratio.GetXaxis().SetTitleOffset(
        g.GetXaxis().GetTitleOffset())  # / ytp_ratio)

    g_ratio.GetYaxis().SetLabelSize(g.GetYaxis().GetLabelSize() * xtp_ratio)
    g_ratio.GetXaxis().SetLabelSize(g.GetXaxis().GetLabelSize() * ytp_ratio)

    g_data.GetXaxis().SetLabelColor(0)
    g_data.GetXaxis().SetLabelSize(0)
    g.GetXaxis().SetLabelColor(0)
    g.GetXaxis().SetLabelSize(0)

    g_ratio.GetXaxis().SetTitle(g.GetXaxis().GetTitle())

    # maxy = 1.1 * min(g.GetMaximum(), g_data.GetMaximum(), 0.2)
    g.GetYaxis().SetRangeUser(0.001, 0.2)

    cv, pad, padr = HistDrawer.buildCanvas()

    pad.cd()

    g.Draw('AP')
    g_data.Draw('P')

    legend = TLegend(0.23, 0.73, 0.43, 0.91)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetLineColor(0)
    legend.SetLineWidth(0)

    legend.AddEntry(g.GetName(), 'MC', 'lep')
    legend.AddEntry(g_data.GetName(), 'Observed', 'lep')

    legend.Draw()

    padr.cd()
    g_ratio.GetYaxis().SetRangeUser(0.51, 1.49)
    g_ratio.GetYaxis().SetTitle('Obs/MC')
    g_ratio.Draw('AP')

    drawRatioLines(g_ratio)

    cv.Print(plot_name)
def FitMassPoint(massin, massmin, massmax, nbins=50):

    #    massin = 800;
    #    massmin = 400;
    #    massmax = 1400;
    #    nbins = 50;
    #    massin = 600;
    #    massmin = 200;
    #    massmax = 1000;
    #    nbins = 40;

    inputFile = ROOT.TFile(
        "/uscms_data/d2/andersj/Wjj/2012/data/Moriond2013/ReducedTrees/RD_mu_HWWMH"
        + str(massin) + "_CMSSW532_private.root")
    tree = inputFile.Get("WJet")
    #    tree.Print();

    print "n entries: ", tree.GetEntries()

    ############################################################
    # RooFitting

    rrv_mass = ROOT.RooRealVar("rrv_mass", "rrv_mass", massmin, massmax)
    rrv_weight = RooRealVar("rrv_weight", "rrv_weight", 0., 10000000.)

    rrv_mH = ROOT.RooRealVar("rrv_mH", "rrv_mH", massin, massmin, massmax)
    rrv_gamma = ROOT.RooRealVar("rrv_gamma", "rrv_gamma", 20., massmax)
    rrv_mH2 = ROOT.RooRealVar("rrv_mH2", "rrv_mH2", massin, massmin, massmax)
    rrv_gamma2 = ROOT.RooRealVar("rrv_gamma2", "rrv_gamma2", 20., massmax)
    #    rrv_gamma2 = ROOT.RooRealVar("rrv_gamma2","rrv_gamma2",350.,600.)
    rrv_mH3 = ROOT.RooRealVar("rrv_mH3", "rrv_mH3", massin, massmin, massmax)
    rrv_gamma3 = ROOT.RooRealVar("rrv_gamma3", "rrv_gamma3", 20., massmax)
    rrv_mH4 = ROOT.RooRealVar("rrv_mH4", "rrv_mH4", massin, massmin, massmax)
    rrv_gamma4 = ROOT.RooRealVar("rrv_gamma4", "rrv_gamma4", 20., massmax)

    rds_raw = ROOT.RooDataSet("rds_raw", "rds_raw",
                              RooArgSet(rrv_mass, rrv_weight),
                              RooFit.WeightVar(rrv_weight))
    rds_cps = ROOT.RooDataSet("rds_cps", "rds_cps",
                              RooArgSet(rrv_mass, rrv_weight),
                              RooFit.WeightVar(rrv_weight))
    rds_cps_intf = ROOT.RooDataSet("rds_cps_intf", "rds_cps_intf",
                                   RooArgSet(rrv_mass, rrv_weight),
                                   RooFit.WeightVar(rrv_weight))

    model_pdf = ROOT.RooRelBWHighMass("model_pdf", "model_pdf", rrv_mass,
                                      rrv_mH, rrv_gamma)
    model2_pdf = ROOT.RooRelBWRunningWidth("model2_pdf", "model2_pdf",
                                           rrv_mass, rrv_mH2, rrv_gamma2)

    model3_pdf = ROOT.RooRelBWRunningWidth("model3_pdf", "model3_pdf",
                                           rrv_mass, rrv_mH3, rrv_gamma3)
    model4_pdf = ROOT.RooRelBWRunningWidth("model4_pdf", "model4_pdf",
                                           rrv_mass, rrv_mH4, rrv_gamma4)

    for i in range(tree.GetEntries()):

        if i % 10000 == 0: print "i: ", i
        tree.GetEntry(i)

        curmass = getattr(tree, "W_H_mass_gen")
        if curmass < massmax and curmass > massmin:

            rrv_mass.setVal(curmass)

            tmpweight_cps = getattr(
                tree, "complexpolewtggH" + str(massin)) / getattr(
                    tree, "avecomplexpolewtggH" + str(massin))
            tmpweight_cps_intf = getattr(
                tree, "complexpolewtggH" + str(massin)) * getattr(
                    tree, "interferencewtggH" + str(massin)) / getattr(
                        tree, "avecomplexpolewtggH" + str(massin))

            rds_raw.add(RooArgSet(rrv_mass), 1.)
            rds_cps.add(RooArgSet(rrv_mass), tmpweight_cps)
            rds_cps_intf.add(RooArgSet(rrv_mass), tmpweight_cps_intf)

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

    rfresult = model_pdf.fitTo(rds_cps, RooFit.Save(1),
                               RooFit.SumW2Error(kTRUE))
    rfresult2 = model2_pdf.fitTo(rds_cps, RooFit.Save(1),
                                 RooFit.SumW2Error(kTRUE))
    rrv_mH3.setVal(rrv_mH2.getVal())
    rrv_gamma3.setVal(0.5 * rrv_gamma2.getVal())
    rrv_mH4.setVal(rrv_mH2.getVal())
    rrv_gamma4.setVal(0.2 * rrv_gamma2.getVal())

    mplot = rrv_mass.frame(RooFit.Title("mass plot"))
    rds_raw.plotOn(mplot, RooFit.MarkerColor(kBlack), RooFit.LineColor(kBlack),
                   RooFit.Binning(nbins, massmin, massmax),
                   RooFit.DataError(RooAbsData.SumW2))
    rds_cps_intf.plotOn(mplot, RooFit.MarkerColor(kBlue),
                        RooFit.LineColor(kBlue),
                        RooFit.Binning(nbins, massmin, massmax),
                        RooFit.DataError(RooAbsData.SumW2))
    rds_cps.plotOn(mplot, RooFit.MarkerColor(kRed), RooFit.LineColor(kRed),
                   RooFit.Binning(nbins, massmin, massmax),
                   RooFit.DataError(RooAbsData.SumW2))
    #    model_pdf.plotOn(mplot, RooFit.LineColor(kRed));
    model2_pdf.plotOn(mplot, RooFit.LineColor(kRed), RooFit.LineStyle(2))
    model3_pdf.plotOn(mplot, RooFit.LineColor(ROOT.kGreen + 2),
                      RooFit.LineStyle(2))
    model4_pdf.plotOn(mplot, RooFit.LineColor(ROOT.kGreen + 2),
                      RooFit.LineStyle(3))

    print "rds_cps_intf.sumEntries() = ", rds_cps_intf.sumEntries()
    print "model_pdf: mH = ", rrv_mH.getVal(), ", gamma = ", rrv_gamma.getVal(
    )
    print "model2_pdf: mH = ", rrv_mH2.getVal(
    ), ", gamma = ", rrv_gamma2.getVal()

    dummy_h1 = ROOT.TH1F("dummy_h1", "dummy_h1", 1, 0, 1)
    dummy_h1.SetMarkerColor(ROOT.kBlack)
    dummy_h2 = ROOT.TH1F("dummy_h2", "dummy_h2", 1, 0, 1)
    dummy_h2.SetMarkerColor(ROOT.kRed)
    dummy_h3 = ROOT.TH1F("dummy_h3", "dummy_h3", 1, 0, 1)
    dummy_h3.SetMarkerColor(ROOT.kBlue)
    dummy_h4 = ROOT.TH1F("dummy_h4", "dummy_h4", 1, 0, 1)
    dummy_h4.SetLineColor(ROOT.kRed)
    dummy_h5 = ROOT.TH1F("dummy_h5", "dummy_h5", 1, 0, 1)
    dummy_h5.SetLineColor(ROOT.kRed)
    dummy_h5.SetLineStyle(2)
    dummy_h6 = ROOT.TH1F("dummy_h6", "dummy_h6", 1, 0, 1)
    dummy_h6.SetLineColor(ROOT.kGreen + 2)
    dummy_h6.SetLineStyle(2)
    dummy_h7 = ROOT.TH1F("dummy_h7", "dummy_h7", 1, 0, 1)
    dummy_h7.SetLineColor(ROOT.kGreen + 2)
    dummy_h6.SetLineStyle(3)

    L = TLegend(0.65, 0.60, 0.93, 0.85)
    L.SetFillStyle(0)
    L.AddEntry(dummy_h1, "Powheg", "p")
    L.AddEntry(dummy_h2, "w/CPS weight", "p")
    L.AddEntry(dummy_h3, "w/CPS,Intf weight", "p")
    #    L.AddEntry(dummy_h4,"Fit, BW (Mario)","l");
    L.AddEntry(dummy_h5, "Fit, BW (running)", "l")
    L.AddEntry(dummy_h6, "BW (running), width*0.5", "l")
    L.AddEntry(dummy_h7, "Fit, BW (running), width*0.2", "l")

    can2 = ROOT.TCanvas("can2", "can2", 800, 800)
    mplot.Draw()
    L.Draw()
    ROOT.gPad.SetLogy()
    can2.SaveAs("massFits/mass_rf_" + str(massin) + ".eps")
    can2.SaveAs("massFits/mass_rf_" + str(massin) + ".png")

    outputpar = []
    outputpar.append(rrv_mH2.getVal())
    outputpar.append(rrv_gamma2.getVal())
    outputpar.append(rrv_mH.getVal())
    outputpar.append(rrv_gamma.getVal())
    return outputpar
Example #22
0
def MakeLegend(can,
               x1=.8,
               y1=.8,
               x2=.9,
               y2=.9,
               textsize=18,
               ncolumns=1,
               totalentries=0,
               option='f',
               skip=[]):
    from ROOT import TLegend, TH1, gStyle, TGraph
    if can.GetPrimitive('pad_top'):
        MakeLegend(can.GetPrimitive('pad_top'),
                   x1,
                   y1,
                   x2,
                   y2,
                   textsize,
                   ncolumns,
                   totalentries,
                   skip=skip)
        return
    if CanvasEmpty(can):
        print 'Error: trying to make legend from canvas with 0 plots. Will do nothing.'
        return
    #
    # if a previous version exists from this function, delete it
    #
    if can.GetPrimitive('legend'):
        can.GetPrimitive('legend').Delete()
    leg = TLegend(x1, y1, x2, y2)
    leg.SetName('legend')
    tobject_collector.append(leg)
    leg.SetTextFont(43)
    leg.SetTextSize(textsize)
    leg.SetTextFont(43)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetNColumns(ncolumns)
    #
    # Add by TH1 GetTitle()
    #
    the_primitives = can.GetListOfPrimitives()
    if can.GetPrimitive('pad_top'):
        the_primitives = can.GetPrimitive('pad_top').GetListOfPrimitives()
    if can.GetPrimitive('stack'):
        the_stack = list(reversed(list(can.GetPrimitive('stack').GetHists())))
        the_primitives = the_stack + list(the_primitives)

    if type(option) == type(''):
        option = [option] * 100

    total = 0
    for i in the_primitives:
        if i.GetName() == 'stack': continue
        drawopt = i.GetDrawOption()
        if issubclass(type(i), TH1) or issubclass(type(i), TGraph):
            if i.GetTitle() in skip:
                continue
            leg.AddEntry(i, i.GetTitle(), option[total])  # plef
            total += 1

    #
    # Add empty entries to ensure a standard layout
    #
    for i in range(100):
        if totalentries == 0: break
        if total >= totalentries: break
        leg.AddEntry(None, '', '')
        total += 1

    # recipe for making roughly square boxes
    h = leg.GetY2() - leg.GetY1()
    w = leg.GetX2() - leg.GetX1()
    leg.SetMargin(leg.GetNColumns() * h / float(leg.GetNRows() * w))
    can.cd()
    if can.GetPrimitive('pad_top'):
        can.GetPrimitive('pad_top').cd()
    leg.Draw()
    can.Modified()
    can.Update()
    return
def plotUpperLimits(model, lambdas, helicity):

    N = len(lambdas)
    #yellow = TGraph(2*N)    # yellow band
    #green = TGraph(2*N)     # green band
    #median = TGraph(N)      # median line

    Mmin = [100 + i * 100 for i in range(40)]
    graphs = []
    for i in range(N):
        thislam = TGraph(len(Mmin))
        thislimit = []
        for mm in range(len(Mmin)):
            file_name = "./%sdataCards/ee_signif%s/higgsCombine%d.Significance.mH%d.root" % (
                model, helicity, Mmin[mm], lambdas[i])
            limit = getLimits(file_name)
            thislam.SetPoint(mm, Mmin[mm], limit[0])
            thislam.SetLineColor(i + 2)
            thislam.SetLineWidth(2)
            thislimit.append(limit[0])
        graphs.append(thislam.Clone())
        print "this minimum mass cut is %d" % Mmin[mm]
        print thislimit

        #yellow.SetPoint(    i,    values[i], limit[4] ) # + 2 sigma
        #green.SetPoint(     i,    values[i], limit[3] ) # + 1 sigma
        #median.SetPoint(    i,    labels[i], limit[0] ) # median
        #green.SetPoint(  2*N-1-i, values[i], limit[1] ) # - 1 sigma
        #yellow.SetPoint( 2*N-1-i, values[i], limit[0] ) # - 2 sigma

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()
    if model == "ADD": frame = c.DrawFrame(100, 0.01, 4000, 22)
    elif "Con" in helicity: frame = c.DrawFrame(100, 0.01, 4000, 15)
    else: frame = c.DrawFrame(100, 0.01, 4000, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    frame.GetYaxis().SetTitle("Significance")
    frame.GetXaxis().SetTitle("M_{min} [GeV]")
    frame.SetMinimum(0)
    #frame.SetMaximum(max(up2s)*1.05)
    #frame.GetXaxis().SetLimits(min(values),max(values))

    for gf in graphs:
        gf.Draw('Lsame')
    '''
    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')
 
    green.SetFillColor(ROOT.kGreen+1)
    green.SetLineColor(ROOT.kGreen+1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')
    
    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')'''

    CMS_lumi.CMS_lumi(c, 13, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    x1 = 0.75
    x2 = x1 + 0.24
    y2 = 0.86
    y1 = 0.60
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    for i in range(N):
        legend.AddEntry(graphs[i], "#Lambda = %d" % lambdas[i], 'l')
    #legend.AddEntry(median, "Asymptotic CL_{s} expected",'L')
    #legend.AddEntry(green, "#pm 1 std. deviation",'f')
    #legend.AddEntry(green, "Asymptotic CL_{s} #pm 1 std. deviation",'f')
    #legend.AddEntry(yellow,"#pm 2 std. deviation",'f')
    #legend.AddEntry(green, "Asymptotic CL_{s} #pm 2 std. deviation",'f')
    legend.Draw()

    print " "
    c.SaveAs("%slimits/%sSignificance_ee%s.png" % (model, model, helicity))
    c.Close()
Example #24
0
def plotDataMC(datahist,mchist,usedata, label1, label2,name,filename):
	

	hCanvas = TCanvas("hCanvas", "Distribution", 800,800)
	if usedata==True:
                plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1)
                ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3)
                setTDRStyle()
                plotPad.UseCurrentStyle()
                ratioPad.UseCurrentStyle()
                plotPad.Draw("hist")
                ratioPad.Draw("hist")
                plotPad.cd()
        else:
                plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
                setTDRStyle()
                plotPad.UseCurrentStyle()
                plotPad.Draw()
                plotPad.cd()	
	colors = createMyColors()		
	legend = TLegend(0.55, 0.6, 0.925, 0.925)
	legend.SetFillStyle(0)
	legend.SetBorderSize(0)
	legend.SetTextFont(42)
	legendEta = TLegend(0.45, 0.75, 0.925, 0.925)
	legendEta.SetFillStyle(0)
	legendEta.SetBorderSize(0)
	legendEta.SetTextFont(42)
	legendEta.SetNColumns(2)
	latex = ROOT.TLatex()
	latex.SetTextFont(42)
	latex.SetTextAlign(31)
	latex.SetTextSize(0.04)
	latex.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.06)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.045)
	latexCMSExtra.SetNDC(True)	
	legendHists = []
	legendHistData = ROOT.TH1F()
	category = ROOT.TLatex()
	category.SetNDC(True)
	category.SetTextSize(0.04)
	if usedata==True:	
		legend.AddEntry(legendHistData,label1,"pe")	
		legendEta.AddEntry(legendHistData,label1,"pe")	

	#process.label = process.label.replace("#mu^{+}#mu^{-}","e^{+^{*}}e^{-}")
	temphist = ROOT.TH1F()
	if label2=="Generated":
		temphist.SetFillColor(3)
		mchist.SetFillColor(3)
	else:
		temphist.SetFillColor(2)
		mchist.SetFillColor(2)
	legendHists.append(temphist.Clone)
	legend.AddEntry(temphist,label2,"f")
	#legendEta.AddEntry(temphist,process.label,"f")
	
	# Modify plot pad information	
	nEvents=-1

	ROOT.gStyle.SetOptStat(0)
	
	intlumi = ROOT.TLatex()
	intlumi.SetTextAlign(12)
	intlumi.SetTextSize(0.045)
	intlumi.SetNDC(True)
	intlumi2 = ROOT.TLatex()
	intlumi2.SetTextAlign(12)
	intlumi2.SetTextSize(0.07)
	intlumi2.SetNDC(True)
	scalelabel = ROOT.TLatex()
	scalelabel.SetTextAlign(12)
	scalelabel.SetTextSize(0.03)
	scalelabel.SetNDC(True)
	metDiffLabel = ROOT.TLatex()
	metDiffLabel.SetTextAlign(12)
	metDiffLabel.SetTextSize(0.03)
	metDiffLabel.SetNDC(True)
	chi2Label = ROOT.TLatex()
	chi2Label.SetTextAlign(12)
	chi2Label.SetTextSize(0.03)
	chi2Label.SetNDC(True)
	hCanvas.SetLogy()


	# Luminosity information	
	plotPad.cd()
	plotPad.SetLogy(0)
	plotPad.SetLogy()
	if usedata==True:
		yMax = datahist.GetBinContent(datahist.GetMaximumBin())*1000
		yMin = 0.00000001
		xMax = datahist.GetXaxis().GetXmax()
		xMin = datahist.GetXaxis().GetXmin()
	else:	
		yMax = mchist.GetBinContent(datahist.GetMaximumBin())
		yMin = 0.00000001
		xMax = mchist.GetXaxis().GetXmax()
		xMin = mchist.GetXaxis().GetXmin()	
		yMax = yMax*10000
	if name.find("dimuon")!=-1:
		plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; m_{#mu#mu}[GeV] ;fb/GeV")
        else:
		plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; m_{ee}[GeV] ;fb/GeV")
	
	
	# Draw signal information
	
	# Draw background from stack
	mchist.Draw("samehist")		

	# Draw data
	datahist.SetMinimum(0.0001)
	if usedata==True:
		datahist.SetMarkerStyle(8)
		datahist.Draw("samepehist")	

	# Draw legend
	legend.Draw()
	plotPad.SetLogx()
	latex.DrawLatex(0.95,0.96,"13 TeV")
	yLabelPos = 0.85
	cmsExtra = "Preliminary"
	if not usedata==True:
		cmsExtra = "#splitline{Preliminary}{Simulation}"
		yLabelPos = 0.82	
	latexCMS.DrawLatex(0.19,0.89,"CMS")
	category.DrawLatex(0.3,0.7,name)
	latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))
	#~ print datahist.Integral()
	if usedata==True:
		try:
			ratioPad.cd()
			ratioPad.SetLogx()
		except AttributeError:
			print ("Plot fails. Look up in errs/failedPlots.txt")
			outFile =open("errs/failedPlots.txt","a")
			outFile.write('%s\n'%plot.filename%("_"+run.label+"_"+dilepton))
			outFile.close()
			#plot.cuts=baseCut
			return 1
		if label2=="Generated":
			ratioGraphs =  ratios.RatioGraph(datahist,mchist, xMin=xMin, xMax=xMax,title="	nokFac/kFac",yMin=0.7,yMax=1.3,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=10000000000000,labelSize=0.125,pull=False)
			ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8)

		else:
			ratioGraphs =  ratios.RatioGraph(datahist,mchist, xMin=xMin, xMax=xMax,title="nokFac/kFac",yMin=0.7,yMax=1.3,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=10000000000000,labelSize=0.125,pull=False)
			ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8)
					

	ROOT.gPad.RedrawAxis()
	plotPad.RedrawAxis()
	if usedata==True:

		ratioPad.RedrawAxis()
	if not os.path.exists("plots"):
		os.makedirs("plots")	
	hCanvas.Print("plots/%s.pdf"%filename)
Example #25
0
def limit2HDM():
    global signals
    signals = range(800, 2000 + 1, 50)
    multF = HTOBB
    THEORY = ['T1', 'T2']

    mass, val = fillValues("./combine/AZh/AZh_M%d.txt")
    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()

    massB, valB = fillValues("./combine/BBAZh/BBAZh_M%d.txt")
    Obs0sB = TGraph()
    Exp0sB = TGraph()
    Exp1sB = TGraphAsymmErrors()
    Exp2sB = TGraphAsymmErrors()

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF)
        Exp0s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF,
                            val[m][4] * multF - val[m][3] * multF)
        Exp2s.SetPoint(n, m, val[m][3] * multF)
        Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF,
                            val[m][5] * multF - val[m][3] * multF)

        Obs0sB.SetPoint(n, m, valB[m][0] * multF)
        Exp0sB.SetPoint(n, m, valB[m][3] * multF)
        Exp1sB.SetPoint(n, m, valB[m][3] * multF)
        Exp1sB.SetPointError(n, 0., 0.,
                             valB[m][3] * multF - valB[m][2] * multF,
                             valB[m][4] * multF - valB[m][3] * multF)
        Exp2sB.SetPoint(n, m, valB[m][3] * multF)
        Exp2sB.SetPointError(n, 0., 0.,
                             valB[m][3] * multF - valB[m][1] * multF,
                             valB[m][5] * multF - valB[m][3] * multF)

    col = 629
    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp0s.SetLineColor(1)
    #    Exp1s.SetFillColorAlpha(col, 0.4) #kGreen+1
    #    Exp1s.SetLineColorAlpha(col, 0.4)
    #    Exp2s.SetFillColorAlpha(col, 0.2) #kOrange
    #    Exp2s.SetLineColorAlpha(col, 0.2)
    Exp1s.SetFillColor(417)
    Exp1s.SetLineColor(417)
    Exp2s.SetFillColor(800)
    Exp2s.SetLineColor(800)

    colB = 922
    Exp2sB.SetLineWidth(2)
    Obs0sB.SetLineStyle(9)
    Obs0sB.SetLineWidth(3)
    Obs0sB.SetMarkerStyle(0)
    Obs0sB.SetLineColor(colB)
    Exp0sB.SetLineStyle(8)
    Exp0sB.SetLineWidth(3)
    Exp0sB.SetLineColor(colB)
    Exp1sB.SetFillColorAlpha(colB, 0.4)  #kGreen+1
    Exp1sB.SetLineColorAlpha(colB, 0.4)
    Exp2sB.SetFillColorAlpha(colB, 0.2)  #kOrange
    Exp2sB.SetLineColorAlpha(colB, 0.2)

    Exp2s.GetXaxis().SetTitle("m_{A} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle(
        "#sigma(A) #bf{#it{#Beta}}(A #rightarrow Zh) #bf{#it{#Beta}}(h #rightarrow bb) (fb)"
    )
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Theory = {}
    #for t in THEORY:
    #    Theory[t] = TGraphAsymmErrors()
    #    for m in sorted(THDM[t]['ggA'].keys()):
    #        if m < mass[0] or m > mass[-1]: continue
    #        Xs, Xs_Up, Xs_Down = 0., 0., 0.
    #        Xs = THDM[t]['ggA'][m]
    #        Xs_Up = Xs*(1.+math.sqrt((THDM['PDF']['ggA'][m][0]-1.)**2 + (THDM['QCD']['ggA'][m][0]-1.)**2))
    #        Xs_Down = Xs*(1.-math.sqrt((1.-THDM['PDF']['ggA'][m][1])**2 + (1.-THDM['QCD']['ggA'][m][1])**2))
    #        n = Theory[t].GetN()
    #        Theory[t].SetPoint(n, m, Xs)
    #        Theory[t].SetPointError(n, 0., 0., (Xs-Xs_Down), (Xs_Up-Xs))

    #    Theory[t].SetLineColor(theoryLineColor[t])
    #    Theory[t].SetFillColor(theoryFillColor[t])
    #    Theory[t].SetFillStyle(theoryFillStyle[t])
    #    Theory[t].SetLineWidth(2)
    #        #Theory[t].SetLineStyle(7)

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    Exp0s.Draw("SAME, L")
    #    Exp2sB.Draw("SAME, 3")
    #    Exp1sB.Draw("SAME, 3")
    Exp0sB.Draw("SAME, L")
    if not options.blind:
        Obs0s.Draw("SAME, L")
        Obs0sB.Draw("SAME, L")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    #setHistStyle(Exp2s)


#    Exp2s.GetXaxis().SetTitleSize(0.045)
#    Exp2s.GetYaxis().SetTitleSize(0.04)
#    Exp2s.GetXaxis().SetLabelSize(0.04)
#    Exp2s.GetYaxis().SetLabelSize(0.04)
#    Exp2s.GetXaxis().SetTitleOffset(1)
#    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.5, 1.e3)
    Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1])
    drawAnalysis('AZh')
    drawRegion('AZHsl', True)
    drawCMS(LUMI, "")  #Preliminary
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)

    # legend
    leg = TLegend(0.6, 0.90, 0.99, 0.90)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(None, "gg #rightarrow A #rightarrow Zh",
                 "")  #"95% CL upper limits"
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    leg.AddEntry(None, "", "")
    leg.AddEntry(None, "bbA #rightarrow Zh", "")
    leg.AddEntry(Obs0sB, "Observed", "l")
    leg.AddEntry(Exp0sB, "Expected", "l")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * 0.045)
    leg.Draw()

    #    latex = TLatex()
    #    latex.SetNDC()
    #    latex.SetTextSize(0.040)
    #    latex.SetTextFont(42)
    #    latex.DrawLatex(0.65, leg.GetY1()-0.045, "cos(#beta-#alpha)=0.25, tan(#beta)=1")

    #    legB = TLegend(0.12, 0.4-4*0.3/5., 0.65, 0.4)
    legB = TLegend(0.15, 0.27, 0.68, 0.27)
    legB.SetBorderSize(0)
    legB.SetFillStyle(0)  #1001
    legB.SetFillColor(0)
    for t in THEORY:
        legB.AddEntry(Theory[t], theoryLabel[t], "fl")
    legB.AddEntry(None, "cos(#beta-#alpha)=0.25, tan(#beta)=1", "")
    legB.SetY1(legB.GetY2() - legB.GetNRows() * 0.045)
    legB.Draw()

    c1.GetPad(0).RedrawAxis()
    leg.Draw()

    c1.Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("plotsLimit/Exclusion/THDM.png")
    c1.Print("plotsLimit/Exclusion/THDM.pdf")
Example #26
0
def draw(hist,
         fit,
         channel,
         data,
         back,
         sign,
         snorm=1,
         lumi=-1,
         ratio=0,
         log=False):
    # If not present, create BkgSum
    if not 'BkgSum' in hist.keys():
        hist['BkgSum'] = hist['data_obs'].Clone(
            "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
        hist['BkgSum'].Reset("MICES")
        for i, s in enumerate(back):
            hist['BkgSum'].Add(hist[s])
    hist['BkgSum'].SetMarkerStyle(0)

    setHistStyle(hist['BkgSum'], 1.1 if ratio else 1.0)
    # Create stack
    bkg = THStack(
        "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";" +
        hist['BkgSum'].GetYaxis().GetTitle())
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    n = len([x for x in data + back + ['BkgSum'] + sign if sample[x]['plot']])
    leg = TLegend(0.69, 0.86 - 0.04 * n, 0.95, 0.86)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pl")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            leg.AddEntry(hist[s],
                         sample[s]['label'].replace("m_{#Chi}=1 GeV",
                                                    ""), "fl")

    ### data/bkg ratio and systematics
    err = hist['BkgSum'].Clone("BkgErr;")
    err.SetTitle("")
    err.GetYaxis().SetTitle("data / bkg")
    if fit == "prefit":
        err.SetFillColor(ROOT.kOrange - 2)
    elif fit == "postfit":
        err.SetFillColor(ROOT.kBlue)
    err.SetFillStyle(3001)
    for i in range(1, err.GetNbinsX() + 1):
        err.SetBinContent(i, 1)
        if hist['BkgSum'].GetBinContent(i) > 0:
            err.SetBinError(
                i, hist['BkgSum'].GetBinError(i) /
                hist['BkgSum'].GetBinContent(i))
    errLine = err.Clone("errLine")
    errLine.SetLineWidth(1)
    errLine.SetFillStyle(0)
    res = hist['data_obs'].Clone("residues")
    for i in range(0, res.GetNbinsX() + 1):
        if hist['BkgSum'].GetBinContent(i) > 0:
            res.SetBinContent(
                i,
                res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
            res.SetBinError(
                i,
                res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))

    # Legend
    leg1 = TLegend(0.12, 0.45, 0.25, 0.5)
    leg1.SetBorderSize(0)
    leg1.SetFillStyle(0)
    leg1.SetFillColor(0)
    leg1.SetTextSize(0.05)
    leg1.AddEntry(err, "systematic uncertainty (" + fit + ")", "f")

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if ratio else 600)
    gStyle.SetOptStat(0)
    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)
    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.08)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if log:
        c1.GetPad(bool(ratio)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    #    hist['BkgSum'].Draw("SAME, E2") # sum of bkg
    if len(data) > 0: hist['data_obs'].Draw("SAME, PE")  # data
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST",
                                   hist[s].Integral() * snorm)  # signals
        pass

    bkg.SetMaximum((2. if log else 1.1) * max(
        bkg.GetMaximum(), hist['data_obs'].GetMaximum() +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 1.e-1) if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)

    setHistStyle(bkg, 1.1 if ratio else 1.0)

    leg.Draw()
    #    drawCMS(lumi, "Preliminary",True)
    drawCMS(lumi, "Private", True)
    drawRegion(channel)
    drawAnalysis(channel)
    drawFit(fit)

    if ratio:
        c1.cd(2)
        setBotStyle(err, 3, True)
        setBotStyle(res)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if len(data) > 0:
            res.Draw("SAME, PE0")
            drawRatio(hist['data_obs'], hist['BkgSum'])
            drawKolmogorov(hist['data_obs'], hist['BkgSum'])

        leg1.Draw()

    c1.Update()

    # return list of objects created by the draw() function
    return [c1, bkg, leg, leg1, err, errLine, res]
Example #27
0
def makeDiTauStack(outDir,
                   inFile,
                   rootDir,
                   s,
                   labelX,
                   units="GeV",
                   left=False,
                   channel="",
                   json="Golden",
                   log=False,
                   dndm=False,
                   doRatio=False,
                   year=2017,
                   sign='OS',
                   LTcut=0.,
                   cat='mmtt',
                   wait='wait'):

    tdrstyle.setTDRStyle()

    writeExtraText = True  # if extra text
    extraText = "Preliminary"  # default extra text is "Preliminary"
    lumi_sqrtS = "13 TeV"
    if json == "Golden": lumi_13TeV = channel + "    41.8 fb^{-1}, 2017"
    iPeriod = 4  # 1=7TeV, 2=8TeV, 3=7+8TeV, 7=7+8+13TeV

    xR = 0.65  #legend parameters
    xR = 0.2  #legend parameters
    H = 600
    W = 600
    H_ref = 600
    W_ref = 600

    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.16 * W_ref
    R = 0.04 * W_ref

    #margins for inbetween the pads in a ratio plot
    B_ratio = 0.1 * H_ref
    T_ratio = 0.03 * H_ref

    #margin required for lebal on bottom of raito plot
    B_ratio_label = 0.3 * H_ref

    c = TCanvas('c1', 'c1', 50, 50, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)

    if not doRatio:
        c.SetLeftMargin(L / W)
        c.SetRightMargin(R / W)
        c.SetTopMargin(T / H)
        c.SetBottomMargin(B / H)

    c.cd()

    ratioPad = TPad("pad2", "", 0.0, 0.0, 1.0, 0.29)
    plotPad = TPad("pad1", "", 0.0016, 0.291, 1.0, 1.0)
    if doRatio:
        plotPad.SetTicks(0, 0)
        plotPad.SetLeftMargin(L / W)
        plotPad.SetRightMargin(R / W)
        plotPad.SetTopMargin(T / H)
        plotPad.SetBottomMargin(B_ratio / H)
        plotPad.SetFillColor(0)
        plotPad.SetBottomMargin(0)

        ratioPad.SetLeftMargin(L / W)
        ratioPad.SetRightMargin(R / W)
        ratioPad.SetTopMargin(T_ratio / H)
        ratioPad.SetTopMargin(0.007)
        ratioPad.SetBottomMargin(B_ratio_label / H)
        ratioPad.SetGridy(1)
        ratioPad.SetFillColor(4000)

    else:
        plotPad = TPad("pad1", "", 0.0, 0.03, 1.0, 1.0)
        plotPad.SetLeftMargin(L / W)
        plotPad.SetRightMargin(R / W)
        plotPad.SetTopMargin(T / H)
        plotPad.SetBottomMargin(B / H)

    plotPad.Draw()
    plotPad.cd()

    print("In makeStack inFile={0:s}".format(inFile))
    f = TFile(inFile)

    groups = ['data', 'Reducible', 'Rare', 'ZZ4L', 'Signal']
    histo = {}
    colors = {
        'data': 0,
        'Reducible': kMagenta - 10,
        'Rare': kBlue - 8,
        'ZZ4L': kAzure - 9,
        'Signal': kRed
    }
    hs = THStack("hs", "")
    for group in groups:
        if len(cat) == 4:
            histo[group] = f.Get("h{0:s}_{1:s}_Mtt".format(group, cat))
        else:
            histo[group] = f.Get("h{0:s}_ee{1:s}_Mtt".format(group, cat))
            histo2 = f.Get("h{0:s}_mm{1:s}_Mtt".format(group, cat))
            histo[group].Add(histo2)

        if dndm: convertToDNDM(histo[group])
        if group == 'data':
            applyDATAStyle(histo[group])
        else:
            applyStyle(histo[group], colors[group], 1, 1001)
        if group != 'data': hs.Add(histo[group])

    try:
        hMax = 1.2 * max(histo['data'].GetMaximum(), hs.GetMaximum())
    except KeyError:
        hMax = 1.2 * hs.GetMaximum()

    hs.SetMaximum(hMax)
    hs.Draw("HIST")
    try:
        histo['data'].Draw("e,SAME")
    except KeyError:
        pass

    if doRatio:
        hs.GetXaxis().SetLabelSize(0)
    else:
        if units != "":
            hs.GetXaxis().SetTitle(labelX + " [" + units + "]")
        else:
            hs.GetXaxis().SetTitle(labelX)

    hs.GetYaxis().SetTitle("Events")
    hs.GetYaxis().SetTitleOffset(1)

    if dndm: hs.GetYaxis().SetTitle("dN/d" + labelX)
    c.cd()
    if doRatio:
        data2 = histo['data'].Clone("data")
        mc = histo['Rare']
        mc.Add(histo['Reducible'])
        mc.Add(histo['ZZ4L'])
        xmin = mc.GetXaxis().GetXmin()
        xmax = mc.GetXaxis().GetXmax()
        line = TLine(xmin, 1.0, xmax, 1.0)
        line.SetLineWidth(1)
        line.SetLineColor(kBlack)

        ratioPad.Draw()
        ratioPad.cd()

        data2.Divide(data2, mc)

        data2.SetMarkerStyle(20)
        data2.SetTitleSize(0.12, "Y")
        data2.SetTitleOffset(0.40, "Y")
        data2.SetTitleSize(0.12, "X")
        data2.SetLabelSize(0.10, "X")
        data2.SetLabelSize(0.08, "Y")
        data2.GetYaxis().SetRangeUser(0.62, 1.38)
        data2.GetYaxis().SetNdivisions(305)
        data2.GetYaxis().SetTitle("Obs/Exp   ")

        if units != "":
            data2.GetXaxis().SetTitle(labelX + " [" + units + "]")
        else:
            data2.GetXaxis().SetTitle(labelX)

        data2.Draw("P")
        line.Draw()

    c.cd()
    plotPad.cd()

    l = TLegend(xR, 0.55, xR + 0.28, 0.9)
    for group in groups:
        try:
            l.AddEntry(histo[group], group, "F")
        except KeyError:
            continue

    l.SetBorderSize(0)
    l.SetFillColor(0)
    l.SetFillStyle(0)
    l.SetTextSize(0.04)
    l.Draw()

    lTex1 = TLatex(120., 0.97 * hMax, 'Preliminary {0:d}'.format(year))
    lTex1.SetTextSize(0.04)
    lTex1.Draw()
    signText = 'Same Sign'
    if sign == 'OS': signText = 'Opposite Sign'
    lTex2 = TLatex(120., 0.90 * hMax, '{0:s}'.format(signText))
    lTex2.SetTextSize(0.04)
    lTex2.Draw()
    if len(cat) == 4:
        lt = {
            'eeet': '#it{l}#it{l}#it{e}#tau',
            'eemt': '#it{l}#it{l}#mu#tau',
            'eett': '#it{l}#it{l}#tau#tau',
            'mmet': '#mu#mu#it{e}#tau',
            'mmmt': '#mu#mu#mu#tau',
            'mmtt': '#mu#mu#tau#tau'
        }
    else:
        lt = {
            'et': '#it{l}#it{l}#it{e}#tau',
            'mt': '#it{l}#it{l}#mu#tau',
            'tt': '#it{l}#it{l}#tau#tau'
        }
    lTex3 = TLatex(120., 0.83 * hMax,
                   '{0:s} H_LT > {1:d} '.format(lt[cat], int(LTcut)))
    lTex3.SetTextSize(0.04)
    lTex3.Draw()

    plotPad.Draw()
    #CMS_lumi(plotPad,4,11)

    outFileBase = "Stack_{0:d}_{1:s}_{2:s}_LT{3:02d}".format(
        year, cat, sign, int(LTcut))
    c.SaveAs("{0:s}.png".format(outFileBase))
    c.SaveAs("{0:s}.root".format(outFileBase))
    if wait == 'wait':
        raw_input()
    else:
        import time
        time.sleep(5.)
Example #28
0
def MakePlot(specWithCuts, specWithoutCuts, options):
    """
        Creating the final plot. The plot will be a two panel plot:
        1st panel shows the comparison of the spectra. 
        2nd panel shows the ratio of the normalised spectra with and 
            without pileup rejection (as without/with)
        """
    plot = TCanvas("ComparisonPileup",
                   "Comparison of raw spectra with/without pileup rejection",
                   1000, 500)
    plot.Divide(2, 1)

    specpad = plot.cd(1)
    specpad.SetGrid(False, False)
    specpad.SetLogx(True)
    specpad.SetLogy(True)

    axispec = TH1F("axispec",
                   "; p_{t} (GeV/c); 1/N_{ev} dN/dp_{t} ((GeV/c)^{-1})", 1000,
                   0., 100.)
    axispec.SetStats(False)
    axispec.GetYaxis().SetRangeUser(1e-10, 100)
    axispec.Draw("axis")
    gObjects.append(axispec)

    specWithCuts.SetMarkerColor(kRed)
    specWithCuts.SetLineColor(kRed)
    specWithCuts.SetMarkerStyle(24)
    specWithoutCuts.SetMarkerColor(kBlue)
    specWithoutCuts.SetLineColor(kBlue)
    specWithoutCuts.SetMarkerStyle(25)
    specWithCuts.Draw("epsame")
    specWithoutCuts.Draw("epsame")
    gObjects.append(specWithCuts)
    gObjects.append(specWithoutCuts)

    leg = TLegend(0.1, 0.15, 0.45, 0.3)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.045)
    leg.AddEntry(specWithCuts, "With standard cuts", "lep")
    leg.AddEntry(specWithoutCuts, "Without standard cuts", "lep")
    leg.Draw()
    gObjects.append(leg)

    label = TPaveText(0.5, 0.75, 0.89, 0.89, "NDC")
    label.SetBorderSize(0)
    label.SetFillStyle(0)
    label.SetTextFont(42)
    label.SetTextAlign(12)
    label.AddText("Trigger:          %s" % (options["Trigger"]))
    label.AddText("Pileup rejection: %s" % (options["pileupreject"]))
    label.Draw()
    gObjects.append(label)

    ratiopad = plot.cd(2)
    ratiopad.SetGrid(False, False)
    ratiopad.SetLogx(True)

    axirat = TH1F("axirat", "; p_{t} (GeV/c); Without/with standard cuts",
                  1000, 0., 100.)
    axirat.SetStats(False)
    axirat.GetYaxis().SetRangeUser(0., 100)
    axirat.Draw("axis")
    gObjects.append(axirat)

    ratiohist = deepcopy(specWithoutCuts)
    ratiohist.SetName("ratioPileup")
    ratiohist.Divide(ratiohist, specWithCuts, 1., 1., "b")
    ratiohist.SetMarkerColor(kBlack)
    ratiohist.SetLineColor(kBlack)
    ratiohist.SetMarkerStyle(20)
    ratiohist.Draw("epsame")
    gObjects.append(ratiohist)

    plot.cd()
    gObjects.append(plot)

    return plot
Example #29
0
### A temperature has a list of samples

### when parsing the data, for each sample, we find a T, and add the data to it. Then finally mesure the averge for the temperature
gr2 = getGraph(Ts2, '../data/BandGap_test1a/temprature_test_b3c2.dat')
gr1 = getGraph(Ts1, '../data/BandGap_test1a/temprature_test_b3c1.dat')

gr1.SetLineColor(2)
gr1.SetMarkerColor(2)
gr1.SetMarkerStyle(25)
gr2.SetLineColor(4)
gr2.SetMarkerColor(4)
gr2.SetMarkerStyle(24)

lg = TLegend(0.2, 0.8, 0.4, 0.9)
lg.SetFillStyle(0)
lg.SetBorderSize(0)
lg.AddEntry(gr1, "Chip #1", 'lp')
lg.AddEntry(gr2, "Chip #2", 'lp')

gStyle.SetOptStat(0)
gStyle.SetOptTitle(0)
gStyle.SetPadLeftMargin(0.16)
gStyle.SetPadRightMargin(0.05)
gStyle.SetPadTopMargin(0.05)
gStyle.SetPadBottomMargin(0.1)
h1 = TH2F('h2', 'h2;T [#circC];Output [V]', 100, -35, 85, 100, 1.116, 1.13)
h1.Draw()
gr2.Draw('P')
gr1.Draw('P')
lg.Draw()
Example #30
0
    def showENC(self):
        tree1 = TTree()
        header = 'idX/i:vL/F:vH:A:D/i:R:W'
        first = True
        for f in self.dataFiles:
            if first: tree1.ReadFile(f, header)
            else: tree1.ReadFile(f)

        p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', self.bins[0],
                      tree1.GetMinimum('vH-vL') * 0.8,
                      tree1.GetMaximum('vH-vL') * 1.2)
        tree1.Draw("D:(vH-vL)>>p1", "", "profE")

        ### change it to tgraph
        g1 = TGraphErrors()
        for i in range(p1.GetNbinsX() + 2):
            N = p1.GetBinEntries(i)
            if N > 0:
                print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(
                    i), p1.GetBinError(i)
                n = g1.GetN()
                g1.SetPoint(n,
                            p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i))
                g1.SetPointError(n, 0, p1.GetBinError(i))

        p1.Draw("axis")
        g1.Draw('Psame')

        fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))',
                   0.05, 0.3)
        fun1.SetParameter(0, 0.155)
        fun1.SetParameter(1, 0.005)

        g1.Fit(fun1)
        fun1a = g1.GetFunction('fun1')

        fun1a.SetLineColor(2)

        v0 = fun1a.GetParameter(0)
        e0 = fun1a.GetParError(0)
        v1 = fun1a.GetParameter(1)
        e1 = fun1a.GetParError(1)

        print v0, v1

        fUnit = 1000.
        self.lt.DrawLatexNDC(
            0.185, 0.89,
            '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit))
        self.lt.DrawLatexNDC(
            0.185, 0.84,
            '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit))
        if self.Info:
            self.lt.DrawLatexNDC(0.185, 0.6, self.Info)

        print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)
        fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1))
        fun2.SetLineColor(4)
        fun2.SetLineStyle(2)
        fun2.Draw('same')

        lg = TLegend(0.7, 0.4, 0.95, 0.5)
        lg.SetFillStyle(0)
        lg.AddEntry(p1, 'Measurement', 'p')
        lg.AddEntry(fun1a, 'Fit', 'l')
        lg.AddEntry(fun2, 'Gaus', 'l')
        lg.Draw()

        waitRootCmdX()