Ejemplo n.º 1
0
    def draw_nse_mean(self):
        cent_bin1 = [0, 4, 7]
        cent_bin2 = [3, 6, 8]
        p_bin1 = [
            0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5,
            3.0, 3.5, 4.0, 4.5
        ]
        p_bin2 = [
            0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0,
            3.5, 4.0, 4.5, 5.0
        ]
        gr_mean = TGraphErrors()
        gr_width = TGraphErrors()
        gr_eff = TGraphErrors()
        for i in range(0, len(p_bin1)):
            f_gaus = self.draw_nse(cent_bin1[1], cent_bin2[1], p_bin1[i],
                                   p_bin2[i], -1, 2)
            mean = f_gaus.GetParameter(1)
            mean_err = f_gaus.GetParError(1)
            width = f_gaus.GetParameter(2)
            width_err = f_gaus.GetParError(2)
            gr_mean.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, mean)
            gr_mean.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, mean_err)
            gr_width.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, width)
            gr_width.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, width_err)
            p = 0.5 * (p_bin1[i] + p_bin2[i])
            if p < 1:
                nse_low = 0.5 * p - 1.5
            else:
                nse_low = -1
            m = f_gaus.Integral(nse_low, 2.0)
            N = f_gaus.Integral(-10.0, 10.0)
            gr_eff.SetPoint(i, p, m / N)
            gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5,
                                 eff_err(m, N))
        gr_mean.SetMarkerStyle(20)

        gr_mean.SetMarkerSize(1.5)
        gr_mean.SetMarkerColor(632)
        gr_width.SetMarkerStyle(20)
        gr_width.SetMarkerSize(1.5)
        gr_width.SetMarkerColor(600)
        gr_eff.SetMarkerStyle(20)
        gr_eff.SetMarkerSize(1.5)
        gr_eff.SetMarkerColor(600)
        hx = histo(0, 10, -0.2, 1.2, "p_{T}(GeV/c)", "Mean/Width")
        canvas_file = self.__canvas__
        canvas_file.cd()
        c1 = TCanvas("c1", "c1", 1000, 800)
        hx.Draw()
        gr_width.Draw("psame")
        gr_mean.Draw("psame")
        c1.Write("nse")
        c1.SaveAs("nse.png")
        c2 = TCanvas("c2", "c2", 1000, 800)
        hx.GetYaxis().SetTitle("n#sigma_{e} cut efficiency")
        hx.Draw()
        gr_eff.Draw("psame")
        c2.Write("nse_eff")
        c2.SaveAs("nse_eff.png")
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
 def draw_tof_cut_eff(self, cent_low, cent_high):
     cent_bin1 = [0, 4, 7]
     cent_bin2 = [3, 6, 8]
     p_bin1 = [
         0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5,
         3.0, 3.5, 4.0, 4.5
     ]
     p_bin2 = [
         0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0,
         3.5, 4.0, 4.5, 5.0
     ]
     gr_mean = TGraphErrors()
     gr_width = TGraphErrors()
     gr_eff = TGraphErrors()
     for i in range(0, len(p_bin1)):
         f_gaus = self.draw_tof_cut(cent_bin1[1], cent_bin2[1], p_bin1[i],
                                    p_bin2[i])
         mean = f_gaus.GetParameter(1)
         mean_err = f_gaus.GetParError(1)
         width = f_gaus.GetParameter(2)
         width_err = f_gaus.GetParError(2)
         gr_mean.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, mean)
         gr_mean.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, mean_err)
         gr_width.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, width)
         gr_width.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, width_err)
         m = f_gaus.Integral(0.97, 1.03)
         N = f_gaus.GetParameter(0) * math.sqrt(
             2 * math.pi) * f_gaus.GetParameter(2)
         print m, N
         gr_eff.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N)
         gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5,
                              eff_err(m, N))
     gr_mean.SetMarkerStyle(20)
     gr_mean.SetMarkerSize(1.5)
     gr_mean.SetMarkerColor(632)
     gr_width.SetMarkerStyle(20)
     gr_width.SetMarkerSize(1.5)
     gr_width.SetMarkerColor(600)
     gr_eff.SetMarkerStyle(20)
     gr_eff.SetMarkerSize(1.5)
     gr_eff.SetMarkerColor(600)
     hx = histo(0, 10, -0.2, 1.2, "p_{T}(GeV/c)", "Mean/Width")
     canvas_file = self.__canvas__
     canvas_file.cd()
     c1 = TCanvas("c1", "c1", 1000, 800)
     hx.GetYaxis().SetTitle("1/#beta cut efficency")
     hx.Draw()
     gr_width.Draw("psame")
     gr_mean.Draw("psame")
     c1.Write("tof")
     c1.SaveAs("tof.png")
     c2 = TCanvas("c2", "c2", 1000, 800)
     hx.Draw()
     gr_eff.Draw("psame")
     c2.Write("tof_cut_eff")
     c2.SaveAs("tof_cut.png")
Ejemplo n.º 4
0
def Sigma_Calc(g,i_,x,y,xe,ye,percentage):
    #print'Creating TGraph with new uncertainty band'
    # sigma factor. What to multiply uncertainties by, assuming current uncertainties are 1 sigma. 
    #print'percentage/100. = ',percentage/100.
    sf = TMath.ErfInverse(percentage/100.)*TMath.Sqrt(2) # sigma value for desired percentage events contained in distribution 
    #print"sf = ",sf

    #for i in range(i_ - 1):
    #print'i_ = ',i_
    for i in range(i_):
        ye[i] = ye[i]*sf # multiply 1 sigma uncertainties by new sigma value. 

    #print sf,'sig errors = ',ye   

    #ng = TGraphErrors(i_ - 1, x, y, xe, ye)
    ng = TGraphErrors(i_, x, y, xe, ye)

    if percentage == 90: j = 2
    if percentage == 99.5: j = 4

    ng.SetMarkerStyle(g.GetMarkerStyle())
    ng.SetLineStyle(g.GetLineStyle())
    #ng.SetMarkerColor(g.GetMarkerColor() + j)
    #ng.SetLineColor(g.GetLineColor() + j)
    ng.SetFillColor(g.GetFillColor() + j)
    #ng.SetName(g.GetName())

    ng.SetFillStyle(g.GetFillStyle())

    return ng
