Esempio n. 1
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
Esempio n. 2
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()
Esempio n. 3
0
def _convert_tgrapherrors(root_obj: TGraphErrors) -> dict:
    """
    Take the values from a TGraphErrors and add them to a series
    of arrays

    Parameters
    ----------
    root_obj : TGraphError
        ROOT TGraphError

    Returns
    -------
    dict
        Dictionary with x, y, xerr, yerr points
    """
    xm, ym, x_errm, y_errm = (root_obj.GetX(),
                              root_obj.GetY(),
                              root_obj.GetEX(),
                              root_obj.GetEY())
    x, y, x_err, y_err = [], [], [], []
    for n in range(0, root_obj.GetN()):
        x.append(xm[n])
        y.append(ym[n])
        x_err.append(x_errm[n])
        y_err.append(y_errm[n])

    return {'x': np.array(x), 'y': np.array(y),
            'xerr': np.array(x_err), 'yerr': np.array(y_err)}
Esempio n. 4
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()
Esempio n. 5
0
def addErrors(err1, err2):
    from ROOT import TGraphErrors
    from math import sqrt

    newErrs = TGraphErrors(err1)

    for i in range(0, newErrs.GetN()):
        newErrs.SetPoint(i, newErrs.GetX()[i], err1.GetY()[i] + err2.GetY()[i])
        newErrs.SetPointError(i, err1.GetErrorX(i),
                              sqrt(err1.GetErrorY(i)**2 + \
                                   err2.GetErrorY(i)**2)
                              )
    return newErrs
Esempio n. 6
0
def GetData(file, scale=1., sed=True, title='SED', barUL=True):
    GetData.Ng += 1
    g = TGraphErrors(file)
    gUL = TGraphErrors()

    if sed:
        for i in range(g.GetN()):
            g.GetY()[i] = pow(g.GetX()[i], 2) * g.GetY()[i] * 1e-6 / scale
            g.GetEY()[i] = pow(g.GetX()[i], 2) * g.GetEY()[i] * 1e-6 / scale
            g.GetX()[i] *= 1e-3

    idel = 0
    nUL = 0
    while idel < g.GetN():
        if g.GetEY()[idel] < 0:
            gUL.SetPoint(nUL, g.GetX()[idel], g.GetY()[idel])
            if barUL:
                gUL.SetPointError(nUL, 0, g.GetY()[idel] * 1e-5)
            nUL += 1
            g.RemovePoint(idel)
        else:
            idel += 1

    if sed:
        g.SetTitle(title + ";Energy [GeV];E^{2}dN/dE [TeV cm^{-2} s^{-1}]")
    else:
        g.SetTitle(title + ";Energy [MeV];dN/dE [cm^{-2} s^{-1} MeV^{-1}]")

    g.SetLineColor(kRed)
    g.SetMarkerColor(kRed)
    g.SetMarkerStyle(20)
    g.SetName("g%d" % GetData.Ng)
    gUL.SetLineColor(g.GetLineColor())
    gUL.SetName("gUL%d" % GetData.Ng)

    return g, gUL
Esempio n. 7
0
def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-i", "--inputfile", dest="inputfile")
    parser.add_option("",
                      "--spline3",
                      action="store_true",
                      dest="spline3",
                      default=False)
    (options, args) = parser.parse_args()

    from ROOT import TFile, TGraph, TGraphErrors, NULL
    import csv

    with open(options.inputfile) as f:
        reader = csv.reader(f, delimiter=" ", skipinitialspace=True)
        rows = list(reader)
        outfile = TFile("%s.root" % options.inputfile, "RECREATE")
        g = TGraphErrors(len(rows))

        for i, row in enumerate(rows):
            g.SetPoint(i, float(row[1]) / 1000., float(row[2]))
            g.SetPointError(i, 0.0, float(row[3]))

        if options.spline3:
            g_spline3 = TGraph(10 * (g.GetN() - 1))
            x = g.GetX()
            y = g.GetY()
            for i in range(g.GetN() - 1):
                step = (x[i + 1] - x[i]) / 10
                for j in range(10):
                    index = 10 * i + j
                    x_ = x[i] + j * step
                    y_ = g.Eval(x_, NULL, "S")
                    g_spline3.SetPoint(index, x_, y_)
            g_spline3.SetName(options.inputfile)
            g_spline3.Write()
        else:
            g.SetName(options.inputfile)
            g.Write()

        outfile.Close()
