def make1DSummaryPlot(binned_mw, bins, channel, variable, treeSuffix):
    nBins = len(bins)

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

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

    outputDir = 'plots/WStudies/%s%s/%s' % (channel, treeSuffix, variable)
    c.Print('%s/Summary.pdf' % outputDir)
Ejemplo n.º 2
0
  def plotGraph(self, x='vv', y='acc'): 
    '''
    Plot a graph with specified quantities on x and y axes , and saves the graph
    '''

    if (x not in self.quantities.keys()) or (y not in self.quantities.keys()):
      raise RuntimeError('selected quantities not available, available quantities are: \n{}'.format(self.quantities.keys()))

    xq = self.quantities[x]
    yq = self.quantities[y]

    #graph = TGraphAsymmErrors()
    #graph = TGraph()
    graph = TGraphErrors()
    for i,s in enumerate(self.samples):
      graph.SetPoint(i,getattr(s, xq.name), getattr(s, yq.name) )
      #if xq.err: 
      #  graph.SetPointEXhigh(i, getattr(s, xq.name+'_errup'))   # errup errdn
      #  graph.SetPointEXlow (i, getattr(s, xq.name+'_errdn'))
      if yq.err: 
        graph.SetPointError(i, 0, getattr(s, yq.name+'_errup'))
      #  graph.SetPointEYhigh(i, getattr(s, yq.name+'_errup'))  
      #  graph.SetPointEYlow (i, getattr(s, yq.name+'_errdn'))

    c = TCanvas()
    graph.SetLineWidth(2)
    graph.SetMarkerStyle(22)
    graph.SetTitle(';{x};{y}'.format(y=yq.title,x=xq.title))
    graph.Draw('APLE')

    if yq.forceRange:
      graph.SetMinimum(yq.Range[0])
      graph.SetMaximum(yq.Range[1])

    gPad.Modified()
    gPad.Update()
    if yq.name=='expNevts':
      line = TLine(gPad.GetUxmin(),3,gPad.GetUxmax(),3)
      line.SetLineColor(ROOT.kBlue)
      line.Draw('same')
      #graph.SetMinimum(0.01)
      #graph.SetMaximum(1E06)

    if xq.log: c.SetLogx()
    if yq.log: c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    c.SaveAs('./plots/{}{}/{}_{}VS{}.pdf'.format(self.label,suffix,self.name,yq.name,xq.name))
    c.SaveAs('./plots/{}{}/{}_{}VS{}.C'.format(self.label,suffix,self.name,yq.name,xq.name))
    c.SaveAs('./plots/{}{}/{}_{}VS{}.png'.format(self.label,suffix,self.name,yq.name,xq.name))

    self.graphs['{}VS{}'.format(yq.name,xq.name)] = graph
    # add the graph container for memory?
    graph_saver.append(graph)
Ejemplo n.º 3
0
 def plot( self, plotoptions, opt="?" ):
     vx= array( "d", self.aostand.getPointsCenter() )
     values= self.values
     sterrs= self.sterrs
     if "m" in opt:
         print "AnalysisObservable::plot: use errors from error matrix"
         sterrs= array( "d", self.aostand.getErrors( "m" ) )
     syerrs= self.syerrs
     npoints= len(vx)
     if "xshift" in plotoptions:
         for i in range(npoints):
             vx[i]+= plotoptions["xshift"]
     vex= array( "d", npoints*[0.0] )
     tgest= TGraphErrors( npoints, vx, values, vex, sterrs )
     toterrs= np.sqrt( np.add( np.square( sterrs ),  np.square( syerrs ) ) )
     tgesy= TGraphErrors( npoints, vx, values, vex, toterrs )
     tgesy.SetMarkerStyle( plotoptions["markerStyle"] )
     tgesy.SetMarkerSize( plotoptions["markerSize"] )
     drawas= plotoptions["drawas"] if "drawas" in plotoptions else "p"
     tgesy.SetName( self.obs )
     if "fillcolor" in plotoptions:
         tgesy.SetFillColor(plotoptions["fillcolor"])
         tgest.SetFillColor(plotoptions["fillcolor"])
     if "s" in opt:
         tgesy.Draw( "psame" )
     else:
         if "title" in plotoptions:
             tgesy.SetTitle( plotoptions["title"] )
         else:
             tgesy.SetTitle( self.obs )
         tgesy.SetMinimum( plotoptions["ymin"] )
         tgesy.SetMaximum( plotoptions["ymax"] )
         xaxis= tgesy.GetXaxis()
         xaxis.SetLimits( plotoptions["xmin"], plotoptions["xmax"] )
         if "xlabel" in plotoptions:
             xaxis.SetTitle( plotoptions["xlabel"] )
         if "ylabel" in plotoptions:
             tgesy.GetYaxis().SetTitle( plotoptions["ylabel"] )
         tgesy.Draw( "a"+drawas )
     optlogx= plotoptions["logx"] if "logx" in plotoptions else 0
     gPad.SetLogx( optlogx )
     optlogy= plotoptions["logy"] if "logy" in plotoptions else 0
     gPad.SetLogy( optlogy )
     tgest.Draw( "same"+drawas )
     return tgest, tgesy
Ejemplo n.º 4
0
# Plotting
##########

fontsize = 0.04

gr = TGraphErrors(len(voltages), voltages / 1000 / 0.1 / 100, v_drift * 100,
                  zeros(len(voltages)), 100 * v_drift_err)

gr_mb = TGraph(len(v_mb), v_mb, v_drift_mb)

gr.GetXaxis().SetTitle("Drift field [kV/cm]")
gr.GetYaxis().SetTitle("Drift velocity [cm/#mus]")
gr.SetTitle("Drift velocity")

gr.GetYaxis().SetTitleOffset(1.25)
gr.SetMinimum(6)

gr.GetXaxis().SetLimits(0.16, 0.64)

gr.SetMarkerStyle(2)
gr.GetXaxis().SetLabelSize(fontsize)
gr.GetXaxis().SetTitleSize(fontsize)
gr.GetYaxis().SetLabelSize(fontsize)
gr.GetYaxis().SetTitleSize(fontsize)

gr_mb.SetMarkerStyle(8)

gr.Draw("AP")
gr_mb.Draw("P")

gr.SetName("gr")
        #### newly introduced, not yet sure if helpful: 
        vmean[m].removeError()
        vsigma[m].removeError()
        valpha1[m].removeError()
        valpha2[m].removeError()
        vslope1[m].removeError()
        vslope2[m].removeError()

        #signalNorm[m].setConstant(False)  ## newly put here to ensure it's freely floating in the combine fit
 
    #c1 = TCanvas("c1", "Crystal Ball", 1200, 1200) #if not isAH else 1200
    #c1.Divide(2, 3)
    c1 = TCanvas("c1", "Crystal Ball", 1800, 800)
    c1.Divide(3, 2)
    c1.cd(1)
    gmean.SetMinimum(0.)
    gmean.Draw("APL")
    imean.Draw("P, SAME")
    drawRegion(category)
    c1.cd(2)
    gsigma.SetMinimum(0.)
    gsigma.Draw("APL")
    isigma.Draw("P, SAME")
    drawRegion(category)
    c1.cd(3)
    galpha1.Draw("APL")
    ialpha1.Draw("P, SAME")
    drawRegion(category)
    galpha1.GetYaxis().SetRangeUser(0., 1.1) #adjusted upper limit from 5 to 2
    c1.cd(4)
    gslope1.Draw("APL")
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()
def main(argv):

    print(len(argv))
    if len(argv) == 5:
        #print ('The script is called: '+str(script))
        print('Your waves are: ' + argv[0])
        print('Number of M bins is: ' + argv[1])
        print('Number of t bins is: ' + argv[2])
        print(
            'Intensity results from fitting the original data are written in: '
            + argv[3])
        print('Phase differences: ' + argv[4])
        if len(argv[0].split()) < 2:
            sys.exit("You should specify more than one amplitude")
    else:
        sys.exit(
            "You need to give 4 args..., usage: python script.py \"S0mi P1pl D1pl ...\" Nmassbins Ntbins fitresultfile \"P0P1diff \""
        )

    amps, NumBins, NumtBins, Fitresultfile, phasedifflist = argv
    N_amps = len(amps.split())
    NumBins = int(NumBins)
    NumtBins = int(NumtBins)
    Numphasediff = len(phasedifflist.split())

    ## Output file to save the histograms in
    file_out = TFile('Drawing_waves.root', 'Recreate')

    ## column number for M value and each of the amplitude intensities and
    ##corresponding errors
    column_m = 0
    column_t = 1
    colomn_Waves = np.arange(2, 2 * N_amps + 1, 2)
    colomn_Waves_err = np.arange(3, 2 * N_amps + 2, 2)
    column_all_Waves = 2 * N_amps + 2
    column_all_Waves_err = 2 * N_amps + 3
    column_phasediff = np.arange(column_all_Waves_err + 1,
                                 column_all_Waves_err + 1 + 2 * Numphasediff,
                                 2)
    column_phasediff_err = np.arange(
        column_all_Waves_err + 2, column_all_Waves_err + 1 + 2 * Numphasediff,
        2)

    ## Arrays of  intensities from fitting the original data in different M bins
    orig_Wave = np.zeros((N_amps, NumBins))
    orig_all_Waves = np.zeros(NumBins)
    ##Reading uncertainties from MINUIT
    orig_Wave_err_square = np.zeros((N_amps, NumBins))
    orig_all_Waves_err_square = np.zeros(NumBins)
    mass_bins = np.zeros(NumBins)
    phase_diff = np.zeros((Numphasediff, NumtBins, NumBins))
    phase_diff_err = np.zeros((Numphasediff, NumtBins, NumBins))

    ## Asigning values to arrays of intensities from fitting the original data in
    ##different M bins by reading from a file
    token_origdata_fitresults = open(Fitresultfile, 'r')
    linestoken_orig = token_origdata_fitresults.readlines()
    j = 0
    fit_res_colomns = 0
    for x in linestoken_orig:

        fit_res_colomns = len(x.split())
        for waves in range(0, N_amps):

            orig_Wave[waves][int(j / NumtBins)] = orig_Wave[waves][int(
                j / NumtBins)] + float(x.split()[colomn_Waves[waves]])
            orig_Wave_err_square[waves][
                j /
                NumtBins] = orig_Wave_err_square[waves][j / NumtBins] + float(
                    x.split()[colomn_Waves_err[waves]]) * float(
                        x.split()[colomn_Waves_err[waves]])
        orig_all_Waves[j / NumtBins] = orig_all_Waves[j / NumtBins] + float(
            x.split()[column_all_Waves])
        orig_all_Waves_err_square[j / NumtBins] = orig_all_Waves_err_square[
            j / NumtBins] + float(x.split()[column_all_Waves_err]) * float(
                x.split()[column_all_Waves_err])
        mass_bins[j / NumtBins] = float(x.split()[column_m])

        for N_phase in range(0, Numphasediff):

            phase_diff[N_phase][int(j % NumtBins)][int(j / NumtBins)] = float(
                x.split()[column_phasediff[N_phase]])
            phase_diff_err[N_phase][int(j % NumtBins)][int(
                j / NumtBins)] = float(
                    x.split()[column_phasediff_err[N_phase]])

        j = j + 1
    if j != NumBins * NumtBins:
        sys.exit(
            "The total number of bins are different from the one provided")

    orig_Wave_err = np.sqrt(orig_Wave_err_square)
    orig_all_Waves_err = np.sqrt(orig_all_Waves_err_square)

    ##Combined intensities of the same amplitudes from diff. sums
    N_comb_waves = int(N_amps / 2)
    orig_Wave_comb = np.zeros((N_comb_waves, NumBins))
    ##Combined uncertainty from MINUIT for the same wave from diff. sums
    orig_Wave_err_square_comb = np.zeros((N_comb_waves, NumBins))

    for waves_comb in range(0, N_comb_waves):

        for M_bin in range(0, NumBins):

            orig_Wave_comb[waves_comb][M_bin] = orig_Wave[int(
                2 * waves_comb)][M_bin] + orig_Wave[int(2 * waves_comb +
                                                        1)][M_bin]
            orig_Wave_err_square_comb[waves_comb][M_bin] = orig_Wave_err[int(
                2 * waves_comb)][M_bin] * orig_Wave_err[int(
                    2 * waves_comb)][M_bin] + orig_Wave_err[int(
                        2 * waves_comb + 1)][M_bin] * orig_Wave_err[int(
                            2 * waves_comb + 1)][M_bin]

    orig_Wave_err_comb = np.sqrt(orig_Wave_err_square_comb)

    print('I am here')

    ##The graphs of intensities of different waves
    error_M = np.zeros(NumBins)
    grerr_list_Wave = []
    for waves in range(0, int(N_amps / 2)):
        grerr_list_Wave.append(
            TGraphErrors(NumBins, mass_bins, orig_Wave_comb[waves], error_M,
                         orig_Wave_err_comb[waves]))

    c1 = TCanvas('c1', 'A Simple Graph with error bars', 200, 10, 700, 500)
    c1.Divide(3, 2)
    c1.SetGrid()
    c1.GetFrame().SetFillColor(21)
    c1.GetFrame().SetBorderSize(12)

    for waves in range(0, int(N_amps / 2)):
        grerr_list_Wave[waves].SetMarkerSize(.5)
        grerr_list_Wave[waves].SetMarkerStyle(20)
        grerr_list_Wave[waves].SetName(amps.split()[2 * waves])
        grerr_list_Wave[waves].SetTitle(amps.split()[2 * waves])
        if waves < 6:
            grerr_list_Wave[waves].SetMaximum(1.2 *
                                              np.amax(orig_Wave_comb[waves]))
        else:
            grerr_list_Wave[waves].SetMaximum(1.2 * np.amax(orig_all_Waves))


#        grerr_list_Wave[waves].SetMinimum(0.8*np.amin(orig_Wave_comb[waves]))

        grerr_list_Wave[waves].SetMinimum(0.8 * np.amin(orig_all_Waves))
        grerr_list_Wave[waves].Draw('AP')
        c1.Print('Plots/Wave' + amps.split()[2 * waves] + '.pdf')

    ##The graph of total intensity
    c3 = TCanvas('c3', 'A Simple Graph with error bars', 200, 10, 700, 500)
    c3.Divide(3, 2)
    c3.SetGrid()
    c3.GetFrame().SetFillColor(21)
    c3.GetFrame().SetBorderSize(12)

    gr_all = TGraphErrors(NumBins, mass_bins, orig_all_Waves, error_M,
                          orig_all_Waves_err)
    gr_all.SetMarkerSize(.5)
    gr_all.SetMarkerStyle(20)
    #gr_all.SetMaximum(max(x_max/2.5))
    #gr_all.SetMinimum(min(x_min/5))
    gr_all.SetMaximum(1.2 * np.amax(orig_all_Waves))
    gr_all.SetMinimum(0.8 * np.amin(orig_all_Waves))
    gr_all.SetTitle('All waves')
    gr_all.Draw('AP')
    c3.Print("Plots/All_waves.pdf")

    #plotting phase differences

    grerr_list_phasediff = []
    t_bin = 0
    for N_phasediff in range(0, Numphasediff):

        grerr_list_phasediff.append(
            TGraphErrors(NumBins, mass_bins, phase_diff[N_phasediff][t_bin],
                         error_M, phase_diff_err[N_phasediff][t_bin]))

    c4 = TCanvas('c4', 'A Simple Graph with error bars', 200, 10, 700, 500)

    c4.SetGrid()
    c4.GetFrame().SetFillColor(21)
    c4.GetFrame().SetBorderSize(12)

    for N_phasediff in range(0, Numphasediff):
        grerr_list_phasediff[N_phasediff].SetMarkerSize(.5)
        grerr_list_phasediff[N_phasediff].SetMarkerStyle(20)
        grerr_list_phasediff[N_phasediff].SetName(
            phasedifflist.split()[N_phasediff])
        grerr_list_phasediff[N_phasediff].SetTitle(
            phasedifflist.split()[N_phasediff])

        grerr_list_phasediff[N_phasediff].SetMaximum(
            1.2 * np.amax(phase_diff[N_phasediff][t_bin]))
        grerr_list_phasediff[N_phasediff].SetMinimum(
            0.8 * np.amin(phase_diff[N_phasediff][t_bin]))
        grerr_list_phasediff[N_phasediff].Draw('AP')
        c4.Print('Plots/Phasediff' + phasedifflist.split()[N_phasediff] +
                 '.pdf')

    file_out.Write()
    file_out.Close()