Ejemplo n.º 5
0
def TGraph(x, y, yError=None, xError=None, **kwargs):

    __parseDrawOptions(kwargs)

    import sys
    #TODO: Need to check the types
    try:
        assert (len(x) == len(y))
    except AssertionError:
        print "Oops! Data points x and y aren't of the same size!"
        sys.exit()

    nPoints = len(x)

    from array import array
    if xError is None: xError = __zeros(nPoints)
    if yError is None: yError = __zeros(nPoints)

    from ROOT import TGraphErrors
    graph = TGraphErrors(nPoints, array('d', x), array('d', y),
                         array('d', xError), array('d', yError))
    graph.SetTitle(__drawOptions['title'])
    graph.SetMarkerStyle(__drawOptions['mstyle'])
    graph.SetMarkerSize(__drawOptions['msize'])
    graph.SetMarkerColor(__drawOptions['mcolour'])
    graph.SetFillStyle(0)
    graph.SetFillColor(0)
    return graph
Ejemplo n.º 6
0
def create_resolutiongraph(n, energies, sigmasmeans, energieserrors, sigmasmeanserrors, graphname):
	"""Function to perform ROOT graphs of resolutions"""
	#How many points
	n = int(n)

	TGraphresolution = TGraphErrors(n, energies, sigmasmeans, energieserrors, sigmasmeanserrors)
	
	#Draw + DrawOptions, Fit + parameter estimation
	Style = gStyle
	Style.SetOptFit()
	XAxis = TGraphresolution.GetXaxis() #TGraphresolution
	TGraphresolution.SetMarkerColor(4)
	TGraphresolution.SetMarkerStyle(20)
	TGraphresolution.SetMarkerSize(2)
	XAxis.SetTitle("Energy (GeV)")
	YAxis = TGraphresolution.GetYaxis()
	YAxis.SetTitle("Sigma/Mean")
	resolutionfit = TF1("resolutionfit", '([0]/((x)**0.5))+[1]', 0, max(energies)) #somma non quadratura
	TGraphresolution.Fit("resolutionfit")
	a = resolutionfit.GetParameter(0)
	b = resolutionfit.GetParameter(1)             
	TGraphresolution.Draw("AP")
	gPad.SaveAs(graphname)
	gPad.Close()
	return a, b
Ejemplo n.º 7
0
def Ratio(histo1,histo2, recorded, title):
    #gSystem.Exec("mkdir -p ZPlots")
    can1 = makeCMSCanvas(str(random.random()),"mult vs lumi ",900,700)
    lumi = []
    lumi_err = []
    ratio = []
    ratio_err = []
    sumLumi = 0.
    for i in range(0,len(recorded)):
        sumLumi += float(recorded[i])
        lumi.append(sumLumi - float(recorded[i])/2)
        lumi_err.append(float(recorded[i])/2)
        ratio.append(histo1[i].GetEntries()/histo2[i].GetEntries())
        ratio_err.append(0)
    graph1 = TGraphErrors(len(recorded),array('d',lumi),array('d',ratio),array('d',lumi_err),array('d',ratio_err))
    can1.cd()
    graph1.SetTitle("")
    graph1.GetXaxis().SetTitle("Lumi [fb^{-1}]")
    graph1.GetYaxis().SetTitle("e^{+}e^{-}/#mu^{+}#mu^{-}")
    graph1.SetMarkerStyle(20)
    graph1.SetMarkerSize(1)
    graph1.Draw("AP")
    printLumiPrelOut(can1)
    can1.SaveAs("ZPlots/Z_ratio_"+title+".pdf")
    can1.SaveAs("ZPlots/Z_ratio_"+title+".png")
    return;
Ejemplo n.º 8
0
    def makeGraph(self, name='', xtitle='', ytitle=''):
        """This function returns an instance of ROOTs TGraphErrors, made with the points in from this class.
        Some of the graph's default settings are changed:
          - black points
          - every point has the symbol of 'x'
          - x- and y-axis are centered

        Arguments:
        name   -- ROOT internal name of graph (default = '')
        xtitle -- title of x-axis (default = '')
        ytitle -- title of y-axis (default = '')
        """
        if self.points:
            x = self.getX()
            y = self.getY()
            ex = self.getEX()
            ey = self.getEY()
            graph = TGraphErrors(self.getLength(), array.array('f', x),
                                 array.array('f', y), array.array('f', ex),
                                 array.array('f', ey))
            graph.SetName(name)
            graph.SetMarkerColor(1)
            graph.SetMarkerStyle(5)
            graph.SetTitle("")
            graph.GetXaxis().SetTitle(xtitle)
            graph.GetXaxis().CenterTitle()
            graph.GetYaxis().SetTitle(ytitle)
            graph.GetYaxis().CenterTitle()
            return graph
        else:
            return None