Esempio n. 8
0
    def ApplyBinShiftCorrectionGeneral(self, hist, fit):
        """
        Alternative method for bin shift correction:
        - Apply user-default model for bin-shift correction
        - don't multiply by pt
        @param hist: Input spectrum for the bin shift correction
        @param fit: Model for the bin-shift correction
        @return: The bin-shift corrected spectrum as graph
        """
        h = deepcopy(hist)
        hist.SetName("htemp")

        result = TGraphErrors(h)
        for i in range(0, result.GetN()):
            result.GetEX()[i] = 0.
        y = 0

        #for now 10 iterations fixes
        for k in range(0, 10):
            for i in range(1, h.GetNbinsX() + 1):
                y = fit.Integral(h.GetBinLowEdge(i),
                                 h.GetBinUpEdge(i)) / h.GetBinWidth(i)
                x = self.FindX(y, fit, h.GetBinLowEdge(i), h.GetBinUpEdge(i))
                result.GetX()[i - 1] = x

        # remove points that are 0
        while result.GetY()[0] < 1.e-99:
            result.RemovePoint(0)

        mybin = 0
        for biniter in range(0, result.GetN()):
            if result.GetY()[biniter] < 1.e-99:
                mybin = biniter
                break
        while result.RemovePoint(mybin) > 0:
            continue

        return result
