Example #1
0
 def makeTMultiGraph(self,name,tit=None):
     title = tit
     if tit is None:title = name.replace('_',' ')
     tmg = TMultiGraph()
     tmg.SetName(name)
     tmg.SetTitle(title)
     return tmg
Example #2
0
    def getGraph(self):
        from array import array
        from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors
        n = len(self.__x)
        if n != len(self.__y) or n != len(self.__yErrLow) or n != len(self.__yErrHigh):
            raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match"%(len(self.__x), len(self.__y), len(self.__yErrLow), len(self.__yErrHigh))

        result = TMultiGraph()
        legendPosition = [float(i) for i in self.__getStyleOption("legendPosition").split()]
        legend = TLegend(*legendPosition)
        legend.SetFillColor(0)
        result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))

        xErr = array("d",[0 for i in range(n)])

        graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__yErrLow,self.__yErrHigh)
        graph.SetLineWidth(2)
        graph.SetFillColor(0)
        graph.SetLineColor(int(self.__getStyleOption("lineColor")))
        graph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        graph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        result.Add(graph,"P")

        result.SetName("MG_%s"%(self.__title))
        legend.AddEntry(graph, self.__getStyleOption("name"))
        
        return (result, legend)
Example #3
0
def MakePlot(PlotList, Mode):
    colors = [
        ROOT.kRed, ROOT.kBlue, ROOT.kGreen, ROOT.kOrange, ROOT.kCyan,
        ROOT.kMagenta
    ]

    MG = TMultiGraph()
    MG.SetTitle(
        "Varying {};Center of Mass Angle in Degrees;Cross Section in mb/sr".
        format(Mode))
    MG.SetTitle("MG_{}".format(Mode))
    MG.SetName("MG_{}".format(Mode))
    legend = ROOT.TLegend(0.65, .65, .9, .9)

    Zipper = zip(PlotList, colors)

    for plot, color in Zipper:
        plot.SetMarkerColor(ROOT.kWhite)
        plot.SetLineColor(color)
        plot.SetFillColor(ROOT.kWhite)
        plot.SetLineWidth(2)
        MG.Add(plot, "L")
        legend.AddEntry(plot, plot.GetName())

    MG.Draw("AL")
    canvas.SetLogy()
    MG.GetXaxis().SetTitle("Center of Mass Angle in Degrees")
    MG.GetYaxis().SetTitle("Cross Section in mb/sr")
    MG.Draw()
    legend.Draw()

    canvas.SaveAs("vary_{}.png".format(Mode))
Example #4
0
    def getGraph(self):
        from array import array
        from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors
        n = len(self.__x)
        if n != len(self.__y) or n != len(self.__yErrLow) or n != len(
                self.__yErrHigh):
            raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match" % (
                len(self.__x), len(self.__y), len(
                    self.__yErrLow), len(self.__yErrHigh))

        result = TMultiGraph()
        legendPosition = [
            float(i) for i in self.__getStyleOption("legendPosition").split()
        ]
        legend = TLegend(*legendPosition)
        legend.SetFillColor(0)
        result.SetTitle("%s;%s;%s" %
                        (self.__title, self.__xTitle, self.__yTitle))
        #(refArrays, refLabel) = self.__getRefernceGraphArrays()
        #refGraph = TGraphAsymmErrors(*refArrays)

        #refGraph.SetLineWidth(2)
        #refGraph.SetLineColor(int(self.__config.get("reference","lineColor")))
        #refGraph.SetFillColor(int(self.__config.get("reference","fillColor")))
        #result.Add(refGraph,"L3")
        #legend.AddEntry(refGraph,self.__config.get("reference","name"))

        xErr = array("d", [0 for i in range(n)])
        print "__x = ", self.__x
        print "__y = ", self.__y
        graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr,
                                  self.__yErrLow, self.__yErrHigh)
        graph.SetLineWidth(2)
        graph.SetFillColor(0)
        graph.SetLineColor(int(self.__getStyleOption("lineColor")))
        graph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        graph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr,
                                     self.__ySysErrLow, self.__ySysErrHigh)
        sysGraph.SetLineWidth(1)
        sysGraph.SetFillColor(0)
        sysGraph.SetLineColor(int(self.__getStyleOption("lineColor")))
        sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        result.Add(sysGraph, "[]")
        result.Add(graph, "P")
        #        result.SetName("MultiPlots")
        #         result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        result.SetName("MG_%s" % (self.__title))
        legend.AddEntry(graph, self.__getStyleOption("name"))

        #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)):
        #    self.__addAnnotaion("hallo",x,y,yErr)

        return (result, legend)
Example #5
0
def printmultigraph(grs, sortk, plotoptions, outn, title, year, doext,
                    ploterror, ymax):
    import CMS_lumi, tdrstyle
    import array
    #set the tdr style
    tdrstyle.setTDRStyle()

    #change the CMS_lumi variables (see CMS_lumi.py)
    CMS_lumi.writeExtraText = 1
    CMS_lumi.extraText = "Preliminary"
    if year == 2018:
        CMS_lumi.extraText2 = "2018 pp data"
    if year == 2017:
        CMS_lumi.extraText2 = "2017 pp data"
    if year == 2016:
        CMS_lumi.extraText2 = "2016 pp data"
    CMS_lumi.lumi_sqrtS = "13 TeV"  # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)
    CMS_lumi.writeTitle = 1
    CMS_lumi.textTitle = title

    iPos = 11
    if (iPos == 0): CMS_lumi.relPosX = 0.12

    H_ref = 600
    W_ref = 800
    W = W_ref
    H = H_ref

    iPeriod = 0
    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.12 * W_ref
    R = 0.04 * W_ref

    c = TCanvas("c", "c", 50, 50, W, H)
    #gStyle.SetOptStat(0)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    #canvassettings(c)

    mg = TMultiGraph()
    #mg  = grs['main']
    mg.SetTitle(title)
    #gStyle.SetTitleAlign(33)
    #gStyle.SetTitleX(0.99)
    leg = TLegend(
        0.345, 0.68, 0.645, 0.88
    )  #TLegend(1. - c.GetRightMargin() - 0.8, 1. - c.GetTopMargin() - 0.40,1. - c.GetRightMargin()- 0.60, 1. - c.GetTopMargin() -0.02)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetMargin(0.1)
    #ymax = 0;
    ratesFromFit = {}
    evVal = 15000
    if doext:
        evVal = 50000

    #f=TFile.Open(outn+".root","RECREATE")


#  for name,value in plotoptions.iteritems():
    for name in sortk:
        if name != 'main': continue
        value = plotoptions[name]
        #print grs
        gr = grs[name]
        #print gr
        gr.SetName(title)
        #extrate = fitGraph(gr,evVal)
        #ratesFromFit[name] = extrate
        if doext:
            #print name, extrate[0], extrate[1]
            NN = gr.GetN()
            gr.Set(NN + 1)
            gr.SetPoint(NN + 1, 50000.0, extrate["rate"][0])
            yErr = extrate["rate"][1]
            if not ploterror:
                yErr = 0.0
            gr.SetPointError(NN + 1, 0.0, yErr)
        gr.SetMarkerColor(value['color'])
        gr.SetMarkerStyle(value['markst'])
        gr.SetLineColor(value['color'])
        gr.SetMarkerSize(1.15)  #1.05
        gr.SetMinimum(0.1)
        #gr.Write()
        mg.Add(gr)
        text = title  #name #+plotoptions[name]['leg']
        leg.AddEntry(gr, text, "p")
        continue

    mg.SetName(outn)
    mg.SetMinimum(0.1)
    mg.SetMaximum(ymax)  #1.6*ymax
    mg.Draw("AP")
    mg.GetXaxis().SetRangeUser(2000, 20000)
    c.Update()
    graphAxis(mg)

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)
    c.cd()
    c.Update()
    frame = c.GetFrame()
    frame.Draw()

    leg.Draw()
    c.SaveAs(outn + ".png")
    #c.SaveAs(outn+".C")
    del c

    return ratesFromFit
Example #6
0
    def getGraph(self,dset):
        from array import array
        from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors
        n = len(self.__x)
        if n != len(self.__y) or n != len(self.__yErrLow) or n != len(self.__yErrHigh):
            raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match"%(len(self.__x), len(self.__y), len(self.__yErrLow), len(self.__yErrHigh))

        result = TMultiGraph()
        legendPosition = [float(i) for i in self.__getStyleOption("legendPosition").split()]
        legend = TLegend(*legendPosition)
        legend.SetFillColor(0)
        result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        #(refArrays, refLabel) = self.__getRefernceGraphArrays()
        #refGraph = TGraphAsymmErrors(*refArrays)

        #refGraph.SetLineWidth(2)
        #refGraph.SetLineColor(int(self.__config.get("reference","lineColor")))
        #refGraph.SetFillColor(int(self.__config.get("reference","fillColor")))
        #result.Add(refGraph,"L3")
        #legend.AddEntry(refGraph,self.__config.get("reference","name"))

        xErr = array("d",[0 for i in range(n)])
        print "__x = ", self.__x
        print "__y = ", self.__y
        lst = []

        for inc in range (0,n):
            d={}
            d['run']=self.__runs[inc]
            d['x']=self.__x[inc]
            d['y']=self.__y[inc]
            d['yErr']=self.__yErrLow[inc]
            d['yTitle']=self.__yTitle
            if self.__config.has_option(self.__section,"yMin") and self.__config.has_option(self.__section,"yMax") :
                d['ymin']=float(self.__config.get(self.__section,"yMin"))
                d['ymax']=float(self.__config.get(self.__section,"yMax"))
            else:
                d['ymin']=0
                d['ymax']=0
            lst.append(d)


        obj ={}
        obj[self.__title]=lst
 #finalObj[self.__title]=lst                                                                                                                           
        #finalList.append(finalObj)                                                                                                                   

       # save_path = './JSON_A/'
        #completeName = os.path.join(save_path, self.__title+".json")
        if not os.path.exists("JSON_RECO"):
            os.makedirs("JSON_RECO")
        if not os.path.exists("JSON_RECO/"+dset):
            os.makedirs("JSON_RECO/"+dset)
        with open("./JSON_RECO/"+dset+"/"+self.__title+".json", 'w') as outfile:
            json.dump(obj, outfile,indent=4)
        print  json.dumps(obj,indent=2)

        graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__yErrLow,self.__yErrHigh)
        graph.SetLineWidth(2)
        graph.SetFillColor(0)
        graph.SetLineColor(int(self.__getStyleOption("lineColor")))
        graph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        graph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__ySysErrLow,self.__ySysErrHigh)
        sysGraph.SetLineWidth(1)
        sysGraph.SetFillColor(0)
        sysGraph.SetLineColor(int(self.__getStyleOption("lineColor")))
        sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize")))
        #TOMAS removed sys error from the plot
        #result.Add(sysGraph,"[]")
        result.Add(graph,"P")