Ejemplo n.º 9
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
Ejemplo n.º 10
0
def evaluateResolutionVariation(model, bcid, prefix, suffix, vtxres, scaling, \
                                legend=False):
    from array import array
    from ROOT import TFile, TMultiGraph, TGraphErrors, gStyle, TCanvas, \
                     TLegend, TLatex

    names = [pre+'_'+model+'_'+bcid+'_'+suf for (pre, suf) in zip(prefix, \
             suffix)]
    xVal = {name: array('d', [0.0]*len(vtxres)) for name in names}
    xErr = {name: array('d', [0.0]*len(vtxres)) for name in names}
    yVal = {name: array('d', [0.0]*len(vtxres)) for name in names}
    yErr = {name: array('d', [0.0]*len(vtxres)) for name in names}

    for name, scale in zip(names, scaling):
        for i, vr in enumerate(vtxres):
            f = TFile('results/'+name+'_'+vr+'.root')
            yVal[name][i] = f.Get('h_overlapInt').GetMean() * 100.0
            yErr[name][i] = f.Get('h_integ').GetMeanError() * 100.0
            xVal[name][i] = f.Get('h_vtxRes').GetMean() * scale * 1.0e4

    multi = TMultiGraph('overlapIntegralBcid'+bcid, '')
    graphs = []
    for i, name in enumerate(names):
        graph = TGraphErrors(len(vtxres), xVal[name], yVal[name], xErr[name], \
                             yErr[name])
        graph.SetName(name)
        graph.SetMarkerStyle(20)
        graph.SetMarkerColor(1+i)
        multi.Add(graph)
        graphs.append(graph)

    gStyle.SetOptStat(0)
    canvas = TCanvas(model+'_'+bcid, '', 600, 600)
    multi.Draw('AP')
    canvas.Update()
    multi.GetXaxis().SetTitle('vertex resolution [#mum]')
    multi.GetXaxis().SetLabelSize(0.025)
    multi.GetXaxis().SetRangeUser(11, 69)
    multi.GetYaxis().SetTitle('overlap integral [a.u.]')
    multi.GetYaxis().SetLabelSize(0.025)
    multi.GetYaxis().SetRangeUser(0.77, 1.43)
    if legend:
        leg = TLegend(0.55, 0.15, 0.88, 0.3)
        leg.SetBorderSize(0)
        for i, name in enumerate(names):
            entry = leg.AddEntry(name, legend[i], 'P')
            entry.SetMarkerStyle(20)
            entry.SetMarkerColor(1+i)
        leg.Draw()
    drawCMS(wip=True)
    text = TLatex()
    text.SetNDC()
    text.SetTextFont(62)
    text.SetTextSize(0.04)
    text.SetTextAlign(21)
    text.DrawLatex(0.5, 0.92, 'Vertex Resolution Study: '+model+', BCID '+bcid)
    canvas.Modified()
    canvas.Update()
    canvas.SaveAs('plots/'+canvas.GetName()+'.pdf')
    canvas.SaveAs('plots/'+canvas.GetName()+'.C')
Ejemplo n.º 11
0
class TimeConstant(object):
    def __init__(self, file_name):
        file = open(file_name)
        out = open(output, 'w')
        for line in file:
            #calculate errors and dump the content to output file
            #skip comment lines
            if '#' in line:
                continue
            t, v = [float(x) for x in line.split()]
            te = osc_error_t(t, TIME_DIV)
            ve = osc_error_v(v, POT_DIV)
            new_line = [t, v, te, ve]
            new_line = ' '.join([str(x) for x in new_line]) + '\n'
            out.write(new_line)
        file.close()
        out.close()
        #create Graph. ROOT automatically reads columns
        self.graph = TGraphErrors(output)
        self.graph.SetMarkerStyle(7)
        self.func = TF1("exp_decay", "[0]*exp(-x/[1])")
        self.func.SetParameters(2, 20)

    def fit_graph(self):
        self.graph.Fit("exp_decay", "Q")
        self.v0 = self.func.GetParameter(0), self.func.GetParError(0)
        self.tau = self.func.GetParameter(1), self.func.GetParError(1)


#        print "%.3f \pm %.3f" %self.v0
#        print "%.3f \pm %.3f" %self.tau

    def get_capacity(self):
        c = (self.tau[0] / INTERNAL_RES, self.tau[1] / INTERNAL_RES)
        return c
Ejemplo n.º 12
0
def CompareToys(MwValuemT, MwValuemTStat):
    print(len(MwValuemT), len(MwValuemTStat))

    n = len(MwValuemT)
    x, y = array('d'), array('d')
    ex, ey = array('d'), array('d')

    for i in range(0, n):
        x.append(i + 1)
        ex.append(0)
        y.append(MwValuemT[i])
        ey.append(MwValuemTStat[i])

    gr = TGraphErrors(n, x, y, ex, ey)
    gr.Draw("P")
    gr.SetLineWidth(0)
    gr.SetMarkerStyle(20)
    gr.SetMarkerSize(1)

    xax = gr.GetXaxis()
    for i in range(0, n):
        binIndex = xax.FindBin(i)
        xax.SetBinLabel(binIndex, "toys")

    Output = ROOT.TFile.Open("Matrix.root", "RECREATE")
    gr.Write("gr")
def make1DSummaryPlot(binned_mw, bins, channel, variable, treeSuffix):
    nBins = len(bins)

    xValues, yValues = array('d'), array('d')
    xErrors, yErrors = array('d'), array('d')
    for bin in bins:
        mW = binned_mw[bin]
        lowBinEdge = bins[bin][0]
        highBinEdge = bins[bin][1]
        binWidth = (bins[bin][1] - bins[bin][0]) / 2
        binCentre = bins[bin][1] - binWidth
        if bin.split('_')[-1] == 'inf':
            binCentre = lowBinEdge * 1.1
            binWidth = lowBinEdge * 0.1
        # print binCentre
        # print bin,bins[bin],mW.getVal(),mW.getError()
        xValues.append(binCentre)
        yValues.append(mW.getVal())
        xErrors.append(binWidth)
        yErrors.append(mW.getError())

    c = TCanvas('c1', 'A Simple Graph Example', 200, 10, 700, 500)
    gr = TGraphErrors(nBins, xValues, yValues, xErrors, yErrors)
    gr.SetMarkerColor(4)
    gr.SetMarkerStyle(3)
    gr.GetXaxis().SetTitle('X title')
    gr.GetYaxis().SetTitle('Y title')
    gr.SetMinimum(75)
    gr.SetMaximum(85)
    gr.Draw('AP')
    c.Update()

    outputDir = 'plots/WStudies/%s%s/%s' % (channel, treeSuffix, variable)
    c.Print('%s/Summary.pdf' % outputDir)