def plotDistributionComparisonPlot(cfg):

    multiGraph = TMultiGraph()
    multiGraph.SetName("triggerRateMultiGraph")

    tfiles = []

    histograms = []

    canvas = TCanvas("canvas", "canvas", 800, 800)
    '''Contains the legend'''
    legend = TLegend(0.3, 0.7, 0.90, 0.9)
    '''Maximum value container, used to scale histograms'''
    maximumY = float("-inf")

    pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    pad1.SetBottomMargin(0.05)  # Upper and lower plot are joined
    #pad1.SetBottomMargin(0) # Upper and lower plot are joined
    pad1.SetGridx()  # Vertical grid
    pad1.Draw()  # Draw the upper pad: pad1
    pad1.cd()  # pad1 becomes the current pad

    for histogramFileNameAndTitle in cfg.plots:
        tfile = TFile(histogramFileNameAndTitle[0])
        tfiles.append(tfile)
        histogram = tfile.Get(histogramFileNameAndTitle[1])
        histograms.append(histogram)
        if histogram.ClassName() == "TH1F":
            histogram.SetStats(0)  # No statistics on upper plot
        maximumY = histogram.GetMaximum(
        ) if histogram.GetMaximum() > maximumY else maximumY
        legend.AddEntry(histogram, histogramFileNameAndTitle[2], "l")

    # histograms[0] settings
    histograms[0].SetMarkerColor(4)
    histograms[0].SetLineColor(4)
    histograms[0].SetLineWidth(1)

    # Y axis histograms[0] plot settings
    histograms[0].GetYaxis().SetTitleSize(20)
    histograms[0].GetYaxis().SetTitleFont(43)
    histograms[0].GetYaxis().SetTitleOffset(1.55)

    #histograms[0].Scale(1./histograms[0].GetEntries())
    if histograms[0].ClassName() == "TH1F":
        histograms[0].Draw(
            "SAME HIST")  # Draw histograms[1] on top of histograms[0]
    else:
        histograms[0].Draw(
            "SAME APE")  # Draw histograms[1] on top of histograms[0]
        #multiGraph.Add(histograms[0])

    if getattr(cfg, "xRange", None) is not None:
        histograms[0].GetXaxis().SetRangeUser(cfg.xRange[0], cfg.xRange[1])
        gPad.RedrawAxis()

    if getattr(cfg, "xAxisLabel", None) is not None:
        histograms[0].GetXaxis().SetTitle(cfg.xAxisLabel)
        gPad.RedrawAxis()

    if getattr(cfg, "yAxisLabel", None) is not None:
        histograms[0].GetYaxis().SetTitle(cfg.yAxisLabel)
        gPad.RedrawAxis()

    if getattr(cfg, "yRange", None) is not None:
        histograms[0].GetYaxis().SetRangeUser(cfg.yRange[0], cfg.yRange[1])
        gPad.RedrawAxis()
    else:
        maximumY *= 1.1
        histograms[0].GetYaxis().SetRangeUser(1e-6, maximumY)

    if getattr(cfg, "logY", False):
        canvas.SetLogy()

    # histograms[1] settings
    histograms[1].SetMarkerColor(2)
    histograms[1].SetLineColor(2)
    histograms[1].SetLineWidth(1)
    #histograms[1].Scale(1./histograms[1].GetEntries())
    if histograms[1].ClassName() == "TH1F":
        histograms[1].Draw(
            "SAME HIST")  # Draw histograms[1] on top of histograms[0]
    else:
        histograms[1].Draw(
            "SAME PE")  # Draw histograms[1] on top of histograms[0]
        #multiGraph.Add(histograms[1])

    #if multiGraph.GetListOfGraphs() != None:
    #  multiGraph.Draw("SAME PE")

    # Do not draw the Y axis label on the upper plot and redraw a small
    # axis instead, in order to avoid the first label (0) to be clipped.
    #histograms[0].GetYaxis().SetLabelSize(0.)
    #axis = TGaxis( 0, 20, 0, maximumY, 20, maximumY, 510,"")
    #axis.SetLabelFont(43) # Absolute font size in pixel (precision 3)
    #axis.SetLabelSize(15)
    #axis.Draw()

    # Adding a small text with the chi-squared

    chiSquared = 0
    if (histograms[0].ClassName() == "TGraph") or (histograms[0].ClassName()
                                                   == "TGraphErrors"):
        numberOfBins = histograms[0].GetN()
        numberOfDegreesOfFreedom = numberOfBins
    else:
        numberOfBins = histograms[0].GetNbinsX()
        numberOfDegreesOfFreedom = numberOfBins

    for x in xrange(
            1, numberOfBins + 1
    ):  # numberOfBins contains last bin, numberOfBins+1 contains the overflow (latter excluded), underflow also excluded
        if (histograms[0].ClassName()
                == "TGraph") or (histograms[0].ClassName() == "TGraphErrors"):
            binContent0 = histograms[0].GetY()[x - 1]
        else:
            binContent0 = histograms[0].GetBinContent(x)
        if (histograms[1].ClassName()
                == "TGraph") or (histograms[1].ClassName() == "TGraphErrors"):
            binContent1 = histograms[1].GetY()[x - 1]
        else:
            binContent1 = histograms[1].GetBinContent(x)
        bin0ErrorSquared = binContent0
        bin1ErrorSquared = binContent1
        #bin1ErrorSquared = 0
        if (binContent0 == 0) and (binContent1 == 0):
            numberOfDegreesOfFreedom -= 1  #No data means one less degree of freedom
        else:
            binDifferenceSquared = (binContent0 - binContent1)**2
            chiSquaredTerm = binDifferenceSquared / (bin0ErrorSquared +
                                                     bin1ErrorSquared)
            chiSquared += chiSquaredTerm
            if chiSquaredTerm > chiSquaredWarningThreshold:
                if (histograms[0].ClassName()
                        == "TGraph") or (histograms[0].ClassName()
                                         == "TGraphErrors"):
                    print "Bin", x, "-", histograms[0].GetX()[
                        x - 1], "has a CS=", chiSquaredTerm
                else:
                    print "Bin", x, "-", histograms[0].GetBinCenter(
                        x), "has a CS=", chiSquaredTerm

    chiSquareLabel = TPaveText(0.7, 0.6, 0.9, 0.4)
    chiSquareLabel.AddText("#chi^{2}/ndf = " + str(chiSquared) + "/" +
                           str(numberOfDegreesOfFreedom) + " = " +
                           str(chiSquared / numberOfDegreesOfFreedom))
    chiSquareLabel.Draw()
    print "FINAL CS IS", format(
        chiSquared,
        ".2f") + "/" + str(numberOfDegreesOfFreedom) + " = " + format(
            chiSquared / numberOfDegreesOfFreedom, ".2f")
    legend.SetHeader(
        "#chi^{2}/ndf = " + format(chiSquared, ".2f") + "/" +
        str(numberOfDegreesOfFreedom) + " = " +
        format(chiSquared / numberOfDegreesOfFreedom, ".2f"), "C")
    legend.Draw()
    # lower plot will be in pad
    canvas.cd()  # Go back to the main canvas before defining pad2
    pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
    pad2.SetTopMargin(0)
    pad2.SetBottomMargin(0.2)
    pad2.SetGridx()  # vertical grid
    pad2.Draw()
    pad2.cd()  # pad2 becomes the current pad
    pad2.SetGridy()

    # Define the ratio plot
    ratioPlot = TGraphErrors(histograms[0])
    ratioPlot.SetName("ratioPlot")
    graph_histo0 = TGraphErrors(histograms[0])
    graph_histo1 = TGraphErrors(histograms[1])
    ratioPlot.SetLineColor(1)
    ratioPlot.SetMinimum(0.6)  # Define Y ..
    ratioPlot.SetMaximum(1.5)  # .. range
    #ratioPlot.Sumw2()
    #ratioPlot.SetStats(0)      # No statistics on lower plot

    #Dividing point by point

    for index in xrange(0, ratioPlot.GetN()):
        if graph_histo1.GetY()[index] == 0:
            ratioPlot.GetY()[index] = 0
            ratioPlot.GetEY()[index] = 0
        else:
            ratioPlot.GetY()[index] /= graph_histo1.GetY()[index]
            ratioPlot.GetEY()[index] = sqrt(
                ((graph_histo1.GetY()[index])**2 *
                 (graph_histo0.GetEY()[index])**2 +
                 (graph_histo0.GetY()[index])**2 *
                 (graph_histo1.GetEY()[index])**2) /
                (graph_histo1.GetY()[index])**4)

    ratioPlot.SetMarkerStyle(21)

    if getattr(cfg, "xRange", None) is not None:
        ratioPlot.GetXaxis().SetRangeUser(cfg.xRange[0], cfg.xRange[1])
        gPad.RedrawAxis()

    if getattr(cfg, "yRangeRatio", None) is not None:
        ratioPlot.GetYaxis().SetRangeUser(cfg.yRangeRatio[0],
                                          cfg.yRangeRatio[1])
        gPad.RedrawAxis()

    ratioPlot.Draw("APE")  # Draw the ratio plot

    line0 = TLine(ratioPlot.GetXaxis().GetXmin(), 1,
                  ratioPlot.GetXaxis().GetXmax(), 1)
    line0.SetLineColor(2)
    line0.SetLineWidth(2)
    line0.SetLineStyle(2)
    line0.Draw()

    # Ratio plot (ratioPlot) settings
    ratioPlot.SetTitle("")  # Remove the ratio title

    # Y axis ratio plot settings
    ratioPlot.GetYaxis().SetTitle("Ratio #frac{blue}{red}")
    ratioPlot.GetYaxis().SetNdivisions(505)
    ratioPlot.GetYaxis().SetTitleSize(20)
    ratioPlot.GetYaxis().SetTitleFont(43)
    ratioPlot.GetYaxis().SetTitleOffset(1.55)
    ratioPlot.GetYaxis().SetLabelFont(
        43)  # Absolute font size in pixel (precision 3)
    ratioPlot.GetYaxis().SetLabelSize(15)

    # X axis ratio plot settings
    ratioPlot.GetXaxis().SetTitleSize(20)
    ratioPlot.GetXaxis().SetTitleFont(43)
    ratioPlot.GetXaxis().SetTitleOffset(4.)
    ratioPlot.GetXaxis().SetLabelFont(
        43)  # Absolute font size in pixel (precision 3)
    ratioPlot.GetXaxis().SetLabelSize(15)

    xRangeBinning = getattr(cfg, "simplifiedRatioPlotXRangeBinning", None)
    if xRangeBinning is not None:
        simplifiedRatioPlot = TGraphErrors(len(xRangeBinning) - 1)
        simplifiedRatioPlot.SetName("simplifiedRatioPlot")
        ratioPlotIndex = 0

        for idx in xrange(0, simplifiedRatioPlot.GetN()):
            yAverage = 0.
            yMax = float("-inf")
            yMin = float("+inf")

            nPoints = 0.
            simplifiedRatioPlot.GetX()[idx] = (xRangeBinning[idx] +
                                               xRangeBinning[idx + 1]) / 2.
            simplifiedRatioPlot.GetEX()[idx] = (xRangeBinning[idx + 1] -
                                                xRangeBinning[idx]) / 2.

            while (ratioPlot.GetX()[ratioPlotIndex] < xRangeBinning[idx]):
                ratioPlotIndex += 1
            while ((ratioPlotIndex < ratioPlot.GetN()) and
                   (ratioPlot.GetX()[ratioPlotIndex] < xRangeBinning[idx + 1])
                   and
                   (ratioPlot.GetX()[ratioPlotIndex] >= xRangeBinning[idx])):
                yAverage += ratioPlot.GetY()[ratioPlotIndex]
                if (yMax < ratioPlot.GetY()[ratioPlotIndex] +
                        ratioPlot.GetEY()[ratioPlotIndex]):
                    yMax = ratioPlot.GetY()[ratioPlotIndex] + ratioPlot.GetEY(
                    )[ratioPlotIndex]
                if (yMin > ratioPlot.GetY()[ratioPlotIndex] -
                        ratioPlot.GetEY()[ratioPlotIndex]):
                    yMin = ratioPlot.GetY()[ratioPlotIndex] - ratioPlot.GetEY(
                    )[ratioPlotIndex]
                nPoints += 1.
                ratioPlotIndex += 1

            simplifiedRatioPlot.GetY()[idx] = yAverage / nPoints
            simplifiedRatioPlot.GetEY()[idx] = (yMax - yMin) / 2.

    saveFile = TFile(cfg.saveFileName, "RECREATE")
    saveFile.cd()
    canvas.Write()
    histograms[0].Write()
    histograms[1].Write()
    if multiGraph.GetListOfGraphs() != None:
        multiGraph.Write()
    ratioPlot.Write()
    if xRangeBinning is not None:
        simplifiedRatioPlot.Write()
    saveFile.Close()
    for tfile in tfiles:
        tfile.Close()
