Ejemplo n.º 1
0
  def ApplyBinShiftCorrection(self, hist):
      """
      Apply bin-shift correction to the input spectrum using an iterative procedure
      @param hist: Input spectrum
      @return: Bin-shift corrected spectrum 
      """
  
      h = deepcopy(hist)
      h.SetName("htemp")    
  
      # Bin shift correction performed in model specturm * pt
      for i in range(1, h.GetNbinsX()+1):
          pt = h.GetBinCenter(i)
          h.SetBinContent(i, h.GetBinContent(i)*pt)
          h.SetBinError(i, h.GetBinError(i)*pt)
 
      result = TGraphErrors(h)
      for i in range(0, result.GetN()): 
          result.GetEX()[i] = 0.   
 
      fitfun = TF1("fitfun","([0]*(1.+x/[1])^(-[2])*x)-[3]",0.15,100.0)
      fitfun.SetParameter(0,1000)
      fitfun.SetParameter(1,1)
      fitfun.SetParameter(2,5)
      fitfun.FixParameter(3,0)
      h.Fit(fitfun,"") 
      self.__StableFit(h, fitfun, True)
 
      # Iterative approach:
      # - Use model to get the mean of the function inside the bin
      # - Get the X where the mean is found
      # - Use the new coordinate (x,y) for the next iteration of the fit
      # for now 10 iterations fixed
      for k in range(1, 11):
          for i in range(1, h.GetNbinsX()+1):
              y = fitfun.Integral(h.GetBinLowEdge(i), h.GetBinUpEdge(i)) / h.GetBinWidth(i)
              result.GetX()[i-1] = self.FindX(y, fitfun, h.GetBinLowEdge(i), h.GetBinUpEdge(i))
          self.__StableFit(result, fitfun, False)
 
      # Undo multiplication with pt
      for i in range(0, result.GetN()):
          pt = result.GetX()[i]
          result.GetY()[i]  /=  pt
          result.GetEY()[i] /=  pt
 
      #remove points that are 0
      while result.GetY()[0] < 1.e-99: 
          result.RemovePoint(0) 
 
      bval = 0
      for mybin in range(0, result.GetN()+1):
          if result.GetY()[bin] < 1.e-99: 
              bval = mybin
              break
          
      while result.RemovePoint(bval) > 0: 
          continue 
      return result
Ejemplo n.º 2
0
 def initGraph(self):
     TGraphErrors.__init__(self, len(self.x) )
     i = 0
     for i in range(0, len(self.x) ):
         # print i, self.x[i], self.y[i]
         self.SetPoint(i, self.x[i], self.y[i])
         errx = 0
         erry = 0
         if len(self.errx)>i:
             errx = self.errx[i]
         if len(self.erry)>i:
             erry = self.erry[i]
         self.SetPointError(i, errx, erry)
Ejemplo n.º 3
0
   def ApplyBinShiftCorrectionGeneral(self, hist, fit):
       """
       Alternative method for bin shift correction:
       - Apply user-default model for bin-shift correction
       - don't multiply by pt
       
       :param hist: Input spectrum for the bin shift correction
       :param fit: Model for the bin-shift correction
       :type hist: TH1
       :type fit: TF1
       :return: The bin-shift corrected spectrum as graph
       :rtype: TGraphErrors
       """
       h = deepcopy(hist)    
       hist.SetName("htemp")
  
       result = TGraphErrors(h);
       for i in range(0, result.GetN()):
           result.GetEX()[i] = 0.   
       y = 0
  
       #for now 10 iterations fixes
       for k in range(0, 10):
           for i in range(1, h.GetNbinsX()+1):
               y = fit.Integral(h.GetBinLowEdge(i),h.GetBinUpEdge(i)) / h.GetBinWidth(i)
               x = self.FindX(y, fit, h.GetBinLowEdge(i), h.GetBinUpEdge(i)) 
               result.GetX()[i-1] = x
 
       # remove points that are 0
       while result.GetY()[0] < 1.e-99:
           result.RemovePoint(0) 
  
       mybin = 0
       for biniter in range(0, result.GetN()):
           if result.GetY()[biniter] < 1.e-99:
               mybin = biniter
               break
       while result.RemovePoint(mybin) > 0:
           continue 
     
       return result
Ejemplo n.º 4
0
bp_tail_mean = RooRealVar("bp_tail_mean", "bp_tail_mean", 0, -10, 10)
bp_tail_sigma = RooRealVar("bp_tail_sigma", "bp_tail_sigma", 9, 0, 15)
bp_tail_gaussian = RooGaussModel("bp_tail_gaussian", "bp_tail_gaussian",
                                 sp_bp_residuals, bp_tail_mean, bp_tail_sigma)

bp_core_fraction = RooRealVar("bp_core_fraction", "Fraction of Core", .8, 0, 1)
resolution_model = RooAddModel("resolution_model", "resolution_model",
                               RooArgList(bp_core_gaussian, bp_tail_gaussian),
                               RooArgList(bp_core_fraction))

canvas.Print("sp_residuals.pdf[")

h_sp_residuals_bp_vs_p_5hit.Draw("colz")
canvas.Print("sp_residuals.pdf(")

g_bp_pos_resolution_vs_p_5hit = TGraphErrors()

for bin in xrange(1, h_sp_residuals_bp_vs_p_5hit.GetXaxis().GetNbins()):

    projection = h_sp_residuals_bp_vs_p_5hit.ProjectionY("", bin, bin)

    if projection.GetEntries() < 100: continue

    sp_bp_residuals_data = RooDataHist("sp_bp_residuals_data",
                                       "Bend Plane Residuals Data",
                                       RooArgList(sp_bp_residuals), projection)
    sp_bp_residuals_plot = sp_bp_residuals.frame()
    sp_bp_residuals_data.plotOn(sp_bp_residuals_plot)

    resolution_model.fitTo(sp_bp_residuals_data)
    resolution_model.plotOn(sp_bp_residuals_plot)
Ejemplo n.º 5
0
    #skip bins with too few events
    if (projectionHist.Integral() > 20):

        tmpDeltaTMean = projectionHist.GetMean()
        tmpDeltaTMeanErr = projectionHist.GetMeanError()

    dTMean.append(tmpDeltaTMean)
    dTMeanErr.append(tmpDeltaTMeanErr)

xArr = array.array('f', x)
xErrArr = array.array('f', xErr)
yArr = array.array('f', dTMean)
yErrArr = array.array('f', dTMeanErr)

effGraph = TGraphErrors(nbins, xArr, yArr, xErrArr, yErrArr)
effGraph.Draw("APE")
effGraph.SetTitle("")
effGraph.GetXaxis().SetTitle("X [mm]")
effGraph.GetXaxis().SetTitleSize(0.05)
effGraph.GetXaxis().SetTitleOffset(0.90)
effGraph.GetXaxis().SetLabelSize(0.03)
#effGraph.GetXaxis().SetRangeUser(23.0,25.0)
effGraph.GetYaxis().SetTitle("Mean #Delta t [ns]")
effGraph.GetYaxis().SetTitleSize(0.05)
effGraph.GetYaxis().SetTitleOffset(0.92)
effGraph.GetYaxis().SetLabelSize(0.03)
effGraph.GetYaxis().SetRangeUser(-2, 2)

