Example #1
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;
Example #2
0
class CauchyRelation(object):
    def __init__(self, ref_indexes, err_ref_ind, wavelengths):
        self.name = 'Cauchy Relation'
        self.init_graph(ref_indexes, err_ref_ind, wavelengths)
        self.fit_graph()

    def init_graph(self, ref_indexes, err_ref_ind, wavelengths):
        n = array('d', ref_indexes)
        errn = array('d', err_ref_ind)
        wl = array('d', wavelengths)
        errwl = array('d', [0] * len(wavelengths))
        self.pars = array('d', [0] * 3)  #fit parameters
        self.parerrs = array('d', [0] * 3)  #fit parameter errors
        self.graph = TGraphErrors(len(wavelengths), wl, n, errwl, errn)
        set_graph_style(self.graph)
        self.graph.SetTitle(self.name)

    def fit_graph(self):
        self.func = TF1('cauchy', '[0] + [1]/x**2', 400, 700)
        self.func.SetParameters(10, 1e4)
        self.graph.Fit('cauchy', 'QR')
        self.func.GetParameters(self.pars)
        self.parerrs[0] = self.func.GetParError(0)
        self.parerrs[1] = self.func.GetParError(1)
        self.r = ResGraph(self.graph, self.func)  #creates residual graph
        set_graph_style(self.r.graph)
        self.r.graph.SetTitle(self.r.name)
        return zip(self.pars, self.parerrs)

    def show_res_graph(self):
        show_graph(self.r.graph, self.r.name)

    def show_graph(self):
        show_graph(self.graph, self.name)
Example #3
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
Example #4
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
  def write(self, setup):

    #Rescaling to efficiency
    normalisation = 1/self.histogram.GetBinContent(1)
    #Rescaling everything to have rates
    self.histogram.Scale(normalisation)

    efficiencyPlot = TGraphErrors(self.histogram)
    efficiencyPlot.SetName(self.cfg_ana.plot_name+"_errors")
    efficiencyPlot.SetTitle(self.cfg_ana.plot_title)

    for index in xrange(0, len(efficiencyPlot.GetX())):
      efficiencyPlot.SetPointError(index, 
                                   efficiencyPlot.GetEX()[index], 
                                   sqrt(efficiencyPlot.GetY()[index] * normalisation)
                                  )
    
    c1 = TCanvas ("canvas_" + self.cfg_ana.plot_name, self.cfg_ana.plot_title, 600, 600)
    c1.SetGridx()
    c1.SetGridy()
    efficiencyPlot.Draw("AP")
    c1.Update()
    c1.Write()
    c1.Print(self.cfg_ana.plot_name + ".svg", "svg")
    efficiencyPlot.Write()
Example #6
0
class CorrezioneAreaLunghezza(LettoreFileDebye):
    """Legge il file con Volt, corrente, Rt, Rd e restituisce temperature,
    resistenze ed errori per l'analisi della temperatura di Debye.
    Inserita correzione al primo ordine per la dipendenza della sezione e
    lunghezza del filo dalla temperatura"""

    def __init__(self, *args, **kwargs):
        super(CorrezioneAreaLunghezza, self).__init__(*args, **kwargs)

    def draw(self, output_file):
        self.output_filename = output_file
        with open(output_file, "w") as out_file:
            for T, sigma_T, R, sigma_R in zip(
                    self.T_i,
                    self.sigma_Ti,
                    self.R_i,
                    self.sigma_i):
                out_line = [T, R * (1 + coefficiente_correttivo(T)), sigma_T, sigma_R, "\n"]
                out_line = [str(x) for x in out_line]
                out_line = " ".join(out_line)
                out_file.write(out_line)
        style.cd()
        self.canvas = TCanvas("temperatura_resistenza_can",
                "temperatura_resistenza_can")
        self.graph = TGraphErrors(output_file)
        self.graph.SetTitle("Resistenza del campione;T#[]{K};R#[]{#Omega}")
        self.graph.Draw("ap")
Example #7
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
Example #8
0
def sub2pull(dataHist, pdfwErrs):
    from ROOT import TGraphErrors
    from math import sqrt

    ThePull = TGraphErrors(dataHist.GetN())

    pdfi = 0
    for i in range(0, ThePull.GetN()):
        while (dataHist.GetX()[i] > pdfwErrs.GetX()[pdfi]):
            pdfi += 1
        #print 'pull point:',i,'pdfi:',pdfi
        diff = dataHist.GetY()[i] - pdfwErrs.GetY()[pdfi]
        if (diff < 0):
            err2 = pdfwErrs.GetErrorY(pdfi)**2 + dataHist.GetErrorYhigh(i)**2
        else:
            err2 = pdfwErrs.GetErrorY(pdfi)**2 + dataHist.GetErrorYlow(i)**2
        if (err2>0):
            pull = diff/(sqrt(err2)*1.2)
        else:
            pull = 0

        ThePull.SetPoint(i, dataHist.GetX()[i], pull)
        ThePull.SetPointError(i, 0., 1.)

    ThePull.SetName(dataHist.GetName() + "_pull")
    ThePull.SetTitle("data")

    return ThePull