Ejemplo n.º 14
0
class DiodeCurrent(object):
    def __init__(self, file_name):
        file = open(file_name)
        out = open(output, 'w')
        for line in file:
            #calculate errors and dump the content to output file
            if '#' in line:
                continue
            t, vin, vout = [float(x) for x in line.split()]
            te = osc_error_t(t, TIME_DIV)
            vd = vin - vout
            voute = osc_error_v(vout, POT_DIV)
            vde = osc_error_v(vd, POT_DIV)
            id = vout / R[0]
            if vout:
                ide = id * ((voute / vout) + (R[1] / R[0]))
            else:
                ide = id * (R[1] / R[0])
            new_line = [vd, id, vde, ide]
            new_line = ' '.join([str(x) for x in new_line]) + '\n'
            out.write(new_line)
        file.close()
        out.close()
        #create Graph. ROOT automatically reads columns
        self.graph = TGraphErrors(output)
        self.graph.SetMarkerStyle(7)
        self.func = TF1("shockley", "[0]*(exp(x/[1])-1)", 0.1, 1)
        self.func.SetParameters(5, 0.026)

    def fit_graph(self):
        self.graph.Fit("shockley", "QRW")
        self.v0 = self.func.GetParameter(0), self.func.GetParError(0)
        self.tau = self.func.GetParameter(1), self.func.GetParError(1)
        print("Is = %.3g \pm %.3g" % self.v0)
        print("n*Vt = %.3f \pm %.3f" % self.tau)
Ejemplo n.º 15
0
def ZMultVsLumi(histo, recorded, outputDir, title):
    #gSystem.Exec("mkdir -p ZPlots")
    can1 = makeCMSCanvas(str(random.random()),"mult vs lumi ",900,700)
    lumi = []
    lumi_err = []
    mult = []
    mult_err = []
    sumLumi = 0.
    for i in range(0,len(recorded)):
        sumLumi += float(recorded[i])
        lumi.append(sumLumi - float(recorded[i])/2)
        lumi_err.append(float(recorded[i])/2)
        mult.append(histo[i].GetEntries()/float(recorded[i]))
        mult_err.append(math.sqrt(histo[i].GetEntries()/float(recorded[i])))
    graph1 = TGraphErrors(len(lumi),array('d',lumi),array('d',mult),array('d',lumi_err),array('d',mult_err))
    can1.cd()
    graph1.SetTitle("")
    graph1.GetXaxis().SetTitle("Lumi [fb^{-1}]")
    graph1.GetYaxis().SetTitle("#Z / fb^{-1}")
    graph1.SetMarkerStyle(20)
    graph1.SetMarkerSize(1)
    graph1.Draw("AP")
    printLumiPrelOut(can1)
    can1.SaveAs(str(outputDir) + "/Z_multiplicity_"+title+".pdf")
    can1.SaveAs(str(outputDir) + "/Z_multiplicity_"+title+".png")
    return graph1;
Ejemplo n.º 16
0
 def draw_neta_cut_eff(self, cent_low, cent_high):
     cent_bin1 = [0, 4, 7]
     cent_bin2 = [3, 6, 8]
     p_bin1 = [
         0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5,
         3.0, 3.5, 4.0, 4.5
     ]
     p_bin2 = [
         0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0,
         3.5, 4.0, 4.5, 5.0
     ]
     gr_eff = TGraphErrors()
     for i in range(0, len(p_bin1)):
         mn = self.draw_neta_cut(cent_low, cent_high, p_bin1[i], p_bin2[i])
         m = mn[0]
         N = mn[1]
         gr_eff.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N)
         gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5,
                              eff_err(m, N))
     gr_eff.SetMarkerStyle(20)
     gr_eff.SetMarkerSize(1.5)
     gr_eff.SetMarkerColor(600)
     hx = histo(0, 8, -0.2, 1.2, "p_{T}(GeV/c)", "n#eta cut efficiency")
     canvas_file = self.__canvas__
     canvas_file.cd()
     c2 = TCanvas("c2", "c2", 1000, 800)
     hx.Draw()
     gr_eff.Draw("psame")
     c2.Write("neta_cut_eff")
     c2.SaveAs("neta_cut.png")
Ejemplo n.º 17
0
def compareEEC( filename="sjm91_all.root", datafilename="../EECMC/share/OPAL/data.dat" ):
    f= TFile( filename )
    ao= createAnalysisObservable( f, "EEC" )
    tokens= datafilename.split( "/" )
    exp= tokens[3]
    plotoptions= { "xmin": 0.0, "xmax": 3.14159, "ymin": 0.05, "ymax": 5.0, "markerStyle": 20,
                       "markerSize": 0.5, "drawas": "3", "fillcolor": 6, "title": "EEC "+exp,
                       "xlabel": "\chi\ [rad.]", "ylabel": "1/\sigma d\Sigma/d\chi", "logy": 1 }
    tgest, tgesy= ao.plot( plotoptions )
    lines= [ line.rstrip( '\n' ) for line in open( datafilename ) ]
    n= len( lines )
    points= TVectorD( n )
    values= TVectorD( n )
    errors= TVectorD( n )
    perrs= TVectorD(n)
    grad2rad= 3.14159/180.0
    for i in range( n ):
        line= (lines[i]).split()
        points[i]= float(line[0])*grad2rad
        values[i]= float(line[3])
        errors[i]= float(line[4])
        perrs[i]= 0.0
    datatge= TGraphErrors( points, values, perrs, errors )
    datatge.SetMarkerStyle( 20 )
    datatge.SetMarkerSize( 0.5 )    
    datatge.Draw( "psame" )
    legend= TLegend( 0.2, 0.7, 0.5, 0.85 )
    datatge.SetName( "datatge" );
    tgesy.SetName( "tgesy" )
    legend.AddEntry( "datatge", exp+" data", "pe" )
    legend.AddEntry( "tgesy", "OPAL "+filename, "f" )
    legend.Draw()
    return 