Ejemplo n.º 8
0
def acceptance(year):
    genPoints = [
        1800, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 7000, 8000
    ]

    treeSign = {}
    ngenSign = {}
    nevtSign = {}
    nevtSign_eta = {}
    nevtSign_dEta = {}
    eff = TGraphErrors()
    eff_eta = TGraphErrors()
    eff_dEta = TGraphErrors()

    for i, m in enumerate(genPoints):
        ngenSign[m] = 0.
        nevtSign[m] = 0.
        nevtSign_eta[m] = 0.
        nevtSign_dEta[m] = 0.

        if year == "run2":
            years = ['2016', '2017', '2018']
        else:
            years = [year]

        for yr in years:
            signName = "MC_signal_{}_M{}".format(yr, m)
            sfile = TFile(ACCEPTANCEDIR + signName + "_acceptanceHist.root",
                          "READ")

            ngenSign[m] += sample["ZpBB_M" + str(m)]['genEvents'][yr]

            #all_events_hist = sfile.Get('all_events')
            #nEvents = all_events_hist.GetBinContent(1)
            #ngenSign[m] += nEvents

            passing_events_hist = sfile.Get('passing')
            eta_flag_hist = sfile.Get('eta_flag')
            dEta_flag_hist = sfile.Get('dEta_flag')

            nEvents = passing_events_hist.GetBinContent(1)
            nEvents_eta = eta_flag_hist.GetBinContent(1)
            nEvents_dEta = dEta_flag_hist.GetBinContent(1)

            nevtSign[m] += nEvents
            nevtSign_eta[m] += nEvents_eta
            nevtSign_dEta[m] += nEvents_dEta

            sfile.Close()

        print m, ":", nevtSign[m], "/", ngenSign[
            m], "=", nevtSign[m] / ngenSign[m]
        if nevtSign[m] == 0 or ngenSign[m] < 0: continue
        n = eff.GetN()
        eff.SetPoint(n, m, nevtSign[m] / ngenSign[m])
        eff.SetPointError(n, 0, math.sqrt(nevtSign[m]) / ngenSign[m])
        eff_eta.SetPoint(n, m, nevtSign_eta[m] / ngenSign[m])
        eff_eta.SetPointError(n, 0, math.sqrt(nevtSign_eta[m]) / ngenSign[m])
        eff_dEta.SetPoint(n, m, nevtSign_dEta[m] / ngenSign[m])
        eff_dEta.SetPointError(n, 0, math.sqrt(nevtSign_dEta[m]) / ngenSign[m])

    eff.SetMarkerColor(4)
    eff.SetMarkerStyle(24)
    eff.SetMarkerSize(2)
    eff.SetLineColor(4)
    eff.SetLineWidth(3)
    eff_eta.SetMarkerColor(2)
    eff_eta.SetMarkerStyle(23)
    eff_eta.SetMarkerSize(2)
    eff_eta.SetLineColor(2)
    eff_eta.SetLineWidth(2)
    eff_eta.SetLineStyle(2)
    eff_dEta.SetMarkerColor(418)
    eff_dEta.SetMarkerStyle(23)
    eff_dEta.SetMarkerSize(2)
    eff_dEta.SetLineColor(418)
    eff_dEta.SetLineWidth(2)
    eff_dEta.SetLineStyle(2)

    n = eff.GetN()
    maxEff = 0.

    leg = TLegend(0.15, 0.7, 0.95, 0.8)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    #leg.SetY1(leg.GetY2()-len([x for x in channels if eff[x].GetN() > 0])/2.*0.045)

    leg.AddEntry(eff, "total")
    leg.AddEntry(eff_eta, "|#eta|<2.5")
    leg.AddEntry(eff_dEta, "#Delta#eta<1.1")

    #legS = TLegend(0.5, 0.85-0.045, 0.9, 0.85)
    #legS.SetBorderSize(0)
    #legS.SetFillStyle(0) #1001
    #legS.SetFillColor(0)
    #legS.AddEntry(eff['sum'], "Total efficiency (1 b tag + 2 b tag)", "pl")

    c1 = TCanvas("c1", "Signal Acceptance", 1200, 800)
    c1.cd(1)
    eff.Draw("APL")
    eff_eta.Draw("SAME, PL")
    eff_dEta.Draw("SAME, PL")
    leg.Draw()
    #legS.Draw()
    #setHistStyle(eff["sum"], 1.1)
    eff.SetTitle(";m_{Z'} (GeV);Acceptance")
    eff.SetMinimum(0.)
    eff.SetMaximum(max(1.5, maxEff * 1.5))  #0.65

    eff.GetXaxis().SetTitleSize(0.045)
    eff.GetYaxis().SetTitleSize(0.045)
    eff.GetYaxis().SetTitleOffset(1.1)
    eff.GetXaxis().SetTitleOffset(1.05)
    eff.GetXaxis().SetRangeUser(1500, 8000)
    c1.SetTopMargin(0.05)
    #drawCMS(-1, "Simulation Preliminary", year=year) #Preliminary
    #drawCMS(-1, "Work in Progress", year=year, suppressCMS=True)
    drawCMS(-1, "", year=year, suppressCMS=True)
    drawAnalysis("")

    c1.Print("plots/Efficiency/" + year + "_Acceptance.pdf")
    c1.Print("plots/Efficiency/" + year + "_Acceptance.png")
Ejemplo n.º 9
0
	masspoint = int(gre.GetName().split("_")[1])
	limit = (math.log(0.05)-fit.GetParameter(0))/fit.GetParameter(1)

	print "%2d\t%4d\t%4.3f"%(ifit,masspoint,limit)
#	print masspoint
	if masspoint <400: continue

	limitVsMass.SetPoint(ifit,masspoint,limit)
	ifit += 1	


limitVsMass.Draw("ape")

limitVsMass.GetXaxis().SetTitle("mass [GeV/c^{2}]")
limitVsMass.GetYaxis().SetTitle("#lambda_{s}")
limitVsMass.SetMinimum(0)

limitVsMass.Draw("ape")
can.Update()

line = TLine(limitVsMass.GetXaxis().GetXmin(),2.5,limitVsMass.GetXaxis().GetXmax(),2.5)
line.SetLineStyle(2)
line.SetLineColor(ROOT.kRed)
line.Draw("same,r")
can.Update()

#can.SaveAs("gif/limitVsLambdaS.gif")