Example #9
0
def Scale(graph, scale):
    if not graph:
        return

    ArrX = array('d')
    ArrY = array('d')
    ArrXErr = array('d')
    ArrYErr = array('d')

    for i in range(graph.GetN()):
        x = ROOT.Double(0)
        y = ROOT.Double(0)
        graph.GetPoint(i, x, y)
        ex = graph.GetErrorX(i)
        ey = graph.GetErrorY(i)

        ArrX.append(x)
        ArrY.append(y * scale)
        ArrXErr.append(ex)
        ArrYErr.append(ey * scale)

    retTG = TGraphErrors(len(ArrX), ArrX, ArrY, ArrXErr, ArrYErr)
    retTG.SetName(graph.GetName())
    retTG.SetTitle(graph.GetTitle())
    return retTG
Example #10
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;
Example #11
0
class LettoreFileDebye(object):
    """Legge il file con Volt, corrente, Rt, Rd e restituisce temperature,
    resistenze ed errori per l'analisi della temperatura di Debye"""
    def __init__(self, file_name):
        super(LettoreFileDebye, self).__init__()
        self.T_i = []
        self.sigma_Ti = []
        self.R_i = []
        self.sigma_i = []
        with open(file_name) as input_file:
            for line in input_file:
                if "//" in line:
                    continue
                V, I, p_t, p_d = [float(x) for x in line.split()]
                PT = PotenziometroTemperatura(calibrazione_potenziometro_T,
                                              tabella_temperatura, p_t)
                PD = PotenziometroResistenza(calibrazione_potenziometro_D, p_d)
                self.T_i.append(PT.T)
                self.sigma_Ti.append(PT.sigma_T)
                self.R_i.append(PD.R)
                self.sigma_i.append(PD.sigma_R)

    def draw(self, output_file):
        self.output_filename = output_file
        with open(output_file, "w") as out_file:
            for T, sigma_T, R, sigma_R in zip(self.T_i, self.sigma_Ti,
                                              self.R_i, self.sigma_i):
                out_line = [T, R, sigma_T, sigma_R, "\n"]
                out_line = [str(x) for x in out_line]
                out_line = " ".join(out_line)
                out_file.write(out_line)
        style.cd()
        self.canvas = TCanvas("temperatura_resistenza_can",
                              "temperatura_resistenza_can")
        self.graph = TGraphErrors(output_file)
        self.graph.SetTitle("Resistenza del campione;T#[]{K};R#[]{#Omega}")
        self.graph.Draw("ap")

    def tabella_latex(self, output_file):
        with open(output_file, "w") as out_file:
            out_file.write("\\begin{tabular}{r@{ $\\pm$ }lr@{ $\\pm$ }l|cc}\n")
            out_file.write(
                "\\multicolumn{2}{c}{$\\unit[T]{[K]}$} &\\multicolumn{2}{c}{$\\unit[R]{[\\ohm]}$} & $\\sigma_R/ R$ [\%] &  $\\Delta_D / D$ [\%] \\\\\n "
            )
            out_file.write("\\hline\n")
            for T, sigma_T, R, sigma_R in zip(self.T_i, self.sigma_Ti,
                                              self.R_i, self.sigma_i):
                line = [
                    T, sigma_T, R, sigma_R, sigma_R / R * 1e2,
                    alpha * (T0 - T) * 1e2
                ]
                out_file.write(
                    "{0[0]:.1f} & {0[1]:.1f} & {0[2]:.2f} & {0[3]:.2f} & {0[4]:.2f} & {0[5]:.2f} \\\\ \n "
                    .format(line))
            out_file.write("\\end{tabular}")

    def save_as(self, name):
        self.canvas.SaveAs(name)