Ejemplo n.º 18
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
    def plotGainSummary(self, strDetName):
        #Create the Plot - Average
        gDet_AvgEffGain = TGraphErrors(len(self.GAIN_AVG_POINTS))
        gDet_AvgEffGain.SetName("g_{0}_EffGainAvg".format(strDetName))

        #Create the Plot - Max Gain
        gDet_MaxEffGain = TGraphErrors(len(self.GAIN_MAX_POINTS))
        gDet_MaxEffGain.SetName("g_{0}_EffGainMax".format(strDetName))

        #Create the Plot - Min Gain
        gDet_MinEffGain = TGraphErrors(len(self.GAIN_MIN_POINTS))
        gDet_MinEffGain.SetName("g_{0}_EffGainMin".format(strDetName))

        #Set and print the points
        #print "===============Printing Gain Data==============="
        #print "[BEGIN_DATA]"
        #print "\tVAR_INDEP,VAR_DEP,VAR_DEP_ERR"
        for i in range(0, len(self.GAIN_AVG_POINTS)):
            #Average
            gDet_AvgEffGain.SetPoint(i, self.DET_IMON_POINTS[i],
                                     self.GAIN_AVG_POINTS[i])
            gDet_AvgEffGain.SetPointError(i, 0, self.GAIN_STDDEV_POINTS[i])
            #print "\t%f,%f,%f"%(self.DET_IMON_POINTS[i],self.GAIN_AVG_POINTS[i],self.GAIN_STDDEV_POINTS[i])

            #Max
            gDet_MaxEffGain.SetPoint(i, self.DET_IMON_POINTS[i],
                                     self.GAIN_MAX_POINTS[i])

            #Min
            gDet_MinEffGain.SetPoint(i, self.DET_IMON_POINTS[i],
                                     self.GAIN_MIN_POINTS[i])
            pass
        #print "[END_DATA]"
        #print ""

        #Draw
        canv_AvgEffGain = TCanvas(
            "canv_{0}_EffGainAvg".format(strDetName),
            "{0} Average Effective Gain".format(strDetName), 600, 600)
        canv_AvgEffGain.cd()
        canv_AvgEffGain.cd().SetLogy()
        gDet_AvgEffGain.GetXaxis().SetTitle("HV")
        gDet_AvgEffGain.GetYaxis().SetTitle("#LT Effective Gain #GT")
        gDet_AvgEffGain.GetYaxis().SetRangeUser(1e2, 1e6)
        gDet_AvgEffGain.SetMarkerStyle(21)
        gDet_AvgEffGain.Draw("AP")
        gDet_MaxEffGain.Draw("sameL")
        gDet_MinEffGain.Draw("sameL")

        #Write
        dir_Summary = self.FILE_OUT.mkdir("Summary")
        dir_Summary.cd()
        canv_AvgEffGain.Write()
        gDet_AvgEffGain.Write()
        gDet_MaxEffGain.Write()
        gDet_MinEffGain.Write()

        return
Ejemplo n.º 20
0
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")
Ejemplo n.º 21
0
def MeanRMSVsLumi(histo, recorded, outputDir, title):
    can1 = makeCMSCanvas(str(random.random()), "mean vs lumi ", 900, 700)
    can2 = makeCMSCanvas(str(random.random()), "RMS vs lumi ", 900, 700)
    lumi = []
    lumi_err = []
    mean = []
    mean_err = []
    RMS = []
    RMS_err = []
    sumLumi = 0.
    for i in range(0, len(recorded)):
        sumLumi += float(recorded[i])
        lumi.append(sumLumi - float(recorded[i]) / 2)
        lumi_err.append(float(recorded[i]) / 2)
        mean.append(histo[i].GetMean())
        mean_err.append(0.)  #dont put error on ISO and SIP histo[i].GetRMS()
        RMS.append(histo[i].GetRMS())
        RMS_err.append(0.)
    graph1 = TGraphErrors(len(recorded), array('d', lumi), array('d', mean),
                          array('d', lumi_err), array('d', mean_err))
    graph2 = TGraphErrors(len(recorded), array('d', lumi), array('d', RMS),
                          array('d', lumi_err), array('d', RMS_err))
    can1.cd()
    graph1.SetTitle("")
    graph1.GetXaxis().SetTitle("Lumi [fb^{-1}]")
    graph1.GetYaxis().SetTitle(" ")
    graph1.SetMarkerStyle(20)
    graph1.SetMarkerSize(1)
    graph1.Draw("AP")
    printLumiPrelOut(can1)
    can1.SaveAs(str(outputDir) + "/" + title + "_mean.pdf")
    can1.SaveAs(str(outputDir) + "/" + title + "_mean.png")
    can2.cd()
    graph2.SetTitle("")
    graph2.GetXaxis().SetTitle(" ")
    graph2.GetYaxis().SetTitle("Width [GeV]")
    graph2.SetMarkerStyle(20)
    graph2.SetMarkerSize(1)
    graph2.Draw("AP")
    printLumiPrelOut(can2)
    can2.SaveAs(str(outputDir) + "/" + title + "_width.pdf")
    can2.SaveAs(str(outputDir) + "/" + title + "_width.png")

    return graph1, graph2