outfile = TFile("out/limitPlot_%s.root"%theDir,"recreate")
outfile.cd()
Ejemplo n.º 10
0
def recenergy(particle, name, chivalue):
    outputfile = str(particle) + "_Femanalysis" + str(chivalue) + "_" + str(
        name)
    displayfile = TFile(outputfile + ".root", "RECREATE")
    '''
	if name == "FTFPBERT":
		chi = 0.3
	if name == "FTFPBERTTRV":
		chi = 0.3
	if name == "QGSPBERT":
		chi = 0.3
	if name == "QBBC":
		chi = 0.3
	'''
    MeanEnergyScin = array('d')
    MeanEnergyCher = array('d')
    Energy = array('d')
    Energyerror = array('d')
    energyfractionscin = array('d')
    energyfractionscinerror = array('d')
    energyfractioncher = array('d')
    energyfractionchererror = array('d')
    energyfraction = array('d')
    energyfractionerror = array('d')
    resolutionscin = array('d')
    resolutionscinerror = array('d')
    resolutioncher = array('d')
    resolutionchererror = array('d')
    resolution = array('d')
    resolutionerror = array('d')
    chiarray = array('d')
    chierrorarray = array('d')
    zeros = array('d')
    containment = array('d')
    containmenterror = array('d')
    femvalues = array('d')
    zvalues = array('d')
    femvalueserror = array('d')
    zvalueserror = array('d')
    znormvalues = array('d')
    znormvalueserror = array('d')

    t = [10, 30, 50, 70, 100, 120, 140, 150]
    sqrtenergies = array('d', [1 / (x**0.5) for x in t])
    energies = array('d', t)
    #inputfiles = ["/home/software/Calo/results/energycont_2p0m/Pion_"+str(i)+".root" for i in t]
    #inputfiles = ["/home/software/Calo/results/pionenergyscan_QGSPBICHP/Pion_"+str(i)+".root" for i in t]
    #inputfiles = ["/home/lorenzo/Desktop/Calo/newresults/FTFPBERTTRV/Pion_"+str(i)+"_FTFPBERTTRV_office.root" for i in t]
    #inputfiles = ["/Users/lorenzo/Desktop/ToPC/newresults/"+str(name)+"/Pion_"+str(i)+".root" for i in t]
    if particle == "pion":
        inputfiles = [
            "/home/lorenzo/Calo/results/Pion_25_3_2020/" + str(name) + "" +
            "/Pion_" + str(i) + ".root" for i in t
        ]
    #inputfiles = ["/home/lorenzo/Calo/results/geant4.10.4.p01/Pion_30_4_2020/"+str(name)+""+"/Pion_"+str(i)+".root" for i in t]
    if particle == "proton":
        inputfiles = [
            "/home/lorenzo/Calo/results/Proton_25_3_2020/" + str(name) + "" +
            "/Proton_" + str(i) + ".root" for i in t
        ]
    if particle == "neutron":
        inputfiles = [
            "/home/lorenzo/Calo/results/Neutron_25_3_2020/" + str(name) + "" +
            "/Neutron_" + str(i) + ".root" for i in t
        ]
    if particle == "kaon":
        inputfiles = [
            "/home/lorenzo/Calo/results/Kaon_5_4_2020/" + str(name) + "" +
            "/Kaon_" + 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(t[counter]),
                              str(t[counter]) + "_scin", 400, 0., 200.)
        CherEnergyHist = TH1F("cherenergy_" + str(t[counter]),
                              str(t[counter]) + "_cher", 400, 0., 200.)
        RecEnergyHist = TH1F("RecEnergy_" + str(t[counter]),
                             str(t[counter]) + "_Energy", 400, 0., 200.)

        #Signalscinhist = TH1F("scintot_", str(counter+1)+"_scin", 3000, 0., 30000)
        EnergyHist = TH1F("Energy_" + str(t[counter]),
                          str(t[counter]) + "_Energy", 400, 0., 200.)
        LeakageHist = TH1F("Leak_" + str(t[counter]),
                           str(t[counter]) + "_Leak", 1000, 0., 100.)
        NeutrinoLeakageHist = TH1F("NeutrinoNeutrinoLeak_" + str(t[counter]),
                                   str(t[counter]) + "_Leak", 1000, 0., 100.)
        TotalLeakageHist = TH1F("TotalLeak_" + str(t[counter]),
                                str(t[counter]) + "_Leak", 1000, 0., 100.)
        ChiHist = TH1F("Chi_" + str(t[counter]),
                       str(t[counter]) + "_Chi", 200, 0., 2.)
        scatterplot = TH2F("scatterplot_" + str(t[counter]), str(t[counter]),
                           int(400), 0., 200., int(400), 0., 200.)
        EnergyContHist = TH1F("EnergyCont_" + str(t[counter]),
                              str(t[counter]) + "_EnergyCont", 400, 0., 200.)
        hesscatterplot = TH2F("H/E_S" + str(t[counter]),
                              "H/E_S" + str(t[counter]), 200, 0., 1.1, 200, 0.,
                              1.1)
        hecscatterplot = TH2F("H/E_C" + str(t[counter]),
                              "H/E_C" + str(t[counter]), 200, 0., 1.1, 200, 0.,
                              1.1)

        #fem and z histo
        femhisto = TH1F("fem_" + str(t[counter]),
                        str(t[counter]) + "_fem", 100, 0., 1.)
        zhisto = TH1F("z" + str(t[counter]),
                      str(t[counter]) + "_z", 100, 0., 1.)
        znormhisto = TH1F("z_norm" + str(t[counter]),
                          str(t[counter]) + "_z_norm", 200, 0., 2.)
        zfemhisto = TH2F("z_fem_histo" + str(t[counter]),
                         str(t[counter]) + "_z_fem_histo", 200, 0., 2., 200,
                         0., 2.)

        #loop over events
        entries = 50000
        for Event in range(entries):

            tree.GetEntry(Event)
            if Event % 1000 == 0:
                print 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
            Leak = tree.leakage
            NeutrinoLeak = tree.neutrinoleakage

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

            energytot = (sum(VectorR) + sum(VectorL)) / 1000
            EnergyHist.Fill(energytot)
            LeakageHist.Fill(Leak / 1000.)
            NeutrinoLeakageHist.Fill(NeutrinoLeak / 1000.)
            TotalLeakageHist.Fill(Leak / 1000. + NeutrinoLeak / 1000.)

            if float(t[counter]) < 12.:
                cutleak = 0.5
            if float(t[counter]) > 12. and float(t[counter]) < 50.:
                cutleak = 1.0
            if float(t[counter]) > 50.:
                cutleak = 3.0

            if (Leak / 1000. + NeutrinoLeak / 1000.) < cutleak:
                #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)
                e_c = float(t[counter]) - (Leak / 1000. + NeutrinoLeak / 1000.)

                hesscatterplot.Fill(Energyem / 1000. / e_c, energyscin / e_c)
                hecscatterplot.Fill(Energyem / 1000. / e_c, energycher / e_c)

                femhisto.Fill(Energyem / 1000. / e_c)
                z = (1. - energycher / energyscin) / (
                    1. - (chivalue * energycher / energyscin))
                zhisto.Fill(z)
                znormhisto.Fill(z / (1 - (Energyem / 1000. / e_c)))
                zfemhisto.Fill(z, (1 - (Energyem / 1000. / e_c)))
                EnergyContHist.Fill(e_c)
                ScinEnergyHist.Fill(energyscin)
                CherEnergyHist.Fill(energycher)
                scatterplot.Fill(energyscin / float(t[counter]),
                                 energycher / float(t[counter]))
                chi = chivalue
                newchi = (energyscin - e_c) / (energycher - e_c)
                ChiHist.Fill(newchi)
                RecEnergyHist.Fill(
                    1. / 0.99 * (energyscin - chi * energycher) / (1. - chi))

        print energies[counter], ScinEnergyHist.GetMean(
        ), CherEnergyHist.GetMean(), RecEnergyHist.GetMean()
        displayfile.cd()
        gStyle.SetOptStat(111)
        #ScinEnergyHist.Fit("gaus")
        #CherEnergyHist.Fit("gaus")
        #RecEnergyHist.Scale(1/RecEnergyHist.Integral())
        #print RecEnergyHist.Integral()
        RecEnergyHist.Fit("gaus")
        RecEnergyHist.Write()
        ScinEnergyHist.Write()
        CherEnergyHist.Write()
        #Signalscinhist.Write()
        EnergyHist.Write()
        EnergyContHist.Write()
        e_cont = EnergyContHist.GetMean()
        e_cont_error = EnergyContHist.GetRMS() / float(entries)**0.5
        scatterplot.Write()
        #cut1 = TCutG("cut1",4)
        #cut1.SetVarX("x")
        #cut1.SetVarY("y")
        #cut1.SetPoint(0,0.,0.)
        #cut1.SetPoint(1,1.,0.)
        #cut1.SetPoint(2,1.,1.)
        #cut1.SetPoint(3,0.,1.)
        #profile = scatterplot.ProfileX("",1,400,"[cut1]")
        #profile.GetYaxis().SetRangeUser(0.,1.5)
        #profile.Write()
        func2 = TF1("func2", '[0]+x*(1.-[0])', 0., 1.)
        pp = hesscatterplot.ProfileX()
        pp.Fit(func2)
        pp.Write()
        hesscatterplot.Write()
        hecscatterplot.Write()
        femhisto
        ppc = hecscatterplot.ProfileX()
        ppc.Fit(func2)
        ppc.Write()
        LeakageHist.Write()
        NeutrinoLeakageHist.Write()
        TotalLeakageHist.Write()
        ChiHist.Write()
        #scin_sqrtenergies.append(1./(ScinEnergyHist.GetFunction("gaus").GetParameter(1)**0.5))
        #cher_sqrtenergies.append(1./(CherEnergyHist.GetFunction("gaus").GetParameter(1)**0.5))
        Energy.append(RecEnergyHist.GetFunction("gaus").GetParameter(1))
        Energyerror.append(3. *
                           RecEnergyHist.GetFunction("gaus").GetParameter(2) /
                           float(entries)**0.5)
        MeanEnergyScin.append(ScinEnergyHist.GetMean())
        MeanEnergyCher.append(CherEnergyHist.GetMean())
        resolution.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(2) /
            RecEnergyHist.GetFunction("gaus").GetParameter(1))
        sigma_energy_e = (
            (RecEnergyHist.GetFunction("gaus").GetParameter(2) /
             (float(entries)**0.5)) /
            RecEnergyHist.GetFunction("gaus").GetParameter(1) +
            RecEnergyHist.GetFunction("gaus").GetParError(2) /
            RecEnergyHist.GetFunction("gaus").GetParameter(2)) * (
                RecEnergyHist.GetFunction("gaus").GetParameter(2) /
                RecEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutionerror.append(sigma_energy_e)
        energyfractionscin.append(ScinEnergyHist.GetMean() / float(t[counter]))
        energyfractionscinerror.append(
            3 * (ScinEnergyHist.GetRMS() / entries**0.5) / float(t[counter]))
        energyfractioncher.append(CherEnergyHist.GetMean() / float(t[counter]))
        energyfractionchererror.append(
            3 * (CherEnergyHist.GetRMS() / entries**0.5) / float(t[counter]))
        energyfraction.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(1) /
            float(t[counter]))
        energyfractionerror.append(
            3 * (RecEnergyHist.GetFunction("gaus").GetParameter(2) /
                 entries**0.5) / float(t[counter]))
        resolutionscin.append(ScinEnergyHist.GetRMS() /
                              ScinEnergyHist.GetMean())
        sigma_energy_e = (
            ScinEnergyHist.GetMeanError() / ScinEnergyHist.GetMean() +
            ScinEnergyHist.GetRMSError() / ScinEnergyHist.GetRMS()) * (
                ScinEnergyHist.GetRMS() / ScinEnergyHist.GetMean())
        resolutionscinerror.append(sigma_energy_e)
        resolutioncher.append(CherEnergyHist.GetRMS() /
                              CherEnergyHist.GetMean())
        sigma_energy_e = (
            CherEnergyHist.GetMeanError() / CherEnergyHist.GetMean() +
            CherEnergyHist.GetRMSError() / CherEnergyHist.GetRMS()) * (
                CherEnergyHist.GetRMS() / CherEnergyHist.GetMean())
        resolutionchererror.append(sigma_energy_e)
        chiarray.append(ChiHist.GetBinCenter(ChiHist.GetMaximumBin()))
        chierrorarray.append(3 * ChiHist.GetRMS() / (entries**0.5))
        zeros.append(0.0)
        containment.append(e_cont / float(t[counter]))
        containmenterror.append(e_cont_error / float(t[counter]))
        femhisto.Write()
        zhisto.Write()
        zfemhisto.Write()
        znormhisto.Write()
        femvalues.append(femhisto.GetMean())
        zvalues.append(zhisto.GetMean())
        femvalueserror.append(femhisto.GetRMS() / (entries**0.5))
        zvalueserror.append(zhisto.GetRMS() / (entries**0.5))
        znormvalues.append(znormhisto.GetMean())
        znormvalueserror.append(znormhisto.GetRMS() / (entries**0.5))

    containmentgraph = TGraphErrors(len(energies), energies, containment,
                                    zeros, containmenterror)
    containmentgraph.SetName("containment")
    containmentgraph.Write()
    ChiGraph = TGraphErrors(len(energies), energies, chiarray, zeros,
                            chierrorarray)
    ChiGraph.SetName("Chi")
    ChiGraph.Write()
    LinearityGraph2 = TGraphErrors(len(energies), energies, Energy, zeros,
                                   Energyerror)
    LinearityGraph2.SetName("LinearityGraph2")
    LinearityGraph2.Write()
    LinearityGraph = TGraphErrors(len(energies), energies, energyfraction,
                                  zeros, energyfractionerror)
    LinearityGraph.SetName("LinearityGraph")
    LinearityGraph.Write()
    LinearityGraphScin = TGraphErrors(len(energies), energies,
                                      energyfractionscin, zeros,
                                      energyfractionscinerror)
    LinearityGraphCher = TGraphErrors(len(energies), energies,
                                      energyfractioncher, zeros,
                                      energyfractionchererror)
    LinearityGraphCher.SetName("LinearityGraphCher")
    LinearityGraphCher.Write()
    LinearityGraphScin.SetName("LinearityGraphScin")
    LinearityGraphScin.Write()

    ResolutionGraphScin = TGraphErrors(len(energies), sqrtenergies,
                                       resolutionscin, zeros,
                                       resolutionscinerror)
    func = TF1("func", "[0]/(x**0.5)+[1]", 10., 150.)
    ResolutionGraphCher = TGraphErrors(len(energies), sqrtenergies,
                                       resolutioncher, zeros,
                                       resolutionchererror)
    #ResolutionGraphScin.Fit("func", "R")
    #ResolutionGraphCher.Fit("func", "R")
    ResolutionGraphScin.SetName("ResolutionGraphScin")
    ResolutionGraphScin.Write()
    ResolutionGraphCher.SetName("ResolutionGraphCher")
    ResolutionGraphCher.Write()
    ResolutionGraph = TGraphErrors(len(energies), sqrtenergies, resolution,
                                   zeros, resolutionerror)
    #ResolutionGraph.Fit("func", "R")
    ResolutionGraph.SetName("ResolutionGraph")
    ResolutionGraph.Write()

    LinearityGraph.SetMinimum(0.976)  #0.976
    LinearityGraph.SetMaximum(1.024)  #1.024
    LinearityGraph.GetXaxis().SetLimits(0.0, 155.0)
    LinearityGraph.SetTitle("")
    LinearityGraph.GetXaxis().SetLabelSize(.105)
    LinearityGraph.GetYaxis().SetLabelSize(0.105)
    LinearityGraph.GetXaxis().SetNdivisions(520)
    LinearityGraph.GetYaxis().SetNdivisions(504)
    LinearityGraph2.SetTitle("")
    LinearityGraph2.SetMinimum(0.0)
    LinearityGraph2.SetMaximum(155.0)
    LinearityGraph2.GetXaxis().SetLimits(0.0, 155.0)
    LinearityGraph2.GetXaxis().SetLabelSize(0.)
    LinearityGraph2.GetXaxis().SetNdivisions(520)
    LinearityGraph2.GetYaxis().SetNdivisions(520)
    c = TCanvas("c", "canvas", 800, 800)
    # Upper histogram plot is pad1
    pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    pad1.SetBottomMargin(0.02)  # joins upper and lower plot
    pad1.SetLeftMargin(0.1)
    pad1.SetRightMargin(0.1)
    pad1.Draw()
    # Lower ratio plot is pad2
    c.cd()  # returns to main canvas before defining pad2
    pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
    pad2.SetTopMargin(0.05)  # joins upper and lower plot
    pad2.SetBottomMargin(0.3)
    pad2.SetLeftMargin(0.1)
    pad2.SetRightMargin(0.1)
    pad2.Draw()
    pad1.cd()
    LinearityGraph2.Draw()
    pad2.cd()
    LinearityGraph.Draw("AP")
    ratioline = TF1("ratioline", str(np.mean(energyfraction)), 0., 160.)
    ratioline.SetLineColor(1)
    ratioline.SetLineWidth(1)
    ratioline.SetLineStyle(9)
    ratioline.Draw("same")
    ratioline.Write()
    c.Update()
    #c.SaveAs("MLratio.pdf")
    c.Write()

    femgraph = TGraphErrors(len(energies), energies, femvalues, zeros,
                            femvalueserror)
    femgraph.SetName("fem_graph")
    femfit = TF1("femfit", "1.-(x/[0])**([1]-1.)", 10., 150.)
    femgraph.Fit("femfit", "R")
    femgraph.Write()

    zvalues = array('d', [math.log(x) for x in zvalues])
    logenergies = array('d', [math.log(x) for x in energies])
    zgraph = TGraphErrors(len(logenergies), logenergies, zvalues, zeros,
                          zvalueserror)
    zgraph.SetName("z_graph")
    zfit = TF1("zfit", "pol1", 2.2, 5.1)
    zgraph.Fit("zfit", "R")
    zgraph.Write()

    znormgraph = TGraphErrors(len(energies), energies, znormvalues, zeros,
                              znormvalueserror)
    znormgraph.SetName("znorm_graph")
    znormgraph.Write()
    '''	
	Resolutions = TMultiGraph()
	Resolutions.Add(ResolutionGraphScin)
	Resolutions.Add(ResolutionGraphCher)
	Resolutions.Add(ResolutionGraph)
	Resolutions.SetName("EMResolutions")
	Resolutions.Write()

	Linearities = TMultiGraph()
	Linearities.Add(LinearityGraph)
	Linearities.Add(LinearityGraphScin)
	Linearities.Add(LinearityGraphCher)
	Linearities.SetName("Linearities")
	Linearities.Write()
	'''
    return RecEnergyHist.GetFunction("gaus").GetParameter(
        2), RecEnergyHist.GetFunction("gaus").GetParameter(
            1), RecEnergyHist.GetFunction("gaus").GetChisquare()
