Пример #1
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
Пример #2
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;
Пример #3
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
Пример #4
0
def CompareToys(MwValuemT, MwValuemTStat):
    print(len(MwValuemT), len(MwValuemTStat))

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

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

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

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

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

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

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

    outputDir = 'plots/WStudies/%s%s/%s' % (channel, treeSuffix, variable)
    c.Print('%s/Summary.pdf' % outputDir)
Пример #6
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;
Пример #7
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 plotGainSummary(self, strDetName):
        #Create the Plot - Average
        gDet_AvgEffGain = TGraphErrors(len(self.GAIN_AVG_POINTS))
        gDet_AvgEffGain.SetName("g_{0}_EffGainAvg".format(strDetName))

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

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

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

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

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

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

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

        return
Пример #9
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
Пример #10
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
    def plotPDSummary(self, strDetName):
        #Create the Plot - Average
        gDet_AvgPD = TGraphErrors(len(self.PD_AVG_POINTS))
        gDet_AvgPD.SetName("g_{0}_PDAvg".format(strDetName))

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

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

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

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

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

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

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

        return
Пример #12
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)
    def plotGainSummary(self, strDetName):
        #Create the Plot - Average
        gDet_AvgEffGain = TGraphErrors( len(self.GAIN_AVG_POINTS) )
        #gDet_AvgEffGain.SetName("g_" + strDetName + "_EffGainAvg")
        gDet_AvgEffGain.SetName("g_{0}_EffGainAvg".format(strDetName))
        
        #Create the Plot - Max Gain
        gDet_MaxEffGain = TGraphErrors( len(self.GAIN_MAX_POINTS) )
        #gDet_MaxEffGain.SetName("g_" + strDetName + "_EffGainMax")
        gDet_MaxEffGain.SetName("g_{0}_EffGainMax".format(strDetName))

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

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

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

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

        #Write
        dir_Summary = self.FILE_OUT.mkdir("Summary")
        dir_Summary.cd()
        canv_AvgEffGain.Write()
        gDet_AvgEffGain.Write()
        gDet_MaxEffGain.Write()
        gDet_MinEffGain.Write()
        
    	return
Пример #14
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
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
Пример #16
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()
Пример #17
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
Пример #18
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")
Пример #19
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)
Пример #20
0
canvas.SetLogy(0)
text.SetX1NDC(0.12)
text.SetX2NDC(0.52)
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events = TGraphErrors(14)
for x in xrange(1, 15):
  efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetPoint(x - 1, jetToMETTriggerRate.GetY()[x], metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetY()[x])
  efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetPointError(x - 1, jetToMETTriggerRate.GetEY()[x], metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetEY()[x])
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetTitle("ff_H_WW_enuenu_1000events")
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetName("efficiencyPlotWithRate_ff_H_WW_enuenu_1000events")
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetYaxis().SetTitle("% accepted events")
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetYaxis().SetTitleOffset(1.2)
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetYaxis().SetRangeUser(0, 1.1)
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetMarkerColor(4)
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetLineColor(1)
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetMarkerStyle(21)
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetXaxis().SetTitle("Rate [Hz]")
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetXaxis().SetTitleOffset(1.2)
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.Draw("AP")
efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.Write()
line_200kHz.Draw()
label_200kHz.Draw()
text.Draw()
canvas.Update()
canvas.Print("metEfficiencyPlotWithRate_ff_H_WW_enuenu_1000events.svg", "svg")
canvas.Print("metEfficiencyPlotWithRate_ff_H_WW_enuenu_1000events.png", "png")
canvas.Print("metEfficiencyPlotWithRate_ff_H_WW_enuenu_1000events.pdf", "pdf")

canvas.SetLogx(0)
canvas.SetLogy(0)
text.SetX1NDC(0.5)
text.SetX2NDC(0.9)
Пример #21
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')
####

g_reco_eff = TGraphErrors(len(eff_list), array(tolerance_list), reco_eff,
                          no_err, array(eff_err_list))
g_eff = TGraphErrors(len(eff_list), array(tolerance_list), array(eff_list),
                     no_err, array(eff_err_list))
g_purity = TGraphErrors(len(purity_list), array(tolerance_list),
                        array(purity_list), no_err, array(purity_err_list))
g_acceptance = TGraphErrors(len(acceptance), array(tolerance_list),
                            array(acceptance), no_err, array(purity_err_list))
g_reco_eff_data = TGraphErrors(len(reco_eff_list), array(tolerance_list),
                               array(reco_eff_list), no_err,
                               array(eff_err_list))
g_data_eff = TGraphErrors(len(reco_eff_list), array(tolerance_list),
                          array(data_eff_list), no_err, array(eff_err_list))