Ejemplo n.º 22
0
def GraphVsLumi(result, outputDir, title):
    #gSystem.Exec("mkdir -p ZPlots")
    can1 = makeCMSCanvas(str(random.random()), "mean vs lumi ", 900, 700)
    can2 = makeCMSCanvas(str(random.random()), "width vs lumi ", 900, 700)
    lumi = []
    lumi_err = []
    mean = []
    mean_err = []
    width = []
    width_err = []
    sumLumi = 0.
    for i in range(0, len(result)):
        sumLumi += float(result[i].lumi)
        lumi.append(sumLumi - float(result[i].lumi) / 2)
        lumi_err.append(float(result[i].lumi) / 2)
        mean.append(result[i].mean)
        mean_err.append(result[i].mean_err)
        width.append(result[i].width)
        width_err.append(result[i].width_err)
    graph1 = TGraphErrors(len(result), array('d', lumi), array('d', mean),
                          array('d', lumi_err), array('d', mean_err))
    graph2 = TGraphErrors(len(result), array('d', lumi), array('d', width),
                          array('d', lumi_err), array('d', width_err))
    can1.cd()
    graph1.SetTitle("")
    graph1.GetXaxis().SetTitle("Lumi [fb^{-1}]")
    graph1.GetYaxis().SetTitle("Mass [GeV]")
    graph1.SetMarkerStyle(20)
    graph1.SetMarkerSize(1)
    graph1.Draw("AP")
    printLumiPrelOut(can1)
    can1.SaveAs(str(outputDir) + "/" + title + "_mean.pdf")
    can1.SaveAs(str(outputDir) + "/" + title + "_mean.png")
    can2.cd()
    graph2.SetTitle("")
    graph2.GetXaxis().SetTitle("Lumi [fb^{-1}]")
    graph2.GetYaxis().SetTitle("Width [GeV]")
    graph2.SetMarkerStyle(20)
    graph2.SetMarkerSize(1)
    graph2.Draw("AP")
    printLumiPrelOut(can2)
    can2.SaveAs(str(outputDir) + "/" + title + "_width.pdf")
    can2.SaveAs(str(outputDir) + "/" + title + "_width.png")
    return graph1, graph2