Example #12
0
 def plot( self, plotoptions, opt="?" ):
     vx= array( "d", self.aostand.getPointsCenter() )
     values= self.values
     sterrs= self.sterrs
     if "m" in opt:
         print "AnalysisObservable::plot: use errors from error matrix"
         sterrs= array( "d", self.aostand.getErrors( "m" ) )
     syerrs= self.syerrs
     npoints= len(vx)
     if "xshift" in plotoptions:
         for i in range(npoints):
             vx[i]+= plotoptions["xshift"]
     vex= array( "d", npoints*[0.0] )
     tgest= TGraphErrors( npoints, vx, values, vex, sterrs )
     toterrs= np.sqrt( np.add( np.square( sterrs ),  np.square( syerrs ) ) )
     tgesy= TGraphErrors( npoints, vx, values, vex, toterrs )
     tgesy.SetMarkerStyle( plotoptions["markerStyle"] )
     tgesy.SetMarkerSize( plotoptions["markerSize"] )
     drawas= plotoptions["drawas"] if "drawas" in plotoptions else "p"
     tgesy.SetName( self.obs )
     if "fillcolor" in plotoptions:
         tgesy.SetFillColor(plotoptions["fillcolor"])
         tgest.SetFillColor(plotoptions["fillcolor"])
     if "s" in opt:
         tgesy.Draw( "psame" )
     else:
         if "title" in plotoptions:
             tgesy.SetTitle( plotoptions["title"] )
         else:
             tgesy.SetTitle( self.obs )
         tgesy.SetMinimum( plotoptions["ymin"] )
         tgesy.SetMaximum( plotoptions["ymax"] )
         xaxis= tgesy.GetXaxis()
         xaxis.SetLimits( plotoptions["xmin"], plotoptions["xmax"] )
         if "xlabel" in plotoptions:
             xaxis.SetTitle( plotoptions["xlabel"] )
         if "ylabel" in plotoptions:
             tgesy.GetYaxis().SetTitle( plotoptions["ylabel"] )
         tgesy.Draw( "a"+drawas )
     optlogx= plotoptions["logx"] if "logx" in plotoptions else 0
     gPad.SetLogx( optlogx )
     optlogy= plotoptions["logy"] if "logy" in plotoptions else 0
     gPad.SetLogy( optlogy )
     tgest.Draw( "same"+drawas )
     return tgest, tgesy
Example #13
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
Example #14
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
Example #15
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)
Example #16
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
Example #17
0
def DrawScat(all_, wrong_, DCAs_, title, fname):

    c = TCanvas("c2", "", 800, 600)

    # Normal arrays don't work for whatever reason, must be a ROOT thing
    x, y, ex, ey = array('d'), array('d'), array('d'), array('d')

    n = len(all_)

    # if(n != len(wrongHist)):
    # print("*** Error, hist arrays different length ***")
    # return

    for i in range(0, n):

        frac = wrong_[i].GetEntries() / all_[i].GetEntries()
        x.append(DCAs_[i])
        ex.append(0)
        y.append(frac)
        ey.append(0)

        print(
            str(DCAs_[i]) + " * " + str(frac) + " * " +
            str(wrong_[i].GetEntries()) + " * " + str(all_[i].GetEntries()))

    scat = TGraphErrors(n, x, y, ex, ey)
    scat.SetTitle(title)

    scat.GetXaxis().SetTitleSize(.04)
    scat.GetYaxis().SetTitleSize(.04)
    scat.GetXaxis().SetTitleOffset(1.1)
    scat.GetYaxis().SetTitleOffset(1.25)
    scat.GetXaxis().CenterTitle(1)
    scat.GetYaxis().CenterTitle(1)
    # scat.GetYaxis().SetRangeUser(0.086,0.106)
    scat.GetXaxis().SetRangeUser(-5, 505)
    scat.GetYaxis().SetMaxDigits(4)
    #scat.SetMarkerSize(3)
    #scat.SetLineWidth(3)
    scat.SetMarkerStyle(20)  # Full circle
    #scat.SetMarkerColor(4)
    #scat.SetLineColor(4)
    scat.Draw("AP")
    c.SaveAs(fname)

    return
def graphTruth():
    fname = "PionMinusG4.txt"
    kineticEnergy = []
    crossSec = []
    crossSec_el = []
    crossSec_inel = []
    zero = []

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

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

    nPoints = len(x)
    # . . . and hand over to TGraphErros object
    gr = TGraphErrors(nPoints, x, y, exl, exr)
    gr.SetTitle(title + "; Kinetic Energy [MeV]; Cross Section [barn]")
    gr.GetXaxis().SetRangeUser(0, 1000)
    gr.GetYaxis().SetRangeUser(0, 2.)
    gr.SetLineWidth(2)
    gr.SetLineColor(kGreen - 2)
    gr.SetFillColor(0)
    return gr