Esempio n. 10
0
def make_1d_plots(df, c=None):
    if c is None:
        from ROOT import TCanvas
        c = TCanvas()
        c.Divide(1, 2)
    import seaborn as sns
    import ROOT
    from ROOT import TGraphErrors, TLegend
    plot = PlotData()
    plot.canvas = c

    graphs = plot.graphs = []
    graphs_lam = plot.graphs_lam = []

    leg = plot.legend = TLegend(0.68, 0.6, 0.88, 0.8)
    leg.SetHeader("Centrality", 'C')

#     colors = [ROOT.kRed, ROOT.kBlue, ROOT.k]
    sns_colors = sns.color_palette("colorblind")
    tcolors = plot.tcolors = [ROOT.TColor(ROOT.TColor.GetFreeColorIndex(), *c) for c in sns_colors]
    colors = plot.colors = [c.GetNumber() for c in tcolors]


    for i, (cent, cdf) in enumerate(df.groupby('cent')):
        color = colors[i]
        data = merge_points(cdf)

        g_rinv = TGraphErrors(data.shape[0])
        np.frombuffer(g_rinv.GetX())[:] = np.array(data.kT)
        np.frombuffer(g_rinv.GetY())[:] = np.array(data.radius)
        np.frombuffer(g_rinv.GetEY())[:] =  np.array(data.radius_err) * 10

        g_lam = TGraphErrors(data.shape[0])
        np.frombuffer(g_lam.GetX())[:] = np.array(data.kT)
        np.frombuffer(g_lam.GetY())[:] = np.array(data.lam)
        np.frombuffer(g_lam.GetEY())[:] =  np.array(data.lam_err) * 10


        for g in (g_rinv, g_lam):
            g.SetMarkerStyle(21)
            g.SetMarkerSize(0.7)
            g.SetMarkerColor(color)
            g.SetLineColor(color)

        graphs.append(g_rinv)
        graphs_lam.append(g_lam)

        c.cd(1)
        if i == 0:
            g_rinv.Draw("APE")
        else:
            g_rinv.Draw("P ")

        c.cd(2)
        if i == 0:
            g_lam.Draw("APE")
        else:
            g_lam.Draw("P ")

        cent_name = cent.replace('_', '-')  + "%"
        leg.AddEntry(g_rinv, cent_name, 'P')