Ejemplo n.º 23
0
  def plotGraph(self, x='vv', y='acc'): 
    '''
    Plot a graph with specified quantities on x and y axes , and saves the graph
    '''

    if (x not in self.quantities.keys()) or (y not in self.quantities.keys()):
      raise RuntimeError('selected quantities not available, available quantities are: \n{}'.format(self.quantities.keys()))

    xq = self.quantities[x]
    yq = self.quantities[y]

    #graph = TGraphAsymmErrors()
    #graph = TGraph()
    graph = TGraphErrors()
    for i,s in enumerate(self.samples):
      graph.SetPoint(i,getattr(s, xq.name), getattr(s, yq.name) )
      #if xq.err: 
      #  graph.SetPointEXhigh(i, getattr(s, xq.name+'_errup'))   # errup errdn
      #  graph.SetPointEXlow (i, getattr(s, xq.name+'_errdn'))
      if yq.err: 
        graph.SetPointError(i, 0, getattr(s, yq.name+'_errup'))
      #  graph.SetPointEYhigh(i, getattr(s, yq.name+'_errup'))  
      #  graph.SetPointEYlow (i, getattr(s, yq.name+'_errdn'))

    c = TCanvas()
    graph.SetLineWidth(2)
    graph.SetMarkerStyle(22)
    graph.SetTitle(';{x};{y}'.format(y=yq.title,x=xq.title))
    graph.Draw('APLE')

    if yq.forceRange:
      graph.SetMinimum(yq.Range[0])
      graph.SetMaximum(yq.Range[1])

    gPad.Modified()
    gPad.Update()
    if yq.name=='expNevts':
      line = TLine(gPad.GetUxmin(),3,gPad.GetUxmax(),3)
      line.SetLineColor(ROOT.kBlue)
      line.Draw('same')
      #graph.SetMinimum(0.01)
      #graph.SetMaximum(1E06)

    if xq.log: c.SetLogx()
    if yq.log: c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    c.SaveAs('./plots/{}{}/{}_{}VS{}.pdf'.format(self.label,suffix,self.name,yq.name,xq.name))
    c.SaveAs('./plots/{}{}/{}_{}VS{}.C'.format(self.label,suffix,self.name,yq.name,xq.name))
    c.SaveAs('./plots/{}{}/{}_{}VS{}.png'.format(self.label,suffix,self.name,yq.name,xq.name))

    self.graphs['{}VS{}'.format(yq.name,xq.name)] = graph
    # add the graph container for memory?
    graph_saver.append(graph)
    def plotPDSummary(self, strDetName):
        #Create the Plot - Average
        gDet_AvgPD = TGraphErrors(len(self.PD_AVG_POINTS))
        gDet_AvgPD.SetName("g_{0}_PDAvg".format(strDetName))

        #Create the Plot - Max Gain
        gDet_MaxPD = TGraphErrors(len(self.PD_MAX_POINTS))
        gDet_MaxPD.SetName("g_{0}_PDMax".format(strDetName))

        #Create the Plot - Min Gain
        gDet_MinPD = TGraphErrors(len(self.PD_MIN_POINTS))
        gDet_MinPD.SetName("g_" + strDetName + "_PDMin")
        gDet_MinPD.SetName("g_{0}_PDMin".format(strDetName))

        #Set the points
        for i in range(0, len(self.PD_AVG_POINTS)):
            #Average
            gDet_AvgPD.SetPoint(i, self.GAIN_AVG_POINTS[i],
                                self.PD_AVG_POINTS[i])
            gDet_AvgPD.SetPointError(i, self.GAIN_STDDEV_POINTS[i],
                                     self.PD_STDDEV_POINTS[i])

            #Max
            gDet_MaxPD.SetPoint(i, self.GAIN_AVG_POINTS[i],
                                self.PD_MAX_POINTS[i])

            #Min
            gDet_MinPD.SetPoint(i, self.GAIN_AVG_POINTS[i],
                                self.PD_MIN_POINTS[i])

        #Draw
        canv_AvgPD = TCanvas("canv_{0}_PDAvg".format(strDetName),
                             "{0} Discharge Probability".format(strDetName),
                             600, 600)
        canv_AvgPD.cd()
        canv_AvgPD.cd().SetLogx()
        canv_AvgPD.cd().SetLogy()
        gDet_AvgPD.GetXaxis().SetTitle("#LT Effective Gain #GT")
        gDet_AvgPD.GetYaxis().SetTitle("Discharge Probability P_{D}")
        gDet_AvgPD.GetYaxis().SetRangeUser(1e-11, 1e-6)
        gDet_AvgPD.SetMarkerStyle(21)
        gDet_AvgPD.Draw("AP")
        gDet_MaxPD.Draw("sameL")
        gDet_MinPD.Draw("sameL")

        #Write
        dir_Summary = self.FILE_OUT.GetDirectory("Summary")
        dir_Summary.cd()
        canv_AvgPD.Write()
        gDet_AvgPD.Write()
        gDet_MaxPD.Write()
        gDet_MinPD.Write()

        return
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig,
                             lower1sig, upper2sig, lower2sig):

    channel = np.array(
        [3. * nchannels - 1.5 - 3. * i for i in range(0, nchannels)])
    ey = np.array([0.8 for i in range(0, nchannels)])
    zero = np.zeros(nchannels)

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    x1 = gStyle.GetPadLeftMargin() + 0.01
    y2 = 1 - gStyle.GetPadTopMargin() - 0.01
    leg = TLegend(x1, y2 - 0.17, x1 + 0.25, y2)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    leg.AddEntry(gobs, "Observed", "pl")
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
Ejemplo n.º 26
0
def correctedCrossSectionsPlot(crossings, shapes, overDiff):
    uncorrected = {41: (3.2575816286, 0.00514858611944), \
                   281: (3.26316215713, 0.00468789412223), \
                   872: (3.27340775031, 0.00484925398906), \
                   1783: (3.24986926821, 0.00460908436455), \
                   2063: (3.26363843728, 0.0044071069983)}
    multi = TMultiGraph('sigmavis', '')
    graphs = []
    n = len(shapes) + 1
    for i, shape in enumerate([''] + list(shapes)):
        xval = array('d',
                     [a + 0.08 * (i - 0.5 * n) for a in range(len(crossings))])
        xerr = array('d', len(crossings) * [0])
        yval = array('d', [uncorrected[int(bx)][0] for bx in crossings])
        yerr = array('d', [uncorrected[int(bx)][1] for bx in crossings])
        if shape:
            for j, bx in enumerate(crossings):
                yval[j] *= 1 + overDiff[shape][bx]
                yerr[j] *= 1 + overDiff[shape][bx]
        graph = TGraphErrors(len(crossings), xval, yval, xerr, yerr)
        graph.SetName('ge' + shape)
        graph.SetMarkerStyle(20)
        graph.SetMarkerColor(1 + i)
        multi.Add(graph)
        graphs.append(graph)
    gStyle.SetOptStat(0)
    hist = TH2F('hist', '', len(crossings), -0.5,
                len(crossings) - 0.5, 100, 3.23, 3.33)
    for i, bx in enumerate(crossings):
        hist.GetXaxis().SetBinLabel(i + 1, bx)
    canvas = TCanvas('c_' + multi.GetName(), '', 600, 600)
    hist.Draw('AXIS')
    multi.Draw('P')
    canvas.Update()
    hist.GetXaxis().SetLabelSize(0.035)
    hist.GetXaxis().SetNdivisions(len(crossings), False)
    hist.GetYaxis().SetTitle('#sigma_{vis} [b]')
    hist.GetYaxis().SetLabelSize(0.025)
    hist.GetYaxis().SetTitleOffset(1.3)
    leg = TLegend(0.15, 0.82, 0.85, 0.85)
    leg.SetNColumns(len(shapes) + 1)
    leg.SetBorderSize(0)
    for i, shape in enumerate([''] + list(shapes)):
        entry = leg.AddEntry('ge' + shape, shapeNames[shape], 'P')
        entry.SetMarkerStyle(20)
        entry.SetMarkerColor(1 + i)
    leg.Draw()
    drawCMS()
    canvas.Modified()
    canvas.Update()
    canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf')
    canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
