Exemplo n.º 1
0
    def setup_unfolding ( self, data ):
        self.data = data
        if not self.unfoldObject:
            if not self.unfoldResponse:
                self.unfoldResponse = self._makeUnfoldResponse()
            if self.method == 'RooUnfoldBayes':
                self.unfoldObject = RooUnfoldBayes     ( self.unfoldResponse, self.data, self.Bayes_n_repeat )
            elif self.method == 'RooUnfoldBinByBin':
                self.unfoldObject = RooUnfoldBinByBin     ( self.unfoldResponse, self.data )
            elif self.method == 'RooUnfoldInvert':
                self.unfoldObject = RooUnfoldInvert     ( self.unfoldResponse, self.data )
            elif self.method == 'RooUnfoldSvd':
                if self.k_value > 0:
                    self.unfoldObject = RooUnfoldSvd( self.unfoldResponse, self.data, self.k_value, self.n_toy )
                else:
                    if self.tau >= 0:
                        self.unfoldObject = RooUnfoldSvd( self.unfoldResponse, self.data, self.tau, self.n_toy )
            elif self.method == 'RooUnfoldTUnfold':
                self.unfoldObject = RooUnfoldTUnfold ( self.unfoldResponse, data )
                if self.tau >= 0:
                    self.unfoldObject.FixTau( self.tau )
            elif self.method == 'TSVDUnfold':
                new_data = Hist( list( self.data.xedges() ), type = 'D' )
                new_data.Add( self.data )

                new_measured = Hist( list( self.measured.xedges() ), type = 'D' )
                new_measured.Add( self.measured )

                new_truth = Hist( list( self.truth.xedges() ), type = 'D' )
                new_truth.Add( self.truth )


                if self.fakes:
                    new_fakes = Hist( list ( self.fakes.xedges() ), type = 'D' )
                    new_fakes.Add ( self.fakes )
                    new_measured = new_measured - new_fakes

                new_response = Hist2D( list( self.response.xedges() ), list( self.response.yedges() ), type = 'D' )
                new_response.Add( self.response )

                # replace global objects with new ones
                self.data = new_data
                self.measured = new_measured
                self.truth = new_truth
                self.response = new_response

                self.unfoldObject = TSVDUnfold( self.data, self.measured, self.truth, self.response )
Exemplo n.º 2
0
 def unfolderFactory(self, response, hMeas, BasisSpline_m0=0):
     if "Bayes" in self.optunf:
         # Bayes unfoldung until chi^2 cut (max 10):
         unfold = RooUnfoldBayes(response, hMeas, 10, False, True)
     elif "SVD" in self.optunf:
         # SVD unfolding with free regularisation:
         unfold = RooUnfoldSvd(response, hMeas)
     elif "TUnfold" in self.optunf:
         # TUnfold with fixed regularisation tau=0.002
         # unfold= RooUnfoldTUnfold( response, hMeas, 0.002 )
         unfold = RooUnfoldTUnfold(response, hMeas)
     elif "Invert" in self.optunf:
         unfold = RooUnfoldInvert(response, hMeas)
     elif "Reverse" in self.optunf:
         # Use equivalent Bayes with 1 iteration:
         unfold = RooUnfoldBayes(response, hMeas, 1)
     elif "BasisSplines" in self.optunf:
         # BasisSplines with automatic tau determination
         unfold = RooUnfoldBasisSplines(response, hMeas, self.nrebin, 0.0,
                                        BasisSpline_m0, 2)
     return unfold
