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

        gr_mean.SetMarkerSize(1.5)
        gr_mean.SetMarkerColor(632)
        gr_width.SetMarkerStyle(20)
        gr_width.SetMarkerSize(1.5)
        gr_width.SetMarkerColor(600)
        gr_eff.SetMarkerStyle(20)
        gr_eff.SetMarkerSize(1.5)
        gr_eff.SetMarkerColor(600)
        hx = histo(0, 10, -0.2, 1.2, "p_{T}(GeV/c)", "Mean/Width")
        canvas_file = self.__canvas__
        canvas_file.cd()
        c1 = TCanvas("c1", "c1", 1000, 800)
        hx.Draw()
        gr_width.Draw("psame")
        gr_mean.Draw("psame")
        c1.Write("nse")
        c1.SaveAs("nse.png")
        c2 = TCanvas("c2", "c2", 1000, 800)
        hx.GetYaxis().SetTitle("n#sigma_{e} cut efficiency")
        hx.Draw()
        gr_eff.Draw("psame")
        c2.Write("nse_eff")
        c2.SaveAs("nse_eff.png")
示例#3
0
def testIthr():
    lines = get_lines('DAC_scan_ithr_0x40to0xf0.dat')

    gr1 = TGraphErrors()
    gr2 = TGraphErrors()

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

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

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

    useAtlasStyle()
    gStyle.SetMarkerStyle(20)

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

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

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

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

    gr2x.Draw('Psame')

    waitRootCmdX()
    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
示例#5
0
文件: pho_e.py 项目: pfjoker/phe_eff
 def draw_tof_cut_eff(self, cent_low, cent_high):
     cent_bin1 = [0, 4, 7]
     cent_bin2 = [3, 6, 8]
     p_bin1 = [
         0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5,
         3.0, 3.5, 4.0, 4.5
     ]
     p_bin2 = [
         0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0,
         3.5, 4.0, 4.5, 5.0
     ]
     gr_mean = TGraphErrors()
     gr_width = TGraphErrors()
     gr_eff = TGraphErrors()
     for i in range(0, len(p_bin1)):
         f_gaus = self.draw_tof_cut(cent_bin1[1], cent_bin2[1], p_bin1[i],
                                    p_bin2[i])
         mean = f_gaus.GetParameter(1)
         mean_err = f_gaus.GetParError(1)
         width = f_gaus.GetParameter(2)
         width_err = f_gaus.GetParError(2)
         gr_mean.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, mean)
         gr_mean.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, mean_err)
         gr_width.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, width)
         gr_width.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, width_err)
         m = f_gaus.Integral(0.97, 1.03)
         N = f_gaus.GetParameter(0) * math.sqrt(
             2 * math.pi) * f_gaus.GetParameter(2)
         print m, N
         gr_eff.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N)
         gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5,
                              eff_err(m, N))
     gr_mean.SetMarkerStyle(20)
     gr_mean.SetMarkerSize(1.5)
     gr_mean.SetMarkerColor(632)
     gr_width.SetMarkerStyle(20)
     gr_width.SetMarkerSize(1.5)
     gr_width.SetMarkerColor(600)
     gr_eff.SetMarkerStyle(20)
     gr_eff.SetMarkerSize(1.5)
     gr_eff.SetMarkerColor(600)
     hx = histo(0, 10, -0.2, 1.2, "p_{T}(GeV/c)", "Mean/Width")
     canvas_file = self.__canvas__
     canvas_file.cd()
     c1 = TCanvas("c1", "c1", 1000, 800)
     hx.GetYaxis().SetTitle("1/#beta cut efficency")
     hx.Draw()
     gr_width.Draw("psame")
     gr_mean.Draw("psame")
     c1.Write("tof")
     c1.SaveAs("tof.png")
     c2 = TCanvas("c2", "c2", 1000, 800)
     hx.Draw()
     gr_eff.Draw("psame")
     c2.Write("tof_cut_eff")
     c2.SaveAs("tof_cut.png")
    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