def main(argv):

    print(len(argv))
    if len(argv) == 6:
        #print ('The script is called: '+str(script))
        print('Your waves are: ' + argv[0])
        print('Number of M bins is: ' + argv[1])
        print('Number of t bins is: ' + argv[2])
        print('Number of bootstrap samples is:' + argv[3])
        print('Directory for bootstrap results for different M bins is: ' +
              argv[4])
        print(
            'Intensity results from fitting the original data are written in: '
            + argv[5])
        if len(argv[0].split()) < 2:
            sys.exit("You should specify more than one amplitude")
    else:
        sys.exit(
            "You need to give 6 args..., usage: python script.py \"S0mi P1pl D1pl ...\" Nmassbins NBootstrapsamples Bindir fitresultfile"
        )

    amps, NumBins, NumtBins, kBootstrapPoints, Binfolderdir, Fitresultfile = argv
    N_amps = len(amps.split())
    NumBins = int(NumBins)
    NumtBins = int(NumtBins)
    kBootstrapPoints = int(kBootstrapPoints)

    ## Output file to save the histograms in
    file_out = TFile('Drawing_Bootstrap_errors.root', 'Recreate')

    ## column number for M value and each of the amplitude intensities and
    ##corresponding errors
    column_m = 0
    column_t = 1
    colomn_Waves = np.arange(2, 2 * N_amps + 1, 2)
    colomn_Waves_err = np.arange(3, 2 * N_amps + 2, 2)
    column_all_Waves = 2 * N_amps + 2
    column_all_Waves_err = 2 * N_amps + 3

    ## Arrays of  intensities from fitting the original data in different M bins
    orig_Wave = np.zeros((N_amps, NumBins))
    orig_all_Waves = np.zeros(NumBins)
    ##Reading uncertainties from MINUIT
    orig_Wave_err_square = np.zeros((N_amps, NumBins))
    orig_all_Waves_err_square = np.zeros(NumBins)

    ## Asigning values to arrays of intensities from fitting the original data in
    ##different M bins by reading from a file
    token_origdata_fitresults = open(Fitresultfile, 'r')
    linestoken_orig = token_origdata_fitresults.readlines()
    j = 0
    fit_res_colomns = 0
    for x in linestoken_orig:

        fit_res_colomns = len(x.split())
        for waves in range(0, N_amps):

            orig_Wave[waves][int(j / NumtBins)] = orig_Wave[waves][int(
                j / NumtBins)] + float(x.split()[colomn_Waves[waves]])
            orig_Wave_err_square[waves][
                j /
                NumtBins] = orig_Wave_err_square[waves][j / NumtBins] + float(
                    x.split()[colomn_Waves_err[waves]]) * float(
                        x.split()[colomn_Waves_err[waves]])
        orig_all_Waves[j / NumtBins] = orig_all_Waves[j / NumtBins] + float(
            x.split()[column_all_Waves])
        orig_all_Waves_err_square[j / NumtBins] = orig_all_Waves_err_square[
            j / NumtBins] + float(x.split()[column_all_Waves_err]) * float(
                x.split()[column_all_Waves_err])
        j = j + 1
    if j != NumBins * NumtBins:
        sys.exit(
            "The total number of bins are different from the one provided")

    orig_Wave_err = np.sqrt(orig_Wave_err_square)
    orig_all_Waves_err = np.sqrt(orig_all_Waves_err_square)

    ## Arrays of intensities for given amplitude from
    ##fitting different bootstrapping samples
    mass = np.zeros(kBootstrapPoints)
    Waves = np.zeros((N_amps, kBootstrapPoints))
    Waves_err = np.zeros((N_amps, kBootstrapPoints))
    all_Waves = np.zeros(kBootstrapPoints)
    all_Waves_err = np.zeros(kBootstrapPoints)

    ## Arrays of mean intensities from bootstrapping for different M bins
    mass_bins = np.zeros(NumBins)

    ## Arrays of std intensities from bootstrapping for different M bins
    std_Waves_square = np.zeros((N_amps, NumBins))
    std_all_Waves_square = np.zeros(NumBins)

    ## Histograms of intensities for given mass bin and amplitude from different bootstraping samples

    h1_list_Waves = []
    h1_list_all = []
    i_Mbin = 0
    for Mb in range(0, NumBins):
        h1_list_Waves.append([])
        h1_list_all.append([])
        for tb in range(0, NumtBins):
            h1_list_Waves[i_Mbin].append([])
        i_Mbin = i_Mbin + 1

    main = []
    #Defining histograms for intensities from different bootstraping samples for a given aplitude and M bin
    for Bin in range(0, NumBins):

        #N_bins=int(300*orig_all_Waves[Bin])
        N_bins = int(80000)
        x_min = int(-500)
        x_max = int(3 * orig_all_Waves[Bin])

        outer = []

        for Bint in range(0, NumtBins):

            inner = []
            for waves in range(0, N_amps):
                h1_list_Waves[Bin][Bint].append(
                    TH1F(
                        'h1_boot_' + str(amps.split()[waves]) + '_Mbin' +
                        str(Bin + 1) + '_tbin' + str(Bint + 1),
                        str(amps.split()[waves]), N_bins, x_min, x_max))
                #inner.append(TH1F('h1_boot_'+str(amps.split()[waves])+'_Mbin'+str(Bin+1)+'_tbin'+str(Bint+1),str(amps.split()[waves]),N_bins,x_min,x_max))
                #hh = TH1F('h1_boot_'+str(amps.split()[waves])+'_Mbin'+str(Bin+1)+'_tbin'+str(Bint+1),str(amps.split()[waves]),N_bins,x_min,x_max)
                #print( "N_bins = " + str(N_bins) + " x_min =  " + str(x_min) + "   x_max = " + str(x_max)  )
                #inner.append(hh)

            h1_list_all[Bin].append(
                TH1F(
                    'h1_boot_All_' + 'Mbin' + str(Bin + 1) + '_tbin' +
                    str(Bint + 1), 'All waves', N_bins, x_min, x_max))

            #outer.append(inner);
        #main.append(outer)

    ## Assigning values to arrays of intensities for given amplitude from fitting different bootstrapping samples
    ## by reading the values from files of each of the M bins
    ##(number of lines in the .txt file corresponds to number of bootstraping samples)
    for bin in range(0, NumBins):
        for bint in range(0, NumtBins):
            token = open(
                Binfolderdir + '/bin_' + str(bin) + '_' + str(bint) +
                '/etapi_fit.txt', 'r')
            linestoken = token.readlines()
            i = 0

            #Looping through lines corresponding to results from fitting different bottstraping samples
            for x in linestoken:

                if len(x.split()) != fit_res_colomns:
                    sys.exit(
                        "Fit results and bootstraping results have different number of waves"
                    )
                mass[i] = x.split()[column_m]

                for waves in range(0, N_amps):
                    Waves[waves][i] = x.split()[colomn_Waves[waves]]
                    Waves_err[waves][i] = x.split()[colomn_Waves_err[waves]]
                    h1_list_Waves[bin][bint][waves].Fill(Waves[waves][i])
                all_Waves[i] = x.split()[column_all_Waves]
                all_Waves_err[i] = x.split()[column_all_Waves_err]
                h1_list_all[bin][bint].Fill(all_Waves[i])

                i = i + 1
            token.close()

            mass_bins[bin] = mass[0]

            for waves in range(0, N_amps):
                std_Waves_square[waves][bin] = std_Waves_square[waves][
                    bin] + Waves[waves].std() * Waves[waves].std()
            std_all_Waves_square[bin] = std_all_Waves_square[
                bin] + all_Waves.std() * all_Waves.std()

    std_Waves = np.sqrt(std_Waves_square)
    std_all_Waves = np.sqrt(std_all_Waves_square)

    print('I am here')

    ##The graphs of intensities of different waves
    error_M = np.zeros(NumBins)
    grerr_list_Wave = []
    for waves in range(0, N_amps):
        grerr_list_Wave.append(
            TGraphErrors(NumBins, mass_bins, orig_Wave[waves], error_M,
                         std_Waves[waves]))

    c1 = TCanvas('c1', 'A Simple Graph with error bars', 200, 10, 700, 500)
    c1.Divide(3, 2)
    c1.SetGrid()
    c1.GetFrame().SetFillColor(21)
    c1.GetFrame().SetBorderSize(12)

    for waves in range(0, N_amps):
        grerr_list_Wave[waves].SetMarkerSize(.5)
        grerr_list_Wave[waves].SetMarkerStyle(20)
        grerr_list_Wave[waves].SetName(amps.split()[waves])
        grerr_list_Wave[waves].SetTitle(amps.split()[waves])
        grerr_list_Wave[waves].SetMaximum(1.2 * np.amax(orig_Wave[waves]))

        grerr_list_Wave[waves].SetMinimum(0.8 * np.amin(orig_Wave[waves]))
        grerr_list_Wave[waves].Draw('AP')
        c1.Print('Wave' + amps.split()[waves] + '.pdf')

    ##The graph of total intensity
    c3 = TCanvas('c3', 'A Simple Graph with error bars', 200, 10, 700, 500)
    c3.Divide(3, 2)
    c3.SetGrid()
    c3.GetFrame().SetFillColor(21)
    c3.GetFrame().SetBorderSize(12)

    gr_all = TGraphErrors(NumBins, mass_bins, orig_all_Waves, error_M,
                          std_all_Waves)
    gr_all.SetMarkerSize(.5)
    gr_all.SetMarkerStyle(20)
    #gr_all.SetMaximum(max(x_max/2.5))
    #gr_all.SetMinimum(min(x_min/5))
    gr_all.SetMaximum(1.2 * np.amax(orig_all_Waves))
    gr_all.SetMinimum(0.8 * np.amin(orig_all_Waves))
    gr_all.SetTitle('All waves')
    gr_all.Draw('AP')
    c3.Print("All_waves.pdf")

    ## Plotting with MINUIT uncertainties

    grerr_list_Wave_minuit = []
    for waves in range(0, N_amps):
        grerr_list_Wave_minuit.append(
            TGraphErrors(NumBins, mass_bins, orig_Wave[waves], error_M,
                         orig_Wave_err[waves]))

    c4 = TCanvas('c4', 'A Simple Graph with error bars', 200, 10, 700, 500)
    #c4.Divide(3,2)
    c4.SetGrid()
    c4.GetFrame().SetFillColor(21)
    c4.GetFrame().SetBorderSize(12)

    for waves in range(0, N_amps):
        grerr_list_Wave_minuit[waves].SetMarkerSize(.5)
        grerr_list_Wave_minuit[waves].SetMarkerStyle(20)
        grerr_list_Wave_minuit[waves].SetName(amps.split()[waves])
        grerr_list_Wave_minuit[waves].SetTitle(amps.split()[waves])
        grerr_list_Wave_minuit[waves].SetMaximum(1.2 *
                                                 np.amax(orig_Wave[waves]))
        grerr_list_Wave_minuit[waves].SetMinimum(0.8 *
                                                 np.amin(orig_Wave[waves]))
        grerr_list_Wave_minuit[waves].Draw('AP')
        c4.Print('Wave' + amps.split()[waves] + 'minuit.pdf')

    ##The graph of total intensity
    c5 = TCanvas('c5', 'A Simple Graph with error bars', 200, 10, 700, 500)
    #c5.Divide(3,2)
    c5.SetGrid()
    c5.GetFrame().SetFillColor(21)
    c5.GetFrame().SetBorderSize(12)

    gr_all_minuit = TGraphErrors(NumBins, mass_bins, orig_all_Waves, error_M,
                                 orig_all_Waves_err)
    gr_all_minuit.SetMarkerSize(.5)
    gr_all_minuit.SetMarkerStyle(20)
    #gr_all_minuit .SetMaximum(max(x_max/2.5))
    #gr_all_minuit .SetMinimum(min(x_min/5))
    gr_all_minuit.SetMaximum(1.2 * np.amax(orig_all_Waves))
    gr_all_minuit.SetMinimum(0.8 * np.amin(orig_all_Waves))
    gr_all_minuit.SetTitle('All waves')
    gr_all_minuit.Draw('AP')
    c3.Print("All_waves_minuit.pdf")

    file_out.Write()
    file_out.Close()
Ejemplo n.º 12
0
            listdndetafitrun5[i].GetParameter(2) * scalefactor)
    listdndetafitrun5[i].FixParameter(3, \
            listdndetafitrun5[i].GetParameter(3) * scalefactor)
    listdndetafitrun5[i].FixParameter(6, \
            listdndetafitrun5[i].GetParameter(6) * scalefactor)
    listdndetafitrun5[i].SetTitle(";dN^{ch}/d#eta;#eta;")
    listdndetafitrun5[i].Write()
    for index, etap in enumerate(dndeta_points):
        print("species=", species)
        print("dndeta at eta=%f" % etap +
              ", val =%.2f" % listdndetafitrun5[i].Eval(etap))
    print("dndeta at -4<eta<4, val =%.2f" % \
          listdndetafitrun5[i].Integral(dndeta_points_min, dndeta_points_max))

c3 = TCanvas("c3", "A Simple Graph with error bars", 200, 10, 700, 500)
gPad.SetLogy()
graphpbpb05_sym.Draw("ALP")
graphpbpb05_sym.SetMinimum(10.)
graphpbpb05_sym.SetMaximum(50000.)
leg = TLegend(.1, .7, .3, .9, "")
leg.AddEntry(graphpbpb05_sym, "XeXe 0-5% data")
for i, species in enumerate(speciesrun5):
    listdndetafitrun5[i].SetLineColor(colorrun5[i])
    leg.AddEntry(listdndetafitrun5[i], "Extrapolation %s at %.2f TeV" % \
                 (speciesrun5[i], energyrun5[i]))
    listdndetafitrun5[i].Draw("SAME")
    print("booo", listdndetafitrun5[i].Eval(0.))
leg.Draw()
c3.SaveAs("dndetapbpb_multiplespecies.pdf")
c3.SaveAs("dndetapbpb_multiplespecies.png")
Ejemplo n.º 13
0
def makePlots():
    outputFile_name = 'PUbins_{0}.ps'.format(label)
    canvas = TCanvas("canvas", "canvas")
    canvas.Print(outputFile_name + "[")

    lowEdgesOfBins = [0, 11, 14, 18, 40]

    lowEdgesOfBins.pop()  # toglie 40. dalla lista cosi` ho solo gli inizi

    PU_cuts_labels = []
    PU_cuts_labels.append('# PV #leq {}'.format(lowEdgesOfBins[1]))
    for i in range(1, len(lowEdgesOfBins) - 1):
        PU_cuts_labels.append('{} < # PV #leq {}'.format(
            lowEdgesOfBins[i], lowEdgesOfBins[i + 1]))
    PU_cuts_labels.append('# PV > {}'.format(
        lowEdgesOfBins[len(lowEdgesOfBins) - 1]))

    PU_cuts = []
    PU_cuts.append('numPrimaryVertices <= {}'.format(lowEdgesOfBins[1]))
    for i in range(1, len(lowEdgesOfBins) - 1):
        PU_cuts.append(
            'numPrimaryVertices > {} && numPrimaryVertices <= {}'.format(
                lowEdgesOfBins[i], lowEdgesOfBins[i + 1]))
    PU_cuts.append('numPrimaryVertices > {}'.format(
        lowEdgesOfBins[len(lowEdgesOfBins) - 1]))

    cuts = Cuts()
    cuts = cuts.loadFromFile("../cuts.txt")

    Chib1_parameters, canvas = doMCFit(inputfile_name=rootupla_Chib1_Sel,
                                       mass_chib=mass_chib1_1P,
                                       output_name='ChiB1',
                                       cuts=cuts,
                                       plotTitle='#chi_{b1}',
                                       fittedVariable=fittedVariable)
    canvas.Print(outputFile_name)
    Chib2_parameters, canvas = doMCFit(inputfile_name=rootupla_Chib2_Sel,
                                       mass_chib=mass_chib2_1P,
                                       output_name='ChiB2',
                                       cuts=cuts,
                                       plotTitle='#chi_{b2}',
                                       fittedVariable=fittedVariable)
    canvas.Print(outputFile_name)

    print "Creating DataSet from file " + str(rootupla_2012Data)
    dataSet = makeRooDataset(rootupla_2012Data)

    y = []
    ey = []

    for i in range(len(lowEdgesOfBins)):
        cuts.str_cut = '&& ' + PU_cuts[i]
        plotTitle_add = PU_cuts_labels[i]
        numChib, canvas = doDataFit(RooDataSet=dataSet,
                                    Chib1_parameters=Chib1_parameters,
                                    Chib2_parameters=Chib2_parameters,
                                    cuts=cuts,
                                    plotTitle='#chi_{b}(1P)' + plotTitle_add,
                                    fittedVariable=fittedVariable)
        canvas.Print(outputFile_name)
        #canvas.Print('imgPU/{}_PU{}.png'.format(label,i+1))
        y.append(numChib.calcRatio())
        ey.append(numChib.calcRatioError())

    lowEdgesOfBins = lowEdgesOfBins + [40]
    x = array('d', [(lowEdgesOfBins[i - 1] + lowEdgesOfBins[i]) / 2.
                    for i in range(1, len(lowEdgesOfBins))])
    ex = array('d', [(x[i - 1] - lowEdgesOfBins[i - 1])
                     for i in range(1, len(lowEdgesOfBins))])

    y = array('d', y)
    ey = array('d', ey)

    h_ratios = TGraphErrors(len(x), x, y, ex, ey)
    h_ratios.SetTitle(
        'Ratio #chi_{b2}/#chi_{b1};Number of primary vertices;N_{2}/N_{1}')

    gStyle.SetOptStat(0)
    h_ratios.SetMinimum(0)
    h_ratios.SetMaximum(1)
    h_ratios.Draw()
    canvas.Print(outputFile_name)
    # #canvas.Print('imgPU/{0}_PU.pdf'.format(label))
    # canvas.Print('imgPU/{0}_PU.root'.format(label))
    h_ratios.SaveAs('imgPU/{0}_PU.root'.format(label))

    canvas.Print(outputFile_name + "]")
