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 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.º 3
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.º 4
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.º 5
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.º 6
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.º 7
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.º 8
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.º 9
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 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.º 11
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.º 12
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.º 13
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.º 14
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 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
Ejemplo n.º 16
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'
Ejemplo n.º 17
0
def create_linearitygraph(n, energies, energieserrors, means, sigmameans, graphname):
	"""Function to perform ROOT graphs of resolutions"""
	#How many points
	n = int(n)

	TGraphlinearity = TGraphErrors(n, energies, means, energieserrors, sigmameans)
	
	#Draw + DrawOptions, Fit + parameter estimation
	Style = gStyle
	Style.SetOptFit()
	XAxis = TGraphlinearity.GetXaxis() #TGraphresolution
	TGraphlinearity.SetMarkerColor(4)
	TGraphlinearity.SetMarkerStyle(20)
	TGraphlinearity.SetMarkerSize(2)
	XAxis.SetTitle("Energy (GeV)")
	YAxis = TGraphlinearity.GetYaxis()
	YAxis.SetTitle("Mean/TrueEnergy")
	TGraphlinearity.Draw("AP")
	gPad.SaveAs(graphname)
	gPad.Close()
Ejemplo n.º 18
0
def getResponseGraph(file):
    print "Read=", file
    i = 0
    g1 = TGraphErrors()
    for line in open(file, "r"):
        columns = line.split(',')
        pt = float(columns[0])
        pt_err = float(columns[1])
        sigma = float(columns[2])
        err = float(columns[3])
        g1.SetPoint(i, pt, sigma)
        ex = pt_err
        ey = err
        g1.SetPointError(i, ex, ey)
        i = i + 1

    g1.SetMarkerColor(1)
    g1.SetMarkerStyle(20)
    g1.SetMarkerSize(0.5)

    # g1->Print();
    return g1
Ejemplo n.º 19
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
Ejemplo n.º 20
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")
Ejemplo n.º 21
0
    def draw_bemc_match(self, cent_low, cent_high):
        h_tpc_e = self.get_subtract(self.hist_sige, cent_low, cent_high)
        h_tpc_e.SetName("h_tpc_e")
        h_bemcmatch = self.get_subtract(self.hist_bemcmatch, cent_low,
                                        cent_high)
        h_bemcmatch.SetName("h_bemcmatch")
        ymax = h_tpc_e.GetMaximum()
        haxis = histo(0, 10, 1, ymax * 3.5, "p_{T}(GeV/c)", "Counts")
        haxis.SetNdivisions(510)

        h_tpc_e.SetLineColor(600)
        h_tpc_e.SetFillColor(600)
        h_tpc_e.SetFillStyle(1001)
        h_tpc_e.SetMarkerStyle(1)
        h_tpc_e.SetMarkerColor(600)
        h_bemcmatch.SetLineColor(632)
        h_bemcmatch.SetFillColorAlpha(632, 1)
        h_bemcmatch.SetFillStyle(1001)
        h_bemcmatch.SetMarkerStyle(1)
        h_bemcmatch.SetMarkerColor(632)
        leg = TLegend(0.55, 0.5, 0.8, 0.65)
        leg.SetBorderSize(0)
        leg.SetTextSize(0.035)
        leg.SetTextFont(132)
        leg.AddEntry(h_tpc_e, "TPC electron", "f")
        leg.AddEntry(h_bemcmatch, "BEMC match electon", "f")
        data_set = "Run10 Au+Au@200GeV MinBias"
        cent_range = "{}-{}% centrality".format(self.cent_list1[cent_high],
                                                self.cent_list2[cent_low])
        c = TCanvas("c", "c", 1000, 800)
        haxis.SetStats(0)
        haxis.Draw()
        gPad.SetLogy()
        h_tpc_e.Draw("histsamelfbar2")
        h_bemcmatch.Draw("histsamelfbar2")
        leg.Draw("same")
        drawLatex(0.55, 0.72, data_set, 0.035, 132, 1)
        drawLatex(0.55, 0.67, cent_range, 0.035, 132, 1)
        c.SaveAs("tpc_e.png")
        self.__canvas__.cd()
        c.Write("tpc_e")
        c1 = TCanvas("c1", "c1", 1000, 800)
        gr = TGraphErrors()
        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, 5.0, 5.5, 6.0
        ]
        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, 5.5, 6.0, 7.0
        ]
        for i in range(0, len(p_bin1)):
            xlow = h_tpc_e.GetXaxis().FindBin(p_bin1[i] + 1E-3)
            xup = h_tpc_e.GetXaxis().FindBin(p_bin2[i] + 1E-3)
            N = h_tpc_e.Integral(xlow, xup)
            xlow = h_bemcmatch.GetXaxis().FindBin(p_bin1[i] + 1E-3)
            xup = h_bemcmatch.GetXaxis().FindBin(p_bin2[i] + 1E-3)
            m = h_bemcmatch.Integral(xlow, xup)
            gr.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N)
            gr.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, eff_err(m, N))
        hx = histo(0, 10, 0, 1.5, "p_{T}(GeV/c)", "TOF match efficiency")
        hx.Draw()
        gr.Draw("psame")
        gr.SetMarkerStyle(20)
        gr.SetMarkerSize(1.5)
        gr.SetMarkerColor(632)
        canvas_file = self.__canvas__
        canvas_file.cd()
        c1.Write("bemc_match_eff")
        c1.SaveAs("bemc_match_eff.png")