示例#7
0
def fit(label, iter, xs_file, tfunc, xmin, xmax, is_fit=True):
    ''' ARGUE: 1. label of your input
               2. iter name
               3. data source file path and its name
               4. fit function
               5. minimum of tfunc
               6. maximum of tfunc
               7. is fit or not
    '''
    ipoint, gaexs, geeff, gexs = 0, TGraphAsymmErrors(0), TGraphErrors(
        0), TGraphErrors(0)
    ipoint_xs = 0
    for line in open(xs_file):
        try:
            fargs = map(float, line.strip().split())
            sample, ecms, lum, br, nsig, nsigerrl, nsigerrh = fargs[0], fargs[
                1], fargs[2], fargs[3], fargs[4], fargs[5], fargs[6]
            eff, isr, vp, N0 = fargs[7], fargs[8], fargs[9], fargs[10]
            '''
            USER DEFINE SECTION { formula of cross section
            '''
            xs = nsig / (2 * lum * eff * br * isr)
            xserrl = sqrt(3) * nsigerrl / (2 * lum * eff * br * isr)
            xserrh = sqrt(3) * nsigerrh / (2 * lum * eff * br * isr)
            '''
            } USER DEFINE SECTION
            '''
            gexs.Set(ipoint_xs + 1)
            gexs.SetPoint(ipoint_xs, ecms, xs)
            gexs.SetPointError(ipoint_xs, 0.0, xserrl)
            ipoint_xs += 1
            if (sample == 4700 and xmin == 4.0205): continue
            gaexs.Set(ipoint + 1)
            gaexs.SetPoint(ipoint, ecms, xs)
            gaexs.SetPointError(ipoint, 0.0, 0.0, xserrl, xserrh)
            geeff.Set(ipoint + 1)
            geeff.SetPoint(ipoint, ecms, eff * isr)
            geeff.SetPointError(ipoint, 0.0,
                                sqrt(isr * eff * (1.00 - eff) / N0))
            ipoint += 1
        except:
            '''
            '''
    if is_fit:
        results = gaexs.Fit(tfunc, 'S')
        path_user = '******' + label + '_' + iter + '.dat'
        f_user = open(path_user, 'w')
        for i in xrange(int((xmax - xmin) / 0.001)):
            ecm = xmin + i * 0.001
            xs_ecm = tfunc.Eval(ecm)
            out = str(ecm) + ' ' + str(xs_ecm) + '\n'
            f_user.write(out)
        f_user.close()
    return gaexs, geeff, gexs, tfunc
    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
示例#9
0
    def __init__(self, num_pars=0, pars=None, norm=True):
        pars = pars or []

        self._numPars = num_pars
        self.parameter = pars
        self.fCov = [[None for j in range(self._numPars)]
                     for i in range(self._numPars)
                     ]  # Simple matrix replacement
        self._dEff_dP = list()
        self.TGraph = TGraphErrors()

        # Normalization factors
        self._doNorm = norm
        self.norm = 1.0
        self.TF1.FixParameter(0, self.norm)  # Normalization
        self.TF1.SetRange(0, 10000)  # Default range for efficiency function

        self._fitInput = Pairs(lambda x: ufloat(x, 0))

        #         if self.parameter: # Parameters were given
        #             map(lambda i: self.TF1.SetParameter(i + 1, self.parameter[i]), range(1, len(pars))) # Set initial parameters
        #         else:
        #             self.parameter = [None for i in range(1, self._numPars + 1)]
        #
        self.TF1.SetParName(0, "N")  # Normalization

        for i in range(0, num_pars):
            self._dEff_dP.append(None)
            if num_pars <= len(string.ascii_lowercase):
                self.TF1.SetParName(i + 1, string.ascii_lowercase[i])
示例#10
0
        def dip_residual_method():

            hh = TH2F("hh", "", 20, hodo_center - 4.0, hodo_center + 4.0, 200,
                      -2, 2)
            cuts = 'n_tracks==1 && amp_max[{}]>1000 && amp_max[{}]>1000'.format(
                self.xtal[0], self.xtal[1])
            t_tree.Draw("(fit_time[{0}]-fit_time[{1}]):{2}>>hh".format(
                self.xtal[0], self.xtal[1], axis[0]), cuts,
                        "COLZ")  # Plot dt vs (X or Y)
            hh.FitSlicesY()  # Fit slices with gaussians
            gr = TGraphErrors(t_file.Get(
                "hh_1"))  # hh_1 is the histo of means from FitSlicesY

            ## Sorry for the confusing names. We plot dt vs (X or Y), so dt is our y_var, and dx is our x_var, the distance term (ie X OR Y)
            points = range(gr.GetN())
            dx = array('d', gr.GetX())
            dt = array('d', gr.GetY())
            p1 = TF1("p1", "pol1")
            TGraph(gr.GetN(), dx, dt).Fit("p1",
                                          "WQ")  # Fit dt_mean vs Y linearly

            ## Sum each 3 consecutive residuals, take the max from this value's abs(), and the middle index is where the "dip" is farthest from the fit, the "center"
            res = [dt[i] - p1.Eval(dx[i])
                   for i in points]  # The residual between the fit and data
            sum_res = [abs(sum(res[i:i + 3])) for i in points[:-2]
                       ]  # Sum 3 residuals ([:-2] to avoid index out of range)
            axis_center = dx[
                sum_res.index(max(sum_res)) +
                1]  # +1 b/c we index the 1st out of 3 residuals, but we want the middle one

            return axis_center