#     for g in graphs:
#         g.Draw('AP')
#     g.Draw('APL')

#     g.SetTitle("Radius")
    leg.Draw()
    return plot
Esempio n. 11
0
#gr = TGraphErrors(len(list_x_ll), x_ll, ratio_ll, x_data_unc_ll, y_data_unc_ll)



# Fitting histogram (with predefined function):
fit_x = TF1("fit_x", "pol1", 0.0, 550.0)
fit_x.SetLineColor(1)
fit_x.SetLineWidth(3)
gr.Fit(fit_x)

#Create a TGraphErrors to hold the confidence intervals
grint = TGraphErrors(len(xbins_comb))
grint.SetTitle(" ")
for i in range(0,len(xbins_comb)):
    grint.SetPoint(i, gr.GetX()[i], 0)
    #Compute the confidence intervals at the x points of the created graph
    #(TVirtualFitter::GetFitter())->GetConfidenceIntervals(grint);
    #Now the "grint" graph contains function values as its y-coordinates
    #and confidence intervals as the errors on these coordinates
    #Draw the graph, the function and the confidence intervals
    
    
#fit = hist->GetFunction(function_name);
chi2 = fit_x.GetChisquare()
# value of the first parameter
p1 = fit_x.GetParameter(0)
p1 = round(p1,4)
# error of the first parameter
e1 = fit_x.GetParError(0)
e1 = round(e1,4)
Esempio n. 12
0
    def ApplyBinShiftCorrection(self, hist):
        """
        Apply bin-shift correction to the input spectrum using an iterative procedure
        @param hist: Input spectrum
        @return: Bin-shift corrected spectrum 
        """

        h = deepcopy(hist)
        h.SetName("htemp")

        # Bin shift correction performed in model specturm * pt
        for i in range(1, h.GetNbinsX() + 1):
            pt = h.GetBinCenter(i)
            h.SetBinContent(i, h.GetBinContent(i) * pt)
            h.SetBinError(i, h.GetBinError(i) * pt)

        result = TGraphErrors(h)
        for i in range(0, result.GetN()):
            result.GetEX()[i] = 0.

        fitfun = TF1("fitfun", "([0]*(1.+x/[1])^(-[2])*x)-[3]", 0.15, 100.0)
        fitfun.SetParameter(0, 1000)
        fitfun.SetParameter(1, 1)
        fitfun.SetParameter(2, 5)
        fitfun.FixParameter(3, 0)
        h.Fit(fitfun, "")
        self.__StableFit(h, fitfun, True)

        # Iterative approach:
        # - Use model to get the mean of the function inside the bin
        # - Get the X where the mean is found
        # - Use the new coordinate (x,y) for the next iteration of the fit
        # for now 10 iterations fixed
        for k in range(1, 11):
            for i in range(1, h.GetNbinsX() + 1):
                y = fitfun.Integral(h.GetBinLowEdge(i),
                                    h.GetBinUpEdge(i)) / h.GetBinWidth(i)
                result.GetX()[i - 1] = self.FindX(y, fitfun,
                                                  h.GetBinLowEdge(i),
                                                  h.GetBinUpEdge(i))
            self.__StableFit(result, fitfun, False)

        # Undo multiplication with pt
        for i in range(0, result.GetN()):
            pt = result.GetX()[i]
            result.GetY()[i] /= pt
            result.GetEY()[i] /= pt

        #remove points that are 0
        while result.GetY()[0] < 1.e-99:
            result.RemovePoint(0)

        bval = 0
        for mybin in range(0, result.GetN() + 1):
            if result.GetY()[bin] < 1.e-99:
                bval = mybin
                break

        while result.RemovePoint(bval) > 0:
            continue
        return result