Ejemplo n.º 22
0
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' )

func1 = TF1('fun1', 'x', 0., 100.)
func1.SetLineColor(4)
Ejemplo n.º 23
0
    dya4.append(r["defafr4"])
    ya5.append(r["efaem888"])
    dya5.append(r["defaem888"])
    hv = r["hveff"]
    # calibration fausse d'un facteur 3 (7.2/2.4)
    thrc = "%.0f_{HR}/%.0f_{LR} fC" % (r["hrq"] * 3, r["lrq"] * 3)
    print(' i %i %f %f ' % (i, x[n], y5[n]))
    if (y4[n] < leff):
        leff = y4[n]
    if (y5[n] < leff):
        leff = y5[n]
    n = n + 1

gr4 = TGraphErrors(n, x, y4, dx, dy4)

gr4.SetMarkerColor(1)
gr4.SetMarkerStyle(20)
gr4.SetTitle('HV scan Threshold=%s' % thrc)
#gr4.GetXaxis().SetTitle( 'Threshold (fC)' )
gr4.GetXaxis().SetTitle('HV_{eff} (V)')
gr4.GetYaxis().SetTitle('Efficiency (%)')

gr4.GetYaxis().SetRangeUser(leff - 10, 103.)
gr4.Draw('AP')
gr5 = TGraphErrors(n, x, y5, dx, dy5)
gr5.SetMarkerColor(2)
gr5.SetMarkerStyle(22)
gr5.Draw('PSAME')

