Ejemplo n.º 1
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)}
Ejemplo n.º 2
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
Ejemplo n.º 3
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()
Ejemplo 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()
Ejemplo n.º 5
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
Ejemplo 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
Ejemplo 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()
Ejemplo n.º 8
0
def analyzeData(country, total, active, recovered, deaths, tStart, tStop,
                totalPopulation, symptomaticFraction, transmissionProbability,
                recoveryRate, doSmearing, doFit):
    ntuple = [
        tStart, tStop, totalPopulation, symptomaticFraction,
        transmissionProbability, recoveryRate
    ]
    farFromMax = 0.95
    growthRate = 0.13
    carryingCapacity = 4e5

    ################
    # Active cases #
    ################
    myCanvActive = TCanvas('myCanvActive_' + country,
                           'Active cases ' + country)

    xValues = [
        i for i in range(len(active.keys())) if i >= tStart and i <= tStop
    ]
    yValues = [
        active[k] for i, k in enumerate(sorted(active.keys()))
        if i >= tStart and i <= tStop
    ]
    erryValues = assignErrors(yValues)

    myGraphActive = TGraphErrors()
    myGraphActive.SetMarkerStyle(20)
    for i in range(len(xValues)):
        myGraphActive.SetPoint(myGraphActive.GetN(), xValues[i], yValues[i])
        myGraphActive.SetPointError(myGraphActive.GetN() - 1, 0, erryValues[i])
    myGraphActive.Draw('APE1')
    myGraphActive.GetHistogram().GetXaxis().SetTitle('Time (days)')
    myGraphActive.GetHistogram().GetYaxis().SetTitle(
        'Active cases affected by CoViD-19')

    historyActive = 0.
    for i, k in enumerate(sorted(active.keys())):
        if i < tStart:
            historyActive += active[k]
    ntuple.extend([historyActive, xValues, yValues, erryValues])
    print('==> History active cases:', historyActive)

    ###################
    # Build the model #
    ###################
    evActive = evolution([yValues[0], carryingCapacity, growthRate], tStart,
                         tStop, totalPopulation, recoveryRate,
                         symptomaticFraction, transmissionProbability,
                         historyActive)

    if doFit == True:
        evActive.runOptimization(xValues, yValues, erryValues, [], doSmearing)
        evActive.evolve(evActive.tStop, evActive.parValues, True)
        if doSmearing == True:
            evActive.smearing()
        evActiveGraphN = evActive.getGraphN()
        evActiveGraphN.Draw('PL same')
        statActive = evActive.addStats(evActive.parNames, evActive.parValues)

        print(
            '==> Active cases, history active cases, p-infected, Carrying capacity, total population alive',
            evActive.evolve(tStop, evActive.parValues), 'at day', tStop)
        print('==> Percentage population with antibodies',
              round(100. * evActive.totalInfected(tStop) / totalPopulation),
              '% at day', tStop, '(herd immunity at', evActive.herdImmunity(),
              '%)')
        print('==> Doubling time:', round(log(2.) / evActive.parValues[2], 1),
              'days')

        now = TLine(
            len(active) - 1, 0,
            len(active) - 1, evActive.fitFun.Eval(len(active) - 1))
        now = TLine(len(active) - 1, 0, len(active) - 1, 1)
        now.SetLineColor(4)
        now.SetLineWidth(2)
        now.Draw('same')

        willbe = TLine(evActive.fitFun.GetMaximumX(), 0,
                       evActive.fitFun.GetMaximumX(),
                       evActive.fitFun.GetMaximum())
        willbe.SetLineColor(6)
        willbe.SetLineWidth(2)
        willbe.Draw('same')

        myCanvActiveR0 = TCanvas('myCanvActiveR0_' + country, 'R0 ' + country)

        evActiveGraphR0 = evActive.getGraphR0(evActiveGraphN)
        evActiveGraphR0.Draw('APL')
        evActiveGraphR0.GetHistogram().GetXaxis().SetTitle('Time (days)')
        evActiveGraphR0.GetHistogram().GetYaxis().SetTitle('R')

        myCanvActiveR0.SetGrid()
        myCanvActiveR0.Modified()
        myCanvActiveR0.Update()

    myCanvActive.SetGrid()
    myCanvActive.Modified()
    myCanvActive.Update()

    #################
    # CONTROL PLOTS #
    #################

    ###############
    # Total cases #
    ###############
    myCanvTotal = TCanvas('myCanvTotal_' + country, 'Total cases ' + country)
    myGraphTotal = TGraphErrors()
    myGraphTotal.SetMarkerStyle(20)

    for k in sorted(total.keys()):
        myGraphTotal.SetPoint(myGraphTotal.GetN(), myGraphTotal.GetN(),
                              total[k])
        myGraphTotal.SetPointError(myGraphTotal.GetN() - 1, 0, sqrt(total[k]))

    myGraphTotal.Draw('APE1')
    myGraphTotal.GetHistogram().GetXaxis().SetTitle('Time (days)')
    myGraphTotal.GetHistogram().GetYaxis().SetTitle(
        'Total cases affected by CoViD-19')

    myCanvTotal.SetGrid()
    myCanvTotal.Modified()
    myCanvTotal.Update()

    ##########
    # Deaths #
    ##########
    myCanvDeaths = TCanvas('myCanvDeaths_' + country, 'Deaths ' + country)
    myGraphDeaths = TGraphErrors()
    myGraphDeaths.SetMarkerStyle(20)

    for k in sorted(deaths.keys()):
        myGraphDeaths.SetPoint(myGraphDeaths.GetN(), myGraphDeaths.GetN(),
                               deaths[k])
        myGraphDeaths.SetPointError(myGraphDeaths.GetN() - 1, 0,
                                    sqrt(deaths[k]))

    myGraphDeaths.Draw('APE1')
    myGraphDeaths.GetHistogram().GetXaxis().SetTitle('Time (days)')
    myGraphDeaths.GetHistogram().GetYaxis().SetTitle('Total deaths')

    myCanvDeaths.SetGrid()
    myCanvDeaths.Modified()
    myCanvDeaths.Update()

    ########################
    # Ratio deaths / total #
    ########################
    myCanvRatio01 = TCanvas('myCanvRatio01_' + country, 'Ratio ' + country)
    myGraphRatio01 = TGraphErrors()
    myGraphRatio01.SetMarkerStyle(20)

    for k in sorted(deaths.keys()):
        myGraphRatio01.SetPoint(myGraphRatio01.GetN(), myGraphRatio01.GetN(),
                                deaths[k] / total[k])
        myGraphRatio01.SetPointError(
            myGraphRatio01.GetN() - 1, 0,
            myGraphRatio01.GetY()[myGraphRatio01.GetN() - 1] *
            sqrt(deaths[k] / (deaths[k] * deaths[k]) + total[k] /
                 (total[k] * total[k])))

    myGraphRatio01.Draw('APE1')
    myGraphRatio01.GetHistogram().GetXaxis().SetTitle('Time (days)')
    myGraphRatio01.GetHistogram().GetYaxis().SetTitle(
        'Total deaths / Total cases')

    myCanvRatio01.SetGrid()
    myCanvRatio01.Modified()
    myCanvRatio01.Update()

    ############################################
    # Ratio delta(deaths + recovered) / active #
    ############################################
    myCanvRatio02 = TCanvas('myCanvRatio02_' + country, 'Ratio ' + country)
    myGraphRatio02 = TGraphErrors()
    myGraphRatio02.SetMarkerStyle(20)

    sortedKeys = sorted(deaths.keys())
    for i, k in enumerate(sortedKeys[1:]):
        numerator = abs(deaths[k] - deaths[sortedKeys[i]] + recovered[k] -
                        recovered[sortedKeys[i]])
        denominator = active[k]
        myGraphRatio02.SetPoint(
            myGraphRatio02.GetN(),
            myGraphRatio02.GetN() + 1,
            numerator / denominator if denominator != 0 else 0)
        myGraphRatio02.SetPointError(
            myGraphRatio02.GetN() - 1, 0,
            (myGraphRatio02.GetY()[myGraphRatio02.GetN() - 1] *
             sqrt(numerator / pow(numerator, 2) +
                  denominator / pow(denominator, 2)))
            if denominator != 0 else 0)

    myGraphRatio02.Draw('AP')
    myGraphRatio02.GetHistogram().GetXaxis().SetTitle('Time (days)')
    myGraphRatio02.GetHistogram().GetYaxis().SetTitle(
        '#Delta Recovered (alive + dead) / Active cases')

    myCanvRatio02.SetGrid()
    myCanvRatio02.Modified()
    myCanvRatio02.Update()

    ######################################
    # Ratio delta(deaths) / delta(total) #
    ######################################
    myCanvRatio03 = TCanvas('myCanvRatio03_' + country, 'Ratio ' + country)
    myGraphRatio03 = TGraphErrors()
    myGraphRatio03.SetMarkerStyle(20)

    sortedKeys = sorted(deaths.keys())
    for i, k in enumerate(sortedKeys[1:]):
        numerator = abs(deaths[k] - deaths[sortedKeys[i]])
        denominator = total[k] - total[sortedKeys[i]]
        myGraphRatio03.SetPoint(
            myGraphRatio03.GetN(),
            myGraphRatio03.GetN() + 1,
            numerator / denominator if denominator != 0 else 0)
        myGraphRatio03.SetPointError(
            myGraphRatio03.GetN() - 1, 0,
            (myGraphRatio03.GetY()[myGraphRatio03.GetN() - 1] *
             sqrt(numerator / pow(numerator, 2) +
                  denominator / pow(denominator, 2)))
            if denominator != 0 else 0)

    myGraphRatio03.Draw('AP')
    myGraphRatio03.GetHistogram().GetXaxis().SetTitle('Time (days)')
    myGraphRatio03.GetHistogram().GetYaxis().SetTitle(
        '#Delta deaths / #Delta total')

    myCanvRatio03.SetGrid()
    myCanvRatio03.Modified()
    myCanvRatio03.Update()

    if doFit == False:
        return [
            ntuple, myCanvTotal, myGraphTotal, myCanvActive, myGraphActive,
            myCanvDeaths, myGraphDeaths, myCanvRatio01, myGraphRatio01,
            myCanvRatio02, myGraphRatio02, myCanvRatio03, myGraphRatio03
        ]

    return [
        ntuple, myCanvTotal, myGraphTotal, myCanvActive, myGraphActive,
        evActive, evActiveGraphN, statActive, now, willbe, myCanvActiveR0,
        evActiveGraphR0, myCanvDeaths, myGraphDeaths, myCanvRatio01,
        myGraphRatio01, myCanvRatio02, myGraphRatio02, myCanvRatio03,
        myGraphRatio03
    ]
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()
            cPreview.cd(islice + 1)
            draw_1histogram(h,"","")
        # make graph
        if result:
            gSF.SetPoint(islice, sliceSum[islice]-sliceWidth[islice]*0.5, result.Get().Parameter(1))
            gSF.SetPointError(islice, sliceWidth[islice]*0.5 , result.Get().Parameter(2))
    prepare_graph(gSF, 'sf_'+str(len(merge))+'layers', ';radial depth [cm];sampling fraction', ifile+9)
    all_graphs.append(gSF)
    graphTitles.append('#color['+str(colour[ifile])+']{'+str(energy)+' GeV e^{-}}')
    print("samplFractMap ["+str(energy)+"]= ", end='')
    for islice in range(0, Nslicesmerged):
        if islice == 0:
            print("{ ", end='')
        if islice > 0:
            print(", ", end='')
        print(str(gSF.GetY()[islice]), end='')
    print("};")