g_eff.Draw("APL")
g_eff.GetXaxis().SetTitle("#it{d}_{max} [cm]")
g_eff.GetYaxis().SetTitle("[%]")
g_eff.GetYaxis().SetRangeUser(90, 100)
g_eff.SetMarkerStyle(20)
g_eff.SetLineColor(kRed + 1)
g_eff.SetLineWidth(2)
g_purity.Draw("PL")
g_purity.SetMarkerStyle(21)
g_purity.SetLineColor(kBlue + 1)
g_purity.SetLineWidth(2)
g_acceptance.Draw("PL")
g_acceptance.SetMarkerStyle(23)
g_acceptance.SetLineColor(kGreen + 2)
g_acceptance.SetLineWidth(2)
g_reco_eff.Draw("PL")
g_reco_eff.SetLineColor(kGray + 2)
Пример #23
0
    # 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')
gra5 = TGraphErrors(n, x, ya5, dx, dya5)
gra5.SetMarkerColor(4)
Пример #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()
Пример #25
0
err6s = array( 'f', [0.102, 0.070, 0.073, 0.088, 0.078, 0.076, 0.080, 0.081, 0.100, 0.155, 0.189, 0.180, 0.107, 0.101, 0.086, 0.083, 0.076, 0.080, 0.075, 0.080, 0.110])
err6 = array( 'f', [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ,0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
n4s = 21
nxs = 33
n2s = 21
c1 = TCanvas( 'c1', 'Y', 200, 10, 1400, 1000 )

g1s = TGraphErrors(nxs, Arr1, det1s, err1, err1s)
g1s.SetTitle( 'Y=0 Detected PE' )
g1s.SetMarkerColor( 4 )
g1s.SetLineColor( 4 )
g1s.SetMarkerStyle( 21 )
g1s.Draw('APC')
g1s.GetYaxis().SetRangeUser(0,45)
g1s.GetYaxis().SetTitle("Hits [PE]")
g1s.GetXaxis().SetTitle("X [cm]")
g2xs = TGraphErrors(nxs, Arr2x, det2xs, err2x, err2xs)
g2xs.SetTitle( 'Y=0 Detected PE' )
g2xs.SetMarkerColor( 9 )
g2xs.SetLineColor( 9 )
g2xs.SetMarkerStyle( 5 )
g2xs.Draw('PC SAME')
#c1.Print("xs.png")
#c2 = TCanvas( 'c1', 'Y', 200, 10, 700, 500 )
'''
g2s = TGraphErrors(nxs, Arr2, det2s, err2, err2s)
g2s.SetTitle( 'Y=0 Detected PE' )
g2s.SetMarkerColor( 800 )
g2s.SetLineColor( 800 )
g2s.SetMarkerSize( 2 )
g2s.SetMarkerStyle( 22 )
Пример #26
0
    lengtharray.append(fit.Get().Parameter(4))
    sigmaErr.append(fit.Get().ParError(2))
    breakzErr.append(fit.Get().ParError(3))
    lengthErr.append(fit.Get().ParError(4))

    fit_params.Write("fit {0} GeV".format(mass))
    c.Print(remainder[0] + ".pdf", "Title:mass_{0}".format(mass))

c.Clear()
outfile.cd()

gPad.SetLogy(0)
graph = TGraphErrors(len(massarray), massarray, sigmaarray, zeroArr, sigmaErr)
graph.Draw("A*")
graph.SetTitle("Vertex Resolution")
graph.GetXaxis().SetTitle("mass [GeV]")
graph.GetYaxis().SetTitle("sigma [mm]")
graph.Write("sigmaz")
c.Print(remainder[0] + ".pdf", "Title:sigmaz")

graph = TGraphErrors(len(massarray), massarray, breakzarray, zeroArr,
                     breakzErr)
graph.Draw("A*")
graph.SetTitle("Tail Z")
graph.GetXaxis().SetTitle("mass [GeV]")
graph.GetYaxis().SetTitle("tail Z [mm]")
graph.Write("breakz")
c.Print(remainder[0] + ".pdf", "Title:tailz")

graph = TGraphErrors(len(massarray), massarray, lengtharray, zeroArr,
                     lengthErr)
Пример #27
0
for i in range(len(timestamps)):
	timestamps_array[i] = timestamps[i]
	peak3_array[i] = peak3[i]
	error3_array[i] = error3[i] 
scan_nums = ''
for i in range(len(scan)):
	scan_nums += '_%s' % (scan[i])


time_pdf = '%sscan%s_peak3_time.pdf' % (OutputPath, scan_nums)

# Draw graphs
c1 = TCanvas("c1", "Peak VS Time", 200, 10, 700, 500)
graph1 = TGraphErrors(len(timestamps), timestamps_array, peak3_array, time_error, error3_array)
graph1.SetTitle("peak 3 over time")
graph1.GetXaxis().SetTitle("Datetime")
graph1.GetYaxis().SetTitle("Peaks Amp (mV)")
print("Bin Number: " + str(graph1.GetXaxis().GetNbins()))
for i in range(len(timestamps_array)):
	binx = graph1.GetXaxis().FindBin(timestamps_array[i])
	graph1.GetXaxis().SetBinLabel(binx, time.ctime(timestamps_array[i]))
graph1.Draw()
c1.Update()
c1.Print(time_pdf)


c1.Clear()
temp_pdf = '%sscan%s_peak3_temperature.pdf' % (OutputPath, scan_nums)
graph2 = TGraphErrors(len(timestamps), timestamps_array, peak3_array, time_error, error3_array)
graph2.SetTitle("Peak3 Temperature")
graph2.GetXaxis().SetTitle("Temperature (degree Celsius)")
Пример #28
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
Пример #29
0
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)
leg1.SetFillColor(0)
leg1.SetFillStyle(0)
leg1.SetTextSize(0.05)
leg1.SetBorderSize(0)
leg1.SetTextFont(22)
leg1.AddEntry("", "GeIA group", "")
leg1.AddEntry("", "Avalanche region:", "")
leg1.AddEntry(gr, str(Avalanche_region) + "cm(Square)", "lp")
leg1.AddEntry(gr1, str(Avalanche_region1) + "cm(Circle)", "lp")

line = TLine(
    math.pow(10, 15), 0, math.pow(10, 15),
    Number_of_Atom(Avalanche_region, math.pow(math.pow(10, 15), 0.33)))
Пример #30
0
def plot_2(var,cuts):
    for s in attr:
        c1 = TCanvas("c1", "Signals", 1200, 800)

        if log_y == 1: 
            c1.SetLogy()

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

            c1.Print(path1 + s + var + cuts.replace('(','_').replace(')','_').replace('&&','_').replace('>','LG').replace('<','LS').replace('=','EQ').replace('.','P').replace('-','N').replace('Jet','J').replace('GenBquark','GBQ') + ".pdf")
            
        elif ct_dep == 1:
            eac0 = str( entries_after_cut['ct0'][s] )
            c1.SetLogx()
            #gr = TGraph( len_of_lt , x , yy['sgn'][s] )
            gr = TGraphErrors( len_of_lt , x , yy['sgn'][s] , ex , ey['sgn'][s] )
            gr.SetMarkerSize(1.5)
            gr.SetMarkerStyle(1)
            gr.GetYaxis().SetTitleOffset(1.6)
            gr.SetLineColor(4)
            gr.SetLineWidth(4)
            gr.SetTitle('mean ' + s )
            gr.GetXaxis().SetTitle('decaying length (mm)')
            gr.GetYaxis().SetTitle('mean normalized number of events')
            gr.GetXaxis().SetTitleOffset(1.4)
            gr.SetMaximum( plotrange[s] * 1.12 )
            gr.SetName('sgn')
            gr.Draw('ACP')  # '' sets up the scattering style
            gr1 = TGraphErrors( len_of_lt , x , yy['QCD'][s] , ex , ey['QCD'][s] )
            gr1.SetMarkerSize(1.0)
            gr1.SetMarkerStyle(1)
            gr.GetYaxis().SetTitleOffset(1.6)
            gr1.SetLineColor(2)
            gr1.SetLineWidth(2)
            gr1.SetName('QCD')
            #gr1.SetTitle('averaged ' + s)
            #gr1.GetXaxis().SetTitle('decaying length (mm)')
            #gr1.GetYaxis().SetTitle('mean frequency')
            gr1.Draw('CP')  # '' sets up the scattering style
            legend = TLegend(0.76, 0.56, 0.99, 0.88)
            legend.SetHeader( 'Entries: ' + eac0 )
            legend.AddEntry('QCD', legendb, 'l')
            legend.AddEntry('sgn', legends, 'l')
            legend.Draw()
            for ct in cut_text:
                cut_text[ct].Draw()
            c1.Print(path1 + 'mean_' + s + var + cuts.replace('(','_').replace(')','_').replace('&&','_').replace('>','LG').replace('<','LS').replace('=','EQ').replace('.','P').replace('-','N').replace('Jet','J').replace('GenBquark','GBQ') + ".pdf")
        c1.Update()
        c1.Close() 
        print('|||||||||||||||||||||||||||||||||||||||||||||||||||')