Exemplo n.º 3
0
def main(optunf="Bayes"):

    optunfs = ["Bayes", "SVD", "TUnfold", "Invert", "Reverse"]
    if not optunf in optunfs:
        txt = "Unfolding option " + optunf + " not recognised"
        raise ValueError(txt)

    global hReco, hMeas, hTrue, hTrueEE, hTrueMM, hMeasMM, hMeasEE

    #c2 = TCanvas("c2")
    print "==================================== TRAIN ===================================="
    # Create response matrix object
    inputdirZZ = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/UNFOLDacc/HADD/UnfoldInput/"  #ZZ
    # inputdirWZ = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/UNFOLDWZ/HADD/UnfoldInput/" #WZ
    # inputdirNoPrep = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/ZZoutput/" #data, NRB
    inputdirDY = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/DYbkgd/"  #gamma
    #inputGEN = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/Unfolding/PT.root"

    inputdir = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/EWKSET/HADD/UnfoldInput/"  #ZZ
    inputdirWZ = inputdir  #WZ
    inputdirNoPrep = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/EWKSET/"  #data, NRB
    #inputdirNoPrep2 = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/" #data, NRB
    inputdir2 = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/NOSET/HADD/UnfoldInput/"
    # inputdirWZ = inputdir

    fw = '/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/Unfolding/MCFM_withAcceptance/ZZlept_tota_MSTW200_90__90__test.root'
    fwo = '/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/Unfolding/MCFM_withoutAcceptance/ZZlept_tota_MSTW200_90__90__test.root'

    #inputdirOTH = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/NOSET/HADD/UnfoldInput/"
    #inputdirWZOTH = inputdirOTH

    #inputdirEWK = "/afs/cern.ch/work/c/chasco/CMSSW_5_3_11/src/CMGTools/HtoZZ2l2nu/test/results/EWKSET/HADD/UnfoldInput/" #ZZ

    PAIR = ['zptG', 'zpt']
    outputnameGR = PAIR[0] + '_vs_' + PAIR[1] + '.png'
    outputnameG = PAIR[0] + '.png'
    outputnameR = PAIR[1] + '.png'
    cutData = "(zpt>45)*(preco>0)"  #"preco"

    cutGMM = "((L1GId*L2GId)==-13*13)"
    cutRMM = "((l1id*l2id)==-13*13)"
    cutGEE = "((L1GId*L2GId)==-11*11)"
    cutREE = "((l1id*l2id)==-11*11)"
    cutQQ = "(abs(l1id*l2id) == 11*13)"

    hsWW = makehistos("DataFused.root", inputdirNoPrep)
    hsDY = makehistosDY('gamma_out_8_MoreBins_ll.root', inputdirDY)
    print "MEASURED DATA " + "=" * 30
    hMeasMM = Make1DPlot(inputdirNoPrep + "DataFused.root", "finalTree",
                         PAIR[1], "Data.png", cutRMM + "*" + cutData)
    hMeasEE = Make1DPlot(inputdirNoPrep + "DataFused.root", "finalTree",
                         PAIR[1], "Data.png", cutREE + "*" + cutData)
    #hMeasQQ = Make1DPlot(inputdirNoPrep+"DataFused.root","finalTree",PAIR[1],"Data.png",cutQQ + "*" + cutData)
    print "MEASURED DATA " + "=" * 30

    print hMeasMM.Integral(), hMeasEE.Integral(), "Measured"

    print "NRB and DY"
    print hsWW[0].Integral(), hsWW[1].Integral(), "WW"
    print hsDY[0].Integral(), hsDY[1].Integral(), "DY"

    #MCFM rescaling and plotting
    #
    hMCFM = GetMCFMHisto(fwo, True)
    hMCFM.Scale(143.2 / hMCFM.Integral())
    hMCFM = REBIN(hMCFM)

    print hMCFM.Integral()
    hMCFM.Print("range")

    #sys.exit("donesies")

    MWO = GetMCFMHisto(fwo, True)
    MW = GetMCFMHisto(fw, False)
    MWO.Divide(MW)

    MWO.Print("range")

    MWO = REBIN(MWO)

    MWO.Print("range")

    # MWO = REBIN(GetMCFMHisto(fwo,True))
    # MW = REBIN(GetMCFMHisto(fw, False))

    # MWO.Divide(MW)

    # MWO.Print("range")

    #sys.exit("donesies")

    systematic = [
        '_jer', '_jes', '_umet', '_les', '_pu', '_btag', '_qcd', '_pdf'
    ]  #'_jer','_jes','_umet','_les','_pu','_btag','_sherpa','_qcd','_pdf']
    # systematic = ['_jer','_jes','_qcd','_pdf']
    UD = ['up', 'down']
    SYST_UD = ['']
    for syst in systematic:
        for ud in UD:
            SYST_UD.append(syst + ud)

    MCGenHistos = []
    MCRecoHistos = []
    hTrues = []
    hDiffs = []
    hCloses = []
    hunfolds = []
    ########
    MCGenHistosMM = []
    MCRecoHistosMM = []
    hTruesMM = []
    hDiffsMM = []
    hClosesMM = []
    hunfoldsMM = []
    ########
    MCGenHistosEE = []
    MCRecoHistosEE = []
    hTruesEE = []
    hDiffsEE = []
    hClosesEE = []
    hunfoldsEE = []
    ######
    MCGenHistosMM2 = []
    MCGenHistosEE2 = []
    MCGenHistos2 = []

    for syst_ud in SYST_UD:
        print "=O" * 40
        print syst_ud
        print "O=" * 40
        SYS = "(sys" + syst_ud + ">0)"
        cutR = "Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*(preco>0)*" + SYS
        # cutG = "Eweight*BR*(B2/B3)*(pgen>0)*"+SYS #Accstring
        # [5718.8469039797783, 1737.4891278286839, 1737.4891278286839] fb
        #SSS = 2.1299863918*(3.0)
        #SSS = 2.1299863918*(3.0/2.0)
        #SSS = (3.0/2.0)
        #SSS = (3.0)
        #cutG = str(SSS)+"*Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*(pgen>0)*"+SYS #Accstring
        cutG = "Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*(pgen>0)*" + SYS  #Accstring
        # cutG = str(SSS)+"*Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*(1/Acc2)*(pgen>0)*"+SYS #Accstring
        #cutG = str(SSS)+"*Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*(pgen>0)*"+SYS #Accstring
        cutGR = "Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*(pgen>0)*(preco>0)*" + SYS  #+Accstring
        cutWZ = "Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*(preco>0)*" + SYS

        cutGEN = "XS*LUM*(1/NGE)*(B2/B3)*(g_pt>45.0)"
        cutee = "(ee>0.0)"
        cutmm = "(mumu>0.0)"

        # MCRecoHistoMM = REBIN(Make1DPlot(inputdir+"ZZ.root","tmvatree",PAIR[1],outputnameR,cutR+"*"+cutRMM))
        # MCRecoHistoEE = REBIN(Make1DPlot(inputdir+"ZZ.root","tmvatree",PAIR[1],outputnameR,cutR+"*"+cutREE))
        # MCGenHistoMM = REBIN(Make1DPlot(inputdir+"ZZ.root","tmvatree",PAIR[0],outputnameG,cutG+"*"+cutGMM))
        # MCGenHistoEE = REBIN(Make1DPlot(inputdir+"ZZ.root","tmvatree",PAIR[0],outputnameG,cutG+"*"+cutGEE))
        MCRecoHistoMM = Make1DPlot(inputdir + "ZZ.root", "tmvatree", PAIR[1],
                                   outputnameR, cutR + "*" + cutRMM)
        MCRecoHistoEE = Make1DPlot(inputdir + "ZZ.root", "tmvatree", PAIR[1],
                                   outputnameR, cutR + "*" + cutREE)
        MCGenHistoMM = Make1DPlotGEN(inputdir + "ZZ.root", "tmvatree", PAIR[0],
                                     outputnameG, cutG + "*" + cutGMM)
        MCGenHistoEE = Make1DPlotGEN(inputdir + "ZZ.root", "tmvatree", PAIR[0],
                                     outputnameG, cutG + "*" + cutGEE)
        # MCGenHistoMM = Make1DPlotGEN(inputGEN,"GPT","g_pt",outputnameG,cutGEN+"*"+cutmm)
        # MCGenHistoEE = Make1DPlotGEN(inputGEN,"GPT","g_pt",outputnameG,cutGEN+"*"+cutee)
        # MCGenHistoMM.Print("range")
        # sys.exit("done")
        GenVsReco2DHistoMM = Make2DPlot(inputdir + "ZZ.root", "tmvatree", PAIR,
                                        'MM' + outputnameGR,
                                        cutGR + "*" + cutGMM + "*" + cutRMM,
                                        syst_ud)
        GenVsReco2DHistoEE = Make2DPlot(inputdir + "ZZ.root", "tmvatree", PAIR,
                                        'EE' + outputnameGR,
                                        cutGR + "*" + cutGEE + "*" + cutREE,
                                        syst_ud)
        # sys.exit("done")
        #
        MCGenHistoMM2 = Make1DPlotGEN(inputdir2 + "ZZ.root", "tmvatree",
                                      PAIR[0], outputnameG,
                                      cutG + "*" + cutGMM)
        MCGenHistoEE2 = Make1DPlotGEN(inputdir2 + "ZZ.root", "tmvatree",
                                      PAIR[0], outputnameG,
                                      cutG + "*" + cutGEE)

        #MCGenHistoMM2 = Make1DPlotMCFM(1)
        #MCGenHistoEE2 = Make1DPlotMCFM(1)

        hWZMM = Make1DPlot(inputdirWZ + "WZ.root", "tmvatree", PAIR[1],
                           "WZ.png", cutWZ + "*" + cutRMM)  #MC
        hWZEE = Make1DPlot(inputdirWZ + "WZ.root", "tmvatree", PAIR[1],
                           "WZ.png", cutWZ + "*" + cutREE)  #MC

        print hWZMM.Integral(), hWZEE.Integral(), "WZ MM EE"
        print MCRecoHistoMM.Integral(), MCRecoHistoEE.Integral(), "ZZ MM EE"

        BKGDSMM = [REBIN(hsWW[0]), REBIN(hsDY[0]), hWZMM]
        BKGDSEE = [REBIN(hsWW[1]), REBIN(hsDY[1]), hWZEE]

        for bk in (BKGDSMM + BKGDSEE):
            print bk.Integral(), "subtract"

        print hMeasMM.Integral()
        print hMeasEE.Integral()

        hDiffMM = SubtractMany1DPlots(hMeasMM, BKGDSMM)
        hDiffEE = SubtractMany1DPlots(hMeasEE, BKGDSEE)

        # hDiffMM = hMeasMM
        # hDiffEE = hMeasEE

        print hDiffMM.Integral(), quadadd(BinError(hDiffMM))
        print hDiffEE.Integral(), quadadd(BinError(hDiffEE))
        print "Difference between Data and Background^"

        print hMeasMM.Integral(), quadadd(BinError(hMeasMM))
        print hMeasEE.Integral(), quadadd(BinError(hMeasEE))
        print "DATA yield^"

        print REBIN(hsWW[0]).Integral(), quadadd(BinError(REBIN(hsWW[0])))
        print REBIN(hsWW[1]).Integral(), quadadd(BinError(REBIN(hsWW[1])))
        print "NRB yield^"

        print REBIN(hsDY[0]).Integral(), quadadd(BinError(REBIN(hsDY[0])))
        print REBIN(hsDY[1]).Integral(), quadadd(BinError(REBIN(hsDY[1])))
        print "DY yield^"

        print hWZMM.Integral(), quadadd(BinError(hWZMM))
        print hWZEE.Integral(), quadadd(BinError(hWZEE))
        print "WZ yield^"

        print MCRecoHistoMM.Integral(), quadadd(BinError(MCRecoHistoMM))
        print MCRecoHistoEE.Integral(), quadadd(BinError(MCRecoHistoEE))
        print "ZZ yield^"

        #sys.exit("donesies")

        responseMM = RooUnfoldResponse(MCRecoHistoMM, MCGenHistoMM,
                                       GenVsReco2DHistoMM)
        responseEE = RooUnfoldResponse(MCRecoHistoEE, MCGenHistoEE,
                                       GenVsReco2DHistoEE)
        # MCRecoHistoMM.Print("range")
        # MCGenHistoMM.Print("range")
        # GenVsReco2DHistoMM.Print("range")
        #sys.exit("DONE")
        #sys.exit("done")

        # print "==================================== TEST ====================================="
        # #hTrue= TH1D( "true", "Test Truth", 20, -40.0, 40.0 )
        # #hMeas= TH1D( "meas", "Test Measured", 40, -10.0, 10.0 )
        # #hTrue= TH1D( "true", "Test Truth", 10, 40.0, 760.0 )
        # # hMeas= TH1D( "meas", "Test Measured", 10, 0.0, 800.0 )

        print "==================================== UNFOLD ==================================="
        print "Unfolding method:", optunf
        if "Bayes" in optunf:
            # Bayes unfoldung with 4 iterations
            #unfoldMM= RooUnfoldBayes( responseMM, hDiffMM, 4)
            closureMM = RooUnfoldBayes(responseMM, MCRecoHistoMM, 4)

            #unfoldEE= RooUnfoldBayes( responseEE, hDiffEE, 4)
            closureEE = RooUnfoldBayes(responseEE, MCRecoHistoEE, 4)

            unfoldsysMM = RooUnfoldBayes(responseMM, hDiffMM, 4)
            unfoldsysEE = RooUnfoldBayes(responseEE, hDiffEE, 4)

            # if syst_ud == "":
            #   unfoldsysMM.SetNToys(100)
            #   unfoldsysMM.IncludeSystematics()
            #   unfoldsysEE.SetNToys(100)
            #   unfoldsysEE.IncludeSystematics()

            print "Bayes " * 20
            #closure= RooUnfoldBayes( response, MCRecoHisto , 4 )
            #unfold= RooUnfoldBayes( response, hMeas, 10, False, True )
        elif "SVD" in optunf:
            # SVD unfoding with free regularisation
            # unfold= RooUnfoldSvd( response, hMeas, 20 )
            unfold = RooUnfoldSvd(response, hMeas)
        elif "TUnfold" in optunf:
            # TUnfold with fixed regularisation tau=0.002
            # unfold= RooUnfoldTUnfold( response, hMeas )
            unfold = RooUnfoldTUnfold(response, hMeas, 0.002)
        elif "Invert" in optunf:
            unfold = RooUnfoldInvert(response, hMeas)
        elif "Reverse" in optunf:
            unfold = RooUnfoldBayes(response, hMeas, 1)

        #hTrueMM= unfoldMM.Hreco()
        hCloseMM = closureMM.Hreco()
        #hTrueEE= unfoldEE.Hreco()
        hCloseEE = closureEE.Hreco()

        if syst_ud == "":
            #unfoldsysMM.SetNToys(500)
            # unfoldsysMM.IncludeSystematics(0) # 0 DATA ONLY
            unfoldsysMM.IncludeSystematics(1)  # 1 EVERYTHING
            # unfoldsysMM.IncludeSystematics(2) # 2 MC RESPONSE
            #unfoldsysEE.SetNToys(500)
            unfoldsysEE.IncludeSystematics(1)
            # hunfoldMM = unfoldsysMM.Hreco(2) # 2 DIRECT ERROR PROAGATION, ONLY WITH IncludeSystematics(0) -- data only. Can't directly propagate MC response unc.
            hunfoldMM = unfoldsysMM.Hreco(2)
            hunfoldEE = unfoldsysEE.Hreco(
                2
            )  # 3 Toy MC error evaluation. Would apply to both data-MC uncertainty, and MC response uncertainty.
            print "STUFF" * 40
            hunfoldMM.Print("range")

            print "UNFOLDED NUMBERS :--:" * 10
            print hunfoldMM.Integral(), quadadd(BinError(hunfoldMM))
            print hunfoldEE.Integral(), quadadd(BinError(hunfoldEE))
            print "UNFOLDED NUMBERS :--:" * 10

            #############################
            #IMPORTANT!!! Includesys&Hreco: 0&2, 1&2 (some errors), N&2 (bayesian)*, 1&3, 2&3
            #############################
        else:
            hunfoldMM = unfoldsysMM.Hreco()
            hunfoldEE = unfoldsysEE.Hreco()

        print "      ---- TEST @@@@@@@@@@@@@@@@@@@@@@@@@ "
        hunfoldEE.Print("range")
        hunfoldMM.Print("range")

        # print hTrueMM.Integral(), hTrueEE.Integral(), "True"
        print MCGenHistoMM.Integral(), MCGenHistoEE.Integral(), "Gen"
        print hunfoldMM.Integral(), hunfoldEE.Integral(), "unfold"
        #makeComparison(MCGenHistoMM,MCRecoHistoMM,hTrueMM,hDiffMM,hCloseMM,"MM"+syst_ud)
        #makeComparison(MCGenHistoEE,MCRecoHistoEE,hTrueEE,hDiffEE,hCloseEE,"EE"+syst_ud)

        #RESCALE TO MCFM with kinematic cut ratios
        hunfoldEE.Multiply(MWO)
        hunfoldMM.Multiply(MWO)
        MCGenHistoEE.Multiply(MWO)
        MCGenHistoMM.Multiply(MWO)
        MCGenHistoEE2.Multiply(MWO)
        MCGenHistoMM2.Multiply(MWO)
        SSS = 3.0  #3.0 for single channel, 3.0/2.0 for both
        hunfoldMM.Scale(SSS)
        hunfoldEE.Scale(SSS)
        MCGenHistoMM.Scale(SSS)
        MCGenHistoEE.Scale(SSS)
        MCGenHistoMM2.Scale(SSS)
        MCGenHistoEE2.Scale(SSS)

        print MCGenHistoMM.Integral(), MCGenHistoEE.Integral(), "Gen"
        print hunfoldMM.Integral(), hunfoldEE.Integral(), "unfold"

        #sys.exit("donesies")

        #For mumu channel
        hDiffsEE.append([hDiffEE, syst_ud])
        hunfoldsEE.append([hunfoldEE, syst_ud])
        if syst_ud == "":
            hClosesEE.append([hCloseEE, syst_ud])
            MCGenHistosEE.append([MCGenHistoEE, syst_ud])
            MCRecoHistosEE.append([MCRecoHistoEE, syst_ud])
            #MCGenHistosEE2.append([hMCFM,syst_ud])

        #For mumu channel
        hDiffsMM.append([hDiffMM, syst_ud])
        hunfoldsMM.append([hunfoldMM, syst_ud])
        if syst_ud == "":
            hClosesMM.append([hCloseMM, syst_ud])
            MCGenHistosMM.append([MCGenHistoMM, syst_ud])
            MCRecoHistosMM.append([MCRecoHistoMM, syst_ud])
            MCGenHistosMM2.append([hMCFM, syst_ud])

        #For combined channel
        hDiffs.append([ADDER(hDiffMM, hDiffEE, 1), syst_ud])
        hunfolds.append([ADDER(hunfoldMM, hunfoldEE, 1), syst_ud])
        if syst_ud == "":
            hCloses.append([ADDER(hCloseMM, hCloseEE, 1), syst_ud])
            MCGenHistos.append([ADDER(MCGenHistoMM, MCGenHistoEE, 1), syst_ud])
            MCRecoHistos.append(
                [ADDER(MCRecoHistoMM, MCRecoHistoEE, 1), syst_ud])
            MCGenHistos2.append(
                [ADDER(MCGenHistoMM2, MCGenHistoEE2, 1), syst_ud])

        print "=|" * 20
        print syst_ud * 20
        print "unfold yield:"
        print(hunfoldMM.Integral() + hunfoldEE.Integral()) / 19.7
        print(MCGenHistoMM.Integral() + MCGenHistoEE.Integral()) / 19.7, "Gen"

        hunfoldMM.Print("range")
        hunfoldEE.Print("range")
        print ">GEN<" * 40
        MCGenHistoMM.Print("range")
        MCGenHistoEE.Print("range")

        print "=|" * 20

        # print "=|"*20
        # print "unfold yield:"
        # print (hunfoldMM.Integral()+hunfoldEE.Integral())/19.7
        # print "=|"*20

        # hDiffs.append([hDiffEE,syst_ud])
        # hunfolds.append([hunfoldEE,syst_ud])
        # if syst_ud == "":
        #   hCloses.append([hCloseEE,syst_ud])
        #   MCGenHistos.append([MCGenHistoEE,syst_ud])
        #   MCRecoHistos.append([MCRecoHistoEE,syst_ud])

    #QQQ = makeComparison(LUMscale(MCGenHistos),LUMscale(MCRecoHistos),LUMscale(hunfolds),LUMscale(hDiffs),LUMscale(MCGenHistos2),"comb")
    #QQQ= makeComparison(LUMscale(MCGenHistosEE),LUMscale(MCRecoHistosEE),LUMscale(hunfoldsEE),LUMscale(hDiffsEE),MCGenHistosMM2,"ee")
    #QQQ = makeComparison(LUMscale(MCGenHistosMM),LUMscale(MCRecoHistosMM),LUMscale(hunfoldsMM),LUMscale(hDiffsMM),MCGenHistosMM2,"mm")

    #QQQ = makeComparison(LUMscale(MCGenHistos),LUMscale(MCRecoHistos),LUMscale(hunfolds),LUMscale(hDiffs),MCGenHistosMM2,"comb")
    QQQ = makeComparison(LUMscale(MCGenHistosEE), LUMscale(MCRecoHistosEE),
                         LUMscale(hunfoldsEE), LUMscale(hDiffsEE),
                         MCGenHistosMM2, "ee")
    #QQQ = makeComparison(LUMscale(MCGenHistosMM),LUMscale(MCRecoHistosMM),LUMscale(hunfoldsMM),LUMscale(hDiffsMM),MCGenHistosMM2,"mm")
    Neemm = QQQ[0]
    #Nee = makeComparison(LUMscale(MCGenHistosEE),LUMscale(MCRecoHistosEE),LUMscale(hunfoldsEE),LUMscale(hDiffsEE),LUMscale(hClosesEE),"ee")
    #Nmm = makeComparison(LUMscale(MCGenHistosMM),LUMscale(MCRecoHistosMM),LUMscale(hunfoldsMM),LUMscale(hDiffsMM),LUMscale(hClosesMM),"mm")
    # #makeComparison(MCGenHistos,MCRecoHistos,hunfolds,hDiffs,hCloses)
    # print len(MCRecoHistos)
    # print len(hunfolds)

    # print "Bin Content Check"
    # print "#"*30
    # print "#"*10, "DIMUON CHANNEL", "#"*10
    # print "MCReco", MCRecoHistosMM[0][0].Integral(), BinContent(MCRecoHistosMM[0][0])
    # print "MCGen", MCGenHistosMM[0][0].Integral(), BinContent(MCGenHistosMM[0][0])
    # print "True", hunfoldsMM[0][0].Integral(), BinContent(hunfoldsMM[0][0])
    # print "Diff", hDiffsMM[0][0].Integral(), BinContent(hDiffsMM[0][0])

    # print "#"*30
    # print "#"*10, "DIELECTRON CHANNEL", "#"*10
    # print "MCReco", MCRecoHistosEE[0][0].Integral(), BinContent(MCRecoHistosEE[0][0])
    # print "MCGen", MCGenHistosEE[0][0].Integral(), BinContent(MCGenHistosEE[0][0])
    # print "True", hunfoldsEE[0][0].Integral(), BinContent(hunfoldsEE[0][0])
    # print "Diff", hDiffsEE[0][0].Integral(), BinContent(hDiffsEE[0][0])

    # print "#"*30
    # print "#"*10, "COMBINED CHANNEL", "#"*10
    # print "MCReco", MCRecoHistos[0][0].Integral(), BinContent(MCRecoHistos[0][0])
    # print "MCGen", MCGenHistos[0][0].Integral(), BinContent(MCGenHistos[0][0])
    # print "True", hunfolds[0][0].Integral(), BinContent(hunfolds[0][0])
    # print "Diff", hDiffs[0][0].Integral(), BinContent(hDiffs[0][0])
    # print "#"*30
    # print "#"*30
    # print "#"*30

    # print hunfoldsMM[0][0].Integral()*(3.0)*2.13, "ZZ->2l2nu cross section, muon"
    # print hunfoldsEE[0][0].Integral()*(3.0)*2.13, "ZZ->2l2nu cross section, electron"
    # print hunfolds[0][0].Integral()*(3.0/2.0)*2.13, "ZZ->2l2nu cross section, combined"

    # print "#"*30

    # print Nmm
    # print Nee
    print Neemm

    print QQQ[1]
    #print Nmm
    #print Nee

    # print "@"*30
    # print "@"*30
    # print "@"*30

    # S=2.1299863918
    # dS=0.0451194907919

    # print numpy.multiply(Nmm,S*3)
    # print numpy.multiply(Nee,S*3)
    # print numpy.multiply(Neemm,S*3.0/2.0)

    # print "#"*30
    # print "#"*30
    # print "#"*30
    # print numpy.multiply(RescaleToPreZpt45(Nmm,S,dS),3.0), "muons"
    # print numpy.multiply(RescaleToPreZpt45(Nee,S,dS),3.0), "electrons"
    # print numpy.multiply(RescaleToPreZpt45(Neemm,S,dS),3.0/2.0), "combined"

    # Just unfolding
    # [ 317.58667967  124.62000891  124.62000891] muons
    # [ 204.44743361   93.817413     93.817413  ] electrons
    # [ 261.01705568   78.68129176   78.68129176] combined

    #all else
    # Bin Content Check
    # ##############################
    # ########## DIMUON CHANNEL ##########
    # MCReco 5.48821856594 [1.6566265821456909, 1.5307177305221558, 2.0848486423492432, 0.21176119148731232, 0.0042644194327294827]
    # MCGen 50.3628177345 [28.911533355712891, 8.1944065093994141, 11.555961608886719, 1.5890809297561646, 0.11183533072471619]
    # True 49.7008933779 [27.718360900878906, 7.7494301795959473, 13.04161262512207, 1.2007522583007812, -0.0092625860124826431]
    # Diff 5.54152165353 [1.6073417663574219, 1.4832497835159302, 2.371938943862915, 0.16530285775661469, -0.086311697959899902]
    # ##############################
    # ########## DIELECTRON CHANNEL ##########
    # MCReco 3.674643751 [1.0442177057266235, 0.9972614049911499, 1.4791457653045654, 0.15098364651203156, 0.0030352284666150808]
    # MCGen 33.3869778588 [18.415399551391602, 5.4404187202453613, 8.2116708755493164, 1.2221240997314453, 0.097364611923694611]
    # True 31.9951079488 [22.219881057739258, 3.5517585277557373, 5.7815923690795898, 0.44187599420547485, 0.0]
    # Diff 3.02480854467 [1.2913563251495361, 0.70207256078720093, 1.0841209888458252, 0.059399198740720749, -0.11214052885770798]
    # ##############################
    # ########## COMBINED CHANNEL ##########
    # MCReco 9.16539874254 [2.7004456520080566, 2.5281918048858643, 3.5664489269256592, 0.36300751566886902, 0.0073048430494964123]
    # MCGen 83.7497940361 [47.326930999755859, 13.634824752807617, 19.767633438110352, 2.8112049102783203, 0.2091999351978302]
    # True 81.6960010286 [49.938240051269531, 11.301189422607422, 18.823205947875977, 1.6426281929016113, -0.0092625860124826431]
    # Diff 8.56633037329 [2.8986983299255371, 2.1853222846984863, 3.4560599327087402, 0.22470206022262573, -0.19845223426818848]
    # ##############################
    # ##############################
    # ##############################
    # 317.588708685 ZZ->2l2nu cross section, muon
    # 204.448739793 ZZ->2l2nu cross section, electron
    # 261.018723287 ZZ->2l2nu cross section, combined
    # ##############################
    # [49.700893377885222, 24.356035601246898, 24.954409212519852]
    # [31.99510794878006, 17.444453802993618, 19.251802135458732]
    # [81.696001028642058, 34.234254955780528, 37.056285190785381]
    # ##############################
    # ##############################
    # ##############################
    # [ 317.58667967  155.77940538  159.59950658] muons       93.47233023637472982875, 99.70885557387058841952 quaddifference to just unfolding
    # [ 204.44743361  111.55344624  123.09443832] electrons   60.35283246052335146028, 79.69023631100434516015
    # [ 261.01705568  109.51740717  118.52311228] combined    76.17950380658385143785, 88.63962134122213690629

    # os.system(str(Npm)+' > output.txt')
    # SystematicErrors(MCRecoHistos,MCGenHistos,hTrues,hDiffs,hCloses)
    #
    #testtest

    return