示例#11
0
def compareEEC( filename="sjm91_all.root", datafilename="../EECMC/share/OPAL/data.dat" ):
    f= TFile( filename )
    ao= createAnalysisObservable( f, "EEC" )
    tokens= datafilename.split( "/" )
    exp= tokens[3]
    plotoptions= { "xmin": 0.0, "xmax": 3.14159, "ymin": 0.05, "ymax": 5.0, "markerStyle": 20,
                       "markerSize": 0.5, "drawas": "3", "fillcolor": 6, "title": "EEC "+exp,
                       "xlabel": "\chi\ [rad.]", "ylabel": "1/\sigma d\Sigma/d\chi", "logy": 1 }
    tgest, tgesy= ao.plot( plotoptions )
    lines= [ line.rstrip( '\n' ) for line in open( datafilename ) ]
    n= len( lines )
    points= TVectorD( n )
    values= TVectorD( n )
    errors= TVectorD( n )
    perrs= TVectorD(n)
    grad2rad= 3.14159/180.0
    for i in range( n ):
        line= (lines[i]).split()
        points[i]= float(line[0])*grad2rad
        values[i]= float(line[3])
        errors[i]= float(line[4])
        perrs[i]= 0.0
    datatge= TGraphErrors( points, values, perrs, errors )
    datatge.SetMarkerStyle( 20 )
    datatge.SetMarkerSize( 0.5 )    
    datatge.Draw( "psame" )
    legend= TLegend( 0.2, 0.7, 0.5, 0.85 )
    datatge.SetName( "datatge" );
    tgesy.SetName( "tgesy" )
    legend.AddEntry( "datatge", exp+" data", "pe" )
    legend.AddEntry( "tgesy", "OPAL "+filename, "f" )
    legend.Draw()
    return 
示例#12
0
 def overlay(self, x, y, dx=None, dy=None, symbol='plus', color='black'):
     npts, xx, yy, dxx, dyy = self._fillArrays(x, y, dx, dy)
     if npts == 0:
         return
     self.graphs.append(TGraphErrors(npts, xx, yy, dxx, dyy))
     self.canvas.cd()
     self._drawData(self.graphs[-1], symbol, color)
示例#13
0
def load_cck():

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

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

    #scaling to XnXn
    kx = 0.1702

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

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

    return gCCK