Example #19
0
def DrawScat(hists, DCAs, flag, title, fname):

    c = TCanvas("c2", "", 800, 600)

    # Normal arrays don't work for whatever reason, must be a ROOT thing
    x, y, ex, ey = array('d'), array('d'), array('d'), array('d')
    n = len(hists)

    for i in range(0, n):

        if (flag == 0):
            print(str(DCAs[i]) + " * " + str(hists[i].GetMean()))
            x.append(DCAs[i])
            ex.append(0)
            y.append(hists[i].GetMean())
            ey.append(hists[i].GetMeanError())
        else:
            print(str(DCAs[i]) + " * " + str(hists[i].GetEntries()))
            x.append(DCAs[i])
            ex.append(0)
            y.append(hists[i].GetEntries())
            ey.append(0)

    scat = TGraphErrors(n, x, y, ex, ey)
    scat.SetTitle(title)
    scat.GetXaxis().SetTitleSize(.04)
    scat.GetYaxis().SetTitleSize(.04)
    scat.GetXaxis().SetTitleOffset(1.1)
    scat.GetYaxis().SetTitleOffset(1.25)
    scat.GetXaxis().CenterTitle(1)
    scat.GetYaxis().CenterTitle(1)
    # scat.GetYaxis().SetRangeUser(0.086,0.106)
    scat.GetXaxis().SetRangeUser(-5, 505)
    scat.GetYaxis().SetMaxDigits(4)
    #scat.SetMarkerSize(3)
    #scat.SetLineWidth(3)
    scat.SetMarkerStyle(20)  # Full circle
    #scat.SetMarkerColor(4)
    #scat.SetLineColor(4)
    scat.Draw("AP")
    c.SaveAs(fname)
Example #20
0
def killXErr(graph):
    if not graph:
        return

    ArrX = array('d')
    ArrY = array('d')
    ArrXErr = array('d')
    ArrYErr = array('d')

    for point in range(graph.GetN()):
        ArrX.append(graph.GetX()[point])
        ArrY.append(graph.GetY()[point])
        ArrXErr.append(0)
        ArrYErr.append(graph.GetEY()[point])

    tmpG = TGraphErrors(len(ArrX), ArrX, ArrY, ArrXErr, ArrYErr)
    tmpG.SetName(graph.GetName() + "_noErr")
    tmpG.SetTitle(graph.GetTitle())
    tmpG.GetXaxis().SetTitle(graph.GetXaxis().GetTitle())
    tmpG.GetYaxis().SetTitle(graph.GetYaxis().GetTitle())
    #tmpG.Write()
    return tmpG
Example #21
0
class CalibrazionePotenziometro:
    def __init__(self, tabella):
        self.file_tabella = tabella
        self.gr = TGraphErrors(tabella)
        self.gr.SetTitle("calibrazione potenziometro;potenziometro;R [#Omega]")
        self.result = self.gr.Fit("pol1", "SQ")

    def disegna_grafico(self):
        self.can = TCanvas("can", "can")
        self.gr.Draw("AP")
        can.SaveAs("relazione/img/{0}.eps".format(self.file_tabella))

    def salva_calibrazione(self):
        with open("fit.{0}".format(self.file_tabella), "w") as out_file:
            a = self.result.Parameter(1)
            sigma_a = self.result.ParError(1)
            b = self.result.Parameter(0)
            sigma_b = self.result.ParError(1)
            line = [a, sigma_a, b, sigma_b]
            line = [str(x) for x in line]
            line = " ".join(line)
            out_file.write(line)

    def stampa_tabella(self):
        print("\\begin{tabular}{r@{ $\\pm$ }lr@{ $\\pm$ }l}")
        print(
            "\\multicolumn{2}{c}{$R [\\unit[]{\\ohm}]$} &\\multicolumn{2}{c}{potenziometro} \\\\ "
        )
        print("\\hline")
        with open(name_in) as file:
            for line in file:
                if "//" in line:
                    continue
                line = [float(x) for x in line.split()]
                print(
                    "{0[1]:.2f} & {0[3]:.2f} & {0[0]:.2f} & {0[2]:.2f} \\\\ ".
                    format(line))
        print("\\end{tabular}")
Example #22
0
def SumGraphs(g1, g2, name, title):
    nPoints = g1.GetN()
    if g1.GetN() != g2.GetN():
        print "Mismatch in SumGraphs Points!"
        if g2.GetN() > nPoints:
            nPoints = g2.GetN()

    ArrX = array('d')
    ArrY = array('d')
    ArrXErr = array('d')
    ArrYErr = array('d')

    for gPoint in range(nPoints):
        if int(g1.GetX()[gPoint] * 1000) != int(g2.GetX()[gPoint] * 1000):
            print "Mismatch in X Values!"
            continue
        else:
            ArrX.append(g1.GetX()[gPoint])

        if int(g1.GetEX()[gPoint] * 1000) != int(g2.GetEX()[gPoint] * 1000):
            print "Mismatch in X Error Values!"
            continue
        else:
            ArrXErr.append(g1.GetEX()[gPoint])

        g1Y = ufloat(g1.GetY()[gPoint], g1.GetEY()[gPoint])
        g2Y = ufloat(g2.GetY()[gPoint], g2.GetEY()[gPoint])
        prod = g1Y * g2Y

        ArrY.append(prod.n)
        ArrYErr.append(prod.s)

    SumG = TGraphErrors(len(ArrX), ArrX, ArrY, ArrXErr, ArrYErr)
    SumG.SetName(name)
    SumG.SetTitle(title)

    return SumG