canv = prepare_single_canvas('sf_e'+str(energy)+'GeV', 'Sampling fraction for '+str(energy)+'GeV')

# Draw graph and all labels
prepare_graph(gSF, 'sf_'+str(len(merge))+'layers', ';radial depth;sampling fraction', ifile+9)
all_graphs[0].Draw("ape")
for g in all_graphs[1:]:
    g.Draw("pe")
if calo_init.args.axisMax:
    all_graphs[0].SetMaximum(calo_init.args.axisMax)
if calo_init.args.axisMin:
    all_graphs[0].SetMinimum(calo_init.args.axisMin)
canv.Update()
Ejemplo n.º 11
0
    canv.SaveAs("sampling_fraction_plots.pdf")
    canv.SaveAs("sampling_fraction_plots.png")
    plots = TFile("sampling_fraction.root", "RECREATE")
    if calo_init.args.preview:
        cPreview.SaveAs("preview_sampling_fraction.png")
for g in all_graphs:
    g.Write()

mean = numpy.zeros(1, dtype=float)
std = numpy.zeros(1, dtype=float)
t = TTree("samplingFraction", "Sampling fraction for detector layers")
t.Branch("mean", mean, "mean/D")
t.Branch("std", std, "std/D")
for islice in range(0, Nslicesmerged):
    for ilay in range(0, calo_init.args.merge[islice]):
        mean[0] = gSF.GetY()[islice]
        std[0] = gSF.GetErrorY(islice)
        t.Fill()