def CalibrationENC(calibration_filename):
    # Read data fron the calibration curve dataset
    C, e_C, noise_rms, d_noise_rms, fall_time, d_fall_time, amplitude, d_amplitude = LoadCalibrationFile(calibration_filename)

    noise_rms = noise_rms / 1000. # convert form \muV to mV
    d_noise_rms = d_noise_rms / 1000.

    ENC = (noise_rms/amplitude) * (C * 20.0) * pow(10,-15) / (1.602 * pow(10,-19) ) #pF * mV = 10^-12 * 10^-3 = 10^-15 C / 10^-19 C = 10^4 electrons
    d_ENC = np.zeros([len(ENC)])
    for i in range(len(ENC)):
        d_ENC[i] = sqrt( d_noise_rms[i]*d_noise_rms[i]*(C[i] * 20.0/amplitude[i])*(C[i] * 20.0/amplitude[i])  +  d_amplitude[i]*d_amplitude[i]*((noise_rms[i]/(amplitude[i]*amplitude[i])) * (C[i] * 20.0))*((noise_rms[i]/(amplitude[i]*amplitude[i])) * (C[i] * 20.0))    )
    
    d_ENC = d_ENC * pow(10,-15) / (1.602 * pow(10,-19) ) # conversted to # of electrons

    calib_curve = TGraphErrors(len(ENC), array('d', C[:-1].tolist()), array('d', ENC.tolist()), array('d', e_C.tolist()), array('d', d_ENC) )

    # Construct the fit with a 1st and 2nd order polynomial
    fit_curve = TF1('fit_curve','[1]*x + [0]',0.,110.)
    fit_curve2 = TF1('fit_curve2','[0]*x*x + [1]*x + [2]',0.,110.)

    # Fit the calibration curve
    calib_curve.Fit(fit_curve,'R')
    calib_curve.Fit(fit_curve2, 'R')

    lin_par0   = fit_curve.GetParameter(0)
    lin_e_par0 = fit_curve.GetParError(0)
    lin_par1   = fit_curve.GetParameter(1)
    lin_e_par1 = fit_curve.GetParError(1)

    xx = np.linspace(0., 105, 1000)
    yy = [fit_curve.Eval(x) for x in xx]
    yy2 = [fit_curve2.Eval(x) for x in xx]

    par = [lin_par0, lin_par1]
    l = 'fit pol1 $p_0$: {:.3g} $p_1$: {:.3g}'.format(*par)


    # Plot the calibration curve with matplotlib
    font0 = FontProperties()
    font = font0.copy()
    font.set_style('italic')
    font.set_weight('bold')
    font.set_size('x-large')

    fig, ax = plt.subplots()
    ax.set_xlabel('C [pF]')
    ax.set_ylabel('ENC [# of electrons]')
    ax.errorbar(C, ENC, d_ENC, marker='o', color='k', linestyle='None', label='Data')
    ax.plot(xx, yy, color='r', label=l)
    ax.plot(xx, yy2, color='g', label='fit pol2')
    ax.text(0.05,0.65, 'Group 1', verticalalignment='bottom', horizontalalignment='left',
                fontproperties=font, transform=ax.transAxes)
    ax.legend(loc='upper left', numpoints=1)
    plt.grid()
    #plt.show()
    fig.savefig('../graphics/calibrationENC_diode.pdf')
    plt.close(fig)
    plt.clf()

    return lin_par0, lin_e_par0, lin_par1, lin_e_par1
示例#15
0
def test1a(fname='data/fpgaLin/dp02a_Mar04C1a_data_0.root'):
    add_fit_menu()

    t1 = TChain('reco')
    t1.Add(fname)

    t1.Show(0)
    V = 200
    gr1 = TGraphErrors()

    for i in range(19):
        c1.cd(i+1)
        lt.DrawLatexNDC(0.2,0.4,'Ch={0:d}'.format(i))
        t1.Draw('Q[{0:d}]>>hx{0:d}'.format(i),'tID!=7')
        hx = gPad.GetPrimitive('hx{0:d}'.format(i))
        hx.Fit('gaus')
        fun1 = hx.GetFunction('gaus')
        encN = 7.40*V*fun1.GetParameter(2)/fun1.GetParameter(1)
        encE = 7.40*V*fun1.GetParError(2)/fun1.GetParameter(1)

        gr1.SetPoint(i,i,encN)
        gr1.SetPointError(i,0,encE)

    c1.cd(20)
    gr1.Draw('AP')

    c1.cd()
    waitRootCmdX()
示例#16
0
 def __init__(self, file_name):
     file = open(file_name)
     out = open(output, 'w')
     for line in file:
         #calculate errors and dump the content to output file
         if '#' in line:
             continue
         t, vin, vout = [float(x) for x in line.split()]
         te = osc_error_t(t, TIME_DIV)
         vd = vin - vout
         voute = osc_error_v(vout, POT_DIV)
         vde = osc_error_v(vd, POT_DIV)
         id = vout / R[0]
         if vout:
             ide = id * ((voute / vout) + (R[1] / R[0]))
         else:
             ide = id * (R[1] / R[0])
         new_line = [vd, id, vde, ide]
         new_line = ' '.join([str(x) for x in new_line]) + '\n'
         out.write(new_line)
     file.close()
     out.close()
     #create Graph. ROOT automatically reads columns
     self.graph = TGraphErrors(output)
     self.graph.SetMarkerStyle(7)
     self.func = TF1("shockley", "[0]*(exp(x/[1])-1)", 0.1, 1)
     self.func.SetParameters(5, 0.026)