Example #23
0
class Thickness:

    def __init__(self, name):
        self.name = name
        self.canvas = TCanvas(name, name)
        self.canvas.SetFillColor(0)
        self.name_lin = name + "_lin"
        self.linearize()
        self.make_graph()

    def linearize(self):
        with open(self.name) as file:
            with open(self.name_lin, "w") as out_file:
                for line in file:
                    x, i = [float(_) for _ in line.split()]
                    i_err = 1 / sqrt(i)
                    i = log(i)
                    output_line = [x, i, 0, i_err]
                    output_line = " ".join([str(x) for x in output_line])
                    output_line += "\n"
                    out_file.write(output_line)

    def make_graph(self):
        self.graph = TGraphErrors(self.name_lin)
        self.graph.SetTitle(self.name)
        self.graph.GetYaxis().SetTitle("log(n_events)")
        self.graph.GetXaxis().SetTitle("thickness #[]{#mu m}")
        self.graph.SetMarkerStyle(8)
        self.graph.Fit("pol1")

    def draw(self):
        self.canvas.cd()
        self.graph.Draw("ap")

    def save(self):
        self.canvas.SaveAs(self.name + ".eps")
Example #24
0
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)
func1.SetLineStyle(2)
func1.Draw('same')
####
Example #25
0
class waveLength:
    """			***classe waveLength***

	legge un file formattato con tre colonne:

	ordine	nonio A	nonio B
	5	213.54	33.58
	4	212.52	32.48
	...	...	...
	(significa 213°54', 33°58' per il massimo al quinto ordine etc.)

	opera automaticamente la conversione e la media,
	per poi disporre in grafico (self.graph).

	self.fitGraph() esegue l'interpolazione lineare
	self.showGraph() mostra il grafico
	self.saveToEps() salve il grafico in formato .eps

	la lunghezza d'onda con si calcola con self.getWaveLen(),
	che restituisce una valore ed errore in una lista
	"""

    #	a = (12.65e-6, 0.05e-6) #passo del reticolo, con errore
    #	measerr = 5.*2/300 #errore (in gradi) stimato sulla misura col nonio

    def __init__(self, fileName):
        self.wavelen = [0, 0]
        self.name = fileName
        self.nData = 0
        self.deg = array('d')
        self.degerr = array('d')
        self.ord = array('d')
        self.pars = array('d', [0, 0])  #fit parameters
        self.parerrs = array('d', [0, 0])  #fit parameter errors
        self.fillDeg()  #reads data from file
        self.convertToSine()  #centers mean maximum, calculates sines
        self.initGraph()  #initialize graph, set style

    def fillDeg(self):
        file = open(self.name)
        for line in file:
            o = float(line.split()[0])
            n1 = float(line.split()[1]) - 180
            n2 = float(line.split()[2])
            self.ord.append(o)
            int1 = floor(n1)
            int2 = floor(n2)
            rem1 = 5. * (n1 - int1) / 3
            rem2 = 5. * (n2 - int2) / 3
            int1 += rem1
            int2 += rem2
            self.deg.append((int1 + int2) / 2)
            self.degerr.append(measerr / sqrt(2))
            self.nData += 1
        file.close()

    def convertToSine(self):
        j = self.ord.index(0)  #finds central maximum
        center = self.deg[j]
        for i in xrange(self.nData):
            angle = self.deg[i]
            angle -= center
            self.deg[i] = angle
            self.deg[i] = sin(pi * angle / 180)
            self.degerr[i] = cos(angle) * argerr

    def initGraph(self):
        self.graph = TGraphErrors(self.nData, self.ord, self.deg,
                                  array('d', [0] * self.nData), self.degerr)
        self.setGraphStyle()
        pass

    def fitGraph(self):
        line = TF1('line', 'pol1', -5, 5)  #funzione lineare per fit
        self.graph.Fit('line', 'QR')
        line.GetParameters(self.pars)
        self.parerrs[0] = line.GetParError(0)
        self.parerrs[1] = line.GetParError(1)
        return zip(self.pars, self.parerrs)

    def getWaveLen(self):
        self.wavelen[0] = fabs(self.pars[1] * a[0]) * 1e9
        self.wavelen[1] = self.wavelen[0] * sqrt(
            (self.parerrs[1] / self.pars[1])**2 + (a[1] / a[0])**2)
        print 'lambda %s = %.1f \pm %.1f nm' % (self.name, self.wavelen[0],
                                                self.wavelen[1])
        return self.wavelen

    def showGraph(self):
        c = TCanvas(self.name, self.name)
        self.graph.Draw('AEP')
        raw_input('Press ENTER to continue...')

    def saveToEps(self):
        if self.pars[1]:
            c = TCanvas(self.name, self.name)
            self.graph.Draw('AEP')
            c.SaveAs(self.name + '.fit.eps')
        else:
            pass

    def printData(self):
        """test per verificare la corretta lettura dei dati"""
        for o, d, e in zip(self.ord, self.deg, self.degerr):
            print '%i \t %.3f \t %.3f' % (o, d, e)

    def setGraphStyle(self):
        self.graph.SetMarkerStyle(8)
        self.graph.GetXaxis().SetTitle("order")
        self.graph.GetYaxis().SetTitle("sine")
        self.graph.GetYaxis().SetTitleOffset(1.2)
        self.graph.GetXaxis().SetTitleSize(0.03)
        self.graph.GetYaxis().SetTitleSize(0.03)
        self.graph.GetXaxis().SetLabelSize(0.03)
        self.graph.GetYaxis().SetLabelSize(0.03)
        self.graph.GetXaxis().SetDecimals()
        self.graph.GetYaxis().SetDecimals()
        #		self.graph.SetStats( kFALSE );
        self.graph.SetTitle(self.name)