gra4 = TGraphErrors(n, x, ya4, dx, dya4)
gra4.SetMarkerColor(3)
Ejemplo 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()
Ejemplo n.º 25
0
def main(argv):
    #Usage controls from OptionParser
    parser_usage = ""
    parser = OptionParser(usage=parser_usage)
    (options, args) = parser.parse_args(argv)
    if (len(args) != 2 and len(args) != 3):
        parser.print_help()
        return

    c1 = TCanvas("c1", "c1", 1200, 800)

    f_18deg = TFile.Open(argv[0])
    f_10deg = TFile.Open(argv[1])
    if (len(args) == 3): f_5deg = TFile.Open(argv[2])

    size = 1.3

    gr_L1_US_18deg = f_18deg.Get("gr_layer1_US_RMS")
    gr_L2_US_18deg = f_18deg.Get("gr_layer2_US_RMS")
    gr_L3_US_18deg = f_18deg.Get("gr_layer3_US_RMS")
    gr_L4_US_18deg = f_18deg.Get("gr_layer4_US_RMS")
    gr_global_US_18deg = f_18deg.Get("gr_global_US_RMS")
    gr_L1_US_10deg = f_10deg.Get("gr_layer1_US_RMS")
    gr_L2_US_10deg = f_10deg.Get("gr_layer2_US_RMS")
    gr_L3_US_10deg = f_10deg.Get("gr_layer3_US_RMS")
    gr_L4_US_10deg = f_10deg.Get("gr_layer4_US_RMS")
    gr_global_US_10deg = f_10deg.Get("gr_global_US_RMS")
    if (len(args) == 3): gr_L1_US_5deg = f_5deg.Get("gr_layer1_US_RMS")
    if (len(args) == 3): gr_L2_US_5deg = f_5deg.Get("gr_layer2_US_RMS")
    if (len(args) == 3): gr_L3_US_5deg = f_5deg.Get("gr_layer3_US_RMS")
    if (len(args) == 3): gr_L4_US_5deg = f_5deg.Get("gr_layer4_US_RMS")
    if (len(args) == 3): gr_global_US_5deg = f_5deg.Get("gr_global_US_RMS")

    color = kRed
    gr_L1_US_18deg.SetLineColor(color)
    gr_L1_US_18deg.SetMarkerColor(color)
    gr_L1_US_18deg.SetMarkerSize(size)
    gr_L1_US_18deg.SetMarkerStyle(kOpenCircle)
    gr_L1_US_10deg.SetLineColor(color)
    gr_L1_US_10deg.SetMarkerColor(color)
    gr_L1_US_10deg.SetMarkerSize(size)
    gr_L1_US_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_L1_US_5deg.SetLineColor(color)
    if (len(args) == 3): gr_L1_US_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_L1_US_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_L1_US_5deg.SetMarkerStyle(kRad)
    color = kGreen + 3
    gr_L2_US_18deg.SetLineColor(color)
    gr_L2_US_18deg.SetMarkerColor(color)
    gr_L2_US_18deg.SetMarkerSize(size)
    gr_L2_US_18deg.SetMarkerStyle(kOpenCircle)
    gr_L2_US_10deg.SetLineColor(color)
    gr_L2_US_10deg.SetMarkerColor(color)
    gr_L2_US_10deg.SetMarkerSize(size)
    gr_L2_US_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_L2_US_5deg.SetLineColor(color)
    if (len(args) == 3): gr_L2_US_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_L2_US_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_L2_US_5deg.SetMarkerStyle(kRad)
    color = kBlue
    gr_L3_US_18deg.SetLineColor(color)
    gr_L3_US_18deg.SetMarkerColor(color)
    gr_L3_US_18deg.SetMarkerSize(size)
    gr_L3_US_18deg.SetMarkerStyle(kOpenCircle)
    gr_L3_US_10deg.SetLineColor(color)
    gr_L3_US_10deg.SetMarkerColor(color)
    gr_L3_US_10deg.SetMarkerSize(size)
    gr_L3_US_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_L3_US_5deg.SetLineColor(color)
    if (len(args) == 3): gr_L3_US_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_L3_US_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_L3_US_5deg.SetMarkerStyle(kRad)
    color = kMagenta
    gr_L4_US_18deg.SetLineColor(color)
    gr_L4_US_18deg.SetMarkerColor(color)
    gr_L4_US_18deg.SetMarkerSize(size)
    gr_L4_US_18deg.SetMarkerStyle(kOpenCircle)
    gr_L4_US_10deg.SetLineColor(color)
    gr_L4_US_10deg.SetMarkerColor(color)
    gr_L4_US_10deg.SetMarkerSize(size)
    gr_L4_US_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_L4_US_5deg.SetLineColor(color)
    if (len(args) == 3): gr_L4_US_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_L4_US_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_L4_US_5deg.SetMarkerStyle(kRad)
    color = kBlack
    gr_global_US_18deg.SetLineColor(color)
    gr_global_US_18deg.SetMarkerColor(color)
    gr_global_US_18deg.SetMarkerSize(size)
    gr_global_US_18deg.SetMarkerStyle(kOpenCircle)
    gr_global_US_10deg.SetLineColor(color)
    gr_global_US_10deg.SetMarkerColor(color)
    gr_global_US_10deg.SetMarkerSize(size)
    gr_global_US_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_global_US_5deg.SetLineColor(color)
    if (len(args) == 3): gr_global_US_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_global_US_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_global_US_5deg.SetMarkerStyle(kRad)

    gr_L1_US_18deg.SetTitle("Upstream Pedestal Width " + year)
    gr_L1_US_18deg.GetXaxis().SetTitle("SiPM bias voltage (V)")
    gr_L1_US_18deg.GetYaxis().SetTitle("Pedestal RMS (ADC units)")
    gr_L1_US_18deg.GetYaxis().SetRangeUser(1, 2.5)
    gr_L1_US_18deg.Draw("APx")
    gr_L2_US_18deg.Draw("Pxsame")
    gr_L3_US_18deg.Draw("Pxsame")
    gr_L4_US_18deg.Draw("Pxsame")
    gr_global_US_18deg.Draw("Pxsame")
    gr_L1_US_10deg.Draw("Pxsame")
    gr_L2_US_10deg.Draw("Pxsame")
    gr_L3_US_10deg.Draw("Pxsame")
    gr_L4_US_10deg.Draw("Pxsame")
    gr_global_US_10deg.Draw("Pxsame")
    if (len(args) == 3): gr_L1_US_5deg.Draw("Pxsame")
    if (len(args) == 3): gr_L2_US_5deg.Draw("Pxsame")
    if (len(args) == 3): gr_L3_US_5deg.Draw("Pxsame")
    if (len(args) == 3): gr_L4_US_5deg.Draw("Pxsame")
    if (len(args) == 3): gr_global_US_5deg.Draw("Pxsame")

    legend = TLegend(
        0.13, 0.45, 0.7, 0.85
    )  #0.1 is lower limit of plot, 0.9 is upper limit (beyond on either side is labeling+whitespace)
    legend.AddEntry(gr_L1_US_18deg, "Layer 1 (18 Celcius)", "pl")
    legend.AddEntry(gr_L1_US_10deg, "Layer 1 (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_L1_US_5deg, "Layer 1 (5 Celcius)", "pl")
    legend.AddEntry(gr_L2_US_18deg, "Layer 2 (18 Celcius)", "pl")
    legend.AddEntry(gr_L2_US_10deg, "Layer 2 (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_L2_US_5deg, "Layer 2 (5 Celcius)", "pl")
    legend.AddEntry(gr_L3_US_18deg, "Layer 3 (18 Celcius)", "pl")
    legend.AddEntry(gr_L3_US_10deg, "Layer 3 (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_L3_US_5deg, "Layer 3 (5 Celcius)", "pl")
    legend.AddEntry(gr_L4_US_18deg, "Layer 4 (18 Celcius)", "pl")
    legend.AddEntry(gr_L4_US_10deg, "Layer 4 (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_L4_US_5deg, "Layer 4 (5 Celcius)", "pl")
    legend.AddEntry(gr_global_US_18deg, "ALL upstream (18 Celcius)", "pl")
    legend.AddEntry(gr_global_US_10deg, "ALL upstream (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_global_US_5deg, "ALL upstream (5 Celcius)", "pl")
    legend.Draw()
    c1.SaveAs("plots/upstream" + year + ".png")

    gr_L1_DS_18deg = f_18deg.Get("gr_layer1_DS_RMS")
    gr_L2_DS_18deg = f_18deg.Get("gr_layer2_DS_RMS")
    gr_L3_DS_18deg = f_18deg.Get("gr_layer3_DS_RMS")
    gr_L4_DS_18deg = f_18deg.Get("gr_layer4_DS_RMS")
    gr_global_DS_18deg = f_18deg.Get("gr_global_DS_RMS")
    gr_L1_DS_10deg = f_10deg.Get("gr_layer1_DS_RMS")
    gr_L2_DS_10deg = f_10deg.Get("gr_layer2_DS_RMS")
    gr_L3_DS_10deg = f_10deg.Get("gr_layer3_DS_RMS")
    gr_L4_DS_10deg = f_10deg.Get("gr_layer4_DS_RMS")
    gr_global_DS_10deg = f_10deg.Get("gr_global_DS_RMS")
    if (len(args) == 3): gr_L1_DS_5deg = f_5deg.Get("gr_layer1_DS_RMS")
    if (len(args) == 3): gr_L2_DS_5deg = f_5deg.Get("gr_layer2_DS_RMS")
    if (len(args) == 3): gr_L3_DS_5deg = f_5deg.Get("gr_layer3_DS_RMS")
    if (len(args) == 3): gr_L4_DS_5deg = f_5deg.Get("gr_layer4_DS_RMS")
    if (len(args) == 3): gr_global_DS_5deg = f_5deg.Get("gr_global_DS_RMS")

    color = kRed
    gr_L1_DS_18deg.SetLineColor(color)
    gr_L1_DS_18deg.SetMarkerColor(color)
    gr_L1_DS_18deg.SetMarkerSize(size)
    gr_L1_DS_18deg.SetMarkerStyle(kOpenCircle)
    gr_L1_DS_10deg.SetLineColor(color)
    gr_L1_DS_10deg.SetMarkerColor(color)
    gr_L1_DS_10deg.SetMarkerSize(size)
    gr_L1_DS_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_L1_DS_5deg.SetLineColor(color)
    if (len(args) == 3): gr_L1_DS_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_L1_DS_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_L1_DS_5deg.SetMarkerStyle(kRad)
    color = kGreen + 3
    gr_L2_DS_18deg.SetLineColor(color)
    gr_L2_DS_18deg.SetMarkerColor(color)
    gr_L2_DS_18deg.SetMarkerSize(size)
    gr_L2_DS_18deg.SetMarkerStyle(kOpenCircle)
    gr_L2_DS_10deg.SetLineColor(color)
    gr_L2_DS_10deg.SetMarkerColor(color)
    gr_L2_DS_10deg.SetMarkerSize(size)
    gr_L2_DS_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_L2_DS_5deg.SetLineColor(color)
    if (len(args) == 3): gr_L2_DS_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_L2_DS_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_L2_DS_5deg.SetMarkerStyle(kRad)
    color = kBlue
    gr_L3_DS_18deg.SetLineColor(color)
    gr_L3_DS_18deg.SetMarkerColor(color)
    gr_L3_DS_18deg.SetMarkerSize(size)
    gr_L3_DS_18deg.SetMarkerStyle(kOpenCircle)
    gr_L3_DS_10deg.SetLineColor(color)
    gr_L3_DS_10deg.SetMarkerColor(color)
    gr_L3_DS_10deg.SetMarkerSize(size)
    gr_L3_DS_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_L3_DS_5deg.SetLineColor(color)
    if (len(args) == 3): gr_L3_DS_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_L3_DS_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_L3_DS_5deg.SetMarkerStyle(kRad)
    color = kMagenta
    gr_L4_DS_18deg.SetLineColor(color)
    gr_L4_DS_18deg.SetMarkerColor(color)
    gr_L4_DS_18deg.SetMarkerSize(size)
    gr_L4_DS_18deg.SetMarkerStyle(kOpenCircle)
    gr_L4_DS_10deg.SetLineColor(color)
    gr_L4_DS_10deg.SetMarkerColor(color)
    gr_L4_DS_10deg.SetMarkerSize(size)
    gr_L4_DS_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_L4_DS_5deg.SetLineColor(color)
    if (len(args) == 3): gr_L4_DS_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_L4_DS_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_L4_DS_5deg.SetMarkerStyle(kRad)
    color = kBlack
    gr_global_DS_18deg.SetLineColor(color)
    gr_global_DS_18deg.SetMarkerColor(color)
    gr_global_DS_18deg.SetMarkerSize(size)
    gr_global_DS_18deg.SetMarkerStyle(kOpenCircle)
    gr_global_DS_10deg.SetLineColor(color)
    gr_global_DS_10deg.SetMarkerColor(color)
    gr_global_DS_10deg.SetMarkerSize(size)
    gr_global_DS_10deg.SetMarkerStyle(kSquare)
    if (len(args) == 3): gr_global_DS_5deg.SetLineColor(color)
    if (len(args) == 3): gr_global_DS_5deg.SetMarkerColor(color)
    if (len(args) == 3): gr_global_DS_5deg.SetMarkerSize(size)
    if (len(args) == 3): gr_global_DS_5deg.SetMarkerStyle(kRad)

    gr_L1_DS_18deg.SetTitle("Downstream Pedestal Width " + year)
    gr_L1_DS_18deg.GetXaxis().SetTitle("SiPM bias voltage (V)")
    gr_L1_DS_18deg.GetYaxis().SetTitle("Pedestal RMS (ADC units)")
    gr_L1_DS_18deg.GetYaxis().SetRangeUser(1, 2.5)
    gr_L1_DS_18deg.Draw("APx")
    gr_L2_DS_18deg.Draw("Pxsame")
    gr_L3_DS_18deg.Draw("Pxsame")
    gr_L4_DS_18deg.Draw("Pxsame")
    gr_global_DS_18deg.Draw("Pxsame")
    gr_L1_DS_10deg.Draw("Pxsame")
    gr_L2_DS_10deg.Draw("Pxsame")
    gr_L3_DS_10deg.Draw("Pxsame")
    gr_L4_DS_10deg.Draw("Pxsame")
    gr_global_DS_10deg.Draw("Pxsame")
    if (len(args) == 3): gr_L1_DS_5deg.Draw("Pxsame")
    if (len(args) == 3): gr_L2_DS_5deg.Draw("Pxsame")
    if (len(args) == 3): gr_L3_DS_5deg.Draw("Pxsame")
    if (len(args) == 3): gr_L4_DS_5deg.Draw("Pxsame")
    if (len(args) == 3): gr_global_DS_5deg.Draw("Pxsame")

    legend = TLegend(
        0.13, 0.45, 0.7, 0.85
    )  #0.1 is lower limit of plot, 0.9 is upper limit (beyond on either side is labeling+whitespace)
    legend.AddEntry(gr_L1_DS_18deg, "Layer 1 (18 Celcius)", "pl")
    legend.AddEntry(gr_L1_DS_10deg, "Layer 1 (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_L1_DS_5deg, "Layer 1 (5 Celcius)", "pl")
    legend.AddEntry(gr_L2_DS_18deg, "Layer 2 (18 Celcius)", "pl")
    legend.AddEntry(gr_L2_DS_10deg, "Layer 2 (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_L2_DS_5deg, "Layer 2 (5 Celcius)", "pl")
    legend.AddEntry(gr_L3_DS_18deg, "Layer 3 (18 Celcius)", "pl")
    legend.AddEntry(gr_L3_DS_10deg, "Layer 3 (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_L3_DS_5deg, "Layer 3 (5 Celcius)", "pl")
    legend.AddEntry(gr_L4_DS_18deg, "Layer 4 (18 Celcius)", "pl")
    legend.AddEntry(gr_L4_DS_10deg, "Layer 4 (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_L4_DS_5deg, "Layer 4 (5 Celcius)", "pl")
    legend.AddEntry(gr_global_DS_18deg, "ALL downstream (18 Celcius)", "pl")
    legend.AddEntry(gr_global_DS_10deg, "ALL downstream (10 Celcius)", "pl")
    if (len(args) == 3):
        legend.AddEntry(gr_global_DS_5deg, "ALL downstream (5 Celcius)", "pl")
    legend.Draw()
    c1.SaveAs("plots/downstream" + year + ".png")

    #Difference plots
    size = 0.8
    gr_diff_L1 = TGraphErrors()
    gr_diff_L2 = TGraphErrors()
    gr_diff_L3 = TGraphErrors()
    gr_diff_L4 = TGraphErrors()
    gr_diff_G = TGraphErrors()
    if temp_4PlottingDiff == "5":
        gr_diff_L1 = f_5deg.Get("gr_layer1_diff_RMS")
        gr_diff_L2 = f_5deg.Get("gr_layer2_diff_RMS")
        gr_diff_L3 = f_5deg.Get("gr_layer3_diff_RMS")
        gr_diff_L4 = f_5deg.Get("gr_layer4_diff_RMS")
        gr_diff_G = f_5deg.Get("gr_global_diff_RMS")
    if temp_4PlottingDiff == "10":
        gr_diff_L1 = f_10deg.Get("gr_layer1_diff_RMS")
        gr_diff_L2 = f_10deg.Get("gr_layer2_diff_RMS")
        gr_diff_L3 = f_10deg.Get("gr_layer3_diff_RMS")
        gr_diff_L4 = f_10deg.Get("gr_layer4_diff_RMS")
        gr_diff_G = f_10deg.Get("gr_global_diff_RMS")
    if temp_4PlottingDiff == "18":
        gr_diff_L1 = f_18deg.Get("gr_layer1_diff_RMS")
        gr_diff_L2 = f_18deg.Get("gr_layer2_diff_RMS")
        gr_diff_L3 = f_18deg.Get("gr_layer3_diff_RMS")
        gr_diff_L4 = f_18deg.Get("gr_layer4_diff_RMS")
        gr_diff_G = f_18deg.Get("gr_global_diff_RMS")
    gr_diff_L1.SetMarkerColor(kBlack)
    gr_diff_L2.SetMarkerColor(kRed)
    gr_diff_L3.SetMarkerColor(kBlue)
    gr_diff_L4.SetMarkerColor(kMagenta)
    gr_diff_G.SetMarkerColor(kBlack)
    gr_diff_L1.SetMarkerStyle(20)
    gr_diff_L2.SetMarkerStyle(20)
    gr_diff_L3.SetMarkerStyle(20)
    gr_diff_L4.SetMarkerStyle(20)
    gr_diff_G.SetMarkerStyle(kOpenCircle)
    gr_diff_L1.SetMarkerSize(size)
    gr_diff_L2.SetMarkerSize(size)
    gr_diff_L3.SetMarkerSize(size)
    gr_diff_L4.SetMarkerSize(size)
    gr_diff_G.SetMarkerSize(size)

    gr_diff_L1.Draw("APx")
    c1.SaveAs("plots/diff_L1_" + year + "_" + temp_4PlottingDiff + "C.png")
    gr_diff_L2.Draw("APx")
    c1.SaveAs("plots/diff_L2_" + year + "_" + temp_4PlottingDiff + "C.png")
    gr_diff_L3.Draw("APx")
    c1.SaveAs("plots/diff_L3_" + year + "_" + temp_4PlottingDiff + "C.png")
    gr_diff_L4.Draw("APx")
    c1.SaveAs("plots/diff_L4_" + year + "_" + temp_4PlottingDiff + "C.png")
    gr_diff_G.Draw("APx")
    c1.SaveAs("plots/diff_global_" + year + "_" + temp_4PlottingDiff + "C.png")

    legend = TLegend(
        0.13 + 0.15, 0.65, 0.5 + 0.15, 0.85
    )  #0.1 is lower limit of plot, 0.9 is upper limit (beyond on either side is labeling+whitespace)
    legend.AddEntry(gr_diff_L1, "Layer 1", "pl")
    legend.AddEntry(gr_diff_L2, "Layer 2 / #sqrt{2}", "pl")
    legend.AddEntry(gr_diff_L3, "Layer 3 / #sqrt{3}", "pl")
    legend.AddEntry(gr_diff_L4, "Layer 4 / #sqrt{4}", "pl")
    gr_diff_L1.SetTitle("")
    gr_diff_L1.Draw("APx")
    gr_diff_L2.Draw("pxsame")
    gr_diff_L3.Draw("pxsame")
    gr_diff_L4.Draw("pxsame")
    legend.Draw()
    c1.SaveAs("plots/diff" + year + "_" + temp_4PlottingDiff + "C.png")

    print("Done ")
Ejemplo n.º 26
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
Ejemplo n.º 27
0
                       math.pow(math.pow(10, 10 + i * 0.5), 0.33)))
    print str(
        Number_of_Atom(Avalanche_region1,
                       math.pow(math.pow(10, 10 + i * 0.5), 0.33)))
    print str(
        Number_of_Atom(Avalanche_region,
                       math.pow(math.pow(10, 10 + i * 0.5), 0.33)))

c = TCanvas("c1", "c1", 0, 0, 500, 500)

gStyle.SetOptFit()
gr = TGraphErrors(17, xarray, yarray, xarrayerror, yarrayerror)
gr1 = TGraphErrors(17, xarray, yarray1, xarrayerror, yarrayerror)

gr.SetLineStyle(1)
gr.SetMarkerColor(2)
gr.SetMarkerStyle(8)
gr.SetLineWidth(2)

gr1.SetLineStyle(1)
gr1.SetMarkerColor(3)
gr1.SetMarkerStyle(8)
gr1.SetLineWidth(2)

gr1.SetTitle(";Concentration(1/cm^{3}) ;# of impurities ")
gr1.GetHistogram().SetMaximum(30)
gr1.GetHistogram().SetMinimum(0)
gr1.GetXaxis().SetLimits(math.pow(10, 10 + 0 * 0.5),
                         math.pow(10, 10 + 16 * 0.5))

leg1 = TLegend(0.2, 0.7, 0.5, 0.9)
Ejemplo n.º 28
0
def Plot2DCorrection(hist2D,
                     graph,
                     f1,
                     etBin=None,
                     etaBin=None,
                     outname=None,
                     xlabel='N_{vtx}',
                     runLabel=None,
                     legends=None,
                     extraText1=None,
                     legendX1=.5,
                     etidx=None,
                     etaidx=None,
                     etlist=None,
                     etalist=None):

    import array as ar
    from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack, TLine, kBird, kOrange
    from ROOT import TGraphErrors, TF1, TColor
    pileup_max = hist2D.GetYaxis().GetXmax()
    pileup_min = hist2D.GetYaxis().GetXmin()
    # Retrieve some usefull information
    gStyle.SetPalette(kBird)
    canvas = TCanvas('canvas', 'canvas', 500, 500)
    #FormatCanvasAxes(canvas, XLabelSize=18, YLabelSize=18, XTitleOffset=0.87, YTitleOffset=1.5)
    canvas.SetRightMargin(0.12)
    canvas.SetLeftMargin(0.10)
    hist2D.Draw('colz')
    hist2D.GetZaxis().SetTitle("Entries")
    canvas.SetLogz()
    AddTopLabels(canvas,
                 legends,
                 runLabel=runLabel,
                 legOpt='p',
                 etlist=etlist,
                 etalist=etalist,
                 etidx=etidx,
                 etaidx=etaidx)
    FormatCanvasAxes(canvas,
                     XLabelSize=12,
                     YLabelSize=12,
                     XTitleOffset=0.87,
                     ZLabelSize=12,
                     ZTitleSize=14,
                     YTitleOffset=0.87,
                     ZTitleOffset=0.67)
    SetAxisLabels(canvas, 'Neural Network output (Discriminant)', xlabel)
    # Invert graph
    import array
    x = graph.GetX()
    x.SetSize(graph.GetN())
    ex = graph.GetEX()
    ex.SetSize(graph.GetN())
    y = graph.GetY()
    y.SetSize(graph.GetN())
    ey = graph.GetEY()
    ey.SetSize(graph.GetN())
    nvtx_points = array.array('d', x)
    nvtx_error_points = array.array('d', ex)
    discr_points = array.array('d', y)
    discr_error_points = array.array('d', ey)
    g1 = TGraphErrors(len(discr_points), discr_points, nvtx_points,
                      discr_error_points, nvtx_error_points)
    g1.SetLineWidth(1)
    #g1.SetLineColor(kBlack)
    g1.SetMarkerColor(kBlue + 1)
    g1.SetMarkerSize(.6)
    g1.Draw("P same")
    tobject_collector.append(g1)
    #l2 = TLine(eff_uncorr.thres,miny,eff_uncorr.thres,maxy)
    #l2.SetLineColor(kRed)
    #l2.SetLineWidth(2)
    #l2.Draw("l,same")
    #tobject_collector.append(l2)
    #f1 = eff.f1
    if type(f1) is not list: f1 = [f1]

    for idx, f in enumerate(f1):
        l3 = TLine(f.Eval(pileup_min), pileup_min, f.Eval(pileup_max),
                   pileup_max)
        if idx > 0: l3.SetLineColor(GetTransparent(kRed))
        else:
            l3.SetLineColor(kBlack)
        l3.SetLineWidth(2)
        l3.Draw("l,same")
        tobject_collector.append(l3)

    if outname: canvas.SaveAs(outname)
Ejemplo n.º 29
0
det5s = array( 'f', [10.532, 23.169, 24.020, 24.086, 24.410, 24.671, 22.142, 18.479, 16.205, 17.676, 18.475, 17.173, 16.702, 18.884, 21.872, 24.723, 24.314, 24.122, 23.831, 23.692, 10.672])
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 )
'''
Ejemplo n.º 30
0
jetToMETTriggerRate.SetPointError(2, 5, 15435538)
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)