#        result.SetName("MultiPlots")
#         result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        result.SetName("MG_%s"%(self.__title))
        legend.AddEntry(graph, self.__getStyleOption("name"))
        
        #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)):
        #    self.__addAnnotaion("hallo",x,y,yErr)

        return (result, legend)
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()
Example #8
0
def isobar_analysis_0pp():
	"""Does the 2D isobar analysis, based on 'print2DtoRoot', with all cuts, argands and what not"""
	root_name='isobar_analysis.root'
	outROOT=root_open('./ROOT/'+root_name,mode="RECREATE")
	isobar = 'f0_'
	jpcs = ['0-+','1++','2-+']
#	jpcs = ['0-+']
	M='0'
	iso_slices = { # do not use bin borders in definitions, a bin will be used, if any part of the defined interval overlaps with the bin #hence the *.**1 and *.**9 at the end of each definition
		'0-+':[[1.661,1.699,'below_resonance'],[1.781,1.819,'on_resonance'],[1.901,1.939,'above_resonance']],
		'1++':[[1.261,1.299,'below_resonance'],[1.381,1.419,'on_resonance'],[1.501,1.539,'above_resonance']],
		'2-+':[[1.781,1.819,'below_resonance'],[1.901,1.939,'on_resonance'],[2.021,2.059,'above_resonance']]
	}
	all_slices = True # Set True, if all 3pi slices shall be written out
	if all_slices:
		for i in range(50):
			mmin = 0.5 +i*0.04 + 0.001
			mmax = 0.5 + (i+1)*0.04 - 0.001
			name = "slice_"+str(i)
			iso_slices["0-+"].append([mmin,mmax,name])
			iso_slices["1++"].append([mmin,mmax,name])
			iso_slices["2-+"].append([mmin,mmax,name])
	prefixes = {'0-+':'1-(0-+)0+ f0_','1++':'1-(1++)0+ f0_','2-+':'1-(2-+)0+ f0_'}
        suffixes = {'0-+':' pi S','1++':' pi P','2-+':' pi D'}
	X_slices = [[0.961,0.999,'f_0(980)'],[1.401,1.559,'f_0(1500)'],[0.2781,2.279,'Incoherent_sum']]
	suppressSigma=0
	tbins=['0.10000-0.14077','0.14077-0.19435','0.19435-0.32617','0.32617-1.00000']
	sumintens={}
	for tbin in tbins:
		dataSet = get2D('/nfs/mds/user/fkrinner/massIndepententFits/fits/4tbin_deisobarred/fit/'+tbin, '/nfs/mds/user/fkrinner/massIndepententFits/fits/4tbin_deisobarred/integrals/'+tbin ,normalizeToIntegrals = False, divide_key_intens = True)
		for jpc in jpcs:
			addString = '_'+isobar
			bins2Pi=[]
			bins3Pi=[]
			for i in range(0,len(dataSet[0])):
				if dataSet[0][i][4]==jpc and dataSet[0][i][13] == M and isobar in dataSet[0][i][14]:
					bins3Pi.append(dataSet[0][i][0])
					bins3Pi.append(dataSet[0][i][1])
					bins2Pi.append(dataSet[0][i][2])
					bins2Pi.append(dataSet[0][i][3])
			bins3Pi.sort()
			bins2Pi.sort()
			if not len(bins3Pi) + len(bins2Pi) == 0:
				binning2Pi=[bins2Pi[0]]
				binning3Pi=[bins3Pi[0]]
				for i in range(1,len(bins3Pi)-1):
					if binning3Pi[-1] != bins3Pi[i]:
						binning3Pi.append(bins3Pi[i])
						if bins3Pi[i] != bins3Pi[i+1]:
							print "Warning: Binning in m(3Pi) is wrong."
				binning3Pi.append(bins3Pi[-1])
				for i in range(1,len(bins2Pi)-1):
					if binning2Pi[-1] != bins2Pi[i]:
						binning2Pi.append(bins2Pi[i])
						if bins2Pi[i] != bins2Pi[i+1]:
							print "Warning: Binning in m(2Pi) is wrong."
				binning2Pi.append(bins2Pi[-1])
				binning2Pi= numpy.asarray(binning2Pi,dtype=numpy.float64)
				binning3Pi= numpy.asarray(binning3Pi,dtype=numpy.float64)
				histIn  = TH2D("Intensity of "+jpc+'_'+M+addString+"_"+tbin,"Intensity of "+jpc+addString,len(binning3Pi)-1,binning3Pi,len(binning2Pi)-1,binning2Pi)
				histIn.SetDrawOption('col')
				histIn.GetXaxis().SetTitle("Mass of the #pi^{#font[122]{-}}#pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
				histIn.GetYaxis().SetTitle("Mass of the #pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
				histIn.GetZaxis().SetTitle("Intensity of "+jpc+addString)
				histRe  = TH2D("Real part of "+jpc+'_'+M+addString+"_"+tbin,"Real part of "+jpc+addString,len(binning3Pi)-1,binning3Pi,len(binning2Pi)-1,binning2Pi)
				histRe.SetDrawOption('col')
				histRe.GetXaxis().SetTitle("Mass of the #pi^{#font[122]{-}}#pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
				histRe.GetYaxis().SetTitle("Mass of the #pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
				histRe.GetZaxis().SetTitle("Real part of "+jpc+addString)
				histIm  = TH2D("Imag part of "+jpc+'_'+M+addString+"_"+tbin,"Imag part of "+jpc+addString,len(binning3Pi)-1,binning3Pi,len(binning2Pi)-1,binning2Pi)
				histIm.SetDrawOption('col')
				histIm.GetXaxis().SetTitle("Mass of the #pi^{#font[122]{-}}#pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
				histIm.GetYaxis().SetTitle("Mass of the #pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
				histIm.GetZaxis().SetTitle("Imag part of "+jpc+addString)
				histPh  = TH2D("Phase of "+jpc+'_'+M+addString+"_"+tbin,"Phase of "+jpc+addString,len(binning3Pi)-1,binning3Pi,len(binning2Pi)-1,binning2Pi)
				histPh.SetDrawOption('col')
				histPh.GetXaxis().SetTitle("Mass of the #pi^{#font[122]{-}}#pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
				histPh.GetYaxis().SetTitle("Mass of the #pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
				histPh.GetZaxis().SetTitle("Phase of "+'_'+M+jpc+addString)
				for i in range(0,len(dataSet[0])):
					if dataSet[0][i][4] == jpc and dataSet[0][i][13] == M and isobar in dataSet[0][i][14]:
						m2Center = (dataSet[0][i][3] + dataSet[0][i][2])/2
						m3Center = (dataSet[0][i][0] + dataSet[0][i][1])/2
						n2 = histIn.GetYaxis().FindBin(m2Center)
						n3 = histIn.GetXaxis().FindBin(m3Center)	
						histIn.SetBinContent(n3,n2,dataSet[0][i][5])
						histRe.SetBinContent(n3,n2,dataSet[0][i][7])
						histIm.SetBinContent(n3,n2,dataSet[0][i][9])
						histPh.SetBinContent(n3,n2,dataSet[0][i][11])
						histIn.SetBinError(n3,n2,dataSet[0][i][6])
						histRe.SetBinError(n3,n2,dataSet[0][i][8])
						histIm.SetBinError(n3,n2,dataSet[0][i][10])
						histPh.SetBinError(n3,n2,dataSet[0][i][12])
						if histIn.GetBinContent(n3,n2) < suppressSigma * histIn.GetBinError(n3,n2):
							histIn.SetBinContent(n3,n2,0.)
							histIn.SetBinError(n3,n2,0.)
				histPh=removePhaseAmbiguities(histPh)
				histIn.Write()
				histRe.Write()
				histIm.Write()
				histPh.Write()
				histIn.Draw("col")
#				canv.Print('./pdfs/'+histIn.GetName()+".pdf")
				for slic in iso_slices[jpc]:
					minm = slic[0]
					maxm = slic[1]
					name = slic[2]
					for i in range(len(binning3Pi)-1):
						bul = binning3Pi[i+1]
						bll = binning3Pi[i]
						if bul > maxm and bll < maxm:
							maxb = i+1
						if bul > minm and bll < minm:
							minb = i+1
					massstring = 'm3Pi='+str(binning3Pi[minb-1])+'-'+str(binning3Pi[maxb])
					slcInt=histIn.ProjectionY('slice_of_'+jpc+'_intens_'+name+"_"+tbin   ,minb,maxb)
					slcRe =histRe.ProjectionY('slice_of_'+jpc+'_real_part_'+name+"_"+tbin,minb,maxb)
					slcIm =histIm.ProjectionY('slice_of_'+jpc+'_imag_part_'+name+"_"+tbin,minb,maxb)
					slcPha=histPh.ProjectionY('slice_of_'+jpc+'_phase_'+name+"_"+tbin    ,minb,maxb)
					adjust_phase_range(slcPha)
					slcInt.Draw()
#					canv.Print('./pdfs/'+slcInt.GetName()+".pdf")
					re = []
					im = []
					ree= []
					ime= []
					for i in range(1,slcRe.GetNbinsX()+1):
						e = slcRe.GetBinError(i)+ slcIm.GetBinError(i)
						if not e==0.:
							re.append(slcRe.GetBinContent(i))
							im.append(slcIm.GetBinContent(i))
							ree.append(slcRe.GetBinError(i))
							ime.append(slcIm.GetBinError(i))			
					if len(re)>0 and len(re) == len(im) and len(re) == len(ree) and len(re) == len(ime):
						while re[-1] ==0. and im[-1]==0.: # Kill the last (zero) point
							re = re[:-1]
							im = im[:-1]
							ree=ree[:-1]
							ime=ime[:-1]
						re= numpy.asarray(re,dtype=numpy.float64)
						im= numpy.asarray(im,dtype=numpy.float64)
						ree= numpy.asarray(ree,dtype=numpy.float64)
						ime= numpy.asarray(ime,dtype=numpy.float64)
						argand = TGraphErrors(len(re),re,im,ree,ime)
						argand.SetName('slice_of_'+jpc+'_argand_'+name+"_"+tbin)
#						argand.Write()
						argand.Draw('apl')
#						canv.Print('./pdfs/'+argand.GetName()+".pdf")
						argand_wrapper = TMultiGraph()
						argand_wrapper.SetName(argand.GetName())
						argand_wrapper.Add(argand)
						argand_wrapper.Write()
					slcInt.SetTitle(massstring)
					slcRe.SetTitle(massstring)
					slcIm.SetTitle(massstring)
					slcPha.SetTitle(massstring)
					slcInt.Write()
					slcRe.Write()
					slcIm.Write()
					slcPha.Write()
				for slic in X_slices:
					minm = slic[0]
					maxm = slic[1]
					name = slic[2]
					total_list = make_f0_wavelist(minm,maxm,prefixes[jpc],suffixes[jpc])
#					if name == 'f_0(1500)':
#						print total_list
#						raise Exception
					total_data = getTotal('/nfs/mds/user/fkrinner/massIndepententFits/fits/4tbin_deisobarred/fit/'+tbin,total_list, '/nfs/mds/user/fkrinner/massIndepententFits/fits/4tbin_deisobarred/integrals/'+tbin,normalizeToDiag=True)
					total_binning = [total_data[0][0]]
					for total_point in total_data:
						total_binning.append(total_point[1])
					total_binning= numpy.asarray(total_binning,dtype=numpy.float64)
					total_mmin = total_binning[0]
					total_mmax = total_binning[-1]
					total_hist = TH1D('coherent_sum_of_'+jpc+'_'+name+'_'+tbin,'coherent_sum_of_'+jpc+'_'+name+'_'+tbin,len(total_binning)-1,total_binning)
					total_hist.GetXaxis().SetTitle("Mass of the #pi^{#font[122]{-}}#pi^{#font[122]{+}}#pi^{#font[122]{-}} System (GeV/#it{c}^{2})")
					histIn.GetZaxis().SetTitle("Intensity of "+jpc+addString)
					for i in range(len(total_data)):
						total_hist.SetBinContent(i+1,total_data[i][2])
						total_hist.SetBinError(i+1,total_data[i][3])
					for i in range(len(binning2Pi)-1):
						bul = binning2Pi[i+1]
						bll = binning2Pi[i]
						if bul > maxm and bll < maxm:
							maxb = i+1
						if bul > minm and bll < minm:
							minb = i+1
					massstring = 'm2Pi='+str(binning2Pi[minb-1])+'-'+str(binning2Pi[maxb])
					slcInt=histIn.ProjectionX('slice_of_'+jpc+'_intens_'+name+"_"+tbin   ,minb,maxb)
					slcRe =histRe.ProjectionX('slice_of_'+jpc+'_real_part_'+name+"_"+tbin,minb,maxb)
					slcIm =histIm.ProjectionX('slice_of_'+jpc+'_imag_part_'+name+"_"+tbin,minb,maxb)
					slcPha=histPh.ProjectionX('slice_of_'+jpc+'_phase_'+name+"_"+tbin    ,minb,maxb)
					slcInt.SetTitle(massstring)
					slcRe.SetTitle(massstring)
					slcIm.SetTitle(massstring)
					slcPha.SetTitle(massstring)
					total_hist.SetTitle(massstring)
					slcInt.Write()
					slcRe.Write()
					slcIm.Write()
					slcPha.Write()
					total_hist.Write()
					slcInt.Draw()
#					canv.Print('./pdfs/'+slcInt.GetName()+".pdf")
					if not sumintens.has_key(name+"_"+jpc):
						sumintens[name+"_"+jpc] = slcInt
						sumintens[name+"_"+jpc].SetName('incoherent_sum_'+jpc+'_'+name)
					else:
						sumintens[name+"_"+jpc].Add(slcInt)
	for key in sumintens.iterkeys():
		sumintens[key].Write()
		sumintens[key].Draw()
#		canv.Print('./pdfs/'+sumintens[key].GetName()+".pdf")
	outROOT.close()
	print "ran with no exceptions"
Example #9
0
dSysts = OrderedDict()
dSysts = {
    "ttbarReweightStat": [dStatU, dStatD],
}

trigs = ["00", "25", "35", "25EF", "35EF", "25RNN", "35RNN"]
prongs = ["1P", "3P"]

mc = [(21, kRed + 1), (22, kBlue + 1), (23, kMagenta + 1)]

for trig in trigs:
    for prong in prongs:
        fileName = f"plots/fakerate/fakerate_data_trig{trig}_{prong}.pdf"
        mg = TMultiGraph()
        mg.SetName("Fake Rates")
        c = TCanvas(f"c_{trig}_{prong}", "", 900, 900)
        c.SetLogx()

        leg = TLegend(0.50, 0.55, 0.90, 0.75)
        leg.SetTextFont(42)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextSize(0.036)
        leg.SetTextAlign(32)

        gNom = dNom.Get(f"fakerate_data_trig{trig}_{prong}").CreateGraph()
        x = gNom.GetX()
        y = gNom.GetY()
        x = array('d', [i / 1000 for i in x])
        exH = array('d', [gNom.GetErrorXhigh(i) / 1000 for i in range(len(x))])
Example #10
0
def energylinearity():
    outputfile = "EMLinearityEnergyRes"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    MeanEnergyScin = array('d')
    MeanEnergyCher = array('d')
    MeanEnergy = array('d')
    resolutionscin = array('d')
    resolutioncher = array('d')
    resolution = array('d')
    towers = array('d')
    ##inputfiles = sorted(glob.glob(datapath+"*"), key=os.path.getmtime) #get files from tower 1 to 75 ordered by creation time
    inputfiles = [
        "/home/software/Calo/results/newresults/barrel2/Barrel_" + str(i) +
        ".root" for i in range(1, 76)
    ]
    #inputfiles = ["/home/software/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)]
    #inputfiles = ["/home/lorenzo/Desktop/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)]

    for counter, inputfile in enumerate(inputfiles):
        inputfile = TFile(inputfile)
        print "Analyzing: " + str(inputfile) + " \n"
        tree = TTree()
        inputfile.GetObject("B4", tree)

        ScinEnergyHist = TH1F("scinenergy_",
                              str(counter + 1) + "_scin", 200, 0., 100.)
        CherEnergyHist = TH1F("cherenergy_",
                              str(counter + 1) + "_cher", 200, 0., 100.)
        RecEnergyHist = TH1F("RecEnergy_",
                             str(counter + 1) + "_Energy", 200, 0., 100.)
        Energytot = 0.0

        energy = 40.0
        sqrtenergy = 1 / (40.0**0.5)
        towers.append(counter + 1.)

        #loop over events
        for Event in range(int(tree.GetEntries())):

            tree.GetEntry(Event)

            #Set values of the tree
            PrimaryParticleName = tree.PrimaryParticleName  # MC truth: primary particle Geant4 name
            PrimaryParticleEnergy = tree.PrimaryParticleEnergy
            EnergyTot = tree.EnergyTot  # Total energy deposited in calorimeter
            Energyem = tree.Energyem  # Energy deposited by the em component
            EnergyScin = tree.EnergyScin  # Energy deposited in Scin fibers (not Birk corrected)
            EnergyCher = tree.EnergyCher  # Energy deposited in Cher fibers (not Birk corrected)
            NofCherenkovDetected = tree.NofCherenkovDetected  # Total Cher p.e. detected
            BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelR_VectorSignalsCher = tree.VectorSignalsCherR  # Vector of Cher p.e. detected in Cher fibers
            BarrelL_VectorSignalsCher = tree.VectorSignalsCherL
            VectorR = tree.VectorR
            VectorL = tree.VectorL

            #apply calibrations
            Calib_BarrelL_VectorSignals = calibration2.calibscin(
                BarrelL_VectorSignals)
            Calib_BarrelR_VectorSignals = calibration2.calibscin(
                BarrelR_VectorSignals)
            Calib_BarrelL_VectorSignalsCher = calibration2.calibcher(
                BarrelL_VectorSignalsCher)
            Calib_BarrelR_VectorSignalsCher = calibration2.calibcher(
                BarrelR_VectorSignalsCher)
            #end of calibrations

            energyscin = sum(Calib_BarrelR_VectorSignals) + sum(
                Calib_BarrelL_VectorSignals)
            energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum(
                Calib_BarrelL_VectorSignalsCher)

            ScinEnergyHist.Fill(energyscin)
            CherEnergyHist.Fill(energycher)

            #sigmascin = 0.15*(energyscin**0.5)+0.012*energyscin #old value
            #sigmacher = 0.18*(energycher**0.5)+0.0045*energycher #old value
            sigmascin = 0.177 * (energyscin**0.5) + 0.006 * energyscin
            sigmacher = 0.194 * (energycher**0.5) + 0.001 * energycher

            RecEnergyHist.Fill(
                (energyscin / (sigmascin**2) + energycher /
                 (sigmacher**2)) / (1 / sigmascin**2 + 1 / sigmacher**2))

            #RecEnergyHist.Fill((energyscin+energycher)/2)

            Energytot += (sum(VectorL) + sum(VectorR)) / 1000

        Energytot = Energytot / int(tree.GetEntries())
        print Energytot, ScinEnergyHist.GetMean(), CherEnergyHist.GetMean()
        displayfile.cd()
        gStyle.SetOptStat(111)
        ScinEnergyHist.Fit("gaus")
        CherEnergyHist.Fit("gaus")
        RecEnergyHist.Fit("gaus")
        RecEnergyHist.Write()
        ScinEnergyHist.Write()
        CherEnergyHist.Write()
        #MeanEnergyScin.append(ScinEnergyHist.GetFunction("gaus").GetParameter(1)/Energytot)
        MeanEnergyScin.append(ScinEnergyHist.GetMean() / energy)
        #MeanEnergyCher.append(CherEnergyHist.GetFunction("gaus").GetParameter(1)/Energytot)
        MeanEnergyCher.append(CherEnergyHist.GetMean() / energy)
        MeanEnergy.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(1) / energy)
        resolution.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(2) /
            RecEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutionscin.append(
            ScinEnergyHist.GetFunction("gaus").GetParameter(2) /
            ScinEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutioncher.append(
            CherEnergyHist.GetFunction("gaus").GetParameter(2) /
            CherEnergyHist.GetFunction("gaus").GetParameter(1))

    print MeanEnergyScin, MeanEnergyCher
    LinearityGraph = TGraph(len(towers), towers, MeanEnergy)
    LinearityGraph.SetName("LinearityGraph")
    LinearityGraph.Write()
    LinearityGraphScin = TGraph(len(towers), towers, MeanEnergyScin)
    LinearityGraphCher = TGraph(len(towers), towers, MeanEnergyCher)
    LinearityGraphCher.SetName("LinearityGraphCher")
    LinearityGraphCher.Write()
    LinearityGraphScin.SetName("LinearityGraphScin")
    LinearityGraphScin.Write()
    ResolutionGraphScin = TGraph(len(towers), towers, resolutionscin)
    ResolutionGraphCher = TGraph(len(towers), towers, resolutioncher)
    ResolutionGraphScin.SetName("ResolutionGraphScin")
    ResolutionGraphScin.Write()
    ResolutionGraphCher.SetName("ResolutionGraphCher")
    ResolutionGraphCher.Write()
    ResolutionGraph = TGraph(len(towers), towers, resolution)
    ResolutionGraph.SetName("ResolutionGraph")
    ResolutionGraph.Write()
    x2 = array('d', (0., 90., 90., 0.))
    y2 = array('d', (0.024, 0.024, 0.034, 0.034))
    Fillgraph2 = TGraph(4, x2, y2)
    Fillgraph2.SetName("ban")
    Fillgraph2.Write()
    linefill1 = TF1("1", str(1.0), 0., 90.)
    linefill1.Write()

    EMResolutions = TMultiGraph()
    EMResolutions.Add(ResolutionGraphScin)
    EMResolutions.Add(ResolutionGraphCher)
    EMResolutions.Add(ResolutionGraph)
    EMResolutions.SetName("EMResolutions")
    EMResolutions.Write()

    Linearities = TMultiGraph()
    Linearities.Add(LinearityGraph)
    Linearities.Add(LinearityGraphScin)
    Linearities.Add(LinearityGraphCher)
    Linearities.SetName("Linearities")
    Linearities.Write()
Example #11
0
def RunRPFCode(fCTask, fOutputDir, fOutputFile):

    #  logging.basicConfig(level="DEBUG")

    fNumTriggers = fCTask.GetNumTriggers()
    print("Found the number of triggers = %f" % (fNumTriggers))
    fObservable = fCTask.GetObservable()
    nObsBins = fCTask.GetNObsBins()

    fFlowTermMode = fCTask.GetFlowTermModeAssoc()
    nFixV40Last = fCTask.GetFixV4Threshold()

    iV1Mode = fCTask.GetFlowV1Mode()
    iV5Mode = fCTask.GetFlowV5Mode()
    iV6TMode = fCTask.GetFlowV6TMode()
    iV6AMode = fCTask.GetFlowV6AMode()

    fObsBins = [0, 1. / 6, 2. / 6, 3. / 6, 4. / 6, 5. / 6, 1.]
    # FIXME do the new zt bins
    if fObservable == 0:
        print("Error: trigger pt is the observable, haven't coded bins in yet")
    if fObservable == 1:
        print("Using z_T as the observable")
    if fObservable == 2:
        fObsBins = [0.2, 0.4, 0.8, 1.5, 2.5, 4, 7, 11, 17]
        #fObsBins=[0.15,0.4,0.8,1.45,2.5,4.2,6.95,11.4,18.6]
        print("Using associated pt as the observable")
        # assoc pt

    print("This analysis is in observable %d, with %d bins" %
          (fObservable, nObsBins))
    iCentBin = fCTask.GetCentBin()
    print(" Centrality Bin %d" % (iCentBin))

    iEPRSet = fCTask.GetEPRSet()

    fUseEPRSet = fEPRes_Set_0
    if iEPRSet == 3:
        fUseEPRSet = fEPRes_Set_3

    res_par = {
        "R22": fUseEPRSet[iCentBin][1],
        "R42": fUseEPRSet[iCentBin][3],
        "R62": fUseEPRSet[iCentBin][5],
        "R82": 0.0
    }
    # res_par = {"R22": fEPRes_Set_0[iCentBin][1], "R42" : fEPRes_Set_0[iCentBin][3], "R62": fEPRes_Set_0[iCentBin][5], "R82": 0.0}

    print("Resolution parameters:")
    print(res_par)

    #  enableInclusiveFit=False
    #  enableRPDepFit=False
    #  enableReduxFit=False
    #  useMinos=False

    nRebin = 1
    MCRescale = -1
    if (fCTask.GetMCGenMode()):
        MCRescale = fCTask.GetMCRescaleFactor()
        #    MCRescale=MCRescaleValue
        nRebin = 2 * nRebin

    # Initializing some TGraphs
#  Py_B_TGraph: TGraphErrors
# Graphs for basic RPF
    Py_ChiSq_TGraph = TGraphErrors(nObsBins)
    Py_ChiSq_TGraph.SetName("Py_ChiSq_TGraph")

    Py_B_TGraph = TGraphErrors(nObsBins)
    Py_B_TGraph.SetName("Py_B_TGraph")
    Py_V1_TGraph = TGraphErrors(nObsBins)
    Py_V1_TGraph.SetName("Py_V1_TGraph")
    Py_V2T_TGraph = TGraphErrors(nObsBins)
    Py_V2T_TGraph.SetName("Py_V2T_TGraph")
    Py_V2A_TGraph = TGraphErrors(nObsBins)
    Py_V2A_TGraph.SetName("Py_V2A_TGraph")
    Py_V3_TGraph = TGraphErrors(nObsBins)
    Py_V3_TGraph.SetName("Py_V3_TGraph")
    Py_V4T_TGraph = TGraphErrors(nObsBins)
    Py_V4T_TGraph.SetName("Py_V4T_TGraph")
    Py_V4A_TGraph = TGraphErrors(nObsBins)
    Py_V4A_TGraph.SetName("Py_V4A_TGraph")

    #Py_TGraphs= [Py_B_TGraph, Py_V2T_TGraph, Py_V2A_TGraph, Py_V3_TGraph, Py_V4T_TGraph, Py_V4A_TGraph]
    Py_TGraphs = [
        Py_B_TGraph, Py_V1_TGraph, Py_V2T_TGraph, Py_V2A_TGraph, Py_V3_TGraph,
        Py_V4T_TGraph, Py_V4A_TGraph
    ]

    # Graphs for RPDep Fit
    Py_RPDep_ChiSq_TGraph = TGraphErrors(nObsBins)
    Py_RPDep_ChiSq_TGraph.SetName("Py_RPDep_ChiSq_TGraph")
    Py_RPDep_B_TGraph = TGraphErrors(nObsBins)
    Py_RPDep_B_TGraph.SetName("Py_RPDep_B_TGraph")
    Py_RPDep_V1_TGraph = TGraphErrors(nObsBins)
    Py_RPDep_V1_TGraph.SetName("Py_RPDep_V1_TGraph")
    Py_RPDep_V2T_TGraph = TGraphErrors(nObsBins)
    Py_RPDep_V2T_TGraph.SetName("Py_RPDep_V2T_TGraph")
    Py_RPDep_V2A_TGraph = TGraphErrors(nObsBins)
    Py_RPDep_V2A_TGraph.SetName("Py_RPDep_V2A_TGraph")
    Py_RPDep_V3_TGraph = TGraphErrors(nObsBins)
    Py_RPDep_V3_TGraph.SetName("Py_RPDep_V3_TGraph")
    Py_RPDep_V4T_TGraph = TGraphErrors(nObsBins)
    Py_RPDep_V4T_TGraph.SetName("Py_RPDep_V4T_TGraph")
    Py_RPDep_V4A_TGraph = TGraphErrors(nObsBins)
    Py_RPDep_V4A_TGraph.SetName("Py_RPDep_V4A_TGraph")
    # Reaction Plane Dependent Signal fit unique parameters
    # Yields
    Py_RPDep_IP_YieldNS = TGraphErrors(nObsBins)
    Py_RPDep_IP_YieldNS.SetName("Py_RPDep_IP_YieldNS")
    Py_RPDep_MP_YieldNS = TGraphErrors(nObsBins)
    Py_RPDep_MP_YieldNS.SetName("Py_RPDep_MP_YieldNS")
    Py_RPDep_OP_YieldNS = TGraphErrors(nObsBins)
    Py_RPDep_OP_YieldNS.SetName("Py_RPDep_OP_YieldNS")

    Py_RPDep_IP_YieldAS = TGraphErrors(nObsBins)
    Py_RPDep_IP_YieldAS.SetName("Py_RPDep_IP_YieldAS")
    Py_RPDep_MP_YieldAS = TGraphErrors(nObsBins)
    Py_RPDep_MP_YieldAS.SetName("Py_RPDep_MP_YieldAS")
    Py_RPDep_OP_YieldAS = TGraphErrors(nObsBins)
    Py_RPDep_OP_YieldAS.SetName("Py_RPDep_OP_YieldAS")

    # Sigmas
    Py_RPDep_IP_SigmaNS = TGraphErrors(nObsBins)
    Py_RPDep_IP_SigmaNS.SetName("Py_RPDep_IP_SigmaNS")
    Py_RPDep_MP_SigmaNS = TGraphErrors(nObsBins)
    Py_RPDep_MP_SigmaNS.SetName("Py_RPDep_MP_SigmaNS")
    Py_RPDep_OP_SigmaNS = TGraphErrors(nObsBins)
    Py_RPDep_OP_SigmaNS.SetName("Py_RPDep_OP_SigmaNS")

    Py_RPDep_IP_SigmaAS = TGraphErrors(nObsBins)
    Py_RPDep_IP_SigmaAS.SetName("Py_RPDep_IP_SigmaAS")
    Py_RPDep_MP_SigmaAS = TGraphErrors(nObsBins)
    Py_RPDep_MP_SigmaAS.SetName("Py_RPDep_MP_SigmaAS")
    Py_RPDep_OP_SigmaAS = TGraphErrors(nObsBins)
    Py_RPDep_OP_SigmaAS.SetName("Py_RPDep_OP_SigmaAS")

    Py_RPDep_TGraphs = [
        Py_RPDep_B_TGraph, Py_RPDep_V1_TGraph, Py_RPDep_V2T_TGraph,
        Py_RPDep_V2A_TGraph, Py_RPDep_V3_TGraph, Py_RPDep_V4T_TGraph,
        Py_RPDep_V4A_TGraph
    ]

    # Load the Vn TGraphs for triggers and tracks
    FlowV2TGraph = fCTask.GetTriggerV2()
    FlowV2AGraph = fCTask.GetTrackV2()

    FlowV4TGraph = fCTask.GetTriggerV4()
    FlowV4AGraph = fCTask.GetTrackV4()

    for iObsBin in range(nObsBins):
        print("Doing the thing for %s bin %d" %
              (fCTask.GetObservableName(), iObsBin))
        ObsBinCenter = 0.5 * (fObsBins[iObsBin] + fObsBins[iObsBin + 1])
        ObsBinWidth = 0.5 * (fObsBins[iObsBin + 1] - fObsBins[iObsBin])

        UseLogLikelihood = False
        if (iObsBin > nSkipLast):
            continue
        #  UseLogLikelihood=True

        #  Clone these all first so they are not alterred in the original program

        SigInPlaneHistOrig = fCTask.GetNearEtaDPhiProjEP(iObsBin, 0)
        SigMidPlaneHistOrig = fCTask.GetNearEtaDPhiProjEP(iObsBin, 1)
        SigOutPlaneHistOrig = fCTask.GetNearEtaDPhiProjEP(iObsBin, 2)
        SigInclusiveHistOrig = fCTask.GetNearEtaDPhiProjAll(iObsBin)

        BkgInPlaneHistOrig = fCTask.GetFarEtaDPhiProjEP(iObsBin, 0)
        BkgMidPlaneHistOrig = fCTask.GetFarEtaDPhiProjEP(iObsBin, 1)
        BkgOutPlaneHistOrig = fCTask.GetFarEtaDPhiProjEP(iObsBin, 2)
        BkgInclusiveHistOrig = fCTask.GetFarEtaDPhiProjAll(iObsBin)

        SigInPlaneHist = SigInPlaneHistOrig.Clone(
            "%s_Clone" % (SigInPlaneHistOrig.GetName()))
        SigMidPlaneHist = SigMidPlaneHistOrig.Clone(
            "%s_Clone" % (SigMidPlaneHistOrig.GetName()))
        SigOutPlaneHist = SigOutPlaneHistOrig.Clone(
            "%s_Clone" % (SigOutPlaneHistOrig.GetName()))
        SigInclusiveHist = SigInclusiveHistOrig.Clone(
            "%s_Clone" % (SigInclusiveHistOrig.GetName()))
        BkgInPlaneHist = BkgInPlaneHistOrig.Clone(
            "%s_Clone" % (BkgInPlaneHistOrig.GetName()))
        BkgMidPlaneHist = BkgMidPlaneHistOrig.Clone(
            "%s_Clone" % (BkgMidPlaneHistOrig.GetName()))
        BkgOutPlaneHist = BkgOutPlaneHistOrig.Clone(
            "%s_Clone" % (BkgOutPlaneHistOrig.GetName()))
        BkgInclusiveHist = BkgInclusiveHistOrig.Clone(
            "%s_Clone" % (BkgInclusiveHistOrig.GetName()))

        ListOfHists = [
            SigInPlaneHist, SigMidPlaneHist, SigOutPlaneHist, SigInclusiveHist,
            BkgInPlaneHist, BkgMidPlaneHist, BkgOutPlaneHist, BkgInclusiveHist
        ]

        # Rescaling by Number of Triggers for numerical betterness
        SigInPlaneHist.Scale(fNumTriggers)
        SigMidPlaneHist.Scale(fNumTriggers)
        SigOutPlaneHist.Scale(fNumTriggers)
        SigInclusiveHist.Scale(fNumTriggers * 3)
        BkgInPlaneHist.Scale(fNumTriggers)
        BkgMidPlaneHist.Scale(fNumTriggers)
        BkgOutPlaneHist.Scale(fNumTriggers)
        BkgInclusiveHist.Scale(
            fNumTriggers * 3)  # to correct for previous graphical downscale

        # FIXME rescale in case of MC
        # Weighting causes all the histograms to have fractional entries even when not divided by num triggers (which also has fractional weighting)
        # if MC is done without reweighting, this would be unnecessary (and wrong)
        # could define a rescale
        if (MCRescale > 0):
            for hist in ListOfHists:
                hist.Scale(MCRescale)

        if (nRebin > 1):
            for hist in ListOfHists:
                hist.Rebin(nRebin)

        # Fitting just the background
        rp_fit = three_orientations.BackgroundFit(
            resolution_parameters=res_par,
            use_log_likelihood=UseLogLikelihood,
            signal_region=(0, 0.8),
            background_region=(0.8, 1.35),
            use_minos=useMinos)

        # Fitting the background and signal regions. Same yield parameters across RPs?
        rp_fit_IncSig = three_orientations.InclusiveSignalFit(
            resolution_parameters=res_par,
            use_log_likelihood=UseLogLikelihood,
            signal_region=(0, 0.8),
            background_region=(0.8, 1.35),
            use_minos=useMinos)

        rp_fit_RPSig = three_orientations.SignalFit(
            resolution_parameters=res_par,
            use_log_likelihood=UseLogLikelihood,
            signal_region=(0, 0.8),
            background_region=(0.8, 1.35),
            use_minos=useMinos)

        rp_fit_Redux = three_orientations.BackgroundFit(
            resolution_parameters=res_par,
            use_log_likelihood=UseLogLikelihood,
            signal_region=(0, 0.8),
            background_region=(0.8, 1.35),
            use_minos=useMinos)

        dataBkg = {
            "background": {
                "in_plane": BkgInPlaneHist,
                "mid_plane": BkgMidPlaneHist,
                "out_of_plane": BkgOutPlaneHist,
                "inclusive": BkgInclusiveHist
            }
        }
        dataFull = {
            "background": {
                "in_plane": BkgInPlaneHist,
                "mid_plane": BkgMidPlaneHist,
                "out_of_plane": BkgOutPlaneHist,
                "inclusive": BkgInclusiveHist
            },
            "signal": {
                "in_plane": SigInPlaneHist,
                "mid_plane": SigMidPlaneHist,
                "out_of_plane": SigOutPlaneHist,
                "inclusive": SigInclusiveHist
            }
        }

        print("Done loading the histograms?", flush=True)

        print(BkgInPlaneHist)

        print("Fitting the background dominated region only")
        # draw_fit expects data to be in pachyderm histogram1D format

        # Estimate variables?
        # B is approximately 1/pi times the average value of the histogram in [-pi/2,pi/2]
        # FIXME implement this

        maxValue = 0.0
        for hist in ListOfHists:
            localMaxValue = hist.GetBinContent(hist.GetMaximumBin())
            if (localMaxValue > maxValue):
                maxValue = localMaxValue

        # magic number for safety
        maxValue = 1.05 * maxValue
        # the near side has the addition of the

        maxv2t = fCTask.GetGlobalV2TMax()
        maxv2a = fCTask.GetGlobalV2AMax()
        maxv3 = fCTask.GetGlobalV3Max()
        maxv4t = fCTask.GetGlobalV4TMax()
        maxv4a = fCTask.GetGlobalV4AMax()

        MyDefaultArgs = {
            "limit_B": [0., maxValue],
            "limit_v2_t": [0.0, maxv2t],
            "limit_v2_a": [0.0, maxv2a],
            "limit_v3": [0.0, maxv3],
            "limit_v4_t": [0.0, maxv4t],
            "limit_v4_a": [0.0, maxv4a]
        }
        #MyDefaultArgs={"limit_B": [0.,maxValue],"limit_v2_a": [0.0, 0.5] }
        #    MyDefaultArgs={"limit_B": [0.,1e7],"limit_v2_a": [0.0, 0.5],"fix_v3":True,"v3":0.0}

        # Getting the initial values.
        #FlowV2TValue = FlowV2TGraph.GetY()[] # Trigger pt bin
        #FlowV4TValue = FlowV4TGraph.GetY()[] # Trigger pt bin

        #FlowV3Value = # good luck with this one

        #FlowV2AValue = FlowV2AGraph.GetY()[iObsBin]
        #FlowV4AValue = FlowV4AGraph.GetY()[iObsBin]
        # FIXME could use spline interpolation
        # Need
        #fPtAMin = fTrackPtProjectionSE->GetXaxis()->GetBinLowEdge(iObsBin+1);
        #fPtAMax = fTrackPtProjectionSE->GetXaxis()->GetBinUpEdge(iObsBin+1);
        # or write a function for the c++ task that returns the value
        # may also want one for the error

        #    FlowV2AValue = FlowV2AGraph.Eval(pTA_Value)
        #    FlowV4AValue = FlowV4AGraph.Eval(pTA_Value)

        FlowV2AError = 0
        FlowV2AValue = fCTask.GetFlowVNAFromObsBin(2, iObsBin)
        FlowV2AError = fCTask.GetFlowVNAeFromObsBin(2, iObsBin)

        print("Found Flow V2 = %f +- %f" % (FlowV2AValue, FlowV2AError))

        FlowV4AError = 0
        FlowV4AValue = fCTask.GetFlowVNAFromObsBin(4, iObsBin)
        FlowV4AError = fCTask.GetFlowVNAeFromObsBin(4, iObsBin)
        print("Found Flow V4 = %f +- %f" % (FlowV4AValue, FlowV4AError))

        # Now apply fFlowTermMode
        # 0 = no action
        # 1 = Fix V2A, V4A to interpolation of flow grpahs
        # 2 = Limit V2A, V4A to flow graph interpolation +- sigma

        print("   FTM=%d" % fFlowTermMode)
        if (fFlowTermMode == 0):
            # Setting initial values
            MyDefaultArgs['v2_a'] = FlowV2AValue
            MyDefaultArgs['v4_a'] = FlowV4AValue
        if (fFlowTermMode == 1):
            MyDefaultArgs["fix_v2_a"] = True
            MyDefaultArgs['v2_a'] = FlowV2AValue
            MyDefaultArgs["fix_v4_a"] = True
            MyDefaultArgs['v4_a'] = FlowV4AValue
        if (fFlowTermMode == 2):
            MyDefaultArgs['v2_a'] = FlowV2AValue
            MyDefaultArgs['v4_a'] = FlowV4AValue
            MyDefaultArgs['limit_v2_a'] = [
                FlowV2AValue - FlowV2AError, FlowV2AValue + FlowV2AError
            ]
            MyDefaultArgs['limit_v4_a'] = [
                FlowV4AValue - FlowV4AError, FlowV4AValue + FlowV4AError
            ]

        # Update this guess
        MyDefaultArgs['v3'] = 0.01

        # this version would need access to the functors.
        #    if (fCTask.GetInitV2T() > -1):
        #      MyDefaultArgs['v2_t'] = fCTask.GetInitV2T()
        #    if (fCTask.GetInitV2A() > -1):
        #      MyDefaultArgs['v2_a'] = fCTask.GetInitV2A()
        #    if (fCTask.GetInitV3() > -1):
        #      MyDefaultArgs['v3'] = fCTask.GetInitV3()
        #    if (fCTask.GetInitV4T() > -1):
        #      MyDefaultArgs['v4_t'] = fCTask.GetInitV4T()
        #    if (fCTask.GetInitV4A() > -1):
        #      MyDefaultArgs['v4_a'] = fCTask.GetInitV4A()

        # Switch on V1,V5,V6T,V6A terms if requested
        # iV1Mode iV5Mode iV6TMode iV6AMode
        # v5,v6 not implemented here

        if (iV1Mode == 1):
            MyDefaultArgs["fix_v1"] = False
            MyDefaultArgs["v1"] = 0.0

        if (iObsBin >= 4):
            print("doing the fix thing")
            for data in dataFull:
                print("data = %s" % (data))
                # background or signal ...
                for entry in dataFull[data]:
                    print(entry)
                    FixErrorsOnHist(dataFull[data][entry])

        if (iObsBin >= nFixV40Last):
            MyDefaultArgs["fix_v4_t"] = True
            MyDefaultArgs['v4_t'] = 0.0
            if (fFlowTermMode != 1):  # Checking if already fixed to a value
                MyDefaultArgs["fix_v4_a"] = True
                MyDefaultArgs['v4_a'] = 0.0
            # could also fix off the v6,v5

        MyUserArgs = {}
        #MyUserArgs={"v4_t": 0,"fix_v4_t": True,"v4_a": 0,"fix_v4_a": True}
        InclusiveUserArgs = {}
        RPDepUserArgs = {}
        # Get initial parameters from RP Dep Fit
        ReduxUserArgs = {}

        MyUserArgs.update(MyDefaultArgs)
        InclusiveUserArgs.update(MyDefaultArgs)
        RPDepUserArgs.update(MyDefaultArgs)
        ReduxUserArgs.update(MyDefaultArgs)

        print("Fitting ObsBin %d with user args:" % (iObsBin))
        print(MyUserArgs)

        # The Fitting is done here
        #    (success,data_BkgFit,_) = rp_fit.fit(data=dataBkg, user_arguments=MyUserArgs)

        try:
            (success, data_BkgFit, _) = rp_fit.fit(data=dataFull,
                                                   user_arguments=MyUserArgs)
        except FitFailed:
            #    except pachyderm.fit.base.FitFailed:
            print("Caught a Fit failed exception. Continuing")
            continue
        except RuntimeError:
            print("Caught a run-time error. Continuing")
            continue
        print("Finished doing the fit, maybe")

        print("Fit result: {fit_result}".format(fit_result=rp_fit.fit_result))

        BkgFitResults = rp_fit.fit_result

        BkgChiSquare = BkgFitResults.minimum_val
        BkgNDOF = BkgFitResults.nDOF

        Py_ChiSq_TGraph.SetPoint(iObsBin, ObsBinCenter, BkgChiSquare / BkgNDOF)
        Py_ChiSq_TGraph.SetPointError(iObsBin, ObsBinWidth, 0)

        for j in range(len(Py_TGraphs)):
            Py_Val = BkgFitResults.values_at_minimum[PyParamNames[j]]
            Py_Err = BkgFitResults.errors_on_parameters[PyParamNames[j]]
            Py_TGraphs[j].SetPoint(iObsBin, ObsBinCenter, Py_Val)
            Py_TGraphs[j].SetPointError(iObsBin, ObsBinWidth, Py_Err)
            # Storing result for next fit
            InclusiveUserArgs[PyParamNames[j]] = Py_Val
            RPDepUserArgs[PyParamNames[j]] = Py_Val
            # Also Set some reasonable starting values for parameters
            RPDepUserArgs["in_plane_ns_sigma"] = 0.36
            RPDepUserArgs["in_plane_as_sigma"] = 0.42
            RPDepUserArgs["mid_plane_ns_sigma"] = 0.36
            RPDepUserArgs["mid_plane_as_sigma"] = 0.42
            RPDepUserArgs["out_of_plane_ns_sigma"] = 0.36
            RPDepUserArgs["out_of_plane_as_sigma"] = 0.42

#------------------------------------------------------------------------------------------------------------------
#| 0 | in_plane_ns_amplitude        |  0.52E4   |  0.03E4   |            |            |    0    |  1e+07  |       |
#| 1 | in_plane_as_amplitude        |    530    |    310    |            |            |    0    |  1e+07  |       |
#| 2 | in_plane_ns_sigma            |   0.363   |   0.023   |            |            |  0.02   |   0.7   |       |
#| 3 | in_plane_as_sigma            |   0.42    |   0.17    |            |            |  0.02   |   0.7   |       |
#| 4 | in_plane_signal_pedestal     |    0.0    |    1.0    |            |            |         |         |  yes  |
#| 5 | B                            |  1.891E5  |  0.002E5  |            |            |    0    |  1e+07  |       |
#| 6 | v2_t                         | 0.547E-1  | 0.007E-1  |            |            |  0.001  |   0.2   |       |
#| 7 | v2_a                         | 3.000E-2  | 0.008E-2  |            |            |  0.03   |   0.5   |       |
#| 8 | v4_t                         | 0.005E-4  | 0.714E-4  |            |            |    0    |   0.5   |       |
#| 9 | v4_a                         | 0.005E-4  | 2.563E-4  |            |            |    0    |   0.5   |       |
#| 10| v1                           |  0.000E1  |  0.000E1  |            |            |   -1    |    1    |  yes  |
#| 11| v3                           |  2.5E-3   |  0.6E-3   |            |            |   -1    |    1    |       |
#| 12| mid_plane_ns_amplitude       |  0.88E4   |  0.03E4   |            |            |    0    |  1e+07  |       |
#| 13| mid_plane_as_amplitude       |  0.49E4   |  0.03E4   |            |            |    0    |  1e+07  |       |
#| 14| mid_plane_ns_sigma           |   0.467   |   0.022   |            |            |  0.02   |   0.7   |       |
#| 15| mid_plane_as_sigma           |   0.700   |   0.027   |            |            |  0.02   |   0.7   |       |
#| 16| mid_plane_signal_pedestal    |    0.0    |    1.0    |            |            |         |         |  yes  |
#| 17| out_of_plane_ns_amplitude    |  0.76E4   |  0.03E4   |            |            |    0    |  1e+07  |       |
#| 18| out_of_plane_as_amplitude    |  0.361E4  |  0.031E4  |            |            |    0    |  1e+07  |       |
#| 19| out_of_plane_ns_sigma        |   0.436   |   0.019   |            |            |  0.02   |   0.7   |       |
#| 20| out_of_plane_as_sigma        |   0.45    |   0.04    |            |            |  0.02   |   0.7   |       |
#| 21| out_of_plane_signal_pedestal |    0.0    |    1.0    |            |            |         |         |  yes  |
#------------------------------------------------------------------------------------------------------------------

#    Py_B = BkgFitResults.values_at_minimum["B"]
#    Py_B_Err = BkgFitResults.errors_on_parameters["B"]
#    Py_B_TGraph.SetPoint(iObsBin,ObsBinCenter,Py_B)
#    Py_B_TGraph.SetPointError(iObsBin,ObsBinWidth,Py_B_Err)

#    Py_V2T = BkgFitResults.values_at_minimum["v2_t"]
#    Py_V2T_Err = BkgFitResults.errors_on_parameters["v2_t"]
#    Py_V2T_TGraph.SetPoint(iObsBin,ObsBinCenter,Py_V2T)
#    Py_V2T_TGraph.SetPointError(iObsBin,ObsBinWidth,Py_V2T_Err)

        fit_label = "Test"
        filename = "%s/PyRPF_BkgFit_ObsBin%d.pdf" % (fOutputDir, iObsBin)
        plot.draw_fit(rp_fit=rp_fit,
                      data=data_BkgFit,
                      fit_label=fit_label,
                      filename=filename)
        filename = "%s/PyRPF_BkgFit_ObsBin%d.png" % (fOutputDir, iObsBin)
        plot.draw_fit(rp_fit=rp_fit,
                      data=data_BkgFit,
                      fit_label=fit_label,
                      filename=filename)
        #    filename="%s/PyRPF_BkgFit_PlotAll_ObsBin%d.pdf" % (fOutputDir,iObsBin)
        #    plot.draw_fit(rp_fit=rp_fit,data=dataFull,fit_label=fit_label,filename=filename)
        #    plot.fit_draw_func(data=data_BkgFit,fit_label=fit_label,filename=filename)

        if (enableInclusiveFit):
            # Settings for inclusive fit
            InclusiveUserArgs["fix_v2_t"] = True
            InclusiveUserArgs["fix_v2_a"] = True
            # could estimate yields based on integrals and the B parameter found earlier
            print(str(InclusiveUserArgs))
            print("Fitting background dominated and signal regions")
            (success_IncSig, data_IncSig,
             _) = rp_fit_IncSig.fit(data=dataFull,
                                    user_arguments=InclusiveUserArgs)
            #      try:
            #        (success_IncSig,data_IncSig,_) = rp_fit_IncSig.fit(data=dataFull,user_arguments=InclusiveUserArgs)
            #      except pachyderm.fit.base.FitFailed:
            #        print("Da Fit Failed")

            print("Fit result: {fit_result}".format(
                fit_result=rp_fit_IncSig.fit_result))
            filename = "%s/PyRPF_IncFit_ObsBin%d.pdf" % (fOutputDir, iObsBin)
            plot.draw_fit(rp_fit=rp_fit_IncSig,
                          data=data_IncSig,
                          fit_label=fit_label,
                          filename=filename)

        if (enableRPDepFit):
            print(
                "Fitting background dominated and signal regions with RP dependent signal"
            )
            (success_RPSig, data_RPSig,
             _) = rp_fit_RPSig.fit(data=dataFull, user_arguments=RPDepUserArgs)
            filename = "%s/PyRPF_RPDepF_ObsBin%d.pdf" % (fOutputDir, iObsBin)
            plot.draw_fit(rp_fit=rp_fit_RPSig,
                          data=data_RPSig,
                          fit_label=fit_label,
                          filename=filename)

            RPDepBkgFitResults = rp_fit_RPSig.fit_result

            RPDepChiSquare = RPDepBkgFitResults.minimum_val
            RPDepNDOF = RPDepBkgFitResults.nDOF

            Py_RPDep_ChiSq_TGraph.SetPoint(iObsBin, ObsBinCenter,
                                           RPDepChiSquare / RPDepNDOF)
            Py_RPDep_ChiSq_TGraph.SetPointError(iObsBin, ObsBinWidth, 0)

            # Save fit parameters
            if (enableRPDepFit):
                for j in range(len(Py_RPDep_TGraphs)):
                    Py_Val = RPDepBkgFitResults.values_at_minimum[
                        PyParamNames[j]]
                    Py_Err = RPDepBkgFitResults.errors_on_parameters[
                        PyParamNames[j]]
                    Py_RPDep_TGraphs[j].SetPoint(iObsBin, ObsBinCenter, Py_Val)
                    Py_RPDep_TGraphs[j].SetPointError(iObsBin, ObsBinWidth,
                                                      Py_Err)

            if (enableReduxFit):
                for key in rp_fit_RPSig.fit_result.values_at_minimum:
                    if key in BkgFitResults.parameters:
                        print("Loading parameter %s" % (str(key)))
                        ReduxUserArgs[
                            key] = rp_fit_RPSig.fit_result.values_at_minimum[
                                key]
                print(
                    "Fitting Background dominated only with initial parameters from RP Dep Fit (Redux)"
                )
                (success_Redux, data_Redux,
                 _) = rp_fit_Redux.fit(data=dataFull,
                                       user_arguments=ReduxUserArgs)
                filename = "%s/PyRPF_Redux_ObsBin%d.pdf" % (fOutputDir,
                                                            iObsBin)
                plot.draw_fit(rp_fit=rp_fit_Redux,
                              data=data_Redux,
                              fit_label=fit_label,
                              filename=filename)

    # End of obs bin loop

    print("Finished the Observable Bin Loop")

    # Get Vn from C++ Code
    C_B_TGraph = fCTask.GetParamGraph(0)
    C_V1_TGraph = fCTask.GetParamGraph(1)
    C_V2T_TGraph = fCTask.GetParamGraph(2)
    C_V2A_TGraph = fCTask.GetParamGraph(3)
    C_V3_TGraph = fCTask.GetParamGraph(4)
    C_V4T_TGraph = fCTask.GetParamGraph(5)
    C_V4A_TGraph = fCTask.GetParamGraph(6)

    #C_TGraphs=[C_B_TGraph, C_V2T_TGraph, C_V2A_TGraph,  C_V3_TGraph, C_V4T_TGraph, C_V4A_TGraph]
    C_TGraphs = [
        C_B_TGraph, C_V1_TGraph, C_V2T_TGraph, C_V2A_TGraph, C_V3_TGraph,
        C_V4T_TGraph, C_V4A_TGraph
    ]

    for graph in C_TGraphs:
        graph.SetLineColor(CColor)
        graph.SetMarkerColor(CColor)
        graph.SetMarkerStyle(CMarkerStyle)
    for graph in Py_TGraphs:
        for i in range(1 + nObsBins - nSkipLast):
            graph.RemovePoint(nSkipLast + 1)
        graph.SetLineColor(PyColor)
        graph.SetMarkerColor(PyColor)
        graph.SetMarkerStyle(PyMarkerStyle)
#    graph.GetXaxis().SetTitle("z_{T}")
    if (enableRPDepFit):
        for graph in Py_RPDep_TGraphs:
            for i in range(1 + nObsBins - nSkipLast):
                graph.RemovePoint(nSkipLast + 1)
            graph.SetLineColor(PyRPDepColor)
            graph.SetMarkerColor(PyRPDepColor)
            graph.SetMarkerStyle(PyRPDepMarkerStyle)
    #    graph.GetXaxis().SetTitle("z_{T}")

    c1 = TCanvas("c1", "c1", 900, 600)
    c1.cd()

    # FIXME note that B value must be scaled by num_triggers to be compared

    # Comparing CTask and Python Bkg Parameters
    MultiGraphs = []
    MergedList = tuple(zip(C_TGraphs, Py_TGraphs))
    for i in range(len(MergedList)):
        print("i = %d" % (i))
        (CGraph, PyGraph) = MergedList[i]
        c1.Clear()
        tmg = TMultiGraph()

        #  tmg.Add(CGraph,"lp")
        #  tmg.Add(PyGraph,"lp")
        tmg.Add(CGraph.Clone(), "lp")
        tmg.Add(PyGraph.Clone(), "lp")

        #   gROOT.SetOwnership(CGraph,False)
        #   gROOT.SetOwnership(PyGraph,False)

        tmg.Draw("a")
        tmg.SetName("tmg_%d" % (i))
        tmg.SetTitle(CGraph.GetTitle())
        tmg.GetXaxis().SetTitle(CGraph.GetXaxis().GetTitle())
        PyGraph.SetTitle(CGraph.GetTitle())
        PyGraph.GetXaxis().SetTitle(CGraph.GetXaxis().GetTitle())
        MultiGraphs.append(tmg)

        filename = "RPF_Comp_Param_%s" % (ParamNames[i])
        c1.Print("%s/%s.pdf" % (fOutputDir, filename))
        c1.Print("%s/CFiles/%s.C" % (fOutputDir, filename))

    # Comparing Python BkgOnly and InclusiveSignal
    PyMultiGraphs = []
    MergedList = tuple(zip(Py_TGraphs, Py_RPDep_TGraphs))
    for i in range(len(MergedList)):
        print("i = %d" % (i))
        (PyBkgGraph, PySigGraph) = MergedList[i]
        c1.Clear()
        tmg = TMultiGraph()

        #tmg.Add(PyBkgGraph,"lp")
        #tmg.Add(PySigGraph,"lp")
        tmg.Add(PyBkgGraph.Clone(), "lp")
        tmg.Add(PySigGraph.Clone(), "lp")

        tmg.Draw("a")
        tmg.SetName("tmg_%d" % (i))
        tmg.SetTitle(PyBkgGraph.GetTitle())
        tmg.GetXaxis().SetTitle(PyBkgGraph.GetXaxis().GetTitle())

        PySigGraph.SetTitle(PyBkgGraph.GetTitle())
        PySigGraph.GetXaxis().SetTitle(PyBkgGraph.GetXaxis().GetTitle())

        PyMultiGraphs.append(tmg)

        filename = "RPF_CompBkgSig_Param_%s" % (ParamNames[i])
        c1.Print("%s/%s.pdf" % (fOutputDir, filename))
        c1.Print("%s/CFiles/%s.C" % (fOutputDir, filename))

    # Drawing the ChiSquare Graphs

#  print("Saving to file %s" % (fOutputFile))
#  OutFile = TFile(fOutputFile,"UPDATE")
#  print("Opened file %s" % (OutFile.GetName()))

    print("Trying to get the output file from the c++ task")
    OutFile = fCTask.GetOutputFile()

    #  for graph in Py_TGraphs:
    #    OutFile.Add(graph)
    #   graph.Write()
    #  if (enableRPDepFit):
    #    for graph in Py_RPDep_TGraphs:
    #      OutFile.Add(graph)
    #    graph.Write()

    # Add the chisq/ndf and  parameter graphs to the CTask
    fCTask.InputPyBkgChiSqGraph(Py_ChiSq_TGraph)
    print("About to add %d PyBkg Graphs to CTask" % (len(Py_TGraphs)))
    for i in range(len(Py_TGraphs)):
        print("Adding graph [ %d ] = %s" % (i, Py_TGraphs[i].GetName()))
        fCTask.InputPyBkgParamGraph(i, Py_TGraphs[i])

    if (enableRPDepFit):
        print("About to add %d PyRODepBkg Graphs to CTask" %
              (len(Py_RPDep_TGraphs)))
        fCTask.InputPyRPSChiSqGraph(Py_RPDep_ChiSq_TGraph)
        for i in range(len(Py_RPDep_TGraphs)):
            fCTask.InputPyRPSParamGraph(i, Py_RPDep_TGraphs[i])

    print("about to try deleting recursive objects")

    del MultiGraphs
    del PyMultiGraphs

    # Input the Covariance matrices

    # Should maybe find a nice way to save the covariance matrices
    # TH2D ?
    print("Writing File...")
    # OutFile.Write()
    print("Successfully wrote file! (maybe)")
    # OutFile.Close()
    print("Closed file!")

    print("=======================================================")
    print("Done with the python part")
    print("=======================================================")

    fCTask.Run_Part2()
Example #12
0
def MakePlot(PlotList, name):
    canvas = TCanvas('canvas', 'shouldnotseethis', 0, 0, 1280, 720)

    colors = [ROOT.kRed, ROOT.kBlue, ROOT.kGreen, ROOT.kCyan,
              ROOT.kMagenta]  # ROOT.kOrange+1,

    MG = TMultiGraph()
    MG.SetTitle(
        "Best Fits per Chi Square;Center of Mass Angle in Degrees;Cross Section in mb/sr"
    )
    MG.SetTitle("MG")
    MG.SetName(name)
    legend = ROOT.TLegend(0.3, .65, .9, .9)

    # if len(PlotList) >6:
    #     PlotList = PlotList[:6]
    #     print "Cutting PlotList length for {}".format(name)
    #
    Zipper = zip(PlotList, colors)
    #
    # MG.Add(dataG,"P")
    # legend.AddEntry(dataG,"Data")
    i = 2
    for bigInfo, color in Zipper:
        if len(Zipper) == 1:
            color = ROOT.kBlack
        plot = bigInfo[-1]
        plot.SetMarkerColor(ROOT.kWhite)
        plot.SetLineColor(color)
        plot.SetFillColor(ROOT.kWhite)
        plot.SetLineWidth(2)
        if len(Zipper) > 1:
            plot.SetLineStyle(i)
        i += 1
        MG.Add(plot, "L")
        legend.AddEntry(
            plot, "chiSquare(" + str(int(bigInfo[0])) + ")_" + plot.GetName())

        dataPlot = bigInfo[-2]
        dataPlot.SetMarkerColor(ROOT.TColor.GetColorDark(color))
        dataPlot.SetLineColor(ROOT.TColor.GetColorDark(color))
        dataPlot.SetFillColor(ROOT.kWhite)
        MG.Add(dataPlot, "P")
        legend.AddEntry(
            dataPlot,
            "data_chiSquare(" + str(int(bigInfo[0])) + ")_" + plot.GetName())

        if len(PlotList) < 4:
            blurPlot = bigInfo[-3]
            blurPlot.SetMarkerColor(color)
            blurPlot.SetLineColor(color)
            blurPlot.SetLineStyle(2)
            blurPlot.SetLineWidth(2)
            blurPlot.SetFillColor(ROOT.kWhite)  # print blurPlot.GetName()
            # blurPlot.Print()
            MG.Add(blurPlot, "L")
            legend.AddEntry(blurPlot, "Blurred Fresco Output")

    MG.Draw("AL")
    canvas.SetLogy()
    MG.GetXaxis().SetTitle("Center of Mass Angle in Degrees")
    MG.GetYaxis().SetTitle("Cross Section in mb/sr")
    MG.Draw()
    legend.Draw()

    outF.cd()
    MG.Write()

    canvas.SaveAs("pngs/{}.png".format(name))
Example #13
0
def FrescoDraw(title, name, beforeGraph, afterGraph, blurGraph, dataGraph):

    MG = TMultiGraph()
    MG.SetTitle(
        "Fresco Results;Center of Mass Angle in Degrees;Cross Section in mb/sr"
    )
    MG.SetTitle(title)
    MG.SetName(name)
    legend = ROOT.TLegend(0.65, .65, .9, .9)

    # afterGraph = Chop(afterGraph)
    if coulombH:
        coulombH.SetMarkerColor(ROOT.kWhite)
        coulombH.SetLineColor(ROOT.kRed)
        coulombH.SetLineStyle(10)
        coulombH.SetFillColor(ROOT.kWhite)
        coulombH.SetMarkerStyle(20)
        MG.Add(coulombH, "L")
        legend.AddEntry(coulombH, "Coulomb Only")

    if beforeGraph:
        beforeGraph.SetMarkerColor(ROOT.kWhite)
        beforeGraph.SetLineColor(ROOT.kBlack)
        beforeGraph.SetFillColor(ROOT.kWhite)
        beforeGraph.SetMarkerStyle(20)
        MG.Add(beforeGraph, "L")
        legend.AddEntry(beforeGraph, "FRESCO output")

    MG.Draw("al*")
    # if args.rRuth:
    #   canvas.SetLogy(0)
    # else:
    canvas.SetLogy()

    MG.GetXaxis().SetTitle("Center of Mass Angle in Degrees")
    MG.GetYaxis().SetTitle("Cross Section in mb/sr")
    if args.rRuth:
        MG.GetYaxis().SetTitle("Ratio to Rutherford")

    MG.Draw()
    legend.Draw()

    if args.rRuth:
        canvas.SaveAs("aa_{}_before_ruth.png".format(name))
    else:
        canvas.SaveAs("aa_{}_before.png".format(name))

    if afterGraph:
        afterGraph.SetMarkerColor(ROOT.kWhite)
        afterGraph.SetLineColor(ROOT.kGreen)
        afterGraph.SetFillColor(ROOT.kWhite)
        afterGraph.SetMarkerStyle(20)
        MG.Add(afterGraph, "L")
        legend.AddEntry(afterGraph, "After sfresco Fit")

    if blurGraph:
        blurGraph.SetMarkerColor(ROOT.kGreen)
        blurGraph.SetLineColor(ROOT.kWhite)
        blurGraph.SetFillColor(ROOT.kWhite)
        blurGraph.SetMarkerStyle(20)
        MG.Add(blurGraph, "P")
        legend.AddEntry(blurGraph, "Blurred sfresco Fit")

    if dataGraph:
        dataGraph.SetMarkerColor(ROOT.kBlue)
        dataGraph.SetLineColor(ROOT.kBlue)
        dataGraph.SetFillColor(ROOT.kWhite)
        dataGraph.SetMarkerStyle(20)
        MG.Add(dataGraph, "P")
        legend.AddEntry(dataGraph, "Data")

    MG.Draw()
    # if args.rRuth:
    #   canvas.SetLogy(0)
    # else:
    canvas.SetLogy()
    MG.GetXaxis().SetTitle("Center of Mass Angle in Degrees")
    MG.GetYaxis().SetTitle("Cross Section in mb/sr")
    if args.rRuth:
        MG.GetYaxis().SetTitle("Ratio to Rutherford")

    MG.Draw()
    legend.Draw()

    if args.rRuth:
        canvas.SaveAs("aa_{}_ruth.png".format(name))
    else:
        canvas.SaveAs("aa_{}.png".format(name))
Example #14
0
def recenergy():
    outputfile = "EMEnergyRes"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    MeanEnergyScin = array('d')
    MeanEnergyCher = array('d')
    Energy = array('d')
    energyfractionscin = array('d')
    energyfractioncher = array('d')
    energyfraction = array('d')
    resolutionscin = array('d')
    resolutioncher = array('d')
    resolution = array('d')

    energies = array(
        'd',
        [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150])
    energies = array('d', [40, 50, 60, 70, 80, 90, 100])
    energies = array('d', [5, 10, 40, 60, 80, 100, 150])
    sqrtenergies = array('d', [1 / (x**0.5) for x in energies])
    scin_sqrtenergies = array('d')
    cher_sqrtenergies = array('d')
    #inputfiles = sorted(glob.glob(datapath+"*"), key=os.path.getmtime) #get files from tower 1 to 75 ordered by creation time
    t = [5, 10, 40, 60, 80, 100, 150]
    inputfiles = [
        "/home/software/Calo/results/newenergyscan3_noangsmearing/Electron_" +
        str(i) + ".root" for i in t
    ]
    for counter, inputfile in enumerate(inputfiles):
        inputfile = TFile(inputfile)
        print "Analyzing: " + str(inputfile) + " \n"
        tree = TTree()
        inputfile.GetObject("B4", tree)

        ScinEnergyHist = TH1F("scinenergy_",
                              str(counter + 1) + "_scin", 500, 0., 200.)
        CherEnergyHist = TH1F("cherenergy_",
                              str(counter + 1) + "_cher", 500, 0., 200.)
        RecEnergyHist = TH1F("RecEnergy_",
                             str(counter + 1) + "_Energy", 500, 0., 200.)

        Signalscinhist = TH1F("scintot_",
                              str(counter + 1) + "_scin", 3000, 0., 30000)
        EnergyHist = TH1F("Energy_",
                          str(counter + 1) + "_Energy", 500, 0., 200.)

        #loop over events
        for Event in range(int(tree.GetEntries())):

            tree.GetEntry(Event)

            #Set values of the tree
            PrimaryParticleName = tree.PrimaryParticleName  # MC truth: primary particle Geant4 name
            PrimaryParticleEnergy = tree.PrimaryParticleEnergy
            EnergyTot = tree.EnergyTot  # Total energy deposited in calorimeter
            Energyem = tree.Energyem  # Energy deposited by the em component
            EnergyScin = tree.EnergyScin  # Energy deposited in Scin fibers (not Birk corrected)
            EnergyCher = tree.EnergyCher  # Energy deposited in Cher fibers (not Birk corrected)
            NofCherenkovDetected = tree.NofCherenkovDetected  # Total Cher p.e. detected
            BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelR_VectorSignalsCher = tree.VectorSignalsCherR  # Vector of Cher p.e. detected in Cher fibers
            BarrelL_VectorSignalsCher = tree.VectorSignalsCherL
            VectorR = tree.VectorR
            VectorL = tree.VectorL

            totalsignalscin = sum(BarrelR_VectorSignals) + sum(
                BarrelL_VectorSignals)
            Signalscinhist.Fill(totalsignalscin)

            energytot = (sum(VectorR) + sum(VectorL)) / 1000
            EnergyHist.Fill(energytot)

            #apply calibrations
            Calib_BarrelL_VectorSignals = calibration.calibscin(
                BarrelL_VectorSignals)
            Calib_BarrelR_VectorSignals = calibration.calibscin(
                BarrelR_VectorSignals)
            Calib_BarrelL_VectorSignalsCher = calibration.calibcher(
                BarrelL_VectorSignalsCher)
            Calib_BarrelR_VectorSignalsCher = calibration.calibcher(
                BarrelR_VectorSignalsCher)
            #end of calibrations

            energyscin = sum(Calib_BarrelR_VectorSignals) + sum(
                Calib_BarrelL_VectorSignals)
            energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum(
                Calib_BarrelL_VectorSignalsCher)

            ScinEnergyHist.Fill(energyscin)
            sigmascin = 0.15 * (energyscin**0.5) + 0.012 * energyscin
            CherEnergyHist.Fill(energycher)
            sigmacher = 0.18 * (energycher**0.5) + 0.0045 * energycher
            RecEnergyHist.Fill(
                (energyscin / (sigmascin**2) + energycher /
                 (sigmacher**2)) / (1 / sigmascin**2 + 1 / sigmacher**2))

        print energies[counter], ScinEnergyHist.GetMean(
        ), CherEnergyHist.GetMean()
        displayfile.cd()
        gStyle.SetOptStat(111)
        ScinEnergyHist.Fit("gaus")
        CherEnergyHist.Fit("gaus")
        RecEnergyHist.Fit("gaus")
        RecEnergyHist.Write()
        ScinEnergyHist.Write()
        CherEnergyHist.Write()
        Signalscinhist.Write()
        EnergyHist.Write()
        scin_sqrtenergies.append(
            1. / (ScinEnergyHist.GetFunction("gaus").GetParameter(1)**0.5))
        cher_sqrtenergies.append(
            1. / (CherEnergyHist.GetFunction("gaus").GetParameter(1)**0.5))
        MeanEnergyScin.append(
            ScinEnergyHist.GetFunction("gaus").GetParameter(1))
        MeanEnergyCher.append(
            CherEnergyHist.GetFunction("gaus").GetParameter(1))
        resolution.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(2) /
            RecEnergyHist.GetFunction("gaus").GetParameter(1))
        energyfractionscin.append(
            ScinEnergyHist.GetFunction("gaus").GetParameter(1))
        energyfractioncher.append(
            CherEnergyHist.GetFunction("gaus").GetParameter(1))
        energyfraction.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutionscin.append(
            ScinEnergyHist.GetFunction("gaus").GetParameter(2) /
            ScinEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutioncher.append(
            CherEnergyHist.GetFunction("gaus").GetParameter(2) /
            CherEnergyHist.GetFunction("gaus").GetParameter(1))

    LinearityGraph = TGraph(len(energies), energies, energyfraction)
    LinearityGraph.SetName("LinearityGraph")
    LinearityGraph.Write()
    LinearityGraphScin = TGraph(len(energies), energies, energyfractionscin)
    LinearityGraphCher = TGraph(len(energies), energies, energyfractioncher)
    LinearityGraphCher.SetName("LinearityGraphCher")
    LinearityGraphCher.Write()
    LinearityGraphScin.SetName("LinearityGraphScin")
    LinearityGraphScin.Write()

    ResolutionGraphScin = TGraph(len(energies), scin_sqrtenergies,
                                 resolutionscin)
    func = TF1("func", "[0]*x+[1]", 0.1, 0.45)
    ResolutionGraphCher = TGraph(len(energies), cher_sqrtenergies,
                                 resolutioncher)
    ResolutionGraphScin.Fit("func", "R")
    ResolutionGraphCher.Fit("func", "R")
    ResolutionGraphScin.SetName("ResolutionGraphScin")
    ResolutionGraphScin.Write()
    ResolutionGraphCher.SetName("ResolutionGraphCher")
    ResolutionGraphCher.Write()
    ResolutionGraph = TGraph(len(energies), sqrtenergies, resolution)
    ResolutionGraph.Fit("func", "R")
    ResolutionGraph.SetName("ResolutionGraph")
    ResolutionGraph.Write()

    rd52copper = array('d', [
        0.04478505426185217, 0.027392527130926082, 0.02420093893609386,
        0.02229837387624884, 0.020999999999999998
    ])

    rd52graph = TGraph(len(energies), sqrtenergies, rd52copper)
    rd52graph.SetName("rd52resolution")
    rd52graph.Write()

    EMResolutions = TMultiGraph()
    EMResolutions.Add(ResolutionGraphScin)
    EMResolutions.Add(ResolutionGraphCher)
    EMResolutions.Add(ResolutionGraph)
    EMResolutions.Add(rd52graph)
    EMResolutions.SetName("EMResolutions")
    EMResolutions.Write()

    Linearities = TMultiGraph()
    Linearities.Add(LinearityGraph)
    Linearities.Add(LinearityGraphScin)
    Linearities.Add(LinearityGraphCher)
    Linearities.SetName("Linearities")
    Linearities.Write()
Example #15
0
def combinedDraw(frescoGraph, goodPID, badPID, goodCORR, badCORR):
    #print "combinedDraw start"
    canvas = TCanvas('canvas', 'shouldnotseethis', 0, 0, 1280, 720)

    MG = TMultiGraph()
    legend = ROOT.TLegend(0.55, .55, .9, .9)
    ##legend.SetBorderSize(0)
    #underHisto.SetLineColor(ROOT.kBlack)
    #underHisto.SetMinimum(0)
    ##underHisto.SetMaximum(underHisto.GetMaximum() * 1.5)
    #underHisto.GetXaxis().SetRangeUser(0,180)
    #underHisto.SetTitle(title)
    #underHisto.SetLineColor(ROOT.kBlack)
    #underHisto.SetTitle(title)
    #underHisto.GetYaxis().SetTitle("Counts in Arb. Units")
    #legend.AddEntry(underHisto,"Simulated Angular Distribution")
    #underHisto.SetStats(ROOT.kFALSE)
    #underHisto.Draw()

    if frescoGraph:
        #print "frescoGraph"
        frescoGraph.SetMarkerColor(ROOT.kBlack)
        frescoGraph.SetLineColor(ROOT.kBlack)
        frescoGraph.SetFillColor(ROOT.kBlack)
        #frescoGraph.SetMarkerStyle(33)
        MG.Add(frescoGraph, "L")
        legend.AddEntry(frescoGraph, "Fresco Output")
    else:
        print "No FrescoGraph!!!"
        return

    if goodPID:
        #print "goodPID"
        goodPID.SetMarkerColor(ROOT.kGreen)
        goodPID.SetLineColor(ROOT.kGreen)
        goodPID.SetFillColor(ROOT.kGreen)
        #goodPID.SetMarkerStyle(33)
        MG.Add(goodPID, "P")
        legend.AddEntry(goodPID, "ScaledPID")
    else:
        print "No goodPID in Draw()"

    if goodCORR:
        #print "goodCORR"
        goodCORR.SetMarkerColor(TColor.GetColorDark(ROOT.kGreen))
        goodCORR.SetLineColor(TColor.GetColorDark(ROOT.kGreen))
        goodCORR.SetFillColor(TColor.GetColorDark(ROOT.kGreen))
        goodCORR.SetMarkerStyle(21)
        #afterHisto.Draw("PLsame")
        MG.Add(goodCORR, "P")
        legend.AddEntry(goodCORR, "Good Dual Det")
    else:
        print "No goodCORR in Draw()"

    if badPID:
        #print "badPID"
        badPID.SetMarkerColor(ROOT.kRed)
        badPID.SetLineColor(ROOT.kRed)
        badPID.SetFillColor(ROOT.kRed)
        badPID.SetMarkerStyle(33)
        MG.Add(badPID, "P")
        legend.AddEntry(badPID, "Discard PID")
    else:
        print "No badPID in Draw()"

    if badCORR:
        #print "badCORR"
        badCORR.SetMarkerColor(TColor.GetColorDark(ROOT.kRed))
        badCORR.SetLineColor(TColor.GetColorDark(ROOT.kRed))
        badCORR.SetFillColor(TColor.GetColorDark(ROOT.kRed))
        badCORR.SetMarkerStyle(21)
        MG.Add(badCORR, "P")
        legend.AddEntry(badCORR, "Discard Dual Det")
    else:
        print "No badCORR in Draw()"

    MG.SetTitle(
        "Scaled Elastic Distribution for detector {};Center of Mass Angle in Degrees;Cross section in mb/sr"
        .format(det))
    MG.SetName("MG_d{}".format(det))
    MG.Draw("AP")
    legend.Draw()
    MG.Write()
    MG.SetMaximum(500)
    MG.SetMinimum(0)

    canvas.SetLogy()
    #MG.GetYaxis().SetRangeUser(0,500)

    MG.Draw()
    canvas.SaveAs(MG.GetName() + '.png')