Exemplo n.º 4
0
        newContent = gauss(binContent, sqrt(binContent))
        if newContent < 0: newContent = 0
        h_data_toUse.SetBinContent(bin, newContent)
        h_data_toUse.SetBinError(bin, sqrt(newContent))

    h_measured_toUse = asrootpy(h_measured)

    # Remove fakes before unfolding
    h_fakes = h_measured_toUse - h_response.ProjectionX()
    nonFakeRatio = 1 - h_fakes / h_measured_toUse
    h_measured_toUse *= nonFakeRatio / nonFakeRatio
    h_data_toUse *= nonFakeRatio / nonFakeRatio

    # Unfold with SVD
    response = RooUnfoldResponse(h_measured_toUse, h_truth, h_response)
    svdUnfolding = RooUnfoldSvd(response, h_data_toUse, 0.7)
    svdUnfolding.SetVerbose(0)
    h_unfolded_data_svd = svdUnfolding.Hreco(3)

    # Unfold with Bayes
    response_bayes = RooUnfoldResponse(h_measured_toUse, h_truth, h_response)
    bayesUnfolding = RooUnfoldBayes(response_bayes, h_data_toUse, 4)
    h_unfolded_data_bayes = bayesUnfolding.Hreco(3)

    # Store result of first bin
    h_svdFirstBin.Fill(h_unfolded_data_svd.GetBinContent(1))
    h_bayesFirstBin.Fill(h_unfolded_data_bayes.GetBinContent(1))