title = TLatex()
title.SetTextSize(0.05)
Ejemplo n.º 6
0
def mistagSFtopEMu(year_, ana_):
    if year_ == 2017:
        dir = "monohbb.v06.00.05.2017_NCU/withSingleTop/" + ana_ + "/"
    if year_ == 2018:
        dir = "monohbb.v06.00.05.2018_NCU/withSingleTop/" + ana_ + "/"

    print "Top Electron Region"
    print " "

    openfile1 = TFile(dir + "TopE.root")  #

    topmatchTopE = openfile1.Get("h_TopMatch")
    WmatchTopE = openfile1.Get("h_Wmatch")
    unmatchTopE = openfile1.Get("h_unmatch")
    wjetsTopE = openfile1.Get("h_sumWJets")
    dibosonTopE = openfile1.Get("h_sumDiboson")
    unsubtractedDataTopE = openfile1.Get("h_Data")

    failMCsubtractTopE = openfile1.Get("h_ttFailed")
    passMCsubtractTopE = openfile1.Get("h_ttPassed")
    subtractedDataTopE = openfile1.Get("SubtractedData")

    datafailTopE = openfile1.Get("SubtractedDataFailed")
    datapassTopE = openfile1.Get("SubtractedDataPassed")  #
    totaldataTopE = openfile1.Get("h_totaldata")
    totalMCtopE = openfile1.Get("h_tt")

    passedTopEdataBfrSubtract = openfile1.Get("h_Data_Passed")
    wjetsTopEpassed = openfile1.Get("h_sumWJetsPassed")
    dibosonTopEpassed = openfile1.Get("h_sumDibosonPassed")

    failedTopEdataBfrSubtract = openfile1.Get("h_Data_Failed")
    wjetsTopEfailed = openfile1.Get("h_sumWJetsFailed")
    dibosonTopEfailed = openfile1.Get("h_sumDibosonFailed")

    stTopE = openfile1.Get("h_sumST")
    stTopEpassed = openfile1.Get("h_sumSTPassed")
    stTopEfailed = openfile1.Get("h_sumSTFailed")

    print "Top Muon Region"
    print " "

    openfile2 = TFile(dir + "TopMu.root")  #

    topmatchTopMu = openfile2.Get("h_TopMatch")
    WmatchTopMu = openfile2.Get("h_Wmatch")
    unmatchTopMu = openfile2.Get("h_unmatch")
    wjetsTopMu = openfile2.Get("h_sumWJets")
    dibosonTopMu = openfile2.Get("h_sumDiboson")
    unsubtractedDataTopMu = openfile2.Get("h_Data")

    failMCsubtractTopMu = openfile2.Get("h_ttFailed")
    passMCsubtractTopMu = openfile2.Get("h_ttPassed")
    subtractedDataTopMu = openfile2.Get("SubtractedData")

    datafailTopMu = openfile2.Get("SubtractedDataFailed")
    datapassTopMu = openfile2.Get("SubtractedDataPassed")  #
    totaldataTopMu = openfile2.Get("h_totaldata")
    totalMCtopMu = openfile2.Get("h_tt")

    passedTopMudataBfrSubtract = openfile2.Get("h_Data_Passed")
    wjetsTopMupassed = openfile2.Get("h_sumWJetsPassed")
    dibosonTopMupassed = openfile2.Get("h_sumDibosonPassed")

    failedTopMudataBfrSubtract = openfile2.Get("h_Data_Failed")
    wjetsTopMufailed = openfile2.Get("h_sumWJetsFailed")
    dibosonTopMufailed = openfile2.Get("h_sumDibosonFailed")

    stTopMu = openfile2.Get("h_sumST")
    stTopMupassed = openfile2.Get("h_sumSTPassed")
    stTopMufailed = openfile2.Get("h_sumSTFailed")

    print "get histograms from root files: done"
    print " "

    SubtractedDataPassedTopE = datapassTopE.Clone("SubtractedDataPassedTopE")
    SubtractedDataPassedTopMu = datapassTopMu.Clone(
        "SubtractedDataPassedTopMu")

    #merge histogram"
    print "merge histograms"
    print " "

    topmatchMerge = topmatchTopE + topmatchTopMu
    WmatchMerge = WmatchTopE + WmatchTopMu
    unmatchMerge = unmatchTopE + unmatchTopMu
    wjetsMerge = wjetsTopE + wjetsTopMu
    stMerge = stTopE + stTopMu
    dibosonMerge = dibosonTopE + dibosonTopMu
    unsubtractedDataMerge = unsubtractedDataTopE + unsubtractedDataTopMu

    failMCsubtractMerge = failMCsubtractTopE.Clone("failMCsubtractMerge")
    failMCsubtractMerge = failMCsubtractMerge + failMCsubtractTopMu
    passMCsubtractMerge = passMCsubtractTopE.Clone("passMCsubtractMerge")
    passMCsubtractMerge = passMCsubtractMerge + passMCsubtractTopMu
    subtractedDataMerge = subtractedDataTopE + subtractedDataTopMu

    ttData_fraction = arr.array('d')
    ttData_error = arr.array('d')

    totaldataMerge = totaldataTopE + totaldataTopMu
    totaldata = totaldataMerge.Integral()
    totaldataMerge.Rebin(14)

    datafailMerge = datafailTopE + datafailTopMu
    faildata = datafailMerge.Integral()
    datafailMerge.Rebin(14)
    datafailMerge.Sumw2()
    datafailMerge.Divide(totaldataMerge)
    frac_ttData_fail = datafailMerge.Integral()
    ttData_fraction.append(frac_ttData_fail)
    ttData_error.append(datafailMerge.GetBinError(1))

    datapassMerge = datapassTopE + datapassTopMu
    passdata = datapassMerge.Integral()
    datapassMerge.Rebin(14)
    datapassMerge.Sumw2()
    datapassMerge.Divide(totaldataMerge)
    frac_ttData_pass = datapassMerge.Integral()
    ttData_fraction.append(frac_ttData_pass)
    ttData_error.append(datapassMerge.GetBinError(1))

    ttMC_fraction = arr.array('d')
    ttMC_error = arr.array('d')

    totalMCmerge = totalMCtopE + totalMCtopMu
    totalMCmerge.Rebin(14)

    MCfailTopE = failMCsubtractTopE.Clone("MCfailTopE")
    MCfailTopMu = failMCsubtractTopMu.Clone("MCfailTopMu")
    MCfailMerge = MCfailTopE + MCfailTopMu
    MCfailMerge.Rebin(14)
    MCfailMerge.Sumw2()
    MCfailMerge.Divide(totalMCmerge)
    frac_Failed_fin = MCfailMerge.Integral()
    ttMC_fraction.append(frac_Failed_fin)
    ttMC_error.append(MCfailMerge.GetBinError(1))

    MCpassTopE = passMCsubtractTopE.Clone("MCpassTopE")
    MCpassTopMu = passMCsubtractTopMu.Clone("MCpassTopMu")
    MCpassMerge = MCpassTopE + MCpassTopMu
    MCpassMerge.Rebin(14)
    MCpassMerge.Sumw2()
    MCpassMerge.Divide(totalMCmerge)
    frac_Passed_fin = MCpassMerge.Integral()
    ttMC_fraction.append(frac_Passed_fin)
    ttMC_error.append(MCpassMerge.GetBinError(1))

    #print "\nttMC_fraction:", ttMC_fraction
    #print "ttMC_error:", ttMC_error

    sfMerge = datapassMerge.Clone("sfMerge")
    sfMerge.Sumw2()
    sfMerge.Divide(MCpassMerge)

    stacklist = []
    stacklist.append(dibosonMerge)
    stacklist.append(stMerge)
    stacklist.append(wjetsMerge)
    stacklist.append(unmatchMerge)
    stacklist.append(WmatchMerge)
    stacklist.append(topmatchMerge)

    print "merge histograms: done"
    print " "

    print "draw histograms"
    print " "
    #----------------------- canvas 1 -----------------------#

    c1 = TCanvas("c1", "", 800, 900)  #width-height
    c1.SetTopMargin(0.4)
    c1.SetBottomMargin(0.05)
    c1.SetRightMargin(0.1)
    c1.SetLeftMargin(0.15)
    gStyle.SetOptStat(0)

    binvalues1 = []
    for i in range(14):
        binvalue = unsubtractedDataMerge.GetBinContent(i)
        binvalues1.append(binvalue)
    totalmax = max(binvalues1) + 100

    padMain = TPad("padMain", "", 0.0, 0.25, 1.0, 0.97)
    padMain.SetTopMargin(0.4)
    padMain.SetRightMargin(0.05)
    padMain.SetLeftMargin(0.17)
    padMain.SetBottomMargin(0.03)
    padMain.SetTopMargin(0.1)

    padRatio = TPad("padRatio", "", 0.0, 0.0, 1.0, 0.25)
    padRatio.SetRightMargin(0.05)
    padRatio.SetLeftMargin(0.17)
    padRatio.SetTopMargin(0.05)
    padRatio.SetBottomMargin(0.3)
    padMain.Draw()
    padRatio.Draw()

    padMain.cd()

    gPad.GetUymax()
    leg1 = myLegend(coordinate=[0.45, 0.57, 0.65, 0.6])

    unsubtractedDataMerge.SetMaximum(totalmax)
    unsubtractedDataMerge.SetLineColor(1)
    unsubtractedDataMerge.SetMarkerStyle(20)
    unsubtractedDataMerge.SetMarkerSize(1.5)
    unsubtractedDataMerge.GetXaxis().SetLabelSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitleSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitle("DDB")
    unsubtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg1.AddEntry(unsubtractedDataMerge, "Data", "lep")
    unsubtractedDataMerge.Draw("e1")

    stackhisto = myStack(colorlist_=[627, 800, 854, 813, 822, 821],
                         backgroundlist_=stacklist,
                         legendname_=[
                             "Diboson", "Single Top", "W+Jets",
                             "Top (unmtch.)", "Top (W-mtch.)", "Top (mtch.)"
                         ])
    stackhisto[0].Draw("histsame")
    unsubtractedDataMerge.Draw("e1same")
    stackhisto[1].Draw()
    leg1.Draw()

    lt = TLatex()
    lt.DrawLatexNDC(0.23, 0.85,
                    "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    if ana_ == "Inclusive":
        lt.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt.DrawLatexNDC(0.17, 0.92,
                            "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt.DrawLatexNDC(0.71, 0.92,
                        "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    padRatio.cd()

    gPad.GetUymax()

    h_totalBkg = topmatchMerge.Clone("h_totalBkg")
    h_totalBkg = h_totalBkg + WmatchMerge + unmatchMerge + wjetsMerge + dibosonMerge
    ratio = dataPredRatio(data_=unsubtractedDataMerge, totalBkg_=h_totalBkg)
    ratio.SetLineColor(1)
    ratio.SetLineWidth(3)
    ratio.SetMarkerSize(1.5)
    ratio.GetXaxis().SetLabelSize(0.13)
    ratio.GetXaxis().SetTitleOffset(1)
    ratio.GetXaxis().SetTitleSize(0.13)
    ratio.GetXaxis().SetTickLength(0.1)
    ratio.GetYaxis().SetLabelSize(0.12)
    ratio.GetYaxis().SetTitleOffset(0.5)
    ratio.GetYaxis().SetTitleSize(0.13)
    ratio.GetYaxis().SetNdivisions(405)
    ratio.GetYaxis().SetTitle("#frac{Data-Pred}{Pred}")
    ratio.GetXaxis().SetTitle("DDB")
    ratio.Draw("e1")

    c1.SaveAs(dir + "Merge_all.pdf")  #

    #----------------------- canvas 2 -----------------------#

    c2 = myCanvas(c="c2")
    gPad.GetUymax()
    leg2 = myLegend()

    binvalues2 = []
    for i in range(14):
        binvalue = subtractedDataMerge.GetBinContent(i)
        binvalues2.append(binvalue)
    ttmax = max(binvalues2) + 50

    failMCsubtractMerge.SetMaximum(ttmax)
    failMCsubtractMerge.SetFillColor(821)
    failMCsubtractMerge.SetLineColor(821)  #922
    failMCsubtractMerge.GetXaxis().SetTitle("DDB")
    failMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(failMCsubtractMerge, "t#bar{t}", "f")

    passMCsubtractMerge.SetFillColor(622)
    passMCsubtractMerge.SetLineColor(622)
    #passMCsubtractMerge.GetXaxis().SetTitle("DDB")
    #passMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(passMCsubtractMerge, "t#bar{t} mistag", "f")

    subtractedDataMerge.SetLineColor(1)
    subtractedDataMerge.SetMarkerStyle(20)
    subtractedDataMerge.SetMarkerSize(1.5)
    #subtractedDataMerge.GetXaxis().SetTitle("DDB")
    #subtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(subtractedDataMerge, "Subtracted Data", "lep")

    failMCsubtractMerge.Draw("hist")
    passMCsubtractMerge.Draw("histsame")
    subtractedDataMerge.Draw("e1same")
    leg2.Draw()

    lt2 = TLatex()
    if ana_ == "Inclusive":
        lt2.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt2.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt2.DrawLatexNDC(0.23, 0.85,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt2.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt2.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt2.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt2.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    c2.SaveAs(dir + "Merged_subtrac.pdf")  #

    #----------------------- canvas 3 -----------------------#

    c3 = myCanvas(c="c3", size=[700, 900])

    pad1 = TPad("pad1", "", 0.01, 0.25, 0.93, 1.0)
    pad1.SetTopMargin(0.1)
    pad1.SetRightMargin(0.05)
    pad1.SetLeftMargin(0.17)
    pad1.SetBottomMargin(0.05)

    pad2 = TPad("pad2", "", 0.0, 0.0, 0.375, 0.24)
    pad2.SetTopMargin(0.0)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.0)
    pad2.SetBottomMargin(0.0)

    pad3 = TPad("pad3", "", 0.38, 0.025, 0.94, 0.25)
    pad2.SetTopMargin(0.05)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.45)
    pad2.SetBottomMargin(0.2)

    pad1.Draw()
    pad2.Draw()
    pad3.Draw()

    #* Pad 1 *#
    pad1.cd()
    leg3 = myLegend(coordinate=[0.65, 0.4, 0.75, 0.5])

    xaxisname = arr.array('d', [1, 2])
    zero1 = np.zeros(2)

    gPad.Modified()
    gPad.SetGridy()

    gr1 = TGraphErrors(2, xaxisname, ttMC_fraction, zero1, ttMC_error)
    gr1.SetTitle("t#bar{t}")
    gr1.SetLineColor(870)
    gr1.SetLineWidth(3)
    gr1.SetMarkerStyle(20)
    gr1.SetMarkerColor(870)
    leg3.AddEntry(gr1, "t#bar{t}", "lep")

    gr2 = TGraphErrors(2, xaxisname, ttData_fraction, zero1, ttData_error)
    gr2.SetTitle("t#bar{t} Data")
    gr2.SetLineColor(1)
    gr2.SetLineWidth(2)
    gr2.SetMarkerStyle(20)
    gr2.SetMarkerColor(1)
    leg3.AddEntry(gr2, "t#bar{t} Data", "lep")

    mg = TMultiGraph("mg", "")
    mg.Add(gr1)
    mg.Add(gr2)
    mg.GetHistogram().SetMaximum(1.5)
    mg.GetHistogram().SetMinimum(0)
    mg.GetYaxis().SetTitle("Fraction")
    mg.GetXaxis().SetLimits(0, 3)
    mg.GetXaxis().SetTickLength(0.03)
    mg.GetXaxis().SetNdivisions(103)
    mg.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Fail")
    mg.GetXaxis().ChangeLabel(1, -1, 0)
    mg.GetXaxis().ChangeLabel(-1, -1, 0)
    mg.GetXaxis().ChangeLabel(3, -1, -1, -1, -1, -1, "Pass")
    mg.Draw("AP")
    leg3.Draw()

    lt3 = TLatex()
    if ana_ == "Inclusive":
        lt3.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt3.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt3.DrawLatexNDC(0.19, 0.855,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt3.DrawLatexNDC(0.19, 0.805, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt3.DrawLatexNDC(0.19, 0.755, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt3.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt3.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")
    lt3.Draw()

    pad1.Update()

    #* Pad 2 *#
    pad2.cd()

    MCpassMerge.SetFillColor(0)
    MCpassMerge.SetLineColor(870)
    MCpassMerge.SetLineWidth(3)
    MCpassMerge.SetMarkerColor(870)
    MCpassMerge.SetMarkerStyle(20)
    MCpassMerge.GetYaxis().SetTitle("Fraction")
    MCpassMerge.GetYaxis().SetTitleSize(0.09)
    MCpassMerge.GetYaxis().SetLabelSize(0.1)
    MCpassMerge.GetYaxis().SetNdivisions(404)
    MCpassMerge.SetMaximum(0.3)
    MCpassMerge.SetMinimum(0.0)
    MCpassMerge.GetXaxis().SetTitle("")
    MCpassMerge.GetXaxis().SetLabelOffset(0.02)
    MCpassMerge.GetXaxis().SetLabelSize(0.09)
    MCpassMerge.GetXaxis().SetNdivisions(104)
    MCpassMerge.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Pass")
    MCpassMerge.GetXaxis().ChangeLabel(1, -1, 0)
    MCpassMerge.GetXaxis().ChangeLabel(-1, -1, 0)

    datapassMerge.SetFillColor(0)
    datapassMerge.SetLineColor(1)
    datapassMerge.SetLineWidth(2)
    datapassMerge.SetMarkerColor(1)
    datapassMerge.SetMarkerStyle(20)

    MCpassMerge.Draw("e1")
    datapassMerge.Draw("e1histsame")

    #* Pad 3 *#
    pad3.cd()

    SF = sfMerge.Integral()
    print "******"
    print "mistag SF:", SF

    SFfinal = round(SF, 3)
    SFtext = "SF = " + str(SFfinal)

    mistagSFmax = SF + 0.2
    mistagSFmin = SF - 0.2

    sfMerge.SetLineColor(797)
    sfMerge.SetMarkerColor(797)
    sfMerge.SetLineWidth(3)
    sfMerge.SetMaximum(mistagSFmax)
    sfMerge.SetMinimum(mistagSFmin)
    sfMerge.GetXaxis().SetTitle(" ")
    sfMerge.GetXaxis().SetLabelOffset(999)
    sfMerge.GetXaxis().SetLabelSize(0)
    sfMerge.GetXaxis().SetTickLength(0)
    sfMerge.GetYaxis().SetLabelSize(0.1)
    sfMerge.GetYaxis().SetNdivisions(404)
    sfMerge.GetYaxis().SetTitle(" ")

    sfMerge.Draw("e1hist")

    pt = TPaveText(0.21, 0.72, 0.31, 0.8, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.SetTextSize(0.1)
    pt.AddText(SFtext)
    pt.Draw()

    c3.SaveAs(dir + "Merge_SF.pdf")  #

    passedBfrSubtactDataMerge = (passedTopEdataBfrSubtract +
                                 passedTopMudataBfrSubtract).Integral()
    failedBfrSubtractDataMerge = (failedTopEdataBfrSubtract +
                                  failedTopMudataBfrSubtract).Integral()

    passbackground = (wjetsTopEpassed + wjetsTopMupassed + dibosonTopEpassed +
                      dibosonTopMupassed + stTopEpassed +
                      stTopMupassed).Integral()
    failbackground = (wjetsTopEfailed + wjetsTopMufailed + dibosonTopEfailed +
                      dibosonTopMufailed + stTopEfailed +
                      stTopMufailed).Integral()
    totalbackground = (wjetsMerge + dibosonMerge + stMerge).Integral()

    #get the statistical uncertainty#

    dx = ttData_error[1]
    print "data efficiency error", dx

    dy = ttMC_error[1]
    print "MC efficiency error", dy

    x = datapassMerge.Integral()
    y = MCpassMerge.Integral()

    statUnc = TMath.Sqrt(((dx**2) / (y**2)) + ((x**2) * (dy**2) / (y**4)))
    #print "statistical Uncertainty in Top (e+muon) CR", statUnc
    #print " "
    print "relative statistical Uncertainty in Top (e+muon) CR", statUnc / SF * 100, " %"
    print " "

    print "DDB Mistag SF and stat: ", round(SF, 3), " +- ", round(statUnc,
                                                                  3), " (stat)"
    #print "theoretical statistical uncertainty of data efficiency", TMath.Sqrt((x*(1-x))/(subtractedDataMerge.Integral()))
    #print "theoretical statistical uncertainty of MC efficiency", TMath.Sqrt((y*(1-y))/(totalMCmerge.Integral()))
    #print " "

    header = ["Process", "Number of Events", "Top (e+muon)"]
    row1 = [
        " ", "DDB mistag SF",
        str(SFfinal) + " +- " + str(round(statUnc, 3)) + " (stat)"
    ]
    row2 = ["tt MC", "Pass (not normalized)", ""]
    row3 = [
        " ", "Pass (normalized)",
        str(round(passMCsubtractMerge.Integral(), 2))
    ]
    row4 = [" ", "Fail (not normalized)", ""]
    row5 = [
        " ", "Fail (normalized)",
        str(round(failMCsubtractMerge.Integral(), 2))
    ]
    row6 = [" ", "Total (not normalized)", ""]
    row7 = [" ", "Total (normalized)", str(round(totalMCmerge.Integral(), 2))]

    inforMC = [row2, row3, row4, row5, row6, row7]

    row8 = [
        "tt DATA", "Pass (before subtraction)",
        str(round(passedBfrSubtactDataMerge, 2))
    ]
    row9 = [" ", "Pass (after subtraction)", str(round(passdata, 2))]
    row10 = [
        " ", "Fail (before subtraction)",
        str(round(failedBfrSubtractDataMerge, 2))
    ]
    row11 = [" ", "Fail (after subtraction)", str(round(faildata, 2))]
    row12 = [
        " ", "Total (before subtraction)",
        str(round(unsubtractedDataMerge.Integral(), 2))
    ]
    row13 = [" ", "Total (after subtraction)", str(round(totaldata, 2))]

    inforDATA = [row8, row9, row10, row11, row12, row13]

    row14 = ["Background", "Pass (normalized)", str(round(passbackground, 2))]
    row15 = [" ", "Fail (normalized)", str(round(failbackground, 2))]
    row16 = [" ", "Total (normalized)", str(round(totalbackground, 2))]

    inforBKG = [row14, row15, row16]

    DDB_mistagSF.makeTable(header, row1, inforMC, inforDATA, inforBKG)
Ejemplo n.º 7
0
def runGlobalFit(country, active, totalPopulation, symptomaticFraction,
                 transmissionProbability, recoveryRate, doSmearing, doFit):
    tStart = 0
    tStop = 9 + 6 + 12 + 42 + 61 + 40 + 50 + 200
    timeList = [
        9, 9 + 6, 9 + 6 + 12, 9 + 6 + 12 + 42, 9 + 6 + 12 + 42 + 61,
        9 + 6 + 12 + 42 + 61 + 40, 9 + 6 + 12 + 42 + 61 + 40 + 50, tStop
    ]

    ntuple = [
        tStart, tStop, totalPopulation, symptomaticFraction,
        transmissionProbability, recoveryRate
    ]

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

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

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

    ntuple.extend([
        0, xValues, yValues, erryValues, timeList, 1894, 16052, 0.435, 0.438,
        0.308, 0.216, 0.054, 0.435 / 2.5, 0.435 / 1.5, 0.435
    ])  # 0.0133, 0.175, 0.217, 0.393

    if doFit == True:
        ###################
        # Build the model #
        ###################
        evActive = evolution([ntuple[11], ntuple[12], ntuple[13]], tStart,
                             timeList[0], totalPopulation, recoveryRate,
                             symptomaticFraction, transmissionProbability)
        evolutions = [
            evolution([0, 0, ntuple[14 + i]], timeList[i], timeList[i + 1], 0,
                      recoveryRate, symptomaticFraction,
                      transmissionProbability) for i in range(3)
        ]
        evolutions.extend([
            evolution([0, 0, ntuple[14 + 3]], timeList[3], timeList[4], 0,
                      0.035, symptomaticFraction, transmissionProbability / 8)
        ])
        evolutions.extend([
            evolution([0, 0, ntuple[14 + 4]], timeList[4], timeList[5], 0,
                      recoveryRate, symptomaticFraction,
                      transmissionProbability / 2.5)
        ])
        evolutions.extend([
            evolution([0, 0, ntuple[14 + 5]], timeList[5], timeList[6], 0,
                      recoveryRate, symptomaticFraction,
                      transmissionProbability / 1.5)
        ])
        evolutions.extend([
            evolution([0, 0, ntuple[14 + 6]], timeList[6], timeList[7], 0,
                      recoveryRate, symptomaticFraction,
                      transmissionProbability)
        ])

        istat, parValues, parNames = evActive.runGlobalOptimization(
            evolutions, xValues, yValues, erryValues, [0, 1, 2, 3, 4, 5],
            doSmearing)

        evActive.evolveGlobal(evolutions, evolutions[-1].tStop, parValues,
                              True)
        if doSmearing == True:
            evActive.smearing()
        evActive.setFitFun(evActive.evolveLookUpWrapper, tStart, tStop,
                           parNames, parValues)
        evActiveGraphN = evActive.getGraphN()
        evActiveGraphN.Draw('PL same')
        statActive = evActive.addStats(parNames, parValues)

        print(
            '==> Active cases, history active cases * dt, p-infected, Carrying capacity, total population alive',
            evActive.evolveGlobal(evolutions, tStop, parValues), 'at day',
            tStop)
        print(
            '==> Percentage population with antibodies',
            round(100. *
                  evActive.totalInfectedGlobal(evolutions, tStop, parValues) /
                  totalPopulation), '% at day', tStop)

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

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

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

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

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

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

    if doFit == False:
        return [ntuple, myCanvActive, myGraphActive]
    return [
        ntuple, myCanvActive, myGraphActive, evActive, evActiveGraphN,
        statActive, now, willbe, myCanvActiveR0, evActiveGraphR0
    ]
Ejemplo n.º 8
0
            trackEfficiency
        ), "Purity= ", 100 - np.mean(correctedTrackAmbiguity), "%"
    print "Errors: Eff. Error=", np.std(trackEfficiency) / math.sqrt(
        NLoops), "Purity Err", np.std(correctedTrackAmbiguity) / math.sqrt(
            NLoops), "%"

    _Efficiency.append(np.mean(trackEfficiency))
    _Purity.append(100 - np.mean(correctedTrackAmbiguity))
    _NumberOfProtons.append(nMeanProton)
    _EfficiencyErr.append(np.std(trackEfficiency) / math.sqrt(NLoops))
    _PurityErr.append(np.std(correctedTrackAmbiguity) / math.sqrt(NLoops))
    _NumberOfProtonsErr.append(0.0)

canvas1 = TCanvas('c1', "mycanvas", 200, 10, 700, 500)

effGraph = TGraphErrors(len(_NumberOfProtons), _NumberOfProtons, _Efficiency,
                        _NumberOfProtonsErr, _EfficiencyErr)
effGraph.SetMarkerStyle(2)
effGraph.SetMarkerSize(2)
effGraph.GetXaxis().SetTitle("Mean N Proton")
effGraph.GetYaxis().SetTitle("Efficiency/Purity (%)")
effGraph.SetTitle("Efficiency")

purGraph = TGraphErrors(len(_NumberOfProtons), _NumberOfProtons, _Purity,
                        _NumberOfProtonsErr, _PurityErr)
purGraph.SetMarkerStyle(5)
purGraph.SetLineColor(2)
purGraph.SetMarkerColor(2)
purGraph.SetMarkerSize(2)
purGraph.GetXaxis().SetTitle("Mean N Proton")
purGraph.GetYaxis().SetTitle("Purity")
purGraph.SetTitle("Purity")
Ejemplo n.º 9
0
def main(argv):
    #Usage controls from OptionParser
    parser_usage = "outputfile.root"
    parser = OptionParser(usage=parser_usage)
    (options, args) = parser.parse_args(argv)
    if (len(args) != 1):
        parser.print_help()
        return

    #Get files, add to another dictionary
    run_dict = get_run_dict()
    f_list = {}
    for runnum in run_dict:
        print "Run: " + str(runnum)
        filesmatching = glob.glob(base_directory + "*_" + str(runnum) +
                                  "*.root")
        if (len(filesmatching) != 1):
            print "ERROR FINDING FILE: " + base_directory + "hd_root_" + str(
                runnum) + "*.root"
            print "exiting..."
            return
        f = TFile.Open(filesmatching[0])
        f_list[runnum] = f

    rocid_arr = array('i',
                      [31, 32, 34, 35, 37, 38, 40, 41
                       ])  #These are the rocids associated with BCAL fADC250s
    slot_arr = array(
        'i',
        [3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16
         ])  #These are the slots used for BCAL fADC250s, common to all crates
    channel_arr = array(
        'i',
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
         ])  #These are the channels used on each slot, common to all slots
    if (year == "2015"):
        rocid_arr = array(
            'i', [31, 32, 34, 35
                  ])  #These are the rocids associated with BCAL fADC250s

    h_layer1_US_RMS_arr = []
    h_layer2_US_RMS_arr = []
    h_layer3_US_RMS_arr = []
    h_layer4_US_RMS_arr = []
    h_global_US_RMS_arr = []
    h_layer1_DS_RMS_arr = []
    h_layer2_DS_RMS_arr = []
    h_layer3_DS_RMS_arr = []
    h_layer4_DS_RMS_arr = []
    h_global_DS_RMS_arr = []
    h_global_all_RMS_arr = []

    #A whole big bunch of arrays for TGraphErrors
    mean_layer1_US_RMS = array('d', [])
    mean_layer2_US_RMS = array('d', [])
    mean_layer3_US_RMS = array('d', [])
    mean_layer4_US_RMS = array('d', [])
    mean_global_US_RMS = array('d', [])
    mean_layer1_DS_RMS = array('d', [])
    mean_layer2_DS_RMS = array('d', [])
    mean_layer3_DS_RMS = array('d', [])
    mean_layer4_DS_RMS = array('d', [])
    mean_global_DS_RMS = array('d', [])
    mean_global_all_RMS = array('d', [])
    mean_err_layer1_US_RMS = array('d', [])
    mean_err_layer2_US_RMS = array('d', [])
    mean_err_layer3_US_RMS = array('d', [])
    mean_err_layer4_US_RMS = array('d', [])
    mean_err_global_US_RMS = array('d', [])
    mean_err_layer1_DS_RMS = array('d', [])
    mean_err_layer2_DS_RMS = array('d', [])
    mean_err_layer3_DS_RMS = array('d', [])
    mean_err_layer4_DS_RMS = array('d', [])
    mean_err_global_DS_RMS = array('d', [])
    mean_err_global_all_RMS = array('d', [])
    bias_arr = array('d', [])
    bias_err_arr = array('d', [])
    mean_layer1_diff_RMS = array('d', [])
    mean_layer2_diff_RMS = array('d', [])
    mean_layer3_diff_RMS = array('d', [])
    mean_layer4_diff_RMS = array('d', [])
    mean_global_diff_RMS = array('d', [])
    mean_err_layer1_diff_RMS = array('d', [])
    mean_err_layer2_diff_RMS = array('d', [])
    mean_err_layer3_diff_RMS = array('d', [])
    mean_err_layer4_diff_RMS = array('d', [])
    mean_err_global_diff_RMS = array('d', [])

    #Loop over all files
    for curr_run in f_list:
        print "Runnum: " + str(curr_run)
        print "bias V: " + str(run_dict[curr_run])

        curr_file = f_list[curr_run]
        curr_bias = run_dict[curr_run]

        #Create histograms
        hist_min = 0.
        hist_max = 4.
        h_layer1_US_RMS = TH1F("h_layer1_US_RMS_bias" + str(curr_bias),
                               "RMS of US Layer 1 Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_layer2_US_RMS = TH1F("h_layer2_US_RMS_bias" + str(curr_bias),
                               "RMS of US Layer 2 Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_layer3_US_RMS = TH1F("h_layer3_US_RMS_bias" + str(curr_bias),
                               "RMS of US Layer 3 Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_layer4_US_RMS = TH1F("h_layer4_US_RMS_bias" + str(curr_bias),
                               "RMS of US Layer 4 Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_global_US_RMS = TH1F("h_global_US_RMS_bias" + str(curr_bias),
                               "RMS of All US BCAL Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_layer1_DS_RMS = TH1F("h_layer1_DS_RMS_bias" + str(curr_bias),
                               "RMS of DS Layer 1 Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_layer2_DS_RMS = TH1F("h_layer2_DS_RMS_bias" + str(curr_bias),
                               "RMS of DS Layer 2 Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_layer3_DS_RMS = TH1F("h_layer3_DS_RMS_bias" + str(curr_bias),
                               "RMS of DS Layer 3 Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_layer4_DS_RMS = TH1F("h_layer4_DS_RMS_bias" + str(curr_bias),
                               "RMS of DS Layer 4 Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_global_DS_RMS = TH1F("h_global_DS_RMS_bias" + str(curr_bias),
                               "RMS of All DS BCAL Channels;RMS (ADC units)",
                               1000, hist_min, hist_max)
        h_global_all_RMS = TH1F("h_global_all_RMS_bias" + str(curr_bias),
                                "RMS of All BCAL Channels;RMS (ADC units)",
                                1000, hist_min, hist_max)
        #Loop over all channels
        for rocid in rocid_arr:
            for slot in slot_arr:
                for channel in channel_arr:
                    hist = get_hist_from_rocid_slot_channel(
                        curr_file, rocid, slot, channel)
                    quadrant = getquadrant(rocid)
                    layer = getlayer(slot, channel)
                    is_downstream = getend(slot, channel)
                    # if(quadrant==3): continue #Skip quadrant 3, it has LEDs firing (in 2019 at least)
                    if (quadrant == 3 or quadrant == 2 or quadrant == 4):
                        continue  #Skip quadrant 3, it has LEDs firing (in 2019 at least)
                    #Fill appropriate histograms
                    if (layer == 1 and is_downstream == 0):
                        h_layer1_US_RMS.Fill(hist.GetRMS() / sqrt(layer))
                    if (layer == 2 and is_downstream == 0):
                        h_layer2_US_RMS.Fill(hist.GetRMS() / sqrt(layer))
                    if (layer == 3 and is_downstream == 0):
                        h_layer3_US_RMS.Fill(hist.GetRMS() / sqrt(layer))
                    if (layer == 4 and is_downstream == 0):
                        h_layer4_US_RMS.Fill(hist.GetRMS() / sqrt(layer))
                    if (is_downstream == 0):
                        h_global_US_RMS.Fill(hist.GetRMS())
                    if (layer == 1 and is_downstream == 1):
                        h_layer1_DS_RMS.Fill(hist.GetRMS() / sqrt(layer))
                    if (layer == 2 and is_downstream == 1):
                        h_layer2_DS_RMS.Fill(hist.GetRMS() / sqrt(layer))
                    if (layer == 3 and is_downstream == 1):
                        h_layer3_DS_RMS.Fill(hist.GetRMS() / sqrt(layer))
                    if (layer == 4 and is_downstream == 1):
                        h_layer4_DS_RMS.Fill(hist.GetRMS() / sqrt(layer))
                    if (is_downstream == 1):
                        h_global_DS_RMS.Fill(hist.GetRMS())
                    h_global_all_RMS.Fill(hist.GetRMS())
        #End of file: add histograms to list
        h_layer1_US_RMS_arr.append(h_layer1_US_RMS)
        h_layer2_US_RMS_arr.append(h_layer2_US_RMS)
        h_layer3_US_RMS_arr.append(h_layer3_US_RMS)
        h_layer4_US_RMS_arr.append(h_layer4_US_RMS)
        h_global_US_RMS_arr.append(h_global_US_RMS)
        h_layer1_DS_RMS_arr.append(h_layer1_DS_RMS)
        h_layer2_DS_RMS_arr.append(h_layer2_DS_RMS)
        h_layer3_DS_RMS_arr.append(h_layer3_DS_RMS)
        h_layer4_DS_RMS_arr.append(h_layer4_DS_RMS)
        h_global_DS_RMS_arr.append(h_global_DS_RMS)
        h_global_all_RMS_arr.append(h_global_all_RMS)

        mean_layer1_US_RMS.append(h_layer1_US_RMS.GetMean())
        mean_layer2_US_RMS.append(h_layer2_US_RMS.GetMean())
        mean_layer3_US_RMS.append(h_layer3_US_RMS.GetMean())
        mean_layer4_US_RMS.append(h_layer4_US_RMS.GetMean())
        mean_global_US_RMS.append(h_global_US_RMS.GetMean())
        mean_layer1_DS_RMS.append(h_layer1_DS_RMS.GetMean())
        mean_layer2_DS_RMS.append(h_layer2_DS_RMS.GetMean())
        mean_layer3_DS_RMS.append(h_layer3_DS_RMS.GetMean())
        mean_layer4_DS_RMS.append(h_layer4_DS_RMS.GetMean())
        mean_global_DS_RMS.append(h_global_DS_RMS.GetMean())
        mean_global_all_RMS.append(h_global_all_RMS.GetMean())
        mean_err_layer1_US_RMS.append(h_layer1_US_RMS.GetRMS())
        mean_err_layer2_US_RMS.append(h_layer2_US_RMS.GetRMS())
        mean_err_layer3_US_RMS.append(h_layer3_US_RMS.GetRMS())
        mean_err_layer4_US_RMS.append(h_layer4_US_RMS.GetRMS())
        mean_err_global_US_RMS.append(h_global_US_RMS.GetRMS())
        mean_err_layer1_DS_RMS.append(h_layer1_DS_RMS.GetRMS())
        mean_err_layer2_DS_RMS.append(h_layer2_DS_RMS.GetRMS())
        mean_err_layer3_DS_RMS.append(h_layer3_DS_RMS.GetRMS())
        mean_err_layer4_DS_RMS.append(h_layer4_DS_RMS.GetRMS())
        mean_err_global_DS_RMS.append(h_global_DS_RMS.GetRMS())
        mean_err_global_all_RMS.append(h_global_all_RMS.GetRMS())
        bias_arr.append(curr_bias)
        bias_err_arr.append(0)

        mean_layer1_diff_RMS.append(h_layer1_DS_RMS.GetMean() -
                                    h_layer1_US_RMS.GetMean())
        mean_layer2_diff_RMS.append(h_layer2_DS_RMS.GetMean() -
                                    h_layer2_US_RMS.GetMean())
        mean_layer3_diff_RMS.append(h_layer3_DS_RMS.GetMean() -
                                    h_layer3_US_RMS.GetMean())
        mean_layer4_diff_RMS.append(h_layer4_DS_RMS.GetMean() -
                                    h_layer4_US_RMS.GetMean())
        mean_global_diff_RMS.append(h_global_DS_RMS.GetMean() -
                                    h_global_US_RMS.GetMean())
        mean_err_layer1_diff_RMS.append(
            sqrt(h_layer1_DS_RMS.GetRMS()**2 + h_layer1_US_RMS.GetRMS()**2))
        mean_err_layer2_diff_RMS.append(
            sqrt(h_layer2_DS_RMS.GetRMS()**2 + h_layer2_US_RMS.GetRMS()**2))
        mean_err_layer3_diff_RMS.append(
            sqrt(h_layer3_DS_RMS.GetRMS()**2 + h_layer3_US_RMS.GetRMS()**2))
        mean_err_layer4_diff_RMS.append(
            sqrt(h_layer4_DS_RMS.GetRMS()**2 + h_layer4_US_RMS.GetRMS()**2))
        mean_err_global_diff_RMS.append(
            sqrt(h_global_DS_RMS.GetRMS()**2 + h_global_US_RMS.GetRMS()**2))

    gr_layer1_US_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_layer1_US_RMS, bias_err_arr,
                                    mean_err_layer1_US_RMS)
    gr_layer2_US_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_layer2_US_RMS, bias_err_arr,
                                    mean_err_layer2_US_RMS)
    gr_layer3_US_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_layer3_US_RMS, bias_err_arr,
                                    mean_err_layer3_US_RMS)
    gr_layer4_US_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_layer4_US_RMS, bias_err_arr,
                                    mean_err_layer4_US_RMS)
    gr_global_US_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_global_US_RMS, bias_err_arr,
                                    mean_err_global_US_RMS)
    gr_layer1_DS_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_layer1_DS_RMS, bias_err_arr,
                                    mean_err_layer1_DS_RMS)
    gr_layer2_DS_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_layer2_DS_RMS, bias_err_arr,
                                    mean_err_layer2_DS_RMS)
    gr_layer3_DS_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_layer3_DS_RMS, bias_err_arr,
                                    mean_err_layer3_DS_RMS)
    gr_layer4_DS_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_layer4_DS_RMS, bias_err_arr,
                                    mean_err_layer4_DS_RMS)
    gr_global_DS_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                    mean_global_DS_RMS, bias_err_arr,
                                    mean_err_global_DS_RMS)
    gr_global_all_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                     mean_global_all_RMS, bias_err_arr,
                                     mean_err_global_DS_RMS)
    gr_layer1_diff_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                      mean_layer1_diff_RMS, bias_err_arr,
                                      mean_err_layer1_diff_RMS)
    gr_layer2_diff_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                      mean_layer2_diff_RMS, bias_err_arr,
                                      mean_err_layer2_diff_RMS)
    gr_layer3_diff_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                      mean_layer3_diff_RMS, bias_err_arr,
                                      mean_err_layer3_diff_RMS)
    gr_layer4_diff_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                      mean_layer4_diff_RMS, bias_err_arr,
                                      mean_err_layer4_diff_RMS)
    gr_global_diff_RMS = TGraphErrors(len(bias_arr), bias_arr,
                                      mean_global_diff_RMS, bias_err_arr,
                                      mean_err_global_diff_RMS)
    if (subtract_floor_term):
        gr_layer1_US_RMS = remove_floor_term_from_gr(gr_layer1_US_RMS)
        gr_layer2_US_RMS = remove_floor_term_from_gr(gr_layer2_US_RMS)
        gr_layer3_US_RMS = remove_floor_term_from_gr(gr_layer3_US_RMS)
        gr_layer4_US_RMS = remove_floor_term_from_gr(gr_layer4_US_RMS)
        gr_global_US_RMS = remove_floor_term_from_gr(gr_global_US_RMS)
        gr_layer1_DS_RMS = remove_floor_term_from_gr(gr_layer1_DS_RMS)
        gr_layer2_DS_RMS = remove_floor_term_from_gr(gr_layer2_DS_RMS)
        gr_layer3_DS_RMS = remove_floor_term_from_gr(gr_layer3_DS_RMS)
        gr_layer4_DS_RMS = remove_floor_term_from_gr(gr_layer4_DS_RMS)
        gr_global_DS_RMS = remove_floor_term_from_gr(gr_global_DS_RMS)
        gr_global_all_RMS = remove_floor_term_from_gr(gr_global_all_RMS)
        gr_layer1_diff_RMS = remove_floor_term_from_gr_diff(
            gr_layer1_US_RMS, gr_layer1_DS_RMS)
        gr_layer2_diff_RMS = remove_floor_term_from_gr_diff(
            gr_layer2_US_RMS, gr_layer2_DS_RMS)
        gr_layer3_diff_RMS = remove_floor_term_from_gr_diff(
            gr_layer3_US_RMS, gr_layer3_DS_RMS)
        gr_layer4_diff_RMS = remove_floor_term_from_gr_diff(
            gr_layer4_US_RMS, gr_layer4_DS_RMS)
        gr_global_diff_RMS = remove_floor_term_from_gr_diff(
            gr_global_US_RMS, gr_global_DS_RMS)
    gr_layer1_US_RMS.SetNameTitle(
        "gr_layer1_US_RMS",
        "Layer 1 Upstream;Bias (V);Pedestal Width (ADC units)")
    gr_layer2_US_RMS.SetNameTitle(
        "gr_layer2_US_RMS",
        "Layer 2 Upstream;Bias (V);Pedestal Width (ADC units)")
    gr_layer3_US_RMS.SetNameTitle(
        "gr_layer3_US_RMS",
        "Layer 3 Upstream;Bias (V);Pedestal Width (ADC units)")
    gr_layer4_US_RMS.SetNameTitle(
        "gr_layer4_US_RMS",
        "Layer 4 Upstream;Bias (V);Pedestal Width (ADC units)")
    gr_global_US_RMS.SetNameTitle(
        "gr_global_US_RMS", "ALL Upstream;Bias (V);Pedestal Width (ADC units)")
    gr_layer1_DS_RMS.SetNameTitle(
        "gr_layer1_DS_RMS",
        "Layer 1 Downstream;Bias (V);Pedestal Width (ADC units)")
    gr_layer2_DS_RMS.SetNameTitle(
        "gr_layer2_DS_RMS",
        "Layer 2 Downstream;Bias (V);Pedestal Width (ADC units)")
    gr_layer3_DS_RMS.SetNameTitle(
        "gr_layer3_DS_RMS",
        "Layer 3 Downstream;Bias (V);Pedestal Width (ADC units)")
    gr_layer4_DS_RMS.SetNameTitle(
        "gr_layer4_DS_RMS",
        "Layer 4 Downstream;Bias (V);Pedestal Width (ADC units)")
    gr_global_DS_RMS.SetNameTitle(
        "gr_global_DS_RMS",
        "ALL Downstream;Bias (V);Pedestal Width (ADC units)")
    gr_global_all_RMS.SetNameTitle(
        "gr_global_all_RMS",
        "ALL Channels;Bias (V);Pedestal Width (ADC units)")
    gr_layer1_diff_RMS.SetNameTitle(
        "gr_layer1_diff_RMS",
        "Layer 1 Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)"
    )
    gr_layer2_diff_RMS.SetNameTitle(
        "gr_layer2_diff_RMS",
        "Layer 2 Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)"
    )
    gr_layer3_diff_RMS.SetNameTitle(
        "gr_layer3_diff_RMS",
        "Layer 3 Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)"
    )
    gr_layer4_diff_RMS.SetNameTitle(
        "gr_layer4_diff_RMS",
        "Layer 4 Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)"
    )
    gr_global_diff_RMS.SetNameTitle(
        "gr_global_diff_RMS",
        "ALL Downstream - Upstream;Bias (V);Pedestal Width Difference (ADC units)"
    )

    #Save results to file
    f_out = TFile(argv[0], "RECREATE")
    f_out.cd()
    gr_layer1_US_RMS.Write()
    gr_layer2_US_RMS.Write()
    gr_layer3_US_RMS.Write()
    gr_layer4_US_RMS.Write()
    gr_global_US_RMS.Write()
    gr_layer1_DS_RMS.Write()
    gr_layer2_DS_RMS.Write()
    gr_layer3_DS_RMS.Write()
    gr_layer4_DS_RMS.Write()
    gr_global_DS_RMS.Write()
    gr_global_all_RMS.Write()
    gr_layer1_diff_RMS.Write()
    gr_layer2_diff_RMS.Write()
    gr_layer3_diff_RMS.Write()
    gr_layer4_diff_RMS.Write()
    gr_global_diff_RMS.Write()
    for i in range(0, len(h_layer1_US_RMS_arr)):
        h_layer1_US_RMS_arr[i].Write()
        h_layer2_US_RMS_arr[i].Write()
        h_layer3_US_RMS_arr[i].Write()
        h_layer4_US_RMS_arr[i].Write()
        h_global_US_RMS_arr[i].Write()
        h_layer1_DS_RMS_arr[i].Write()
        h_layer2_DS_RMS_arr[i].Write()
        h_layer3_DS_RMS_arr[i].Write()
        h_layer4_DS_RMS_arr[i].Write()
        h_global_DS_RMS_arr[i].Write()
        h_global_all_RMS_arr[i].Write()
    f_out.Close()

    print("Done")
    return