Ejemplo n.º 14
0
def signal(category):

    interPar = True
    n = len(genPoints)

    cColor = color[category] if category in color else 4
    nBtag = category.count('b')
    isAH = False  #relict from using Alberto's more complex script

    if not os.path.exists(PLOTDIR + "MC_signal_" + YEAR):
        os.makedirs(PLOTDIR + "MC_signal_" + YEAR)

    #*******************************************************#
    #                                                       #
    #              Variables and selections                 #
    #                                                       #
    #*******************************************************#

    X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV")
    j1_pt = RooRealVar("jpt_1", "jet1 pt", 0., 13000., "GeV")
    jj_deltaEta = RooRealVar("jj_deltaEta_widejet", "", 0., 5.)
    jbtag_WP_1 = RooRealVar("jbtag_WP_1", "", -1., 4.)
    jbtag_WP_2 = RooRealVar("jbtag_WP_2", "", -1., 4.)
    fatjetmass_1 = RooRealVar("fatjetmass_1", "", -1., 2500.)
    fatjetmass_2 = RooRealVar("fatjetmass_2", "", -1., 2500.)
    jid_1 = RooRealVar("jid_1", "j1 ID", -1., 8.)
    jid_2 = RooRealVar("jid_2", "j2 ID", -1., 8.)
    jnmuons_1 = RooRealVar("jnmuons_1", "j1 n_{#mu}", -1., 8.)
    jnmuons_2 = RooRealVar("jnmuons_2", "j2 n_{#mu}", -1., 8.)
    jnmuons_loose_1 = RooRealVar("jnmuons_loose_1", "jnmuons_loose_1", -1., 8.)
    jnmuons_loose_2 = RooRealVar("jnmuons_loose_2", "jnmuons_loose_2", -1., 8.)
    nmuons = RooRealVar("nmuons", "n_{#mu}", -1., 10.)
    nelectrons = RooRealVar("nelectrons", "n_{e}", -1., 10.)
    HLT_AK8PFJet500 = RooRealVar("HLT_AK8PFJet500", "", -1., 1.)
    HLT_PFJet500 = RooRealVar("HLT_PFJet500", "", -1., 1.)
    HLT_CaloJet500_NoJetID = RooRealVar("HLT_CaloJet500_NoJetID", "", -1., 1.)
    HLT_PFHT900 = RooRealVar("HLT_PFHT900", "", -1., 1.)
    HLT_AK8PFJet550 = RooRealVar("HLT_AK8PFJet550", "", -1., 1.)
    HLT_PFJet550 = RooRealVar("HLT_PFJet550", "", -1., 1.)
    HLT_CaloJet550_NoJetID = RooRealVar("HLT_CaloJet550_NoJetID", "", -1., 1.)
    HLT_PFHT1050 = RooRealVar("HLT_PFHT1050", "", -1., 1.)
    #HLT_DoublePFJets100_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets100_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1. )
    #HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1. )
    #HLT_DoublePFJets200_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets200_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets350_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets350_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets40_CaloBTagDeepCSV_p71                  =RooRealVar("HLT_DoublePFJets40_CaloBTagDeepCSV_p71"                 , "", -1., 1. )

    weight = RooRealVar("eventWeightLumi", "", -1.e9, 1.e9)

    # Define the RooArgSet which will include all the variables defined before
    # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add'
    variables = RooArgSet(X_mass)
    variables.add(
        RooArgSet(j1_pt, jj_deltaEta, jbtag_WP_1, jbtag_WP_2, fatjetmass_1,
                  fatjetmass_2, jnmuons_1, jnmuons_2, weight))
    variables.add(
        RooArgSet(nmuons, nelectrons, jid_1, jid_2, jnmuons_loose_1,
                  jnmuons_loose_2))
    variables.add(
        RooArgSet(HLT_AK8PFJet500, HLT_PFJet500, HLT_CaloJet500_NoJetID,
                  HLT_PFHT900, HLT_AK8PFJet550, HLT_PFJet550,
                  HLT_CaloJet550_NoJetID, HLT_PFHT1050))
    #variables.add(RooArgSet(HLT_DoublePFJets100_CaloBTagDeepCSV_p71, HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71, HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71, HLT_DoublePFJets200_CaloBTagDeepCSV_p71, HLT_DoublePFJets350_CaloBTagDeepCSV_p71, HLT_DoublePFJets40_CaloBTagDeepCSV_p71))
    X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_integration_range", X_mass.getMin(), X_mass.getMax())

    if VARBINS:
        binsXmass = RooBinning(len(abins) - 1, abins)
        X_mass.setBinning(binsXmass)
        plot_binning = RooBinning(
            int((X_mass.getMax() - X_mass.getMin()) / 100.), X_mass.getMin(),
            X_mass.getMax())
    else:
        X_mass.setBins(int((X_mass.getMax() - X_mass.getMin()) / 10))
        binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin()) / 100.),
                               X_mass.getMin(), X_mass.getMax())
        plot_binning = binsXmass

    X_mass.setBinning(plot_binning, "PLOT")

    #X_mass.setBins(int((X_mass.getMax() - X_mass.getMin())/10))
    #binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax())
    #X_mass.setBinning(binsXmass, "PLOT")
    massArg = RooArgSet(X_mass)

    # Cuts
    if BTAGGING == 'semimedium':
        SRcut = aliasSM[category]
        #SRcut = aliasSM[category+"_vetoAK8"]
    else:
        SRcut = alias[category].format(WP=working_points[BTAGGING])
        #SRcut = alias[category+"_vetoAK8"].format(WP=working_points[BTAGGING])

    if ADDSELECTION: SRcut += SELECTIONS[options.selection]

    print "  Cut:\t", SRcut

    #*******************************************************#
    #                                                       #
    #                    Signal fits                        #
    #                                                       #
    #*******************************************************#

    treeSign = {}
    setSignal = {}

    vmean = {}
    vsigma = {}
    valpha1 = {}
    vslope1 = {}
    valpha2 = {}
    vslope2 = {}
    smean = {}
    ssigma = {}
    salpha1 = {}
    sslope1 = {}
    salpha2 = {}
    sslope2 = {}
    sbrwig = {}
    signal = {}
    signalExt = {}
    signalYield = {}
    signalIntegral = {}
    signalNorm = {}
    signalXS = {}
    frSignal = {}
    frSignal1 = {}
    frSignal2 = {}
    frSignal3 = {}

    # Signal shape uncertainties (common amongst all mass points)
    xmean_jes = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p1_scale_jes",
        "Variation of the resonance position with the jet energy scale", 0.02,
        -1., 1.)  #0.001
    smean_jes = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p1_jes",
        "Change of the resonance position with the jet energy scale", 0., -10,
        10)

    xsigma_jer = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p2_scale_jer",
        "Variation of the resonance width with the jet energy resolution",
        0.10, -1., 1.)
    ssigma_jer = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p2_jer",
        "Change of the resonance width with the jet energy resolution", 0.,
        -10, 10)

    xmean_jes.setConstant(True)
    smean_jes.setConstant(True)

    xsigma_jer.setConstant(True)
    ssigma_jer.setConstant(True)

    for m in massPoints:

        signalMass = "%s_M%d" % (stype, m)
        signalName = "ZpBB_{}_{}_M{}".format(YEAR, category, m)
        sampleName = "ZpBB_M{}".format(m)

        signalColor = sample[sampleName][
            'linecolor'] if signalName in sample else 1

        # define the signal PDF
        vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m,
                              m * 0.96, m * 1.05)
        smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)",
                                 RooArgList(vmean[m], xmean_jes, smean_jes))

        vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma",
                               m * 0.0233, m * 0.019, m * 0.025)
        ssigma[m] = RooFormulaVar(
            signalName + "_sigma", "@0*(1+@1*@2)",
            RooArgList(vsigma[m], xsigma_jer, ssigma_jer))

        valpha1[m] = RooRealVar(
            signalName + "_valpha1", "Crystal Ball alpha 1", 0.2, 0.05, 0.28
        )  # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0",
                                   RooArgList(valpha1[m]))

        #vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope 1", 10., 0.1, 20.) # slope of the power tail
        vslope1[m] = RooRealVar(signalName + "_vslope1",
                                "Crystal Ball slope 1", 13., 10.,
                                20.)  # slope of the power tail
        sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0",
                                   RooArgList(vslope1[m]))

        valpha2[m] = RooRealVar(signalName + "_valpha2",
                                "Crystal Ball alpha 2", 1.)
        valpha2[m].setConstant(True)
        salpha2[m] = RooFormulaVar(signalName + "_alpha2", "@0",
                                   RooArgList(valpha2[m]))

        #vslope2[m] = RooRealVar(signalName + "_vslope2", "Crystal Ball slope 2", 6., 2.5, 15.) # slope of the higher power tail
        ## FIXME test FIXME
        vslope2_estimation = -5.88111436852 + m * 0.00728809389442 + m * m * (
            -1.65059568762e-06) + m * m * m * (1.25128996309e-10)
        vslope2[m] = RooRealVar(signalName + "_vslope2",
                                "Crystal Ball slope 2", vslope2_estimation,
                                vslope2_estimation * 0.9, vslope2_estimation *
                                1.1)  # slope of the higher power tail
        ## FIXME end FIXME
        sslope2[m] = RooFormulaVar(
            signalName + "_slope2", "@0",
            RooArgList(vslope2[m]))  # slope of the higher power tail

        signal[m] = RooDoubleCrystalBall(signalName,
                                         "m_{%s'} = %d GeV" % ('X', m), X_mass,
                                         smean[m], ssigma[m], salpha1[m],
                                         sslope1[m], salpha2[m], sslope2[m])

        # extend the PDF with the yield to perform an extended likelihood fit
        signalYield[m] = RooRealVar(signalName + "_yield", "signalYield", 50,
                                    0., 1.e15)
        signalNorm[m] = RooRealVar(signalName + "_norm", "signalNorm", 1., 0.,
                                   1.e15)
        signalXS[m] = RooRealVar(signalName + "_xs", "signalXS", 1., 0., 1.e15)
        signalExt[m] = RooExtendPdf(signalName + "_ext", "extended p.d.f",
                                    signal[m], signalYield[m])

        # ---------- if there is no simulated signal, skip this mass point ----------
        if m in genPoints:
            if VERBOSE: print " - Mass point", m

            # define the dataset for the signal applying the SR cuts
            treeSign[m] = TChain("tree")

            if YEAR == 'run2':
                pd = sample[sampleName]['files']
                if len(pd) > 3:
                    print "multiple files given than years for a single masspoint:", pd
                    sys.exit()
                for ss in pd:
                    if not '2016' in ss and not '2017' in ss and not '2018' in ss:
                        print "unknown year given in:", ss
                        sys.exit()
            else:
                pd = [x for x in sample[sampleName]['files'] if YEAR in x]
                if len(pd) > 1:
                    print "multiple files given for a single masspoint/year:", pd
                    sys.exit()

            for ss in pd:

                if options.unskimmed:
                    j = 0
                    while True:
                        if os.path.exists(NTUPLEDIR + ss + "/" + ss +
                                          "_flatTuple_{}.root".format(j)):
                            treeSign[m].Add(NTUPLEDIR + ss + "/" + ss +
                                            "_flatTuple_{}.root".format(j))
                            j += 1
                        else:
                            print "found {} files for sample:".format(j), ss
                            break
                else:
                    if os.path.exists(NTUPLEDIR + ss + ".root"):
                        treeSign[m].Add(NTUPLEDIR + ss + ".root")
                    else:
                        print "found no file for sample:", ss

            if treeSign[m].GetEntries() <= 0.:
                if VERBOSE:
                    print " - 0 events available for mass", m, "skipping mass point..."
                signalNorm[m].setVal(-1)
                vmean[m].setConstant(True)
                vsigma[m].setConstant(True)
                salpha1[m].setConstant(True)
                sslope1[m].setConstant(True)
                salpha2[m].setConstant(True)
                sslope2[m].setConstant(True)
                signalNorm[m].setConstant(True)
                signalXS[m].setConstant(True)
                continue

            #setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar("eventWeightLumi*BTagAK4Weight_deepJet"), RooFit.Import(treeSign[m]))
            setSignal[m] = RooDataSet("setSignal_" + signalName, "setSignal",
                                      variables, RooFit.Cut(SRcut),
                                      RooFit.WeightVar(weight),
                                      RooFit.Import(treeSign[m]))
            if VERBOSE:
                print " - Dataset with", setSignal[m].sumEntries(
                ), "events loaded"

            # FIT
            entries = setSignal[m].sumEntries()
            if entries < 0. or entries != entries: entries = 0
            signalYield[m].setVal(entries)
            # Instead of eventWeightLumi
            #signalYield[m].setVal(entries * LUMI / (300000 if YEAR=='run2' else 100000) )

            if treeSign[m].GetEntries(SRcut) > 5:
                if VERBOSE: print " - Running fit"
                frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1),
                                                 RooFit.Extended(True),
                                                 RooFit.SumW2Error(True),
                                                 RooFit.PrintLevel(-1))
                if VERBOSE:
                    print "********** Fit result [", m, "] **", category, "*" * 40, "\n", frSignal[
                        m].Print(), "\n", "*" * 80
                if VERBOSE: frSignal[m].correlationMatrix().Print()
                drawPlot(signalMass + "_" + category, stype + category, X_mass,
                         signal[m], setSignal[m], frSignal[m])

            else:
                print "  WARNING: signal", stype, "and mass point", m, "in category", category, "has 0 entries or does not exist"

            # Remove HVT cross sections
            #xs = getCrossSection(stype, channel, m)
            xs = 1.
            signalXS[m].setVal(xs * 1000.)

            signalIntegral[m] = signalExt[m].createIntegral(
                massArg, RooFit.NormSet(massArg),
                RooFit.Range("X_integration_range"))
            boundaryFactor = signalIntegral[m].getVal()
            if boundaryFactor < 0. or boundaryFactor != boundaryFactor:
                boundaryFactor = 0
            if VERBOSE:
                print " - Fit normalization vs integral:", signalYield[
                    m].getVal(), "/", boundaryFactor, "events"
            signalNorm[m].setVal(boundaryFactor * signalYield[m].getVal() /
                                 signalXS[m].getVal()
                                 )  # here normalize to sigma(X) x Br = 1 [fb]

        vmean[m].setConstant(True)
        vsigma[m].setConstant(True)
        valpha1[m].setConstant(True)
        vslope1[m].setConstant(True)
        valpha2[m].setConstant(True)
        vslope2[m].setConstant(True)
        signalNorm[m].setConstant(True)
        signalXS[m].setConstant(True)

    #*******************************************************#
    #                                                       #
    #                 Signal interpolation                  #
    #                                                       #
    #*******************************************************#

    ### FIXME FIXME just for a test FIXME FIXME

    #print
    #print
    #print "slope2 fit results:"
    #print
    #y_vals = []
    #for m in genPoints:
    #    y_vals.append(vslope2[m].getVal())
    #print "m =", genPoints
    #print "y =", y_vals
    #sys.exit()

    ### FIXME FIXME test end FIXME FIXME

    # ====== CONTROL PLOT ======
    color_scheme = [
        636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635,
        634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633,
        632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633
    ]
    c_signal = TCanvas("c_signal", "c_signal", 800, 600)
    c_signal.cd()
    frame_signal = X_mass.frame()
    for j, m in enumerate(genPoints):
        if m in signalExt.keys():
            #print "color:",(j%9)+1
            #print "signalNorm[m].getVal() =", signalNorm[m].getVal()
            #print "RooAbsReal.NumEvent =", RooAbsReal.NumEvent
            signal[m].plotOn(
                frame_signal, RooFit.LineColor(color_scheme[j]),
                RooFit.Normalization(signalNorm[m].getVal(),
                                     RooAbsReal.NumEvent),
                RooFit.Range("X_reasonable_range"))
    frame_signal.GetXaxis().SetRangeUser(0, 10000)
    frame_signal.Draw()
    drawCMS(-1, "Simulation Preliminary", year=YEAR)
    #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True)
    #drawCMS(-1, "", year=YEAR, suppressCMS=True)
    drawAnalysis(category)
    drawRegion(category)

    c_signal.SaveAs(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" +
                    category + "_Signal.pdf")
    c_signal.SaveAs(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" +
                    category + "_Signal.png")
    #if VERBOSE: raw_input("Press Enter to continue...")
    # ====== CONTROL PLOT ======

    # Normalization
    gnorm = TGraphErrors()
    gnorm.SetTitle(";m_{X} (GeV);integral (GeV)")
    gnorm.SetMarkerStyle(20)
    gnorm.SetMarkerColor(1)
    gnorm.SetMaximum(0)
    inorm = TGraphErrors()
    inorm.SetMarkerStyle(24)
    fnorm = TF1("fnorm", "pol9", 700, 3000)
    fnorm.SetLineColor(920)
    fnorm.SetLineStyle(7)
    fnorm.SetFillColor(2)
    fnorm.SetLineColor(cColor)

    # Mean
    gmean = TGraphErrors()
    gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)")
    gmean.SetMarkerStyle(20)
    gmean.SetMarkerColor(cColor)
    gmean.SetLineColor(cColor)
    imean = TGraphErrors()
    imean.SetMarkerStyle(24)
    fmean = TF1("fmean", "pol1", 0, 10000)
    fmean.SetLineColor(2)
    fmean.SetFillColor(2)

    # Width
    gsigma = TGraphErrors()
    gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)")
    gsigma.SetMarkerStyle(20)
    gsigma.SetMarkerColor(cColor)
    gsigma.SetLineColor(cColor)
    isigma = TGraphErrors()
    isigma.SetMarkerStyle(24)
    fsigma = TF1("fsigma", "pol1", 0, 10000)
    fsigma.SetLineColor(2)
    fsigma.SetFillColor(2)

    # Alpha1
    galpha1 = TGraphErrors()
    galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha")
    galpha1.SetMarkerStyle(20)
    galpha1.SetMarkerColor(cColor)
    galpha1.SetLineColor(cColor)
    ialpha1 = TGraphErrors()
    ialpha1.SetMarkerStyle(24)
    falpha1 = TF1("falpha", "pol1", 0, 10000)  #pol0
    falpha1.SetLineColor(2)
    falpha1.SetFillColor(2)

    # Slope1
    gslope1 = TGraphErrors()
    gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)")
    gslope1.SetMarkerStyle(20)
    gslope1.SetMarkerColor(cColor)
    gslope1.SetLineColor(cColor)
    islope1 = TGraphErrors()
    islope1.SetMarkerStyle(24)
    fslope1 = TF1("fslope", "pol1", 0, 10000)  #pol0
    fslope1.SetLineColor(2)
    fslope1.SetFillColor(2)

    # Alpha2
    galpha2 = TGraphErrors()
    galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha")
    galpha2.SetMarkerStyle(20)
    galpha2.SetMarkerColor(cColor)
    galpha2.SetLineColor(cColor)
    ialpha2 = TGraphErrors()
    ialpha2.SetMarkerStyle(24)
    falpha2 = TF1("falpha", "pol1", 0, 10000)  #pol0
    falpha2.SetLineColor(2)
    falpha2.SetFillColor(2)

    # Slope2
    gslope2 = TGraphErrors()
    gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)")
    gslope2.SetMarkerStyle(20)
    gslope2.SetMarkerColor(cColor)
    gslope2.SetLineColor(cColor)
    islope2 = TGraphErrors()
    islope2.SetMarkerStyle(24)
    fslope2 = TF1("fslope", "pol1", 0, 10000)  #pol0
    fslope2.SetLineColor(2)
    fslope2.SetFillColor(2)

    n = 0
    for i, m in enumerate(genPoints):
        if not m in signalNorm.keys(): continue
        if signalNorm[m].getVal() < 1.e-6: continue

        if gnorm.GetMaximum() < signalNorm[m].getVal():
            gnorm.SetMaximum(signalNorm[m].getVal())
        gnorm.SetPoint(n, m, signalNorm[m].getVal())
        #gnorm.SetPointError(i, 0, signalNorm[m].getVal()/math.sqrt(treeSign[m].GetEntriesFast()))
        gmean.SetPoint(n, m, vmean[m].getVal())
        gmean.SetPointError(n, 0,
                            min(vmean[m].getError(), vmean[m].getVal() * 0.02))
        gsigma.SetPoint(n, m, vsigma[m].getVal())
        gsigma.SetPointError(
            n, 0, min(vsigma[m].getError(), vsigma[m].getVal() * 0.05))
        galpha1.SetPoint(n, m, valpha1[m].getVal())
        galpha1.SetPointError(
            n, 0, min(valpha1[m].getError(), valpha1[m].getVal() * 0.10))
        gslope1.SetPoint(n, m, vslope1[m].getVal())
        gslope1.SetPointError(
            n, 0, min(vslope1[m].getError(), vslope1[m].getVal() * 0.10))
        galpha2.SetPoint(n, m, salpha2[m].getVal())
        galpha2.SetPointError(
            n, 0, min(valpha2[m].getError(), valpha2[m].getVal() * 0.10))
        gslope2.SetPoint(n, m, sslope2[m].getVal())
        gslope2.SetPointError(
            n, 0, min(vslope2[m].getError(), vslope2[m].getVal() * 0.10))
        #tmpVar = w.var(var+"_"+signalString)
        #print m, tmpVar.getVal(), tmpVar.getError()
        n = n + 1

    gmean.Fit(fmean, "Q0", "SAME")
    gsigma.Fit(fsigma, "Q0", "SAME")
    galpha1.Fit(falpha1, "Q0", "SAME")
    gslope1.Fit(fslope1, "Q0", "SAME")
    galpha2.Fit(falpha2, "Q0", "SAME")
    gslope2.Fit(fslope2, "Q0", "SAME")
    #    gnorm.Fit(fnorm, "Q0", "", 700, 5000)
    #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S"))
    #gnorm.Fit(fnorm, "Q", "SAME", 700, 6000)
    gnorm.Fit(fnorm, "Q", "SAME", 1800, 8000)  ## adjusted recently

    for m in massPoints:

        if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.)

        # Interpolation method
        syield = gnorm.Eval(m)
        spline = gnorm.Eval(m, 0, "S")
        sfunct = fnorm.Eval(m)

        #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield))
        delta = abs(1. - spline / sfunct) if sfunct > 0 else 0
        syield = spline

        if interPar:
            #jmean = gmean.Eval(m)
            #jsigma = gsigma.Eval(m)
            #jalpha1 = galpha1.Eval(m)
            #jslope1 = gslope1.Eval(m)
            #jalpha2 = galpha2.Eval(m)
            #jslope2 = gslope2.Eval(m)
            jmean = gmean.Eval(m, 0, "S")
            jsigma = gsigma.Eval(m, 0, "S")
            jalpha1 = galpha1.Eval(m, 0, "S")
            jslope1 = gslope1.Eval(m, 0, "S")
            jalpha2 = galpha2.Eval(m, 0, "S")
            jslope2 = gslope2.Eval(m, 0, "S")

        else:
            jmean = fmean.GetParameter(
                0) + fmean.GetParameter(1) * m + fmean.GetParameter(2) * m * m
            jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(
                1) * m + fsigma.GetParameter(2) * m * m
            jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(
                1) * m + falpha1.GetParameter(2) * m * m
            jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(
                1) * m + fslope1.GetParameter(2) * m * m
            jalpha2 = falpha2.GetParameter(0) + falpha2.GetParameter(
                1) * m + falpha2.GetParameter(2) * m * m
            jslope2 = fslope2.GetParameter(0) + fslope2.GetParameter(
                1) * m + fslope2.GetParameter(2) * m * m

        inorm.SetPoint(inorm.GetN(), m, syield)
        signalNorm[m].setVal(max(0., syield))

        imean.SetPoint(imean.GetN(), m, jmean)
        if jmean > 0: vmean[m].setVal(jmean)

        isigma.SetPoint(isigma.GetN(), m, jsigma)
        if jsigma > 0: vsigma[m].setVal(jsigma)

        ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1)
        if not jalpha1 == 0: valpha1[m].setVal(jalpha1)

        islope1.SetPoint(islope1.GetN(), m, jslope1)
        if jslope1 > 0: vslope1[m].setVal(jslope1)

        ialpha2.SetPoint(ialpha2.GetN(), m, jalpha2)
        if not jalpha2 == 0: valpha2[m].setVal(jalpha2)

        islope2.SetPoint(islope2.GetN(), m, jslope2)
        if jslope2 > 0: vslope2[m].setVal(jslope2)

        #### newly introduced, not yet sure if helpful:
        vmean[m].removeError()
        vsigma[m].removeError()
        valpha1[m].removeError()
        valpha2[m].removeError()
        vslope1[m].removeError()
        vslope2[m].removeError()

        #signalNorm[m].setConstant(False)  ## newly put here to ensure it's freely floating in the combine fit

    #c1 = TCanvas("c1", "Crystal Ball", 1200, 1200) #if not isAH else 1200
    #c1.Divide(2, 3)
    c1 = TCanvas("c1", "Crystal Ball", 1800, 800)
    c1.Divide(3, 2)
    c1.cd(1)
    gmean.SetMinimum(0.)
    gmean.Draw("APL")
    imean.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    c1.cd(2)
    gsigma.SetMinimum(0.)
    gsigma.Draw("APL")
    isigma.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    c1.cd(3)
    galpha1.Draw("APL")
    ialpha1.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    galpha1.GetYaxis().SetRangeUser(0., 1.1)  #adjusted upper limit from 5 to 2
    c1.cd(4)
    gslope1.Draw("APL")
    islope1.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    gslope1.GetYaxis().SetRangeUser(0.,
                                    150.)  #adjusted upper limit from 125 to 60
    if True:  #isAH:
        c1.cd(5)
        galpha2.Draw("APL")
        ialpha2.Draw("P, SAME")
        drawRegion(category)
        drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
        galpha2.GetYaxis().SetRangeUser(0., 2.)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(category)
        drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
        gslope2.GetYaxis().SetRangeUser(0., 20.)

    c1.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalShape.pdf")
    c1.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalShape.png")

    c2 = TCanvas("c2", "Signal Efficiency", 800, 600)
    c2.cd(1)
    gnorm.SetMarkerColor(cColor)
    gnorm.SetMarkerStyle(20)
    gnorm.SetLineColor(cColor)
    gnorm.SetLineWidth(2)
    gnorm.Draw("APL")
    inorm.Draw("P, SAME")
    gnorm.GetXaxis().SetRangeUser(genPoints[0] - 100, genPoints[-1] + 100)
    gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum() * 1.25)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)
    #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True)
    #drawCMS(-1, "", year=YEAR, suppressCMS=True)
    drawAnalysis(category)
    drawRegion(category)
    c2.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalNorm.pdf")
    c2.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalNorm.png")

    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    # create workspace
    w = RooWorkspace("Zprime_" + YEAR, "workspace")
    for m in massPoints:
        getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName()))
        getattr(w, "import")(signalNorm[m],
                             RooFit.Rename(signalNorm[m].GetName()))
        getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName()))
    w.writeToFile(WORKDIR + "MC_signal_%s_%s.root" % (YEAR, category), True)
    print "Workspace", WORKDIR + "MC_signal_%s_%s.root" % (
        YEAR, category), "saved successfully"