plots.Write()
plots.Close()

print("============================================================")
print("== to be used in FCCSW, with CalibrateInLayers algorithm: ==")
print("============================================================")
print "samplingFraction = ",
for islice in range(0, Nslicesmerged):
    if islice > 0:
        print " + ",
    print "[" + str(gSF.GetY()[islice]) + "] * " + str(
        calo_init.args.merge[islice]),
print()
Ejemplo n.º 12
0
def showDAC(fname, Infox=None, saveName='temp_figs/test', mode=1):

    lines = None
    with open(fname, 'r') as f1:
        lines = f1.readlines()

    gr1 = TGraphErrors()
    gr2 = TGraph()
    gr3 = TGraph()
    gr4 = TGraph()

    largeError = -1
    largeErrorI = None
    largeErrorMS = None

    for line in lines:
        line = line.rstrip()
        if len(line) == 0:
            continue
        elif line[0] == '#':
            fs = line.split()
            code = int(fs[3][5:], 16)
            print code
        else:
            ms = [float(x) for x in line.split(',')][1::2]
            if mode == 0: ms = [float(line)]
            mean = nm.mean(ms)
            error = nm.std(ms)

            if error > largeError:
                largeError = error
                largeErrorI = code
                largeErrorMS = ms

            gr1.SetPoint(code, code, mean)
            gr1.SetPointError(code, 0, error)

    print largeErrorI, largeErrorMS, nm.mean(largeErrorMS), nm.mean(ms)
    for i in range(len(largeErrorMS)):
        gr4.SetPoint(i, i, largeErrorMS[i])

    N = gr1.GetN()
    Ys = gr1.GetY()
    print Ys[0], Ys[N - 1], Ys[largeErrorI]
    LSB = (Ys[N - 1] - Ys[0]) / (N - 1)
    print LSB
    for i in range(N):
        gr2.SetPoint(i, i, Ys[i] - (Ys[0] + i * LSB))
        gr3.SetPoint(i, i, Ys[i] - Ys[i - 1] - LSB if i > 0 else 0)

    line = TLine()
    lt = TLatex()

    cav1 = TCanvas('cav1', 'cav1', 1000, 800)
    cav1.Divide(2, 2)
    cav1.cd(1)
    gr1.Draw('AP')
    h1 = gr1.GetHistogram()
    h1.GetXaxis().SetTitle('Code')
    h1.GetYaxis().SetTitle('U [V]')
    ln1 = line.DrawLine(0, Ys[0], N - 1, Ys[N - 1])
    ln1.SetLineColor(2)

    rgInfo = '[{0:.2g},{1:.2g}] V'.format(Ys[0], Ys[N - 1])
    if Infox:
        rgInfo = Infox + ': ' + rgInfo
    lt.DrawLatexNDC(0.2, 0.85, rgInfo)

    cav1.cd(2)
    gr4.SetMarkerStyle(20)
    gr4.Draw('AP')
    h4 = gr4.GetHistogram()
    h4.GetXaxis().SetTitle('#it{i}th')
    h4.GetYaxis().SetTitle('U [V]')
    lt.DrawLatexNDC(
        0.2, 0.85,
        "{0:d} measurements for code={1:d}".format(len(largeErrorMS),
                                                   largeErrorI))

    cav1.cd(3)
    gr2.SetFillColor(2)
    gr2.Draw('APB')
    h2 = gr2.GetHistogram()
    h2.GetXaxis().SetTitle('Code')
    h2.GetYaxis().SetTitle('INL [V]')

    lY = LSB if gr2.GetMean(2) > 0 else -LSB
    ln2 = line.DrawLine(0, lY, N, lY)
    ln2.SetLineStyle(2)

    lt.DrawLatexNDC(
        0.6, 0.85,
        "Max INL={0:.1f} LSB".format(max([abs(x) for x in gr2.GetY()]) / LSB))

    cav1.cd(4)
    gr3.SetFillColor(4)
    gr3.Draw('APB')
    h3 = gr3.GetHistogram()
    h3.GetXaxis().SetTitle('Code')
    h3.GetYaxis().SetTitle('DNL [V]')

    lY = LSB if gr3.GetMean(2) > 0 else -LSB
    ln3 = line.DrawLine(0, lY, N, lY)
    ln3.SetLineStyle(2)
    lt.DrawLatexNDC(
        0.6, 0.85,
        "Max DNL={0:.1f} LSB".format(max([abs(x) for x in gr3.GetY()]) / LSB))

    cav1.cd()
    waitRootCmdX(saveName)
