Exemplo n.º 1
0
def DivideTGraphErrors(num, denom, name):
    nPoints = num.GetN()
    nSkipPoints = 0  # count of when we can't divide
    newTGraph = TGraphErrors(nPoints)
    newTGraph.SetName(name)
    for i in range(nPoints):
        x = num.GetX()[i]
        x_err = num.GetEX()[i]
        y1 = num.GetY()[i]
        y2 = denom.GetY()[i]
        y = 0.0
        y_err = 0.0
        if ((y1 != 0) and (y2 != 0)):
            # technically could make this work for y1 = 0
            y = y1 / y2
            y1_err = num.GetEY()[i]
            y2_err = denom.GetEY()[i]
            y_err = y * math.sqrt(
                math.pow(y1_err / y1, 2) + math.pow(y2_err / y2, 2))
            newTGraph.SetPoint(i - nSkipPoints, x, y)
            newTGraph.SetPointError(i - nSkipPoints, x_err, y_err)
        else:
            newTGraph.RemovePoint(i - nSkipPoints)
            nSkipPoints += 1
    newTGraph.SetLineColor(num.GetLineColor())
    newTGraph.SetMarkerColor(num.GetMarkerColor())
    newTGraph.SetMarkerStyle(num.GetMarkerStyle())

    return newTGraph
Exemplo n.º 2
0
def make_tgrapherrors(name,
                      title,
                      color=1,
                      marker=20,
                      marker_size=1,
                      width=1,
                      asym_err=False,
                      style=1,
                      x=None,
                      y=None):
    if (x and y) is None:
        gr = TGraphErrors() if not asym_err else TGraphAsymmErrors()
    else:
        gr = TGraphErrors(len(x), array(x, 'd'), array(
            y, 'd')) if not asym_err else TGraphAsymmErrors(
                len(x), array(x, 'd'), array(y), 'd')
    gr.SetTitle(title)
    gr.SetName(name)
    gr.SetMarkerStyle(marker)
    gr.SetMarkerColor(color)
    gr.SetLineColor(color)
    gr.SetMarkerSize(marker_size)
    gr.SetLineWidth(width)
    gr.SetLineStyle(style)
    return gr
Exemplo n.º 3
0
def load_cck():

    #model by Guillermo at. al.
    f = open("data/data-dtdy-y_0-RHIC-clean_CCK.dat", "read")
    sigma = []
    for line in f:
        if line[0] == "#": continue
        p = line.split("\t")
        t = float(p[3])
        nucl = float(p[4])
        hs = float(p[8])
        sigma.append({"t": t, "nucl": nucl, "hs": hs})

    #correction from gamma-Au to AuAu by Michal
    k_auau = 9.0296

    #scaling to XnXn
    kx = 0.1702

    gCCK = TGraphErrors(len(sigma))
    for i in xrange(len(sigma)):
        gCCK.SetPoint(i, sigma[i]["t"], sigma[i]["hs"] * k_auau * kx)

    gCCK.SetLineColor(rt.kRed)
    gCCK.SetLineWidth(3)
    gCCK.SetLineStyle(rt.kDashed)  # 9

    return gCCK
Exemplo n.º 4
0
def testIthr():
    lines = get_lines('DAC_scan_ithr_0x40to0xf0.dat')

    gr1 = TGraphErrors()
    gr2 = TGraphErrors()

    fUnit = 1000. / 0.7
    yUnit = 'e^{-}'

    for line in lines:
        if len(line) == 0: continue
        if line[0] in ['#', '\n']: continue
        fs = line.rstrip().split()

        ix = int(fs[0])
        gr1.SetPoint(ix, float(fs[1]), float(fs[2]) * fUnit)
        gr1.SetPointError(ix, 0, float(fs[3]) * fUnit)
        gr2.SetPoint(ix, float(fs[1]), float(fs[4]) * fUnit)
        gr2.SetPointError(ix, 0, float(fs[5]) * fUnit)

    useAtlasStyle()
    gStyle.SetMarkerStyle(20)

    gr1.SetMarkerStyle(20)
    gr1.Draw('AP')
    h1 = gr1.GetHistogram()
    h1.GetYaxis().SetTitle("Threshold [" + yUnit + "]")
    h1.GetXaxis().SetTitle("I_{Thre} code")
    # h1.GetYaxis().SetRangeUser(0,0.2)

    gPad.SetTicks(1, 0)
    gPad.SetRightMargin(0.16)

    y1b = 0
    y2b = 15
    x1 = h1.GetXaxis().GetXmax()
    y1 = h1.GetYaxis().GetXmin()
    y2 = h1.GetYaxis().GetXmax()
    raxis = TGaxis(x1, y1, x1, y2, y1b, y2b, 506, "+L")
    raxis.SetLineColor(2)
    raxis.SetLabelColor(2)
    raxis.SetTitleColor(2)
    raxis.SetTitle("ENC [" + yUnit + "]")
    raxis.Draw()

    nP = gr2.GetN()
    Ys = gr2.GetY()
    EYs = gr2.GetEY()
    Y = array(
        'd', [y1 + (y2 - y1) / (y2b - y1b) * (Ys[i] - y1b) for i in range(nP)])
    EY = array('d', [(y2 - y1) / (y2b - y1b) * EYs[i] for i in range(nP)])
    gr2x = TGraphErrors(nP, gr2.GetX(), Y, gr2.GetEX(), EY)
    gr2x.SetMarkerStyle(24)
    gr2x.SetLineColor(2)
    gr2x.SetMarkerColor(2)

    gr2x.Draw('Psame')

    waitRootCmdX()
class GraphicsObject:
    def __init__(self, data, name):
        self._data = data
        self._graphics = None
        self._style = Style(kBlack, 20)
        self._plotrange = {"Min": None, "Max": None}
        self._name = name

    def SetPlotRange(self, min, max):
        self._plotrange[min] = min
        self._plotrange[max] = max

    def SetStyle(self, style):
        self._style = style

    def SetName(self, name):
        self._name = name

    def GetData(self):
        return self._data

    def GetGraphics(self):
        return self._graphics

    def GetStyle(self):
        return self._style

    def Draw(self):
        if not self._graphics:
            self._graphics = TGraphErrors()
            np = 0
            for bin in range(1, self._data.GetXaxis().GetNbins() + 1):
                if self._plotrange["Min"] and self._data.GetXaxis(
                ).GetBinLowEdge(bin) < self._plotrange["Min"]:
                    continue
                if self._plotrange["Max"] and self._data.GetXaxis(
                ).GetBinUpEdge(bin) > self._plotrange["Max"]:
                    break
                self._graphics.SetPoint(
                    np,
                    self._data.GetXaxis().GetBinCenter(bin),
                    self._data.GetBinContent(bin))
                self._graphics.SetPointError(
                    np,
                    self._data.GetXaxis().GetBinWidth(bin) / 2.,
                    self._data.GetBinError(bin))
                np = np + 1
        self._graphics.SetMarkerColor(self._style.GetColor())
        self._graphics.SetLineColor(self._style.GetColor())
        self._graphics.SetMarkerStyle(self._style.GetMarker())
        self._graphics.Draw("epsame")

    def AddToLegend(self, legend, title=None):
        if self._graphics:
            tit = self._name
            if title:
                tit = title
            legend.AddEntry(self._graphics, tit, "lep")
Exemplo n.º 6
0
def GetData(file, scale=1., sed=True, title='SED', barUL=True):
    GetData.Ng += 1
    g = TGraphErrors(file)
    gUL = TGraphErrors()

    if sed:
        for i in range(g.GetN()):
            g.GetY()[i] = pow(g.GetX()[i], 2) * g.GetY()[i] * 1e-6 / scale
            g.GetEY()[i] = pow(g.GetX()[i], 2) * g.GetEY()[i] * 1e-6 / scale
            g.GetX()[i] *= 1e-3

    idel = 0
    nUL = 0
    while idel < g.GetN():
        if g.GetEY()[idel] < 0:
            gUL.SetPoint(nUL, g.GetX()[idel], g.GetY()[idel])
            if barUL:
                gUL.SetPointError(nUL, 0, g.GetY()[idel] * 1e-5)
            nUL += 1
            g.RemovePoint(idel)
        else:
            idel += 1

    if sed:
        g.SetTitle(title + ";Energy [GeV];E^{2}dN/dE [TeV cm^{-2} s^{-1}]")
    else:
        g.SetTitle(title + ";Energy [MeV];dN/dE [cm^{-2} s^{-1} MeV^{-1}]")

    g.SetLineColor(kRed)
    g.SetMarkerColor(kRed)
    g.SetMarkerStyle(20)
    g.SetName("g%d" % GetData.Ng)
    gUL.SetLineColor(g.GetLineColor())
    gUL.SetName("gUL%d" % GetData.Ng)

    return g, gUL
Exemplo n.º 7
0
def Plot2DHist( th2, slope, offset, x_points, y_points, error_points, outname, xlabel='',
            etBinIdx=None, etaBinIdx=None, etBins=None,etaBins=None):

    from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack,TLine,kBird, kOrange,kGray
    from ROOT import TGraphErrors,TF1,TColor
    import array

    def AddTopLabels(can, etlist = None, etalist = None, etidx = None, etaidx = None, logger=None):

        extraText = [GetAtlasInternalText()]
        if etlist and etidx is not None:
            etlist=copy(etlist)
            if etlist[-1]>9999:  etlist[-1]='#infty'
            binEt = (str(etlist[etidx]) + ' < E_{T} [GeV] < ' + str(etlist[etidx+1]) if etidx+1 < len(etlist) else
                                     'E_{T} > ' + str(etlist[etidx]) + ' GeV')
            extraText.append(binEt)
        if etalist and etaidx is not None:
            binEta = (str(etalist[etaidx]) + ' < #eta < ' + str(etalist[etaidx+1]) if etaidx+1 < len(etalist) else
                                        str(etalist[etaidx]) + ' < #eta < 2.47')
            extraText.append(binEta)
        DrawText(can,extraText,.14,.68,.35,.93,totalentries=4)

    gStyle.SetPalette(kBird)
    drawopt='lpE2'
    canvas = TCanvas('canvas','canvas',500, 500)
    canvas.SetRightMargin(0.15)
    th2.GetXaxis().SetTitle('Neural Network output (Discriminant)')
    th2.GetYaxis().SetTitle(xlabel)
    th2.GetZaxis().SetTitle('Count')
    th2.Draw('colz')
    canvas.SetLogz()
    g = TGraphErrors(len(x_points), array.array('d',x_points), array.array('d',y_points), array.array('d',error_points), array.array('d',[0]*len(x_points)))
    g.SetLineWidth(1)
    g.SetLineColor(kBlue)
    g.SetMarkerColor(kBlue)
    g.Draw("P same")
    line = TLine(slope*th2.GetYaxis().GetXmin()+offset,th2.GetYaxis().GetXmin(), slope*th2.GetYaxis().GetXmax()+offset, th2.GetYaxis().GetXmax())
    line.SetLineColor(kBlack)
    line.SetLineWidth(2)
    line.Draw()
    AddTopLabels( canvas, etlist=etBins,etalist=etaBins,etidx=etBinIdx,etaidx=etaBinIdx)
    FormatCanvasAxes(canvas, XLabelSize=16, YLabelSize=16, XTitleOffset=0.87, ZLabelSize=14,ZTitleSize=14, YTitleOffset=0.87, ZTitleOffset=1.1)
    SetAxisLabels(canvas,'Neural Network output (Discriminant)',xlabel)
    canvas.SaveAs(outname+'.pdf')
    canvas.SaveAs(outname+'.C')
    return outname+'.pdf'
def graphTruth():
    fname = "PionMinusG4.txt"
    kineticEnergy = []
    crossSec = []
    crossSec_el = []
    crossSec_inel = []
    zero = []

    title = ""
    with open(fname) as f:
        for fLine in f.readlines():
            w = fLine.split()
            if is_number(w[0]):
                runIn = int(w[0])
                ke = float(w[1])
                xstot = float(w[4])
                kineticEnergy.append(ke)
                crossSec.append(xstot)
                zero.append(0.)
            else:
                if "for" not in fLine:
                    continue
                title = fLine[9:]

    #define some data points . . .
    x = array('f', kineticEnergy)
    y = array('f', crossSec)
    y_el = array('f', crossSec_el)
    y_inel = array('f', crossSec_inel)
    exl = array('f', zero)
    exr = array('f', zero)

    nPoints = len(x)
    # . . . and hand over to TGraphErros object
    gr = TGraphErrors(nPoints, x, y, exl, exr)
    gr.SetTitle(title + "; Kinetic Energy [MeV]; Cross Section [barn]")
    gr.GetXaxis().SetRangeUser(0, 1000)
    gr.GetYaxis().SetRangeUser(0, 2.)
    gr.SetLineWidth(2)
    gr.SetLineColor(kGreen - 2)
    gr.SetFillColor(0)
    return gr
Exemplo n.º 9
0
def load_sartre():

    sartre = TFile.Open(
        "/home/jaroslav/sim/sartre_tx/sartre_AuAu_200GeV_Jpsi_coh_2p7Mevt.root"
    )
    sartre_tree = sartre.Get("sartre_tree")

    hSartre = ut.prepare_TH1D("hSartre", 0.002, 0., 0.12)
    sartre_tree.Draw("-tval >> hSartre", "rapidity>-1 && rapidity<1")

    ut.norm_to_integral(hSartre, 0.025)  # now same as Starlight

    gSartre = TGraphErrors(hSartre.GetNbinsX())
    for ibin in xrange(1, hSartre.GetNbinsX() + 1):
        gSartre.SetPoint(ibin - 1, hSartre.GetBinCenter(ibin),
                         hSartre.GetBinContent(ibin))

    gSartre.SetLineColor(rt.kYellow + 1)
    gSartre.SetLineWidth(3)
    #gSartre.SetLineStyle(rt.kDashDotted)

    return gSartre
Exemplo n.º 10
0
def load_ms():

    #model by Heikki and Bjorn
    f = open("data/to_star_ms.txt", "read")
    t_sigma = []
    for line in f:
        if line[0] == "#": continue
        point = line.split(" ")
        t_sigma.append([float(point[0]), float(point[1])])

    #scaling to XnXn
    kx = 0.1702

    gMS = TGraphErrors(len(t_sigma))
    for i in xrange(len(t_sigma)):
        gMS.SetPoint(i, t_sigma[i][0], t_sigma[i][1] * kx)

    gMS.SetLineColor(rt.kViolet)
    gMS.SetLineWidth(3)
    gMS.SetLineStyle(rt.kDashDotted)  # kDashed

    return gMS
Exemplo n.º 11
0
def MeasurePSF_in_Sections(data, fitted_line, nsecs = 3, tgraph_filename = '', DEBUG = False, DEBUG_Filenum = 0):
    #get new coefficients as distance to line uses straight line of form ax + by + c = 0
    a = -1. * fitted_line.a
    b = 1
    c = -1. * fitted_line.b
    
    histmin = -1 * max(data.shape[0], data.shape[1])
    histmax = max(data.shape[0], data.shape[1])
    nbins = (histmax - histmin) * 2
    
    hists = []
    for i in range(nsecs):
       hists.append(TH1F('Track section ' + str(i), 'Track section ' + str(i), nbins, histmin, histmax))
    
    for xcoord in range(data.shape[0]):
        for ycoord in range(data.shape[1]):
            x = xcoord + 0.5 #adjust for bin centers - NB This is important!
            y = ycoord + 0.5 #adjust for bin centers - NB This is important!
            secnum = GetSecNum(data, x, y, nsecs, None) # TODO!
            
            value = float(data[xcoord,ycoord])
#            if value < 800:
            non_abs_distance = (a*x + b*y + c) / (a**2 + b**2)**0.5
            hists[secnum].Fill(non_abs_distance, value)
        
    sigmas, sigma_errors = [], []
            
    for i, hist in enumerate(hists):
        fitmin, fitmax = GetLastBinAboveX(hist, 0.1)
#        viewmin, viewmax = GetLastBinAboveX(hist, 0.1)
        viewmin, viewmax = -2,2
        hist.GetXaxis().SetRangeUser(viewmin,viewmax)
    
        fit_func = TF1("gaus", "gaus", fitmin, fitmax)
        fit_func.SetNpx(1000)
        hist.Fit(fit_func, "MEQ", "", fitmin, fitmax)
        
        legend_text = []
        
        sigma = fit_func.GetParameter(2) 
        sigma_error = fit_func.GetParError(2)
        
        sigmas.append(abs(15*sigma)) #15 for the 15um per pixel
        sigma_errors.append(abs(15*sigma_error)) #15 for the 15um per pixel
        
        mean = fit_func.GetParameter(15*1) #15 for the 15um per pixel
        mean_error = fit_func.GetParError(15*1) #10 for the 15um per pixel
        
        chisq = fit_func.GetChisquare()
        NDF = fit_func.GetNDF()
        try:
            chisqr_over_NDF = chisq/NDF
        except:
            chisqr_over_NDF = -1  
#        if chisqr_over_NDF > 500 or chisqr_over_NDF <= 1:
#            return [], [], []
        
        legend_text.append('mean = ' + str(mean) + ' #pm ' + str(mean_error) + " #mum")
        legend_text.append('#sigma = ' + str(round(sigma,4)) + ' #pm ' + str(round(sigma_error,4)) + " #mum")
    
        if DEBUG: #For showing each of n PSF *Histograms* per track
            c1 = TCanvas( 'canvas', 'canvas', CANVAS_WIDTH,CANVAS_HEIGHT)
            hist.Draw("")
            if legend_text != '':
                from ROOT import TPaveText
                textbox = TPaveText(0.0,1.0,0.2,0.8,"NDC")
                for line in legend_text:
                    textbox.AddText(line)
                textbox.SetFillColor(0)
                textbox.Draw("same")
            c1.SaveAs(OUTPUT_PATH + str(DEBUG_Filenum) + "psf_section_" + str(i) + FILE_TYPE)
            del c1

    from ROOT import TGraphErrors
    c2 = TCanvas( 'canvas', 'canvas', CANVAS_WIDTH,CANVAS_HEIGHT)
    assert nsecs == len(sigmas) == len(sigma_errors)
    xpoints = GenXPoints(nsecs, 250.)
    
    gr = TGraphErrors(nsecs, np.asarray(xpoints,dtype = float), np.asarray(sigmas,dtype = float), np.asarray([0 for i in range(nsecs)],dtype = float), np.asarray(sigma_errors,dtype = float)) #populate graph with data points
    gr.SetLineColor(2)
    gr.SetMarkerColor(2)
    gr.Draw("AP")
    
    fit_func = TF1("line","[1]*x + [0]", -1, nsecs+1)
    fit_func.SetNpx(1000)
    gr.Fit(fit_func, "MEQ", "")
    a = fit_func.GetParameter(1) 
    a_error = fit_func.GetParError(1)
    
    if DEBUG:
        if tgraph_filename == '': tgraph_filename = OUTPUT_PATH + 'psf_graph' + '.png'
        gr.SetTitle("")
        gr.GetYaxis().SetTitle('PSF #sigma (#mum)')
        gr.GetXaxis().SetTitle('Av. Si Depth (#mum)')
        c2.SaveAs(tgraph_filename)
        
#    if a_error >= a:
#        print "Inconclusive muon directionality - skipped track %s"%tgraph_filename
#        return [],[],[]

    del c2, hists, gr
    import gc
    gc.collect()
                   
    for j in range(nsecs):
        if sigma_errors[j] > sigmas[j]:
            print "bad fit skipped"
            return [],[],[]
    
    if a < 0:
        sigmas.reverse()
        sigma_errors.reverse()
        return xpoints, sigmas, sigma_errors
    else:
        return xpoints, sigmas, sigma_errors