示例#17
0
    def __make_summary_plot(self, name, ibin2, successful):

        # Nominal histogram
        successful_tmp = copy(successful)
        successful_tmp.sort()

        filename = f"finalcross{self.case}{self.typean}mult{ibin2}.root"
        filepath = join(self.nominal_analyzer_merged.d_resultsallpdata,
                        filename)
        nominal_histo = self.__get_histogram(filepath, name)

        histos = []
        ml_trials = []
        for succ in successful_tmp:
            filename = f"finalcross{self.case}{self.typean}mult{ibin2}.root"
            filepath = join(self.analyzers_syst[succ].d_resultsallpdata,
                            filename)
            histos.append(self.__get_histogram(filepath, name))
            ml_trials.append(
                list(map(itemgetter(self.mcopt), self.ml_wps[succ])))

        nptbins = self.nominal_processer_mc.p_nptfinbins
        gr = [TGraphErrors(0) for _ in range(nptbins)]
        for ipt in range(nptbins):
            gr[ipt].SetTitle("pT bin %d" % ipt)
            gr[ipt].SetPoint(0, self.cent_cv_cut[ipt],
                             nominal_histo.GetBinContent(ipt + 1))
            gr[ipt].SetPointError(0, 0.0001,
                                  nominal_histo.GetBinError(ipt + 1))
            for iml, succ in enumerate(successful_tmp):
                gr[ipt].SetPoint(iml + 1, ml_trials[succ][ipt],
                                 histos[succ].GetBinContent(ipt + 1))
                gr[ipt].SetPointError(iml + 1, 0.0001,
                                      histos[succ].GetBinError(ipt + 1))

        canvas = TCanvas("cvsml%d" % ibin2, "", 1200, 800)
        if len(gr) <= 6:
            canvas.Divide(3, 2)
        elif len(gr) <= 12:
            canvas.Divide(4, 3)
        else:
            canvas.Divide(5, 4)
        for i, graph in enumerate(gr):
            canvas.cd(i + 1)
            graph.Draw("a*")

        save_path = join(self.nominal_analyzer_merged.d_resultsallpdata,
                         self.syst_out_dir,
                         f"ml_wp_syst_{name}_vs_MLcut_ibin2_{ibin2}.eps")
        canvas.SaveAs(save_path)
        save_path = join(self.nominal_analyzer_merged.d_resultsallpdata,
                         self.syst_out_dir,
                         f"ml_wp_syst_{name}_vs_MLcut_ibin2_{ibin2}.root")
        file_out = TFile.Open(save_path, "RECREATE")
        file_out.cd()
        for i, graph in enumerate(gr):
            graph.Write("%s%d" % (graph.GetName(), i))
        canvas.Write()
        file_out.Close()
        canvas.Close()
示例#18
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
示例#19
0
 def __init__(self, models, bcids, values, fill=4954, workinprogress=False):
     """Initialize a summary plot of values per model and bcid."""
     nbcid, nmodels = len(bcids), len(models)
     order = sorted(range(nbcid), key=lambda i: bcids[i])
     mini, maxi = 1.0e99, -1.0e99
     multi = TMultiGraph('summary', '')
     for i, mod in enumerate(models):
         xval = array(
             'd', [c + 0.09 * (i - 0.5 * nmodels) for c in range(nbcid)])
         xerr = array('d', [0.0] * nbcid)
         yval = array('d', [values[i][j][0] for j in order])
         yerr = array('d', [values[i][j][1] for j in order])  #[0.0]*nbcid)
         mini = min(mini, min([v - e for v, e in zip(yval, yerr)]))
         maxi = max(maxi, max([v + e for v, e in zip(yval, yerr)]))
         graph = TGraphErrors(nbcid, xval, yval, xerr, yerr)
         graph.SetName('summary_{0}'.format(mod))
         multi.Add(graph)
     self._multi = multi
     mini, maxi = mini - 0.08 * (maxi - mini), maxi + 0.25 * (maxi - mini)
     hist = TH2F('axishist', '', nbcid, -0.5, nbcid - 0.5, 100, mini, maxi)
     for i, j in enumerate(order):
         hist.GetXaxis().SetBinLabel(i + 1, str(bcids[j]))
     SingleGraphBase.__init__(self, hist, 'summary', fill, workinprogress)
     for gr in multi.GetListOfGraphs():
         self.add(gr, draw=False)
     self._xtitle = 'bcid'
     self._drawoption = 'AXIS'
     self.markers = [markers(i) for i in range(nmodels)]
     self.colors = [colors(i) for i in range(nmodels)]
     self.xrange(-0.5, nbcid - 0.5)
     self.yrange(mini, maxi)