# Draw histograms
h_svdFirstBin.Draw()
raw_input('SVD')
Exemplo n.º 5
0
def main(optunf="Bayes"):

    optunfs = ["Bayes", "SVD", "TUnfold", "Invert", "Reverse"]
    if not optunf in optunfs:
        txt = "Unfolding option " + optunf + " not recognised"
        raise ValueError(txt)

    global hReco, hMeas, hTrue

    print "==================================== TRAIN ===================================="
    # Create response matrix object for 40 measured and 20
    # unfolded bins:
    response = RooUnfoldResponse(40, -10.0, 10.0, 20, -10.0, 10.0)

    #  Train with a Breit-Wigner, mean 0.3 and width 2.5.
    for i in xrange(100000):
        # xt= gRandom.BreitWigner( 0.3, 2.5 )
        xt = gRandom.Gaus(0.0, 5.0)
        x = smear(xt)
        if x != None:
            response.Fill(x, xt)
        else:
            response.Miss(xt)

    print "==================================== TEST ====================================="
    hTrue = TH1D("true", "Test Truth", 20, -10.0, 10.0)
    hMeas = TH1D("meas", "Test Measured", 40, -10.0, 10.0)
    #  Test with a Gaussian, mean 0 and width 2.
    for i in xrange(10000):
        # xt= gRandom.Gaus( 0.0, 2.0 )
        xt = gRandom.BreitWigner(0.3, 2.5)
        x = smear(xt)
        hTrue.Fill(xt)
        if x != None:
            hMeas.Fill(x)

    print "==================================== UNFOLD ==================================="
    print "Unfolding method:", optunf
    if "Bayes" in optunf:
        # Bayes unfoldung with 4 iterations
        # unfold= RooUnfoldBayes( response, hMeas, 4 )
        unfold = RooUnfoldBayes(response, hMeas, 10, False, True)
    elif "SVD" in optunf:
        # SVD unfoding with free regularisation
        # unfold= RooUnfoldSvd( response, hMeas, 20 )
        unfold = RooUnfoldSvd(response, hMeas)
    elif "TUnfold" in optunf:
        # TUnfold with fixed regularisation tau=0.002
        # unfold= RooUnfoldTUnfold( response, hMeas )
        unfold = RooUnfoldTUnfold(response, hMeas, 0.002)
    elif "Invert" in optunf:
        unfold = RooUnfoldInvert(response, hMeas)
    elif "Reverse" in optunf:
        unfold = RooUnfoldBayes(response, hMeas, 1)

    hReco = unfold.Hreco()
    # unfold.PrintTable( cout, hTrue )
    unfold.PrintTable(cout, hTrue, 2)

    hReco.Draw()
    hMeas.Draw("SAME")
    hTrue.SetLineColor(8)
    hTrue.Draw("SAME")

    return
Exemplo n.º 6
0
for i in range(N / 2, N):
    tree.GetEntry(i)
    xm = tree._recoTop_0_Eta
    xt = tree.trueTop_genParticleSelector_0_Eta
    if xm == xm:
        hMeas_test.Fill(xm)
    if xt == xt:
        hTrue_test.Fill(xt)

of = ROOT.TFile("out_unfold.root", "RECREATE" if unfold else "READ")

if unfold:
    unfoldBayes = RooUnfoldBayes(response, hMeas_test, 4, False, "bayes")
    kReg = 10  #Nbins/2
    unfoldSVD = RooUnfoldSvd(response, hMeas_test, kReg, 1000, "svd")
    unfoldTUnf = RooUnfoldTUnfold(response, hMeas_test,
                                  ROOT.TUnfold.kRegModeDerivative, "tunf")

    hRecoBayes = unfoldBayes.Hreco()
    hRecoSVD = unfoldSVD.Hreco()
    hRecoTUnf = unfoldTUnf.Hreco()
    of.Write()

else:
    hRecoBayes = of.Get("bayes")
    hRecoSVD = of.Get("svd")
    hRecoTUnf = of.Get("tunf")