Ejemplo n.º 10
0
            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)")
#	ts_wrongmass[i].Write()
#	rootfile2[i].Close()

# this part for different plot

c2 = TCanvas("c2", "mean value of inv.m. vs top mass", 100, 100, 500, 500)

x = []
x.append(166.5)
x.append(169.5)
x.append(172.5)
x.append(173.5)
x.append(175.5)
x.append(178.5)

graph1 = TGraphErrors(6)
graph2 = TGraphErrors(6)
graph1err = TGraphErrors(6)
graph2err = TGraphErrors(6)

y = [0.] * 6
z = [0.] * 6
yerr = [0.] * 6
zerr = [0.] * 6

for i in range(0, 6):
    y[i] = ts_correct[i].GetMean()
    z[i] = ts_correctmass[i].GetMean()
    yerr[i] = ts_correct[i].GetMeanError()
    zerr[i] = ts_correctmass[i].GetMeanError()
    graph1.SetPoint(i, x[i], y[i])
Ejemplo n.º 12
0
##
## \macro_image
## \macro_code
##
## \author Wim Lavrijsen

from ROOT import TCanvas, TGraphErrors
from ROOT import gROOT
from array import array

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

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

n = 10
x = array('f', [-0.22, 0.05, 0.25, 0.35, 0.5, 0.61, 0.7, 0.85, 0.89, 0.95])
ex = array('f', [0.05, 0.1, 0.07, 0.07, 0.04, 0.05, 0.06, 0.07, 0.08, 0.05])
y = array('f', [1, 2.9, 5.6, 7.4, 9.0, 9.6, 8.7, 6.3, 4.5, 1])
ey = array('f', [0.8, 0.7, 0.6, 0.5, 0.4, 0.4, 0.5, 0.6, 0.7, 0.8])