Esempio n. 13
0
def plot2BodyDist(theFitter, pars, chi2, ndf, 
                  Err = -1, NP = False, Prefix = "Mjj", Left = False):
    from ROOT import gPad, TLatex, TCanvas, kRed, kCyan, kBlue, \
         RooFit, RooPlot, RooCurve, RooAbsReal, TGraphErrors, TLine, \
         RooWjjMjjFitter

    if pars.includeMuons and pars.includeElectrons:
        modeString = ''
    elif pars.includeMuons:
        modeString = 'Muon'
    elif pars.includeElectrons:
        modeString = 'Electron'
    else:
        modeString = ''

    mf = theFitter.stackedPlot(False, RooWjjMjjFitter.mjj, Left)
    mf.SetName("%s_Stacked" % (Prefix));
    sf = theFitter.residualPlot(mf, "h_background", "dibosonPdf", False)
    sf.SetName("%s_Subtracted" % (Prefix));
    pf = theFitter.residualPlot(mf, "h_total", "", True)
    pf.SetName("%s_Pull" % (Prefix))
    pf2 = pf.emptyClone("%s_Pull_Corrected" % (Prefix))
    pf2.SetMinimum(-5.)
    pf2.SetMaximum(5.)
    corrPull = False
    lf = theFitter.stackedPlot(True, RooWjjMjjFitter.mjj, Left)
    lf.SetName("%s_Stacked_Log" % (Prefix));

    if Err > 0:
        totalPdf = theFitter.getWorkSpace().pdf('totalPdf')
        ## Ntotal = totalPdf.expectedEvents(iset)

        ## print 'Ntotal:',Ntotal
        h_dibosonPdf = sf.getCurve('h_dibosonPdf')
        totalPdf.plotOn(sf,
                        RooFit.ProjWData(theFitter.getWorkSpace().data('data')),
                        RooFit.Normalization(Err, RooAbsReal.Raw),
                        #RooFit.AddTo('h_dibosonPdf', 1., 1.),
                        #RooFit.Invisible(),
                        RooFit.Name('h_ErrUp'),
                        RooFit.Range('RangeForPlot'),
                        RooFit.NormRange('RangeForPlot'),
                        RooFit.LineColor(kRed), RooFit.LineStyle(3))
        h_ErrUp = sf.getCurve('h_ErrUp')
        sf.remove('h_ErrUp', False)

        ErrBand = TGraphErrors(h_dibosonPdf.GetN(), h_dibosonPdf.GetX(),
                               h_dibosonPdf.GetY())
        for pt in range(1, ErrBand.GetN()):
            ErrBand.SetPointError(pt, 0,
                                  h_ErrUp.interpolate(ErrBand.GetX()[pt]))
        ErrBand.SetName("ErrBand")
        ErrBand.SetTitle("Uncertainty")
        ErrBand.SetLineColor(kRed)