Example #26
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()
Example #27
0
    efffunc.SetParameters(1.0, 500)
    efffunc.FixParameter(0, 1.0)
    s = sliceeff.Fit(efffunc, "S")
    sliceeff.Draw("AP")
    #c.Print(outfilename+".pdf");

    if s.Get() and s.Get().IsValid() and s.Get().CovMatrixStatus() == 3:
        massArr.append(cleanhist.GetYaxis().GetBinCenter(iy))
        zeroArr.append(0)
        xintArr.append(s.Parameter(1))
        yintArr.append(s.Parameter(0))
        xintErrArr.append(s.ParError(1))
        yintErrArr.append(s.ParError(0))

xintgraph = TGraphErrors(len(massArr), massArr, xintArr, zeroArr, xintErrArr)
xintgraph.SetTitle("X-intercept;mass [GeV];D1")
xintgraph.SetName("xintgraph")
xintgraph.Write()
xintgraph.Draw("A*")
xintgraph.GetYaxis().SetRangeUser(0, 1000)
xintgraph.Fit("pol3")
c.Print(outfilename + ".pdf")

yintgraph = TGraphErrors(len(massArr), massArr, yintArr, zeroArr, yintErrArr)
yintgraph.Draw("A*")
yintgraph.GetYaxis().SetRangeUser(0.5, 1.5)
c.Print(outfilename + ".pdf")