gr = TGraphErrors(n, x, y, ex, ey)
gr.SetTitle('TGraphErrors Example')
gr.SetMarkerColor(4)
gr.SetMarkerStyle(21)
gr.Draw('ALP')

c1.Update()
c1.Draw()
c1.Print("TGrpah.png")
Ejemplo n.º 13
0
def makeBeamspotPlots(name, beamspots):
    if len(beamspots) == 0:
        print "No beamspot"

    nPoints = len(beamspots)
    print "Found", nPoints

    x = TGraphErrors(nPoints)
    x.SetName(name + "_x")
    x.SetTitle(name + "  x; lb; x [mm]")
    y = TGraphErrors(nPoints)
    y.SetName(name + "_y")
    y.SetTitle(name + "  y; lb; y [mm]")
    z = TGraphErrors(nPoints)
    z.SetName(name + "_z")
    z.SetTitle(name + "  z; lb; z [mm]")
    sx = TGraphErrors(nPoints)
    sx.SetName(name + "_sx")
    sx.SetTitle(name + "  sx; lb; #sigma(x) [mm]")
    sy = TGraphErrors(nPoints)
    sy.SetName(name + "_sy")
    sy.SetTitle(name + "  sy; lb; #sigma(y) [mm]")
    sz = TGraphErrors(nPoints)
    sz.SetName(name + "_sz")
    sz.SetTitle(name + "  sz; lb; #sigma(z) [mm]")
    ax = TGraphErrors(nPoints)
    ax.SetName(name + "_ax")
    ax.SetTitle(name + "  ax; lb; slope x-z [rad]")
    ay = TGraphErrors(nPoints)
    ay.SetName(name + "_ay")
    ay.SetTitle(name + "  ay; lb; slope y-z [rad]")
    k = TGraphErrors(nPoints)
    k.SetName(name + "_k")
    k.SetTitle(name + "  k; lb; k")
    rhoxy = TGraphErrors(nPoints)
    rhoxy.SetName(name + "_rhoxy")
    rhoxy.SetTitle(name + "  rhoxy; lb; #rho_{xy}")

    nEvents = TGraphErrors(nPoints)
    nEvents.SetName(name + "_nEvents")
    nEvents.SetTitle(name + "  nEvents; lb; nEvents")

    graphs.extend([x, y, z, sx, sy, sz, ax, ay, k, rhoxy, nEvents])

    point = 0
    for evt, bs in beamspots:
        xmid = evt.lbStart + 0.5 * evt.lumiRange
        xerr = 0.5 * evt.lumiRange

        x.SetPoint(point, xmid, bs.xc)
        y.SetPoint(point, xmid, bs.yc)
        z.SetPoint(point, xmid, bs.z)
        sx.SetPoint(point, xmid, bs.sx)
        sy.SetPoint(point, xmid, bs.sy)
        sz.SetPoint(point, xmid, bs.sz)
        ax.SetPoint(point, xmid, bs.ax)
        ay.SetPoint(point, xmid, bs.ay)
        k.SetPoint(point, xmid, bs.k)
        rhoxy.SetPoint(point, xmid, bs.rhoxy)

        nEvents.SetPoint(point, xmid, evt.nEvents)

        x.SetPointError(point, xerr, bs.Exc)
        y.SetPointError(point, xerr, bs.Eyc)
        z.SetPointError(point, xerr, bs.Ez)
        sx.SetPointError(point, xerr, bs.Esx)
        sy.SetPointError(point, xerr, bs.Esy)
        sz.SetPointError(point, xerr, bs.Esz)
        ax.SetPointError(point, xerr, bs.Eax)
        ay.SetPointError(point, xerr, bs.Eay)

        k.SetPointError(point, xerr, bs.Ek)
        rhoxy.SetPointError(point, xerr, bs.Erhoxy)
        nEvents.SetPointError(point, xerr, sqrt(evt.nEvents))

        point = point + 1
    return (x, y, z, sx, sy, sz, ax, ay, k, rhoxy, nEvents)
Ejemplo n.º 14
0
import numpy as np
from xlrd import open_workbook
from ROOT import TCanvas, TH1F, TGraph, TGraphErrors, TH1D, TLegend, TFile, TDirectory, gROOT, gStyle

gStyle.SetOptFit(1111)

totalNbOfFiles = 388;
filenamelist = open("filenamelist.txt");

#prepare histograms and root file
rootfile = TFile("Histograms1.root","recreate");
hist_spec_list = []
hist_deri_list = []
hist_comptonedge = TH1F("comptonedge_stable","",40,680,720)
gComptonVsRun = TGraphErrors()
gChi2VsRun = TGraph()
filecount = 0;
for i in range(0,totalNbOfFiles,1):
    filename = filenamelist.readline().rstrip("\r\n")
    #filename = [s[0:12] for s in filename]
    print filename
    hist_spec_name = filename + "_spec" + str(i)
    hist_spec = TH1F(hist_spec_name,"",4096,0,4096)
    hist_spec_list.append(hist_spec)
    hist_deri_name = filename + "_deri" + str(i)
    hist_deri = TH1F(hist_deri_name,"",4096,0,4096)
    hist_deri_list.append(hist_deri)
    wb = open_workbook(filename)
    totalCnts = 0
    for sheet in wb.sheets():
        number_of_rows = sheet.nrows
Ejemplo n.º 15
0
def make_tgrapherrors(name,
                      title,
                      color=1,
                      marker=20,
                      marker_size=1,
                      width=1,
                      asym_err=False,
                      style=1,
                      x=None,
                      y=None):
    if (x and y) is None:
        gr = TGraphErrors() if not asym_err else TGraphAsymmErrors()
    else:
        gr = TGraphErrors(len(x), array(x, 'd'), array(
            y, 'd')) if not asym_err else TGraphAsymmErrors(
                len(x), array(x, 'd'), array(y), 'd')
    gr.SetTitle(title)
    gr.SetName(name)
    gr.SetMarkerStyle(marker)
    gr.SetMarkerColor(color)
    gr.SetLineColor(color)
    gr.SetMarkerSize(marker_size)
    gr.SetLineWidth(width)
    gr.SetLineStyle(style)
    return gr
Ejemplo n.º 16
0
    tren_phi_er.append(0)
    asy_er.append(y_err)

# create fit function for asy
fasy = TF1("fasy", "[0]*sin(x*3.1415926/180.0)", 0.0, 361.0)
fasy.SetParameter(0, 1)

c1 = TCanvas("c1", "canvas", 800, 800)
gStyle.SetOptStat(0000)
c1.Divide(2, 2)

c1.cd(1)
h_pos_asym.SetTitle("Counts with Pos. Helicity; #phi_{trento}; Counts")
h_pos_asym.Draw()

c1.cd(2)
h_neg_asym.SetTitle("Counts with Neg. Helicity; #phi_{trento}; Counts")
h_neg_asym.Draw()

c1.cd(3)
h_p_copy.SetTitle("Pos.-Neg. Helicity; #phi_{trento}; Counts")
h_p_copy.Draw()