##         ErrBand.SetLineWidth(0)
##         ErrBand.SetLineStyle(0)
        ErrBand.SetFillColor(kRed)
        ErrBand.SetFillStyle(3353)

        
        #ErrBand.Draw('ap3')
        #h_ErrUp.Draw('lp')
        #gPad.Update()
        #gPad.WaitPrimitive()
##         h_ErrUp.Draw("al")
##         h_ErrUp.GetXaxis().Set(36, 40., 400.)
##         gPad.Update()
##         gPad.WaitPrimitive()
##         h_UpBand = RooCurve("h_UpBand", "Uncertainty", h_dibosonPdf, h_ErrUp,
##                             1., 1.)
##         h_UpBand.SetLineStyle(3)
##         h_UpBand.SetLineColor(kBlue+1)
##         h_DownBand = RooCurve("h_DownBand", "Uncertainty", h_dibosonPdf, h_ErrUp,
##                               1., -1.)
##         h_DownBand.SetLineStyle(3)
##         h_DownBand.SetLineColor(kBlue+1)

##         sf.addPlotable(h_UpBand, "L")
##         sf.addPlotable(h_DownBand, "L")
        sf.addObject(ErrBand, "3")
        #sf.Print("v")
        sf.drawAfter('h_dibosonPdf', 'ErrBand')
        #sf.Print("v")
        sf.drawAfter('ErrBand', 'theData')
        #sf.Print("v")
        sf.findObject('theLegend').AddEntry(ErrBand, 'Uncertainty', 'f')
        sf.findObject('theLegend').SetY1NDC(sf.findObject('theLegend').GetY1NDC() - 0.057)
        sf.findObject('theLegend').SetY1(sf.findObject('theLegend').GetY1NDC())

        corrPull = True
        pf2.addObject(sub2pull(sf.getHist('theData'),
                               sf.findObject('ErrBand')),
                      'p0')
        for item in range(0, int(pf.numItems())):
            firstItem = pf.getObject(item)
            if (type(firstItem) == TLine):
                newLine = TLine(firstItem)
                newLine.SetY1(4.)
                newLine.SetY2(-4.)
                pf2.addObject(newLine, 'l')
                #SetOwnership(newLine, False)


    if NP:
        NPPdf = theFitter.makeNPPdf();
        NPNorm = 4.*0.11*46.8/12.*pars.intLumi

        if (modeString == 'Electron'):
            if pars.njets == 2:
                NPNorm *= 0.0381
            elif pars.njets == 3:
                NPNorm *= 0.0123
        else:
            if pars.njets == 2:
                NPNorm *= 0.0550
            elif pars.njets == 3:
                NPNorm *= 0.0176

        print '**** N_NP:', NPNorm,'****'

        NPPdf.plotOn(sf, RooFit.ProjWData(theFitter.getWorkSpace().data('data')),
                     RooFit.Normalization(NPNorm, RooAbsReal.Raw),
                     RooFit.AddTo('h_dibosonPdf', 1., 1.),
                     RooFit.Name('h_NP'),
                     RooFit.Range('RangeForPlot'),
                     RooFit.NormRange('RangeForPlot'),
                     RooFit.LineColor(kBlue), RooFit.LineStyle(2))

        h_NP = sf.getCurve('h_NP')

        sf.drawBefore('h_dibosonPdf', 'h_NP')
        #sf.Print("v")
        sf.findObject('theLegend').AddEntry(h_NP, "CDF-like Signal", "L")
        sf.findObject('theLegend').SetY1NDC(sf.findObject('theLegend').GetY1NDC() - 0.057)
        sf.findObject('theLegend').SetY1(sf.findObject('theLegend').GetY1NDC())

    l = TLatex()
    l.SetNDC()
    l.SetTextSize(0.045)
    l.SetTextFont(42)

    cstacked = TCanvas("cstacked", "stacked")
    mf.Draw()
    if (chi2 > 0):
        l.DrawLatex(0.55, 0.49,
                    '#chi^{2}/dof = %0.3f/%d' % (chi2, ndf)
                    )
    pyroot_logon.cmsLabel(cstacked, pars.intLumi/1000, prelim = True)
    cstacked.Print('Wjj_%s_%s_%ijets_Stacked.pdf' % (Prefix, modeString,
                                                     pars.njets))
    cstacked.Print('Wjj_%s_%s_%ijets_Stacked.png' % (Prefix, modeString,
                                                     pars.njets))
    c2 = TCanvas("c2", "stacked_log")
    c2.SetLogy()
    lf.Draw()
    pyroot_logon.cmsPrelim(c2, pars.intLumi/1000)
    c2.Print('Wjj_%s_%s_%ijets_Stacked_log.pdf' % (Prefix, modeString,
                                                    pars.njets))
    c2.Print('Wjj_%s_%s_%ijets_Stacked_log.png' % (Prefix, modeString,
                                                    pars.njets))
    c3 = TCanvas("c3", "subtracted")
    sf.Draw()
    pyroot_logon.cmsLabel(c3, pars.intLumi/1000, prelim = True)
    c3.Print('Wjj_%s_%s_%ijets_Subtracted.pdf' % (Prefix, modeString,
                                                  pars.njets))
    c3.Print('Wjj_%s_%s_%ijets_Subtracted.png' % (Prefix, modeString,
                                                  pars.njets))
    c4 = TCanvas("c4", "pull")
    pf.Draw()
    c4.SetGridy()
    pyroot_logon.cmsPrelim(c4, pars.intLumi/1000)
    c4.Print('Wjj_%s_%s_%ijets_Pull.pdf' % (Prefix, modeString, pars.njets))
    c4.Print('Wjj_%s_%s_%ijets_Pull.png' % (Prefix, modeString, pars.njets))

    c5 = None
    if corrPull:
        c5 = TCanvas("c5", "corrected pull")
        pf2.Draw()
        c5.SetGridy()
        pyroot_logon.cmsPrelim(c5, pars.intLumi/1000)
        c5.Print('Wjj_%s_%s_%ijets_Pull_Corrected.pdf' % (Prefix, modeString,
                                                          pars.njets))
        c5.Print('Wjj_%s_%s_%ijets_Pull_Corrected.png' % (Prefix, modeString,
                                                          pars.njets))

    return ([mf,sf,pf2,lf],[cstacked,c2,c3,c5])