Ejemplo n.º 13
0
class RatePlotProducerPileUp(Analyzer):
    '''Analyzer creating a rate plot with pile up events and saving it to ROOT and SVG format.
  
  Example::
  
    rate = cfg.Analyzer(
      RatePlotProducerPileUp,
      file_label = 'tfile1',
      plot_name = 'rate',
      plot_title = 'A rate plot',
      zerobias_rate = 1/25e-9,
      input_objects = 'jets',
      bins = [30, 40, 50, 60],
      yscale = 1e6,
      scale_factors = [3, 5, 4]
    )
    
  * file_label: (Facultative) Name of a TFileService. If specified, the histogram will be saved in that root file, otherwise it will be saved in a <plot_name>.png and <plot_name>.root file
  * plot_name: Name of the plot (Key in the output root file).
  * plot_title: Title of the plot.
  * bins: Array containing the bins to be tested
  * zerobias_rate: zero bias trigger rate, 40 MHz @ 25 ns bunch spacing
  * input_objects: name of the particle collection
  * yscale: y level of the reference line
  * scale_factors: custom factors to be applied to the bin, 1 is assumed in case of missing parameter or if less factors than bins are provided
  '''
    '''Generates a threshold function'''
    def thresholdTriggerGenerator(self, threshold):
        def thresholdTrigger(ptc):
            return ptc.pt() > threshold

        return thresholdTrigger

    def beginLoop(self, setup):
        super(RatePlotProducerPileUp, self).beginLoop(setup)

        self.hasTFileService = hasattr(self.cfg_ana, "file_label")
        if self.hasTFileService:
            servname = '_'.join([
                'heppy.framework.services.tfile.TFileService',
                self.cfg_ana.file_label
            ])
            tfileservice = setup.services[servname]
            self.rootfile = tfileservice.file
        else:
            self.rootfile = TFile(
                '/'.join([self.dirName, self.cfg_ana.plot_name + '.root']),
                'recreate')

        bins = array("f", self.cfg_ana.bins)
        self.histogram = TH1F(self.cfg_ana.plot_name, self.cfg_ana.plot_title,
                              len(bins) - 1, bins)
        self.numberOfEvents = self.cfg_comp.nGenEvents

    def process(self, event):
        '''Process the event.
      event must contain
    
    * self.cfg_ana.input_objects: collection of objects to be selected
       These objects must be usable by the filtering function
       self.cfg_ana.trigger_func.
    '''

        input_collection = getattr(event, self.cfg_ana.input_objects)

        #We want accept events without objects if the threshold is 0 or less
        startIdx = 0

        #Adding events for that thresholds
        for x in range(0, len(self.cfg_ana.bins) - 1):
            if self.cfg_ana.bins[x] <= 0:
                self.histogram.AddBinContent(x + 1)
                startIdx = x + 1

        #startIdx keeps track of where the positive thresholds start

        # MET is not iterable, it is a single object
        # We treat here single objects
        if not isinstance(input_collection, collections.Iterable):

            for x in range(startIdx, len(self.cfg_ana.bins) - 1):
                # Preparing the check function
                trigger_func = self.thresholdTriggerGenerator(
                    self.cfg_ana.bins[x])
                # Checking if the object passes the trigger
                if trigger_func(input_collection):
                    self.histogram.AddBinContent(x + 1)
                else:
                    #If no item passes the threshold I can stop
                    break

        elif isinstance(input_collection, collections.Mapping):

            # Iterating through all the objects
            for x in range(startIdx, len(self.cfg_ana.bins) - 1):
                # Checking what thresholds are satisfied
                isPassed = False
                for key, val in input_collection.iteritems():

                    # Preparing the check function
                    trigger_func = self.thresholdTriggerGenerator(
                        self.cfg_ana.bins[x])
                    # Checking if the object passes the trigger
                    if trigger_func(val):
                        self.histogram.AddBinContent(x + 1)
                        isPassed = True
                        # We don't need to check for other objects
                        break

                if not isPassed:
                    #If no objects passes the threshold I can stop
                    break

        else:

            for x in range(startIdx, len(self.cfg_ana.bins) - 1):
                # Checking what thresholds are satisfied
                isPassed = False
                for obj in input_collection:
                    # Preparing the check function
                    trigger_func = self.thresholdTriggerGenerator(
                        self.cfg_ana.bins[x])
                    # Checking if the object passes the trigger
                    if trigger_func(obj):
                        self.histogram.AddBinContent(x + 1)
                        isPassed = True
                        # We don't need to check for other objects
                        break

                if not isPassed:
                    #If no objects passes the threshold I can stop
                    break

    def write(self, setup):

        self.rootfile.cd()
        #Rescaling to corresponding rate
        if self.cfg_ana.normalise:
            normalisation = self.cfg_ana.zerobias_rate / self.numberOfEvents
            self.graphErrors = TGraphErrors(self.histogram)
            for x in xrange(0, self.graphErrors.GetN()):
                #Rescaling everything to have rates
                self.graphErrors.GetEY()[x] *= normalisation
                self.graphErrors.GetY()[x] *= normalisation
                self.graphErrors.SetName(self.cfg_ana.plot_name)
                self.histogram = self.graphErrors

        if hasattr(self.cfg_ana, "scale_factors"):
            for x in xrange(0, len(self.cfg_ana.scale_factors)):
                self.histogram.SetBinContent(
                    x + 1,
                    self.histogram.GetBinContent(x + 1) *
                    self.cfg_ana.scale_factors[x])

        self.histogram.Write()
        xMax = self.histogram.GetXaxis().GetXmax()
        xMin = self.histogram.GetXaxis().GetXmin()
        yMin = self.histogram.GetMinimum()
        yMax = self.histogram.GetMaximum()

        self.histogram.SetMarkerStyle(20)
        self.histogram.SetMarkerColor(4)
        self.histogram.SetLineColor(1)

        c1 = TCanvas("canvas_" + self.cfg_ana.plot_name,
                     self.cfg_ana.plot_title, 600, 600)
        c1.SetGridx()
        c1.SetGridy()
        self.histogram.Draw("PE")
        c1.SetLogy(True)

        c1.Update()
        c1.Print(self.cfg_ana.plot_name + ".svg", "svg")