#clean.Draw("D1>>cleanslice(10,0,500)",xfcut+" && mass>{0} && mass<{1}".format(5.0,5.2))
#cleanslice = gDirectory.Get("cleanslice")
#messyclean.Draw("D1>>messyslice(10,0,500)",xfcut+" && mass>{0} && mass<{1}".format(5.0,5.2))
Example #28
0
def getHists(contained_only=False):

    # Define the desired energy ranges
    ERanges = [(0.3, 0.5), (0.5, 0.7), (0.7, 0.9), (0.9, 1.1), (1.1, 1.3),
               (1.3, 1.5), (1.5, 1.7), (1.7, 1.9), (1.9, 2.1)]

    # Creating empty histograms
    hist_dictionary = {}
    for myE in ERanges:
        myName = "h_min%s_max%s" % (myE[0], myE[1])
        if contained_only: myName = "cont_h_min%s_max%s" % (myE[0], myE[1])
        myTitle = "Energies from %0.1f to %0.1f;(Recotrack Range p - Reco p) / Recotrack Range p;Entries" % (
            myE[0], myE[1])
        if contained_only:
            myTitle = "Contained Tracks: Energies from %0.1f to %0.1f;(Recotrack Range p - Reco p) / Recotrack Range p;Entries" % (
                myE[0], myE[1])
        hist_dictionary[myE] = TH1D(myName, myTitle, 100, -4, 4)

    # Loop over energy ranges to create graphs of type (2)
    for myE in ERanges:
        myPlot = "(range_recotrack_mom - mcs_reco_mom) / range_recotrack_mom >> h_min%0.1f_max%0.1f" % (
            myE[0], myE[1])
        if contained_only:
            myPlot = "(range_recotrack_mom - mcs_reco_mom) / range_recotrack_mom >> cont_h_min%0.1f_max%0.1f" % (
                myE[0], myE[1])
        myCut = "mcs_reco_mom > 0 && range_recotrack_mom > %f && range_recotrack_mom < %f" % (
            myE[0], myE[1])
        if contained_only: myCut += " && mu_contained_reco == 1"
        f.ana_tree.Draw(myPlot, myCut)

    # Create lists for graphs (3), (4) that will be filled in the next loop
    xpoints = []
    filMeanVals, filSqrtHistEntries = [], []
    filStdVals, filStdErrs = [], []

    for myE in ERanges:
        # Filter out energy ranges with 0 entries
        if hist_dictionary[myE].GetEntries() != 0:
            xpoints.append(myE[0] + (myE[1] - myE[0]) / 2.)
            filMeanVals.append(hist_dictionary[myE].GetMean())
            filSqrtHistEntries.append(
                TMath.sqrt(hist_dictionary[myE].GetEntries()))
            filStdVals.append(hist_dictionary[myE].GetRMS())
            filStdErrs.append(hist_dictionary[myE].GetRMSError())

    # Calculate error bars for graph (3): (stdDev / sqrt(entries))
    yerrs = map(truediv, filStdVals, filSqrtHistEntries)

    # Define a constant width (x-error bar) for each marker
    xerrs = [(myE[1] - myE[0]) / 2. for myE in ERanges]

    # Graph (3) and (4) setup
    meanGraph = TGraphErrors()
    stdGraph = TGraphErrors()

    meanGraphTitle = "Mean vs. Energy;Recotrack Muon Energy from Range (GeV);#left[p_{Reco Range}-p_{MCS} / p_{Reco Range}#right]"
    if contained_only:
        meanGraphTitle = "Contained Tracks: Mean vs. Energy;Recotrack Muon Energy from Range (GeV);#left[p_{Reco Range}-p_{MCS} / p_{Reco Range}#right]"
    stdGraphTitle = "Standard Deviation vs. Energy;Recotrack Muon Energy from Range(GeV);Fractional Momentum Resolution"
    if contained_only:
        stdGraphTitle = "Contained Tracks: Standard Deviation vs. Energy;Recotrack Muon Energy from Range (GeV);Fractional Momentum Resolution"

    meanGraph.SetTitle(meanGraphTitle)
    stdGraph.SetTitle(stdGraphTitle)

    # Fill in data for graph (3)
    for i in xrange(len(xpoints)):
        meanGraph.SetPoint(i, xpoints[i], filMeanVals[i])
        meanGraph.SetPointError(i, xerrs[i], yerrs[i])
    meanGraph.Draw("ALP")

    # Fill in data for graph (4)
    for i in xrange(len(xpoints)):
        stdGraph.SetPoint(i, xpoints[i], filStdVals[i])
        stdGraph.SetPointError(i, xerrs[i], filStdErrs[i])
    stdGraph.Draw("ALP")

    return hist_dictionary, meanGraph, stdGraph
Example #29
0
    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)