c1 = ROOT.TCanvas("c1")
hTrue_test.SetTitle("Unfolding result")
Exemplo n.º 7
0
def MyRooUnfold(matrix_name=args.h_matrix, h_reco_getG0_name=args.h_data, h_ptcl_getG0_name = args.h_particle,h_reco_get_bkg_name = args.h_background,outputname=args.h_data+"_unfolded",nrebin = args.nrebin):

    rfile_data = TFile(args.rfile_data, 'read')
    rfile_particle = TFile(args.rfile_particle, 'read')
    rfile_matrix = TFile(args.rfile_matrix, 'read')
    rfile_background = TFile(args.rfile_background, 'read')

    myfbu = fbu.PyFBU()
    myfbu.verbose = True 
    #GET DATA
    h_reco_get = rfile_data.Get(h_reco_getG0_name)
    h_reco_get.Rebin(nrebin)
    #GET PARTICLE
    h_ptcl_get = rfile_particle.Get(h_ptcl_getG0_name)
    h_ptcl_get.Rebin(nrebin)
    #GET MATRIX
    h_response_unf = rfile_matrix.Get(matrix_name)
    h_response_unf.ClearUnderflowAndOverflow()
    h_response_unf.GetXaxis().SetRange(1, h_response_unf.GetXaxis().GetNbins() )
    h_response_unf.GetYaxis().SetRange(1, h_response_unf.GetYaxis().GetNbins() )
    h_response_unf.Rebin2D(nrebin,nrebin)
    h_response_unf.SetName("Migration_Matrix_simulation")

    ########### ACCEPTANCY
    h_acc = h_response_unf.ProjectionX("reco_recoandparticleX") # Reco M
    h_acc.Divide(h_reco_get)
    ########### AKCEPTANCE saved in h_acc #############
    ########### EFFICIENCY
    h_eff = h_response_unf.ProjectionY("reco_recoandparticleY") # Ptcl M
    h_eff.Divide(h_ptcl_get)
    
    h_reco_get_input = rfile_data.Get(h_reco_getG0_name)
    h_reco_get_bkg = rfile_background.Get(h_reco_get_bkg_name)
    h_reco_get_bkg.Rebin(nrebin)

    h_reco_get_input_clone=h_reco_get_input.Clone("")

    h_reco_get_input_clone.Add(h_reco_get_bkg,-1)
    h_reco_get_input_clone.Multiply(h_acc)
    
   
    h_reco_or = rfile_data.Get(h_reco_getG0_name)
    h_ptcl_or = rfile_particle.Get(h_ptcl_getG0_name)
    h_ptcl_or.SetMaximum(h_ptcl_or.GetMaximum()*1.5)
    
    ### ROOUNFOLD METHOD ###
    
    m_RooUnfold = RooUnfoldBayes()
    m_RooUnfold.SetRegParm( 4 )
    m_RooUnfold.SetNToys( 10000 )
    m_RooUnfold.SetVerbose( 0 )
    m_RooUnfold.SetSmoothing( 0 )
  
    response = RooUnfoldResponse(None, None, h_response_unf, "response", "methods")
    
    m_RooUnfold.SetResponse( response )
    m_RooUnfold.SetMeasured( h_reco_get_input_clone )
    
    ### SVD METHOD ###
    
    m_RooUnfold_svd = RooUnfoldSvd (response, h_reco_get_input_clone, int(round(h_reco_get_input_clone.GetNbinsX()/2.0,0))) #8
    svd_par = int(round(h_reco_get_input_clone.GetNbinsX()/2.0,0))
    m_RooUnfold_T = RooUnfoldTUnfold (response, h_reco_get_input_clone)         #  OR
    m_RooUnfold_Ids= RooUnfoldIds (response, h_reco_get_input_clone,int(round(h_reco_get_input_clone.GetNbinsX()/12.0,0))) ## TO DO, SET PARAMETERS TO THE BINNING
    Ids_par = int(round(h_reco_get_input_clone.GetNbinsX()/12.0,0))
    
    ### FBU METHOD ###
    
    h_response_unf_fbu = TransposeMatrix(h_response_unf)
    h_response_unf_fbu_norm = NormalizeResponse(h_response_unf_fbu)
    h_response_unf_fbu_norm.SetName("Migration_Matrix_simulation_transpose")
    histograms.append(h_response_unf_fbu_norm)
    myfbu.response = MakeListResponse(h_response_unf_fbu_norm)
    myfbu.data = MakeListFromHisto(h_reco_get_input_clone) 
    myfbu.lower = []
    myfbu.upper = []
    
    h_det_div_ptcl=h_reco_get_input_clone.Clone("")
    h_det_div_ptcl.Divide(h_ptcl_or)
    h_det_div_ptcl.Divide(h_eff)
    h_det_div_ptcl.SetName("det_div_ptcl")
    histograms.append(h_det_div_ptcl)

    for l in range(len(myfbu.data)):
        if ( args.SplitFromBinLow != 0) and ( l+1 <= args.SplitFromBinLow ):
            myfbu.lower.append(h_reco_get_input_clone.GetBinContent(l+1)*(2-args.ParameterSplitFromBinLow)*h_det_div_ptcl.GetBinContent(l+1))
            myfbu.upper.append(h_reco_get_input_clone.GetBinContent(l+1)*args.ParameterSplitFromBinLow*h_det_div_ptcl.GetBinContent(l+1))
        elif ( args.SplitFromBinHigh != 0 ) and ( l+1 >= args.SplitFromBinHigh ):
            myfbu.lower.append(h_reco_get_input_clone.GetBinContent(l+1)*(2-args.ParameterSplitFromBinHigh)*h_det_div_ptcl.GetBinContent(l+1))
            myfbu.upper.append(h_reco_get_input_clone.GetBinContent(l+1)*args.ParameterSplitFromBinHigh*h_det_div_ptcl.GetBinContent(l+1))
        else:
            myfbu.lower.append(h_reco_get_input_clone.GetBinContent(l+1)*(2-args.par)*h_det_div_ptcl.GetBinContent(l+1))
            myfbu.upper.append(h_reco_get_input_clone.GetBinContent(l+1)*args.par*h_det_div_ptcl.GetBinContent(l+1))
    #myfbu.regularization = Regularization('Tikhonov',parameters=[{'refcurv':0.1,'alpha':0.2}]) works for old FBU package and python2.7 and old pymc
    myfbu.run()
    trace = myfbu.trace
    traceName = 'Posterior_1_iteration'
    posteriors_diag = MakeTH1Ds(trace, traceName)
    h_reco_unfolded, h_reco_unfolded_Mean = MakeUnfoldedHisto(h_reco_or, posteriors_diag)
    PlotPosteriors(posteriors_diag,outputname+'_iteration_1')
    # EFFICIENCY AND ACCEPTANCY CORRECTIONS
    h_reco_unfolded.Divide(h_eff)
    h_reco_unfolded_Mean.Divide(h_eff)

    h_reco_unfolded_roof = m_RooUnfold.Hreco()
    h_reco_unfolded_roof.Divide(h_eff)

    h_reco_unfolded_svd = m_RooUnfold_svd.Hreco()
    h_reco_unfolded_svd.Divide(h_eff)

    h_reco_unfolded_T = m_RooUnfold_T.Hreco()
    h_reco_unfolded_T.Divide(h_eff)

    h_reco_unfolded_Ids = m_RooUnfold_Ids.Hreco()
    h_reco_unfolded_Ids.Divide(h_eff)

    PlotRatio(h_reco_unfolded_Mean, h_ptcl_or, h_reco_unfolded_roof, h_reco_unfolded_svd, h_reco_unfolded_T,h_reco_unfolded_Ids, svd_par, Ids_par, outputname+'_iteration_1')        

    Repeat = True
    j = 2
    while Repeat:
        print("Runnig iteration number: ",j)
        myfbu.lower = []
        myfbu.upper = []
        for l in range(len(myfbu.data)):
            posteriors_diag[l].Fit("gaus")
            fit = posteriors_diag[l].GetFunction("gaus") 
            p1 = fit.GetParameter(1)
            p2 = fit.GetParameter(2)
            myfbu.lower.append(p1-4*p2)
            myfbu.upper.append(p1+4*p2)
        myfbu.run()
        trace = myfbu.trace
        traceName = 'Posterior_'+str(j)+'_iteration'
        posteriors_diag = MakeTH1Ds(trace, traceName)
        h_reco_unfolded, h_reco_unfolded_Mean = MakeUnfoldedHisto(h_reco_or, posteriors_diag)
        Repeat = PlotPosteriors(posteriors_diag,outputname+'_iteration_'+str(j))
        # EFFICIENCY AND ACCEPTANCY CORRECTIONS
        h_reco_unfolded.Divide(h_eff)
        h_reco_unfolded_Mean.Divide(h_eff)
        h_reco_unfolded_roof = m_RooUnfold.Hreco()
        h_reco_unfolded_roof.Divide(h_eff)
        h_reco_unfolded_svd = m_RooUnfold_svd.Hreco()
        h_reco_unfolded_svd.Divide(h_eff)
        h_reco_unfolded_T = m_RooUnfold_T.Hreco()
        h_reco_unfolded_T.Divide(h_eff)
        h_reco_unfolded_Ids = m_RooUnfold_Ids.Hreco()
        h_reco_unfolded_Ids.Divide(h_eff)
        PlotRatio(h_reco_unfolded_Mean, h_ptcl_or, h_reco_unfolded_roof, h_reco_unfolded_svd, h_reco_unfolded_T,h_reco_unfolded_Ids, svd_par, Ids_par, outputname+'_iteration_'+str(j))
        if j == args.maxiterations:
            break
        j = j+1

    h_reco_unfolded.SetName("result_fbu_fit")
    histograms.append(h_reco_unfolded)
    
    h_reco_unfolded_Mean.SetName("result_fbu_Mean")
    histograms.append(h_reco_unfolded_Mean)
    
    h_reco_unfolded_roof.SetName("result_roof")
    histograms.append(h_reco_unfolded_roof)
    
    h_reco_unfolded_svd.SetName("result_svd")
    histograms.append(h_reco_unfolded_svd)
    
    h_reco_unfolded_T.SetName("result_T")
    histograms.append(h_reco_unfolded_T)
    
    h_reco_unfolded_Ids.SetName("result_Ids")
    histograms.append(h_reco_unfolded_Ids)

    h_eff.SetName("efficiency")
    histograms.append(h_eff)
    h_acc.SetName("acceptancy")
    histograms.append(h_acc)
    
    h_reco_or.SetName("reco")
    histograms.append(h_reco_or)
    h_ptcl_or.SetName("ptcl_simulation")
    histograms.append(h_ptcl_or)

    h_ratio = h_reco_unfolded.Clone("")
    h_ratio.Divide(h_ptcl_or)
    h_ratio.SetName("ratio_fbu_fit")
    histograms.append(h_ratio)
    
    h_ratio = h_reco_unfolded_Mean.Clone("")
    h_ratio.Divide(h_ptcl_or)
    h_ratio.SetName("ratio_fbu_Mean")
    histograms.append(h_ratio)

    h_ratio = h_reco_unfolded_roof.Clone("")
    h_ratio.Divide(h_ptcl_or)
    h_ratio.SetName("ratio_roof")
    histograms.append(h_ratio)
    
    h_ratio = h_reco_unfolded_svd.Clone("")
    h_ratio.Divide(h_ptcl_or)
    h_ratio.SetName("ratio_svd")
    histograms.append(h_ratio)

    m_RooUnfold_svd.PrintTable (cout, h_ptcl_or)
    m_RooUnfold.PrintTable (cout, h_ptcl_or)
  
    # CORRECTIONS TO GET CROSS SECTION

    #DivideBinWidth(h_reco_unfolded_Mean)
    #DivideBinWidth(h_reco_unfolded_roof)
    #DivideBinWidth(h_reco_unfolded_svd)
    #DivideBinWidth(h_reco_unfolded_T)
    #DivideBinWidth(h_reco_unfolded_Ids)
    #DivideBinWidth(h_ptcl_or)
    #Lumi = 36.1e3
    #for j in range(1,h_reco_unfolded_Mean.GetXaxis().GetNbins()+1):
    #    h_reco_unfolded_Mean.SetBinContent(j,h_reco_unfolded_Mean.GetBinContent(j)/(Lumi))
    #    h_reco_unfolded_Mean.SetBinError(j,h_reco_unfolded_Mean.GetBinError(j)/(Lumi))
    #    h_reco_unfolded_roof.SetBinContent(j,h_reco_unfolded_roof.GetBinContent(j)/(Lumi))
    #    h_reco_unfolded_roof.SetBinError(j,h_reco_unfolded_roof.GetBinError(j)/(Lumi))
    #    h_reco_unfolded_svd.SetBinContent(j,h_reco_unfolded_svd.GetBinContent(j)/(Lumi))
    #    h_reco_unfolded_svd.SetBinError(j,h_reco_unfolded_svd.GetBinError(j)/(Lumi))
    #    h_reco_unfolded_T.SetBinContent(j,h_reco_unfolded_T.GetBinContent(j)/(Lumi))
    #    h_reco_unfolded_T.SetBinError(j,h_reco_unfolded_T.GetBinError(j)/(Lumi))
    #    h_reco_unfolded_Ids.SetBinContent(j,h_reco_unfolded_Ids.GetBinContent(j)/(Lumi))
    #    h_reco_unfolded_Ids.SetBinError(j,h_reco_unfolded_Ids.GetBinError(j)/(Lumi))
    #    h_ptcl_or.SetBinContent(j,h_ptcl_or.GetBinContent(j)/(Lumi))
    #    h_ptcl_or.SetBinError(j,h_ptcl_or.GetBinError(j)/(Lumi))
    #h_reco_unfolded_Mean_clone=h_reco_unfolded_Mean.Clone("FBU_cross_section")
    #h_reco_unfolded_roof_clone=h_reco_unfolded_roof.Clone("DAgostini_cross_section")
    #h_reco_unfolded_svd_clone=h_reco_unfolded_svd.Clone("SVD_cross_section")
    #h_reco_unfolded_T_clone=h_reco_unfolded_T.Clone("TUnfold_cross_section")
    #h_reco_unfolded_Ids_clone=h_reco_unfolded_Ids.Clone("Ids_cross_section")
    #h_ptcl_or_clone=h_ptcl_or.Clone("Truth_cross_section")
    #
    #print("CONTROL*******************************************************************: ",h_reco_unfolded_Mean_clone.GetXaxis().GetNbins(),h_reco_unfolded_roof_clone.GetXaxis().GetNbins(),h_reco_unfolded_svd_clone.GetXaxis().GetNbins(),h_reco_unfolded_T_clone.GetXaxis().GetNbins(),h_reco_unfolded_Ids_clone.GetXaxis().GetNbins(),h_ptcl_or_clone.GetXaxis().GetNbins())
    #histograms.append(h_reco_unfolded_Mean_clone)
    #histograms.append(h_reco_unfolded_roof_clone)
    #histograms.append(h_reco_unfolded_svd_clone)
    #histograms.append(h_reco_unfolded_T_clone)
    #histograms.append(h_reco_unfolded_Ids_clone)
    #histograms.append(h_ptcl_or_clone)
    SaveHistograms(outputname)