示例#20
0
def rescaleJetPlot(plot):

    #loop on all data points
    nPoints = plot.GetN()
    #    print "old:",plot.GetName(), nPoints
    #create another TGraph
    newPlot = TGraphErrors()

    for i in xrange(0, nPoints):

        dataPointX = Double(0)
        dataPointY = Double(0)
        error = Double(0)
        plot.GetPoint(i, dataPointX, dataPointY)
        #if numpy.isnan(dataPointY) : dataPointY = 0.000001
        if dataPointY < 0.000001: dataPointY = 0.000001
        errorX = plot.GetErrorX(i)
        errorY = plot.GetErrorY(i)
        newPlot.SetPoint(i, dataPointX / 1000., dataPointY)
        newPlot.SetPointError(i, errorX / 1000., errorY)


#    print "new:", newPlot.GetName(), newPlot.GetN()

    return newPlot
示例#21
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
示例#22
0
    def create_tgrapherrors(self, x_value, y_value, dx_value, dy_value):
        """Function to create pyroot TGraphErrors object"""
        # pylint: disable=no-self-use

        # Creating pyroot TGraphErrors object
        x_values = array('i')
        y_values = array('i')
        dx_values = array('i')
        dy_values = array('i')
        length = len(x_value)
        if (all(isinstance(x, int)
                for x in x_value) and all(isinstance(x, int) for x in y_value)
                and all(isinstance(x, int) for x in dx_value)
                and all(isinstance(x, int) for x in dy_value)):
            y_values = array('i')
            x_values = array('i')
            dx_values = array('i')
            dy_values = array('i')
        else:
            y_values = array('d')
            x_values = array('d')
            dx_values = array('d')
            dy_values = array('d')
        for value in range(length):
            x_values.append(x_value[value])
            y_values.append(y_value[value])
            dx_values.append(dx_value[value])
            dy_values.append(dy_value[value])
        t_object = TGraphErrors(length, x_values, y_values, dx_values,
                                dy_values)
        graph = ru.get_graph_points(t_object)

        return graph
示例#23
0
def h1_to_graph(hx):

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

    return tx
示例#24
0
  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()
示例#25
0
def Sigma_Calc(g,i_,x,y,xe,ye,percentage):
    #print'Creating TGraph with new uncertainty band'
    # sigma factor. What to multiply uncertainties by, assuming current uncertainties are 1 sigma. 
    #print'percentage/100. = ',percentage/100.
    sf = TMath.ErfInverse(percentage/100.)*TMath.Sqrt(2) # sigma value for desired percentage events contained in distribution 
    #print"sf = ",sf

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

    #print sf,'sig errors = ',ye   

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

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

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

    ng.SetFillStyle(g.GetFillStyle())

    return ng
示例#26
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;
示例#27
0
def getTGraphErrors(x, y, ex=None, ey=None):
    if (ex == None):
        ex = [0] * len(x)
    if (ey == None):
        ey = [0] * len(x)
    return TGraphErrors(len(x), array('f', x), array('f', y), array('f', ex),
                        array('f', ey))
示例#28
0
文件: data.py 项目: QuantumDancer/FP2
    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
示例#29
0
文件: pho_e.py 项目: pfjoker/phe_eff
 def draw_neta_cut_eff(self, cent_low, cent_high):
     cent_bin1 = [0, 4, 7]
     cent_bin2 = [3, 6, 8]
     p_bin1 = [
         0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5,
         3.0, 3.5, 4.0, 4.5
     ]
     p_bin2 = [
         0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0,
         3.5, 4.0, 4.5, 5.0
     ]
     gr_eff = TGraphErrors()
     for i in range(0, len(p_bin1)):
         mn = self.draw_neta_cut(cent_low, cent_high, p_bin1[i], p_bin2[i])
         m = mn[0]
         N = mn[1]
         gr_eff.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N)
         gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5,
                              eff_err(m, N))
     gr_eff.SetMarkerStyle(20)
     gr_eff.SetMarkerSize(1.5)
     gr_eff.SetMarkerColor(600)
     hx = histo(0, 8, -0.2, 1.2, "p_{T}(GeV/c)", "n#eta cut efficiency")
     canvas_file = self.__canvas__
     canvas_file.cd()
     c2 = TCanvas("c2", "c2", 1000, 800)
     hx.Draw()
     gr_eff.Draw("psame")
     c2.Write("neta_cut_eff")
     c2.SaveAs("neta_cut.png")
示例#30
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;