Ejemplo n.º 27
0
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig,
                             lower1sig, upper2sig, lower2sig):

    channel = np.array(
        [nchannels - 1.5 - float(i) for i in range(0, nchannels)])
    ey = np.full(nchannels, 0.494)
    zero = np.zeros(nchannels)

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    #gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    leg = TLegend(0.75, 0.75, 0.95, 0.9)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    #leg.AddEntry( gobs,        "Observed", "pl" )
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
Ejemplo n.º 28
0
def plot_correction( h2, slope, offset, x_points, y_points, error_points, outname, 
                     xlabel='',
                     etBinIdx=None, 
                     etaBinIdx=None, 
                     etBins=None,
                     etaBins=None, 
                     label='Internal',
                     ref_value=None, 
                     pd_value=None,
                     palette=kBlackBody):

    def toStrBin(etlist = None, etalist = None, etidx = None, etaidx = None):
        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')
            return 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')
            return binEta

    canvas = TCanvas("canvas","canvas",500,500)
    rpl.set_figure(canvas)
    gStyle.SetPalette(palette)
    canvas.SetRightMargin(0.15)
    canvas.SetTopMargin(0.15)
    canvas.SetLogz()
    h2.GetXaxis().SetTitle('Neural Network output (Discriminant)')
    h2.GetYaxis().SetTitle(xlabel)
    h2.GetZaxis().SetTitle('Count')
    h2.Draw('colz')
    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.SetMarkerColor(kBlue)
    g.SetMarkerStyle(8)
    g.SetMarkerSize(1)
    g.Draw("P same")
    line = TLine(slope*h2.GetYaxis().GetXmin()+offset,h2.GetYaxis().GetXmin(), slope*h2.GetYaxis().GetXmax()+offset, h2.GetYaxis().GetXmax())
    line.SetLineColor(kBlack)
    line.SetLineWidth(2)
    line.Draw()
    # Add text labels into the canvas
    text = toStrBin(etlist=etBins, etidx=etBinIdx)
    text+= ', '+toStrBin(etalist=etaBins, etaidx=etaBinIdx)
    if ref_value and pd_value:
        text+=', P_{D} = %1.2f (%1.2f) [%%]'%(pd_value*100, ref_value*100)
    rpl.add_text(0.15, 0.885, text, textsize=.03)
    rpl.set_atlas_label(0.15, 0.94, label)
    rpl.format_canvas_axes(XLabelSize=16, YLabelSize=16, XTitleOffset=0.87, ZLabelSize=16,ZTitleSize=16, YTitleOffset=0.87, ZTitleOffset=1.1)
    canvas.SaveAs(outname)
    def plotGainSummary(self, strDetName):
        #Create the Plot - Average
        gDet_AvgEffGain = TGraphErrors( len(self.GAIN_AVG_POINTS) )
        #gDet_AvgEffGain.SetName("g_" + strDetName + "_EffGainAvg")
        gDet_AvgEffGain.SetName("g_{0}_EffGainAvg".format(strDetName))
        
        #Create the Plot - Max Gain
        gDet_MaxEffGain = TGraphErrors( len(self.GAIN_MAX_POINTS) )
        #gDet_MaxEffGain.SetName("g_" + strDetName + "_EffGainMax")
        gDet_MaxEffGain.SetName("g_{0}_EffGainMax".format(strDetName))

        #Create the Plot - Min Gain
        gDet_MinEffGain = TGraphErrors( len(self.GAIN_MIN_POINTS) )
        #gDet_MinEffGain.SetName("g_" + strDetName + "_EffGainMin")
        gDet_MinEffGain.SetName("g_{0}_EffGainMin".format(strDetName))

        #Set the points
        for i in range(0, len(self.GAIN_AVG_POINTS) ):
            #Average
            gDet_AvgEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_AVG_POINTS[i])
            gDet_AvgEffGain.SetPointError(i,0,self.GAIN_STDDEV_POINTS[i])

            #Max
            gDet_MaxEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_MAX_POINTS[i])

            #Min
            gDet_MinEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_MIN_POINTS[i])
        
        #Draw
        #canv_AvgEffGain = TCanvas("canv_" + strDetName + "_EffGainAvg",strDetName + " Average Effective Gain",600,600)
        canv_AvgEffGain = TCanvas("canv_{0}_EffGainAvg".format(strDetName),"{0} Average Effective Gain".format(strDetName),600,600)
        canv_AvgEffGain.cd()
        canv_AvgEffGain.cd().SetLogy()
        gDet_AvgEffGain.GetXaxis().SetTitle("HV")
        gDet_AvgEffGain.GetYaxis().SetTitle("#LT Effective Gain #GT")
        gDet_AvgEffGain.GetYaxis().SetRangeUser(1e2,1e6)
        gDet_AvgEffGain.SetMarkerStyle(21)
        gDet_AvgEffGain.Draw("AP")
        gDet_MaxEffGain.Draw("sameL")
        gDet_MinEffGain.Draw("sameL")

        #Write
        dir_Summary = self.FILE_OUT.mkdir("Summary")
        dir_Summary.cd()
        canv_AvgEffGain.Write()
        gDet_AvgEffGain.Write()
        gDet_MaxEffGain.Write()
        gDet_MinEffGain.Write()
        
    	return
def fit_slices(histo, x_range, x_bin_step, y_fit_range):

    x_start = histo.GetXaxis().FindBin(x_range[0])
    x_stop = histo.GetXaxis().FindBin(x_range[1])

    x_values = array('d')
    slices = []
    fits = []
    for i, x_bin in enumerate(range(x_start, x_stop + 1, x_bin_step)):
        projec = histo.ProjectionY(histo.GetTitle() + '_proj{}'.format(i),
                                   x_bin, x_bin + x_bin_step)

        fit = TF1(histo.GetTitle() + '_fit{}'.format(i), 'gaus')
        fit.SetTitle(histo.GetTitle() + '_fit{}'.format(i))
        fit.SetName(histo.GetTitle() + '_fit{}'.format(i))

        if y_fit_range:
            fit.SetParameter(1, 0.5 * (y_fit_range[0] + y_fit_range[1]))

        projec.Fit(fit, 'R', '', y_fit_range[0], y_fit_range[1])

        slices.append(projec)
        fits.append(fit)

        x_low = histo.GetXaxis().GetBinCenter(x_bin)
        x_high = histo.GetXaxis().GetBinCenter(x_bin + x_bin_step)
        x_values.append(0.5 * (x_high + x_low))

    means = array('d')
    means_err = array('d')
    stds = array('d')
    stds_err = array('d')
    zeros = array('d')

    for f in fits:
        means.append(f.GetParameter(1))
        means_err.append(f.GetParError(1))
        stds.append(f.GetParameter(2))
        stds_err.append(
            f.GetParError(1))  ### change if want the sigma of dist.
        zeros.append(0.0)

    graph = TGraphErrors(len(x_values), x_values, means, zeros, stds_err)
    graph.SetName('g_' + histo.GetName())
    graph.SetMarkerStyle(21)
    graph.SetMarkerColor(kRed)

    return graph, slices, fits