Ejemplo n.º 15
0
def main():
    gStyle.SetOptStat(0)
    BIAS_DIR = global_paths.BIASDIR+args.btagging+"/"
    if args.year == 'run2c':
        BIAS_DIR += "combined_run2/"
        #BIAS_DIR += "combined_run2_signal{}/"
        ## individual plots stored in run2c_masspoints    
    
    ## extract pulls
    pulls = TGraphErrors()
    for m in range(1600,8001,100):
        #try:
            pull0=int(PULL0[m])
            #pull0=10.

            #tfile = TFile.Open(BIAS_DIR+"fitDiagnostics_M{mass}.root".format(mass=m), "READ")
            #tfile = TFile.Open(BIAS_DIR.format(pull0)+"fitDiagnostics_M{mass}.root".format(mass=m), "READ")
            #tree = tfile.Get("tree_fit_sb")
            tree = TChain("tree_fit_sb")
            for seed in ['123456', '234567', '345678', '456789', '567891', '678912', '789123', '891234', '912345', '123459']:
                tree.Add(BIAS_DIR+"fitDiagnostics_M{mass}_{seed}.root".format(mass=m, seed=seed))
 
            ## the method proposed in the documemtation
            #hist = TH1D("hist", "hist", 20, -5, 5)
            #tree.Project("hist", "(r-1)/(0.5*(rHiErr+rLoErr))")
            #fit_func = TF1("gaussfit","gaus" , -5., 5.)
            #hist.Fit(fit_func, "E")
            #pulls.SetPoint(pulls.GetN(), m, fit_func.GetParameter(1)) ## get mean of gaussian fit
            
            ## Alberto's method
            #hist = TH1D("s_pulls", ";%s/#sigma_{r};Number of toys" % ("(r - "+str(pull0)+")"), 25, -5, +5) #
            hist = TH1D("s_pulls", ";%s/#sigma_{r};Number of toys" % ("#Deltar"), 25, -5, +5) #
            for i in range(tree.GetEntries()):
                if hist.GetEntries() >= 1000: continue
                tree.GetEntry(i)
                #print "r = {} (+{}, -{})".format(tree.r, tree.rHiErr, tree.rLoErr)
                ##if tree.rLoErr < 0.: continue
                if abs(tree.r+1.) < 0.001: continue
                if abs(tree.r-1.) < 0.001: continue
                if abs(tree.r-0.) < 0.001: continue
                #if abs(tree.rLoErr)>8.: continue # trying to skip these values FIXME
                if tree.rHiErr==0. or tree.rLoErr==0.: continue
                #print "r = {} (+{}, -{})".format(tree.r, tree.rHiErr, tree.rLoErr)
                #pull = (tree.r-pull0)/(0.5*(abs(tree.rHiErr)+abs(tree.rLoErr))) ## documentation approach
                #pull = (tree.r-pull0)/abs(tree.rHiErr) if tree.r-pull0 < 0. else (tree.r-pull0)/abs(tree.rLoErr)  ## Alberto's sign convention
                pull = (tree.r-pull0)/abs(tree.rHiErr) if tree.r-pull0 > 0. else (tree.r-pull0)/abs(tree.rLoErr) ## my own approach
                #pull = (tree.r-pull0)/abs(tree.rHiErr) if tree.r < 0. else (tree.r-pull0)/abs(tree.rLoErr)  ## Alberto's sign convention but depending directly on the sign of r
                #pull = (tree.r-pull0)/abs(tree.rHiErr) if tree.r > 0. else (tree.r-pull0)/abs(tree.rLoErr) ## my own approach with an rErr dependence on r, not r-1
                hist.Fill(pull)

            ## individual plots for checking the fit quality
            c1 = TCanvas("c1", "Pulls", 600, 600)
            c1.cd()
            #c1.GetPad(0).SetTopMargin(0.06)
            #c1.GetPad(0).SetRightMargin(0.05)
            #c1.GetPad(0).SetBottomMargin(0.15)
            #c1.GetPad(0).SetTicks(1, 1)
            hist.GetXaxis().SetTitleSize(0.045)
            hist.GetYaxis().SetTitleSize(0.045)
            hist.GetYaxis().SetTitleOffset(1.1)
            hist.GetXaxis().SetTitleOffset(1.05)
            hist.GetXaxis().SetLimits(-5, 5.)
            hist.GetYaxis().SetLimits(0, 200.)
            hist.SetMinimum(0.)
            hist.SetMaximum(190.)
            c1.SetTopMargin(0.05)

            ##print "@ m= {}: \t mean = {}".format(m, hist.GetMean())
            #pulls.SetPoint(pulls.GetN(), m, hist.GetMean()) ## get actual mean of histogram
            fit_func = TF1("gaussfit","gaus" , -3., 3.)
            ###fit_func.SetParameter(1, hist.GetMean())
            #fit_func.SetParameter(1, 0.)
            ###fit_func.SetParLimits(1, -0.8, 0.8)
            #fit_func.SetParameter(2, 1.)
            ###fit_func.SetParameter(0, 45.)
            ###fit_func.SetParLimits(0, 30., 100.)
            hist.Fit(fit_func, "E")

            hist.Draw()

            drawCMS(-1, "Simulation Preliminary", year='run2')
            drawMass("m_{Z'} = "+str(m)+" GeV")
            c1.Print("plots/bias/run2c_masspoints/bias_fit_"+str(m)+"_"+args.year+".pdf")
            c1.Print("plots/bias/run2c_masspoints/bias_fit_"+str(m)+"_"+args.year+".png")

            n = pulls.GetN()
            pulls.SetPoint(n, m, fit_func.GetParameter(1)) ## get fitted gaussian mean
            pulls.SetPointError(n, 0., fit_func.GetParError(1)) ## set gaussian width as error

            hist.Delete()
            c1.Delete()
            #tfile.Close()
        #except:
        #    print "something went wrong in m =", m

    ## draw pulls
    c = TCanvas("canvas", "canvas", 800, 600)
    pulls.SetTitle(";m_{Z'} (GeV);mean #Deltar/#sigma_{r}")
    pulls.SetMarkerStyle(2)
    pulls.SetMarkerColor(2)
    pulls.SetLineColor(2)
    pulls.SetLineWidth(2)
    #pulls.GetYaxis().SetNdivisions(1020)
    pulls.SetMinimum(-0.5)
    pulls.SetMaximum(0.5)
    pulls.Draw("APL")
    zeroline = TGraph()
    zeroline.SetPoint(zeroline.GetN(), 1000, 0)
    zeroline.SetPoint(zeroline.GetN(), 8600, 0)
    zeroline.SetMarkerStyle(7)
    zeroline.SetMarkerSize(0)
    zeroline.SetLineStyle(15)
    zeroline.SetLineColor(1)
    zeroline.Draw("PL")
    c.SetGrid()
    pulls.GetXaxis().SetTitleSize(0.045)
    pulls.GetYaxis().SetTitleSize(0.045)
    pulls.GetYaxis().SetTitleOffset(1.1)
    pulls.GetXaxis().SetTitleOffset(1.05)
    pulls.GetXaxis().SetLimits(1350., 8150.)
    c.SetTopMargin(0.05)
    drawCMS(-1, "Simulation Preliminary", year='run2')
    c.Print("plots/bias/bias_study_"+args.year+".png")
    c.Print("plots/bias/bias_study_"+args.year+".pdf")