Ejemplo n.º 14
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
Ejemplo n.º 15
0
def plot_results(switch_pre_post, no_mpa_light, x1, y1, calibconfsxmlroot,
                 prev_fit_mat):
    drawstr = ""
    savestr = ''
    col = 1
    if switch_pre_post == 0:
        savestr = 'pre'
    else:
        savestr = 'post'
        col = 2
        drawstr = " same"

    xvec = np.array(x1, dtype='uint16')
    xdacval = 0.
    thdacvv = []
    yarrv = []
    xdvals = []
    linearr = []
    stackarr = []
    fitfuncarr = []
    fitparameterarray = []
    c1 = TCanvas('c1', 'Pixel Monitor ' + savestr, 700, 900)
    c1.Divide(3, 2)
    for i in range(0, no_mpa_light):
        backup = TFile(
            "plots/backup_" + savestr + "Calibration_" + options.string +
            "_MPA" + str(i) + ".root", "recreate")
        calibconfxmlroot = calibconfsxmlroot[i]
        xdvals.append(0.)
        c1.cd(i + 1)
        thdacv = []
        yarr = np.array(y1[i])
        linearr.append([])
        gr1 = []
        lines = []
        fitfuncarr.append([])
        fitfuncs = []
        fitparameterarray.append([])
        fitparams = []
        yarrv.append(yarr)
        stackarr.append(
            THStack('a', 'pixel curves;DAC Value (1.456 mV);Counts (1/1.456)'))
        # hstack = THStack('a','pixel curves;DAC Value (1.456 mV);Counts (1/1.456)')
        for iy1 in range(0, len(yarr[0, :])):
            yvec = yarr[:, iy1]
            # if max(yvec)==0:
            # 	print "zero"
            gr1.append(
                TH1I(str(iy1), ';DAC Value (1.456 mV);Counts (1/1.456)',
                     len(x1), 0, x1[-1]))
            gr1[iy1].Sumw2(ROOT.kFALSE)
            for j in np.nditer(xvec):
                gr1[iy1].SetBinContent(gr1[iy1].FindBin(j),
                                       (np.array(yvec, dtype='int')[j]))
            gr1[iy1].Sumw2(ROOT.kTRUE)
            color = iy1 % 9 + 1
            gr1[iy1].SetLineColor(color)
            gr1[iy1].SetMarkerColor(color)
            gr1[iy1].SetFillColor(color)
            gr1[iy1].SetLineStyle(1)
            gr1[iy1].SetLineWidth(1)
            gr1[iy1].SetFillStyle(1)
            gr1[iy1].SetMarkerStyle(1)
            gr1[iy1].SetMarkerSize(.5)
            gr1[iy1].SetMarkerStyle(20)
            fitfuncs.append(TF1('gaus', 'gaus', 0, 256))
            fitfuncs[iy1].SetNpx(256)
            fitfuncs[iy1].SetParameters(gr1[iy1].GetMaximum(),
                                        gr1[iy1].GetMean(), gr1[iy1].GetRMS())
            cloned = gr1[iy1].Clone()
            cloned.SetDirectory(0)
            fitparams.append([])
            mean = 0
            if gr1[iy1].GetMaximum() > 1:
                gr1[iy1].Fit(fitfuncs[iy1], 'rq +rob=0.8', '', 0, 256)
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(0))
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(1))
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(2))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(0))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(1))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(2))
                if (fitfuncs[iy1].GetNDF() > 0):
                    fitparams[iy1].append(fitfuncs[iy1].GetChisquare() /
                                          fitfuncs[iy1].GetNDF())
                else:
                    fitparams[iy1].append(0)
                mean = fitfuncs[iy1].GetParameter(1)
            else:
                for kk in range(0, 7):
                    fitparams[iy1].append(0)
            fitparameterarray[i].append(fitparams[iy1])
            fitfuncarr[i].append(fitfuncs[iy1])
            stackarr[i].Add(cloned)
            if iy1 == (len(yarr[0, :]) - 1):
                stackarr[i].Draw('nostack hist e1 x0')
                # for fitfuncs1 in fitfuncarr[i]:
                # 	fitfuncs1.Draw("same")
                # for lines1 in linearr[i]:
                # 	lines1.Draw("same")
                if (stackarr[i].GetMaximum() > 1):
                    Maximum = TMath.Power(
                        10, (round(TMath.Log10(stackarr[i].GetMaximum())) - 1))
                    stackarr[i].SetMinimum(.1)
                    stackarr[i].SetMaximum(Maximum)
                    gPad.SetLogy()
                    gPad.Update()
            gr1[iy1].SetLineColor(1)
            gr1[iy1].SetMarkerColor(1)
            gr1[iy1].SetFillColor(1)
            gr1[iy1].Write(str(iy1))
            fitfuncs[iy1].Write(str(iy1) + 'fit')
            #Get prevous trim value for the channel
            if iy1 % 2 == 0:
                prev_trim = int(calibconfxmlroot[(iy1) / 2 +
                                                 1].find('TRIMDACL').text)
            else:
                prev_trim = int(calibconfxmlroot[(iy1 + 1) /
                                                 2].find('TRIMDACR').text)
            trimdac = 0
            # Now we have the routine to find the midpoint
            # dummy = []
            # dummy = traditional_trim(xvec,yvec,prev_trim,i)
            if (options.cal_type == 0):
                dummy = traditional_trim(xvec, yvec, prev_trim, i)
            elif (options.cal_type == 1):
                dummy = new_trim(xvec, yvec, prev_trim, i, mean)
            elif (options.cal_type == 2):
                dummy = new_trim1(xvec, yvec, prev_trim, i, mean)

            xdacval = dummy[0]
            trimdac = dummy[1]
            xdvals[i] = xdacval
            thdacv.append(trimdac)
            lines.append(
                TLine(xdacval / scalefac, .1, xdacval / scalefac,
                      cloned.GetMaximum()))
            linearr[i].append(lines[iy1])
            linearr[i][iy1].SetLineColor(2)
        thdacvv.append(thdacv)
        # print thdacv
    c1.SaveAs(
        'plots/Scurve_Calibration' + options.string + '_' + savestr + '.root',
        'root')
    c1.SaveAs(
        'plots/Scurve_Calibration' + options.string + '_' + savestr + '.pdf',
        'pdf')
    c1.SaveAs(
        'plots/Scurve_Calibration' + options.string + '_' + savestr + '.png',
        'png')
    backup.Close()
    objarr = []
    normgraph = TGraphErrors(no_mpa_light * 48)
    meangraph = TGraphErrors(no_mpa_light * 48)
    sigmagraph = TGraphErrors(no_mpa_light * 48)
    chisquaregraph = TGraphErrors(no_mpa_light * 48)
    mean_corrgraph = TGraphErrors(no_mpa_light * 48)
    normgraph.SetName('normgraph_' + savestr)
    meangraph.SetName('meangraph_' + savestr)
    sigmagraph.SetName('sigmagraph_' + savestr)
    chisquaregraph.SetName('chisquare_' + savestr)
    mean_corrgraph.SetName('mean_corr_' + savestr)
    meanhist = TH1F('meanhist_' + savestr,
                    'Mean DAC; DAC Value (1.456 mV); counts', 256, 0, 255)
    sigmahist = TH1F('sigmahist_' + savestr,
                     'Sigma DAC; DAC Value (1.456 mV); counts', 250, 0, 10)
    normgraph.SetTitle('Normalization; Channel; Normalization')
    meangraph.SetTitle('Mean; Channel; DAC Value (1.456 mV)')
    sigmagraph.SetTitle('Sigma; Channel; DAC Value (1.456 mV)')
    chisquaregraph.SetTitle('Chisquared/NDF; Channel; Chisquared/NDF ')
    mean_corrgraph.SetTitle('Correction; chann; DAC Value (1.456 mV)')
    objarr.append([
        normgraph, meangraph, sigmagraph, chisquaregraph, meanhist, sigmahist,
        mean_corrgraph
    ])
    A = np.array(fitparameterarray)
    RMSMeanPerChip = []
    pointno = 0
    for j in range(0, A.shape[0]):
        tmparr = []
        for j1 in range(0, A.shape[1]):
            # print A[j][j1][2]
            normgraph.SetPoint(pointno, pointno + 1, A[j][j1][0])
            normgraph.SetPointError(pointno, 0, A[j][j1][3])
            # if (A[j][j1][1]>1):
            tmparr.append(A[j][j1][1])
            meangraph.SetPoint(pointno, pointno + 1, A[j][j1][1])
            meangraph.SetPointError(pointno, 0, A[j][j1][4])
            sigmagraph.SetPoint(pointno, pointno + 1, A[j][j1][2])
            sigmagraph.SetPointError(pointno, 0, A[j][j1][5])
            chisquaregraph.SetPoint(pointno, pointno + 1, A[j][j1][6])
            chisquaregraph.SetPointError(pointno, 0, 0)
            if (switch_pre_post == 1):
                mean_corrgraph.SetPoint(pointno, pointno + 1,
                                        A[j][j1][1] - prev_fit_mat[j][j1][1])
                mean_corrgraph.SetPointError(
                    pointno, 0, A[j][j1][4] - prev_fit_mat[j][j1][4])
            if (A[j][j1][1] > 0):
                meanhist.Fill(A[j][j1][1])
            if (A[j][j1][2] > 0):
                sigmahist.Fill(A[j][j1][2])
            pointno += 1
        tmpmeanarray = np.array(tmparr, dtype=np.float)
        # print tmpmeanarray
        # print tmpmeanarray.shape[0]
        # tmpmeanarray.shape[]
        # print 'the array'
        # print ROOT.TMath.RMS(48,tmpmeanarray)
        RMSMeanPerChip.append(0)
    length = len(yarrv[0][0, :])
    RMSCorrection = []
    if (switch_pre_post == 1):
        corr_arr = np.array(mean_corrgraph.GetY(), dtype='d')
        # print corr_arr
        for j in range(0, no_mpa_light):
            # print j, array('d',corr_arr[(j*48):((j+1)*48):1])
            RMSCorrection.append(
                ROOT.TMath.RMS(48,
                               array('d',
                                     corr_arr[(j * 48):((j + 1) * 48):1])))
        # print ROOT.TMath.RMS(48,corr_arr[(j*48):((j+1)*48):1])
    return thdacvv, xdvals, A, length, objarr, RMSMeanPerChip, RMSCorrection
Ejemplo n.º 16
0
canvas.Print("metTriggerEfficiency_ff_H_WW_enuenu_1000events.png", "png")
canvas.Print("metTriggerEfficiency_ff_H_WW_enuenu_1000events.pdf", "pdf")

label_200kHz = TLatex(220000, 0.9, "110 GeV - 200 kHz")
label_200kHz.SetTextSize(0.03)
line_200kHz = TLine(200000, 0, 200000, 1.1)
line_200kHz.SetLineColor(2)
line_200kHz.SetLineStyle(2)

canvas.SetLogx(1)
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()
Ejemplo n.º 17
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
Ejemplo n.º 18
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)