Esempio n. 14
0
def build_tgraphs_from_data(df,
                            keys=None,
                            xkey='kT',
                            skip_systematics=False,
                            title_dict=None):
    """
    """
    from collections import defaultdict
    from ROOT import TGraphErrors

    if keys is None:
        keys = ("Ro", "Rs", "Rl")

    if title_dict is None:
        title_dict = {
            'Ro': "R_{out}",
            'Rs': "R_{side}",
            'Rl': "R_{long}",
            'lam': "#lambda",
            'alpha': "#alpha",
            'radius': 'R_{inv}'
        }

    missing_titles = set(keys) - set(title_dict.keys())
    if missing_titles:
        raise ValueError(f"Title dict missing keys: {missing_titles}")

    def _merge_points(df, key):
        results = []

        for kt, data in df.groupby(xkey):
            errs = np.array(data[key + '_err'])
            weights = errs**-2
            val = (data[key] * weights).sum() / weights.sum()
            err = np.sqrt(1.0 / weights.sum())
            results.append([kt, val, err])

        return np.array(results).T

    graphs = defaultdict(dict)

    for cent, cdf in df.sort_values(xkey).groupby('cent'):

        for r in keys:
            x = []
            y = []
            ye = []
            x, y, ye = _merge_points(cdf, r)

            xe = np.zeros_like(x)
            title = [r]

            gdata = TGraphErrors(x.size)
            np.frombuffer(gdata.GetX(), dtype=np.float64)[:] = x
            np.frombuffer(gdata.GetY(), dtype=np.float64)[:] = y
            np.frombuffer(gdata.GetEY(), dtype=np.float64)[:] = ye

            if skip_systematics:
                gsys = None
            else:
                sys_key = f"{r}_sys_err"
                sys_err = np.array(cdf[sys_key])

                gsys = TGraphErrors(x.size)
                np.frombuffer(gsys.GetX(), dtype=np.float64)[:] = x  # - 0.004
                np.frombuffer(gsys.GetY(), dtype=np.float64)[:] = y
                np.frombuffer(gsys.GetEY(), dtype=np.float64)[:] = sys_err
                np.frombuffer(gsys.GetEX(), dtype=np.float64)[:] = 0.012

            graphs[r][cent] = (gdata, gsys)

    return dict(graphs)