Ejemplo n.º 16
0
def signal(channel, stype):
    if 'VBF' in channel:
        stype = 'XZHVBF'
    else:
        stype = 'XZH'
    # HVT model
    if stype.startswith('X'):
        signalType = 'HVT'
        genPoints = [800, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000, 3500, 4000, 4500, 5000]
        massPoints = [x for x in range(800, 5000+1, 100)]
        interPar = True
    else:
        print "Signal type", stype, "not recognized"
        return
    
    n = len(genPoints)  
    
    category = channel
    cColor = color[category] if category in color else 1

    nElec = channel.count('e')
    nMuon = channel.count('m')
    nLept = nElec + nMuon
    nBtag = channel.count('b')
    if '0b' in channel:
        nBtag = 0

    X_name = "VH_mass"

    if not os.path.exists(PLOTDIR+stype+category): os.makedirs(PLOTDIR+stype+category)

    #*******************************************************#
    #                                                       #
    #              Variables and selections                 #
    #                                                       #
    #*******************************************************#
    X_mass = RooRealVar(  "X_mass",    "m_{ZH}",       XBINMIN, XBINMAX, "GeV")
    J_mass = RooRealVar(  "H_mass",   "jet mass",        LOWMIN, HIGMAX, "GeV")
    V_mass = RooRealVar(  "V_mass", "V jet mass",           -9.,  1.e6, "GeV")
    CSV1    = RooRealVar( "H_csv1",           "",         -999.,     2.     )
    CSV2    = RooRealVar( "H_csv2",           "",         -999.,     2.     )
    DeepCSV1= RooRealVar( "H_deepcsv1",       "",         -999.,     2.     )
    DeepCSV2= RooRealVar( "H_deepcsv2",       "",         -999.,     2.     )
    H_ntag  = RooRealVar( "H_ntag",           "",           -9.,     9.     )
    H_dbt   = RooRealVar( "H_dbt",            "",           -2.,     2.     )
    H_tau21 = RooRealVar( "H_tau21",          "",           -9.,     2.     )
    H_eta = RooRealVar( "H_eta",              "",           -9.,     9.     )
    H_tau21_ddt = RooRealVar( "H_ddt",  "",           -9.,     2.     )
    MaxBTag = RooRealVar( "MaxBTag",          "",          -10.,     2.     )
    H_chf   = RooRealVar( "H_chf",            "",           -1.,     2.     )
    MinDPhi = RooRealVar( "MinDPhi",          "",           -1.,    99.     )
    DPhi    = RooRealVar( "DPhi",             "",           -1.,    99.     )
    DEta    = RooRealVar( "DEta",             "",           -1.,    99.     )
    Mu1_relIso = RooRealVar( "Mu1_relIso",    "",           -1.,    99.     )
    Mu2_relIso = RooRealVar( "Mu2_relIso",    "",           -1.,    99.     )
    nTaus   = RooRealVar( "nTaus",            "",           -1.,    99.     )
    Vpt     = RooRealVar( "V.Pt()",           "",           -1.,   1.e6     )
    V_pt     = RooRealVar( "V_pt",            "",           -1.,   1.e6     )
    H_pt     = RooRealVar( "H_pt",            "",           -1.,   1.e6     )
    VH_deltaR=RooRealVar( "VH_deltaR",        "",           -1.,    99.     )
    isZtoNN = RooRealVar( "isZtoNN",          "",            0.,     2.     )
    isZtoEE = RooRealVar( "isZtoEE",          "",            0.,     2.     )
    isZtoMM = RooRealVar( "isZtoMM",          "",            0.,     2.     )
    isHtobb = RooRealVar( "isHtobb",          "",            0.,     2.     )
    isVBF   = RooRealVar( "isVBF",            "",            0.,     2.     )
    isMaxBTag_loose = RooRealVar( "isMaxBTag_loose", "",     0.,     2.     )
    weight  = RooRealVar( "eventWeightLumi",  "",         -1.e9,   1.e9     )

    Xmin = XBINMIN
    Xmax = XBINMAX

    # Define the RooArgSet which will include all the variables defined before
    # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add'
    variables = RooArgSet(X_mass, J_mass, V_mass, CSV1, CSV2, H_ntag, H_dbt, H_tau21)
    variables.add(RooArgSet(DEta, DPhi, MaxBTag, MinDPhi, nTaus, Vpt))
    variables.add(RooArgSet(DeepCSV1, DeepCSV2,VH_deltaR, H_tau21_ddt))
    variables.add(RooArgSet(isZtoNN, isZtoEE, isZtoMM, isHtobb, isMaxBTag_loose, weight))
    variables.add(RooArgSet(isVBF, Mu1_relIso, Mu2_relIso, H_chf, H_pt, V_pt,H_eta))
    #X_mass.setRange("X_extended_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_integration_range", Xmin, Xmax)
    X_mass.setBins(int((X_mass.getMax() - X_mass.getMin())/100))
    binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax())
    X_mass.setBinning(binsXmass, "PLOT")
    massArg = RooArgSet(X_mass)

    # Cuts
    SRcut = selection[category]+selection['SR']
    print "  Cut:\t", SRcut
    #*******************************************************#
    #                                                       #
    #                    Signal fits                        #
    #                                                       #
    #*******************************************************#

    treeSign = {}
    setSignal = {}

    vmean  = {}
    vsigma = {}
    valpha1 = {}
    vslope1 = {}
    smean  = {}
    ssigma = {}
    salpha1 = {}
    sslope1 = {}
    salpha2 = {}
    sslope2 = {}
    a1 = {}
    a2 = {}
    sbrwig = {}
    signal = {}
    signalExt = {}
    signalYield = {}
    signalIntegral = {}
    signalNorm = {}
    signalXS = {}
    frSignal = {}
    frSignal1 = {}
    frSignal2 = {}
    frSignal3 = {}

    # Signal shape uncertainties (common amongst all mass points)
    xmean_fit = RooRealVar("sig_p1_fit", "Variation of the resonance position with the fit uncertainty", 0.005, -1., 1.)
    smean_fit = RooRealVar("CMSRunII_sig_p1_fit", "Change of the resonance position with the fit uncertainty", 0., -10, 10)
    xmean_jes = RooRealVar("sig_p1_scale_jes", "Variation of the resonance position with the jet energy scale", 0.010, -1., 1.) #0.001
    smean_jes = RooRealVar("CMSRunII_sig_p1_jes", "Change of the resonance position with the jet energy scale", 0., -10, 10)
    xmean_e = RooRealVar("sig_p1_scale_e", "Variation of the resonance position with the electron energy scale", 0.001, -1., 1.)
    smean_e = RooRealVar("CMSRunII_sig_p1_scale_e", "Change of the resonance position with the electron energy scale", 0., -10, 10)
    xmean_m = RooRealVar("sig_p1_scale_m", "Variation of the resonance position with the muon energy scale", 0.001, -1., 1.)
    smean_m = RooRealVar("CMSRunII_sig_p1_scale_m", "Change of the resonance position with the muon energy scale", 0., -10, 10)

    xsigma_fit = RooRealVar("sig_p2_fit", "Variation of the resonance width with the fit uncertainty", 0.02, -1., 1.)
    ssigma_fit = RooRealVar("CMSRunII_sig_p2_fit", "Change of the resonance width with the fit uncertainty", 0., -10, 10)
    xsigma_jes = RooRealVar("sig_p2_scale_jes", "Variation of the resonance width with the jet energy scale", 0.010, -1., 1.) #0.001
    ssigma_jes = RooRealVar("CMSRunII_sig_p2_jes", "Change of the resonance width with the jet energy scale", 0., -10, 10)
    xsigma_jer = RooRealVar("sig_p2_scale_jer", "Variation of the resonance width with the jet energy resolution", 0.020, -1., 1.)
    ssigma_jer = RooRealVar("CMSRunII_sig_p2_jer", "Change of the resonance width with the jet energy resolution", 0., -10, 10)
    xsigma_e = RooRealVar("sig_p2_scale_e", "Variation of the resonance width with the electron energy scale", 0.001, -1., 1.)
    ssigma_e = RooRealVar("CMSRunII_sig_p2_scale_e", "Change of the resonance width with the electron energy scale", 0., -10, 10)
    xsigma_m = RooRealVar("sig_p2_scale_m", "Variation of the resonance width with the muon energy scale", 0.040, -1., 1.)
    ssigma_m = RooRealVar("CMSRunII_sig_p2_scale_m", "Change of the resonance width with the muon energy scale", 0., -10, 10)
    
    xalpha1_fit = RooRealVar("sig_p3_fit", "Variation of the resonance alpha with the fit uncertainty", 0.03, -1., 1.)
    salpha1_fit = RooRealVar("CMSRunII_sig_p3_fit", "Change of the resonance alpha with the fit uncertainty", 0., -10, 10)
    
    xslope1_fit = RooRealVar("sig_p4_fit", "Variation of the resonance slope with the fit uncertainty", 0.10, -1., 1.)
    sslope1_fit = RooRealVar("CMSRunII_sig_p4_fit", "Change of the resonance slope with the fit uncertainty", 0., -10, 10)

    xmean_fit.setConstant(True)
    smean_fit.setConstant(True)
    xmean_jes.setConstant(True)
    smean_jes.setConstant(True)
    xmean_e.setConstant(True)
    smean_e.setConstant(True)
    xmean_m.setConstant(True)
    smean_m.setConstant(True)
    
    xsigma_fit.setConstant(True)
    ssigma_fit.setConstant(True)
    xsigma_jes.setConstant(True)
    ssigma_jes.setConstant(True)
    xsigma_jer.setConstant(True)
    ssigma_jer.setConstant(True)
    xsigma_e.setConstant(True)
    ssigma_e.setConstant(True)
    xsigma_m.setConstant(True)
    ssigma_m.setConstant(True)
    
    xalpha1_fit.setConstant(True)
    salpha1_fit.setConstant(True)
    xslope1_fit.setConstant(True)
    sslope1_fit.setConstant(True)

    # the alpha method is now done.
    for m in massPoints:
        signalString = "M%d" % m
        signalMass = "%s_M%d" % (stype, m)
        signalName = "%s%s_M%d" % (stype, category, m)
        signalColor = sample[signalMass]['linecolor'] if signalName in sample else 1

        # define the signal PDF
        vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m, m*0.5, m*1.25)
        smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)", RooArgList(vmean[m], xmean_e, smean_e, xmean_m, smean_m, xmean_jes, smean_jes, xmean_fit, smean_fit))

        vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma", m*0.035, m*0.01, m*0.4)
        sigmaList = RooArgList(vsigma[m], xsigma_e, ssigma_e, xsigma_m, ssigma_m, xsigma_jes, ssigma_jes, xsigma_jer, ssigma_jer)
        sigmaList.add(RooArgList(xsigma_fit, ssigma_fit))
        ssigma[m] = RooFormulaVar(signalName + "_sigma", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)*(1+@9*@10)", sigmaList)
        
        valpha1[m] = RooRealVar(signalName + "_valpha1", "Crystal Ball alpha", 1.,  0., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0*(1+@1*@2)", RooArgList(valpha1[m], xalpha1_fit, salpha1_fit))

        vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope", 10., 1., 60.) # slope of the power tail   #10 1 60
        sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0*(1+@1*@2)", RooArgList(vslope1[m], xslope1_fit, sslope1_fit))

        salpha2[m] = RooRealVar(signalName + "_alpha2", "Crystal Ball alpha", 2,  1., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        sslope2[m] = RooRealVar(signalName + "_slope2", "Crystal Ball slope", 10, 1.e-1, 115.) # slope of the power tail
        #define polynomial
        #a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", m, 0.5*m, 2*m)
        a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", 0.001*m, 0.0005*m, 0.01*m)
        a2[m] = RooRealVar(signalName + "_a2", "par 2 for polynomial", 0.05, -1.,1.)
        #if channel=='nnbbVBF' or channel=='nn0bVBF':
        #    signal[m] = RooPolynomial(signalName,"m_{%s'} = %d GeV" % (stype[1], m) , X_mass, RooArgList(a1[m],a2[m]))
        #else:
        #    signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel
        signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel
        # extend the PDF with the yield to perform an extended likelihood fit
        signalYield[m] = RooRealVar(signalName+"_yield", "signalYield", 100, 0., 1.e6)
        signalNorm[m] = RooRealVar(signalName+"_norm", "signalNorm", 1., 0., 1.e6)
        signalXS[m] = RooRealVar(signalName+"_xs", "signalXS", 1., 0., 1.e6)
        signalExt[m] = RooExtendPdf(signalName+"_ext", "extended p.d.f", signal[m], signalYield[m])
        
        vslope1[m].setMax(50.)
        vslope1[m].setVal(20.)
        #valpha1[m].setVal(1.0)
        #valpha1[m].setConstant(True)
        
        if 'bb' in channel and 'VBF' not in channel:
            if 'nn' in channel:
                valpha1[m].setVal(0.5)
        elif '0b' in channel and 'VBF' not in channel:
            if 'nn' in channel:
                if m==800:
                    valpha1[m].setVal(2.)
                    vsigma[m].setVal(m*0.04)
            elif 'ee' in channel:
                valpha1[m].setVal(0.8)
                if m==800:
                    #valpha1[m].setVal(1.2)
                    valpha1[m].setVal(2.5)
                    vslope1[m].setVal(50.)
            elif 'mm' in channel:
                if m==800:
                    valpha1[m].setVal(2.)
                    vsigma[m].setVal(m*0.03)
                else:
                    vmean[m].setVal(m*0.9)
                    vsigma[m].setVal(m*0.08)
        elif 'bb' in channel and 'VBF' in channel:
            if 'nn' in channel:
                if m!=1800:
                    vmean[m].setVal(m*0.8)
                vsigma[m].setVal(m*0.08)
                valpha1[m].setMin(1.)
            elif 'ee' in channel:
                valpha1[m].setVal(0.7)
            elif 'mm' in channel:
                if m==800:
                    vslope1[m].setVal(50.)
                valpha1[m].setVal(0.7)
        elif '0b' in channel and 'VBF' in channel:
            if 'nn' in channel:
                valpha1[m].setVal(3.) 
                vmean[m].setVal(m*0.8)
                vsigma[m].setVal(m*0.08)
                valpha1[m].setMin(1.)
            elif 'ee' in channel:
                if m<2500:
                    valpha1[m].setVal(2.)
                if m==800:
                    vsigma[m].setVal(m*0.05)
                elif m==1000:
                    vsigma[m].setVal(m*0.03)
                elif m>1000 and m<1800:
                    vsigma[m].setVal(m*0.04)
            elif 'mm' in channel:
                if m<2000:
                    valpha1[m].setVal(2.)
                if m==1000 or m==1800:
                    vsigma[m].setVal(m*0.03)
                elif m==1200 or m==1600:
                    vsigma[m].setVal(m*0.04)

            
        #if m < 1000: vsigma[m].setVal(m*0.06)

        # If it's not the proper channel, make it a gaussian
        #if nLept==0 and 'VBF' in channel:
        #    valpha1[m].setVal(5)
        #    valpha1[m].setConstant(True)
        #    vslope1[m].setConstant(True)
        #    salpha2[m].setConstant(True)
        #    sslope2[m].setConstant(True)

        
        # ---------- if there is no simulated signal, skip this mass point ----------
        if m in genPoints:
            if VERBOSE: print " - Mass point", m

            # define the dataset for the signal applying the SR cuts
            treeSign[m] = TChain("tree")
            for j, ss in enumerate(sample[signalMass]['files']):
                treeSign[m].Add(NTUPLEDIR + ss + ".root")
            
            if treeSign[m].GetEntries() <= 0.:
                if VERBOSE: print " - 0 events available for mass", m, "skipping mass point..."
                signalNorm[m].setVal(-1)
                vmean[m].setConstant(True)
                vsigma[m].setConstant(True)
                salpha1[m].setConstant(True)
                sslope1[m].setConstant(True)
                salpha2[m].setConstant(True)
                sslope2[m].setConstant(True)
                signalNorm[m].setConstant(True)
                signalXS[m].setConstant(True)
                continue
            
            setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar(weight), RooFit.Import(treeSign[m]))
            if VERBOSE: print " - Dataset with", setSignal[m].sumEntries(), "events loaded"
            
            # FIT
            signalYield[m].setVal(setSignal[m].sumEntries())
            
            if treeSign[m].GetEntries(SRcut) > 5:
                if VERBOSE: print " - Running fit"
 
                frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1), RooFit.Extended(True), RooFit.SumW2Error(True), RooFit.PrintLevel(-1))
                if VERBOSE: print "********** Fit result [", m, "] **", category, "*"*40, "\n", frSignal[m].Print(), "\n", "*"*80
                if VERBOSE: frSignal[m].correlationMatrix().Print()
                drawPlot(signalMass, stype+channel, X_mass, signal[m], setSignal[m], frSignal[m])
            
            else:
                print "  WARNING: signal", stype, "and mass point", m, "in channel", channel, "has 0 entries or does not exist"          
            # Remove HVT cross section (which is the same for Zlep and Zinv)
            if stype == "XZHVBF":
                sample_name = 'Zprime_VBF_Zh_Zlephinc_narrow_M-%d' % m
            else:
                sample_name = 'ZprimeToZHToZlepHinc_narrow_M%d' % m

            xs = xsection[sample_name]['xsec']
            
            signalXS[m].setVal(xs * 1000.)
            
            signalIntegral[m] = signalExt[m].createIntegral(massArg, RooFit.NormSet(massArg), RooFit.Range("X_integration_range"))
            boundaryFactor = signalIntegral[m].getVal()
            if VERBOSE: 
                print " - Fit normalization vs integral:", signalYield[m].getVal(), "/", boundaryFactor, "events"
            if channel=='nnbb' and m==5000:
                signalNorm[m].setVal(2.5)
            elif channel=='nn0b' and m==5000:
                signalNorm[m].setVal(6.7)
            else:
                signalNorm[m].setVal( boundaryFactor * signalYield[m].getVal() / signalXS[m].getVal()) # here normalize to sigma(X) x Br(X->VH) = 1 [fb]
            
            
        a1[m].setConstant(True)
        a2[m].setConstant(True)
        vmean[m].setConstant(True)
        vsigma[m].setConstant(True)
        valpha1[m].setConstant(True)
        vslope1[m].setConstant(True)
        salpha2[m].setConstant(True)
        sslope2[m].setConstant(True)
        signalNorm[m].setConstant(True)
        signalXS[m].setConstant(True)

    #*******************************************************#
    #                                                       #
    #                 Signal interpolation                  #
    #                                                       #
    #*******************************************************#


    # ====== CONTROL PLOT ======
    c_signal = TCanvas("c_signal", "c_signal", 800, 600)
    c_signal.cd()
    frame_signal = X_mass.frame()
    for m in genPoints[:-2]:
        if m in signalExt.keys():
            signal[m].plotOn(frame_signal, RooFit.LineColor(sample["%s_M%d" % (stype, m)]['linecolor']), RooFit.Normalization(signalNorm[m].getVal(), RooAbsReal.NumEvent), RooFit.Range("X_reasonable_range"))
    frame_signal.GetXaxis().SetRangeUser(0, 6500)
    frame_signal.Draw()
    drawCMS(-1, YEAR, "Simulation")
    drawAnalysis(channel)
    drawRegion(channel)
    c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.pdf")
    c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.png")
    #if VERBOSE: raw_input("Press Enter to continue...")
    # ====== CONTROL PLOT ======

    # Normalization
    gnorm = TGraphErrors()
    gnorm.SetTitle(";m_{X} (GeV);integral (GeV)")
    gnorm.SetMarkerStyle(20)
    gnorm.SetMarkerColor(1)
    gnorm.SetMaximum(0)
    inorm = TGraphErrors()
    inorm.SetMarkerStyle(24)
    fnorm = TF1("fnorm", "pol9", 800, 5000) #"pol5" if not channel=="XZHnnbb" else "pol6" #pol5*TMath::Floor(x-1800) + ([5]*x + [6]*x*x)*(1-TMath::Floor(x-1800))
    fnorm.SetLineColor(920)
    fnorm.SetLineStyle(7)
    fnorm.SetFillColor(2)
    fnorm.SetLineColor(cColor)

    # Mean
    gmean = TGraphErrors()
    gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)")
    gmean.SetMarkerStyle(20)
    gmean.SetMarkerColor(cColor)
    gmean.SetLineColor(cColor)
    imean = TGraphErrors()
    imean.SetMarkerStyle(24)
    fmean = TF1("fmean", "pol1", 0, 5000)
    fmean.SetLineColor(2)
    fmean.SetFillColor(2)

    # Width
    gsigma = TGraphErrors()
    gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)")
    gsigma.SetMarkerStyle(20)
    gsigma.SetMarkerColor(cColor)
    gsigma.SetLineColor(cColor)
    isigma = TGraphErrors()
    isigma.SetMarkerStyle(24)
    fsigma = TF1("fsigma", "pol1", 0, 5000)
    fsigma.SetLineColor(2)
    fsigma.SetFillColor(2)

    # Alpha1
    galpha1 = TGraphErrors()
    galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha")
    galpha1.SetMarkerStyle(20)
    galpha1.SetMarkerColor(cColor)
    galpha1.SetLineColor(cColor)
    ialpha1 = TGraphErrors()
    ialpha1.SetMarkerStyle(24)
    falpha1 = TF1("falpha", "pol0", 0, 5000)
    falpha1.SetLineColor(2)
    falpha1.SetFillColor(2)

    # Slope1
    gslope1 = TGraphErrors()
    gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)")
    gslope1.SetMarkerStyle(20)
    gslope1.SetMarkerColor(cColor)
    gslope1.SetLineColor(cColor)
    islope1 = TGraphErrors()
    islope1.SetMarkerStyle(24)
    fslope1 = TF1("fslope", "pol0", 0, 5000)
    fslope1.SetLineColor(2)
    fslope1.SetFillColor(2)

    # Alpha2
    galpha2 = TGraphErrors()
    galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha")
    galpha2.SetMarkerStyle(20)
    galpha2.SetMarkerColor(cColor)
    galpha2.SetLineColor(cColor)
    ialpha2 = TGraphErrors()
    ialpha2.SetMarkerStyle(24)
    falpha2 = TF1("falpha", "pol0", 0, 5000)
    falpha2.SetLineColor(2)
    falpha2.SetFillColor(2)

    # Slope2
    gslope2 = TGraphErrors()
    gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)")
    gslope2.SetMarkerStyle(20)
    gslope2.SetMarkerColor(cColor)
    gslope2.SetLineColor(cColor)
    islope2 = TGraphErrors()
    islope2.SetMarkerStyle(24)
    fslope2 = TF1("fslope", "pol0", 0, 5000)
    fslope2.SetLineColor(2)
    fslope2.SetFillColor(2)



    n = 0
    for i, m in enumerate(genPoints):
        if not m in signalNorm.keys(): continue
        if signalNorm[m].getVal() < 1.e-6: continue
        signalString = "M%d" % m
        signalName = "%s_M%d" % (stype, m)

        if gnorm.GetMaximum() < signalNorm[m].getVal(): gnorm.SetMaximum(signalNorm[m].getVal())
        gnorm.SetPoint(n, m, signalNorm[m].getVal())
        gmean.SetPoint(n, m, vmean[m].getVal())
        gmean.SetPointError(n, 0, min(vmean[m].getError(), vmean[m].getVal()*0.02))
        gsigma.SetPoint(n, m, vsigma[m].getVal())
        gsigma.SetPointError(n, 0, min(vsigma[m].getError(), vsigma[m].getVal()*0.05))
        galpha1.SetPoint(n, m, valpha1[m].getVal())
        galpha1.SetPointError(n, 0, min(valpha1[m].getError(), valpha1[m].getVal()*0.10))
        gslope1.SetPoint(n, m, vslope1[m].getVal())
        gslope1.SetPointError(n, 0, min(vslope1[m].getError(), vslope1[m].getVal()*0.10))
        galpha2.SetPoint(n, m, salpha2[m].getVal())
        galpha2.SetPointError(n, 0, min(salpha2[m].getError(), salpha2[m].getVal()*0.10))
        gslope2.SetPoint(n, m, sslope2[m].getVal())
        gslope2.SetPointError(n, 0, min(sslope2[m].getError(), sslope2[m].getVal()*0.10))
        n = n + 1
    print "fit on gmean:"
    gmean.Fit(fmean, "Q0", "SAME")
    print "fit on gsigma:"
    gsigma.Fit(fsigma, "Q0", "SAME")
    print "fit on galpha:"
    galpha1.Fit(falpha1, "Q0", "SAME")
    print "fit on gslope:"
    gslope1.Fit(fslope1, "Q0", "SAME")
    galpha2.Fit(falpha2, "Q0", "SAME")
    gslope2.Fit(fslope2, "Q0", "SAME")
    #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S"))
    gnorm.Fit(fnorm, "Q", "SAME", 700, 5000)

    for m in massPoints:
        signalName = "%s_M%d" % (stype, m)
        
        if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.)

        # Interpolation method
        syield = gnorm.Eval(m)
        spline = gnorm.Eval(m, 0, "S")
        sfunct = fnorm.Eval(m)
        
        #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield))
        delta = abs(1.-spline/sfunct) if sfunct > 0 else 0
        syield = spline
               
        if interPar:
            jmean = gmean.Eval(m)
            jsigma = gsigma.Eval(m)
            jalpha1 = galpha1.Eval(m)
            jslope1 = gslope1.Eval(m)
        else:
            jmean = fmean.GetParameter(0) + fmean.GetParameter(1)*m + fmean.GetParameter(2)*m*m
            jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(1)*m + fsigma.GetParameter(2)*m*m
            jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(1)*m + falpha1.GetParameter(2)*m*m
            jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(1)*m + fslope1.GetParameter(2)*m*m

        inorm.SetPoint(inorm.GetN(), m, syield)
        signalNorm[m].setVal(syield)

        imean.SetPoint(imean.GetN(), m, jmean)
        if jmean > 0: vmean[m].setVal(jmean)

        isigma.SetPoint(isigma.GetN(), m, jsigma)
        if jsigma > 0: vsigma[m].setVal(jsigma)

        ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1)
        if not jalpha1==0: valpha1[m].setVal(jalpha1)

        islope1.SetPoint(islope1.GetN(), m, jslope1)
        if jslope1 > 0: vslope1[m].setVal(jslope1)
    

    c1 = TCanvas("c1", "Crystal Ball", 1200, 800)
    c1.Divide(2, 2)
    c1.cd(1)
    gmean.SetMinimum(0.)
    gmean.Draw("APL")
    imean.Draw("P, SAME")
    drawRegion(channel)
    c1.cd(2)
    gsigma.SetMinimum(0.)
    gsigma.Draw("APL")
    isigma.Draw("P, SAME")
    drawRegion(channel)
    c1.cd(3)
    galpha1.Draw("APL")
    ialpha1.Draw("P, SAME")
    drawRegion(channel)
    galpha1.GetYaxis().SetRangeUser(0., 5.)
    c1.cd(4)
    gslope1.Draw("APL")
    islope1.Draw("P, SAME")
    drawRegion(channel)
    gslope1.GetYaxis().SetRangeUser(0., 125.)
    if False:
        c1.cd(5)
        galpha2.Draw("APL")
        ialpha2.Draw("P, SAME")
        drawRegion(channel)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(channel)
        gslope2.GetYaxis().SetRangeUser(0., 10.)


    c1.Print(PLOTDIR+stype+category+"/"+stype+"_SignalShape.pdf")
    c1.Print(PLOTDIR+stype+category+"/"+stype+"_SignalShape.png")


    c2 = TCanvas("c2", "Signal Efficiency", 800, 600)
    c2.cd(1)
    gnorm.SetMarkerColor(cColor)
    gnorm.SetMarkerStyle(20)
    gnorm.SetLineColor(cColor)
    gnorm.SetLineWidth(2)
    gnorm.Draw("APL")
    inorm.Draw("P, SAME")
    gnorm.GetXaxis().SetRangeUser(genPoints[0]-100, genPoints[-1]+100)
    gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum()*1.25)
    drawCMS(-1,YEAR , "Simulation")
    drawAnalysis(channel)
    drawRegion(channel)
    c2.Print(PLOTDIR+stype+category+"/"+stype+"_SignalNorm.pdf")
    c2.Print(PLOTDIR+stype+category+"/"+stype+"_SignalNorm.png")





    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    # create workspace
    w = RooWorkspace("ZH_RunII", "workspace")
    for m in massPoints:
        getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName()))
        getattr(w, "import")(signalNorm[m], RooFit.Rename(signalNorm[m].GetName()))
        getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName()))
    w.writeToFile("%s%s.root" % (WORKDIR, stype+channel), True)
    print "Workspace", "%s%s.root" % (WORKDIR, stype+channel), "saved successfully"
    sys.exit()
    resgraph = TGraphErrors(len(sigma_energy), sqrtenergies, sigma_energy,
                            zeros, sigma_energy_error)
    resgraph.SetName("resgraph")
    lingraph = TGraphErrors(len(trueenergies), trueenergies, mean, zeros,
                            meanerror)
    lingraph.SetName("lingraph")
    ratiograph = TGraphErrors(len(trueenergies), trueenergies, ratio, zeros,
                              ratioerror)
    ratiograph.SetName("ratiograph")
    displayfile = TFile("MLPionEnergyResFTFPBERT.root", "UPDATE")
    displayfile.cd()
    resgraph.Write()
    lingraph.Write()
    ratiograph.Write()

    ratiograph.SetMinimum(0.976)
    ratiograph.SetMaximum(1.024)
    ratiograph.GetXaxis().SetLimits(0.0, 155.0)
    ratiograph.SetTitle("")
    ratiograph.GetXaxis().SetLabelSize(.105)
    ratiograph.GetYaxis().SetLabelSize(0.105)
    ratiograph.GetXaxis().SetNdivisions(520)
    ratiograph.GetYaxis().SetNdivisions(504)
    lingraph.SetTitle("")
    lingraph.SetMinimum(0.0)
    lingraph.SetMaximum(155.0)
    lingraph.GetXaxis().SetLimits(0.0, 155.0)
    lingraph.GetXaxis().SetLabelSize(0.)
    lingraph.GetXaxis().SetNdivisions(520)
    lingraph.GetYaxis().SetNdivisions(520)
    c = TCanvas("c", "canvas", 800, 800)