c1.cd(4)
g_asy = TGraphErrors(len(tren_phi), tren_phi, asy, tren_phi_er, asy_er)
g_asy.SetTitle("Measured Asym; #phi_{trento}; Asym")
g_asy.Fit("fasy")
g_asy.Draw("AP")
fasy.Draw("same")
c1.SaveAs("phi_asy.pdf")
Ejemplo n.º 17
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.)
    jmuonpt_1 = RooRealVar("jmuonpt_1", "j1 muon pt", 0., 13000.)
    jmuonpt_2 = RooRealVar("jmuonpt_2", "j2 muon pt", 0., 13000.)
    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, jmuonpt_1, jmuonpt_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 = "bstar_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_bstar_" + YEAR + "/" + stype + "_" +
                    category + "_Signal.pdf")
    c_signal.SaveAs(PLOTDIR + "MC_bstar_" + 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)
    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")
    islope1.Draw("P, SAME")
    drawRegion(category)
    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)
        galpha2.GetYaxis().SetRangeUser(0., 2.)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(category)
        gslope2.GetYaxis().SetRangeUser(0., 20.)

    c1.Print(PLOTDIR + "MC_bstar_" + YEAR + "/" + stype + "_" + category +
             "_SignalShape.pdf")
    c1.Print(PLOTDIR + "MC_bstar_" + 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_bstar_" + YEAR + "/" + stype + "_" + category +
             "_SignalNorm.pdf")
    c2.Print(PLOTDIR + "MC_bstar_" + YEAR + "/" + stype + "_" + category +
             "_SignalNorm.png")

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

    # create workspace
    w = RooWorkspace("bstar_" + 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.º 18
0
def main(network_name, do_weights, general_weights, electron_weights,
         muon_weights, data_files, no_true_comp, nbins, veto_all_jets,
         require_jets, WorkingP_List, Independant_Variable_List,
         Histogram_Variable_List, Profile_List, TH2D_List):

    TH1.SetDefaultSumw2()

    ## First we check that you havent vetoed and requested jets
    if veto_all_jets and require_jets:
        print("\n\n\nYOU CANT ASK FOR NONE YET SOME JETS\n\n\n")
        return 0

    for data_dir, data_set_name in data_files:
        OUTPUT_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Output")
        DATA_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Data")
        data_base_dir = os.path.join(DATA_dir, data_dir)
        print("\n\n" + data_set_name)
        """
         ____    ____    _____   ____       _      ____       _      _____   ___    ___    _   _
        |  _ \  |  _ \  | ____| |  _ \     / \    |  _ \     / \    |_   _| |_ _|  / _ \  | \ | |
        | |_) | | |_) | |  _|   | |_) |   / _ \   | |_) |   / _ \     | |    | |  | | | | |  \| |
        |  __/  |  _ <  | |___  |  __/   / ___ \  |  _ <   / ___ \    | |    | |  | |_| | | |\  |
        |_|     |_| \_\ |_____| |_|     /_/   \_\ |_| \_\ /_/   \_\   |_|   |___|  \___/  |_| \_|

        """

        ## The list of matrices
        Indp_output = [None for var in Independant_Variable_List]
        TH1D_output = [[None for wp in WorkingP_List]
                       for var in Histogram_Variable_List]
        Tail_output = [[None for wp in WorkingP_List]
                       for var in Histogram_Variable_List]
        Prof_output = [[None for wp in WorkingP_List] for var in Profile_List]
        TH2D_output = [[None for wp in WorkingP_List] for var in TH2D_List]

        ## Open the root file
        root_file = TFile.Open(os.path.join(data_base_dir, data_set_name))

        ## Loading the tree containing the working point information
        wpt_tree = root_file.Get("wpt_tree")

        ## Making the wpt_tree and the other trees friends so that they can be compared
        wpt_tree.AddFriend(network_name, root_file)
        wpt_tree.AddFriend("alt_tree", root_file)
        wpt_tree.AddFriend("var_tree", root_file)

        ## Creating a string of all the weights to be applied
        event_weights = []
        if "SR" in data_dir: event_weights += general_weights
        if "ee" in data_dir: event_weights += electron_weights
        if "mumu" in data_dir: event_weights += muon_weights

        if veto_all_jets:
            event_weights += ["(var_tree.Jets_Loose_SumET==0)"]
        if require_jets:
            event_weights += ["(var_tree.Jets_Loose_SumET>0)"]

        if do_weights: weight_string = " * ".join(event_weights)
        else: weight_string = ""

        if len(weight_string):
            print("Events are weighted using: {}".format(weight_string))

        ## The strings to call up the Truth Values
        if no_true_comp:
            True_Et = "0"
            True_Ex = "0"
            True_Ey = "0"
            True_Phi = "0"
        else:
            True_Et = "WP_Truth_ET"
            True_Ex = "WP_Truth_X"
            True_Ey = "WP_Truth_Y"
            True_Phi = "WP_Truth_Phi"
        """
         ____    ____       _     __        __  ___   _   _    ____
        |  _ \  |  _ \     / \    \ \      / / |_ _| | \ | |  / ___|
        | | | | | |_) |   / _ \    \ \ /\ / /   | |  |  \| | | |  _
        | |_| | |  _ <   / ___ \    \ V  V /    | |  | |\  | | |_| |
        |____/  |_| \_\ /_/   \_\    \_/\_/    |___| |_| \_|  \____|

        """

        ## Before the workingpoint loop, the independant variables are drawn
        for v, var in enumerate(Independant_Variable_List):
            print(" -- {}".format(var.name))

            ## Creating the histogram which will be filled
            hist_name = var.name
            myhist = TH1D(hist_name, hist_name, var.nbins, var.xmin, var.xmax)
            myhist.SetStats(True)
            myhist.StatOverflows(True)

            ## Get Maths Function from variable
            maths_string = var.tree + "." + var.branch

            ## Drawing the tree and saving the hist to the matrix
            execution = "{}>>{}".format(maths_string, hist_name)
            wpt_tree.Draw(execution, weight_string, "goff")

            ## Saving the Histogram to the Matrix
            myhist.SetDirectory(0)
            Indp_output[v] = myhist

        ## First we select the working point and create the correct strings
        for w, wp in enumerate(WorkingP_List):
            print(" -- {}:".format(wp.name))

            Rec_Et = wp.Et
            Rec_Ex = wp.Ex
            Rec_Ey = wp.Ey
            Rec_Phi = wp.Phi
            if wp.tree == "ann_tree":
                Rec_Et = network_name + "." + Rec_Et
                Rec_Ex = network_name + "." + Rec_Ex
                Rec_Ey = network_name + "." + Rec_Ey

            rec_and_truth_vars = [
                Rec_Et, Rec_Ex, Rec_Ey, Rec_Phi, True_Et, True_Ex, True_Ey,
                True_Phi
            ]

            ## Drawing the 1D histograms
            for v, var in enumerate(Histogram_Variable_List):
                print(" -- -- {}".format(var.name))

                ## Creating the histogram which will be filled
                hist_name = "{}_{}".format(var.name, wp.name)
                myhist = TH1D(hist_name, hist_name, var.nbins, var.xmin,
                              var.xmax)
                myhist.SetStats(True)
                myhist.StatOverflows(True)

                ## Individual special plots
                if var.name == "XY":
                    ## Plot the X histogram
                    maths_string = Evaluation.TH1D_Maths_String(
                        "X", *rec_and_truth_vars)
                    execution = "{} >> {}".format(maths_string, hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff")

                    ## Add the y histogram
                    maths_string = Evaluation.TH1D_Maths_String(
                        "Y", *rec_and_truth_vars)
                    execution = "{} >> +{}".format(maths_string, hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff")

                else:
                    ## Get Maths Function from variable
                    maths_string = Evaluation.TH1D_Maths_String(
                        var.name, *rec_and_truth_vars)

                    ## Drawing the tree and saving the hist to the matrix
                    execution = "{} >> {}".format(maths_string, hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff")

                ## Saving the Histogram to the Matrix
                myhist.SetDirectory(0)
                TH1D_output[v][w] = myhist

            ## Drawing the Profiles
            for v, (vx, vy) in enumerate(Profile_List):
                print(" -- -- {} vs {}".format(vx.name, vy.name))

                ## Creating the profile which will be filled
                hist_name = "{}_vs_{}_{}".format(vx.name, vy.name, wp.name)
                myhist = TProfile(hist_name, hist_name, vx.nbins, vx.xmin,
                                  vx.xmax)

                if vy.reso: myhist.SetErrorOption('s')

                ## The x variable is called from its branch in the correct tree
                x_string = vx.tree + "." + vx.branch

                ## Individual special plots
                if vy.name == "XY":
                    y_string = Evaluation.TH1D_Maths_String(
                        "X", *rec_and_truth_vars)
                    execution = "{}:{} >> {}".format(y_string, x_string,
                                                     hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff prof")

                    y_string = Evaluation.TH1D_Maths_String(
                        "Y", *rec_and_truth_vars)
                    execution = "{}:{} >>+{}".format(y_string, x_string,
                                                     hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff prof")

                elif vy.name == "AZ":
                    z_x = "(alt_tree.ll_px)"
                    z_y = "(alt_tree.ll_py)"
                    z_pt = "(alt_tree.ll_pt)"

                    x_string = z_pt
                    y_string = "({rx}*{zx} + {ry}*{zy})/{zpt}".format(
                        rx=Rec_Ex, ry=Rec_Ey, zx=z_x, zy=z_y, zpt=z_pt)
                    execution = "{}:{} >> {}".format(y_string, x_string,
                                                     hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff prof")

                else:
                    y_string = Evaluation.TH1D_Maths_String(
                        vy.name, *rec_and_truth_vars)
                    execution = "{}:{} >> {}".format(y_string, x_string,
                                                     hist_name)
                    wpt_tree.Draw(execution, weight_string, "goff prof")

                ## Saving the Histogram to the Matrix
                myhist.SetDirectory(0)
                Prof_output[v][w] = myhist

            if wp.name not in ["Network", "Tight"]:
                continue

            ## Drawing the TH2Ds
            for v, (vx, vy) in enumerate(TH2D_List):
                print(" -- -- {} vs {}".format(vx.name, vy.name))

                ## Creating the profile which will be filled
                hist_name = "2D_{}_vs_{}_{}".format(vx.name, vy.name, wp.name)
                myhist = TH2D(hist_name, hist_name, vx.nbins2d, vx.xmin2d,
                              vx.xmax2d, vy.nbins2d, vy.xmin2d, vy.xmax2d)

                x_string = Evaluation.TH1D_Maths_String(
                    vx.name, *rec_and_truth_vars)
                y_string = Evaluation.TH1D_Maths_String(
                    vy.name, *rec_and_truth_vars)

                ## The x variable is called from its branch in the correct tree
                if x_string is None:
                    x_string = vx.tree + "." + vx.branch

                execution = "{}:{} >> {}".format(y_string, x_string, hist_name)
                wpt_tree.Draw(execution, weight_string, "goff")

                ## Saving the Histogram to the Matrix
                myhist.SetDirectory(0)
                TH2D_output[v][w] = myhist

        root_file.Close()
        """
         _____   ____    ___   _____   ___   _   _    ____
        | ____| |  _ \  |_ _| |_   _| |_ _| | \ | |  / ___|
        |  _|   | | | |  | |    | |    | |  |  \| | | |  _
        | |___  | |_| |  | |    | |    | |  | |\  | | |_| |
        |_____| |____/  |___|   |_|   |___| |_| \_|  \____|

        """

        ## We now go through the 1D histograms and make them include overflow and underflow
        for v, var in enumerate(Histogram_Variable_List):
            for w, wp in enumerate(WorkingP_List):

                ## Include the overflow
                last_bin = TH1D_output[v][w].GetBinContent(nbins)
                overflow = TH1D_output[v][w].GetBinContent(nbins + 1)
                TH1D_output[v][w].SetBinContent(nbins, last_bin + overflow)
                TH1D_output[v][w].SetBinContent(nbins + 1, 0)

                ## Include the underflow
                first_bin = TH1D_output[v][w].GetBinContent(1)
                underflow = TH1D_output[v][w].GetBinContent(0)
                TH1D_output[v][w].SetBinContent(1, first_bin + underflow)
                TH1D_output[v][w].SetBinContent(0, 0)

                ## We create a tail distrobution if it is requested
                if var.tail:
                    tail_temp = TH1D_output[v][w].GetCumulative(False)
                    tail_temp.Scale(1 / tail_temp.GetBinContent(1))
                    Tail_output[v][w] = tail_temp

        ## We go through the resolution profiles and replace their entries with the RMSE for each bin
        for v, (vx, vy) in enumerate(Profile_List):

            if not vy.reso:
                continue

            for w, wp in enumerate(WorkingP_List):

                old_prof = Prof_output[v][w]
                bin_width = old_prof.GetBinWidth(1)

                name = "{}_vs_{}_{}_res".format(vx.name, vy.name, wp.name)
                new_prof = TGraphErrors(vx.nbins)
                new_prof.SetName(name)
                new_prof.SetTitle(name)

                new_prof.SetLineWidth(2)

                for b_idx in range(vx.nbins):
                    new_prof.SetPoint(b_idx, old_prof.GetBinCenter(b_idx + 1),
                                      old_prof.GetBinError(b_idx + 1))
                    new_prof.SetPointError(b_idx, bin_width / 2, 0)

                Prof_output[v][w] = new_prof
        """
         ____       _     __     __  ___   _   _    ____
        / ___|     / \    \ \   / / |_ _| | \ | |  / ___|
        \___ \    / _ \    \ \ / /   | |  |  \| | | |  _
         ___) |  / ___ \    \ V /    | |  | |\  | | |_| |
        |____/  /_/   \_\    \_/    |___| |_| \_|  \____|

        """

        ## Creating the output directory
        output_dir = os.path.join(OUTPUT_dir, network_name, data_set_name[:-5])
        if veto_all_jets:
            output_dir = output_dir + "_NOJETS"
        if require_jets:
            output_dir = output_dir + "_SOMEJETS"

        ## Check that the file can be saved
        if not os.path.exists(output_dir):
            os.system("mkdir -p " + output_dir)

        ## We create an output file for the histograms
        output_file = TFile(os.path.join(output_dir, "histograms.root"),
                            "update")
        gFile = output_file

        ## We save the independants
        for v, var in enumerate(Independant_Variable_List):
            Indp_output[v].Write("", TObject.kOverwrite)

        ## We save the TH1Ds and tails
        for v, var in enumerate(Histogram_Variable_List):
            for w in range(len(WorkingP_List)):
                TH1D_output[v][w].Write("", TObject.kOverwrite)
                if var.tail:
                    Tail_output[v][w].Write("", TObject.kOverwrite)

        ## We save the profiles
        for v in range(len(Profile_List)):
            for w in range(len(WorkingP_List)):
                Prof_output[v][w].Write("", TObject.kOverwrite)

        ## We save the TH2Ds
        for v in range(len(TH2D_List)):
            for w in range(len(WorkingP_List[:2])):
                TH2D_output[v][w].Write("", TObject.kOverwrite)

        output_file.Close()
    return 0
Ejemplo n.º 19
0
def makeBeamspotCutPlots(name, points):
    nPoints = len(points)

    x = TGraphErrors(nPoints)
    x.SetName(name)
    x.SetTitle(name + "  x; lb; x [mm]")
    y = TGraphErrors(nPoints)
    y.SetName(name)
    y.SetTitle(name + "  y; lb; y [mm]")
    z = TGraphErrors(nPoints)
    z.SetName(name)
    z.SetTitle(name + "  z; lb; z [mm]")
    sx = TGraphErrors(nPoints)
    sx.SetName(name)
    sx.SetTitle(name + "  sx; lb; #sigma(x) [mm]")
    sy = TGraphErrors(nPoints)
    sy.SetName(name)
    sy.SetTitle(name + "  sy; lb; #sigma(y) [mm]")
    sz = TGraphErrors(nPoints)
    sz.SetName(name)
    sz.SetTitle(name + "  sz; lb; #sigma(z) [mm]")

    xrms = TGraphErrors(nPoints)
    xrms.SetName(name + "_rms")
    xrms.SetTitle(name + "_rms" + "  x")
    yrms = TGraphErrors(nPoints)
    yrms.SetName(name + "_rms")
    yrms.SetTitle(name + "_rms" + "  y")
    zrms = TGraphErrors(nPoints)
    zrms.SetName(name + "_rms")
    zrms.SetTitle(name + "_rms" + "  z")
    sxrms = TGraphErrors(nPoints)
    sxrms.SetName(name + "_rms")
    sxrms.SetTitle(name + "_rms" + "  sx")
    syrms = TGraphErrors(nPoints)
    syrms.SetName(name + "_rms")
    syrms.SetTitle(name + "_rms" + "  sy")
    szrms = TGraphErrors(nPoints)
    szrms.SetName(name + "_rms")
    szrms.SetTitle(name + "_rms" + "  sz")

    graphs.extend([x, y, z, sx, sy, sz, xrms, yrms, zrms, sxrms, syrms, szrms])
    print len(points)
    for i in range(len(points)):
        xval = points[i][0]
        yvals = points[i][1]

        xerr = 0

        x.SetPoint(i, xval, yvals[0][0])
        y.SetPoint(i, xval, yvals[1][0])
        z.SetPoint(i, xval, yvals[2][0])
        sx.SetPoint(i, xval, yvals[3][0])
        sy.SetPoint(i, xval, yvals[4][0])
        sz.SetPoint(i, xval, yvals[5][0])

        x.SetPointError(i, xerr, yvals[0][1])
        y.SetPointError(i, xerr, yvals[1][1])
        z.SetPointError(i, xerr, yvals[2][1])
        sx.SetPointError(i, xerr, yvals[3][1])
        sy.SetPointError(i, xerr, yvals[4][1])
        sz.SetPointError(i, xerr, yvals[5][1])

        xrms.SetPoint(i, xval, yvals[0][2])
        yrms.SetPoint(i, xval, yvals[1][2])
        zrms.SetPoint(i, xval, yvals[2][2])
        sxrms.SetPoint(i, xval, yvals[3][2])
        syrms.SetPoint(i, xval, yvals[4][2])
        szrms.SetPoint(i, xval, yvals[5][2])

        xrms.SetPointError(i, xerr, yvals[0][3])
        yrms.SetPointError(i, xerr, yvals[1][3])
        zrms.SetPointError(i, xerr, yvals[2][3])
        sxrms.SetPointError(i, xerr, yvals[3][3])
        syrms.SetPointError(i, xerr, yvals[4][3])
        szrms.SetPointError(i, xerr, yvals[5][3])

    c = TCanvas("cx")
    c.Divide(3, 1)
    c.cd(1)
    x.Draw("ap")
    c.cd(2)
    y.Draw("ap+Y+")
    c.cd(3)
    yaxis_xrms = TGaxis(-1, 0.2, 1, 0.2, -1, 2, 510, "+R")
    yaxis_xrms.ImportAxisAttributes(y.GetHistogram().GetYaxis())
    #g = TMultiGraph()
    #g.Add(x,"aXp")
    #g.Add(y,"aY*")
    #g.Draw("a")
    # graphs.append(g)
    #   aa = y.GetHistogram()

    #x.Draw("ap")
    yaxis_xrms.Draw()
    #axis.PaintAxis(0,0.5,0.1,0.6,0.4,1.4,510,"+R")
    #y.Draw("pY+sames")
    #b.Draw("sames")
    c.Modified()
    c.Update()
    #c.Print()
    canvases.append(c)
Ejemplo n.º 20
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.º 21
0
def main(argv):

    print(len(argv))
    if len(argv) == 5:
        #print ('The script is called: '+str(script))
        print('Number of M bins is: ' + argv[0])
        print('Number of t bins is: ' + argv[1])
        print('Number of bootstrap samples is:' + argv[2])
        print('Directory for bootstrap results for different M bins is: ' +
              argv[3])
        print(
            'Intensity results from fitting the original data are written in: '
            + argv[4])

    else:
        sys.exit(
            "You need to give 5 args..., usage: python script.py Nmassbins Ntbins NBootstrapsamples Bindir fitresultfile"
        )

    NumBins, NumtBins, kBootstrapPoints, Binfolderdir, Fitresultfile = argv
    NumBins = int(NumBins)
    NumtBins = int(NumtBins)
    kBootstrapPoints = int(kBootstrapPoints)

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

    with open(Fitresultfile, 'r') as f:
        t = f.read()
        l = t.splitlines()
        amps = l[0]
        amps = amps.split()[
            2::2]  # start at 3rd element and take every other element
        N_amps = (len(l[0].split()) -
                  2) / 2  #first two arguments in the line are M and t

    print(amps)
    print(N_amps)

    if N_amps < 1:
        sys.exit("You should specify at least one moment")

    ## column number for M value and each of the amplitude intensities and
    ##corresponding errors
    column_m = 0
    column_t = 1
    colomn_moments = np.arange(2, 2 * N_amps + 1, 2)
    colomn_moments_err = np.arange(3, 2 * N_amps + 2, 2)
    mass_bins = np.zeros(NumBins)

    ## Arrays of  intensities from fitting the original data in different M bins
    orig_moment = np.zeros((N_amps, NumtBins, NumBins))
    ##Reading uncertainties from MINUIT
    orig_moment_err = np.zeros((N_amps, NumtBins, NumBins))

    ## Asigning values to arrays of moments from fitting the original fit amplitude calculation in
    ##different M and t 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[1:]:

        fit_res_colomns = len(x.split())
        mass_bins[j / NumtBins] = float(x.split()[column_m])

        for Moms in range(0, N_amps):

            orig_moment[Moms][int(j % NumtBins)][int(j / NumtBins)] = float(
                x.split()[colomn_moments[Moms]])
            orig_moment_err[Moms][int(j % NumtBins)][j / NumtBins] = float(
                x.split()[colomn_moments_err[Moms]])

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

    ## Arrays of values for given moment from
    ##fitting different bootstrapping samples
    moments = np.zeros((N_amps, kBootstrapPoints))

    #uncertainty on the given moment for each M and t bin
    std_moments = np.zeros((N_amps, NumtBins, NumBins))

    ## Histograms of moments for given mass and t bin and moment from different bootstraping samples

    h1_list_moments = []
    i_Mbin = 0
    for Mb in range(0, NumBins):
        h1_list_moments.append([])

        for tb in range(0, NumtBins):
            h1_list_moments[i_Mbin].append([])
        i_Mbin = i_Mbin + 1

    #Defining histograms for moments from different bootstraping samples for a given aplitude and M bin
    for Bin in range(0, NumBins):

        #N_bins=int(300*orig_all_moments[Bin])
        N_bins = int(80000)
        x_min = int(-500)

        for Bint in range(0, NumtBins):

            for Moms in range(0, N_amps):

                x_max = int(3 * orig_moment[Moms][Bint][Bin])
                if Moms == 11 and Bint == 0 and Bin == 5:
                    x_max = 1000000
                h1_list_moments[Bin][Bint].append(
                    TH1F(
                        'h1_boot_' + str(amps[Moms]) +
                        '_Mbin' + str(Bin + 1) + '_tbin' + str(Bint + 1),
                        str(amps[Moms]), N_bins, x_min, x_max))

    ## Assigning values to arrays of values for given moment from fitting different bootstrapping samples
    ## by reading the values from files of each of the M and t bins
    ##(number of lines in the .txt file corresponds to number of bootstraping samples + 1)
    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[1:]:  #First line has the names of arguments

                if len(x.split()) != fit_res_colomns:
                    sys.exit(
                        "Fit results and bootstraping results have different number of moments"
                    )

                for Moms in range(0, N_amps):
                    moments[Moms][i] = x.split()[colomn_moments[Moms]]
                    h1_list_moments[bin][bint][Moms].Fill(moments[Moms][i])

                i = i + 1
            token.close()

            for Moms in range(0, N_amps):
                std_moments[Moms][bint][bin] = moments[Moms].std()

    print('I am here')

    ##The graphs of intensities of different Moms
    error_M = np.zeros(NumBins)
    grerr_list_moment = []
    t_bin = 0
    for Moms in range(0, N_amps):
        grerr_list_moment.append(
            TGraphErrors(NumBins, mass_bins, orig_moment[Moms][t_bin], error_M,
                         std_moments[Moms][t_bin]))

    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 Moms in range(0, N_amps):
        grerr_list_moment[Moms].SetMarkerSize(.5)
        grerr_list_moment[Moms].SetMarkerStyle(20)
        grerr_list_moment[Moms].SetName(amps[Moms])
        grerr_list_moment[Moms].SetTitle(amps[Moms])
        grerr_list_moment[Moms].SetMaximum(1.2 * np.amax(orig_moment[Moms]))

        grerr_list_moment[Moms].SetMinimum(0.8 * np.amin(orig_moment[Moms]))
        grerr_list_moment[Moms].Draw('AP')
        grerr_list_moment[Moms].SetName(amps[Moms])
        grerr_list_moment[Moms].Write()
        c1.Print('Plots/Moment_' + amps[Moms] + '_boot.pdf')

    file_out.Write()
    file_out.Close()
Ejemplo n.º 22
0
def comparePxcone( filename="sjm91_all.root", optKind="emin", optRate="R2" ):

    pr097vals= dict()
    pr097st= dict()
    pr097sy= dict()
    arrays= ascii2arrays( "pr097-pxcone"+optKind+".txt" )
    pr097pts= arrays[0]
    pr097vals["R2"]= arrays[1]
    pr097st["R2"]= arrays[2]
    pr097sy["R2"]= arrays[3]
    pr097vals["R3"]= arrays[4]
    pr097st["R3"]= arrays[5]
    pr097sy["R3"]= arrays[6]
    pr097vals["R4"]= arrays[7]
    pr097st["R4"]= arrays[8]
    pr097sy["R4"]= arrays[9]        
    npr097pts= len( pr097pts )
    vexpr097= array( "d", npr097pts*[0.0] )
    pr097vals= np.divide( pr097vals[optRate], 100.0 )
    pr097st= np.divide( pr097st[optRate], 100.0 )
    pr097sy= np.divide( pr097sy[optRate], 100.0 )    
    pr097tot= np.sqrt( np.add( np.square( pr097st ),  np.square( pr097sy ) ) )

    pr408vals= dict()
    pr408st= dict()
    pr408sy= dict()
    arrays= ascii2arrays( "pr408-pxcone"+optKind+"91.txt" )
    pr408pts= arrays[0]
    pr408vals["R2"]= arrays[1]
    pr408st["R2"]= arrays[2]
    pr408sy["R2"]= arrays[3]
    pr408vals["R3"]= arrays[4]
    pr408st["R3"]= arrays[5]
    pr408sy["R3"]= arrays[6]
    pr408vals["R4"]= arrays[7]
    pr408st["R4"]= arrays[8]
    pr408sy["R4"]= arrays[9]        
    npr408pts= len( pr408pts )
    vexpr408= array( "d", npr408pts*[0.0] )
    pr408vals= pr408vals[optRate]
    pr408st= np.divide( pr408st[optRate], 100.0 )
    pr408sy= np.divide( pr408sy[optRate] , 100.0 )
    pr408tot= np.sqrt( np.add( np.square( pr408st ),  np.square( pr408sy ) ) )
    
    f= TFile( filename )
    aopxcone= createAnalysisObservable( f, "pxcone"+optKind+optRate )
    xmax= { "R": 1.7, "emin": 27.0 }
    ymax= { "R2": 1.1, "R3": 0.35, "R4": 0.18 }
    xlabel= { "R": "R [rad.]", "emin": "E_{min} [GeV]" }
    ylabel= { "R2": "2-jet rate", "R3": "3-jet rate", "R4": "4-jet rate" }
    plotoptions= { "xmin": 0.0, "xmax": xmax[optKind], "ymin": 0.0, "ymax": ymax[optRate],
                       "markerStyle": 20, "markerSize": 0.8,
                       "xlabel": xlabel[optKind], "ylabel": ylabel[optRate],
                       "title": "Cone "+optKind+" "+filename }
    aopxcone.plot( plotoptions )
    xshift= { "R": 0.02, "emin": 0.2 }
    pr097pts= np.add( pr097pts, -xshift[optKind] )
    tgepr097= TGraphErrors( npr097pts, pr097pts, pr097vals, vexpr097, pr097tot )
    tgepr097.SetMarkerStyle( 24 )
    tgepr097.SetMarkerSize( 1.0 )
    tgepr097.SetName( "pr097" )
    tgepr097.Draw( "psame" )
    pr408pts= np.add( pr408pts, xshift[optKind] )
    tgepr408= TGraphErrors( npr408pts, pr408pts, pr408vals, vexpr408, pr408tot )
    tgepr408.SetMarkerStyle( 29 )
    tgepr408.SetMarkerSize( 1.0 )
    tgepr408.SetName( "pr408" )
    tgepr408.Draw( "psame" )    
    tl= TLegend( 0.7, 0.5, 0.9, 0.7 )
    tl.AddEntry( "pr097", "OPAL PR097", "ep" )
    tl.AddEntry( "pr408", "OPAL PR408", "ep" )
    tl.AddEntry( "pxcone"+optKind+optRate, filename, "ep" )
    tl.Draw()
    return
Ejemplo n.º 23
0
vis.Draw()
c3.Update()
c3.Print(vis_pdf) # save to pdf
# Save graph to file
OutputFilevis = '%svisibility_voltage_plot_%s.root' % (OutputPath, scan)
f3 = TFile(OutputFilevis, "RECREATE")
vis.Write()
f3.Close()

# Voltage plots 
# Draw graphs
voltage_pdf1 = '%sscan%s_peak1_voltage.pdf' % (PDFFilePath, scan)
voltage_pdf2 = '%sscan%s_peak2_voltage.pdf' % (PDFFilePath, scan)
voltage_pdf3 = '%sscan%s_peak3_voltage.pdf' % (PDFFilePath, scan)
c2 = TCanvas("c2", "Peak VS Voltage", 200, 10, 700, 500)
graph1v = TGraphErrors(n_points, voltage_sq, peak1_array, voltage_error, error1_array)
graph1v.SetTitle("peak 1")
graph1v.GetXaxis().SetTitle("Voltage^2 (V^2)")
graph1v.GetYaxis().SetTitle("Peaks Amp (mV)")
graph1v.Draw()
c2.Update()
c2.Print(voltage_pdf1)

c2.Clear()
graph2v = TGraphErrors(n_points, voltage_sq, peak2_array, voltage_error, error2_array)
graph2v.SetTitle("peak 2")
graph2v.GetXaxis().SetTitle("Voltage^2 (V^2)")
graph2v.GetYaxis().SetTitle("Peaks Amp (mV)")
graph2v.Draw()
c2.Update()
c2.Print(voltage_pdf2)
Ejemplo n.º 24
0
def compareDurhamjetrates( filename="sjm91_all.root",
                           datafilename="/home/iwsatlas1/skluth/Downloads/JRTMC/share/NEW/data.dat",
                           donkersfilename="donkers-durhamjets91.txt" ):
    f= TFile( filename )
    R2ao= createAnalysisObservable( f, "durhamycutfjR2" )
    R3ao= createAnalysisObservable( f, "durhamycutfjR3" )
    plotoptions= { "xmin": 0.0005, "xmax": 0.5, "ymin": 0.0, "ymax": 1.05, "markerStyle": 20,
                       "markerSize": 0.75, "title": "Durham R2 and R3 "+filename,
                       "xlabel": "y_{cut}", "ylabel": "Jet rates", "logx": 1 }
    R2tgest, R2tgesy= R2ao.plot( plotoptions )
    plotoptions["markerStyle"]= 21
    R3tgest, R3tgesy= R3ao.plot( plotoptions, "s" )

    arrays= ascii2arrays( datafilename )
    ycutpoints= arrays[0]
    R2values= np.divide( arrays[1], 100.0 )
    R2sterrs= np.divide( arrays[2], 100.0 )
    R2syerrs= np.divide( arrays[3], 100.0 )
    R3values= np.divide( arrays[4], 100.0 )
    R3sterrs= np.divide( arrays[5], 100.0 )
    R3syerrs= np.divide( arrays[6], 100.0 )
    R2errs= np.sqrt( np.add( np.square( R2sterrs ), np.square( R2syerrs ) ) )
    R3errs= np.sqrt( np.add( np.square( R3sterrs ), np.square( R3syerrs ) ) )
    n= len(ycutpoints)
    xerrs= array( "d", n*[0.0] )

    R2datatge= TGraphErrors( n, ycutpoints, R2values, xerrs, R2errs )
    R2datatge.SetMarkerStyle( 24 )
    R2datatge.SetMarkerSize( 0.75 )    
    R2datatge.SetName( "R2datatge" )
    R2datatge.Draw( "psame" )
    R3datatge= TGraphErrors( n, ycutpoints, R3values, xerrs, R3errs )
    R3datatge.SetMarkerStyle( 25 )
    R3datatge.SetMarkerSize( 0.75 )    
    R3datatge.SetName( "R3datatge" )
    R3datatge.Draw( "psame" )

    legend= TLegend( 0.6, 0.6, 0.9, 0.9 )
    R2tgesy.SetName( "R2tgesy" )
    legend.AddEntry( "R2tgesy", "OPAL R2", "pe" )
    R3tgesy.SetName( "R3tgesy" )
    legend.AddEntry( "R3tgesy", "OPAL R3", "pe" )
    legend.AddEntry( "R2datatge", "Andrii R2", "pe" )
    legend.AddEntry( "R3datatge", "Andrii R3", "pe" )

    if donkersfilename:
        dkarrays= ascii2arrays( donkersfilename )
        dkycutpoints= np.power( 10.0, dkarrays[0] )
        dkR2values= dkarrays[1]
        dkR2sterrs= np.divide( dkarrays[2], 100.0 )
        dkR2syerrs= np.divide( dkarrays[3], 100.0 )
        dkR3values= dkarrays[4]
        dkR3sterrs= np.divide( dkarrays[5], 100.0 )
        dkR3syerrs= np.divide( dkarrays[6], 100.0 )
        dkR2errs= np.sqrt( np.add( np.square( dkR2sterrs ), np.square( dkR2syerrs ) ) )
        dkR3errs= np.sqrt( np.add( np.square( dkR3sterrs ), np.square( dkR3syerrs ) ) )
        dkn= len( dkycutpoints )
        dkxerrs= array( "d", dkn*[0.0] )
        dkR2datatge= TGraphErrors( dkn, dkycutpoints, dkR2values, dkxerrs, dkR2errs )
        dkR2datatge.SetMarkerStyle( 26 )
        dkR2datatge.SetMarkerSize( 0.75 )    
        dkR2datatge.SetName( "dkR2datatge" )
        dkR2datatge.Draw( "psame" )
        dkR3datatge= TGraphErrors( dkn, dkycutpoints, dkR3values, dkxerrs, dkR3errs )
        dkR3datatge.SetMarkerStyle( 27 )
        dkR3datatge.SetMarkerSize( 0.75 )    
        dkR3datatge.SetName( "dkR3datatge" );
        dkR3datatge.Draw( "psame" )
        legend.AddEntry( "dkR2datatge", "Donkers R2", "pe" )
        legend.AddEntry( "dkR3datatge", "Donkers R3", "pe" )
        
    legend.Draw()
    return
Ejemplo n.º 25
0
data_y = np.array([6 ,1 ,10 ,12 ,6 ,13 ,23 ,22 ,15 ,21 ,23 ,26 ,36 ,25 ,27 ,35 ,40 ,44 ,66 ,81,  75 , 57 ,48 ,45 ,46 ,41 ,35 ,36 ,53 ,32 ,40 ,37 ,38 ,31 ,36 ,44 ,42 ,37 ,32 ,32, 43 ,44 ,35 ,33 ,33 ,39 ,29 ,41 ,32 ,44 ,26 ,39 ,29 ,35 ,32 ,21 ,21 ,15 ,25 ,15], dtype=np.float)
sigma_x = np.array(nPoints*[0], dtype=np.float)
sigma_y = np.array(np.sqrt(data_y), dtype=np.float)

pi=np.pi
L=TF1("L","[0]*([1]/2)/(pi*((x-[2])**2+([1]/2)**2))",0.6,1.2)
Pol=TF1("Pol","[0]*x**2+[1]*x+[2]",0,3)

#Fiting data with 6 parameters-------------------------------------------------------

gStyle.SetOptFit(111)  # superimpose fit results

c1=TCanvas("c1","Daten",200,10,700,500) #make nice Canvas 
c1.SetGrid()

gr=TGraphErrors(nPoints,data_x,data_y,sigma_x,sigma_y)
gr.SetTitle("6 Parameter Fit")
gr.Draw("AP");


Tmp=TF1("Tmp","[0]*x**2+[1]*x+[2]+[3]*([4]/2)/(3.141*((x-[5])**2+([4]/2)**2))",0,3)
Tmp.SetParameter(3,90)
Tmp.SetParameter(4,0.9)
Tmp.SetParameter(5,0.1)
gr.Fit(Tmp)
#c1.Update()
gr.Draw('AP')
fitrp = TVirtualFitter.GetFitter()
nPar = fitrp.GetNumberTotalParameters()
covmat = TMatrixD(nPar, nPar,fitrp.GetCovarianceMatrix())
print('The Covariance Matrix is: ')
Ejemplo n.º 26
0
def fit():
    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    mbc.cd()

    ipoint, geexs = 0, TGraphErrors(0)
    path = './txts/xs_total_' + patch + '_plot.txt'
    xs_max = 0
    from tools.data_base import ECMS
    for line in open(path):
        try:
            if '#' in line: continue
            fargs = map(float, line.strip().split())
            ecms, xs, xserr = fargs[0], fargs[1], fargs[2]
            geexs.Set(ipoint + 1)
            geexs.SetPoint(ipoint, ECMS(int(ecms*1000)), xs)
            geexs.SetPointError(ipoint, 0.0, xserr)
            if xs > xs_max: xs_max = xs
            ipoint += 1
        except:
            '''
            '''
    xtitle = '#sqrt{s}(GeV)'
    ytitle = '#sigma(e^{+}e^{-}#rightarrow#pi^{+}#pi^{-}D^{+}D^{-})(pb)'
    if 'BW_4230_a' not in components and 'PHSP_a' not in components: set_graph_style(geexs, xtitle, ytitle, xmin = -15., xmax = xs_max * 1.7)
    else: set_graph_style(geexs, xtitle, ytitle, xmin = -5., xmax = xs_max * 1.7)
    geexs.Draw('ap')
    tfunc = construct_A2()
    geexs.Fit(tfunc, 'E')
    tfunc.Draw('same')
    mbc.Update()

    from tools.Resonances import Resonances
    start_param_pos = 0
    param = {}
    for component in components:
        par = []
        len_param = len(Resonances[component]['init']) - len(Resonances[component]['constant'])
        for i in range(start_param_pos, start_param_pos + len_param): 
            par.append(tfunc.GetParameter(i))
        for const in Resonances[component]['constant']:
            if const == 'mass': par.insert(0, Resonances[component]['init']['mass'])
            if const == 'width': par.insert(1, Resonances[component]['init']['width'])
            if const == 'BrGam': par.insert(2, Resonances[component]['init']['BrGam'])
            if const == 'phase': par.insert(3, Resonances[component]['init']['phase'])
        start_param_pos += len_param
        param[component] = par

    used = []
    VarsManager = locals()
    for i, icomponent in enumerate(components):
        for j, jcomponent in enumerate(components):
            if (icomponent, jcomponent) in used or (jcomponent, icomponent) in used: continue
            used.append((icomponent, jcomponent))
            color = 1 + i + j
            if color == 5: color += 1 # not yellow
            if icomponent == jcomponent and 'BW' in icomponent and 'BW' in jcomponent:
                par = param[icomponent]
                VarsManager['f_' + icomponent + '_' + jcomponent] = TF1(icomponent, BW_BW, xmin, xmax, len(par));
                VarsManager['f_' + icomponent + '_' + jcomponent].SetParameters(array('d', par));
                VarsManager['f_' + icomponent + '_' + jcomponent].SetLineColor(color)
                VarsManager['f_' + icomponent + '_' + jcomponent].SetLineStyle(ROOT.kSolid)
                VarsManager['f_' + icomponent + '_' + jcomponent].Draw('same')
            if icomponent == jcomponent and 'PHSP' in icomponent and 'PHSP' in jcomponent:
                par = param[icomponent]
                VarsManager['f_' + icomponent + '_' + jcomponent] = TF1(icomponent, PHSP_PHSP, xmin, xmax, len(par));
                VarsManager['f_' + icomponent + '_' + jcomponent].SetParameters(array('d', par));
                VarsManager['f_' + icomponent + '_' + jcomponent].SetLineColor(color)
                VarsManager['f_' + icomponent + '_' + jcomponent].SetLineStyle(ROOT.kSolid)
                VarsManager['f_' + icomponent + '_' + jcomponent].Draw('same')
            if icomponent != jcomponent and 'BW' in icomponent and 'BW' in jcomponent:
                param_i = param[icomponent]
                param_j = param[jcomponent]
                par = param_i + param_j
                VarsManager['f_' + icomponent + '_' + jcomponent] = TF1(icomponent + '_' + str(jcomponent), BW1_BW2, xmin, xmax, len(par));
                VarsManager['f_' + icomponent + '_' + jcomponent].SetParameters(array('d', par));
                VarsManager['f_' + icomponent + '_' + jcomponent].SetLineColor(color)
                VarsManager['f_' + icomponent + '_' + jcomponent].SetLineStyle(ROOT.kDashed)
                VarsManager['f_' + icomponent + '_' + jcomponent].Draw('same')
            if 'BW' in icomponent and 'PHSP' in jcomponent:
                param_i = param[icomponent]
                param_j = param[jcomponent]
                par = param_i + param_j
                VarsManager['f_' + icomponent + '_' + jcomponent] = TF1(icomponent + '_' + jcomponent, BW_PHSP, xmin, xmax, len(par));
                VarsManager['f_' + icomponent + '_' + jcomponent].SetParameters(array('d', par));
                VarsManager['f_' + icomponent + '_' + jcomponent].SetLineColor(color)
                VarsManager['f_' + icomponent + '_' + jcomponent].SetLineStyle(4)
                VarsManager['f_' + icomponent + '_' + jcomponent].Draw('same')
    funcs = []
    names = []
    for key, value in VarsManager.items():
        if 'f_' in key:
            names.append(value.GetName())
            funcs.append(value)
    mbc.Update()

    chi2 =  tfunc.GetChisquare()
    ndf = tfunc.GetNDF()
    line = '#chi^{2}/ndf = ' + str(round(chi2, 1)) + '/' + str(round(ndf, 1)) + ' = ' + str(round(chi2/ndf, 1))
    if not os.path.exists('./txts/'):
        os.makedirs('./txts/')
    label = ''
    for component in components:
        label += '_' + component
    with open('./txts/likelihood' + label + '.txt', 'w') as f:
        f.write(str(chi2) + '\n' + str(ndf))
    
    with open('./txts/params' + label + '.txt', 'w') as f:
        for key, value in par_index.items():
            out = key + ' ' + str(tfunc.GetParameter(value)) + '\n'
            f.write(out)

    if 'BW_4230_a' not in components and 'PHSP_a' not in components: legend = TLegend(0.45, 0.6, 0.65, 0.88)
    else: legend = TLegend(0.2, 0.6, 0.5, 0.88)
    set_legend(legend, tfunc, names, funcs, line)
    legend.Draw()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')
    mbc.SaveAs('./figs/xs' + label + '.pdf')

    raw_input('Enter anything to end...')
def plot_data_histogram(fits, name):
    return
    test_canvas = TCanvas("TestCanvas", "Ds Fit", 0, 0, 800, 575)

    gStyle.SetPadBorderMode(0)
    gStyle.SetFrameBorderMode(0)

    test_canvas.Divide(1, 2, 0, 0)
    upper_pad = test_canvas.GetPad(1)
    lower_pad = test_canvas.GetPad(2)
    low, high = 0.05, 0.95
    upper_pad.SetPad(low, 0.4, high, high)
    lower_pad.SetPad(low, low, high, 0.4)

    test_canvas.cd(1)

    ROOT.IABstyles.canvas_style(test_canvas, 0.25, 0.05, 0.02, 0.15, 0, 0)

    h_Mjj = TH1D("h_Mjj", "Mass Spectrum", 100, 0.2, 12)
    h_Mjj.GetYaxis().SetTitle("num. events")
    h_Mjj.GetXaxis().SetTitle("M [Tev/c^{-2}]")

    ROOT.IABstyles.h1_style(h_Mjj, ROOT.IABstyles.lWidth // 2,
                            ROOT.IABstyles.Scolor, 1, 0, 0, -1111.0, -1111.0,
                            508, 508, 8, ROOT.IABstyles.Scolor, 0.1, 0)

    h_Mjj.GetYaxis().SetRangeUser(0.1, 1e6)
    h_Mjj.GetXaxis().SetRangeUser(1, 10)
    h_Mjj.GetXaxis().SetTitleOffset(1)
    h_Mjj.GetYaxis().SetTitleOffset(1.1)

    upper_pad.SetLogy(1)
    upper_pad.SetLogx(1)
    lower_pad.SetLogx(1)

    gr = TGraphErrors(fits.num_bins, array("d", fits.xmiddle),
                      array("d", fits.data), array("d", fits.xwidth),
                      array("d", fits.errors))
    ROOT.IABstyles.h1_style(gr, ROOT.IABstyles.lWidth // 2,
                            ROOT.IABstyles.Scolor, 1, 0, 0, -1111, -1111, 505,
                            505, 8, ROOT.IABstyles.Scolor, 0.1, 0)

    grFit = TGraph(fits.num_bins, array("d", fits.xmiddle),
                   array("d", fits.data_fits))
    ROOT.IABstyles.h1_style(grFit, ROOT.IABstyles.lWidth // 2, 632, 1, 0, 0,
                            -1111, -1111, 505, 505, 8, 632, 0.1, 0)

    h_Mjj.Draw("axis")
    gr.Draw("P")
    grFit.Draw("c")

    test_canvas.Update()

    gPad.SetBottomMargin(1e-5)

    test_canvas.cd(2)
    gPad.SetTopMargin(1e-5)

    h2 = TH1D("h2", "", 100, 0.2, 12)
    h2.GetXaxis().SetRangeUser(1, 10)
    h2.GetYaxis().SetRangeUser(-10, 10)
    h2.SetStats(False)  # don't show stats box
    h2.Draw("axis")
    sig_values = [(data - theory) / theory if
                  (data != 0 and theory != 0) else -100
                  for data, theory in zip(fits.data, fits.data_fits)]
    sig = TGraph(fits.num_bins, array("d", fits.xmiddle),
                 array("d", sig_values))
    #ROOT.IABstyles.h1_style(sig, ROOT.IABstyles.lWidth/2, 632, 1, 0, 0, -1111, -1111, 505, 505, 8, 632, 0.1, 0)
    ROOT.IABstyles.h1_style(gr, ROOT.IABstyles.lWidth // 2,
                            ROOT.IABstyles.Scolor, 1, 0, 0, -1111, -1111, 505,
                            505, 8, ROOT.IABstyles.Scolor, 0.1, 0)
    sig.SetMarkerStyle(22)  # triangle
    sig.SetMarkerColor(2)  # red
    sig.SetMarkerSize(0.8)
    sig.Draw("P")
    #lower_pad.Draw()

    label = ROOT.TText()
    label.SetNDC()
    label.SetTextSize(0.03)
    label.DrawText(0.5, 0.7, "{0}GeV q*".format(MASS_FILE))

    # test_canvas.SaveAs("output_qstar.pdf")
    test_canvas.SaveAs("plots/{0}/{2}/plot-{1}-{2}-hist.png".format(
        CLUSTER_ID, name, MASS_FILE))
Ejemplo n.º 28
0
def makePlot1D(filepath, foutname, plottitle='', masstitle=''):
    br = 1 if 'Resonant' in plottitle else 0.68
    limits = parseLimitFiles2D(filepath, br)

    xaxis = []
    xseclist = []
    xsecerr = []
    cent = []
    obs = []
    up1 = []
    up2 = []
    down1 = []
    down2 = []
    maxval = 0
    minval = 999
    for m in sorted(limits):
        l = limits[m]
        xaxis.append(m)
        xseclist.append(l.xsec)
        xsecerr.append(l.xsec * .2)
        cent.append(l.cent)
        up1.append(l.up1 - l.cent)
        up2.append(l.up2 - l.cent)
        down1.append(l.cent - l.down1)
        down2.append(l.cent - l.down2)
        obs.append(l.obs)
        maxval = max(maxval, l.up2)
        minval = min(minval, l.down2)

    N = len(xaxis)

    up1Sigma = array('f', up1)
    up2Sigma = array('f', up2)
    down1Sigma = array('f', down1)
    down2Sigma = array('f', down2)
    cent = array('f', cent)
    obs = array('f', obs)
    xarray = array('f', xaxis)
    xsecarray = array('f', xseclist)
    xsecerrarray = array('f', xsecerr)
    zeros = array('f', [0 for i in xrange(N)])

    graphXsec = TGraphErrors(N, xarray, xsecarray, zeros, xsecerrarray)

    graphCent = TGraph(N, xarray, cent)
    graphObs = TGraph(N, xarray, obs)
    graph1Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down1Sigma,
                                    up1Sigma)
    graph2Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down2Sigma,
                                    up2Sigma)

    c = TCanvas('c', 'c', 700, 600)
    c.SetLogy()
    c.SetLeftMargin(.15)

    graph2Sigma.GetXaxis().SetTitle(masstitle + ' [GeV]')
    graph2Sigma.GetYaxis().SetTitle(
        '95% C.L. upper limit [#sigma/#sigma_{theory}]')
    c2 = root.kOrange
    c1 = root.kGreen + 1
    graph2Sigma.SetLineColor(c2)
    graph1Sigma.SetLineColor(c1)
    graph2Sigma.SetFillColor(c2)
    graph1Sigma.SetFillColor(c1)
    graph2Sigma.SetMinimum(0.5 * minval)
    graph2Sigma.SetMaximum(10 * maxval)
    graphCent.SetLineWidth(2)
    graphCent.SetLineStyle(2)
    graphObs.SetLineColor(1)
    graphObs.SetLineWidth(3)
    graphObs.SetMarkerStyle(20)
    graphObs.SetMarkerSize(1)
    graphObs.SetMarkerColor(1)
    graph1Sigma.SetLineStyle(0)
    graph2Sigma.SetLineStyle(0)

    leg = TLegend(0.55, 0.7, 0.9, 0.9)
    leg.AddEntry(graphCent, 'Expected', 'L')
    if not BLIND:
        leg.AddEntry(graphObs, 'Observed', 'Lp')
    leg.AddEntry(graph1Sigma, '1 std. dev.', 'F')
    leg.AddEntry(graph2Sigma, '2 std. dev.', 'F')
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    graph2Sigma.Draw('A3')
    graph1Sigma.Draw('3 same')
    graphCent.Draw('same L')
    if not BLIND:
        graphObs.Draw('same Lp')

    subscript = 'SR' if 'Resonant' in plottitle else 'FC'
    coupling = '0.1' if 'Resonant' in plottitle else '0.25'

    graphXsec.SetLineColor(2)
    graphXsec.SetLineWidth(2)
    graphXsec.SetLineStyle(2)
    graphXsec.SetFillColor(2)
    graphXsec.SetFillStyle(3005)
    graphXsec.Draw('same L3')
    '''
  if not scale:
    if 'Resonant' in plottitle:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=100 GeV}'%(subscript,subscript,coupling),'l')
    else:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=10 GeV}'%(subscript,subscript,coupling),'l')
  '''
    if not BLIND:
        findIntersect1D(graphObs, graphXsec, xaxis[0], xaxis[-1])
    findIntersect1D(graphCent, graphXsec, xaxis[0], xaxis[-1])

    leg.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.8 * c.GetTopMargin())
    label.SetTextFont(62)
    label.SetTextAlign(11)
    label.DrawLatex(0.15, 0.94, "CMS")
    label.SetTextFont(52)
    label.SetTextSize(0.6 * c.GetTopMargin())
    #  label.DrawLatex(0.25,0.94,"Preliminary")
    label.SetTextFont(42)
    label.SetTextSize(0.7 * c.GetTopMargin())
    label.DrawLatex(0.19, 0.83, plottitle)
    if 'Resonant' in plottitle:
        label.DrawLatex(0.19, 0.75, "a_{SR} = b_{SR} = %s" % coupling)
        label.DrawLatex(0.19, 0.68, "m_{#chi}=100 GeV")
    else:
        label.DrawLatex(0.19, 0.75, "g_{DM}^{V}=1,g_{q}^{V}=0.25")
        label.DrawLatex(0.19, 0.68, "m_{#chi}=1 GeV")
    label.SetTextSize(0.6 * c.GetTopMargin())
    label.SetTextFont(42)
    label.SetTextAlign(31)  # align right
    label.DrawLatex(0.95, 0.94, "%.1f fb^{-1} (13 TeV)" % (plotConfig.lumi))

    c.SaveAs(foutname + '.pdf')
    c.SaveAs(foutname + '.png')
Ejemplo n.º 29
0
def closureTest_plots(filename):
    f = BareRootFile(filename)
    tree = f.Get('closureTest')

    gStyle.SetStatX(0.9)
    gStyle.SetStatY(0.9)
    gStyle.SetStatW(0.2)
    gStyle.SetStatH(0.14)

    hist1 = TH1F('hist1', '', 55, 0.9, 2.0)
    hist2 = TH1F('hist2', '', 55, 0.9, 2.0)
    condition = ('fit_overlapDiff>=0 && temp_overlapDiff>=0 && '
                 'fit_chisq/fit_dof<=2 && temp_chisq/temp_dof<=2')
    tree.Draw('temp_chisq/temp_dof>>hist1', condition)
    tree.Draw('fit_chisq/fit_dof>>hist2', condition)
    for i, hist in [(0, hist1), (1, hist2)]:
        hist.SetLineColor(colors[i])
        hist.SetLineWidth(3)
    maxi = max(hist1.GetMaximum(), hist2.GetMaximum()) * 1.1
    plot = SingleHistBase(hist1,
                          'hist_numberPerChisq',
                          fill=None,
                          workinprogress=wip)
    gStyle.SetOptStat(10)
    plot._xtitle = '#chi^{2}/d.o.f.'
    plot._ytitle = 'number of toys'
    plot.yrange(0.0, maxi)
    leg = TLegend(0.65, 0.75, 0.89, 0.85)
    leg.SetBorderSize(0)
    leg.AddEntry(hist1, 'DG fit', 'L')
    leg.AddEntry(hist2, 'SupDG fit', 'L')
    plot.draw()
    hist2.Draw('SAMEH')
    leg.Draw()
    plot.save_pdf()
    plot.Close()

    hist3 = TH2F('hist3', '', 31, -0.05, 3.05, 31, -0.05, 3.05)
    tree.Draw('100*temp_overlapDiff:100*fit_overlapDiff>>hist3', condition)
    one = TF1('one', 'x', -10.0, 10.0)
    one.SetLineColor(1)
    plot = SingleHistBase(hist3,
                          'correctionDGvsSupDG',
                          fill=None,
                          workinprogress=wip)
    plot.add(one)
    plot._drawoption = 'BOX'
    plot._xtitle = 'correction [%] from SupDG fit'
    plot._ytitle = 'correction [%] from DG fit'
    plot._above = True
    plot.draw()
    plot.save_pdf()
    plot.Close()

    hist4 = TH2F('hist4', '', 22, 0.95, 1.5, 22, 0.95, 1.5)
    tree.Draw('temp_chisq/temp_dof:fit_chisq/fit_dof>>hist4', condition)
    plot = SingleHistBase(hist4,
                          'chisqDGvsSupDG',
                          fill=None,
                          workinprogress=wip)
    plot.add(one)
    plot._drawoption = 'BOX'
    plot._xtitle = '#chi^{2}/d.o.f. of SupDG fit'
    plot._ytitle = '#chi^{2}/d.o.f. of DG fit'
    plot._above = True
    plot.draw()
    plot.save_pdf()
    plot.Close()

    gStyle.SetStatX(0.9)
    gStyle.SetStatY(0.83)
    gStyle.SetStatW(0.3)
    gStyle.SetStatH(0.08)

    #bins_csq = [(0.0, 1.1), (1.1, 1.3), (1.3, 1.6), (1.6, 2.0)]
    #bins_cor = [(0.0, 0.5), (0.5, 1.0), (1.0, 1.5), (1.5, 2.0), (2.0, 2.5)]
    #bins_csq = [(1.07, 1.13), (1.06, 1.11), (1.3, 1.5), (1.08, 1.17), (1.1, 1.2)]
    #bins_cor = [(0.3, 0.8), (0.9, 1.2), (0.1, 0.5), (0.4, 0.7), (0.3, 1.1)]
    bins_csq = [(0.99, 1.06), (0.98, 1.07), (0.99, 1.10), (1.02, 1.06),
                (1.00, 1.06), (1.00, 1.04)]
    bins_cor = [(0.9, 1.9), (0.4, 1.6), (0.6, 1.5), (0.6, 1.9), (1.0, 1.3),
                (0.3, 1.5)]

    means = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    meane = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    rmses = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    rmser = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }

    #for i, (csq_lo, csq_hi) in enumerate(bins_csq):
    #    for j, (cor_lo, cor_hi) in enumerate(bins_cor):
    for i, ((csq_lo, csq_hi), (cor_lo,
                               cor_hi)) in enumerate(zip(bins_csq, bins_cor)):
        j = i
        name = 'hist_{{0}}_{0}csq{1}_{2}cor{3}' \
               .format(csq_lo, csq_hi, cor_lo, cor_hi)
        fields = '100*({0}_overlapDiff-toy_overlapDiff)>>hist'
        condition = (
            '100*{{0}}_overlapDiff>={0} && 100*{{0}}_overlapDiff<{1} && '
            '{{0}}_chisq/{{0}}_dof>={2} && {{0}}_chisq/{{0}}_dof<{3} && '
            'fit_overlapDiff>=0 && temp_overlapDiff>=0 && '
            'fit_chisq/fit_dof<=2 && temp_chisq/temp_dof<=2').format(
                cor_lo, cor_hi, csq_lo, csq_hi)
        xtitle = 'correction [%] from {0} fit #minus true correction [%]'
        line1 = '{0} < correction < {1}'.format(cor_lo, cor_hi)
        line2 = '{0} < #chi^{{2}}/d.o.f. < {1}'.format(csq_lo, csq_hi)
        gStyle.SetOptStat(2210)
        for prefix, modname in (('temp', 'DG'), ('fit', 'SupDG')):
            hist = TH1F('hist', '', 41, -2.05, 2.05)
            hist.StatOverflows()
            tree.Draw(fields.format(prefix), condition.format(prefix))
            plot = SingleHistBase(hist,
                                  name.format(modname),
                                  fill=None,
                                  workinprogress=wip)
            gStyle.SetOptStat(2210)
            plot._xtitle = xtitle.format(modname)
            plot._ytitle = 'number of toys'
            plot.xrange(-2.05, 2.05)
            plot.yrange(0.0, plot._graph.GetMaximum() * 1.2)
            pave = plot.add_pave(0.6, 0.83, 0.9, 0.9, border=True)
            pave(line1)
            pave(line2)
            plot.draw()
            plot.save_pdf()
            means[modname][i][j] = plot._graph.GetMean()
            meane[modname][i][j] = plot._graph.GetMeanError()
            rmses[modname][i][j] = plot._graph.GetRMS()
            rmser[modname][i][j] = plot._graph.GetRMSError()
            plot.Close()

    multi = TMultiGraph('multi', '')
    for k, modname in enumerate(('DG', 'SupDG')):
        for i, (csq_lo, csq_hi) in enumerate(bins_csq):
            xval = array(
                'd',
                [j - 0.35 + k * 0.4 + i * 0.1 for j in range(len(bins_cor))])
            xerr = array('d', [0.0] * len(bins_cor))
            yval = array('d', means[modname][i])
            yerr = array('d', rmses[modname][i])
            graph = TGraphErrors(len(bins_cor), xval, yval, xerr, yerr)
            graph.SetName('graph{0}{1}'.format(k, i))
            graph.SetMarkerStyle(22 + k)
            graph.SetMarkerColor(colors[i])
            graph.SetLineColor(colors[i])
            multi.Add(graph)
    minvalues = [
        means[mod][i][j] - rmses[mod][i][j] for j in range(len(bins_cor))
        for i in range(len(bins_csq)) for mod in ('DG', 'SupDG')
    ]
    maxvalues = [
        means[mod][i][j] + rmses[mod][i][j] for j in range(len(bins_cor))
        for i in range(len(bins_csq)) for mod in ('DG', 'SupDG')
    ]
    mini, maxi = min(minvalues), max(maxvalues)
    mini, maxi = mini - 0.1 * (maxi - mini), maxi + 0.3 * (maxi - mini)
    hist = TH2F('axishist', '', len(bins_cor), -0.5,
                len(bins_cor) - 0.5, 100, mini, maxi)
    for j, (cor_lo, cor_hi) in enumerate(bins_cor):
        hist.GetXaxis().SetBinLabel(j + 1,
                                    '{0}% #minus {1}%'.format(cor_lo, cor_hi))
    leg1 = TLegend(0.53, 0.78, 0.63, 0.86)
    leg1.SetBorderSize(0)
    dgmarker = TMarker(0.0, 0.0, 22)
    supdgmarker = TMarker(0.0, 0.0, 23)
    leg1.AddEntry(dgmarker, 'DG', 'P')
    leg1.AddEntry(supdgmarker, 'SupDG', 'P')
    leg2 = TLegend(0.65, 0.75, 0.89, 0.89)
    leg2.SetBorderSize(0)
    csqmarker = TMarker(0.0, 0.0, 1)
    for i, (csq_lo, csq_hi) in enumerate(bins_csq):
        title = '{0} < #chi^{{2}}/d.o.f. < {1}'.format(csq_lo, csq_hi)
        entry = leg2.AddEntry(csqmarker, title, 'L')
        entry.SetMarkerColor(colors[i])
        entry.SetLineColor(colors[i])
    zero = TF1('zero', '0.0', -1.0, 10.0)
    zero.SetLineColor(1)
    zero.SetLineStyle(2)
    plot = SingleHistBase(hist,
                          name='differenceDoubleDifferential',
                          fill=None,
                          workinprogress=wip)
    plot._xtitle = 'correction from fit'
    plot._ytitle = 'correction [%] from fit #minus true correction [%]'
    plot.xrange(-0.5, len(bins_cor) - 0.5)
    plot.yrange(mini, maxi)
    plot._drawoption = 'AXIS'
    plot.draw()
    plot.xaxis().SetNdivisions(len(bins_cor), False)
    plot.xaxis().SetLabelSize(0.03)
    zero.Draw('SAME')
    multi.Draw('P')
    leg1.Draw()
    leg2.Draw()
    plot.save_pdf()
    plot.Close()

    bcid = (41, 281, 872, 1783, 2063)
    DGcor1 = array('d', [0.809, 0.392, 0.846, 0.731, 0.497])
    DGerr1 = array('d', [0.548, 0.567, 0.984, 0.984, 1.018])
    DGcor2 = array('d', [1.145, 0.799, 1.58, 1.465, 1.281])
    DGerr2 = array('d', [0.432, 0.395, 0.656, 0.656, 0.649])
    DGxval = array('d', [j - 0.1 for j in range(5)])
    SupDGcor1 = array('d', [0.823, 0.761, 1.458, 0.986, 1.012])
    SupDGerr1 = array('d', [0.513, 0.513, 0.499, 0.513, 0.499])
    SupDGcor2 = array('d', [0.978, 0.916, 1.532, 1.141, 1.086])
    SupDGerr2 = array('d', [0.489, 0.489, 0.493, 0.489, 0.493])
    SupDGxval = array('d', [j + 0.1 for j in range(5)])
    xerr = array('d', [0.0] * 5)

    for fill, values in [
        (4266, {
            'DGcor': [1.021, 1.057, 0.968, 1.084, 1.114],
            'DGerr': [(e**2 + 0.74**2)**0.5
                      for e in (0.118, 0.124, 0.119, 0.117, 0.119)],
            'SupDGcor': [1.402, 1.411, 1.164, 1.549, 1.589],
            'SupDGerr': [(e**2 + 0.45**2)**0.5
                         for e in (0.106, 0.110, 0.108, 0.106, 0.115)],
            'bcids': [51, 771, 1631, 2211, 2674]
        }),
        (4954, {
            'DGcor': [0.799, 0.398, 0.845, 0.724, 0.502],
            'DGerr': [(e**2 + 0.79**2)**0.5
                      for e in (0.137, 0.124, 0.122, 0.130, 0.116)],
            'SupDGcor': [0.794, 0.694, 1.642, 0.983, 0.993],
            'SupDGerr': [(e**2 + 0.50**2)**0.5
                         for e in (0.126, 0.112, 0.186, 0.102, 0.144)],
            'bcids': [41, 281, 872, 1783, 2063]
        }),
        (4937, {
            'DGcor': [0.649, 0.494, 0.575, 0.527, 0.602],
            'DGerr':
            [(e**2 + 0.85**2)**0.5 for e in (0.127, 0.115, 0.120, 0.125)],
            'SupDGcor': [0.377, 0.611, 1.137, 0.453, 1.840],
            'SupDGerr': [(e**2 + 0.56**2)**0.5
                         for e in (0.100, 0.105, 0.288, 0.161, 0.207)],
            'bcids': [81, 875, 1610, 1690, 1730]
        }),
        (6016, {
            'DGcor': [0.146, 0.394, 0.377, 0.488, 0.184],
            'DGerr': [(e**2 + 1.15**2)**0.5
                      for e in (0.110, 0.114, 0.118, 0.123, 0.109)],
            'SupDGcor': [0.760, 0.953, 1.048, 0.847, 0.373],
            'SupDGerr': [(e**2 + 0.79**2)**0.5
                         for e in (0.219, 0.094, 0.189, 0.098, 0.169)],
            'bcids': [41, 281, 872, 1783, 2063]
        })
    ]:
        bcid = values['bcids']
        DGcor = array('d', values['DGcor'])
        DGerr = array('d', values['DGerr'])
        DGxvl = array('d', [j - 0.1 for j in range(len(bcid))])
        SupDGcor = array('d', values['SupDGcor'])
        SupDGerr = array('d', values['SupDGerr'])
        SupDGxvl = array('d', [j + 0.1 for j in range(len(bcid))])
        xerr = array('d', [0.0] * len(bcid))
        maxi = max(max([v + e for v, e in zip(DGcor, DGerr)]),
                   max([v + e for v, e in zip(SupDGcor, SupDGerr)]))
        mini = min(min([v - e for v, e in zip(DGcor, DGerr)]),
                   min([v - e for v, e in zip(SupDGcor, SupDGerr)]))
        maxi, mini = maxi + 0.2 * (maxi - mini), mini - 0.1 * (maxi - mini)

        graphDG = TGraphErrors(len(bcid), DGxvl, DGcor, xerr, DGerr)
        graphDG.SetName('graphDG')
        graphSupDG = TGraphErrors(len(bcid), SupDGxvl, SupDGcor, xerr,
                                  SupDGerr)
        graphSupDG.SetName('graphSupDG')
        multi = TMultiGraph('multi', '')
        for i, graph in [(0, graphDG), (1, graphSupDG)]:
            graph.SetMarkerStyle(22 + i)
            graph.SetMarkerColor(colors[i])
            graph.SetLineColor(colors[i])
            multi.Add(graph)
        leg = TLegend(0.15, 0.80, 0.5, 0.83)
        leg.SetNColumns(2)
        leg.SetBorderSize(0)
        leg.AddEntry(graphDG, 'DG fit', 'PL')
        leg.AddEntry(graphSupDG, 'SupDG fit', 'PL')
        axishist = TH2F('axishist', '', len(bcid), -0.5,
                        len(bcid) - 0.5, 100, mini, maxi)
        for i, bx in enumerate(bcid):
            axishist.GetXaxis().SetBinLabel(i + 1, '{0}'.format(bx))

        plot = SingleHistBase(axishist,
                              name='Fill{0}biased'.format(fill),
                              fill=fill,
                              workinprogress=wip)
        plot._xtitle = 'BCID'
        plot._ytitle = 'correction [%] from fit'
        plot.xrange(-0.5, len(bcid) - 0.5)
        plot.yrange(mini, maxi)
        plot._drawoption = 'AXIS'
        plot.draw()
        plot.xaxis().SetNdivisions(len(bcid), False)
        plot.xaxis().SetLabelSize(0.03)
        multi.Draw('P')
        leg.Draw()
        plot.save_pdf()
        plot.Close()

        print
        print 'Fill', fill
        for bx, cor, err in zip(bcid, SupDGcor, SupDGerr):
            print 'BCID {0}:\t{1:.2f} +- {2:.2f}'.format(bx, cor, err)
        print
Ejemplo n.º 30
0
#linearizzazione
intensity = [1 / x**0.5 for x in intensity]
intensity_error = [
    0.5 * i**3 * old_err for i, old_err in zip(intensity, intensity_error)
]

out_intensity = "intensity.out"
with open(out_intensity, "w") as out_file:
    for dist, intens, int_err in zip(prefissi, intensity, intensity_error):
        line = dist + " " + str(intens) + " " + "0" + " " + str(int_err) + "\n"
        out_file.write(line)

can = TCanvas("dist", "dist")
can.SetFillColor(0)
intensity_graph = TGraphErrors(out_intensity)
intensity_graph.SetTitle()
line = TF1("line", "pol1")
intensity_graph.SetMarkerStyle(8)
intensity_graph.Fit("line")
intensity_graph.GetYaxis().SetDecimals()
intensity_graph.GetYaxis().SetTitle("I^{-1/2} #[]{n_events^{-1/2}}")
intensity_graph.GetYaxis().SetDecimals()
intensity_graph.GetXaxis().SetTitle("distance #[]{mm}")
intensity_graph.Draw("ap")
r = intensity_graph.GetCorrelationFactor()  #correlation coefficient=?
print(r)
#r = 0.826 #correlation coefficient=?
npoints = 6
ndf = npoints - 2
t = r * sqrt(ndf / (1 - r**2))
Ejemplo n.º 31
0
def analyzeData(country, total, active, recovered, deaths, tStart, tStop,
                totalPopulation, symptomaticFraction, transmissionProbability,
                recoveryRate, doSmearing, doFit):
    ntuple = [
        tStart, tStop, totalPopulation, symptomaticFraction,
        transmissionProbability, recoveryRate
    ]
    farFromMax = 0.95
    growthRate = 0.13
    carryingCapacity = 4e5

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return [
        ntuple, myCanvTotal, myGraphTotal, myCanvActive, myGraphActive,
        evActive, evActiveGraphN, statActive, now, willbe, myCanvActiveR0,
        evActiveGraphR0, myCanvDeaths, myGraphDeaths, myCanvRatio01,
        myGraphRatio01, myCanvRatio02, myGraphRatio02, myCanvRatio03,
        myGraphRatio03
    ]
def plotDistributionComparisonPlot(cfg):

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

    tfiles = []

    histograms = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # Adding a small text with the chi-squared

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

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

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

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

    #Dividing point by point

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

    ratioPlot.SetMarkerStyle(21)

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

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

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

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

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

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

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

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

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

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

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

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

    saveFile = TFile(cfg.saveFileName, "RECREATE")
    saveFile.cd()
    canvas.Write()
    histograms[0].Write()
    histograms[1].Write()
    if multiGraph.GetListOfGraphs() != None:
        multiGraph.Write()
    ratioPlot.Write()
    if xRangeBinning is not None:
        simplifiedRatioPlot.Write()
    saveFile.Close()
    for tfile in tfiles:
        tfile.Close()
Ejemplo n.º 33
0
def plot_2(var, cuts):
    for s in attr:
        if ct_dep == 0:
            c1 = TCanvas("c1", "Signals", 800, 800)
            c1.cd()
            c1.SetGrid()
            #gStyle.SetTitleFontSize(8.1)
            if s in ('elf', 'muf', 'chm', 'cm', 'nm'):
                c1.SetLogx()
            for cc in channel:
                hist[cc][s].Draw('colz same')
                hist_CHS[cc][s].Draw('colz same')
            legend = TLegend(0.90, 0.90, 0.99, 0.99)
            #legend.SetHeader('Samples')
            for cc in channel:
                legend.AddEntry(hist[cc][s], cc)
                legend.AddEntry(hist_CHS[cc][s], cc + 'CHS')
            legend.Draw()
            c1.Print(path1 + s + var +
                     cuts.replace('(', '_').replace(')', '_').replace(
                         '&&', 'A').replace('>', 'LG').replace('<', 'LS').
                     replace('=', 'EQ').replace('.', 'P').replace('-', 'N').
                     replace('Jet', 'J').replace('GenBquark', 'GBQ') + ".pdf")
            c1.Update()
            c1.Close()
            print('|||||||||||||||||||||||||||||||||||||||||||||||||||')
        elif ct_dep == 1:
            eac0 = str(entries_after_cut['ct0'][s])
            c1 = TCanvas("c1", "Signals", 800, 800)
            c1.SetGrid()
            c1.cd()
            c1.SetLogx()
            #gr = TGraph( len_of_lt , x , yy['sgn'][s] )
            gr = TGraphErrors(len_of_lt, x, yy['sgn'][s], ex, ey['sgn'][s])
            gr.SetMarkerSize(1.5)
            gr.SetMarkerStyle(21)
            gr.SetLineColor(4)
            gr.SetLineWidth(4)
            gr.SetTitle(
                'averaged ' + s + ' cut: ' +
                cuts.replace('(', '_').replace(')', '_').replace('&&', ',').
                replace('Jet', 'J').replace('GenBquark', 'GBQ') + '[entries:' +
                eac0 + ']')
            gr.GetXaxis().SetTitle('decaying length (mm)')
            gr.GetYaxis().SetTitle('mean frequency')
            gr.SetName('sgn')
            gr.Draw('ACP')  # '' sets up the scattering style
            gr1 = TGraphErrors(len_of_lt, x, yy['qcd'][s], ex, ey['qcd'][s])
            gr1.SetMarkerSize(1.0)
            gr1.SetMarkerStyle(2)
            gr1.SetLineColor(2)
            gr1.SetLineWidth(2)
            gr1.SetName('qcd')
            #gr1.SetTitle('averaged ' + s)
            #gr1.GetXaxis().SetTitle('decaying length (mm)')
            #gr1.GetYaxis().SetTitle('mean frequency')
            gr1.Draw('CP')  # '' sets up the scattering style
            legend = TLegend(0.89, 0.89, 0.99, 0.99)
            legend.AddEntry('qcd', legendb)
            legend.AddEntry('sgn', legends)
            legend.Draw()
            c1.Print(path1 + 'mean_' + s + var +
                     cuts.replace('(', '_').replace(')', '_').replace(
                         '&&', 'A').replace('>', 'LG').replace('<', 'LS').
                     replace('=', 'EQ').replace('.', 'P').replace('-', 'N').
                     replace('Jet', 'J').replace('GenBquark', 'GBQ') + ".pdf")
            c1.Update()
            c1.Close()
            print('|||||||||||||||||||||||||||||||||||||||||||||||||||')
Ejemplo n.º 34
0
pdfGraph = None
if plotPDF :
    # plot PDF asymmetry in time bins
    if blind or not pdfBlindVals :
        vals = pdfVals
        valsTot = pdfValsTot if plotComp else pdfVals
    else :
        vals = pdfBlindVals
        valsTot = pdfBlindValsTot if plotComp else pdfBlindVals
        
    pdfArr = array( 'd', [ ( pVals[frac] - mVals[frac] ) / ( pValsTot[frac] + mValsTot[frac] )\
                           for pVals, mVals, pValsTot, mValsTot in zip( vals['plus'], vals['minus'], valsTot['plus'], valsTot['minus'] )\
                           for frac in timeFracs ] )
    for it in range( len(timeFracs) + 1 ) : pdfArr.append( pdfArr[it] )
    pdfErrArr = array( 'd', [ 0. ] * len(pdfArr) )
    pdfGraph = Graph( len(timeArrPdf), timeArrPdf, pdfArr, timeErrArrPdf, pdfErrArr )
    pdfGraph.SetName('pdf')

pdfIntGraph = None
if plotPDFInt :
    # plot integrated-PDF asymmetry in time bins
    if blind or not pdfIntBlindVals :
        intVals = pdfIntVals
    else :
        intVals = pdfIntBlindVals

    pdfIntArr = array( 'd', [ 2. * pVal / ( pVal + mVal ) - 1. for pVal, mVal in zip( intVals['plus'], intVals['minus'] ) ] )
    pdfIntArr.append( pdfIntArr[0] )
    pdfIntErrArr = array( 'd', [ 0. ] * len(pdfIntArr) )
    pdfIntGraph = Graph( len(timeArr), timeArr, pdfIntArr, timeErrArr, pdfIntErrArr )
    pdfIntGraph.SetName('pdfInt')