gra4.SetMarkerStyle(20)
gra4.Draw('PSAME')
Example #30
0
class GlobBeamSpotRunPlots:
    def  __init__(self,run):
        self.run = run
        self.hFitWidth   = TH1I("run_"+ str(self.run)+"_hFitWidth","Run:" + str(self.run) + " Is Fitted Width", 10,0,10)
        self.hOnline     = TH1I("run_"+ str(self.run)+"_hOnline"  ,"Run:" + str(self.run) + " Is Online", 10,0,10)
        self.hStatus     = TH1I("run_"+ str(self.run)+"_hStatus"  ,"Run:" + str(self.run) + " Status", 10,0,10)
        self.AlgType     = TH1I("run_"+ str(self.run)+"_hAlgType" ,"Run:" + str(self.run) + " Alg Type", 10,0,10)
        self.hPosX       = TH1D("run_"+ str(self.run)+"_hPosX"    ,"Run:" + str(self.run)+ "Beamspot x-positon; x [mm]; events ", 100,-5,5)  
        self.hPosY       = TH1D("run_"+ str(self.run)+"_hPosY"    ,"Run:" + str(self.run)+ "Beamspot y-positon; y [mm]; events ", 100,-5,5)
        self.hPosZ       = TH1D("run_"+ str(self.run)+"_hPosZ"    ,"Run:" + str(self.run)+ "Beamspot z-positon; z [mm]; events ", 100,-50,50)
        self.hSigmaX     = TH1D("run_"+ str(self.run)+"_hSigmaX"  ,"Run:" + str(self.run)+ "Beamspot #sigma_x; #sigma_x [mm]; events ", 100,0,1)
        self.hSigmaY     = TH1D("run_"+ str(self.run)+"_hSigmaY"  ,"Run:" + str(self.run)+ "Beamspot #sigma_y; #sigma_y [mm]; events ", 100,0,1)
        self.hSigmaZ     = TH1D("run_"+ str(self.run)+"_hSigmaZ"  ,"Run:" + str(self.run)+ "Beamspot #sigma_z; #sigma_z [mm]; events ", 100,0,50)
        self.hTiltX      = TH1D("run_"+ str(self.run)+"_hTilitX"  ,"Run:" + str(self.run)+ "Beamspot tilt_x; tilt_x [rad]; events ", 100,-0.01,0.01)
        self.hTiltY      = TH1D("run_"+ str(self.run)+"_hTilitY"  ,"Run:" + str(self.run)+ "Beamspot tilt_y; tilt_y [rad]; events ", 100,-0.01,0.01)

        self.lbMid = [] 
        self.lbEr  = []
        self.lbX   = []
        self.lbSX  = []
        self.lbY   = []
        self.lbSY  = []
        self.lbZ   = []
        self.lbSZ  = []
        
    def fill(self, beamspot):
        (status, online, fitWidth, alg) = getStatus(beamspot.status)
        self.hFitWidth.Fill(fitWidth,1)
        self.hOnline.Fill(online,1)
        self.AlgType.Fill(alg,1)
        self.hStatus.Fill(status,1)
        self.hPosX.Fill(beamspot.posX)
        self.hPosY.Fill(beamspot.posY)
        self.hPosZ.Fill(beamspot.posZ)
        self.hSigmaX.Fill(beamspot.sigmaX)
        self.hSigmaY.Fill(beamspot.sigmaY)
        self.hSigmaZ.Fill(beamspot.sigmaZ)
        self.hTiltX.Fill(beamspot.tiltX)
        self.hTiltY.Fill(beamspot.tiltY)

        (run,lb)   = getRunLumi(beamspot.begin)
        (runE,lbE) = getRunLumi(beamspot.end)
        self.lbMid.append(0.5*( lb + lbE ))
        self.lbEr.append( 0.5*(lb - lbE)) 
        self.lbX.append( beamspot.posX ) 
        self.lbSX.append( beamspot.sigmaX)
        self.lbY.append( beamspot.posY ) 
        self.lbSY.append( beamspot.sigmaY)
        self.lbZ.append( beamspot.posZ) 
        self.lbSZ.append( beamspot.sigmaZ)


    def display(self):
        self.c = TCanvas("run_"+ str(self.run))
        self.c.Divide(4,4)
        self.c.cd(1)
        self.hStatus.Draw()
        self.c.cd(2)
        self.hOnline.Draw()
        self.c.cd(3)
        self.hFitWidth.Draw()
        self.c.cd(4)
        self.AlgType.Draw()
        self.c.cd(5)
        self.hPosX.Draw()
        self.c.cd(9)
        self.hPosY.Draw()
        self.c.cd(13)
        self.hPosZ.Draw()

        self.c.cd(6)
        self.hSigmaX.Draw()
        self.c.cd(10)
        self.hSigmaY.Draw()
        self.c.cd(14)
        self.hSigmaZ.Draw()

        self.c.cd(7)
        self.hTiltX.Draw()
        self.c.cd(11)
        self.hTiltY.Draw()
        
        self.c.cd(8)
        self.gx.Draw("ap")
        self.c.cd(12)
        self.gy.Draw("ap")
        self.c.cd(16)
        self.gz.Draw("ap")
        

    def makeGraphs(self):
        nPoints = len(self.lbMid)
        print "N points", nPoints
        from ROOT import TGraphErrors
        self.gx = TGraphErrors(nPoints)
        self.gx.SetTitle("x-position and width; lb; x [mm]")
        self.gx.SetName("gr_run_"+str(self.run)+"_x")
        self.gy = TGraphErrors(nPoints)
        self.gy.SetTitle("y-position and width; lb; y [mm]")
        self.gy.SetName("gr_run_"+str(self.run)+"_y")
        self.gz = TGraphErrors(nPoints)
        self.gz.SetTitle("z-position and width; lb; z [mm]")
        self.gz.SetName("gr_run_"+str(self.run)+"_z")
        
        for i,lb in enumerate(self.lbMid):
            self.gx.SetPoint(i,lb, self.lbX[i])
            self.gx.SetPointError(i,self.lbEr[i], self.lbSX[i])
            self.gy.SetPoint(i,lb, self.lbY[i])
            self.gy.SetPointError(i,self.lbEr[i], self.lbSY[i])
            self.gz.SetPoint(i,lb, self.lbZ[i])
            self.gz.SetPointError(i,self.lbEr[i], self.lbSZ[i])