Exemplo n.º 12
0
def plot_2(var,cuts):
    for s in attr:
        c1 = TCanvas("c1", "Signals", 1200, 800)

        if log_y == 1: 
            c1.SetLogy()

        c1.SetTopMargin(0.08)#0.12
        c1.SetBottomMargin(0.11)#0.12
        c1.SetLeftMargin(0.14)
        c1.SetRightMargin(0.14)#0.24
        c1.cd()
        #c1.SetGrid()
        gStyle.SetTitleFontSize(0.04)
        if ct_dep == 0:
            if s in ('elf','muf','cm','nm','chm'): 
                c1.SetLogx()
            for cc in channel:
                #hist[cc][s].SetMaximum(0.44)
                if   'combind' in cc:     
                    fc = 30
                    #hist[cc][s].SetFillStyle()#3005)
                elif 'VBF'      in cc:   
                    fc = 38    
                    hist[cc][s].SetFillStyle(3444)
                elif 'HT50'     in cc:  
                    fc = 7
                    hist[cc][s].SetFillStyle(3001)                  
                elif 'HT100'    in cc: 
                    fc = 4
                    hist[cc][s].SetFillStyle(3002) 
                elif 'HT200'    in cc: 
                    fc = 6
                    hist[cc][s].SetFillStyle(3003) 
                elif 'HT300'    in cc: 
                    fc = 9
                    hist[cc][s].SetFillStyle(3004) 
                
                if histFillColOn == 1:
                    pass
                    #hist[cc][s].SetFillColor(fc) 
                
                hist[cc][s].Draw(histStyl) 
            #legend = TLegend(0.76, 0.56, 0.99, 0.88)
            legend = TLegend(0.60, 0.9-0.04*2, 0.85, 0.9) #x_left y_bottom x_right y_top
            legend.SetBorderSize(0)
            legend.SetFillStyle(0)#1001
            legend.SetFillColor(0)
            #legend.SetHeader( entry['entries'] )
            for cc in channel:
                legend.AddEntry(hist[cc][s],cc)
            legend.Draw()
            for ct in cut_text:
                cut_text[ct].Draw()
            
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Line for critical value
            if   s == 'chm':
                l = TLine(11.4,0.0,11.4,0.084) 
            elif s == 'cHadEFrac':
                l = TLine(0.38,0.0,0.38,0.027)
            elif s == 'FracCal':
                l = TLine(30,0.0,30,0.44)
            #l.SetLineColor(2)
            #l.SetLineWidth(3)
            if critical_line == 1: 
                l.SetLineColor(46)#4,2
                l.SetLineWidth(3)
                l.Draw('same')

            c1.Print(path1 + s + var + cuts.replace('(','_').replace(')','_').replace('&&','_').replace('>','LG').replace('<','LS').replace('=','EQ').replace('.','P').replace('-','N').replace('Jet','J').replace('GenBquark','GBQ') + ".pdf")
            
        elif ct_dep == 1:
            eac0 = str( entries_after_cut['ct0'][s] )
            c1.SetLogx()
            #gr = TGraph( len_of_lt , x , yy['sgn'][s] )
            gr = TGraphErrors( len_of_lt , x , yy['sgn'][s] , ex , ey['sgn'][s] )
            gr.SetMarkerSize(1.5)
            gr.SetMarkerStyle(1)
            gr.GetYaxis().SetTitleOffset(1.6)
            gr.SetLineColor(4)
            gr.SetLineWidth(4)
            gr.SetTitle('mean ' + s )
            gr.GetXaxis().SetTitle('decaying length (mm)')
            gr.GetYaxis().SetTitle('mean normalized number of events')
            gr.GetXaxis().SetTitleOffset(1.4)
            gr.SetMaximum( plotrange[s] * 1.12 )
            gr.SetName('sgn')
            gr.Draw('ACP')  # '' sets up the scattering style
            gr1 = TGraphErrors( len_of_lt , x , yy['QCD'][s] , ex , ey['QCD'][s] )
            gr1.SetMarkerSize(1.0)
            gr1.SetMarkerStyle(1)
            gr.GetYaxis().SetTitleOffset(1.6)
            gr1.SetLineColor(2)
            gr1.SetLineWidth(2)
            gr1.SetName('QCD')
            #gr1.SetTitle('averaged ' + s)
            #gr1.GetXaxis().SetTitle('decaying length (mm)')
            #gr1.GetYaxis().SetTitle('mean frequency')
            gr1.Draw('CP')  # '' sets up the scattering style
            legend = TLegend(0.76, 0.56, 0.99, 0.88)
            legend.SetHeader( 'Entries: ' + eac0 )
            legend.AddEntry('QCD', legendb, 'l')
            legend.AddEntry('sgn', legends, 'l')
            legend.Draw()
            for ct in cut_text:
                cut_text[ct].Draw()
            c1.Print(path1 + 'mean_' + s + var + cuts.replace('(','_').replace(')','_').replace('&&','_').replace('>','LG').replace('<','LS').replace('=','EQ').replace('.','P').replace('-','N').replace('Jet','J').replace('GenBquark','GBQ') + ".pdf")
        c1.Update()
        c1.Close() 
        print('|||||||||||||||||||||||||||||||||||||||||||||||||||')        