Exemplo n.º 8
0
def main():
    if len(sys.argv) < 3:
        print("Usage: ToyMC [numberEvents] [randomSeed]")
        return
    numberEvents = int(sys.argv[1])
    seed = int(sys.argv[2])
    print(
        "==================================== TRAIN ===================================="
    )

    f = root_open(
        "legotrain_350_20161117-2106_LHCb4_fix_CF_pPb_MC_ptHardMerged.root", "read"
    )
    hJetPt = f.Get("AliJJetJtTask/AliJJetJtHistManager/JetPt/JetPtNFin{:02d}".format(2))
    hZ = f.Get("AliJJetJtTask/AliJJetJtHistManager/Z/ZNFin{:02d}".format(2))

    FillFakes = False
    dummy_variable = True
    weight = True

    NBINS = 50
    LimL = 0.1
    LimH = 500
    logBW = (TMath.Log(LimH) - TMath.Log(LimL)) / NBINS
    LogBinsX = [LimL * math.exp(ij * logBW) for ij in range(0, NBINS + 1)]

    hJetPtMeas = Hist(LogBinsX)
    hJetPtTrue = Hist(LogBinsX)

    myRandom = TRandom3(seed)
    fEff = TF1("fEff", "1-0.5*exp(-x)")
    jetBinBorders = [5, 10, 20, 30, 40, 60, 80, 100, 150, 500]
    hJetPtMeasCoarse = Hist(jetBinBorders)
    hJetPtTrueCoarse = Hist(jetBinBorders)

    NBINSJt = 64
    low = 0.01
    high = 10
    BinW = (TMath.Log(high) - TMath.Log(low)) / NBINSJt
    LogBinsJt = [low * math.exp(i * BinW) for i in range(NBINSJt + 1)]
    hJtTrue = Hist(LogBinsJt)
    hJtMeas = Hist(LogBinsJt)
    hJtFake = Hist(LogBinsJt)
    LogBinsPt = jetBinBorders
    jetPtBins = [(a, b) for a, b in zip(jetBinBorders, jetBinBorders[1:])]

    hJtTrue2D = Hist2D(LogBinsJt, LogBinsPt)
    hJtMeas2D = Hist2D(LogBinsJt, LogBinsPt)
    hJtFake2D = Hist2D(LogBinsJt, LogBinsPt)
    hJtMeasBin = [Hist(LogBinsJt) for i in jetBinBorders]
    hJtTrueBin = [Hist(LogBinsJt) for i in jetBinBorders]

    response = RooUnfoldResponse(hJtMeas, hJtTrue)
    response2D = RooUnfoldResponse(hJtMeas2D, hJtTrue2D)
    responseBin = [RooUnfoldResponse(hJtMeas, hJtTrue) for i in jetBinBorders]
    responseJetPt = RooUnfoldResponse(hJetPtMeas, hJetPtTrue)
    responseJetPtCoarse = RooUnfoldResponse(hJetPtMeasCoarse, hJetPtTrueCoarse)

    # Histogram index is jet pT index, Bin 0 is 5-10 GeV
    # Histogram X axis is observed jT, Bin 0 is underflow
    # Histogram Y axis is observed jet Pt, Bin 0 is underflow
    # Histogram Z axis is True jT, Bin 0 is underflow
    responses = [Hist3D(LogBinsJt, LogBinsPt, LogBinsJt) for i in jetPtBins]
    misses = Hist2D(LogBinsJt, LogBinsPt)
    fakes2D = Hist2D(LogBinsJt, LogBinsPt)
    outFile = TFile("tuple.root", "recreate")
    responseTuple = TNtuple(
        "responseTuple", "responseTuple", "jtObs:ptObs:jtTrue:ptTrue"
    )

    hMultiTrue = Hist(50, 0, 50)
    hMultiMeas = Hist(50, 0, 50)
    hZMeas = Hist(50, 0, 1)
    hZTrue = Hist(50, 0, 1)
    hZFake = Hist(50, 0, 1)
    responseMatrix = Hist2D(LogBinsJt, LogBinsJt)
    numberJets = 0
    numberFakes = 0
    numberJetsMeasBin = [0 for i in jetBinBorders]
    numberJetsTrueBin = [0 for i in jetBinBorders]
    numberFakesBin = [0 for i in jetBinBorders]
    ieout = numberEvents / 10
    if ieout > 10000:
        ieout = 10000
    fakeRate = 1
    start_time = datetime.now()
    print("Processing Training Events")
    for ievt in range(numberEvents):
        tracksTrue = []
        tracksMeas = [0 for x in range(100)]
        if ievt % ieout == 0 and ievt > 0:
            time_elapsed = datetime.now() - start_time
            time_left = timedelta(
                seconds=time_elapsed.total_seconds()
                * 1.0
                * (numberEvents - ievt)
                / ievt
            )
            print(
                "Event {} [{:.2f}%] Time Elapsed: {} ETA: {}".format(
                    ievt,
                    100.0 * ievt / numberEvents,
                    fmtDelta(time_elapsed),
                    fmtDelta(time_left),
                )
            )
        jetTrue = TVector3(0, 0, 0)
        jetMeas = TVector3(0, 0, 0)
        jetPt = hJetPt.GetRandom()
        remainder = jetPt
        if jetPt < 5:
            continue
        nt = 0
        nt_meas = 0
        while remainder > 0:
            trackPt = hZ.GetRandom() * jetPt
            if trackPt < remainder:
                track = TVector3()
                remainder = remainder - trackPt
            else:
                trackPt = remainder
                remainder = -1
            if trackPt > 0.15:
                track.SetPtEtaPhi(
                    trackPt, myRandom.Gaus(0, 0.1), myRandom.Gaus(math.pi, 0.2)
                )
                tracksTrue.append(track)
                jetTrue += track
                if fEff.Eval(trackPt) > myRandom.Uniform(0, 1):
                    tracksMeas[nt] = 1
                    jetMeas += track
                    nt_meas += 1
                else:
                    tracksMeas[nt] = 0
                nt += 1
        fakes = []
        for it in range(fakeRate * 100):
            if myRandom.Uniform(0, 1) > 0.99:
                fake = TVector3()
                fake.SetPtEtaPhi(
                    myRandom.Uniform(0.15, 1),
                    myRandom.Gaus(0, 0.1),
                    myRandom.Gaus(math.pi, 0.2),
                )
                fakes.append(fake)
                jetMeas += fake

        hJetPtMeas.Fill(jetMeas.Pt())
        hJetPtTrue.Fill(jetTrue.Pt())
        responseJetPt.Fill(jetMeas.Pt(), jetTrue.Pt())
        responseJetPtCoarse.Fill(jetMeas.Pt(), jetTrue.Pt())
        hMultiTrue.Fill(nt)
        hMultiMeas.Fill(nt_meas)
        ij_meas = GetBin(jetBinBorders, jetMeas.Pt())
        ij_true = GetBin(jetBinBorders, jetTrue.Pt())
        if nt < 5 or nt_meas < 5:
            continue
        numberJets += 1
        if ij_meas >= 0:
            numberJetsMeasBin[ij_meas] += 1
            hJetPtMeasCoarse.Fill(jetMeas.Pt())
        if ij_true >= 0:
            numberJetsTrueBin[ij_true] += 1
            hJetPtTrueCoarse.Fill(jetTrue.Pt())
        for track, it in zip(tracksTrue, range(100)):
            zTrue = (track * jetTrue.Unit()) / jetTrue.Mag()
            jtTrue = (track - scaleJet(jetTrue, zTrue)).Mag()
            hZTrue.Fill(zTrue)
            if ij_true >= 0:
                if weight:
                    hJtTrue.Fill(jtTrue, 1.0 / jtTrue)
                    hJtTrueBin[ij_true].Fill(jtTrue, 1.0 / jtTrue)
                    hJtTrue2D.Fill(jtTrue, jetTrue.Pt(), 1.0 / jtTrue)
                else:
                    hJtTrue.Fill(jtTrue)
                    hJtTrueBin[ij_true].Fill(jtTrue)
                    hJtTrue2D.Fill(jtTrue, jetTrue.Pt())
            if ij_meas >= 0:
                if tracksMeas[it] == 1:
                    zMeas = (track * jetMeas.Unit()) / jetMeas.Mag()
                    jtMeas = (track - scaleJet(jetMeas, zMeas)).Mag()
                    hZMeas.Fill(zMeas)
                    if weight:
                        hJtMeasBin[ij_meas].Fill(jtMeas, 1.0 / jtMeas)
                        hJtMeas.Fill(jtMeas, 1.0 / jtMeas)
                        hJtMeas2D.Fill(jtMeas, jetMeas.Pt(), 1.0 / jtMeas)
                    else:
                        hJtMeas.Fill(jtMeas)
                        hJtMeasBin[ij_meas].Fill(jtMeas)
                        hJtMeas2D.Fill(jtMeas, jetMeas.Pt())
                    response.Fill(jtMeas, jtTrue)
                    responseBin[ij_true].Fill(jtMeas, jtTrue)
                    response2D.Fill(jtMeas, jetMeas.Pt(), jtTrue, jetTrue.Pt())
                    responseMatrix.Fill(jtMeas, jtTrue)
                    responses[ij_true].Fill(jtMeas, jetMeas.Pt(), jtTrue)
                    responseTuple.Fill(jtMeas, jetMeas.Pt(), jtTrue, jetTrue.Pt())
                else:
                    response.Miss(jtTrue)
                    responseBin[ij_true].Miss(jtTrue)
                    response2D.Miss(jtTrue, jetTrue.Pt())
                    misses.Fill(jtTrue, jetTrue.Pt())
                    responseTuple.Fill(-1, -1, jtTrue, jetTrue.Pt())
        if ij_meas >= 0:
            for fake in fakes:
                zFake = (fake * jetMeas.Unit()) / jetMeas.Mag()
                jtFake = (fake - scaleJet(jetMeas, zFake)).Mag()
                hZMeas.Fill(zFake)
                hZFake.Fill(zFake)
                if weight:
                    hJtMeas.Fill(jtFake, 1.0 / jtFake)
                    hJtMeasBin[ij_meas].Fill(jtFake, 1.0 / jtFake)
                    hJtMeas2D.Fill(jtFake, jetMeas.Pt(), 1.0 / jtFake)
                    hJtFake2D.Fill(jtFake, jetMeas.Pt(), 1.0 / jtFake)
                    hJtFake.Fill(jtFake, 1.0 / jtFake)
                else:
                    hJtMeas.Fill(jtFake)
                    hJtMeasBin[ij_meas].Fill(jtFake)
                    hJtMeas2D.Fill(jtFake, jetMeas.Pt())
                    hJtFake2D.Fill(jtFake, jetMeas.Pt())
                    hJtFake.Fill(jtFake)
                if FillFakes:
                    response.Fake(jtFake)
                    responseBin[ij_true].Fake(jtFake)
                    response2D.Fake(jtFake, jetMeas.Pt())
                    fakes2D.Fill(jtFake, jetMeas.Pt())
                    responseTuple.Fill(jtFake, jetMeas.Pt(), -1, -1)
                    numberFakes += 1
                    numberFakesBin[ij_true] += 1

    response2Dtest = make2Dresponse(
        responses, jetPtBins, hJtMeas2D, hJtTrue2D, misses=misses, fakes=fakes2D
    )

    if dummy_variable:
        hJetPtMeas.Reset()
        hJetPtTrue.Reset()
        hMultiTrue.Reset()
        hMultiMeas.Reset()
        hJetPtMeasCoarse.Reset()
        hJetPtTrueCoarse.Reset()
        hZTrue.Reset()
        hZMeas.Reset()
        hJtTrue.Reset()
        hJtTrue2D.Reset()
        hJtMeas.Reset()
        hJtMeas2D.Reset()
        hJtFake.Reset()
        hJtFake2D.Reset()
        for h, h2 in zip(hJtTrueBin, hJtMeasBin):
            h.Reset()
            h2.Reset()
        numberJetsMeasBin = [0 for i in jetBinBorders]
        numberJetsTrueBin = [0 for i in jetBinBorders]
        numberJets = 0
        print("Create testing data")
        start_time = datetime.now()
        numberEvents = numberEvents / 2
        for ievt in range(numberEvents):
            tracksTrue = []
            tracksMeas = [0 for x in range(100)]
            if ievt % ieout == 0 and ievt > 0:
                time_elapsed = datetime.now() - start_time
                time_left = timedelta(
                    seconds=time_elapsed.total_seconds()
                    * 1.0
                    * (numberEvents - ievt)
                    / ievt
                )
                print(
                    "Event {} [{:.2f}%] Time Elapsed: {} ETA: {}".format(
                        ievt,
                        100.0 * ievt / numberEvents,
                        fmtDelta(time_elapsed),
                        fmtDelta(time_left),
                    )
                )
            jetTrue = TVector3(0, 0, 0)
            jetMeas = TVector3(0, 0, 0)
            jetPt = hJetPt.GetRandom()
            remainder = jetPt
            if jetPt < 5:
                continue
            nt = 0
            nt_meas = 0
            while remainder > 0:
                trackPt = hZ.GetRandom() * jetPt
                if trackPt < remainder:
                    track = TVector3()
                    remainder = remainder - trackPt
                else:
                    trackPt = remainder
                    remainder = -1
                if trackPt > 0.15:
                    track.SetPtEtaPhi(
                        trackPt, myRandom.Gaus(0, 0.1), myRandom.Gaus(math.pi, 0.2)
                    )
                    tracksTrue.append(track)
                    jetTrue += track
                    if fEff.Eval(trackPt) > myRandom.Uniform(0, 1):
                        tracksMeas[nt] = 1
                        jetMeas += track
                        nt_meas += 1
                    else:
                        tracksMeas[nt] = 0
                    nt += 1
            fakes = []
            for it in range(fakeRate * 100):
                if myRandom.Uniform(0, 1) > 0.99:
                    fake = TVector3()
                    fake.SetPtEtaPhi(
                        myRandom.Uniform(0.15, 1),
                        myRandom.Gaus(0, 0.1),
                        myRandom.Gaus(math.pi, 0.2),
                    )
                    fakes.append(fake)
                    jetMeas += fake
            hJetPtMeas.Fill(jetMeas.Pt())
            hJetPtTrue.Fill(jetTrue.Pt())
            hMultiTrue.Fill(nt)
            hMultiMeas.Fill(nt_meas)
            ij_meas = GetBin(jetBinBorders, jetMeas.Pt())
            ij_true = GetBin(jetBinBorders, jetTrue.Pt())
            if nt < 5 or nt_meas < 5:
                continue
            numberJets += 1
            if ij_meas >= 0:
                numberJetsMeasBin[ij_meas] += 1
                hJetPtMeasCoarse.Fill(jetMeas.Pt())
            if ij_true >= 0:
                numberJetsTrueBin[ij_true] += 1
                hJetPtTrueCoarse.Fill(jetTrue.Pt())
            for track, it in zip(tracksTrue, range(100)):
                zTrue = (track * jetTrue.Unit()) / jetTrue.Mag()
                jtTrue = (track - scaleJet(jetTrue, zTrue)).Mag()
                hZTrue.Fill(zTrue)
                if ij_true >= 0:
                    if weight:
                        hJtTrue.Fill(jtTrue, 1.0 / jtTrue)
                        hJtTrueBin[ij_true].Fill(jtTrue, 1.0 / jtTrue)
                        hJtTrue2D.Fill(jtTrue, jetTrue.Pt(), 1.0 / jtTrue)
                    else:
                        hJtTrue.Fill(jtTrue)
                        hJtTrueBin[ij_true].Fill(jtTrue)
                        hJtTrue2D.Fill(jtTrue, jetTrue.Pt())
                if ij_meas >= 0:
                    if tracksMeas[it] == 1:
                        zMeas = (track * jetMeas.Unit()) / jetMeas.Mag()
                        jtMeas = (track - scaleJet(jetMeas, zMeas)).Mag()
                        hZMeas.Fill(zMeas)
                        if weight:
                            hJtMeasBin[ij_meas].Fill(jtMeas, 1.0 / jtMeas)
                            hJtMeas.Fill(jtMeas, 1.0 / jtMeas)
                            hJtMeas2D.Fill(jtMeas, jetMeas.Pt(), 1.0 / jtMeas)
                        else:
                            hJtMeas.Fill(jtMeas)
                            hJtMeasBin[ij_meas].Fill(jtMeas)
                            hJtMeas2D.Fill(jtMeas, jetMeas.Pt())
            if ij_meas >= 0:
                for fake in fakes:
                    zFake = (fake * jetMeas.Unit()) / jetMeas.Mag()
                    jtFake = (fake - scaleJet(jetMeas, zFake)).Mag()
                    hZMeas.Fill(zFake)
                    hZFake.Fill(zFake)
                    if weight:
                        hJtMeas.Fill(jtFake, 1.0 / jtFake)
                        hJtMeasBin[ij_meas].Fill(jtFake, 1.0 / jtFake)
                        hJtMeas2D.Fill(jtFake, jetMeas.Pt(), 1.0 / jtFake)
                        hJtFake2D.Fill(jtFake, jetMeas.Pt(), 1.0 / jtFake)
                        hJtFake.Fill(jtFake, 1.0 / jtFake)
                    else:
                        hJtMeas.Fill(jtFake)
                        hJtMeasBin[ij_meas].Fill(jtFake)
                        hJtMeas2D.Fill(jtFake, jetMeas.Pt())
                        hJtFake2D.Fill(jtFake, jetMeas.Pt())
                        hJtFake.Fill(jtFake)

    time_elapsed = datetime.now() - start_time
    print(
        "Event {} [{:.2f}%] Time Elapsed: {}".format(
            numberEvents, 100.0, fmtDelta(time_elapsed)
        )
    )
    if not FillFakes:
        hJtMeas.Add(hJtFake, -1)
        hJtMeas2D.Add(hJtFake2D, -1)
    responseTuple.Print()
    outFile.Write()
    #  printTuple(responseTuple)

    hJtMeasProjBin = [
        makeHist(hJtMeas2D.ProjectionX("histMeas{}".format(i), i, i), bins=LogBinsJt)
        for i in range(1, len(jetBinBorders))
    ]
    hJtMeasProj = makeHist(hJtMeas2D.ProjectionX("histMeas"), bins=LogBinsJt)
    hJtTrueProjBin = [
        makeHist(hJtTrue2D.ProjectionX("histTrue{}".format(i), i, i), bins=LogBinsJt)
        for i in range(1, len(jetBinBorders))
    ]
    hJtTrueProj = makeHist(hJtTrue2D.ProjectionX("histTrue"), bins=LogBinsJt)
    hJtFakeProjBin = [
        makeHist(hJtFake2D.ProjectionX("histFake{}".format(i), i, i), bins=LogBinsJt)
        for i in range(1, len(jetBinBorders))
    ]

    if not FillFakes:
        for h, h2 in zip(hJtMeasBin, hJtFakeProjBin):
            h.Add(h2, -1)

    for h in (
        hJtMeasProj,
        hJtTrueProj,
        hJtMeas,
        hJtTrue,
        hJtFake,
        hZFake,
        hZMeas,
        hZTrue,
    ):
        h.Scale(1.0 / numberJets, "width")
    for meas, true, n_meas, n_true in zip(
        hJtMeasBin, hJtTrueBin, numberJetsMeasBin, numberJetsTrueBin
    ):
        if n_meas > 0:
            meas.Scale(1.0 / n_meas, "width")
        if n_true > 0:
            true.Scale(1.0 / n_true, "width")

    numberJetsMeasFromHist = [
        hJetPtMeasCoarse.GetBinContent(i)
        for i in range(1, hJetPtMeasCoarse.GetNbinsX() + 1)
    ]
    numberJetsTrueFromHist = [
        hJetPtTrueCoarse.GetBinContent(i)
        for i in range(1, hJetPtTrueCoarse.GetNbinsX() + 1)
    ]
    print("Total number of jets: {}".format(numberJets))
    print("Total number of fakes: {}".format(numberFakes))
    print("Measured jets by bin")
    print(numberJetsMeasBin)
    print(numberJetsMeasFromHist)
    print("True jets by bin")
    print(numberJetsTrueBin)
    print(numberJetsTrueFromHist)
    hRecoJetPtCoarse = unfoldJetPt(hJetPtMeasCoarse, responseJetPtCoarse, jetBinBorders)
    numberJetsFromReco = [
        hRecoJetPtCoarse.GetBinContent(i)
        for i in range(1, hRecoJetPtCoarse.GetNbinsX())
    ]
    print("Unfolded jet numbers by bin:")
    print(numberJetsFromReco)

    print("Fakes by bin")
    print(numberFakesBin)

    print(
        "==================================== UNFOLD ==================================="
    )
    unfold = RooUnfoldBayes(response, hJtMeas, 4)  #  OR
    unfoldSVD = RooUnfoldSvd(response, hJtMeas, 20)  #  OR
    unfold2D = RooUnfoldBayes(response2D, hJtMeas2D, 4)
    for u in (unfold, unfoldSVD, unfold2D):
        u.SetVerbose(0)
    # response2Dtest = makeResponseFromTuple(responseTuple,hJtMeas2D,hJtTrue2D)

    unfold2Dtest = RooUnfoldBayes(response2Dtest, hJtMeas2D, 4)

    unfoldBin = [
        RooUnfoldBayes(responseBin[i], hJtMeasBin[i]) for i in range(len(jetBinBorders))
    ]
    for u in unfoldBin:
        u.SetVerbose(0)
    hRecoBayes = makeHist(unfold.Hreco(), bins=LogBinsJt)
    hRecoSVD = makeHist(unfoldSVD.Hreco(), bins=LogBinsJt)
    hRecoBin = [
        makeHist(unfoldBin[i].Hreco(), bins=LogBinsJt)
        for i in range(len(jetBinBorders))
    ]
    hReco2D = make2DHist(unfold2D.Hreco(), xbins=LogBinsJt, ybins=LogBinsPt)
    hReco2Dtest = make2DHist(unfold2Dtest.Hreco(), xbins=LogBinsJt, ybins=LogBinsPt)
    hRecoJetPt = unfoldJetPt(hJetPtMeas, responseJetPt, LogBinsX)

    hReco2DProjBin = [
        makeHist(hReco2D.ProjectionX("histReco{}".format(i), i, i), bins=LogBinsJt)
        for i in range(1, len(jetBinBorders))
    ]
    hReco2DTestProjBin = [
        makeHist(
            hReco2Dtest.ProjectionX("histRecoTest{}".format(i), i, i), bins=LogBinsJt
        )
        for i in range(1, len(jetBinBorders))
    ]

    hReco2DProj = makeHist(hReco2D.ProjectionX("histReco"), bins=LogBinsJt)
    hReco2DProj.Scale(1.0 / numberJets, "width")
    for h, h2, n in zip(hReco2DProjBin, hReco2DTestProjBin, numberJetsFromReco):
        if n > 0:
            h.Scale(1.0 / n, "width")
            h2.Scale(1.0 / n, "width")
    # unfold.PrintTable (cout, hJtTrue)
    for h, h2, nj in zip(hJtMeasProjBin, hJtFakeProjBin, numberJetsMeasBin):
        if nj > 0:
            h.Scale(1.0 / nj, "width")
            h2.Scale(1.0 / nj, "width")
        # else:
        #    print("nj is 0 for {}".format(h.GetName()))
    for h, nj in zip(hJtTrueProjBin, numberJetsTrueBin):
        if nj > 0:
            h.Scale(1.0 / nj, "width")

    # draw8grid(hJtMeasBin[1:],hJtTrueBin[1:],jetPtBins[1:],xlog = True,ylog = True,name="newfile.pdf",proj = hJtMeasProjBin[2:], unf2d = hReco2DProjBin[2:], unf=hRecoBin[1:])
    if numberEvents > 1000:
        if numberEvents > 1000000:
            filename = "ToyMC_{}M_events.pdf".format(numberEvents / 1000000)
        else:
            filename = "ToyMC_{}k_events.pdf".format(numberEvents / 1000)
    else:
        filename = "ToyMC_{}_events.pdf".format(numberEvents)
    draw8gridcomparison(
        hJtMeasBin,
        hJtTrueBin,
        jetPtBins,
        xlog=True,
        ylog=True,
        name=filename,
        proj=None,
        unf2d=hReco2DProjBin,
        unf2dtest=hReco2DTestProjBin,
        unf=hRecoBin,
        fake=hJtFakeProjBin,
        start=1,
        stride=1,
    )
    drawQA(
        hJtMeas,
        hJtTrue,
        hJtFake,
        hRecoBayes,
        hRecoSVD,
        hReco2DProj,
        hZ,
        hZTrue,
        hZMeas,
        hZFake,
        hMultiMeas,
        hMultiTrue,
        hJetPt,
        hJetPtTrue,
        hJetPtMeas,
        hRecoJetPt,
        responseMatrix,
    )
    outFile.Close()