Exemplo n.º 13
0
err5s = array( 'f', [0.251, 0.172, 0.153, 0.142, 0.155, 0.156, 0.253, 0.273, 0.259, 0.267, 0.343, 0.287, 0.248, 0.251, 0.255, 0.154, 0.148, 0.150, 0.148, 0.182, 0.239])
err5 = array( 'f', [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ,0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
#40x40
Arr6 = array( 'f', [-2.0, -1.8, -1.6, -1.4, -1.2, -1.0, -0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0])
det6s = array( 'f', [3.002, 6.100, 6.024, 6.364, 6.701, 6.940, 7.706, 7.920, 8.293, 10.141, 11.660, 10.456, 8.198, 7.676, 7.642, 6.966, 6.677, 6.378, 6.243, 6.122, 3.024])
err6s = array( 'f', [0.102, 0.070, 0.073, 0.088, 0.078, 0.076, 0.080, 0.081, 0.100, 0.155, 0.189, 0.180, 0.107, 0.101, 0.086, 0.083, 0.076, 0.080, 0.075, 0.080, 0.110])
err6 = array( 'f', [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ,0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
n4s = 21
nxs = 33
n2s = 21
c1 = TCanvas( 'c1', 'Y', 200, 10, 1400, 1000 )

g1s = TGraphErrors(nxs, Arr1, det1s, err1, err1s)
g1s.SetTitle( 'Y=0 Detected PE' )
g1s.SetMarkerColor( 4 )
g1s.SetLineColor( 4 )
g1s.SetMarkerStyle( 21 )
g1s.Draw('APC')
g1s.GetYaxis().SetRangeUser(0,45)
g1s.GetYaxis().SetTitle("Hits [PE]")
g1s.GetXaxis().SetTitle("X [cm]")
g2xs = TGraphErrors(nxs, Arr2x, det2xs, err2x, err2xs)
g2xs.SetTitle( 'Y=0 Detected PE' )
g2xs.SetMarkerColor( 9 )
g2xs.SetLineColor( 9 )
g2xs.SetMarkerStyle( 5 )
g2xs.Draw('PC SAME')
#c1.Print("xs.png")
#c2 = TCanvas( 'c1', 'Y', 200, 10, 700, 500 )
'''
g2s = TGraphErrors(nxs, Arr2, det2s, err2, err2s)
Exemplo n.º 14
0
jetToMETTriggerRate.SetPointError(3, 5, 9161739)
jetToMETTriggerRate.SetPointError(4, 5, 2492531)
jetToMETTriggerRate.SetPointError(5, 5, 592722)
jetToMETTriggerRate.SetPointError(6, 5, 304389)
jetToMETTriggerRate.SetPointError(7, 5, 193864)
jetToMETTriggerRate.SetPointError(8, 5, 176138)
jetToMETTriggerRate.SetPointError(9, 5, 120598)
jetToMETTriggerRate.SetPointError(10, 5, 91404)
jetToMETTriggerRate.SetPointError(11, 5, 75712)
jetToMETTriggerRate.SetPointError(12, 5, 58571)
jetToMETTriggerRate.SetPointError(13, 5, 45729)
jetToMETTriggerRate.SetPointError(14, 5, 39702)

jetToMETTriggerRate.Draw("AP")
jetToMETTriggerRate.SetMarkerColor(4)
jetToMETTriggerRate.SetLineColor(1)
jetToMETTriggerRate.SetMarkerStyle(21)
text.Draw()
canvas.Update()
canvas.Print("jetToMETTriggerRate.svg", "svg")
canvas.Print("jetToMETTriggerRate.png", "png")
canvas.Print("jetToMETTriggerRate.pdf", "pdf")

print "Retrieving efficiency vs MET plot"
print "Building efficiency vs rate plots"

canvas.SetLogx(0)
canvas.SetLogy(0)
text.SetX1NDC(0.5)
text.SetX2NDC(0.9)
metTriggerEfficiency_ff_H_WW_enuenu_1000events = DelphesSim_ff_H_WW_enuenu_1000events_efficiency_file.Get("metTriggerEfficiency_errors")
Exemplo n.º 15
0
    _NumberOfProtonsErr.append(0.0)

canvas1 = TCanvas('c1', "mycanvas", 200, 10, 700, 500)

effGraph = TGraphErrors(len(_NumberOfProtons), _NumberOfProtons, _Efficiency,
                        _NumberOfProtonsErr, _EfficiencyErr)
effGraph.SetMarkerStyle(2)
effGraph.SetMarkerSize(2)
effGraph.GetXaxis().SetTitle("Mean N Proton")
effGraph.GetYaxis().SetTitle("Efficiency/Purity (%)")
effGraph.SetTitle("Efficiency")

purGraph = TGraphErrors(len(_NumberOfProtons), _NumberOfProtons, _Purity,
                        _NumberOfProtonsErr, _PurityErr)
purGraph.SetMarkerStyle(5)
purGraph.SetLineColor(2)
purGraph.SetMarkerColor(2)
purGraph.SetMarkerSize(2)
purGraph.GetXaxis().SetTitle("Mean N Proton")
purGraph.GetYaxis().SetTitle("Purity")
purGraph.SetTitle("Purity")
MyFile = TFile(
    "effVsPurity_bs" + (str)(beamSpread) + "mrad_geo" + geoName +
    "_RestrictTracks" + (str)(restrictNTracks) + "_pitch" + (str)(pitch) +
    ".root", "RECREATE")

mg = TMultiGraph()
mg.SetTitle("Efficiency and Purity vs nProtons;Mean N Protons; (%)")
mg.Add(effGraph, "lp")
mg.Add(purGraph, "lp")
mg.Draw("a")
Exemplo n.º 16
0
    linFunc = TF1('linFunc', '[0]+[1]*x', 0.0, 0.5)
    linFunc.SetParameters(0.0, 1.0)

    for i in range(rawfitresultList.GetSize()):
        #tageffValVList[i] = rawfitresultList.At(i).getValV();
        #tageffErrorList[i] = rawfitresultList.At(i).getError();
        #etaAvgValList[i] = etaAvgValVarList.At(i).getValV();
        #etaAvgErrorList[i] = etaAvgValVarList.At(i).getError();
        tageffVsEtaGraph.SetPoint(i,
                                  etaAvgValVarList.At(i).getValV(),
                                  rawfitresultList.At(i).getValV())
        tageffVsEtaGraph.SetPointError(i,
                                       etaAvgValVarList.At(i).getError(),
                                       rawfitresultList.At(i).getError())
        tageffVsEtaGraph.SetLineColor(currentColor)
        linFunc.SetLineColor(currentColor)
        tageffVsEtaGraph.Fit(linFunc)

    graphHolder.Add(tageffVsEtaGraph)
    currentColor += 1

    #tageffVsEtaGraph = TGraph(rawfitresultList.GetSize(),etaAvgValList,tageffValVList)#,etaAvgErrorList,tageffErrorList);

    #tageffVsEtaGraph.
    #ROOT.gSystem.ProcessEvents();
    #img.FromPad(theCanvas);

os.chdir("..")

theCanvas = TCanvas()
Exemplo n.º 17
0
    gnorm.SetMarkerColor(1)
    gnorm.SetMaximum(0)
    inorm = TGraphErrors()
    inorm.SetMarkerStyle(24)
    fnorm = TF1("fnorm", "pol9", 700, 3000) 
    fnorm.SetLineColor(920)
    fnorm.SetLineStyle(7)
    fnorm.SetFillColor(2)
    fnorm.SetLineColor(cColor)

    # Mean
    gmean = TGraphErrors()
    gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)")
    gmean.SetMarkerStyle(20)
    gmean.SetMarkerColor(cColor)
    gmean.SetLineColor(cColor)
    imean = TGraphErrors()
    imean.SetMarkerStyle(24)
    fmean = TF1("fmean", "pol1", 0, 10000)
    fmean.SetLineColor(2)
    fmean.SetFillColor(2)

    # Width
    gsigma = TGraphErrors()
    gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)")
    gsigma.SetMarkerStyle(20)
    gsigma.SetMarkerColor(cColor)
    gsigma.SetLineColor(cColor)
    isigma = TGraphErrors()
    isigma.SetMarkerStyle(24)
    fsigma = TF1("fsigma", "pol1", 0, 10000)
Exemplo n.º 18
0
def signal(category):

    interPar = True
    n = len(genPoints)

    cColor = color[category] if category in color else 4
    nBtag = category.count('b')
    isAH = False  #relict from using Alberto's more complex script

    if not os.path.exists(PLOTDIR + "MC_signal_" + YEAR):
        os.makedirs(PLOTDIR + "MC_signal_" + YEAR)

    #*******************************************************#
    #                                                       #
    #              Variables and selections                 #
    #                                                       #
    #*******************************************************#

    X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV")
    j1_pt = RooRealVar("jpt_1", "jet1 pt", 0., 13000., "GeV")
    jj_deltaEta = RooRealVar("jj_deltaEta_widejet", "", 0., 5.)
    jbtag_WP_1 = RooRealVar("jbtag_WP_1", "", -1., 4.)
    jbtag_WP_2 = RooRealVar("jbtag_WP_2", "", -1., 4.)
    fatjetmass_1 = RooRealVar("fatjetmass_1", "", -1., 2500.)
    fatjetmass_2 = RooRealVar("fatjetmass_2", "", -1., 2500.)
    jid_1 = RooRealVar("jid_1", "j1 ID", -1., 8.)
    jid_2 = RooRealVar("jid_2", "j2 ID", -1., 8.)
    jnmuons_1 = RooRealVar("jnmuons_1", "j1 n_{#mu}", -1., 8.)
    jnmuons_2 = RooRealVar("jnmuons_2", "j2 n_{#mu}", -1., 8.)
    jnmuons_loose_1 = RooRealVar("jnmuons_loose_1", "jnmuons_loose_1", -1., 8.)
    jnmuons_loose_2 = RooRealVar("jnmuons_loose_2", "jnmuons_loose_2", -1., 8.)
    nmuons = RooRealVar("nmuons", "n_{#mu}", -1., 10.)
    nelectrons = RooRealVar("nelectrons", "n_{e}", -1., 10.)
    HLT_AK8PFJet500 = RooRealVar("HLT_AK8PFJet500", "", -1., 1.)
    HLT_PFJet500 = RooRealVar("HLT_PFJet500", "", -1., 1.)
    HLT_CaloJet500_NoJetID = RooRealVar("HLT_CaloJet500_NoJetID", "", -1., 1.)
    HLT_PFHT900 = RooRealVar("HLT_PFHT900", "", -1., 1.)
    HLT_AK8PFJet550 = RooRealVar("HLT_AK8PFJet550", "", -1., 1.)
    HLT_PFJet550 = RooRealVar("HLT_PFJet550", "", -1., 1.)
    HLT_CaloJet550_NoJetID = RooRealVar("HLT_CaloJet550_NoJetID", "", -1., 1.)
    HLT_PFHT1050 = RooRealVar("HLT_PFHT1050", "", -1., 1.)
    #HLT_DoublePFJets100_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets100_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1. )
    #HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1. )
    #HLT_DoublePFJets200_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets200_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets350_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets350_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets40_CaloBTagDeepCSV_p71                  =RooRealVar("HLT_DoublePFJets40_CaloBTagDeepCSV_p71"                 , "", -1., 1. )

    weight = RooRealVar("eventWeightLumi", "", -1.e9, 1.e9)

    # Define the RooArgSet which will include all the variables defined before
    # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add'
    variables = RooArgSet(X_mass)
    variables.add(
        RooArgSet(j1_pt, jj_deltaEta, jbtag_WP_1, jbtag_WP_2, fatjetmass_1,
                  fatjetmass_2, jnmuons_1, jnmuons_2, weight))
    variables.add(
        RooArgSet(nmuons, nelectrons, jid_1, jid_2, jnmuons_loose_1,
                  jnmuons_loose_2))
    variables.add(
        RooArgSet(HLT_AK8PFJet500, HLT_PFJet500, HLT_CaloJet500_NoJetID,
                  HLT_PFHT900, HLT_AK8PFJet550, HLT_PFJet550,
                  HLT_CaloJet550_NoJetID, HLT_PFHT1050))
    #variables.add(RooArgSet(HLT_DoublePFJets100_CaloBTagDeepCSV_p71, HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71, HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71, HLT_DoublePFJets200_CaloBTagDeepCSV_p71, HLT_DoublePFJets350_CaloBTagDeepCSV_p71, HLT_DoublePFJets40_CaloBTagDeepCSV_p71))
    X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_integration_range", X_mass.getMin(), X_mass.getMax())

    if VARBINS:
        binsXmass = RooBinning(len(abins) - 1, abins)
        X_mass.setBinning(binsXmass)
        plot_binning = RooBinning(
            int((X_mass.getMax() - X_mass.getMin()) / 100.), X_mass.getMin(),
            X_mass.getMax())
    else:
        X_mass.setBins(int((X_mass.getMax() - X_mass.getMin()) / 10))
        binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin()) / 100.),
                               X_mass.getMin(), X_mass.getMax())
        plot_binning = binsXmass

    X_mass.setBinning(plot_binning, "PLOT")

    #X_mass.setBins(int((X_mass.getMax() - X_mass.getMin())/10))
    #binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax())
    #X_mass.setBinning(binsXmass, "PLOT")
    massArg = RooArgSet(X_mass)

    # Cuts
    if BTAGGING == 'semimedium':
        SRcut = aliasSM[category]
        #SRcut = aliasSM[category+"_vetoAK8"]
    else:
        SRcut = alias[category].format(WP=working_points[BTAGGING])
        #SRcut = alias[category+"_vetoAK8"].format(WP=working_points[BTAGGING])

    if ADDSELECTION: SRcut += SELECTIONS[options.selection]

    print "  Cut:\t", SRcut

    #*******************************************************#
    #                                                       #
    #                    Signal fits                        #
    #                                                       #
    #*******************************************************#

    treeSign = {}
    setSignal = {}

    vmean = {}
    vsigma = {}
    valpha1 = {}
    vslope1 = {}
    valpha2 = {}
    vslope2 = {}
    smean = {}
    ssigma = {}
    salpha1 = {}
    sslope1 = {}
    salpha2 = {}
    sslope2 = {}
    sbrwig = {}
    signal = {}
    signalExt = {}
    signalYield = {}
    signalIntegral = {}
    signalNorm = {}
    signalXS = {}
    frSignal = {}
    frSignal1 = {}
    frSignal2 = {}
    frSignal3 = {}

    # Signal shape uncertainties (common amongst all mass points)
    xmean_jes = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p1_scale_jes",
        "Variation of the resonance position with the jet energy scale", 0.02,
        -1., 1.)  #0.001
    smean_jes = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p1_jes",
        "Change of the resonance position with the jet energy scale", 0., -10,
        10)

    xsigma_jer = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p2_scale_jer",
        "Variation of the resonance width with the jet energy resolution",
        0.10, -1., 1.)
    ssigma_jer = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p2_jer",
        "Change of the resonance width with the jet energy resolution", 0.,
        -10, 10)

    xmean_jes.setConstant(True)
    smean_jes.setConstant(True)

    xsigma_jer.setConstant(True)
    ssigma_jer.setConstant(True)

    for m in massPoints:

        signalMass = "%s_M%d" % (stype, m)
        signalName = "ZpBB_{}_{}_M{}".format(YEAR, category, m)
        sampleName = "ZpBB_M{}".format(m)

        signalColor = sample[sampleName][
            'linecolor'] if signalName in sample else 1

        # define the signal PDF
        vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m,
                              m * 0.96, m * 1.05)
        smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)",
                                 RooArgList(vmean[m], xmean_jes, smean_jes))

        vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma",
                               m * 0.0233, m * 0.019, m * 0.025)
        ssigma[m] = RooFormulaVar(
            signalName + "_sigma", "@0*(1+@1*@2)",
            RooArgList(vsigma[m], xsigma_jer, ssigma_jer))

        valpha1[m] = RooRealVar(
            signalName + "_valpha1", "Crystal Ball alpha 1", 0.2, 0.05, 0.28
        )  # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0",
                                   RooArgList(valpha1[m]))

        #vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope 1", 10., 0.1, 20.) # slope of the power tail
        vslope1[m] = RooRealVar(signalName + "_vslope1",
                                "Crystal Ball slope 1", 13., 10.,
                                20.)  # slope of the power tail
        sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0",
                                   RooArgList(vslope1[m]))

        valpha2[m] = RooRealVar(signalName + "_valpha2",
                                "Crystal Ball alpha 2", 1.)
        valpha2[m].setConstant(True)
        salpha2[m] = RooFormulaVar(signalName + "_alpha2", "@0",
                                   RooArgList(valpha2[m]))

        #vslope2[m] = RooRealVar(signalName + "_vslope2", "Crystal Ball slope 2", 6., 2.5, 15.) # slope of the higher power tail
        ## FIXME test FIXME
        vslope2_estimation = -5.88111436852 + m * 0.00728809389442 + m * m * (
            -1.65059568762e-06) + m * m * m * (1.25128996309e-10)
        vslope2[m] = RooRealVar(signalName + "_vslope2",
                                "Crystal Ball slope 2", vslope2_estimation,
                                vslope2_estimation * 0.9, vslope2_estimation *
                                1.1)  # slope of the higher power tail
        ## FIXME end FIXME
        sslope2[m] = RooFormulaVar(
            signalName + "_slope2", "@0",
            RooArgList(vslope2[m]))  # slope of the higher power tail

        signal[m] = RooDoubleCrystalBall(signalName,
                                         "m_{%s'} = %d GeV" % ('X', m), X_mass,
                                         smean[m], ssigma[m], salpha1[m],
                                         sslope1[m], salpha2[m], sslope2[m])

        # extend the PDF with the yield to perform an extended likelihood fit
        signalYield[m] = RooRealVar(signalName + "_yield", "signalYield", 50,
                                    0., 1.e15)
        signalNorm[m] = RooRealVar(signalName + "_norm", "signalNorm", 1., 0.,
                                   1.e15)
        signalXS[m] = RooRealVar(signalName + "_xs", "signalXS", 1., 0., 1.e15)
        signalExt[m] = RooExtendPdf(signalName + "_ext", "extended p.d.f",
                                    signal[m], signalYield[m])

        # ---------- if there is no simulated signal, skip this mass point ----------
        if m in genPoints:
            if VERBOSE: print " - Mass point", m

            # define the dataset for the signal applying the SR cuts
            treeSign[m] = TChain("tree")

            if YEAR == 'run2':
                pd = sample[sampleName]['files']
                if len(pd) > 3:
                    print "multiple files given than years for a single masspoint:", pd
                    sys.exit()
                for ss in pd:
                    if not '2016' in ss and not '2017' in ss and not '2018' in ss:
                        print "unknown year given in:", ss
                        sys.exit()
            else:
                pd = [x for x in sample[sampleName]['files'] if YEAR in x]
                if len(pd) > 1:
                    print "multiple files given for a single masspoint/year:", pd
                    sys.exit()

            for ss in pd:

                if options.unskimmed:
                    j = 0
                    while True:
                        if os.path.exists(NTUPLEDIR + ss + "/" + ss +
                                          "_flatTuple_{}.root".format(j)):
                            treeSign[m].Add(NTUPLEDIR + ss + "/" + ss +
                                            "_flatTuple_{}.root".format(j))
                            j += 1
                        else:
                            print "found {} files for sample:".format(j), ss
                            break
                else:
                    if os.path.exists(NTUPLEDIR + ss + ".root"):
                        treeSign[m].Add(NTUPLEDIR + ss + ".root")
                    else:
                        print "found no file for sample:", ss

            if treeSign[m].GetEntries() <= 0.:
                if VERBOSE:
                    print " - 0 events available for mass", m, "skipping mass point..."
                signalNorm[m].setVal(-1)
                vmean[m].setConstant(True)
                vsigma[m].setConstant(True)
                salpha1[m].setConstant(True)
                sslope1[m].setConstant(True)
                salpha2[m].setConstant(True)
                sslope2[m].setConstant(True)
                signalNorm[m].setConstant(True)
                signalXS[m].setConstant(True)
                continue

            #setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar("eventWeightLumi*BTagAK4Weight_deepJet"), RooFit.Import(treeSign[m]))
            setSignal[m] = RooDataSet("setSignal_" + signalName, "setSignal",
                                      variables, RooFit.Cut(SRcut),
                                      RooFit.WeightVar(weight),
                                      RooFit.Import(treeSign[m]))
            if VERBOSE:
                print " - Dataset with", setSignal[m].sumEntries(
                ), "events loaded"

            # FIT
            entries = setSignal[m].sumEntries()
            if entries < 0. or entries != entries: entries = 0
            signalYield[m].setVal(entries)
            # Instead of eventWeightLumi
            #signalYield[m].setVal(entries * LUMI / (300000 if YEAR=='run2' else 100000) )

            if treeSign[m].GetEntries(SRcut) > 5:
                if VERBOSE: print " - Running fit"
                frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1),
                                                 RooFit.Extended(True),
                                                 RooFit.SumW2Error(True),
                                                 RooFit.PrintLevel(-1))
                if VERBOSE:
                    print "********** Fit result [", m, "] **", category, "*" * 40, "\n", frSignal[
                        m].Print(), "\n", "*" * 80
                if VERBOSE: frSignal[m].correlationMatrix().Print()
                drawPlot(signalMass + "_" + category, stype + category, X_mass,
                         signal[m], setSignal[m], frSignal[m])

            else:
                print "  WARNING: signal", stype, "and mass point", m, "in category", category, "has 0 entries or does not exist"

            # Remove HVT cross sections
            #xs = getCrossSection(stype, channel, m)
            xs = 1.
            signalXS[m].setVal(xs * 1000.)

            signalIntegral[m] = signalExt[m].createIntegral(
                massArg, RooFit.NormSet(massArg),
                RooFit.Range("X_integration_range"))
            boundaryFactor = signalIntegral[m].getVal()
            if boundaryFactor < 0. or boundaryFactor != boundaryFactor:
                boundaryFactor = 0
            if VERBOSE:
                print " - Fit normalization vs integral:", signalYield[
                    m].getVal(), "/", boundaryFactor, "events"
            signalNorm[m].setVal(boundaryFactor * signalYield[m].getVal() /
                                 signalXS[m].getVal()
                                 )  # here normalize to sigma(X) x Br = 1 [fb]

        vmean[m].setConstant(True)
        vsigma[m].setConstant(True)
        valpha1[m].setConstant(True)
        vslope1[m].setConstant(True)
        valpha2[m].setConstant(True)
        vslope2[m].setConstant(True)
        signalNorm[m].setConstant(True)
        signalXS[m].setConstant(True)

    #*******************************************************#
    #                                                       #
    #                 Signal interpolation                  #
    #                                                       #
    #*******************************************************#

    ### FIXME FIXME just for a test FIXME FIXME

    #print
    #print
    #print "slope2 fit results:"
    #print
    #y_vals = []
    #for m in genPoints:
    #    y_vals.append(vslope2[m].getVal())
    #print "m =", genPoints
    #print "y =", y_vals
    #sys.exit()

    ### FIXME FIXME test end FIXME FIXME

    # ====== CONTROL PLOT ======
    color_scheme = [
        636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635,
        634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633,
        632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633
    ]
    c_signal = TCanvas("c_signal", "c_signal", 800, 600)
    c_signal.cd()
    frame_signal = X_mass.frame()
    for j, m in enumerate(genPoints):
        if m in signalExt.keys():
            #print "color:",(j%9)+1
            #print "signalNorm[m].getVal() =", signalNorm[m].getVal()
            #print "RooAbsReal.NumEvent =", RooAbsReal.NumEvent
            signal[m].plotOn(
                frame_signal, RooFit.LineColor(color_scheme[j]),
                RooFit.Normalization(signalNorm[m].getVal(),
                                     RooAbsReal.NumEvent),
                RooFit.Range("X_reasonable_range"))
    frame_signal.GetXaxis().SetRangeUser(0, 10000)
    frame_signal.Draw()
    drawCMS(-1, "Simulation Preliminary", year=YEAR)
    #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True)
    #drawCMS(-1, "", year=YEAR, suppressCMS=True)
    drawAnalysis(category)
    drawRegion(category)

    c_signal.SaveAs(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" +
                    category + "_Signal.pdf")
    c_signal.SaveAs(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" +
                    category + "_Signal.png")
    #if VERBOSE: raw_input("Press Enter to continue...")
    # ====== CONTROL PLOT ======

    # Normalization
    gnorm = TGraphErrors()
    gnorm.SetTitle(";m_{X} (GeV);integral (GeV)")
    gnorm.SetMarkerStyle(20)
    gnorm.SetMarkerColor(1)
    gnorm.SetMaximum(0)
    inorm = TGraphErrors()
    inorm.SetMarkerStyle(24)
    fnorm = TF1("fnorm", "pol9", 700, 3000)
    fnorm.SetLineColor(920)
    fnorm.SetLineStyle(7)
    fnorm.SetFillColor(2)
    fnorm.SetLineColor(cColor)

    # Mean
    gmean = TGraphErrors()
    gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)")
    gmean.SetMarkerStyle(20)
    gmean.SetMarkerColor(cColor)
    gmean.SetLineColor(cColor)
    imean = TGraphErrors()
    imean.SetMarkerStyle(24)
    fmean = TF1("fmean", "pol1", 0, 10000)
    fmean.SetLineColor(2)
    fmean.SetFillColor(2)

    # Width
    gsigma = TGraphErrors()
    gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)")
    gsigma.SetMarkerStyle(20)
    gsigma.SetMarkerColor(cColor)
    gsigma.SetLineColor(cColor)
    isigma = TGraphErrors()
    isigma.SetMarkerStyle(24)
    fsigma = TF1("fsigma", "pol1", 0, 10000)
    fsigma.SetLineColor(2)
    fsigma.SetFillColor(2)

    # Alpha1
    galpha1 = TGraphErrors()
    galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha")
    galpha1.SetMarkerStyle(20)
    galpha1.SetMarkerColor(cColor)
    galpha1.SetLineColor(cColor)
    ialpha1 = TGraphErrors()
    ialpha1.SetMarkerStyle(24)
    falpha1 = TF1("falpha", "pol1", 0, 10000)  #pol0
    falpha1.SetLineColor(2)
    falpha1.SetFillColor(2)

    # Slope1
    gslope1 = TGraphErrors()
    gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)")
    gslope1.SetMarkerStyle(20)
    gslope1.SetMarkerColor(cColor)
    gslope1.SetLineColor(cColor)
    islope1 = TGraphErrors()
    islope1.SetMarkerStyle(24)
    fslope1 = TF1("fslope", "pol1", 0, 10000)  #pol0
    fslope1.SetLineColor(2)
    fslope1.SetFillColor(2)

    # Alpha2
    galpha2 = TGraphErrors()
    galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha")
    galpha2.SetMarkerStyle(20)
    galpha2.SetMarkerColor(cColor)
    galpha2.SetLineColor(cColor)
    ialpha2 = TGraphErrors()
    ialpha2.SetMarkerStyle(24)
    falpha2 = TF1("falpha", "pol1", 0, 10000)  #pol0
    falpha2.SetLineColor(2)
    falpha2.SetFillColor(2)

    # Slope2
    gslope2 = TGraphErrors()
    gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)")
    gslope2.SetMarkerStyle(20)
    gslope2.SetMarkerColor(cColor)
    gslope2.SetLineColor(cColor)
    islope2 = TGraphErrors()
    islope2.SetMarkerStyle(24)
    fslope2 = TF1("fslope", "pol1", 0, 10000)  #pol0
    fslope2.SetLineColor(2)
    fslope2.SetFillColor(2)

    n = 0
    for i, m in enumerate(genPoints):
        if not m in signalNorm.keys(): continue
        if signalNorm[m].getVal() < 1.e-6: continue

        if gnorm.GetMaximum() < signalNorm[m].getVal():
            gnorm.SetMaximum(signalNorm[m].getVal())
        gnorm.SetPoint(n, m, signalNorm[m].getVal())
        #gnorm.SetPointError(i, 0, signalNorm[m].getVal()/math.sqrt(treeSign[m].GetEntriesFast()))
        gmean.SetPoint(n, m, vmean[m].getVal())
        gmean.SetPointError(n, 0,
                            min(vmean[m].getError(), vmean[m].getVal() * 0.02))
        gsigma.SetPoint(n, m, vsigma[m].getVal())
        gsigma.SetPointError(
            n, 0, min(vsigma[m].getError(), vsigma[m].getVal() * 0.05))
        galpha1.SetPoint(n, m, valpha1[m].getVal())
        galpha1.SetPointError(
            n, 0, min(valpha1[m].getError(), valpha1[m].getVal() * 0.10))
        gslope1.SetPoint(n, m, vslope1[m].getVal())
        gslope1.SetPointError(
            n, 0, min(vslope1[m].getError(), vslope1[m].getVal() * 0.10))
        galpha2.SetPoint(n, m, salpha2[m].getVal())
        galpha2.SetPointError(
            n, 0, min(valpha2[m].getError(), valpha2[m].getVal() * 0.10))
        gslope2.SetPoint(n, m, sslope2[m].getVal())
        gslope2.SetPointError(
            n, 0, min(vslope2[m].getError(), vslope2[m].getVal() * 0.10))
        #tmpVar = w.var(var+"_"+signalString)
        #print m, tmpVar.getVal(), tmpVar.getError()
        n = n + 1

    gmean.Fit(fmean, "Q0", "SAME")
    gsigma.Fit(fsigma, "Q0", "SAME")
    galpha1.Fit(falpha1, "Q0", "SAME")
    gslope1.Fit(fslope1, "Q0", "SAME")
    galpha2.Fit(falpha2, "Q0", "SAME")
    gslope2.Fit(fslope2, "Q0", "SAME")
    #    gnorm.Fit(fnorm, "Q0", "", 700, 5000)
    #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S"))
    #gnorm.Fit(fnorm, "Q", "SAME", 700, 6000)
    gnorm.Fit(fnorm, "Q", "SAME", 1800, 8000)  ## adjusted recently

    for m in massPoints:

        if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.)

        # Interpolation method
        syield = gnorm.Eval(m)
        spline = gnorm.Eval(m, 0, "S")
        sfunct = fnorm.Eval(m)

        #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield))
        delta = abs(1. - spline / sfunct) if sfunct > 0 else 0
        syield = spline

        if interPar:
            #jmean = gmean.Eval(m)
            #jsigma = gsigma.Eval(m)
            #jalpha1 = galpha1.Eval(m)
            #jslope1 = gslope1.Eval(m)
            #jalpha2 = galpha2.Eval(m)
            #jslope2 = gslope2.Eval(m)
            jmean = gmean.Eval(m, 0, "S")
            jsigma = gsigma.Eval(m, 0, "S")
            jalpha1 = galpha1.Eval(m, 0, "S")
            jslope1 = gslope1.Eval(m, 0, "S")
            jalpha2 = galpha2.Eval(m, 0, "S")
            jslope2 = gslope2.Eval(m, 0, "S")

        else:
            jmean = fmean.GetParameter(
                0) + fmean.GetParameter(1) * m + fmean.GetParameter(2) * m * m
            jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(
                1) * m + fsigma.GetParameter(2) * m * m
            jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(
                1) * m + falpha1.GetParameter(2) * m * m
            jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(
                1) * m + fslope1.GetParameter(2) * m * m
            jalpha2 = falpha2.GetParameter(0) + falpha2.GetParameter(
                1) * m + falpha2.GetParameter(2) * m * m
            jslope2 = fslope2.GetParameter(0) + fslope2.GetParameter(
                1) * m + fslope2.GetParameter(2) * m * m

        inorm.SetPoint(inorm.GetN(), m, syield)
        signalNorm[m].setVal(max(0., syield))

        imean.SetPoint(imean.GetN(), m, jmean)
        if jmean > 0: vmean[m].setVal(jmean)

        isigma.SetPoint(isigma.GetN(), m, jsigma)
        if jsigma > 0: vsigma[m].setVal(jsigma)

        ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1)
        if not jalpha1 == 0: valpha1[m].setVal(jalpha1)

        islope1.SetPoint(islope1.GetN(), m, jslope1)
        if jslope1 > 0: vslope1[m].setVal(jslope1)

        ialpha2.SetPoint(ialpha2.GetN(), m, jalpha2)
        if not jalpha2 == 0: valpha2[m].setVal(jalpha2)

        islope2.SetPoint(islope2.GetN(), m, jslope2)
        if jslope2 > 0: vslope2[m].setVal(jslope2)

        #### newly introduced, not yet sure if helpful:
        vmean[m].removeError()
        vsigma[m].removeError()
        valpha1[m].removeError()
        valpha2[m].removeError()
        vslope1[m].removeError()
        vslope2[m].removeError()

        #signalNorm[m].setConstant(False)  ## newly put here to ensure it's freely floating in the combine fit

    #c1 = TCanvas("c1", "Crystal Ball", 1200, 1200) #if not isAH else 1200
    #c1.Divide(2, 3)
    c1 = TCanvas("c1", "Crystal Ball", 1800, 800)
    c1.Divide(3, 2)
    c1.cd(1)
    gmean.SetMinimum(0.)
    gmean.Draw("APL")
    imean.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    c1.cd(2)
    gsigma.SetMinimum(0.)
    gsigma.Draw("APL")
    isigma.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    c1.cd(3)
    galpha1.Draw("APL")
    ialpha1.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    galpha1.GetYaxis().SetRangeUser(0., 1.1)  #adjusted upper limit from 5 to 2
    c1.cd(4)
    gslope1.Draw("APL")
    islope1.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    gslope1.GetYaxis().SetRangeUser(0.,
                                    150.)  #adjusted upper limit from 125 to 60
    if True:  #isAH:
        c1.cd(5)
        galpha2.Draw("APL")
        ialpha2.Draw("P, SAME")
        drawRegion(category)
        drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
        galpha2.GetYaxis().SetRangeUser(0., 2.)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(category)
        drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
        gslope2.GetYaxis().SetRangeUser(0., 20.)

    c1.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalShape.pdf")
    c1.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalShape.png")

    c2 = TCanvas("c2", "Signal Efficiency", 800, 600)
    c2.cd(1)
    gnorm.SetMarkerColor(cColor)
    gnorm.SetMarkerStyle(20)
    gnorm.SetLineColor(cColor)
    gnorm.SetLineWidth(2)
    gnorm.Draw("APL")
    inorm.Draw("P, SAME")
    gnorm.GetXaxis().SetRangeUser(genPoints[0] - 100, genPoints[-1] + 100)
    gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum() * 1.25)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)
    #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True)
    #drawCMS(-1, "", year=YEAR, suppressCMS=True)
    drawAnalysis(category)
    drawRegion(category)
    c2.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalNorm.pdf")
    c2.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalNorm.png")

    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    # create workspace
    w = RooWorkspace("Zprime_" + YEAR, "workspace")
    for m in massPoints:
        getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName()))
        getattr(w, "import")(signalNorm[m],
                             RooFit.Rename(signalNorm[m].GetName()))
        getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName()))
    w.writeToFile(WORKDIR + "MC_signal_%s_%s.root" % (YEAR, category), True)
    print "Workspace", WORKDIR + "MC_signal_%s_%s.root" % (
        YEAR, category), "saved successfully"
Exemplo n.º 19
0
small=1.e-5
c1.Divide(1,2,small,small)

c1.cd(1)
gPad.SetPad(small, 0.3, 1.-small, 1.-small)
gPad.SetBottomMargin(small)

labelSize=10
makerSize = 0.3

gStyle.SetEndErrorSize(0)

gr = TGraphErrors( n, energyVec, recoEnergyVec, energyErrorVec, recoEnergyErrorVec )
gr.SetName('gr')
gr.SetLineColor( 1 )
gr.SetLineWidth( 1 )
gr.SetLineStyle( 2 )
gr.SetMarkerColor( 2 )
gr.SetMarkerStyle( 20 )
gr.SetMarkerSize( makerSize )
textsize = labelSize/(gPad.GetWh()*gPad.GetAbsHNDC())
gr.SetTitle( '' )
gr.GetXaxis().SetTitle( 'E_{particle} (GeV)' )
gr.GetYaxis().SetTitle( 'E_{reco} (GeV)' )
gr.GetYaxis().SetTitleSize(textsize)
gr.GetYaxis().SetLabelSize(textsize)
gr.GetYaxis().SetTitleOffset(1.4)
gr.GetYaxis().SetRangeUser(2, 100)
gPad.SetLeftMargin(0.15)
gr.Draw( 'AP' )
g_purity = TGraphErrors(len(purity_list), array(tolerance_list),
                        array(purity_list), no_err, array(purity_err_list))
g_acceptance = TGraphErrors(len(acceptance), array(tolerance_list),
                            array(acceptance), no_err, array(purity_err_list))
g_reco_eff_data = TGraphErrors(len(reco_eff_list), array(tolerance_list),
                               array(reco_eff_list), no_err,
                               array(eff_err_list))
g_data_eff = TGraphErrors(len(reco_eff_list), array(tolerance_list),
                          array(data_eff_list), no_err, array(eff_err_list))

g_eff.Draw("APL")
g_eff.GetXaxis().SetTitle("#it{d}_{max} [cm]")
g_eff.GetYaxis().SetTitle("[%]")
g_eff.GetYaxis().SetRangeUser(90, 100)
g_eff.SetMarkerStyle(20)
g_eff.SetLineColor(kRed + 1)
g_eff.SetLineWidth(2)
g_purity.Draw("PL")
g_purity.SetMarkerStyle(21)
g_purity.SetLineColor(kBlue + 1)
g_purity.SetLineWidth(2)
g_acceptance.Draw("PL")
g_acceptance.SetMarkerStyle(23)
g_acceptance.SetLineColor(kGreen + 2)
g_acceptance.SetLineWidth(2)
g_reco_eff.Draw("PL")
g_reco_eff.SetLineColor(kGray + 2)
g_reco_eff.SetLineWidth(2)
g_reco_eff.SetMarkerStyle(29)
g_reco_eff.SetMarkerSize(1.5)
g_reco_eff_data.Draw("PL")
Exemplo n.º 21
0
legend.SetBorderSize(0)
legend.SetFillColor(0)
legend.SetFillStyle(0)
legend.SetTextFont(42)
legend.SetTextSize(0.035)
legend.AddEntry(GraphL0Unc, "L0", "LP")
legend.AddEntry(GraphNomUnc, "nominal", "LP")

GraphNomUnc.Draw("")
GraphNomUnc.GetXaxis().SetRangeUser(minMass, maxMass)
GraphNomUnc.GetYaxis().SetRangeUser(0, 0.005)
GraphNomUnc.SetTitle("Unconstrained Invariant Mass Resolution Prompt A's")
GraphNomUnc.GetXaxis().SetTitle("mass [GeV]")
GraphNomUnc.GetYaxis().SetTitle("mass resolution [GeV]")
GraphL0Unc.Draw("same")
GraphL0Unc.SetLineColor(2)

gStyle.SetOptStat(0)

legend.Draw()
c.Print("uncInvMass.pdf", "Title:histoTitle")

c.Clear()

GraphNomTarg.Draw("")
GraphNomTarg.GetXaxis().SetRangeUser(minMass, maxMass)
GraphNomTarg.GetYaxis().SetRangeUser(0, 0.005)
GraphNomTarg.SetTitle(
    "Target Constrained Invariant Mass Resolution Prompt A's")
GraphNomTarg.GetXaxis().SetTitle("mass [GeV]")
GraphNomTarg.GetYaxis().SetTitle("mass resolution [GeV]")
Exemplo n.º 22
0
def closureTest_plots(filename):
    f = BareRootFile(filename)
    tree = f.Get('closureTest')

    gStyle.SetStatX(0.9)
    gStyle.SetStatY(0.9)
    gStyle.SetStatW(0.2)
    gStyle.SetStatH(0.14)

    hist1 = TH1F('hist1', '', 55, 0.9, 2.0)
    hist2 = TH1F('hist2', '', 55, 0.9, 2.0)
    condition = ('fit_overlapDiff>=0 && temp_overlapDiff>=0 && '
                 'fit_chisq/fit_dof<=2 && temp_chisq/temp_dof<=2')
    tree.Draw('temp_chisq/temp_dof>>hist1', condition)
    tree.Draw('fit_chisq/fit_dof>>hist2', condition)
    for i, hist in [(0, hist1), (1, hist2)]:
        hist.SetLineColor(colors[i])
        hist.SetLineWidth(3)
    maxi = max(hist1.GetMaximum(), hist2.GetMaximum()) * 1.1
    plot = SingleHistBase(hist1,
                          'hist_numberPerChisq',
                          fill=None,
                          workinprogress=wip)
    gStyle.SetOptStat(10)
    plot._xtitle = '#chi^{2}/d.o.f.'
    plot._ytitle = 'number of toys'
    plot.yrange(0.0, maxi)
    leg = TLegend(0.65, 0.75, 0.89, 0.85)
    leg.SetBorderSize(0)
    leg.AddEntry(hist1, 'DG fit', 'L')
    leg.AddEntry(hist2, 'SupDG fit', 'L')
    plot.draw()
    hist2.Draw('SAMEH')
    leg.Draw()
    plot.save_pdf()
    plot.Close()

    hist3 = TH2F('hist3', '', 31, -0.05, 3.05, 31, -0.05, 3.05)
    tree.Draw('100*temp_overlapDiff:100*fit_overlapDiff>>hist3', condition)
    one = TF1('one', 'x', -10.0, 10.0)
    one.SetLineColor(1)
    plot = SingleHistBase(hist3,
                          'correctionDGvsSupDG',
                          fill=None,
                          workinprogress=wip)
    plot.add(one)
    plot._drawoption = 'BOX'
    plot._xtitle = 'correction [%] from SupDG fit'
    plot._ytitle = 'correction [%] from DG fit'
    plot._above = True
    plot.draw()
    plot.save_pdf()
    plot.Close()

    hist4 = TH2F('hist4', '', 22, 0.95, 1.5, 22, 0.95, 1.5)
    tree.Draw('temp_chisq/temp_dof:fit_chisq/fit_dof>>hist4', condition)
    plot = SingleHistBase(hist4,
                          'chisqDGvsSupDG',
                          fill=None,
                          workinprogress=wip)
    plot.add(one)
    plot._drawoption = 'BOX'
    plot._xtitle = '#chi^{2}/d.o.f. of SupDG fit'
    plot._ytitle = '#chi^{2}/d.o.f. of DG fit'
    plot._above = True
    plot.draw()
    plot.save_pdf()
    plot.Close()

    gStyle.SetStatX(0.9)
    gStyle.SetStatY(0.83)
    gStyle.SetStatW(0.3)
    gStyle.SetStatH(0.08)

    #bins_csq = [(0.0, 1.1), (1.1, 1.3), (1.3, 1.6), (1.6, 2.0)]
    #bins_cor = [(0.0, 0.5), (0.5, 1.0), (1.0, 1.5), (1.5, 2.0), (2.0, 2.5)]
    #bins_csq = [(1.07, 1.13), (1.06, 1.11), (1.3, 1.5), (1.08, 1.17), (1.1, 1.2)]
    #bins_cor = [(0.3, 0.8), (0.9, 1.2), (0.1, 0.5), (0.4, 0.7), (0.3, 1.1)]
    bins_csq = [(0.99, 1.06), (0.98, 1.07), (0.99, 1.10), (1.02, 1.06),
                (1.00, 1.06), (1.00, 1.04)]
    bins_cor = [(0.9, 1.9), (0.4, 1.6), (0.6, 1.5), (0.6, 1.9), (1.0, 1.3),
                (0.3, 1.5)]

    means = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    meane = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    rmses = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    rmser = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }

    #for i, (csq_lo, csq_hi) in enumerate(bins_csq):
    #    for j, (cor_lo, cor_hi) in enumerate(bins_cor):
    for i, ((csq_lo, csq_hi), (cor_lo,
                               cor_hi)) in enumerate(zip(bins_csq, bins_cor)):
        j = i
        name = 'hist_{{0}}_{0}csq{1}_{2}cor{3}' \
               .format(csq_lo, csq_hi, cor_lo, cor_hi)
        fields = '100*({0}_overlapDiff-toy_overlapDiff)>>hist'
        condition = (
            '100*{{0}}_overlapDiff>={0} && 100*{{0}}_overlapDiff<{1} && '
            '{{0}}_chisq/{{0}}_dof>={2} && {{0}}_chisq/{{0}}_dof<{3} && '
            'fit_overlapDiff>=0 && temp_overlapDiff>=0 && '
            'fit_chisq/fit_dof<=2 && temp_chisq/temp_dof<=2').format(
                cor_lo, cor_hi, csq_lo, csq_hi)
        xtitle = 'correction [%] from {0} fit #minus true correction [%]'
        line1 = '{0} < correction < {1}'.format(cor_lo, cor_hi)
        line2 = '{0} < #chi^{{2}}/d.o.f. < {1}'.format(csq_lo, csq_hi)
        gStyle.SetOptStat(2210)
        for prefix, modname in (('temp', 'DG'), ('fit', 'SupDG')):
            hist = TH1F('hist', '', 41, -2.05, 2.05)
            hist.StatOverflows()
            tree.Draw(fields.format(prefix), condition.format(prefix))
            plot = SingleHistBase(hist,
                                  name.format(modname),
                                  fill=None,
                                  workinprogress=wip)
            gStyle.SetOptStat(2210)
            plot._xtitle = xtitle.format(modname)
            plot._ytitle = 'number of toys'
            plot.xrange(-2.05, 2.05)
            plot.yrange(0.0, plot._graph.GetMaximum() * 1.2)
            pave = plot.add_pave(0.6, 0.83, 0.9, 0.9, border=True)
            pave(line1)
            pave(line2)
            plot.draw()
            plot.save_pdf()
            means[modname][i][j] = plot._graph.GetMean()
            meane[modname][i][j] = plot._graph.GetMeanError()
            rmses[modname][i][j] = plot._graph.GetRMS()
            rmser[modname][i][j] = plot._graph.GetRMSError()
            plot.Close()

    multi = TMultiGraph('multi', '')
    for k, modname in enumerate(('DG', 'SupDG')):
        for i, (csq_lo, csq_hi) in enumerate(bins_csq):
            xval = array(
                'd',
                [j - 0.35 + k * 0.4 + i * 0.1 for j in range(len(bins_cor))])
            xerr = array('d', [0.0] * len(bins_cor))
            yval = array('d', means[modname][i])
            yerr = array('d', rmses[modname][i])
            graph = TGraphErrors(len(bins_cor), xval, yval, xerr, yerr)
            graph.SetName('graph{0}{1}'.format(k, i))
            graph.SetMarkerStyle(22 + k)
            graph.SetMarkerColor(colors[i])
            graph.SetLineColor(colors[i])
            multi.Add(graph)
    minvalues = [
        means[mod][i][j] - rmses[mod][i][j] for j in range(len(bins_cor))
        for i in range(len(bins_csq)) for mod in ('DG', 'SupDG')
    ]
    maxvalues = [
        means[mod][i][j] + rmses[mod][i][j] for j in range(len(bins_cor))
        for i in range(len(bins_csq)) for mod in ('DG', 'SupDG')
    ]
    mini, maxi = min(minvalues), max(maxvalues)
    mini, maxi = mini - 0.1 * (maxi - mini), maxi + 0.3 * (maxi - mini)
    hist = TH2F('axishist', '', len(bins_cor), -0.5,
                len(bins_cor) - 0.5, 100, mini, maxi)
    for j, (cor_lo, cor_hi) in enumerate(bins_cor):
        hist.GetXaxis().SetBinLabel(j + 1,
                                    '{0}% #minus {1}%'.format(cor_lo, cor_hi))
    leg1 = TLegend(0.53, 0.78, 0.63, 0.86)
    leg1.SetBorderSize(0)
    dgmarker = TMarker(0.0, 0.0, 22)
    supdgmarker = TMarker(0.0, 0.0, 23)
    leg1.AddEntry(dgmarker, 'DG', 'P')
    leg1.AddEntry(supdgmarker, 'SupDG', 'P')
    leg2 = TLegend(0.65, 0.75, 0.89, 0.89)
    leg2.SetBorderSize(0)
    csqmarker = TMarker(0.0, 0.0, 1)
    for i, (csq_lo, csq_hi) in enumerate(bins_csq):
        title = '{0} < #chi^{{2}}/d.o.f. < {1}'.format(csq_lo, csq_hi)
        entry = leg2.AddEntry(csqmarker, title, 'L')
        entry.SetMarkerColor(colors[i])
        entry.SetLineColor(colors[i])
    zero = TF1('zero', '0.0', -1.0, 10.0)
    zero.SetLineColor(1)
    zero.SetLineStyle(2)
    plot = SingleHistBase(hist,
                          name='differenceDoubleDifferential',
                          fill=None,
                          workinprogress=wip)
    plot._xtitle = 'correction from fit'
    plot._ytitle = 'correction [%] from fit #minus true correction [%]'
    plot.xrange(-0.5, len(bins_cor) - 0.5)
    plot.yrange(mini, maxi)
    plot._drawoption = 'AXIS'
    plot.draw()
    plot.xaxis().SetNdivisions(len(bins_cor), False)
    plot.xaxis().SetLabelSize(0.03)
    zero.Draw('SAME')
    multi.Draw('P')
    leg1.Draw()
    leg2.Draw()
    plot.save_pdf()
    plot.Close()

    bcid = (41, 281, 872, 1783, 2063)
    DGcor1 = array('d', [0.809, 0.392, 0.846, 0.731, 0.497])
    DGerr1 = array('d', [0.548, 0.567, 0.984, 0.984, 1.018])
    DGcor2 = array('d', [1.145, 0.799, 1.58, 1.465, 1.281])
    DGerr2 = array('d', [0.432, 0.395, 0.656, 0.656, 0.649])
    DGxval = array('d', [j - 0.1 for j in range(5)])
    SupDGcor1 = array('d', [0.823, 0.761, 1.458, 0.986, 1.012])
    SupDGerr1 = array('d', [0.513, 0.513, 0.499, 0.513, 0.499])
    SupDGcor2 = array('d', [0.978, 0.916, 1.532, 1.141, 1.086])
    SupDGerr2 = array('d', [0.489, 0.489, 0.493, 0.489, 0.493])
    SupDGxval = array('d', [j + 0.1 for j in range(5)])
    xerr = array('d', [0.0] * 5)

    for fill, values in [
        (4266, {
            'DGcor': [1.021, 1.057, 0.968, 1.084, 1.114],
            'DGerr': [(e**2 + 0.74**2)**0.5
                      for e in (0.118, 0.124, 0.119, 0.117, 0.119)],
            'SupDGcor': [1.402, 1.411, 1.164, 1.549, 1.589],
            'SupDGerr': [(e**2 + 0.45**2)**0.5
                         for e in (0.106, 0.110, 0.108, 0.106, 0.115)],
            'bcids': [51, 771, 1631, 2211, 2674]
        }),
        (4954, {
            'DGcor': [0.799, 0.398, 0.845, 0.724, 0.502],
            'DGerr': [(e**2 + 0.79**2)**0.5
                      for e in (0.137, 0.124, 0.122, 0.130, 0.116)],
            'SupDGcor': [0.794, 0.694, 1.642, 0.983, 0.993],
            'SupDGerr': [(e**2 + 0.50**2)**0.5
                         for e in (0.126, 0.112, 0.186, 0.102, 0.144)],
            'bcids': [41, 281, 872, 1783, 2063]
        }),
        (4937, {
            'DGcor': [0.649, 0.494, 0.575, 0.527, 0.602],
            'DGerr':
            [(e**2 + 0.85**2)**0.5 for e in (0.127, 0.115, 0.120, 0.125)],
            'SupDGcor': [0.377, 0.611, 1.137, 0.453, 1.840],
            'SupDGerr': [(e**2 + 0.56**2)**0.5
                         for e in (0.100, 0.105, 0.288, 0.161, 0.207)],
            'bcids': [81, 875, 1610, 1690, 1730]
        }),
        (6016, {
            'DGcor': [0.146, 0.394, 0.377, 0.488, 0.184],
            'DGerr': [(e**2 + 1.15**2)**0.5
                      for e in (0.110, 0.114, 0.118, 0.123, 0.109)],
            'SupDGcor': [0.760, 0.953, 1.048, 0.847, 0.373],
            'SupDGerr': [(e**2 + 0.79**2)**0.5
                         for e in (0.219, 0.094, 0.189, 0.098, 0.169)],
            'bcids': [41, 281, 872, 1783, 2063]
        })
    ]:
        bcid = values['bcids']
        DGcor = array('d', values['DGcor'])
        DGerr = array('d', values['DGerr'])
        DGxvl = array('d', [j - 0.1 for j in range(len(bcid))])
        SupDGcor = array('d', values['SupDGcor'])
        SupDGerr = array('d', values['SupDGerr'])
        SupDGxvl = array('d', [j + 0.1 for j in range(len(bcid))])
        xerr = array('d', [0.0] * len(bcid))
        maxi = max(max([v + e for v, e in zip(DGcor, DGerr)]),
                   max([v + e for v, e in zip(SupDGcor, SupDGerr)]))
        mini = min(min([v - e for v, e in zip(DGcor, DGerr)]),
                   min([v - e for v, e in zip(SupDGcor, SupDGerr)]))
        maxi, mini = maxi + 0.2 * (maxi - mini), mini - 0.1 * (maxi - mini)

        graphDG = TGraphErrors(len(bcid), DGxvl, DGcor, xerr, DGerr)
        graphDG.SetName('graphDG')
        graphSupDG = TGraphErrors(len(bcid), SupDGxvl, SupDGcor, xerr,
                                  SupDGerr)
        graphSupDG.SetName('graphSupDG')
        multi = TMultiGraph('multi', '')
        for i, graph in [(0, graphDG), (1, graphSupDG)]:
            graph.SetMarkerStyle(22 + i)
            graph.SetMarkerColor(colors[i])
            graph.SetLineColor(colors[i])
            multi.Add(graph)
        leg = TLegend(0.15, 0.80, 0.5, 0.83)
        leg.SetNColumns(2)
        leg.SetBorderSize(0)
        leg.AddEntry(graphDG, 'DG fit', 'PL')
        leg.AddEntry(graphSupDG, 'SupDG fit', 'PL')
        axishist = TH2F('axishist', '', len(bcid), -0.5,
                        len(bcid) - 0.5, 100, mini, maxi)
        for i, bx in enumerate(bcid):
            axishist.GetXaxis().SetBinLabel(i + 1, '{0}'.format(bx))

        plot = SingleHistBase(axishist,
                              name='Fill{0}biased'.format(fill),
                              fill=fill,
                              workinprogress=wip)
        plot._xtitle = 'BCID'
        plot._ytitle = 'correction [%] from fit'
        plot.xrange(-0.5, len(bcid) - 0.5)
        plot.yrange(mini, maxi)
        plot._drawoption = 'AXIS'
        plot.draw()
        plot.xaxis().SetNdivisions(len(bcid), False)
        plot.xaxis().SetLabelSize(0.03)
        multi.Draw('P')
        leg.Draw()
        plot.save_pdf()
        plot.Close()

        print
        print 'Fill', fill
        for bx, cor, err in zip(bcid, SupDGcor, SupDGerr):
            print 'BCID {0}:\t{1:.2f} +- {2:.2f}'.format(bx, cor, err)
        print
Exemplo n.º 23
0
def mistagSFtopEMu(year_, ana_):
    if year_ == 2017:
        dir = "monohbb.v06.00.05.2017_NCU/withSingleTop/" + ana_ + "/"
    if year_ == 2018:
        dir = "monohbb.v06.00.05.2018_NCU/withSingleTop/" + ana_ + "/"

    print "Top Electron Region"
    print " "

    openfile1 = TFile(dir + "TopE.root")  #

    topmatchTopE = openfile1.Get("h_TopMatch")
    WmatchTopE = openfile1.Get("h_Wmatch")
    unmatchTopE = openfile1.Get("h_unmatch")
    wjetsTopE = openfile1.Get("h_sumWJets")
    dibosonTopE = openfile1.Get("h_sumDiboson")
    unsubtractedDataTopE = openfile1.Get("h_Data")

    failMCsubtractTopE = openfile1.Get("h_ttFailed")
    passMCsubtractTopE = openfile1.Get("h_ttPassed")
    subtractedDataTopE = openfile1.Get("SubtractedData")

    datafailTopE = openfile1.Get("SubtractedDataFailed")
    datapassTopE = openfile1.Get("SubtractedDataPassed")  #
    totaldataTopE = openfile1.Get("h_totaldata")
    totalMCtopE = openfile1.Get("h_tt")

    passedTopEdataBfrSubtract = openfile1.Get("h_Data_Passed")
    wjetsTopEpassed = openfile1.Get("h_sumWJetsPassed")
    dibosonTopEpassed = openfile1.Get("h_sumDibosonPassed")

    failedTopEdataBfrSubtract = openfile1.Get("h_Data_Failed")
    wjetsTopEfailed = openfile1.Get("h_sumWJetsFailed")
    dibosonTopEfailed = openfile1.Get("h_sumDibosonFailed")

    stTopE = openfile1.Get("h_sumST")
    stTopEpassed = openfile1.Get("h_sumSTPassed")
    stTopEfailed = openfile1.Get("h_sumSTFailed")

    print "Top Muon Region"
    print " "

    openfile2 = TFile(dir + "TopMu.root")  #

    topmatchTopMu = openfile2.Get("h_TopMatch")
    WmatchTopMu = openfile2.Get("h_Wmatch")
    unmatchTopMu = openfile2.Get("h_unmatch")
    wjetsTopMu = openfile2.Get("h_sumWJets")
    dibosonTopMu = openfile2.Get("h_sumDiboson")
    unsubtractedDataTopMu = openfile2.Get("h_Data")

    failMCsubtractTopMu = openfile2.Get("h_ttFailed")
    passMCsubtractTopMu = openfile2.Get("h_ttPassed")
    subtractedDataTopMu = openfile2.Get("SubtractedData")

    datafailTopMu = openfile2.Get("SubtractedDataFailed")
    datapassTopMu = openfile2.Get("SubtractedDataPassed")  #
    totaldataTopMu = openfile2.Get("h_totaldata")
    totalMCtopMu = openfile2.Get("h_tt")

    passedTopMudataBfrSubtract = openfile2.Get("h_Data_Passed")
    wjetsTopMupassed = openfile2.Get("h_sumWJetsPassed")
    dibosonTopMupassed = openfile2.Get("h_sumDibosonPassed")

    failedTopMudataBfrSubtract = openfile2.Get("h_Data_Failed")
    wjetsTopMufailed = openfile2.Get("h_sumWJetsFailed")
    dibosonTopMufailed = openfile2.Get("h_sumDibosonFailed")

    stTopMu = openfile2.Get("h_sumST")
    stTopMupassed = openfile2.Get("h_sumSTPassed")
    stTopMufailed = openfile2.Get("h_sumSTFailed")

    print "get histograms from root files: done"
    print " "

    SubtractedDataPassedTopE = datapassTopE.Clone("SubtractedDataPassedTopE")
    SubtractedDataPassedTopMu = datapassTopMu.Clone(
        "SubtractedDataPassedTopMu")

    #merge histogram"
    print "merge histograms"
    print " "

    topmatchMerge = topmatchTopE + topmatchTopMu
    WmatchMerge = WmatchTopE + WmatchTopMu
    unmatchMerge = unmatchTopE + unmatchTopMu
    wjetsMerge = wjetsTopE + wjetsTopMu
    stMerge = stTopE + stTopMu
    dibosonMerge = dibosonTopE + dibosonTopMu
    unsubtractedDataMerge = unsubtractedDataTopE + unsubtractedDataTopMu

    failMCsubtractMerge = failMCsubtractTopE.Clone("failMCsubtractMerge")
    failMCsubtractMerge = failMCsubtractMerge + failMCsubtractTopMu
    passMCsubtractMerge = passMCsubtractTopE.Clone("passMCsubtractMerge")
    passMCsubtractMerge = passMCsubtractMerge + passMCsubtractTopMu
    subtractedDataMerge = subtractedDataTopE + subtractedDataTopMu

    ttData_fraction = arr.array('d')
    ttData_error = arr.array('d')

    totaldataMerge = totaldataTopE + totaldataTopMu
    totaldata = totaldataMerge.Integral()
    totaldataMerge.Rebin(14)

    datafailMerge = datafailTopE + datafailTopMu
    faildata = datafailMerge.Integral()
    datafailMerge.Rebin(14)
    datafailMerge.Sumw2()
    datafailMerge.Divide(totaldataMerge)
    frac_ttData_fail = datafailMerge.Integral()
    ttData_fraction.append(frac_ttData_fail)
    ttData_error.append(datafailMerge.GetBinError(1))

    datapassMerge = datapassTopE + datapassTopMu
    passdata = datapassMerge.Integral()
    datapassMerge.Rebin(14)
    datapassMerge.Sumw2()
    datapassMerge.Divide(totaldataMerge)
    frac_ttData_pass = datapassMerge.Integral()
    ttData_fraction.append(frac_ttData_pass)
    ttData_error.append(datapassMerge.GetBinError(1))

    ttMC_fraction = arr.array('d')
    ttMC_error = arr.array('d')

    totalMCmerge = totalMCtopE + totalMCtopMu
    totalMCmerge.Rebin(14)

    MCfailTopE = failMCsubtractTopE.Clone("MCfailTopE")
    MCfailTopMu = failMCsubtractTopMu.Clone("MCfailTopMu")
    MCfailMerge = MCfailTopE + MCfailTopMu
    MCfailMerge.Rebin(14)
    MCfailMerge.Sumw2()
    MCfailMerge.Divide(totalMCmerge)
    frac_Failed_fin = MCfailMerge.Integral()
    ttMC_fraction.append(frac_Failed_fin)
    ttMC_error.append(MCfailMerge.GetBinError(1))

    MCpassTopE = passMCsubtractTopE.Clone("MCpassTopE")
    MCpassTopMu = passMCsubtractTopMu.Clone("MCpassTopMu")
    MCpassMerge = MCpassTopE + MCpassTopMu
    MCpassMerge.Rebin(14)
    MCpassMerge.Sumw2()
    MCpassMerge.Divide(totalMCmerge)
    frac_Passed_fin = MCpassMerge.Integral()
    ttMC_fraction.append(frac_Passed_fin)
    ttMC_error.append(MCpassMerge.GetBinError(1))

    #print "\nttMC_fraction:", ttMC_fraction
    #print "ttMC_error:", ttMC_error

    sfMerge = datapassMerge.Clone("sfMerge")
    sfMerge.Sumw2()
    sfMerge.Divide(MCpassMerge)

    stacklist = []
    stacklist.append(dibosonMerge)
    stacklist.append(stMerge)
    stacklist.append(wjetsMerge)
    stacklist.append(unmatchMerge)
    stacklist.append(WmatchMerge)
    stacklist.append(topmatchMerge)

    print "merge histograms: done"
    print " "

    print "draw histograms"
    print " "
    #----------------------- canvas 1 -----------------------#

    c1 = TCanvas("c1", "", 800, 900)  #width-height
    c1.SetTopMargin(0.4)
    c1.SetBottomMargin(0.05)
    c1.SetRightMargin(0.1)
    c1.SetLeftMargin(0.15)
    gStyle.SetOptStat(0)

    binvalues1 = []
    for i in range(14):
        binvalue = unsubtractedDataMerge.GetBinContent(i)
        binvalues1.append(binvalue)
    totalmax = max(binvalues1) + 100

    padMain = TPad("padMain", "", 0.0, 0.25, 1.0, 0.97)
    padMain.SetTopMargin(0.4)
    padMain.SetRightMargin(0.05)
    padMain.SetLeftMargin(0.17)
    padMain.SetBottomMargin(0.03)
    padMain.SetTopMargin(0.1)

    padRatio = TPad("padRatio", "", 0.0, 0.0, 1.0, 0.25)
    padRatio.SetRightMargin(0.05)
    padRatio.SetLeftMargin(0.17)
    padRatio.SetTopMargin(0.05)
    padRatio.SetBottomMargin(0.3)
    padMain.Draw()
    padRatio.Draw()

    padMain.cd()

    gPad.GetUymax()
    leg1 = myLegend(coordinate=[0.45, 0.57, 0.65, 0.6])

    unsubtractedDataMerge.SetMaximum(totalmax)
    unsubtractedDataMerge.SetLineColor(1)
    unsubtractedDataMerge.SetMarkerStyle(20)
    unsubtractedDataMerge.SetMarkerSize(1.5)
    unsubtractedDataMerge.GetXaxis().SetLabelSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitleSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitle("DDB")
    unsubtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg1.AddEntry(unsubtractedDataMerge, "Data", "lep")
    unsubtractedDataMerge.Draw("e1")

    stackhisto = myStack(colorlist_=[627, 800, 854, 813, 822, 821],
                         backgroundlist_=stacklist,
                         legendname_=[
                             "Diboson", "Single Top", "W+Jets",
                             "Top (unmtch.)", "Top (W-mtch.)", "Top (mtch.)"
                         ])
    stackhisto[0].Draw("histsame")
    unsubtractedDataMerge.Draw("e1same")
    stackhisto[1].Draw()
    leg1.Draw()

    lt = TLatex()
    lt.DrawLatexNDC(0.23, 0.85,
                    "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    if ana_ == "Inclusive":
        lt.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt.DrawLatexNDC(0.17, 0.92,
                            "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt.DrawLatexNDC(0.71, 0.92,
                        "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    padRatio.cd()

    gPad.GetUymax()

    h_totalBkg = topmatchMerge.Clone("h_totalBkg")
    h_totalBkg = h_totalBkg + WmatchMerge + unmatchMerge + wjetsMerge + dibosonMerge
    ratio = dataPredRatio(data_=unsubtractedDataMerge, totalBkg_=h_totalBkg)
    ratio.SetLineColor(1)
    ratio.SetLineWidth(3)
    ratio.SetMarkerSize(1.5)
    ratio.GetXaxis().SetLabelSize(0.13)
    ratio.GetXaxis().SetTitleOffset(1)
    ratio.GetXaxis().SetTitleSize(0.13)
    ratio.GetXaxis().SetTickLength(0.1)
    ratio.GetYaxis().SetLabelSize(0.12)
    ratio.GetYaxis().SetTitleOffset(0.5)
    ratio.GetYaxis().SetTitleSize(0.13)
    ratio.GetYaxis().SetNdivisions(405)
    ratio.GetYaxis().SetTitle("#frac{Data-Pred}{Pred}")
    ratio.GetXaxis().SetTitle("DDB")
    ratio.Draw("e1")

    c1.SaveAs(dir + "Merge_all.pdf")  #

    #----------------------- canvas 2 -----------------------#

    c2 = myCanvas(c="c2")
    gPad.GetUymax()
    leg2 = myLegend()

    binvalues2 = []
    for i in range(14):
        binvalue = subtractedDataMerge.GetBinContent(i)
        binvalues2.append(binvalue)
    ttmax = max(binvalues2) + 50

    failMCsubtractMerge.SetMaximum(ttmax)
    failMCsubtractMerge.SetFillColor(821)
    failMCsubtractMerge.SetLineColor(821)  #922
    failMCsubtractMerge.GetXaxis().SetTitle("DDB")
    failMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(failMCsubtractMerge, "t#bar{t}", "f")

    passMCsubtractMerge.SetFillColor(622)
    passMCsubtractMerge.SetLineColor(622)
    #passMCsubtractMerge.GetXaxis().SetTitle("DDB")
    #passMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(passMCsubtractMerge, "t#bar{t} mistag", "f")

    subtractedDataMerge.SetLineColor(1)
    subtractedDataMerge.SetMarkerStyle(20)
    subtractedDataMerge.SetMarkerSize(1.5)
    #subtractedDataMerge.GetXaxis().SetTitle("DDB")
    #subtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(subtractedDataMerge, "Subtracted Data", "lep")

    failMCsubtractMerge.Draw("hist")
    passMCsubtractMerge.Draw("histsame")
    subtractedDataMerge.Draw("e1same")
    leg2.Draw()

    lt2 = TLatex()
    if ana_ == "Inclusive":
        lt2.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt2.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt2.DrawLatexNDC(0.23, 0.85,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt2.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt2.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt2.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt2.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    c2.SaveAs(dir + "Merged_subtrac.pdf")  #

    #----------------------- canvas 3 -----------------------#

    c3 = myCanvas(c="c3", size=[700, 900])

    pad1 = TPad("pad1", "", 0.01, 0.25, 0.93, 1.0)
    pad1.SetTopMargin(0.1)
    pad1.SetRightMargin(0.05)
    pad1.SetLeftMargin(0.17)
    pad1.SetBottomMargin(0.05)

    pad2 = TPad("pad2", "", 0.0, 0.0, 0.375, 0.24)
    pad2.SetTopMargin(0.0)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.0)
    pad2.SetBottomMargin(0.0)

    pad3 = TPad("pad3", "", 0.38, 0.025, 0.94, 0.25)
    pad2.SetTopMargin(0.05)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.45)
    pad2.SetBottomMargin(0.2)

    pad1.Draw()
    pad2.Draw()
    pad3.Draw()

    #* Pad 1 *#
    pad1.cd()
    leg3 = myLegend(coordinate=[0.65, 0.4, 0.75, 0.5])

    xaxisname = arr.array('d', [1, 2])
    zero1 = np.zeros(2)

    gPad.Modified()
    gPad.SetGridy()

    gr1 = TGraphErrors(2, xaxisname, ttMC_fraction, zero1, ttMC_error)
    gr1.SetTitle("t#bar{t}")
    gr1.SetLineColor(870)
    gr1.SetLineWidth(3)
    gr1.SetMarkerStyle(20)
    gr1.SetMarkerColor(870)
    leg3.AddEntry(gr1, "t#bar{t}", "lep")

    gr2 = TGraphErrors(2, xaxisname, ttData_fraction, zero1, ttData_error)
    gr2.SetTitle("t#bar{t} Data")
    gr2.SetLineColor(1)
    gr2.SetLineWidth(2)
    gr2.SetMarkerStyle(20)
    gr2.SetMarkerColor(1)
    leg3.AddEntry(gr2, "t#bar{t} Data", "lep")

    mg = TMultiGraph("mg", "")
    mg.Add(gr1)
    mg.Add(gr2)
    mg.GetHistogram().SetMaximum(1.5)
    mg.GetHistogram().SetMinimum(0)
    mg.GetYaxis().SetTitle("Fraction")
    mg.GetXaxis().SetLimits(0, 3)
    mg.GetXaxis().SetTickLength(0.03)
    mg.GetXaxis().SetNdivisions(103)
    mg.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Fail")
    mg.GetXaxis().ChangeLabel(1, -1, 0)
    mg.GetXaxis().ChangeLabel(-1, -1, 0)
    mg.GetXaxis().ChangeLabel(3, -1, -1, -1, -1, -1, "Pass")
    mg.Draw("AP")
    leg3.Draw()

    lt3 = TLatex()
    if ana_ == "Inclusive":
        lt3.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt3.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt3.DrawLatexNDC(0.19, 0.855,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt3.DrawLatexNDC(0.19, 0.805, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt3.DrawLatexNDC(0.19, 0.755, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt3.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt3.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")
    lt3.Draw()

    pad1.Update()

    #* Pad 2 *#
    pad2.cd()

    MCpassMerge.SetFillColor(0)
    MCpassMerge.SetLineColor(870)
    MCpassMerge.SetLineWidth(3)
    MCpassMerge.SetMarkerColor(870)
    MCpassMerge.SetMarkerStyle(20)
    MCpassMerge.GetYaxis().SetTitle("Fraction")
    MCpassMerge.GetYaxis().SetTitleSize(0.09)
    MCpassMerge.GetYaxis().SetLabelSize(0.1)
    MCpassMerge.GetYaxis().SetNdivisions(404)
    MCpassMerge.SetMaximum(0.3)
    MCpassMerge.SetMinimum(0.0)
    MCpassMerge.GetXaxis().SetTitle("")
    MCpassMerge.GetXaxis().SetLabelOffset(0.02)
    MCpassMerge.GetXaxis().SetLabelSize(0.09)
    MCpassMerge.GetXaxis().SetNdivisions(104)
    MCpassMerge.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Pass")
    MCpassMerge.GetXaxis().ChangeLabel(1, -1, 0)
    MCpassMerge.GetXaxis().ChangeLabel(-1, -1, 0)

    datapassMerge.SetFillColor(0)
    datapassMerge.SetLineColor(1)
    datapassMerge.SetLineWidth(2)
    datapassMerge.SetMarkerColor(1)
    datapassMerge.SetMarkerStyle(20)

    MCpassMerge.Draw("e1")
    datapassMerge.Draw("e1histsame")

    #* Pad 3 *#
    pad3.cd()

    SF = sfMerge.Integral()
    print "******"
    print "mistag SF:", SF

    SFfinal = round(SF, 3)
    SFtext = "SF = " + str(SFfinal)

    mistagSFmax = SF + 0.2
    mistagSFmin = SF - 0.2

    sfMerge.SetLineColor(797)
    sfMerge.SetMarkerColor(797)
    sfMerge.SetLineWidth(3)
    sfMerge.SetMaximum(mistagSFmax)
    sfMerge.SetMinimum(mistagSFmin)
    sfMerge.GetXaxis().SetTitle(" ")
    sfMerge.GetXaxis().SetLabelOffset(999)
    sfMerge.GetXaxis().SetLabelSize(0)
    sfMerge.GetXaxis().SetTickLength(0)
    sfMerge.GetYaxis().SetLabelSize(0.1)
    sfMerge.GetYaxis().SetNdivisions(404)
    sfMerge.GetYaxis().SetTitle(" ")

    sfMerge.Draw("e1hist")

    pt = TPaveText(0.21, 0.72, 0.31, 0.8, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.SetTextSize(0.1)
    pt.AddText(SFtext)
    pt.Draw()

    c3.SaveAs(dir + "Merge_SF.pdf")  #

    passedBfrSubtactDataMerge = (passedTopEdataBfrSubtract +
                                 passedTopMudataBfrSubtract).Integral()
    failedBfrSubtractDataMerge = (failedTopEdataBfrSubtract +
                                  failedTopMudataBfrSubtract).Integral()

    passbackground = (wjetsTopEpassed + wjetsTopMupassed + dibosonTopEpassed +
                      dibosonTopMupassed + stTopEpassed +
                      stTopMupassed).Integral()
    failbackground = (wjetsTopEfailed + wjetsTopMufailed + dibosonTopEfailed +
                      dibosonTopMufailed + stTopEfailed +
                      stTopMufailed).Integral()
    totalbackground = (wjetsMerge + dibosonMerge + stMerge).Integral()

    #get the statistical uncertainty#

    dx = ttData_error[1]
    print "data efficiency error", dx

    dy = ttMC_error[1]
    print "MC efficiency error", dy

    x = datapassMerge.Integral()
    y = MCpassMerge.Integral()

    statUnc = TMath.Sqrt(((dx**2) / (y**2)) + ((x**2) * (dy**2) / (y**4)))
    #print "statistical Uncertainty in Top (e+muon) CR", statUnc
    #print " "
    print "relative statistical Uncertainty in Top (e+muon) CR", statUnc / SF * 100, " %"
    print " "

    print "DDB Mistag SF and stat: ", round(SF, 3), " +- ", round(statUnc,
                                                                  3), " (stat)"
    #print "theoretical statistical uncertainty of data efficiency", TMath.Sqrt((x*(1-x))/(subtractedDataMerge.Integral()))
    #print "theoretical statistical uncertainty of MC efficiency", TMath.Sqrt((y*(1-y))/(totalMCmerge.Integral()))
    #print " "

    header = ["Process", "Number of Events", "Top (e+muon)"]
    row1 = [
        " ", "DDB mistag SF",
        str(SFfinal) + " +- " + str(round(statUnc, 3)) + " (stat)"
    ]
    row2 = ["tt MC", "Pass (not normalized)", ""]
    row3 = [
        " ", "Pass (normalized)",
        str(round(passMCsubtractMerge.Integral(), 2))
    ]
    row4 = [" ", "Fail (not normalized)", ""]
    row5 = [
        " ", "Fail (normalized)",
        str(round(failMCsubtractMerge.Integral(), 2))
    ]
    row6 = [" ", "Total (not normalized)", ""]
    row7 = [" ", "Total (normalized)", str(round(totalMCmerge.Integral(), 2))]

    inforMC = [row2, row3, row4, row5, row6, row7]

    row8 = [
        "tt DATA", "Pass (before subtraction)",
        str(round(passedBfrSubtactDataMerge, 2))
    ]
    row9 = [" ", "Pass (after subtraction)", str(round(passdata, 2))]
    row10 = [
        " ", "Fail (before subtraction)",
        str(round(failedBfrSubtractDataMerge, 2))
    ]
    row11 = [" ", "Fail (after subtraction)", str(round(faildata, 2))]
    row12 = [
        " ", "Total (before subtraction)",
        str(round(unsubtractedDataMerge.Integral(), 2))
    ]
    row13 = [" ", "Total (after subtraction)", str(round(totaldata, 2))]

    inforDATA = [row8, row9, row10, row11, row12, row13]

    row14 = ["Background", "Pass (normalized)", str(round(passbackground, 2))]
    row15 = [" ", "Fail (normalized)", str(round(failbackground, 2))]
    row16 = [" ", "Total (normalized)", str(round(totalbackground, 2))]

    inforBKG = [row14, row15, row16]

    DDB_mistagSF.makeTable(header, row1, inforMC, inforDATA, inforBKG)
Exemplo n.º 24
0
def signal(channel, stype):
    if 'VBF' in channel:
        stype = 'XZHVBF'
    else:
        stype = 'XZH'
    # HVT model
    if stype.startswith('X'):
        signalType = 'HVT'
        genPoints = [800, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000, 3500, 4000, 4500, 5000]
        massPoints = [x for x in range(800, 5000+1, 100)]
        interPar = True
    else:
        print "Signal type", stype, "not recognized"
        return
    
    n = len(genPoints)  
    
    category = channel
    cColor = color[category] if category in color else 1

    nElec = channel.count('e')
    nMuon = channel.count('m')
    nLept = nElec + nMuon
    nBtag = channel.count('b')
    if '0b' in channel:
        nBtag = 0

    X_name = "VH_mass"

    if not os.path.exists(PLOTDIR+stype+category): os.makedirs(PLOTDIR+stype+category)

    #*******************************************************#
    #                                                       #
    #              Variables and selections                 #
    #                                                       #
    #*******************************************************#
    X_mass = RooRealVar(  "X_mass",    "m_{ZH}",       XBINMIN, XBINMAX, "GeV")
    J_mass = RooRealVar(  "H_mass",   "jet mass",        LOWMIN, HIGMAX, "GeV")
    V_mass = RooRealVar(  "V_mass", "V jet mass",           -9.,  1.e6, "GeV")
    CSV1    = RooRealVar( "H_csv1",           "",         -999.,     2.     )
    CSV2    = RooRealVar( "H_csv2",           "",         -999.,     2.     )
    DeepCSV1= RooRealVar( "H_deepcsv1",       "",         -999.,     2.     )
    DeepCSV2= RooRealVar( "H_deepcsv2",       "",         -999.,     2.     )
    H_ntag  = RooRealVar( "H_ntag",           "",           -9.,     9.     )
    H_dbt   = RooRealVar( "H_dbt",            "",           -2.,     2.     )
    H_tau21 = RooRealVar( "H_tau21",          "",           -9.,     2.     )
    H_eta = RooRealVar( "H_eta",              "",           -9.,     9.     )
    H_tau21_ddt = RooRealVar( "H_ddt",  "",           -9.,     2.     )
    MaxBTag = RooRealVar( "MaxBTag",          "",          -10.,     2.     )
    H_chf   = RooRealVar( "H_chf",            "",           -1.,     2.     )
    MinDPhi = RooRealVar( "MinDPhi",          "",           -1.,    99.     )
    DPhi    = RooRealVar( "DPhi",             "",           -1.,    99.     )
    DEta    = RooRealVar( "DEta",             "",           -1.,    99.     )
    Mu1_relIso = RooRealVar( "Mu1_relIso",    "",           -1.,    99.     )
    Mu2_relIso = RooRealVar( "Mu2_relIso",    "",           -1.,    99.     )
    nTaus   = RooRealVar( "nTaus",            "",           -1.,    99.     )
    Vpt     = RooRealVar( "V.Pt()",           "",           -1.,   1.e6     )
    V_pt     = RooRealVar( "V_pt",            "",           -1.,   1.e6     )
    H_pt     = RooRealVar( "H_pt",            "",           -1.,   1.e6     )
    VH_deltaR=RooRealVar( "VH_deltaR",        "",           -1.,    99.     )
    isZtoNN = RooRealVar( "isZtoNN",          "",            0.,     2.     )
    isZtoEE = RooRealVar( "isZtoEE",          "",            0.,     2.     )
    isZtoMM = RooRealVar( "isZtoMM",          "",            0.,     2.     )
    isHtobb = RooRealVar( "isHtobb",          "",            0.,     2.     )
    isVBF   = RooRealVar( "isVBF",            "",            0.,     2.     )
    isMaxBTag_loose = RooRealVar( "isMaxBTag_loose", "",     0.,     2.     )
    weight  = RooRealVar( "eventWeightLumi",  "",         -1.e9,   1.e9     )

    Xmin = XBINMIN
    Xmax = XBINMAX

    # Define the RooArgSet which will include all the variables defined before
    # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add'
    variables = RooArgSet(X_mass, J_mass, V_mass, CSV1, CSV2, H_ntag, H_dbt, H_tau21)
    variables.add(RooArgSet(DEta, DPhi, MaxBTag, MinDPhi, nTaus, Vpt))
    variables.add(RooArgSet(DeepCSV1, DeepCSV2,VH_deltaR, H_tau21_ddt))
    variables.add(RooArgSet(isZtoNN, isZtoEE, isZtoMM, isHtobb, isMaxBTag_loose, weight))
    variables.add(RooArgSet(isVBF, Mu1_relIso, Mu2_relIso, H_chf, H_pt, V_pt,H_eta))
    #X_mass.setRange("X_extended_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_integration_range", Xmin, Xmax)
    X_mass.setBins(int((X_mass.getMax() - X_mass.getMin())/100))
    binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax())
    X_mass.setBinning(binsXmass, "PLOT")
    massArg = RooArgSet(X_mass)

    # Cuts
    SRcut = selection[category]+selection['SR']
    print "  Cut:\t", SRcut
    #*******************************************************#
    #                                                       #
    #                    Signal fits                        #
    #                                                       #
    #*******************************************************#

    treeSign = {}
    setSignal = {}

    vmean  = {}
    vsigma = {}
    valpha1 = {}
    vslope1 = {}
    smean  = {}
    ssigma = {}
    salpha1 = {}
    sslope1 = {}
    salpha2 = {}
    sslope2 = {}
    a1 = {}
    a2 = {}
    sbrwig = {}
    signal = {}
    signalExt = {}
    signalYield = {}
    signalIntegral = {}
    signalNorm = {}
    signalXS = {}
    frSignal = {}
    frSignal1 = {}
    frSignal2 = {}
    frSignal3 = {}

    # Signal shape uncertainties (common amongst all mass points)
    xmean_fit = RooRealVar("sig_p1_fit", "Variation of the resonance position with the fit uncertainty", 0.005, -1., 1.)
    smean_fit = RooRealVar("CMSRunII_sig_p1_fit", "Change of the resonance position with the fit uncertainty", 0., -10, 10)
    xmean_jes = RooRealVar("sig_p1_scale_jes", "Variation of the resonance position with the jet energy scale", 0.010, -1., 1.) #0.001
    smean_jes = RooRealVar("CMSRunII_sig_p1_jes", "Change of the resonance position with the jet energy scale", 0., -10, 10)
    xmean_e = RooRealVar("sig_p1_scale_e", "Variation of the resonance position with the electron energy scale", 0.001, -1., 1.)
    smean_e = RooRealVar("CMSRunII_sig_p1_scale_e", "Change of the resonance position with the electron energy scale", 0., -10, 10)
    xmean_m = RooRealVar("sig_p1_scale_m", "Variation of the resonance position with the muon energy scale", 0.001, -1., 1.)
    smean_m = RooRealVar("CMSRunII_sig_p1_scale_m", "Change of the resonance position with the muon energy scale", 0., -10, 10)

    xsigma_fit = RooRealVar("sig_p2_fit", "Variation of the resonance width with the fit uncertainty", 0.02, -1., 1.)
    ssigma_fit = RooRealVar("CMSRunII_sig_p2_fit", "Change of the resonance width with the fit uncertainty", 0., -10, 10)
    xsigma_jes = RooRealVar("sig_p2_scale_jes", "Variation of the resonance width with the jet energy scale", 0.010, -1., 1.) #0.001
    ssigma_jes = RooRealVar("CMSRunII_sig_p2_jes", "Change of the resonance width with the jet energy scale", 0., -10, 10)
    xsigma_jer = RooRealVar("sig_p2_scale_jer", "Variation of the resonance width with the jet energy resolution", 0.020, -1., 1.)
    ssigma_jer = RooRealVar("CMSRunII_sig_p2_jer", "Change of the resonance width with the jet energy resolution", 0., -10, 10)
    xsigma_e = RooRealVar("sig_p2_scale_e", "Variation of the resonance width with the electron energy scale", 0.001, -1., 1.)
    ssigma_e = RooRealVar("CMSRunII_sig_p2_scale_e", "Change of the resonance width with the electron energy scale", 0., -10, 10)
    xsigma_m = RooRealVar("sig_p2_scale_m", "Variation of the resonance width with the muon energy scale", 0.040, -1., 1.)
    ssigma_m = RooRealVar("CMSRunII_sig_p2_scale_m", "Change of the resonance width with the muon energy scale", 0., -10, 10)
    
    xalpha1_fit = RooRealVar("sig_p3_fit", "Variation of the resonance alpha with the fit uncertainty", 0.03, -1., 1.)
    salpha1_fit = RooRealVar("CMSRunII_sig_p3_fit", "Change of the resonance alpha with the fit uncertainty", 0., -10, 10)
    
    xslope1_fit = RooRealVar("sig_p4_fit", "Variation of the resonance slope with the fit uncertainty", 0.10, -1., 1.)
    sslope1_fit = RooRealVar("CMSRunII_sig_p4_fit", "Change of the resonance slope with the fit uncertainty", 0., -10, 10)

    xmean_fit.setConstant(True)
    smean_fit.setConstant(True)
    xmean_jes.setConstant(True)
    smean_jes.setConstant(True)
    xmean_e.setConstant(True)
    smean_e.setConstant(True)
    xmean_m.setConstant(True)
    smean_m.setConstant(True)
    
    xsigma_fit.setConstant(True)
    ssigma_fit.setConstant(True)
    xsigma_jes.setConstant(True)
    ssigma_jes.setConstant(True)
    xsigma_jer.setConstant(True)
    ssigma_jer.setConstant(True)
    xsigma_e.setConstant(True)
    ssigma_e.setConstant(True)
    xsigma_m.setConstant(True)
    ssigma_m.setConstant(True)
    
    xalpha1_fit.setConstant(True)
    salpha1_fit.setConstant(True)
    xslope1_fit.setConstant(True)
    sslope1_fit.setConstant(True)

    # the alpha method is now done.
    for m in massPoints:
        signalString = "M%d" % m
        signalMass = "%s_M%d" % (stype, m)
        signalName = "%s%s_M%d" % (stype, category, m)
        signalColor = sample[signalMass]['linecolor'] if signalName in sample else 1

        # define the signal PDF
        vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m, m*0.5, m*1.25)
        smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)", RooArgList(vmean[m], xmean_e, smean_e, xmean_m, smean_m, xmean_jes, smean_jes, xmean_fit, smean_fit))

        vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma", m*0.035, m*0.01, m*0.4)
        sigmaList = RooArgList(vsigma[m], xsigma_e, ssigma_e, xsigma_m, ssigma_m, xsigma_jes, ssigma_jes, xsigma_jer, ssigma_jer)
        sigmaList.add(RooArgList(xsigma_fit, ssigma_fit))
        ssigma[m] = RooFormulaVar(signalName + "_sigma", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)*(1+@9*@10)", sigmaList)
        
        valpha1[m] = RooRealVar(signalName + "_valpha1", "Crystal Ball alpha", 1.,  0., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0*(1+@1*@2)", RooArgList(valpha1[m], xalpha1_fit, salpha1_fit))

        vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope", 10., 1., 60.) # slope of the power tail   #10 1 60
        sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0*(1+@1*@2)", RooArgList(vslope1[m], xslope1_fit, sslope1_fit))

        salpha2[m] = RooRealVar(signalName + "_alpha2", "Crystal Ball alpha", 2,  1., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        sslope2[m] = RooRealVar(signalName + "_slope2", "Crystal Ball slope", 10, 1.e-1, 115.) # slope of the power tail
        #define polynomial
        #a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", m, 0.5*m, 2*m)
        a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", 0.001*m, 0.0005*m, 0.01*m)
        a2[m] = RooRealVar(signalName + "_a2", "par 2 for polynomial", 0.05, -1.,1.)
        #if channel=='nnbbVBF' or channel=='nn0bVBF':
        #    signal[m] = RooPolynomial(signalName,"m_{%s'} = %d GeV" % (stype[1], m) , X_mass, RooArgList(a1[m],a2[m]))
        #else:
        #    signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel
        signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel
        # extend the PDF with the yield to perform an extended likelihood fit
        signalYield[m] = RooRealVar(signalName+"_yield", "signalYield", 100, 0., 1.e6)
        signalNorm[m] = RooRealVar(signalName+"_norm", "signalNorm", 1., 0., 1.e6)
        signalXS[m] = RooRealVar(signalName+"_xs", "signalXS", 1., 0., 1.e6)
        signalExt[m] = RooExtendPdf(signalName+"_ext", "extended p.d.f", signal[m], signalYield[m])
        
        vslope1[m].setMax(50.)
        vslope1[m].setVal(20.)
        #valpha1[m].setVal(1.0)
        #valpha1[m].setConstant(True)
        
        if 'bb' in channel and 'VBF' not in channel:
            if 'nn' in channel:
                valpha1[m].setVal(0.5)
        elif '0b' in channel and 'VBF' not in channel:
            if 'nn' in channel:
                if m==800:
                    valpha1[m].setVal(2.)
                    vsigma[m].setVal(m*0.04)
            elif 'ee' in channel:
                valpha1[m].setVal(0.8)
                if m==800:
                    #valpha1[m].setVal(1.2)
                    valpha1[m].setVal(2.5)
                    vslope1[m].setVal(50.)
            elif 'mm' in channel:
                if m==800:
                    valpha1[m].setVal(2.)
                    vsigma[m].setVal(m*0.03)
                else:
                    vmean[m].setVal(m*0.9)
                    vsigma[m].setVal(m*0.08)
        elif 'bb' in channel and 'VBF' in channel:
            if 'nn' in channel:
                if m!=1800:
                    vmean[m].setVal(m*0.8)
                vsigma[m].setVal(m*0.08)
                valpha1[m].setMin(1.)
            elif 'ee' in channel:
                valpha1[m].setVal(0.7)
            elif 'mm' in channel:
                if m==800:
                    vslope1[m].setVal(50.)
                valpha1[m].setVal(0.7)
        elif '0b' in channel and 'VBF' in channel:
            if 'nn' in channel:
                valpha1[m].setVal(3.) 
                vmean[m].setVal(m*0.8)
                vsigma[m].setVal(m*0.08)
                valpha1[m].setMin(1.)
            elif 'ee' in channel:
                if m<2500:
                    valpha1[m].setVal(2.)
                if m==800:
                    vsigma[m].setVal(m*0.05)
                elif m==1000:
                    vsigma[m].setVal(m*0.03)
                elif m>1000 and m<1800:
                    vsigma[m].setVal(m*0.04)
            elif 'mm' in channel:
                if m<2000:
                    valpha1[m].setVal(2.)
                if m==1000 or m==1800:
                    vsigma[m].setVal(m*0.03)
                elif m==1200 or m==1600:
                    vsigma[m].setVal(m*0.04)

            
        #if m < 1000: vsigma[m].setVal(m*0.06)

        # If it's not the proper channel, make it a gaussian
        #if nLept==0 and 'VBF' in channel:
        #    valpha1[m].setVal(5)
        #    valpha1[m].setConstant(True)
        #    vslope1[m].setConstant(True)
        #    salpha2[m].setConstant(True)
        #    sslope2[m].setConstant(True)

        
        # ---------- if there is no simulated signal, skip this mass point ----------
        if m in genPoints:
            if VERBOSE: print " - Mass point", m

            # define the dataset for the signal applying the SR cuts
            treeSign[m] = TChain("tree")
            for j, ss in enumerate(sample[signalMass]['files']):
                treeSign[m].Add(NTUPLEDIR + ss + ".root")
            
            if treeSign[m].GetEntries() <= 0.:
                if VERBOSE: print " - 0 events available for mass", m, "skipping mass point..."
                signalNorm[m].setVal(-1)
                vmean[m].setConstant(True)
                vsigma[m].setConstant(True)
                salpha1[m].setConstant(True)
                sslope1[m].setConstant(True)
                salpha2[m].setConstant(True)
                sslope2[m].setConstant(True)
                signalNorm[m].setConstant(True)
                signalXS[m].setConstant(True)
                continue
            
            setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar(weight), RooFit.Import(treeSign[m]))
            if VERBOSE: print " - Dataset with", setSignal[m].sumEntries(), "events loaded"
            
            # FIT
            signalYield[m].setVal(setSignal[m].sumEntries())
            
            if treeSign[m].GetEntries(SRcut) > 5:
                if VERBOSE: print " - Running fit"
 
                frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1), RooFit.Extended(True), RooFit.SumW2Error(True), RooFit.PrintLevel(-1))
                if VERBOSE: print "********** Fit result [", m, "] **", category, "*"*40, "\n", frSignal[m].Print(), "\n", "*"*80
                if VERBOSE: frSignal[m].correlationMatrix().Print()
                drawPlot(signalMass, stype+channel, X_mass, signal[m], setSignal[m], frSignal[m])
            
            else:
                print "  WARNING: signal", stype, "and mass point", m, "in channel", channel, "has 0 entries or does not exist"          
            # Remove HVT cross section (which is the same for Zlep and Zinv)
            if stype == "XZHVBF":
                sample_name = 'Zprime_VBF_Zh_Zlephinc_narrow_M-%d' % m
            else:
                sample_name = 'ZprimeToZHToZlepHinc_narrow_M%d' % m

            xs = xsection[sample_name]['xsec']
            
            signalXS[m].setVal(xs * 1000.)
            
            signalIntegral[m] = signalExt[m].createIntegral(massArg, RooFit.NormSet(massArg), RooFit.Range("X_integration_range"))
            boundaryFactor = signalIntegral[m].getVal()
            if VERBOSE: 
                print " - Fit normalization vs integral:", signalYield[m].getVal(), "/", boundaryFactor, "events"
            if channel=='nnbb' and m==5000:
                signalNorm[m].setVal(2.5)
            elif channel=='nn0b' and m==5000:
                signalNorm[m].setVal(6.7)
            else:
                signalNorm[m].setVal( boundaryFactor * signalYield[m].getVal() / signalXS[m].getVal()) # here normalize to sigma(X) x Br(X->VH) = 1 [fb]
            
            
        a1[m].setConstant(True)
        a2[m].setConstant(True)
        vmean[m].setConstant(True)
        vsigma[m].setConstant(True)
        valpha1[m].setConstant(True)
        vslope1[m].setConstant(True)
        salpha2[m].setConstant(True)
        sslope2[m].setConstant(True)
        signalNorm[m].setConstant(True)
        signalXS[m].setConstant(True)

    #*******************************************************#
    #                                                       #
    #                 Signal interpolation                  #
    #                                                       #
    #*******************************************************#


    # ====== CONTROL PLOT ======
    c_signal = TCanvas("c_signal", "c_signal", 800, 600)
    c_signal.cd()
    frame_signal = X_mass.frame()
    for m in genPoints[:-2]:
        if m in signalExt.keys():
            signal[m].plotOn(frame_signal, RooFit.LineColor(sample["%s_M%d" % (stype, m)]['linecolor']), RooFit.Normalization(signalNorm[m].getVal(), RooAbsReal.NumEvent), RooFit.Range("X_reasonable_range"))
    frame_signal.GetXaxis().SetRangeUser(0, 6500)
    frame_signal.Draw()
    drawCMS(-1, YEAR, "Simulation")
    drawAnalysis(channel)
    drawRegion(channel)
    c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.pdf")
    c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.png")
    #if VERBOSE: raw_input("Press Enter to continue...")
    # ====== CONTROL PLOT ======

    # Normalization
    gnorm = TGraphErrors()
    gnorm.SetTitle(";m_{X} (GeV);integral (GeV)")
    gnorm.SetMarkerStyle(20)
    gnorm.SetMarkerColor(1)
    gnorm.SetMaximum(0)
    inorm = TGraphErrors()
    inorm.SetMarkerStyle(24)
    fnorm = TF1("fnorm", "pol9", 800, 5000) #"pol5" if not channel=="XZHnnbb" else "pol6" #pol5*TMath::Floor(x-1800) + ([5]*x + [6]*x*x)*(1-TMath::Floor(x-1800))
    fnorm.SetLineColor(920)
    fnorm.SetLineStyle(7)
    fnorm.SetFillColor(2)
    fnorm.SetLineColor(cColor)

    # Mean
    gmean = TGraphErrors()
    gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)")
    gmean.SetMarkerStyle(20)
    gmean.SetMarkerColor(cColor)
    gmean.SetLineColor(cColor)
    imean = TGraphErrors()
    imean.SetMarkerStyle(24)
    fmean = TF1("fmean", "pol1", 0, 5000)
    fmean.SetLineColor(2)
    fmean.SetFillColor(2)

    # Width
    gsigma = TGraphErrors()
    gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)")
    gsigma.SetMarkerStyle(20)
    gsigma.SetMarkerColor(cColor)
    gsigma.SetLineColor(cColor)
    isigma = TGraphErrors()
    isigma.SetMarkerStyle(24)
    fsigma = TF1("fsigma", "pol1", 0, 5000)
    fsigma.SetLineColor(2)
    fsigma.SetFillColor(2)

    # Alpha1
    galpha1 = TGraphErrors()
    galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha")
    galpha1.SetMarkerStyle(20)
    galpha1.SetMarkerColor(cColor)
    galpha1.SetLineColor(cColor)
    ialpha1 = TGraphErrors()
    ialpha1.SetMarkerStyle(24)
    falpha1 = TF1("falpha", "pol0", 0, 5000)
    falpha1.SetLineColor(2)
    falpha1.SetFillColor(2)

    # Slope1
    gslope1 = TGraphErrors()
    gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)")
    gslope1.SetMarkerStyle(20)
    gslope1.SetMarkerColor(cColor)
    gslope1.SetLineColor(cColor)
    islope1 = TGraphErrors()
    islope1.SetMarkerStyle(24)
    fslope1 = TF1("fslope", "pol0", 0, 5000)
    fslope1.SetLineColor(2)
    fslope1.SetFillColor(2)

    # Alpha2
    galpha2 = TGraphErrors()
    galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha")
    galpha2.SetMarkerStyle(20)
    galpha2.SetMarkerColor(cColor)
    galpha2.SetLineColor(cColor)
    ialpha2 = TGraphErrors()
    ialpha2.SetMarkerStyle(24)
    falpha2 = TF1("falpha", "pol0", 0, 5000)
    falpha2.SetLineColor(2)
    falpha2.SetFillColor(2)

    # Slope2
    gslope2 = TGraphErrors()
    gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)")
    gslope2.SetMarkerStyle(20)
    gslope2.SetMarkerColor(cColor)
    gslope2.SetLineColor(cColor)
    islope2 = TGraphErrors()
    islope2.SetMarkerStyle(24)
    fslope2 = TF1("fslope", "pol0", 0, 5000)
    fslope2.SetLineColor(2)
    fslope2.SetFillColor(2)



    n = 0
    for i, m in enumerate(genPoints):
        if not m in signalNorm.keys(): continue
        if signalNorm[m].getVal() < 1.e-6: continue
        signalString = "M%d" % m
        signalName = "%s_M%d" % (stype, m)

        if gnorm.GetMaximum() < signalNorm[m].getVal(): gnorm.SetMaximum(signalNorm[m].getVal())
        gnorm.SetPoint(n, m, signalNorm[m].getVal())
        gmean.SetPoint(n, m, vmean[m].getVal())
        gmean.SetPointError(n, 0, min(vmean[m].getError(), vmean[m].getVal()*0.02))
        gsigma.SetPoint(n, m, vsigma[m].getVal())
        gsigma.SetPointError(n, 0, min(vsigma[m].getError(), vsigma[m].getVal()*0.05))
        galpha1.SetPoint(n, m, valpha1[m].getVal())
        galpha1.SetPointError(n, 0, min(valpha1[m].getError(), valpha1[m].getVal()*0.10))
        gslope1.SetPoint(n, m, vslope1[m].getVal())
        gslope1.SetPointError(n, 0, min(vslope1[m].getError(), vslope1[m].getVal()*0.10))
        galpha2.SetPoint(n, m, salpha2[m].getVal())
        galpha2.SetPointError(n, 0, min(salpha2[m].getError(), salpha2[m].getVal()*0.10))
        gslope2.SetPoint(n, m, sslope2[m].getVal())
        gslope2.SetPointError(n, 0, min(sslope2[m].getError(), sslope2[m].getVal()*0.10))
        n = n + 1
    print "fit on gmean:"
    gmean.Fit(fmean, "Q0", "SAME")
    print "fit on gsigma:"
    gsigma.Fit(fsigma, "Q0", "SAME")
    print "fit on galpha:"
    galpha1.Fit(falpha1, "Q0", "SAME")
    print "fit on gslope:"
    gslope1.Fit(fslope1, "Q0", "SAME")
    galpha2.Fit(falpha2, "Q0", "SAME")
    gslope2.Fit(fslope2, "Q0", "SAME")
    #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S"))
    gnorm.Fit(fnorm, "Q", "SAME", 700, 5000)

    for m in massPoints:
        signalName = "%s_M%d" % (stype, m)
        
        if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.)

        # Interpolation method
        syield = gnorm.Eval(m)
        spline = gnorm.Eval(m, 0, "S")
        sfunct = fnorm.Eval(m)
        
        #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield))
        delta = abs(1.-spline/sfunct) if sfunct > 0 else 0
        syield = spline
               
        if interPar:
            jmean = gmean.Eval(m)
            jsigma = gsigma.Eval(m)
            jalpha1 = galpha1.Eval(m)
            jslope1 = gslope1.Eval(m)
        else:
            jmean = fmean.GetParameter(0) + fmean.GetParameter(1)*m + fmean.GetParameter(2)*m*m
            jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(1)*m + fsigma.GetParameter(2)*m*m
            jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(1)*m + falpha1.GetParameter(2)*m*m
            jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(1)*m + fslope1.GetParameter(2)*m*m

        inorm.SetPoint(inorm.GetN(), m, syield)
        signalNorm[m].setVal(syield)

        imean.SetPoint(imean.GetN(), m, jmean)
        if jmean > 0: vmean[m].setVal(jmean)

        isigma.SetPoint(isigma.GetN(), m, jsigma)
        if jsigma > 0: vsigma[m].setVal(jsigma)

        ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1)
        if not jalpha1==0: valpha1[m].setVal(jalpha1)

        islope1.SetPoint(islope1.GetN(), m, jslope1)
        if jslope1 > 0: vslope1[m].setVal(jslope1)
    

    c1 = TCanvas("c1", "Crystal Ball", 1200, 800)
    c1.Divide(2, 2)
    c1.cd(1)
    gmean.SetMinimum(0.)
    gmean.Draw("APL")
    imean.Draw("P, SAME")
    drawRegion(channel)
    c1.cd(2)
    gsigma.SetMinimum(0.)
    gsigma.Draw("APL")
    isigma.Draw("P, SAME")
    drawRegion(channel)
    c1.cd(3)
    galpha1.Draw("APL")
    ialpha1.Draw("P, SAME")
    drawRegion(channel)
    galpha1.GetYaxis().SetRangeUser(0., 5.)
    c1.cd(4)
    gslope1.Draw("APL")
    islope1.Draw("P, SAME")
    drawRegion(channel)
    gslope1.GetYaxis().SetRangeUser(0., 125.)
    if False:
        c1.cd(5)
        galpha2.Draw("APL")
        ialpha2.Draw("P, SAME")
        drawRegion(channel)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(channel)
        gslope2.GetYaxis().SetRangeUser(0., 10.)


    c1.Print(PLOTDIR+stype+category+"/"+stype+"_SignalShape.pdf")
    c1.Print(PLOTDIR+stype+category+"/"+stype+"_SignalShape.png")


    c2 = TCanvas("c2", "Signal Efficiency", 800, 600)
    c2.cd(1)
    gnorm.SetMarkerColor(cColor)
    gnorm.SetMarkerStyle(20)
    gnorm.SetLineColor(cColor)
    gnorm.SetLineWidth(2)
    gnorm.Draw("APL")
    inorm.Draw("P, SAME")
    gnorm.GetXaxis().SetRangeUser(genPoints[0]-100, genPoints[-1]+100)
    gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum()*1.25)
    drawCMS(-1,YEAR , "Simulation")
    drawAnalysis(channel)
    drawRegion(channel)
    c2.Print(PLOTDIR+stype+category+"/"+stype+"_SignalNorm.pdf")
    c2.Print(PLOTDIR+stype+category+"/"+stype+"_SignalNorm.png")





    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    # create workspace
    w = RooWorkspace("ZH_RunII", "workspace")
    for m in massPoints:
        getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName()))
        getattr(w, "import")(signalNorm[m], RooFit.Rename(signalNorm[m].GetName()))
        getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName()))
    w.writeToFile("%s%s.root" % (WORKDIR, stype+channel), True)
    print "Workspace", "%s%s.root" % (WORKDIR, stype+channel), "saved successfully"
    sys.exit()
Exemplo n.º 25
0
    c1.SetLogy(False)

    y.append(1.08)
    y.append(1.1)
    y.append(1.15)
    y.append(1.2)
    y.append(1.2)
    y.append(1.22)
    y.append(1.22)

    n = len(x)
    gr0 = TGraphErrors(n, x, y, ex, ey)

    gr0.SetMarkerColor(ROOT.kBlue)
    gr0.SetMarkerStyle(20)
    gr0.SetLineColor(ROOT.kBlue)
    gr0.SetMarkerSize(1.5)

    gr0.Draw()
    p1 = TF1("pol1", "pol1", 200, 900.)
    # p1 = TF1("pol2","pol2",200,2000.);

    p1.SetLineColor(ROOT.kMagenta)

    f1 = TF1("f1", "[0] +[1]*x", 200, 2000)
    f1.SetParameters(0.99601, 0.00241919)

    f1.SetLineColor(ROOT.kBlue)

    gr0.Fit(p1, "0R")
    p1.Draw("sames")
Exemplo n.º 26
0
    z[i] = ts_correctmass[i].GetMean()
    yerr[i] = ts_correct[i].GetMeanError()
    zerr[i] = ts_correctmass[i].GetMeanError()
    graph1.SetPoint(i, x[i], y[i])
    graph2.SetPoint(i, x[i], z[i])
    graph1.SetPointError(i, 0, yerr[i])
    graph2.SetPointError(i, 0, zerr[i])

c2.cd()
graph1.Draw("AP")
graph1.GetYaxis().SetRangeUser(52., 62.)
graph1.GetYaxis().SetTitle("Mean value")
graph1.GetXaxis().SetTitle("Top M(GeV)")
graph1.Draw("AP")
graph1.SetTitle("Mean value of the histogram vs top mass")
graph2.SetLineColor(2)
graph2.SetMarkerColor(2)
graph2.Draw("P")

# fit

graph1.Fit("pol1")
graph2.Fit("pol1")

pol1 = TF1()
pol1 = graph1.GetFunction("pol1")
pol2 = TF1()
pol2 = graph2.GetFunction("pol1")

a0 = str(round(pol1.GetParameter(0), 2))
a1 = str(round(pol1.GetParameter(1), 2))
Exemplo n.º 27
0
def generator(nuslice_tree, rootfile, pset):
    n_bins = pset.n_bins
    drift_distance = pset.DriftDistance
    bin_width = drift_distance/n_bins
    half_bin_width = bin_width/2.

    xvals = np.arange(half_bin_width, drift_distance, bin_width)
    xerrs = np.array([half_bin_width] * len(xvals))
    dist_to_anode_bins = n_bins
    dist_to_anode_low = 0.
    dist_to_anode_up = drift_distance
    profile_bins = n_bins
    profile_option = 's'  # errors are the standard deviation

    dy_spreads = [None] * n_bins
    dy_means = [None] * n_bins
    dy_hist = TH2D("dy_hist", "#Delta y",
                   dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up,
                   pset.dy_bins, pset.dy_low, pset.dy_up)
    dy_hist.GetXaxis().SetTitle("distance from anode (cm)")
    dy_hist.GetYaxis().SetTitle("y_flash - y_TPC (cm)")
    dy_prof = TProfile("dy_prof", "Profile of dy_spreads in #Delta y",
                       profile_bins, dist_to_anode_low, dist_to_anode_up,
                       pset.dy_low*2, pset.dy_up*2, profile_option)
    dy_prof.GetXaxis().SetTitle("distance from anode (cm)")
    dy_prof.GetYaxis().SetTitle("y_flash - y_TPC (cm)")
    dy_h1 = TH1D("dy_h1", "",
                 profile_bins, dist_to_anode_low, dist_to_anode_up)
    dy_h1.GetXaxis().SetTitle("distance from anode (cm)")
    dy_h1.GetYaxis().SetTitle("y_flash - y_TPC (cm)")

    dz_spreads = [None] * n_bins
    dz_means = [None] * n_bins
    dz_hist = TH2D("dz_hist", "#Delta z",
                   dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up,
                   pset.dz_bins, pset.dz_low, pset.dz_up)
    dz_hist.GetXaxis().SetTitle("distance from anode (cm)")
    dz_hist.GetYaxis().SetTitle("z_flash - z_TPC (cm)")
    dz_prof = TProfile("dz_prof", "Profile of dz_spreads in #Delta z",
                       profile_bins, dist_to_anode_low, dist_to_anode_up,
                       pset.dz_low*2.5, pset.dz_up*2.5, profile_option)
    dz_prof.GetXaxis().SetTitle("distance from anode (cm)")
    dz_prof.GetYaxis().SetTitle("z_flash - z_TPC (cm)")
    dz_h1 = TH1D("dz_h1", "",
                 profile_bins, dist_to_anode_low, dist_to_anode_up)
    dz_h1.GetXaxis().SetTitle("distance from anode (cm)")
    dz_h1.GetYaxis().SetTitle("z_flash - z_TPC (cm)")

    rr_spreads = [None] * n_bins
    rr_means = [None] * n_bins
    rr_hist = TH2D("rr_hist", "PE Spread",
                   dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up,
                   pset.rr_bins, pset.rr_low, pset.rr_up)
    rr_hist.GetXaxis().SetTitle("distance from anode (cm)")
    rr_hist.GetYaxis().SetTitle("RMS flash (cm)")
    rr_prof = TProfile("rr_prof", "Profile of PE Spread",
                       profile_bins, dist_to_anode_low, dist_to_anode_up,
                       pset.rr_low, pset.rr_up, profile_option)
    rr_prof.GetXaxis().SetTitle("distance from anode (cm)")
    rr_prof.GetYaxis().SetTitle("RMS flash (cm)")
    rr_h1 = TH1D("rr_h1", "",
                 profile_bins, dist_to_anode_low, dist_to_anode_up)
    rr_h1.GetXaxis().SetTitle("distance from anode (cm)")
    rr_h1.GetYaxis().SetTitle("RMS flash (cm)")

    if detector == "sbnd":
        pe_spreads = [None] * n_bins
        pe_means = [None] * n_bins
        pe_hist = TH2D("pe_hist", "Uncoated/Coated Ratio",
                       dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up,
                       pset.pe_bins, pset.pe_low, pset.pe_up)
        pe_hist.GetXaxis().SetTitle("distance from anode (cm)")
        pe_hist.GetYaxis().SetTitle("ratio_{uncoated/coated}")
        pe_prof = TProfile("pe_prof", "Profile of Uncoated/Coated Ratio",
                           profile_bins, dist_to_anode_low, dist_to_anode_up,
                           pset.pe_low, pset.pe_up, profile_option)
        pe_prof.GetXaxis().SetTitle("distance from anode (cm)")
        pe_prof.GetYaxis().SetTitle("ratio_{uncoated/coated}")
        pe_h1 = TH1D("pe_h1", "",
                     profile_bins, dist_to_anode_low, dist_to_anode_up)
        pe_h1.GetXaxis().SetTitle("distance from anode (cm)")
        pe_h1.GetYaxis().SetTitle("ratio_{uncoated/coated}")

    match_score_scatter = TH2D("match_score_scatter", "Scatter plot of match scores",
                               dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up,
                               pset.score_hist_bins, pset.score_hist_low, pset.score_hist_up*(3./5.))
    match_score_scatter.GetXaxis().SetTitle("distance from anode (cm)")
    match_score_scatter.GetYaxis().SetTitle("match score (arbitrary)")
    match_score_hist = TH1D("match_score", "Match Score",
                            pset.score_hist_bins, pset.score_hist_low, pset.score_hist_up)
    match_score_hist.GetXaxis().SetTitle("match score (arbitrary)")

    for e in nuslice_tree:
        slice = e.charge_x

        dy_hist.Fill(slice, e.flash_y - e.charge_y)
        dy_prof.Fill(slice, e.flash_y - e.charge_y)
        dz_hist.Fill(slice, e.flash_z - e.charge_z)
        dz_prof.Fill(slice, e.flash_z - e.charge_z)
        rr_hist.Fill(slice, e.flash_r)
        rr_prof.Fill(slice, e.flash_r)
        if detector == "sbnd":
            pe_hist.Fill(slice, e.flash_ratio)
            pe_prof.Fill(slice, e.flash_ratio)

    # fill histograms for match score calculation from profile histograms
    for ib in list(range(0, profile_bins)):
        ibp = ib + 1
        dy_h1.SetBinContent(ibp, dy_prof.GetBinContent(ibp))
        dy_h1.SetBinError(ibp, dy_prof.GetBinError(ibp))
        dy_means[int(ib)] = dy_prof.GetBinContent(ibp)
        dy_spreads[int(ib)] = dy_prof.GetBinError(ibp)
        dz_h1.SetBinContent(ibp, dz_prof.GetBinContent(ibp))
        dz_h1.SetBinError(ibp, dz_prof.GetBinError(ibp))
        dz_means[int(ib)] = dz_prof.GetBinContent(ibp)
        dz_spreads[int(ib)] = dz_prof.GetBinError(ibp)
        rr_h1.SetBinContent(ibp, rr_prof.GetBinContent(ibp))
        rr_h1.SetBinError(ibp, rr_prof.GetBinError(ibp))
        rr_means[int(ib)] = rr_prof.GetBinContent(ibp)
        rr_spreads[int(ib)] = rr_prof.GetBinError(ibp)
        if detector == "sbnd":
            pe_h1.SetBinContent(ibp, pe_prof.GetBinContent(ibp))
            pe_h1.SetBinError(ibp, pe_prof.GetBinError(ibp))
            pe_means[int(ib)] = pe_prof.GetBinContent(ibp)
            pe_spreads[int(ib)] = pe_prof.GetBinError(ibp)

    for e in nuslice_tree:
        slice = e.charge_x
        # calculate match score
        isl = int(slice/bin_width)
        score = 0.
        if dy_spreads[isl] <= 1.e-8:
            print("Warning zero spread.\n",
                  f"slice: {slice}. isl: {isl}. dy_spreads[isl]: {dy_spreads[isl]} ")
            dy_spreads[isl] = dy_spreads[isl+1]
        if dz_spreads[isl] <= 1.e-8:
            print("Warning zero spread.\n",
                  f"slice: {slice}. isl: {isl}. dz_spreads[isl]: {dz_spreads[isl]} ")
            dz_spreads[isl] = dz_spreads[isl+1]
        if rr_spreads[isl] <= 1.e-8:
            print("Warning zero spread.\n",
                  f"slice: {slice}. isl: {isl}. rr_spreads[isl]: {rr_spreads[isl]} ")
            rr_spreads[isl] = rr_spreads[isl+1]
        if detector == "sbnd" and pe_spreads[isl] <= 1.e-8:
            print("Warning zero spread.\n",
                  f"slice: {slice}. isl: {isl}. pe_spreads[isl]: {pe_spreads[isl]} ")
            pe_spreads[isl] = pe_spreads[isl+1]
        score += abs(abs(e.flash_y-e.charge_y) - dy_means[isl])/dy_spreads[isl]
        score += abs(abs(e.flash_z-e.charge_z) - dz_means[isl])/dz_spreads[isl]
        score += abs(e.flash_r-rr_means[isl])/rr_spreads[isl]
        if detector == "sbnd" and pset.UseUncoatedPMT:
            score += abs(e.flash_ratio-pe_means[isl])/pe_spreads[isl]
        match_score_scatter.Fill(slice, score)
        match_score_hist.Fill(score)
    metrics_filename = 'fm_metrics_' + detector + '.root'
    hfile = gROOT.FindObject(metrics_filename)
    if hfile:
        hfile.Close()
    hfile = TFile(metrics_filename, 'RECREATE',
                  'Simple flash matching metrics for ' + detector.upper())
    dy_hist.Write()
    dy_prof.Write()
    dy_h1.Write()
    dz_hist.Write()
    dz_prof.Write()
    dz_h1.Write()
    rr_hist.Write()
    rr_prof.Write()
    rr_h1.Write()
    if detector == "sbnd":
        pe_hist.Write()
        pe_prof.Write()
        pe_h1.Write()
    match_score_scatter.Write()
    match_score_hist.Write()
    hfile.Close()

    canv = TCanvas("canv")

    dy_hist.Draw()
    crosses = TGraphErrors(n_bins,
                           array('f', xvals), array('f', dy_means),
                           array('f', xerrs), array('f', dy_spreads))
    crosses.SetLineColor(9)
    crosses.SetLineWidth(3)
    crosses.Draw("Psame")
    canv.Print("dy.pdf")
    canv.Update()

    dz_hist.Draw()
    crosses = TGraphErrors(n_bins,
                           array('f', xvals), array('f', dz_means),
                           array('f', xerrs), array('f', dz_spreads))
    crosses.SetLineColor(9)
    crosses.SetLineWidth(3)
    crosses.Draw("Psame")
    canv.Print("dz.pdf")
    canv.Update()

    rr_hist.Draw()
    crosses = TGraphErrors(n_bins,
                           array('f', xvals), array('f', rr_means),
                           array('f', xerrs), array('f', rr_spreads))
    crosses.SetLineColor(9)
    crosses.SetLineWidth(3)
    crosses.Draw("Psame")
    canv.Print("rr.pdf")
    canv.Update()

    if detector == "sbnd":
        pe_hist.Draw()
        crosses = TGraphErrors(n_bins,
                               array('f', xvals), array('f', pe_means),
                               array('f', xerrs), array('f', pe_spreads))
        crosses.SetLineColor(9)
        crosses.SetLineWidth(3)
        crosses.Draw("Psame")
        canv.Print("pe.pdf")
        canv.Update()

    match_score_scatter.Draw()
    canv.Print("match_score_scatter.pdf")
    canv.Update()

    match_score_hist.Draw()
    canv.Print("match_score.pdf")
    canv.Update()
    sleep(20)
Exemplo n.º 28
0
  def __applyThresholdCorrection( self, refValue, sgn_hist2D, bkg_hist2D, partition_name, output_name, **kwargs):

    legend_position = retrieve_kw( kwargs, 'legend_position', (0.36,0.20,0.66,0.40))
    useNoActivationFunctionInTheLastLayer=retrieve_kw(kwargs,'useNoActivationFunctionInTheLastLayer',False)
    xname           = retrieve_kw( kwargs, 'xname', 'n_{vtx}' )
    draw            = retrieve_kw( kwargs, 'draw', False)
    limits          = retrieve_kw( kwargs, 'limits', [0,10,20])
    dovertical      = retrieve_kw( kwargs, 'dovertical'  , False)
    
    mumin = limits[0]; mumax=limits[-1]
    mubins = mumax-mumin
    from TrigEgammaDevelopments.helper.util import *
    sgn_hist2D = copy2DRegion(sgn_hist2D,1000,-12,7,mubins,mumin,mumax)
    bkg_hist2D = copy2DRegion(bkg_hist2D,1000,-12,7,mubins,mumin,mumax)



    from copy import deepcopy
    refValue_requested = refValue 
    false_alarm = 1.0
    false_alarm_limit = 0.20
    while false_alarm > false_alarm_limit:
      # Calculate the original threshold
      b0, error = find_threshold(sgn_hist2D.ProjectionX(), refValue )
      # Take eff points using uncorrection threshold
      discr_points, nvtx_points, error_points = calculate_dependent_discr_points(sgn_hist2D , refValue )
      # Calculate eff without correction
      sgn_histNum, sgn_histDen, sgn_histEff, det0   = calculate_efficiency(sgn_hist2D, refValue, b0, 0,  doCorrection=False)
      # Generate correction parameters and produce fixed plots
      sgn_histNum_corr, sgn_histDen_corr, sgn_histEff_corr, detection ,b, a = calculate_efficiency( sgn_hist2D, 
                                                          refValue, b0, 0, limits = limits, doCorretion=True)
      
      # Calculate eff without correction
      bkg_histNum, bkg_histDen, bkg_histEff, _  = calculate_efficiency(bkg_hist2D, refValue, b0, 0,  doCorrection=False)
      # Calculate eff using the correction from signal
      bkg_histNum_corr, bkg_histDen_corr, bkg_histEff_corr, false_alarm = calculate_efficiency(bkg_hist2D, refValue, b, a,  doCorrection=False)

      if false_alarm > false_alarm_limit:
        refValue-=0.025

    # To np.array
    discr_points = np.array(discr_points)

    # Plot correction 
    if draw:
      # Retrieve some usefull information
      y_max = sgn_hist2D.GetYaxis().GetXmax()
      y_min = sgn_hist2D.GetYaxis().GetXmin()
      x_min = y_min; x_max = y_max

      from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack,TLine
      from ROOT import TGraphErrors,TF1
      gStyle.SetPalette(107)
      if dovertical:
        canvas = TCanvas('canvas','canvas',1600,2000)
        canvas.Divide(2,3)
      else:
        canvas = TCanvas('canvas','canvas',2800,1600)
        canvas.Divide(3,2)

      pad1= canvas.cd(1)
      sgn_histEff.SetTitle('Signal Efficiency in: '+partition_name)
      sgn_histEff.SetLineColor(kRed)
      sgn_histEff.SetMarkerColor(kRed)
      sgn_histEff.GetYaxis().SetTitle('#epsilon('+xname+')')
      sgn_histEff.GetXaxis().SetTitle(xname)
      sgn_histEff.GetYaxis().SetRangeUser( 0.6, 1.1 ) 
      sgn_histEff.Draw()
      sgn_histEff_corr.SetLineColor(kBlack)
      sgn_histEff_corr.SetMarkerColor(kBlack)
      sgn_histEff_corr.Draw('sames')


      l0 = TLine(x_min,refValue_requested,x_max,refValue_requested)
      l0.SetLineColor(kBlack)
      l0.Draw()
 
      l1 = TLine(x_min,refValue,x_max,refValue)
      l1.SetLineColor(kBlack)
      l1.SetLineStyle(9)
      l1.Draw()
      
      leg1 = TLegend(legend_position[0],legend_position[1], legend_position[2],legend_position[3])
      setLegend1(leg1)
      leg1.SetHeader('Signal efficiency in '+partition_name)
      leg1.AddEntry(sgn_histEff,('Old: d = %1.3f')%(b0),'p' )
      lg1 = leg1.AddEntry(sgn_histEff_corr,('New: d = %1.3f + %s %1.3f')%(b,xname,a),'p' )
      lg1.SetTextColor(kRed)
      leg1.AddEntry(l1,('Reference: %1.3f')%(refValue) ,'l')

      leg1.SetTextSize(0.03)
      leg1.SetBorderSize(0)
      leg1.Draw()
      atlas_template(pad1,**kwargs)

      pad2 = canvas.cd(2) if dovertical else canvas.cd(4)

      bkg_histEff.SetTitle('Background rejection in: '+partition_name)
      bkg_histEff.SetLineColor(kRed)
      bkg_histEff.SetMarkerColor(kRed)
      bkg_histEff.GetYaxis().SetTitle('#epsilon('+xname+')')
      bkg_histEff.GetXaxis().SetTitle(xname)
      bkg_histEff.Draw()
      bkg_histEff_corr.SetLineColor(kBlack)
      bkg_histEff_corr.SetMarkerColor(kBlack)
      bkg_histEff_corr.Draw('sames')
      l0.Draw()
      l1.Draw()
      leg2 = TLegend(legend_position[0],legend_position[1]+0.4, legend_position[2],legend_position[3]+0.4)
      setLegend1(leg2)
      leg2.SetHeader('Background rejection in '+partition_name)
      leg2.AddEntry(sgn_histEff,('Old: d = %1.3f')%(b0),'p' )
      lg2 = leg2.AddEntry(sgn_histEff_corr,('New: d = %1.3f + %s %1.3f')%(b,xname,a),'p' )
      lg2.SetTextColor(kRed)
      leg2.SetTextSize(0.03)
      leg2.SetBorderSize(0)
      leg2.Draw()
      atlas_template(pad2,**kwargs)

      pad3 = canvas.cd(3) if dovertical else canvas.cd(2)
      sgn_hist2D.SetTitle('Neural Network output as a function fo nvtx, '+partition_name)
      sgn_hist2D.GetXaxis().SetTitle('Neural Network output (Discriminant)')
      sgn_hist2D.GetYaxis().SetTitle(xname)
      sgn_hist2D.GetZaxis().SetTitle('')
      if not useNoActivationFunctionInTheLastLayer: sgn_hist2D.SetAxisRange(-1,1, 'X' )
      sgn_hist2D.Draw('colz')
      pad3.SetLogz()
      # Add points

      
      g1 = TGraphErrors(len(discr_points), discr_points, np.array(nvtx_points)+limits[0], np.array(error_points), np.zeros(discr_points.shape))
      g1.SetLineWidth(1)
      g1.SetLineColor(kBlue)
      g1.SetMarkerColor(kBlue) 
      g1.Draw("P same")
      # Old threshold line
      l2 = TLine(b0,y_min,b0,y_max)
      l2.SetLineColor(kRed)
      l2.SetLineWidth(2)
      l2.Draw()
      # New threshold line
      l3 = TLine(b,y_min, a*y_max+b, y_max)
      l3.SetLineColor(kBlack)
      l3.SetLineWidth(2)
      l3.Draw()

      atlas_template(pad3,**kwargs)

      pad4 = canvas.cd(4) if dovertical else canvas.cd(5)
      bkg_hist2D.SetTitle('Neural Network output as a function fo nvtx, '+partition_name)
      bkg_hist2D.GetXaxis().SetTitle('Neural Network output (Discriminant)')
      bkg_hist2D.GetYaxis().SetTitle(xname)
      bkg_hist2D.GetZaxis().SetTitle('')
      if not useNoActivationFunctionInTheLastLayer: bkg_hist2D.SetAxisRange(-1,1, 'X' )
      #sgn_hist2D.SetAxisRange(b+y_max*a-0.2,1, 'X' )
      bkg_hist2D.Draw('colz')
      pad4.SetLogz()
      # Add points
      g2 = TGraphErrors(len(discr_points), discr_points, np.array(nvtx_points)+limits[0], np.array(error_points), np.zeros(discr_points.shape))
      g2.SetLineWidth(1)
      g2.SetLineColor(kBlue)
      g2.SetMarkerColor(kBlue) 
      g2.Draw("P same")
      # Old threshold line
      l4 = TLine(b0,y_min,b0,y_max)
      l4.SetLineColor(kRed)
      l4.SetLineWidth(2)
      l4.Draw()
      # New threshold line
      l5 = TLine(b,y_min, a*y_max+b, y_max)
      l5.SetLineColor(kBlack)
      l5.SetLineWidth(2)
      l5.Draw()
      atlas_template(pad4,**kwargs)
      from ROOT import TH1D, kAzure
      from TrigEgammaDevelopments.plots import AutoFixAxes
      pad5 = canvas.cd(5) if dovertical else canvas.cd(3)
      #pad5.SetLogy()
      h5 = TH1D(sgn_hist2D.ProjectionX())
      h6 = TH1D(bkg_hist2D.ProjectionX())
      if max(h5.GetMaximum(),h6.GetMaximum()) > 10*(min(h5.GetMaximum(),h6.GetMaximum())):
        pad5.SetLogy()

      h5.Rebin(10)
      h6.Rebin(10)
      h5.SetLineColor(kAzure+6)
      h5.SetFillColor(kAzure+6)
      h6.SetLineColor(kRed-7)
      h5.Draw()
      h6.Draw('sames')
      AutoFixAxes(pad5,False,False,1.5)
      atlas_template(pad5,**kwargs)

      pad6 = canvas.cd(6)
      #pad6.SetLogy()
      h7 = TH1D(bkg_hist2D.ProjectionX())
      h8 = TH1D(sgn_hist2D.ProjectionX())
      if max(h7.GetMaximum(),h8.GetMaximum()) > 10*(min(h7.GetMaximum(),h8.GetMaximum())):
        pad6.SetLogy()
      
      h7.Rebin(10)
      h8.Rebin(10)
      h7.SetLineColor(kRed-7)
      h7.SetFillColor(kRed-7)
      h8.SetLineColor(kAzure+6)
      h7.Draw()
      h8.Draw('sames')
      AutoFixAxes(pad6,False,False,1.5)
      atlas_template(pad6,**kwargs)
      canvas.SaveAs(output_name+'.pdf')    

    return b,a,b0
Exemplo n.º 29
0
def DrawNoPull(data, bkg, legend, fileName, varName, dirName, lumi, signals,
               SUM, ControlRegion, hideData, year):
    frame = data.Clone(data.GetName() + '_frame')
    frame.Reset()
    frame.GetXaxis().SetTitle(varName)
    myMax = max(data.GetMaximum(), SUM.GetMaximum())
    frame.SetMaximum(myMax * 1.7)
    frame.SetMinimum(0.5)
    #  frame.GetYaxis().SetMaxDigits(2)

    frame.GetYaxis().SetTitle("Events")

    nbins = frame.GetXaxis().GetNbins()
    binslow = frame.GetXaxis().GetBinLowEdge(1)
    binsup = frame.GetXaxis().GetBinUpEdge(nbins)
    perbin = (float(binsup) - float(binslow)) / float(nbins)
    thisLabel = "Events/(" + str(perbin) + ")"

    if "GeV" in varName:
        thisLabel = "Events/(" + str(perbin) + " GeV)"

    if binsup > 999:
        frame.GetXaxis().SetLimits(binslow, 999)

    frame.GetYaxis().SetTitle(thisLabel)

    SetAxisTextSizes(frame)
    SetGeneralStyle()
    tc = TCanvas('tc', 'tc', 800, 700)
    SetPadStyle(tc)
    frame.Draw()
    bkg.Draw("hist same")
    SUM.Draw("E2 same")

    if hideData == False:
        nbins = data.GetNbinsX()
        gData = TGraphErrors(nbins)
        for i in range(1, nbins + 1):
            xcenter = data.GetBinCenter(i)
            ycenter = data.GetBinContent(i)
            yerror = data.GetBinError(i)
            gData.SetPoint(i - 1, xcenter, ycenter)
            gData.SetPointError(i - 1, 0.0001, yerror)

        gData.SetLineColor(data.GetLineColor())
        gData.SetMarkerColor(data.GetMarkerColor())
        gData.SetMarkerStyle(data.GetMarkerStyle())

        gData.Draw("PE same")

    for si in signals:
        #    print si
        si[0].Draw("hist  same")

    tc.Update()
    tc.RedrawAxis()

    for ll in legend:
        ll.Draw("same")

    Lumi = str(lumi / 1000.)

    l1 = DrawCMSLabels(tc, Lumi, 0, 0.08)
    tc.Update()

    tc.SaveAs(dirName + "/NP_" + fileName + ".pdf")
    tc.SaveAs(dirName + "/NP_" + fileName + ".png")

    for ll in l1:
        ll.Delete()

    if 'cos' in varName or 'Cos' in varName:
        frame.SetMaximum(myMax * 30)
    else:
        frame.SetMaximum(myMax * 60)
    tc.SetLogy()
    tc.Update()

    l2 = DrawCMSLabels(tc, Lumi, 0, 0)

    tc.SaveAs(dirName + "/NP_LOG_" + fileName + ".pdf")
    tc.SaveAs(dirName + "/NP_LOG_" + fileName + ".png")
Exemplo n.º 30
0
def scanKK():
    '''Used to test the scan of one or more parameters'''
    nChips = 19 # the magic number
#     nChan = len(chans)

    iP = 1
    cd = CommonData()
    cd.setupConnection()
    sc1 = SensorConfig(cd)

    ### get list of chains to be updated
#     chains = set([sc1.tms1mmX19chainSensors[sc1.tms1mmX19sensorInChain[c]][0] for c in chans])

    chan = 5
#     cd.inputVs = [3., 0., 3., 0., 0., 0.]
#     cd.inputVs = [3., 0., 0.732, 1.68, 0., 0.]
#     cd.inputVs = [0.75, 2.15, 0.7, 0., 0., 0.]

    show = True
    g1 = None
    if show:
        g1 = TGraphErrors()

    xj = open('scan_KK_6.ttl','w')

    ### point insert scan
    ipar = 2
    pts = [(0.,None),(3.,None)]
    while True:
        print pts
        pt, xy, r1, k = insertPoint(pts)
        print '-'*30
        print pt,xy,r1, k
        print '-'*30
        if xy<3 and (r1<0.01 or xy/r1<0.1 or k<0.007): break

        cd.inputVs[ipar] = pt
        cd.updatePars(chan, None, False)
        sc1.update_sensor(chan)
        time.sleep(3)
        cd.fetch()

        m,v = getMeanVar(cd.adcData[chan])
        print ' '.join([str(x) for x in [chan, m, v]+cd.inputVs])
        xj.write(' '.join([str(x) for x in [chan, m, v]+cd.inputVs])+'\n')

        if g1:
            n1 = g1.GetN()
            g1.SetPoint(n1, pt, m)
            g1.SetPointError(n1, 0, v)

        if xy == 999:
            pts[r1] = (pt,m)
        else:
            pts.append((pt,m))

    ### simple scan
#     while cd.inputVs[0]>0.001:
#         cd.updatePars(chan, None, False)
#         sc1.update_sensor(chan)
#         time.sleep(2)
#         cd.fetch()
# 
#         m,v = getMeanVar(cd.adcData[chan])
#         print ' '.join([str(x) for x in [chan, m, v]+cd.inputVs])
#         xj.write(' '.join([str(x) for x in [chan, m, v]+cd.inputVs])+'\n')
# 
#         if g1:
#             g1.SetPoint(g1.GetN(), cd.inputVs[0], m)
#         cd.inputVs[0] *= 2./3
    if g1:
        g1.SetMarkerStyle(4)
        g1.SetMarkerColor(2)
        g1.SetLineColor(2)
        g1.Draw("AP")
        h1 = g1.GetHistogram()
        h1.GetXaxis().SetTitle(cd.voltsNames[ipar]+' [V]')
        h1.GetYaxis().SetTitle("V_{out} [V]")
        lt = TLatex()
        lt.DrawLatexNDC(0.2,0.92,"Chip %d"%chan)
        waitRootCmdX()