示例#1
0
int main() {
    const double PDGLbMass=5619.51;
    const double RareUpperBlind=PDGLbMass+125.0;
    const double RareLowerBlind=PDGLbMass-125.0;
    const double Rare2UpperBlind=PDGLbMass+175.0;
    const double Rare2LowerBlind=PDGLbMass-175.0;
    bool blind=true;
    bool remakecc=false;
    bool remakerare=false;
    bool remakerare2=false;
    bool sweight=false;
    TRandom3* MultiCandRand=new TRandom3(224); //dont change seed
    TH1I* ControlChannelMultiCands= new TH1I("ControlChannelMultiCands","ControlChannelMultiCands",10,0,10);
    TH1I* RareChannelMultiCands= new TH1I("RareChannelMultiCands","RareChannelMultiCands",10,0,10);
    TH1I* Rare2ChannelMultiCands= new TH1I("RareChannel2MultiCands","RareChannel2MultiCands",10,0,10);

    //_______________________________________ MAKE CONTROL CHANNEL ROODATASET______________________________________
    if(remakecc) {
        std::string ControlDataPath=std::getenv("BUKETAPDATABDTRESPROOT");
        DataFile CC12A(ControlDataPath,Data,Twel,MagAll,buketap,"BDTApplied_SampleA");
        DataFile CC12B(ControlDataPath,Data,Twel,MagAll,buketap,"BDTApplied_SampleB");
        DataFile CC11A(ControlDataPath,Data,Elev,MagAll,buketap,"BDTApplied_SampleA");
        DataFile CC11B(ControlDataPath,Data,Elev,MagAll,buketap,"BDTApplied_SampleB");

        TreeReader* CC12Reader= new TreeReader("DecayTree");
        CC12Reader->AddFile(CC12A);
        CC12Reader->AddFile(CC12B);
        CC12Reader->Initialize(ControlCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalCC12.root","RECREATE");
        TTree* Minimal12Tree=CC12Reader->CopyTree(ControlCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,ControlChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* CC11Reader= new TreeReader("DecayTree");
        CC11Reader->AddFile(CC11A);
        CC11Reader->AddFile(CC11B);
        CC11Reader->Initialize(ControlCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalCC11.root","RECREATE");
        TTree* Minimal11Tree=CC11Reader->CopyTree(ControlCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,ControlChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalCC12.root");
        FlaggedReader->AddFile("MinimalCC11.root");
        FlaggedReader->Initialize();
        TFile* CCSingleFile= new TFile("CCSingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        CCSingleFile->Close();
    }

    //_____________________________________Make Rare Mode One Data__________________________________________________
    if(remakerare) {
        std::string RareDataPath=std::getenv("LBPKETAPPIPIGDATABDTRESPROOT");
        DataFile Rare12A(RareDataPath,Data,Twel,MagAll,lbpketappipig,"BDTApplied_SampleA_NB");
        DataFile Rare12B(RareDataPath,Data,Twel,MagAll,lbpketappipig,"BDTApplied_SampleB_NB");
        DataFile Rare11A(RareDataPath,Data,Elev,MagAll,lbpketappipig,"BDTApplied_SampleA_NB");
        DataFile Rare11B(RareDataPath,Data,Elev,MagAll,lbpketappipig,"BDTApplied_SampleB_NB");

        TreeReader* Rare12Reader= new TreeReader("DecayTree");
        Rare12Reader->AddFile(Rare12A);
        Rare12Reader->AddFile(Rare12B);
        Rare12Reader->Initialize(pipigCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalRare12.root","RECREATE");
        TTree* Minimal12Tree=Rare12Reader->CopyTree(pipigCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,RareChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* Rare11Reader= new TreeReader("DecayTree");
        Rare11Reader->AddFile(Rare11A);
        Rare11Reader->AddFile(Rare11B);
        Rare11Reader->Initialize(pipigCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalRare11.root","RECREATE");
        TTree* Minimal11Tree=Rare11Reader->CopyTree(pipigCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,RareChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalRare12.root");
        FlaggedReader->AddFile("MinimalRare11.root");
        FlaggedReader->Initialize();
        TFile* RareSingleFile= new TFile("RareSingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        RareSingleFile->Close();

    }
    //___________________________________ Make Rare mode Two Data________________________________________________
    if(remakerare2) {
        std::string Rare2DataPath=std::getenv("LBPKETAPETADATABDTRESPROOT");
        DataFile Rare212A(Rare2DataPath,Data,Twel,MagAll,lbpketapeta,"BDTApplied_SampleA_NB");
        DataFile Rare212B(Rare2DataPath,Data,Twel,MagAll,lbpketapeta,"BDTApplied_SampleB_NB");
        DataFile Rare211A(Rare2DataPath,Data,Elev,MagAll,lbpketapeta,"BDTApplied_SampleA_NB");
        DataFile Rare211B(Rare2DataPath,Data,Elev,MagAll,lbpketapeta,"BDTApplied_SampleB_NB");

        TreeReader* Rare212Reader= new TreeReader("DecayTree");
        Rare212Reader->AddFile(Rare212A);
        Rare212Reader->AddFile(Rare212B);
        Rare212Reader->Initialize(etapetaCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalRare212.root","RECREATE");
        TTree* Minimal12Tree=Rare212Reader->CopyTree(etapetaCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,Rare2ChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* Rare211Reader= new TreeReader("DecayTree");
        Rare211Reader->AddFile(Rare211A);
        Rare211Reader->AddFile(Rare211B);
        Rare211Reader->Initialize(etapetaCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalRare211.root","RECREATE");
        TTree* Minimal11Tree=Rare211Reader->CopyTree(etapetaCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,Rare2ChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalRare212.root");
        FlaggedReader->AddFile("MinimalRare211.root");
        FlaggedReader->Initialize();
        TFile* Rare2SingleFile= new TFile("Rare2SingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        Rare2SingleFile->Close();
    }
    //____________________________________ Shared Parameters_______________________________________________________

    RooRealVar DataMCRatio("DataMCRatio","DataMCRatio",1.0,0.5,1.5);
    RooRealVar CCMean("CCMean","CCMean",5279.0,5250.0,5310.0);
    RooFormulaVar LambdabMean("LambdabMean","LambdabMean","@0+339.72",RooArgList(CCMean));
    //RooRealVar LambdabMean("LambdabMean","LambdabMean",5619.0,5615.0,5630.0);
    // RooFormulaVar CCMean("CCMean","CCMean","@0 - 339.72",RooArgList(LambdabMean));

    std::vector<RooRealVar*> FreeParameters;
    FreeParameters.push_back(&DataMCRatio);
    //  FreeParameters.push_back(&LambdabMean);

    //____________________________________ Control Channel PDF______________________________________________________

    TFile* CCInputFile = new TFile("CCSingleFile.root");
    TTree* CCInputTree=(TTree*)CCInputFile->Get("DecayTree");
    RooRealVar CCBMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5550.0);
    RooRealVar CCEtaMass("eta_prime_MM","eta_prime_MM",880.0,1040.0);
    RooArgSet CCArgs(CCBMass,CCEtaMass);
    RooDataSet* CCData=new RooDataSet("CCData","CCData",CCArgs,Import(*CCInputTree));


    //++++++++++++++++++++++++++++++Signal PDF+++++++++++++++++++++++++++++++++


    TFile *CCMCFitResultFile = new TFile("CCFitResult.root");
    RooFitResult* CCMCFitResult=NULL;
    try {
        CCMCFitResult=SafeGetFitResult(CCMCFitResultFile,"CCFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    CCMCFitResult->Print("v");
    RooRealVar* CCMCSigma=NULL;
    RooRealVar* CCMCLAlphaFix=NULL;
    RooRealVar* CCMCRAlphaFix=NULL;
    RooRealVar* CCMCLNFix=NULL;
    RooRealVar* CCMCRNFix=NULL;

    try {
        CCMCSigma=SafeGetVar(CCMCFitResult,"CCSigma");
        CCMCLAlphaFix=SafeGetVar(CCMCFitResult,"CCLAlpha");
        CCMCRAlphaFix=SafeGetVar(CCMCFitResult,"CCRAlpha");
        CCMCLNFix=SafeGetVar(CCMCFitResult,"CCLN");
        CCMCRNFix=SafeGetVar(CCMCFitResult,"CCRN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar CCMCSigmaFix("CCMCSigmaFix","CCMCSigmaFix",CCMCSigma->getVal());
    CCMCSigmaFix.setConstant(kTRUE);
    RooFormulaVar CCSigma("CCSigma","CCSigma","@0*@1",RooArgList(DataMCRatio,CCMCSigmaFix));

    RooRealVar CCLAlpha("CCLAlpha","CCLAlpha",CCMCLAlphaFix->getVal());

    RooRealVar CCRAlpha("CCRAlpha","CCRAlpha",CCMCRAlphaFix->getVal());

    RooRealVar CCLN("CCLN","CCLN",CCMCLNFix->getVal());

    RooRealVar CCRN("CCRN","CCRN",CCMCRNFix->getVal());

    RooCBShape CCDCBLeft("CCDCBLeft","CCDCBLeft",CCBMass,CCMean,CCSigma,CCLAlpha,CCLN);

    RooCBShape CCDCBRight("CCDCBRight","CCDCBRight",CCBMass,CCMean,CCSigma,CCRAlpha,CCRN);

    RooRealVar CCFitFraction("CCFitFraction","CCFitFraction",0.5,0.0,1.0);
    FreeParameters.push_back(&CCFitFraction);
    RooAddPdf CCDCB("CCDCB","CCDCB",RooArgList(CCDCBRight,CCDCBLeft),CCFitFraction);

    RooRealVar CCEtamean("CCEtamean","CCEtamean",958.0,955.0,960.0);
    RooRealVar CCEtasigma("CCEtasigma","CCEtasigma",9.16,9.0,15.0);

    RooRealVar* CCMCEtaLAlpha=NULL;
    RooRealVar* CCMCEtaRAlpha=NULL;
    RooRealVar* CCMCEtaLN=NULL;
    RooRealVar* CCMCEtaRN=NULL;

    try {
        CCMCEtaLAlpha=SafeGetVar(CCMCFitResult,"CCEtaLAlpha");
        CCMCEtaRAlpha=SafeGetVar(CCMCFitResult,"CCEtaRAlpha");
        CCMCEtaLN=SafeGetVar(CCMCFitResult,"CCEtaLN");
        CCMCEtaRN=SafeGetVar(CCMCFitResult,"CCEtaRN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar CCEtaLAlpha("CCEtaLAlpha","CCEtaLAlpha",CCMCEtaLAlpha->getVal());

    RooRealVar CCEtaRAlpha("CCEtaRAlpha","CCEtaRAlpha",CCMCEtaRAlpha->getVal());

    RooRealVar CCEtaLN("CCEtaLN","CCEtaLN",CCMCEtaLN->getVal());

    RooRealVar CCEtaRN("CCEtaRN","CCEtaRN",CCMCEtaRN->getVal());

    RooCBShape CCEtaDCBLeft("CCEtaCBLeft","CCEtaCBLeft",CCEtaMass,CCEtamean,CCEtasigma,CCEtaLAlpha,CCEtaLN);

    RooCBShape CCEtaDCBRight("CCEtaCBRight","CCEtaCBRight",CCEtaMass,CCEtamean,CCEtasigma,CCEtaRAlpha,CCEtaRN);

    RooRealVar CCEtaFitFraction("CCEtaFitFraction","CCEtaFitFraction",0.22,0.1,1.0);
    FreeParameters.push_back(&CCEtaFitFraction);

    RooAddPdf CCEtaDCB("CCEteaDCB","CCEtaDCB",RooArgList(CCEtaDCBRight,CCEtaDCBLeft),CCEtaFitFraction);

    RooProdPdf CCSignalPdf("CCSignalPdf","CCSignalPdf",RooArgSet(CCEtaDCB,CCDCB));
    RooRealVar CCSignalYield("CCSignalYield","CCSignalYield",10000.0,1000.0,20000.0);

    RooExtendPdf CCExtendedSignalPdf("CCExtendedSignalPdf","CCExtendedSignalPdf",CCSignalPdf,CCSignalYield);

    //+++++++++++++++++++++++++++++++++ COMB NO ETAP PDF++++++++++++++++++++++++++++++++++++++++

    RooRealVar CCNoEtaBSlope("CCNoEtaBSlope","CCNoEtaBSlope",-0.6,-0.8,-0.4);
    FreeParameters.push_back(&CCNoEtaBSlope);

    RooRealVar CCNoEtaBCurve("CCNoEtaBCurve","CCNoEtaBCurve",-0.1,-0.30,-0.05);
    FreeParameters.push_back(&CCNoEtaBCurve);

    RooChebychev CCNoEtaBLine("CCNoEtaBLine","CCNoEtaBLine",CCBMass,RooArgList(CCNoEtaBSlope,CCNoEtaBCurve));

    RooRealVar CCNoEtaEtaP1("CCNoEtaEtaP1","CCNoEtaEtaP1",-0.1,-1.0,0.0);
    FreeParameters.push_back(&CCNoEtaEtaP1);

    RooRealVar CCNoEtaEtaP2("CCNoEtaEtaP2","CCNoEtaEtaP2",-0.1,-0.8,0.0);
    FreeParameters.push_back(&CCNoEtaEtaP2);

    RooChebychev CCNoEtaQuad("CCNoEtaQuad","CCNoEtaQuad",CCEtaMass,RooArgList(CCNoEtaEtaP1,CCNoEtaEtaP2));

    RooProdPdf CCNoEtaBkgPdf("CCNoEtaBkgPdf","CCNoEtaBkgPdf",RooArgSet(CCNoEtaQuad,CCNoEtaBLine));
    RooRealVar CCNoEtaBkgYield("CCNoEtaBkgYield","CCNoEtaBkgYield",2400.0,500.0,15000.0);

    RooExtendPdf ExtCCNoEtaBkgPdf("ExtCCNoEtaBkgPdf","ExtCCNoEtaBkgPdf",CCNoEtaBkgPdf,CCNoEtaBkgYield);


    //++++++++++++++++++++++++++++++++++ COMB TRUE ETAP PDF++++++++++++++++++++++++++++++++++

    RooRealVar CCTrueEtaBSlope("CCTrueEtaBSlope","CCTrueEtaBSlope",-0.1,-1.0,0.0);
    FreeParameters.push_back(&CCTrueEtaBSlope);

    RooChebychev CCTrueEtaBLine("CCTrueEtaBLine","CCTrueEtaBLine",CCBMass,RooArgList(CCTrueEtaBSlope));

    RooRealVar CCTrueEtaEtaLAlpha("CCTrueEtaEtaLAlpha","CCTrueEtaEtaLAlpha",CCMCEtaLAlpha->getVal());
    RooRealVar CCTrueEtaEtaRAlpha("CCTrueEtaEtaRAlpha","CCTrueEtaEtaRAlpha",CCMCEtaRAlpha->getVal());
    RooRealVar CCTrueEtaEtaLN("CCTrueEtaEtaLN","CCTrueEtaEtaLN",CCMCEtaLN->getVal());
    RooRealVar CCTrueEtaEtaRN("CCTrueEtaEtaRN","CCTrueEtaEtaRN",CCMCEtaRN->getVal());

    //RooCBShape CCTrueEtaEtaCBLeft("CCTrueEtaEtaCBLeft","CCTrueEtaEtaCBLeft",CCEtaMass,CCEtamean,CCEtasigma,CCTrueEtaEtaLAlpha,CCTrueEtaEtaLN);

    RooCBShape CCTrueEtaEtaCBRight("CCTrueEtaEtaCBRight","CCTrueEtaEtaCBRight",CCEtaMass,CCEtamean,CCEtasigma,CCTrueEtaEtaRAlpha,CCTrueEtaEtaRN);

    //  RooRealVar CCTrueEtaEtaFitFraction("CCTrueEtaEtaFitFraction","CCTrueEtaEtaFitFraction",0.4,0.0,1.0);
    //RooAddPdf CCTrueEtaEtaDCB("CCTrueEtaEtaDCB","CCTrueEtaEtaDCB",RooArgList(CCTrueEtaEtaCBRight,CCTrueEtaEtaCBLeft),CCTrueEtaEtaFitFraction);

    RooProdPdf CCTrueEtaEtaBkgPdf("CCTrueEtaEtaBkgPdf","CCTrueEtaEtaBkgPdf",RooArgSet(CCTrueEtaEtaCBRight,CCTrueEtaBLine));

    RooRealVar CCTrueEtaBkgYield("CCTrueEtaBkgYield","CCTrueEtaBkgYield",800.0,20.0,10000.0);

    RooExtendPdf ExtCCTrueEtaBkgPdf("ExtCCTrueEtaBkgPdf","ExtCCTrueEtaBkgPdf",CCTrueEtaEtaBkgPdf,CCTrueEtaBkgYield);

    RooAddPdf CCTotalPdf("CCTotalPdf","CCTotalPdf",RooArgList(ExtCCTrueEtaBkgPdf,ExtCCNoEtaBkgPdf,CCExtendedSignalPdf));



    //_________________________________Rare1 Fit_____________________________

    TFile * RareInputFile = new TFile("RareSingleFile.root");
    TTree* RareInputTree=NULL;
    try {
        RareInputTree=SafeGetTree(RareInputFile,"DecayTree");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar LbMass("Lambda_b0_DTF_MF","Lambda_b0_DTF_MF",5200.0,6000.0);
    RooRealVar RareLambda_b0_PE("Lambda_b0_PE","Lambda_b0_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PX("Lambda_b0_PX","Lambda_b0_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PY("Lambda_b0_PY","Lambda_b0_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PZ("Lambda_b0_PZ","Lambda_b0_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PE("Proton_PE","Proton_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PX("Proton_PX","Proton_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PY("Proton_PY","Proton_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PZ("Proton_PZ","Proton_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PE("Kaon_PE","Kaon_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PX("Kaon_PX","Kaon_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PY("Kaon_PY","Kaon_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PZ("Kaon_PZ","Kaon_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PE("eta_prime_PE","eta_prime_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PX("eta_prime_PX","eta_prime_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PY("eta_prime_PY","eta_prime_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PZ("eta_prime_PZ","eta_prime_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooArgSet RareArgs(LbMass,RareLambda_b0_PE,RareLambda_b0_PX,RareLambda_b0_PY,RareLambda_b0_PZ,RareProton_PE,RareProton_PX,RareProton_PY,RareProton_PZ);
    RareArgs.add(RareKaon_PE);
    RareArgs.add(RareKaon_PX);
    RareArgs.add(RareKaon_PY);
    RareArgs.add(RareKaon_PZ);
    RareArgs.add(Rareeta_prime_PE);
    RareArgs.add(Rareeta_prime_PX);
    RareArgs.add(Rareeta_prime_PY);
    RareArgs.add(Rareeta_prime_PZ);
    RooDataSet* RareData= new RooDataSet("RareData","RareData",RareArgs,Import(*RareInputTree));


    TFile * RareFitResultFile = new TFile("RareFitResult.root");
    RooFitResult* RareMCFitResult=NULL;
    try {
        RareMCFitResult=SafeGetFitResult(RareFitResultFile,"RareFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RareMCFitResult->Print("v");
    RooRealVar* RareMCRAlpha=NULL;
    RooRealVar* RareMCFitFraction=NULL;
    RooRealVar* RareMCLAlpha=NULL;
    RooRealVar* RareMCLN=NULL;
    RooRealVar* RareMCRN=NULL;
    RooRealVar* RareMCSigma=NULL;
    try {
        RareMCRAlpha=SafeGetVar(RareMCFitResult,"RareAlpha");
        RareMCFitFraction=SafeGetVar(RareMCFitResult,"RareFitFraction");
        RareMCLAlpha=SafeGetVar(RareMCFitResult,"RareLAlpha");
        RareMCLN=SafeGetVar(RareMCFitResult,"RareLN");
        RareMCRN=SafeGetVar(RareMCFitResult,"RareRN");
        RareMCSigma=SafeGetVar(RareMCFitResult,"RareSigma");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    //++++++++++++++++++++++++++++++Rare Signal PDF++++++++++++++++++++++++++++
    RooRealVar RareMCSigmaFix("RareMCSigmaFix","RareMCSigmaFix",RareMCSigma->getVal());
    RareMCSigmaFix.setConstant();

    RooFormulaVar RareSigma("RareSigma","RareSigma","@0*@1",RooArgSet(RareMCSigmaFix,DataMCRatio));
    RooRealVar RareLAlpha("RareLAlpha","RareLAlpha",RareMCLAlpha->getVal());
    RooRealVar RareRAlpha("RareRAlpha","RareRAlpha",RareMCRAlpha->getVal());
    RooRealVar RareRN("RareRN","RareRN",RareMCRN->getVal());
    RooRealVar RareLN("RareLN","RareLN",RareMCLN->getVal());
    RooRealVar RareFitFraction("RareFitFraction","RareFitFraction",RareMCFitFraction->getVal());

    RooCBShape RareDCBLeft("DCBLeft","DCBLeft",LbMass,LambdabMean,RareSigma,RareLAlpha,RareLN);

    RooCBShape RareDCBRight("DCBRight","DCBRight",LbMass,LambdabMean,RareSigma,RareRAlpha,RareRN);

    RooAddPdf RareDCB("RareDCB","RareDCB",RooArgList(RareDCBLeft,RareDCBRight),RareFitFraction);

    RooRealVar RareYield("RareYield","RareYield",40.0,-100.0,1000.0);
    RooExtendPdf RareSignalPdf("RareSignalPdf","RareSignalPdf",RareDCB,RareYield);
    //++++++++++++++++++++++++++++++Rare Combinatorial Bkg+++++++++++++++++++++++++++++++++++
    RooRealVar Rarep1("Rarep1","Rarep1",-1.1,-5.0,-0.1);
    FreeParameters.push_back(&Rarep1);

    RooRealVar Rarep2("Rarep2","Rarep2",0.5,0.001,10.0);
    FreeParameters.push_back(&Rarep2);

    RooChebychev RarePoly("RarePoly","RarePoly",LbMass,RooArgList(Rarep1,Rarep2));

    RooRealVar RareBkgYield("RareBkgYield","RareBkgYield",2000.0,0.0,10000.0);
    RooExtendPdf RareBkgPdf("RareBkgPdf","RareBkgPdf",RarePoly,RareBkgYield);

    //++++++++++++++++++++++++++++Rare PKPhi Bkg+++++++++++++++++++++++++++++++++
    TFile* PKPhiMCFitresultFile= new TFile("PkPhiFitResultFile.root");
    RooFitResult* PKPhiMCFitResult=NULL;
    try {
        PKPhiMCFitResult=SafeGetFitResult(PKPhiMCFitresultFile,"PkPhiFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    PKPhiMCFitResult->Print("v");
    RooRealVar* PkPhiMean=NULL;
    RooRealVar* PkPhiSigma=NULL;
    RooRealVar* PkPhiLAlpha=NULL;
    RooRealVar* PkPhiRAlpha=NULL;
    RooRealVar* PkPhiLN=NULL;
    RooRealVar* PkPhiRN=NULL;
    try {
        PkPhiMean=SafeGetVar(PKPhiMCFitResult,"PkPhiMean");
        PkPhiSigma=SafeGetVar(PKPhiMCFitResult,"PkPhiSigma");
        PkPhiLAlpha=SafeGetVar(PKPhiMCFitResult,"PkPhiLAlpha");
        PkPhiLN=SafeGetVar(PKPhiMCFitResult,"PkPhiLN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    RooRealVar RarePkPhiMean("RarePkPhiMean","RarePkPhiMean",PkPhiMean->getVal());
    RooRealVar RarePkPhiSigma("RarePkPhiSigma","RarePkPhiSigma",PkPhiSigma->getVal());
    RooRealVar RarePkPhiLN("RarePkPhiLN","RarePkPhiLN",PkPhiLN->getVal());
    RooRealVar RarePkPhiLAlpha("RarePkPhiLAlpha","RarePkPhiLAlpha",PkPhiLAlpha->getVal());

    RooCBShape RarePkPhiModel("RarePkPhiModel","RarePkPhiModel",LbMass,RarePkPhiMean,RarePkPhiSigma,RarePkPhiLAlpha,RarePkPhiLN);

    RooRealVar RarePkPhiYield("RarePkPhiYield","RarePkPhiYield",50.0,1.0,150.0);
    RooExtendPdf RarePkPhiPdf("RarePkPhiPdf","RarePkPhiPdf",RarePkPhiModel,RarePkPhiYield);

    RooAddPdf RarePdf("RarePdf","RarePdf",RooArgList(RarePkPhiPdf,RareBkgPdf,RareSignalPdf));

    /*RarePdf.fitTo(*RareData,Extended(kTRUE));
    RooPlot* RareFrame=LbMass.frame(Bins(35),Range(5200.0,6100.0));
    TCanvas RareCanvas;
    RareData->plotOn(RareFrame);
    RarePdf.plotOn(RareFrame);
    RareFrame->Draw();
    RareCanvas.SaveAs("RareCanvas.pdf");*/

    //________________________________ Fit Rare 2_______________________________
    TFile* Rare2InputFile = new TFile("Rare2SingleFile.root");
    TTree* Rare2InputTree=NULL;
    try {
        Rare2InputTree=SafeGetTree(Rare2InputFile,"DecayTree");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar Rare2Lambda_b0_PE("Lambda_b0_PE","Lambda_b0_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PX("Lambda_b0_PX","Lambda_b0_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PY("Lambda_b0_PY","Lambda_b0_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PZ("Lambda_b0_PZ","Lambda_b0_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PE("Proton_PE","Proton_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PX("Proton_PX","Proton_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PY("Proton_PY","Proton_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PZ("Proton_PZ","Proton_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PE("Kaon_PE","Kaon_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PX("Kaon_PX","Kaon_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PY("Kaon_PY","Kaon_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PZ("Kaon_PZ","Kaon_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PE("eta_prime_PE","eta_prime_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PX("eta_prime_PX","eta_prime_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PY("eta_prime_PY","eta_prime_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PZ("eta_prime_PZ","eta_prime_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooArgSet Rare2Args(LbMass,Rare2Lambda_b0_PE,Rare2Lambda_b0_PX,Rare2Lambda_b0_PY,Rare2Lambda_b0_PZ,Rare2Proton_PE,Rare2Proton_PX,Rare2Proton_PY,Rare2Proton_PZ);
    Rare2Args.add(Rare2Kaon_PE);
    Rare2Args.add(Rare2Kaon_PX);
    Rare2Args.add(Rare2Kaon_PY);
    Rare2Args.add(Rare2Kaon_PZ);
    Rare2Args.add(Rare2eta_prime_PE);
    Rare2Args.add(Rare2eta_prime_PX);
    Rare2Args.add(Rare2eta_prime_PY);
    Rare2Args.add(Rare2eta_prime_PZ);

    RooDataSet* Rare2Data=new RooDataSet("Rare2Data","Rare2Data",Rare2Args,Import(*Rare2InputTree));

    TFile* Rare2MCFitResultFile= new TFile("RareTwoFitResult.root");
    RooFitResult* Rare2MCFitResult=NULL;
    try {
        Rare2MCFitResult=SafeGetFitResult(Rare2MCFitResultFile,"RareTwoFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    //++++++++++++++++++++++++++++++Signal PDF++++++++++++++++++++++++++++++++
    RooRealVar* Rare2MCFitFraction=NULL;
    RooRealVar* Rare2MCLAlpha=NULL;
    RooRealVar* Rare2MCLN=NULL;
    RooRealVar* Rare2MCRN=NULL;
    RooRealVar* Rare2MCRAlpha=NULL;
    RooRealVar* Rare2MCSigma=NULL;

    try {
        Rare2MCFitFraction=SafeGetVar(Rare2MCFitResult,"Rare2FitFraction");
        Rare2MCLAlpha=SafeGetVar(Rare2MCFitResult,"Rare2LAlpha");
        Rare2MCLN=SafeGetVar(Rare2MCFitResult,"Rare2LN");
        Rare2MCRN=SafeGetVar(Rare2MCFitResult,"Rare2RN");
        Rare2MCRAlpha=SafeGetVar(Rare2MCFitResult,"Rare2RAlpha");
        Rare2MCSigma=SafeGetVar(Rare2MCFitResult,"Rare2Sigma");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    RooRealVar Rare2SigmaFix("Rare2SigmaFix","Rare2SigmaFix",Rare2MCSigma->getVal());
    RooFormulaVar Rare2Sigma("Rare2Sigma","Rare2Sigma","@0*@1",RooArgList(Rare2SigmaFix,DataMCRatio));

    RooRealVar Rare2LN("Rare2LN","Rare2LN",Rare2MCLN->getVal());
    RooRealVar Rare2RN("Rare2RN","Rare2RN",Rare2MCRN->getVal());
    RooRealVar Rare2RAlpha("Rare2RAlpha","Rare2RAlpha",Rare2MCRAlpha->getVal());
    RooRealVar Rare2LAlpha("Rare2LAlpha","Rare2LAlpha",Rare2MCLAlpha->getVal());
    RooRealVar Rare2FitFraction("Rare2FitFraction","Rare2FitFraction",Rare2MCFitFraction->getVal());

    RooCBShape Rare2CBLeft("Rare2CBLeft","Rare2CBLeft",LbMass,LambdabMean,Rare2Sigma,Rare2LAlpha,Rare2LN);

    RooCBShape Rare2CBRight("Rare2CBRight","Rare2CBRight",LbMass,LambdabMean,Rare2Sigma,Rare2RAlpha,Rare2RN);

    RooAddPdf Rare2DCB("Rare2DCB","Rare2DCB",RooArgList(Rare2CBLeft,Rare2CBRight),Rare2FitFraction);

    RooRealVar Rare2SignalYield("Rare2SignalYield","Rare2SignalYield",100.0,-100.0,1000.0);
    RooExtendPdf Rare2SignalPdf("Rare2SignalPdf","Rare2SignalPdf",Rare2DCB,Rare2SignalYield);

    //++++++++++++++++++++++++++++++Rare 2 Bkg pdf++++++++++++++++++++++++++++++
    RooRealVar Rare2K("K","K",-0.003,-0.1,0.0);
    RooExponential Rare2BkgExp("Rare2BkgExp","Rare2BkgExp",LbMass,Rare2K);
    RooRealVar Rare2BkgYield("Rare2BkgYield","Rare2BkgYield",2000.0,0.0,100000.0);
    RooExtendPdf Rare2BkgPdf("Rare2BkgPdf","Rare2BkgPdf",Rare2BkgExp,Rare2BkgYield);

    RooAddPdf Rare2Pdf("Rare2Pdf","Rare2Pdf",RooArgList(Rare2SignalPdf,Rare2BkgPdf));

    //___________________________________ SImultaneous Part ________________________________________________________

    RooCategory Channel("Channel","Channel");
    Channel.defineType("Rare");
    Channel.defineType("Rare2");
    Channel.defineType("Control");

    RooDataSet* AllData = new RooDataSet("AllData","AllData",RooArgSet(LbMass,CCBMass,CCEtaMass),Index(Channel),Import("Rare",*RareData),Import("Rare2",*Rare2Data),Import("Control",*CCData));

    RooSimultaneous SimPdf("SimPdf","SimPdf",Channel);
    SimPdf.addPdf(Rare2Pdf,"Rare2");
    SimPdf.addPdf(RarePdf,"Rare");
    SimPdf.addPdf(CCTotalPdf,"Control");

    RooDataSet* BlindedData=NULL;
    RooFitResult* SimResult=NULL;
    if(blind) {
        LbMass.setRange("RLSB",5200.0,RareLowerBlind);
        LbMass.setRange("RUSB",RareUpperBlind,6000.0);
        LbMass.setRange("R2LSB",5200.0,Rare2LowerBlind);
        LbMass.setRange("R2USB",Rare2UpperBlind,6000.0);
        LbMass.setRange("RDLSB",5200.0,5493.33333);
        LbMass.setRange("RDUSB",RareUpperBlind,6000.0);

        std::string CutString="Lambda_b0_DTF_MF<"+std::to_string(RareLowerBlind)+"||Lambda_b0_DTF_MF>"+std::to_string(Rare2UpperBlind);
        BlindedData=(RooDataSet*)AllData->reduce(CutString.data());
        RooMsgService::instance().setSilentMode(kTRUE);
        RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL) ;
    }

    RooArgSet MinosPars(Rare2SignalYield,RareYield,CCSignalYield);
    SimResult = SimPdf.fitTo(*AllData,Save(kTRUE),Extended(kTRUE),Minos(MinosPars));
    SimPdf.Print("v");
    RooPlot* NominalLikelihoodRareYield=RareYield.frame(Title("Likelihood scan of RareYield"),Range(50,150));
    RooAbsReal* nll = SimPdf.createNLL(*AllData,NumCPU(2),Extended(kTRUE));
    TCanvas C;
    nll->plotOn(NominalLikelihoodRareYield,ShiftToZero());
    NominalLikelihoodRareYield->Draw();
    C.SaveAs("NominalLikelihood.pdf");
    //  HandyFunctions::SetlhcbStyle();
    //_______________________________ Plot B+ Canvas_____________________________________________________________
    RooPlot* CCBFrame= CCBMass.frame(Bins(50),Range(5000.0,5500.0),Title("Control Channel B+ Mass Projection"));
    AllData->plotOn(CCBFrame,Cut("Channel==Channel::Control"));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("ExtCCTrueEtaBkgPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("ExtCCNoEtaBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("CCExtendedSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),ProjWData(Channel,*AllData));
    TCanvas* CCBCanvas=HandyFunctions::DecoratePlot(CCBFrame);
    /*(TCanvas* CCBCanvas= new TCanvas("CCBCanvas","CCBCanvas",1600,900);
    CCBFrame->Draw();
    CCBCanvas->SaveAs("CCBCanvas.eps");*/

    //________________________________Plot Eta Canvas_____________________________________________________________
    RooPlot* CCEtaFrame=CCEtaMass.frame(Bins(50),Range(880.0,1040.0),Title("Control Channel Eta' Projection"));
    AllData->plotOn(CCEtaFrame,Cut("Channel==Channel::Control"));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("ExtCCTrueEtaBkgPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("ExtCCNoEtaBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("CCExtendedSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),ProjWData(Channel,*AllData));
    TCanvas* CCEtaCanvas=HandyFunctions::DecoratePlot(CCEtaFrame);
    /*TCanvas* CCEtaCanvas=new TCanvas("CCEtaCanvas","CCEtaCanvas",1600,900);
    CCEtaFrame->Draw();
    CCEtaCanvas->Print("CCEtaCanvas.eps");*/


    //________________________________Plot Rare Canvas_____________________________________________________________
    RooPlot* RareFrame=LbMass.frame(Bins(30),Range(5200.0,6000.0),Title("#Lambda_{b} -> p K (#eta' -> #pi #pi #gamma) ;M(#Lambda_{b})"));
    if(blind) {
        double sidebandsN = RareData ->sumEntries("1","RLSB,RUSB");
        double LowsidebandsN = RareData ->sumEntries("1","RLSB");
        RareData->plotOn(RareFrame,CutRange("RDLSB,RDUSB"),Name("RareDataPlotted"));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Components("RarePkPhiPdf"),Name("RarePkPhiBkg"),LineColor(kMagenta),LineStyle(kDashed),Normalization(sidebandsN,RooAbsReal::NumEvent));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Components("RareBkgPdf"),Name("RareCombBkg"),LineColor(kGreen),LineStyle(kDashed),Normalization(sidebandsN,RooAbsReal::NumEvent));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Normalization(sidebandsN,RooAbsReal::NumEvent));
    } else {
        AllData->plotOn(RareFrame,Cut("Channel==Channel::Rare"));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RarePkPhiPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RareBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RareSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),ProjWData(Channel,*AllData));
    }
    int i=RareFrame->numItems();
    std::cout<<"_________________________________________"<<std::endl;
    for(int j=0; j<i; j++) {
        std::cout<<RareFrame->nameOf(j)<<std::endl;
    }
    TLegend * RareLegend = new TLegend(0.66,0.7,0.9,0.9);
    RareLegend->AddEntry(RareFrame->findObject("RarePkPhiBkg"),"#Lambda_{b} -> p K #phi bkg","l");
    RareLegend->AddEntry(RareFrame->findObject("RareCombBkg"),"Combinatorial Background","l");
    std::cout<<"++++++++++++++++++++++++++++++++++++++++++++"<<std::endl;
    RooHist* Pulls=RareFrame->pullHist(0,"RarePdf_Norm[Lambda_b0_DTF_MF]");
    TCanvas* RareCanvas=HandyFunctions::DecoratePlot(RareFrame,"DecoratedRareCanvas");
    RareCanvas->Print("RareCanvas.pdf");
    TCanvas * PullCanvas=new TCanvas("RarePullCanvas","RarePullCanvas",1200,1000);
    Pulls->Draw("AP");
    PullCanvas->SaveAs("RarePulls.pdf");
    TCanvas *RareNoPullCanvas = new TCanvas("RareFitCanvas","RareFitCanvas",1600,900);
    RareFrame->Draw();
    RareLegend->Draw();
    RareNoPullCanvas->Print("RareNoPullCanvasPrinted.eps");


    //_______________________________Plot Rare2 Canvas_____________________________________________________________
    RooPlot* Rare2Frame=LbMass.frame(Bins(25),Range(5200.0,6000.),Title("#Lambda_{b} -> p K (#eta' -> #pi #pi #eta);M(#Lambda_{b})"));
    if(blind) {
        double Rare2sidebandsN= Rare2Data->sumEntries("1","R2LSB,R2USB");
        Rare2Data->plotOn(Rare2Frame,CutRange("R2LSB,R2USB"));
        Rare2Pdf.plotOn(Rare2Frame,Range("R2LSB,R2USB"),Normalization(Rare2sidebandsN,RooAbsReal::NumEvent));
    } else {
        AllData->plotOn(Rare2Frame,Cut("Channel==Channel::Rare2"));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),Components("Rare2BkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),Components("Rare2SignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),ProjWData(Channel,*AllData));
    }
    TCanvas* NoPullRare2= new TCanvas("NoPullRare2","NoPullRare2",1800,1000);
    Rare2Frame->Draw();
    NoPullRare2->SaveAs("PiPiEtaFit.eps");
    TCanvas* Rare2Canvas=HandyFunctions::DecoratePlot(Rare2Frame,"DecoratedRare2Canvas");
    Rare2Canvas->SaveAs("Rare2Canvas.pdf");

    if(blind) {
        RooArgSet NotBlind(CCEtamean,CCSignalYield,DataMCRatio,CCNoEtaBkgYield,CCTrueEtaBkgYield,CCMean,RareBkgYield,Rare2BkgYield,RarePkPhiYield);
        cout << "Fit complete" << endl;
        cout << "covQual:" << SimResult->covQual() << endl;
        cout << "EDM:" << SimResult->edm() << endl;
        cout << "FCN at min:" << SimResult->minNll() << endl;
        NotBlind.Print("s");
    }


    TFile* DataFitResults= new TFile("DataFitResults.root","RECREATE");
    RareNoPullCanvas->Write();
    CCBCanvas->Write();
    CCEtaCanvas->Write();
    RareCanvas->Write();
    Rare2Canvas->Write();
    SimResult->Write("DataFitResult");
    DataFitResults->Close();

    RooWorkspace* Wkspc= new RooWorkspace("w","workspace");
    Wkspc->import(SimPdf);
    //  Wkspc->writeToFile("BigFitWorkspace.root");
    Wkspc->writeToFile("TestBigFitWorkspace.root");

    for(auto Var : FreeParameters) {
        Var->setConstant();
    }

    RooStats::SPlot* sDataMass;
    if(sweight) {
        sDataMass = new RooStats::SPlot("sData","An SPlot",*RareData,&RarePdf,RooArgList(RarePkPhiYield,RareYield,RareBkgYield));
        std::cout<<" Check SWeights: "<<std::endl;
        std::cout<<" BkgYield= "<<RareBkgYield.getVal()<<std::endl;
        std::cout<<" Bkg yield from sweights = "<<sDataMass->GetYieldFromSWeight("RareBkgYield")<<std::endl;
    }




}
示例#2
0
void fitWe(const TString  outputDir="test",   // output directory
           const Double_t lumi=18.7,        // integrated luminosity (/fb)
	   const Int_t    Ecm=8,         // center-of-mass energy
	   const Int_t    doPU=1         // option for PU-reweighting
) {
  gBenchmark->Start("fitWe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS  = 50;
  const Double_t METMAX = 100;

  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.5;

  // file format for output plots
  const TString format("png"); 
    
  // file name with recoil correction
  TString recoilfname("../RecoilSyst/ZeeData/fits.root");
  
  // file name(s) with PU weights
  TString pufname("");
  if(doPU>0) {
    if(doPU==1) { pufname = "Utils/PileupReweighting.Summer11DYmm_To_Run2011A.root"; }
    else        { cout << "Invalid option for PU re-weighting! Aborting..." << endl; assert(0); }
  }
  
  //
  // input ntuple file names
  //
  enum { eData, eWenu, eEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("../Selection/Wenu/ntuples/data_m23_select.root");   typev.push_back(eData);
  fnamev.push_back("../Selection/Wenu/ntuples/we_select.root");         typev.push_back(eWenu);
  fnamev.push_back("../Selection/Wenu/ntuples/ewk_select.root");        typev.push_back(eEWK);
  fnamev.push_back("../Selection/Wenu/ntuples/top_select.root");        typev.push_back(eEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  // Get pile-up weights
  TFile *pufile    = 0;
  TH1D  *puWeights = 0;
  if(doPU>0) {
    pufile = new TFile(pufname);
    assert(pufile);
    puWeights = (TH1D*)pufile->Get("puWeights");
    assert(puWeights);
  }
  
  // Access recoil corrections
  //RecoilCorrector recoilCorr(recoilfname);
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet  = new TH1D("hDataMet", "",NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm = new TH1D("hDataMetm","",NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp = new TH1D("hDataMetp","",NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWenuMet  = new TH1D("hWenuMet", "",NBINS,0,METMAX); hWenuMet->Sumw2();
  TH1D *hWenuMetp = new TH1D("hWenuMetp","",NBINS,0,METMAX); hWenuMetp->Sumw2();
  TH1D *hWenuMetm = new TH1D("hWenuMetm","",NBINS,0,METMAX); hWenuMetm->Sumw2();
  TH1D *hEWKMet   = new TH1D("hEWKMet",  "",NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp  = new TH1D("hEWKMetp", "",NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm  = new TH1D("hEWKMetm", "",NBINS,0,METMAX); hEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genWPt, genWPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  LorentzVector *sc=0;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genWPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genWPhi);   // GEN W boson phi (signal MC)
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);         // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("sc",       &sc);        // electron Supercluster 4-vector
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(mt< 40)  continue;	// LUCA ADD
      TLorentzVector muPosP, muNegP, JpsiP;
      muPosP.SetPtEtaPhiM(lep->Pt(),lep->Eta(),lep->Phi(),lep->M()); // always use the muon
      muNegP.SetPtEtaPhiM(met,0,metPhi,0); // always use the neutrino
      JpsiP = muPosP + muNegP;
      
      // if(JpsiP.Pt() < 15 
      // || JpsiP.Pt() > 25 )  continue;	

      
      if(sc->Pt()        < PT_CUT)  continue;	
      if(fabs(sc->Eta()) > ETA_CUT) continue;
   
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
        if(puWeights)
	  weight *= puWeights->GetBinContent(npu+1);
	
	if(typev[ifile]==eWenu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  //recoilCorr.Correct(corrMet,corrMetPhi,genWPt,genWPhi,lep->Pt(),lep->Phi());
	
          hWenuMet->Fill(corrMet,weight);
	  if(q>0) { hWenuMetp->Fill(corrMet,weight); } 
	  else    { hWenuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWenuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWenuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWenuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  
  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wenuMet ("wenuMET", "wenuMET", RooArgSet(pfmet),hWenuMet);  RooHistPdf pdfWe ("we", "we", pfmet,wenuMet, 1);
  RooDataHist wenuMetp("wenuMETp","wenuMETp",RooArgSet(pfmet),hWenuMetp); RooHistPdf pdfWep("wep","wep",pfmet,wenuMetp,1);
  RooDataHist wenuMetm("wenuMETm","wenuMETm",RooArgSet(pfmet),hWenuMetm); RooHistPdf pdfWem("wem","wem",pfmet,wenuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWe,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWep,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWem,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  //
  // Perform fits
  //
  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet),hDataMet);
  RooFitResult *fitRes = pdfMet.fitTo(dataMet,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp","dataMetp",RooArgSet(pfmet),hDataMetp);
  RooFitResult *fitResp = pdfMetp.fitTo(dataMetp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm","dataMetm",RooArgSet(pfmet),hDataMetm);
  RooFitResult *fitResm = pdfMetm.fitTo(dataMetm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.18);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.18);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.400,"Y");
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = %i TeV",lumi*1000.,Ecm);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = %i TeV",lumi,Ecm);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *weframe = pfmet.frame(Bins(NBINS));    
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(weframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(weframe,LineColor(linecolorW));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfWe)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",weframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrowe#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
//  plotMet.Draw(c,kFALSE,format,1);
  plotMet.Draw(c,kTRUE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wepframe = pfmet.frame(Bins(NBINS));    
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wepframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wepframe,LineColor(linecolorW));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfWep)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wepframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrowe^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wemframe = pfmet.frame(Bins(NBINS)); 
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wemframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wemframe,LineColor(linecolorW));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfWem)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wemframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrowe^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWe.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWep.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl;  
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWem.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWe");
}
int scaleSmearTemplateFit_Ele(TString RDFile, TString MCFile, char BaseName[30])
{
  cout<<"Processing "<<BaseName<<endl;
  gStyle->SetPalette(1);
  //Output file
  TString ResultDir = "MCRDfitEle_Plot";
  ofstream Fout;
  TString FoutName=ResultDir+"/"+BaseName+"_SummaryFinal.txt";
  Fout.open(FoutName);
  //Variables
  char histName[50];
  //Data and histograms
  TFile *f_RD = new TFile(RDFile);
  TFile *f_MC = new TFile(MCFile);
  TH1D *h1_ZmassDaughEtaRD[ScElCombiBins];
  TH1D *h1_ZmassDaughEtaMC[ScElCombiBins];

  //Plots
  RooPlot *zmassFrameRD;
  RooPlot *zmassFrameMC;
  CPlot *plotFitRD;
  CPlot *plotFitMC;
  RooFitResult* fitResTotalMC;
  RooFitResult* fitResTotalRD;
  //RooFitResult* fitResRD;
  RooFitResult* fitResMCbw[ScElCombiBins];
  RooFitResult* fitResMC[ScElCombiBins];
  RooFitResult* fitResRD[ScElCombiBins];

  TCanvas *myCan = MakeCanvas("myCan","myCan",800,600);
  //Fitting stuff
  RooRealVar *scaleMC[ScaleBins];
  RooRealVar *scaleRD[ScaleBins];
  RooRealVar *smearRD[ScaleBins];
  RooRealVar *smearMC[ScaleBins];


  RooRealVar *nSRD[ScElCombiBins];
  RooRealVar *nBRD[ScElCombiBins];
  RooRealVar *CBalpha[ScElCombiBins];
  RooRealVar *CBn[ScElCombiBins];

  RooFormulaVar *scaleScaleMC[ScElCombiBins];
  RooFormulaVar *scaleScaleRD[ScElCombiBins];
  RooFormulaVar *smearSmearMC[ScElCombiBins];
  RooFormulaVar *smearSmearRD[ScElCombiBins];

  RooRealVar zMass("zMass","zMass",60,120);
  RooCategory rooCat("rooCat","rooCat");
  RooDataHist *ZmassRD[ScElCombiBins];

// RooDataHist *ZmassMC;
 RooDataHist *ZmassMC[ScElCombiBins];
//  CBreitWigner *BW[ScElCombiBins];
  CBreitWignerConvCrystalBall *BWCB[ScElCombiBins];
  CBreitWignerConvCrystalBallScale *BWCBsCale[ScElCombiBins];
  CBreitWignerMC  *BWMC[ScElCombiBins];
  CBreitWignerRD  *BWRD[ScElCombiBins];

  RooGaussian *gaus[ScElCombiBins];
  RooCBShape *cbMC[ScElCombiBins];
  RooCBShape *cbRD[ScElCombiBins];

  CErfExpo *ZbgRD[ScElCombiBins];

  CExponential *ZbgExpRD[ScElCombiBins];

  RooAbsPdf *pdfRDsig[ScElCombiBins];
  RooAbsPdf *pdfMCsig[ScElCombiBins];
  //RooAddPdf *pdfRDsig[ScElCombiBins];
  RooAbsPdf *histPdf[ScElCombiBins];
  RooAddPdf *pdfRD[ScElCombiBins];


  //Initialization
  for(int i(0);i<ScaleBins;i++)
  {
    sprintf(histName,"scaleMC_%d",i);
    scaleMC[i] = new RooRealVar(histName, histName,1.01,0.001,3);
    sprintf(histName,"scaleRD_%d",i);
    scaleRD[i] = new RooRealVar(histName, histName,1.01,0.001,3);
    sprintf(histName,"smearMC_%d",i);
    smearMC[i] = new RooRealVar(histName,histName,0.5,0.01,3);
    sprintf(histName,"smearRD_%d",i);
    smearRD[i] = new RooRealVar(histName,histName,0.5,0.01,3);
  }

  for(int i(0);i<ScElCombiBins;i++)
  {
    sprintf(histName,"nBRD_%d",i);
    nBRD[i] = new RooRealVar(histName, histName,0.1,0.01,1);
    sprintf(histName,"nSRD_%d",i);
    nSRD[i]= new RooRealVar(histName,histName,1,0,2);
    sprintf(histName,"CBalpha_%d",i); 
    CBalpha[i]= new RooRealVar(histName,histName,5,0,20);
    sprintf(histName,"CBn_%d",i);     
    CBn[i]     = new RooRealVar(histName,histName,1,0,10);

    sprintf(histName,"cat_%d",i);
    rooCat.defineType(histName);
  }

  RooSimultaneous pdfTotalMC("pdfTotalMC","pdfTotalMC",rooCat);
  map<string,TH1*>hmapMC;
  RooSimultaneous pdfTotalRD("pdfTotalRD","pdfTotalRD",rooCat);
  map<string,TH1*>hmapRD;

 
  //*
  ///scaleScale
  sprintf(histName,"scaleScaleMC_0");
  scaleScaleMC[0] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleMC[0],*scaleMC[0]));
  sprintf(histName,"scaleScaleMC_1");
  scaleScaleMC[1] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[0],*scaleMC[1]));
  sprintf(histName,"scaleScaleMC_2");
  scaleScaleMC[2] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[0],*scaleMC[2]));
  sprintf(histName,"scaleScaleMC_3");
  scaleScaleMC[3] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[0],*scaleMC[3]));
  sprintf(histName,"scaleScaleMC_4");
  scaleScaleMC[4] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[0],*scaleMC[4]));
  sprintf(histName,"scaleScaleMC_5");
  scaleScaleMC[5] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[0],*scaleMC[5]));
  sprintf(histName,"scaleScaleMC_6");
  scaleScaleMC[6] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleMC[1],*scaleMC[1]));

  sprintf(histName,"scaleScaleMC_7");
  scaleScaleMC[7] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[1],*scaleMC[2]));
  sprintf(histName,"scaleScaleMC_8");
  scaleScaleMC[8] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[1],*scaleMC[3]));
  sprintf(histName,"scaleScaleMC_9");
  scaleScaleMC[9] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[1],*scaleMC[4]));
  sprintf(histName,"scaleScaleMC_10");
  scaleScaleMC[10] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[1],*scaleMC[5]));
  sprintf(histName,"scaleScaleMC_11");
  scaleScaleMC[11] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleMC[2],*scaleMC[2]));

  sprintf(histName,"scaleScaleMC_12");
  scaleScaleMC[12] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[2],*scaleMC[3]));
  sprintf(histName,"scaleScaleMC_13");
  scaleScaleMC[13] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[2],*scaleMC[4]));
  sprintf(histName,"scaleScaleMC_14");
  scaleScaleMC[14] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[2],*scaleMC[5]));
  sprintf(histName,"scaleScaleMC_15");
  scaleScaleMC[15] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleMC[3],*scaleMC[3]));

  sprintf(histName,"scaleScaleMC_16");
  scaleScaleMC[16] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[3],*scaleMC[4]));
  sprintf(histName,"scaleScaleMC_17");
  scaleScaleMC[17] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[3],*scaleMC[5]));
  sprintf(histName,"scaleScaleMC_18");
  scaleScaleMC[18] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleMC[4],*scaleMC[4]));

  sprintf(histName,"scaleScaleMC_19");
  scaleScaleMC[19] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleMC[4],*scaleMC[5]));
  sprintf(histName,"scaleScaleMC_20");
  scaleScaleMC[20] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleMC[5],*scaleMC[5]));
  //*/


  //*
  ///scaleScale
  sprintf(histName,"scaleScaleRD_0");
  scaleScaleRD[0] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleRD[0],*scaleRD[0]));
  sprintf(histName,"scaleScaleRD_1");
  scaleScaleRD[1] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[0],*scaleRD[1]));
  sprintf(histName,"scaleScaleRD_2");
  scaleScaleRD[2] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[0],*scaleRD[2]));
  sprintf(histName,"scaleScaleRD_3");
  scaleScaleRD[3] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[0],*scaleRD[3]));
  sprintf(histName,"scaleScaleRD_4");
  scaleScaleRD[4] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[0],*scaleRD[4]));
  sprintf(histName,"scaleScaleRD_5");
  scaleScaleRD[5] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[0],*scaleRD[5]));
  sprintf(histName,"scaleScaleRD_6");
  scaleScaleRD[6] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleRD[1],*scaleRD[1]));

  sprintf(histName,"scaleScaleRD_7");
  scaleScaleRD[7] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[1],*scaleRD[2]));
  sprintf(histName,"scaleScaleRD_8");
  scaleScaleRD[8] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[1],*scaleRD[3]));
  sprintf(histName,"scaleScaleRD_9");
  scaleScaleRD[9] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[1],*scaleRD[4]));
  sprintf(histName,"scaleScaleRD_10");
  scaleScaleRD[10] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[1],*scaleRD[5]));
  sprintf(histName,"scaleScaleRD_11");
  scaleScaleRD[11] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleRD[2],*scaleRD[2]));

  sprintf(histName,"scaleScaleRD_12");
  scaleScaleRD[12] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[2],*scaleRD[3]));
  sprintf(histName,"scaleScaleRD_13");
  scaleScaleRD[13] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[2],*scaleRD[4]));
  sprintf(histName,"scaleScaleRD_14");
  scaleScaleRD[14] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[2],*scaleRD[5]));
  sprintf(histName,"scaleScaleRD_15");
  scaleScaleRD[15] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleRD[3],*scaleRD[3]));

  sprintf(histName,"scaleScaleRD_16");
  scaleScaleRD[16] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[3],*scaleRD[4]));
  sprintf(histName,"scaleScaleRD_17");
  scaleScaleRD[17] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[3],*scaleRD[5]));
  sprintf(histName,"scaleScaleRD_18");
  scaleScaleRD[18] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleRD[4],*scaleRD[4]));

  sprintf(histName,"scaleScaleRD_19");
  scaleScaleRD[19] = new RooFormulaVar(histName,"1/sqrt(@0*@1)",RooArgSet(*scaleRD[4],*scaleRD[5]));
  sprintf(histName,"scaleScaleRD_20");
  scaleScaleRD[20] = new RooFormulaVar(histName,"1/sqrt(@0*@0)",RooArgSet(*scaleRD[5],*scaleRD[5]));
//*/


  //*
  ///smearSmear
  sprintf(histName,"smearSmearMC_0");
  smearSmearMC[0] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearMC[0],*smearMC[0]));
  sprintf(histName,"smearSmearMC_1");
  smearSmearMC[1] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[0],*smearMC[1]));
  sprintf(histName,"smearSmearMC_2");
  smearSmearMC[2] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[0],*smearMC[2]));
  sprintf(histName,"smearSmearMC_3");
  smearSmearMC[3] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[0],*smearMC[3]));
  sprintf(histName,"smearSmearMC_4");
  smearSmearMC[4] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[0],*smearMC[4]));
  sprintf(histName,"smearSmearMC_5");
  smearSmearMC[5] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[0],*smearMC[5]));
  sprintf(histName,"smearSmearMC_6");
  smearSmearMC[6] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearMC[1],*smearMC[1]));

  sprintf(histName,"smearSmearMC_7");
  smearSmearMC[7] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[1],*smearMC[2]));
  sprintf(histName,"smearSmearMC_8");
  smearSmearMC[8] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[1],*smearMC[3]));
  sprintf(histName,"smearSmearMC_9");
  smearSmearMC[9] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[1],*smearMC[4]));
  sprintf(histName,"smearSmearMC_10");
  smearSmearMC[10] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[1],*smearMC[5]));
  sprintf(histName,"smearSmearMC_11");
  smearSmearMC[11] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearMC[2],*smearMC[2]));

  sprintf(histName,"smearSmearMC_12");
  smearSmearMC[12] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[2],*smearMC[3]));
  sprintf(histName,"smearSmearMC_13");
  smearSmearMC[13] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[2],*smearMC[4]));
  sprintf(histName,"smearSmearMC_14");
  smearSmearMC[14] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[2],*smearMC[5]));
  sprintf(histName,"smearSmearMC_15");
  smearSmearMC[15] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearMC[3],*smearMC[3]));

  sprintf(histName,"smearSmearMC_16");
  smearSmearMC[16] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[3],*smearMC[4]));
  sprintf(histName,"smearSmearMC_17");
  smearSmearMC[17] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[3],*smearMC[5]));
  sprintf(histName,"smearSmearMC_18");
  smearSmearMC[18] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearMC[4],*smearMC[4]));

  sprintf(histName,"smearSmearMC_19");
  smearSmearMC[19] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearMC[4],*smearMC[5]));
  sprintf(histName,"smearSmearMC_20");
  smearSmearMC[20] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearMC[5],*smearMC[5]));
//*/  


  //*
  ///smearSmear
  sprintf(histName,"smearSmearRD_0");
  smearSmearRD[0] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearRD[0],*smearRD[0]));
  sprintf(histName,"smearSmearRD_1");
  smearSmearRD[1] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[0],*smearRD[1]));
  sprintf(histName,"smearSmearRD_2");
  smearSmearRD[2] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[0],*smearRD[2]));
  sprintf(histName,"smearSmearRD_3");
  smearSmearRD[3] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[0],*smearRD[3]));
  sprintf(histName,"smearSmearRD_4");
  smearSmearRD[4] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[0],*smearRD[4]));
  sprintf(histName,"smearSmearRD_5");
  smearSmearRD[5] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[0],*smearRD[5]));
  sprintf(histName,"smearSmearRD_6");
  smearSmearRD[6] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearRD[1],*smearRD[1]));

  sprintf(histName,"smearSmearRD_7");
  smearSmearRD[7] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[1],*smearRD[2]));
  sprintf(histName,"smearSmearRD_8");
  smearSmearRD[8] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[1],*smearRD[3]));
  sprintf(histName,"smearSmearRD_9");
  smearSmearRD[9] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[1],*smearRD[4]));
  sprintf(histName,"smearSmearRD_10");
  smearSmearRD[10] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[1],*smearRD[5]));
  sprintf(histName,"smearSmearRD_11");
  smearSmearRD[11] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearRD[2],*smearRD[2]));

  sprintf(histName,"smearSmearRD_12");
  smearSmearRD[12] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[2],*smearRD[3]));
  sprintf(histName,"smearSmearRD_13");
  smearSmearRD[13] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[2],*smearRD[4]));
  sprintf(histName,"smearSmearRD_14");
  smearSmearRD[14] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[2],*smearRD[5]));
  sprintf(histName,"smearSmearRD_15");
  smearSmearRD[15] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearRD[3],*smearRD[3]));

  sprintf(histName,"smearSmearRD_16");
  smearSmearRD[16] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[3],*smearRD[4]));
  sprintf(histName,"smearSmearRD_17");
  smearSmearRD[17] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[3],*smearRD[5]));
  sprintf(histName,"smearSmearRD_18");
  smearSmearRD[18] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearRD[4],*smearRD[4]));

  sprintf(histName,"smearSmearRD_19");
  smearSmearRD[19] = new RooFormulaVar(histName,"sqrt(@0*@0+@1*@1)",RooArgSet(*smearRD[4],*smearRD[5]));
  sprintf(histName,"smearSmearRD_20");
  smearSmearRD[20] = new RooFormulaVar(histName,"sqrt(@0*@0+@0*@0)",RooArgSet(*smearRD[5],*smearRD[5]));
//*/

  RooRealVar gaussMean("gaussMean","gaussMean",0);
  gaussMean.setConstant(kTRUE);
  RooRealVar CBMean("CBMean","CBMean",0);
  CBMean.setConstant(kTRUE);
  for(int i(0);i<ScElCombiBins;i++)
  {
    //Getting histogram from RD & MC
    sprintf(histName,"h1_ZmassDaughEtaEle_%d",i);
    h1_ZmassDaughEtaMC[i] = (TH1D*)f_MC->Get(histName)->Clone(histName);
    h1_ZmassDaughEtaRD[i] = (TH1D*)f_RD->Get(histName)->Clone(histName);

    sprintf(histName,"ZmassRD_%d",i);
    ZmassRD[i] =
     new RooDataHist(histName,histName,RooArgSet(zMass),h1_ZmassDaughEtaRD[i]);

    sprintf(histName,"cat_%d",i);
    hmapMC[histName] = h1_ZmassDaughEtaMC[i];
    sprintf(histName,"cat_%d",i);
    hmapRD[histName] = h1_ZmassDaughEtaRD[i];

    // Making template from MC
    sprintf(histName,"ZmassMC_%d",i);
    ZmassMC[i] = new RooDataHist(histName,histName,RooArgSet(zMass),h1_ZmassDaughEtaMC[i]);
    
    sprintf(histName,"cbMC_%d",i);
    cbMC[i] = new RooCBShape(histName,histName,zMass,CBMean,*smearSmearMC[i],*CBalpha[i],*CBn[i]);
    sprintf(histName,"BWMC_%d",i);
    BWMC[i] = new CBreitWignerMC(histName,zMass, scaleScaleMC[i]);

    sprintf(histName,"pdfMCsig_%d",i);
    pdfMCsig[i] = new RooFFTConvPdf(histName,histName,zMass,*(BWMC[i]->model),*cbMC[i]);


    //Making RD pdf
//    sprintf(histName,"gaus_%d",i);
//    gaus[i] = new RooGaussian(histName,histName,zMass,gaussMean,*smearSmearRD[i]);
   
//    sprintf(histName,"BWCBsCale_%d",i);
//    BWCBsCale[i] = new CBreitWignerConvCrystalBallScale
 //     (histName,zMass, scaleScaleRD[i],
 //     BWCB[i]->mean->getVal(),BWCB[i]->sigma->getVal(),BWCB[i]->alpha->getVal(),BWCB[i]->n->getVal());

//*

    sprintf(histName,"cbRD_%d",i);
    cbRD[i] = new RooCBShape(histName,histName,zMass,CBMean,*smearSmearRD[i],*CBalpha[i],*CBn[i]);

    sprintf(histName,"BWRD_%d",i);
    BWRD[i] = new CBreitWignerRD(histName,zMass, scaleScaleRD[i]);
  sprintf(histName,"pdfRDsig_%d",i);
  //  pdfRDsig[i] = new RooFFTConvPdf(histName,histName,zMass,*(BWCBsCale[i]->model),*gaus[i]);
  pdfRDsig[i] = new RooFFTConvPdf(histName,histName,zMass,*(BWRD[i]->model),*cbRD[i]);
    

    
    sprintf(histName,"cat_%d",i);
    pdfTotalMC.addPdf(*pdfMCsig[i],histName);
 
    sprintf(histName,"cat_%d",i);
    pdfTotalRD.addPdf(*pdfRDsig[i],histName);
  
}
 RooDataHist MCTotal("MCTotal","MCTotal",zMass,rooCat,hmapMC);
 fitResTotalMC = pdfTotalMC.fitTo(MCTotal,Minos(kTRUE),Save(kTRUE),SumW2Error(kTRUE));

 RooDataHist dataTotal("dataTotal","dataTotal",zMass,rooCat,hmapRD);
 fitResTotalRD = pdfTotalRD.fitTo(dataTotal,Minos(kTRUE),Save(kTRUE),SumW2Error(kTRUE));

 Fout<<"bin range \t scale \t smear "<<endl;

  for(int i(0);i<ScaleBins;i++)
  {
//    cout<<" "<<i<<"\t"<<scaleMC[i]->getVal()<<"+"<<scaleMC[i]->getError()<<"\t"<<smearMC[i]->getVal()<<"+"<<smearMC[i]->getError()<<endl;
//    Fout<<" "<<i<<"\t"<<scaleMC[i]->getVal()<<"+"<<scaleMC[i]->getError()<<"\t"<<smearMC[i]->getVal()<<"+"<<smearMC[i]->getError()<<endl;
  
//    cout<<" "<<i<<"\t"<<scaleRD[i]->getVal()<<"+"<<scaleRD[i]->getError()<<"\t"<<smearRD[i]->getVal()<<"+"<<smearRD[i]->getError()<<endl;
//    Fout<<" "<<i<<"\t"<<scaleRD[i]->getVal()<<"+"<<scaleRD[i]->getError()<<"\t"<<smearRD[i]->getVal()<<"+"<<smearRD[i]->getError()<<endl;
 



cout<<" "<<i<<"\t"<<scaleRD[i]->getVal()/scaleMC[i]->getVal()<<"+-"<<(scaleRD[i]->getVal()/scaleMC[i]->getVal())*sqrt((scaleRD[i]->getError()*scaleRD[i]->getError())/scaleRD[i]->getVal()/scaleRD[i]->getVal()+(scaleMC[i]->getError()*scaleMC[i]->getError())/scaleMC[i]->getVal()/scaleMC[i]->getVal())<<"\t"<<sqrt(smearRD[i]->getVal()*smearRD[i]->getVal()- smearMC[i]->getVal()*smearMC[i]->getVal())<<"+"<<sqrt(smearRD[i]->getError()*smearRD[i]->getError()+ smearMC[i]->getError()*smearMC[i]->getError())<<endl;

  
Fout<<" "<<i<<"\t"<<scaleRD[i]->getVal()/scaleMC[i]->getVal()<<"+-"<<(scaleRD[i]->getVal()/scaleMC[i]->getVal())*sqrt((scaleRD[i]->getError()*scaleRD[i]->getError())/scaleRD[i]->getVal()/scaleRD[i]->getVal()+(scaleMC[i]->getError()*scaleMC[i]->getError())/scaleMC[i]->getVal()/scaleMC[i]->getVal())<<"\t"<<sqrt(smearRD[i]->getVal()*smearRD[i]->getVal()- smearMC[i]->getVal()*smearMC[i]->getVal())  <<"+"<<sqrt(smearRD[i]->getError()*smearRD[i]->getError()+ smearMC[i]->getError()*smearMC[i]->getError())<<endl;

  }
//*
  for(int i(0);i<ScElCombiBins;i++)
  {
    //*
    zmassFrameMC = zMass.frame();
     ZmassMC[i]->plotOn(zmassFrameMC,DrawOption("p"));
     pdfMCsig[i]->plotOn(zmassFrameMC,DrawOption("l"));
     sprintf(histName,"ZmassMC_%s_%d",BaseName,i);

     plotFitMC = new CPlot(histName,zmassFrameMC,"","Di-Lepton M","");
     plotFitMC->setOutDir(ResultDir);
     plotFitMC->Draw(myCan,kTRUE,"png");
//*/
     zmassFrameRD = zMass.frame();
     ZmassRD[i]->plotOn(zmassFrameRD,DrawOption("p"));
     pdfRDsig[i]->plotOn(zmassFrameRD,DrawOption("l"));
     sprintf(histName,"ZmassRD_%s_%d",BaseName,i);

     plotFitRD = new CPlot(histName,zmassFrameRD,"","Di-Lepton M","");
     plotFitRD->setOutDir(ResultDir);
     plotFitRD->Draw(myCan,kTRUE,"png");
  }
//*/  
  Fout.close();
  return 0;
}
void fitEfficiency(float thres,
		   float mLow=45, float mHigh=70,
		   TString cutdef="pt_HLT>=20", TString cut_choice="HLT",
		   TString dirIn="/data_CMS/cms/ndaci/ndaci_2012/HTauTau/TriggerStudy/SingleMu/MuMu/Run2012A_PRV1/Pairs/", 
		   TString dirResults="/home//llr/cms/ndaci/SKWork/macro/HTauTau/results/TriggerStudies/MuMu/Run2012A_PRV1/",
		   TString lumi="200 pb", int nCPU=4, 
		   int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
		   TString fileIn="*.root", TString image="eff_HLT_MuTau")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // OUTPUT //
  TString name_image = dirResults+"/"+image;
  ofstream fichier(name_image+".txt", ios::out);

  // BINNING //
  const int nbinsEB = 14;
  Double_t binsEB[nbinsEB] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEB = RooBinning(nbinsEB-1, binsEB, "binningEB");

  const int nbinsEE = 14;
  Double_t binsEE[nbinsEE] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEE = RooBinning(nbinsEE-1, binsEE, "binningEE");

  // EB/EE eta cuts //
  TString etacutEB="eta>-1.479 && eta<1.479", etacutEE="eta<=-1.479 || eta>=1.479";
  TString cutdefEB, cutdefEE;
  if(cutdef=="") { 
    cutdefEB=etacutEB;
    cutdefEE=etacutEE;
  }
  else {
    cutdefEB=cutdef+" && "+etacutEB ;
    cutdefEB=cutdef+" && "+etacutEE ;
  }

  // INPUT DATA //
  TChain* treeTnP = new TChain("treeTnP");
  treeTnP->Add(dirIn+"/"+fileIn);

  RooRealVar xaxis("pt","P_{T} [GeV]",0,150) ;
  RooRealVar mass("mass","mass",mLow,mHigh) ;// consider only this mass range when importing data                                      
  RooRealVar eta("eta","eta",-3., 3) ;
  RooRealVar weight("weight","weight",-1,1000) ;
  RooRealVar pt_HLT_tag("pt_HLT_tag","P_{T} [GeV]",0,150) ;
  RooRealVar pt_HLT_tag_sanity("pt_HLT_tag_sanity","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L3("pt_L3","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L25("pt_L25","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L2("pt_L2","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1jet("et_L1_jet","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1tau("et_L1_tau","P_{T} [GeV]",0,150) ;

  // DEFINE EFFICIENCY CUT //
  RooCategory cutHLT("match","") ;
  cutHLT.defineType("accept",1) ;
  cutHLT.defineType("reject",0) ;

  RooCategory cutL1("L1match","") ;
  cutL1.defineType("accept",1) ;
  cutL1.defineType("reject",0) ;

  RooCategory cutL1L2("L1L2match","") ;
  cutL1L2.defineType("accept",1) ;
  cutL1L2.defineType("reject",0) ;

  RooCategory cutL1L2L25("L1L2L25match","") ;
  cutL1L2L25.defineType("accept",1) ;
  cutL1L2L25.defineType("reject",0) ;

  RooCategory cutL1L2L25L3("L1L2L25L3match","") ;
  cutL1L2L25L3.defineType("accept",1) ;
  cutL1L2L25L3.defineType("reject",0) ;

  RooCategory *cut;
  if(cut_choice=="HLT") cut = &cutHLT;
  if(cut_choice=="L1") cut = &cutL1;
  if(cut_choice=="L1L2") cut = &cutL1L2;
  if(cut_choice=="L1L2L25") cut = &cutL1L2L25;
  if(cut_choice=="L1L2L25L3") cut = &cutL1L2L25L3;

  RooDataSet dataSetEB("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEB) );
  
  RooDataSet dataSetEE("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEE) );
  
  dataSetEB.Print();
  dataSetEE.Print();

  // PLOT //
  RooPlot* frame = xaxis.frame(Bins(18000),Title("Fitted efficiency")) ;
  dataSetEB.plotOn(frame, Binning(binningEB), Efficiency(*cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSetEE.plotOn(frame, Binning(binningEE), Efficiency(*cut), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );

  // PARAMETRES ROOFIT CRYSTAL BALL //
  RooRealVar norm("norm","N",0.95,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.2,0.01,8);
  RooRealVar n("n","n",2,1.1,35);
  RooRealVar mean("mean","mean",10,5,30);
  mean.setVal(thres);
  RooRealVar sigma("sigma","#sigma",0.23,0.01,5);
  RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  FuncCB cb_EB("cb_EB","Fit function EB (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  FuncCB cb_EE("cb_EE","Fit function EE (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  
  RooEfficiency eff_EB("eff_EB","efficiency EB", cb_EB, *cut, "accept");
  RooEfficiency eff_EE("eff_EE","efficiency EE", cb_EE, *cut, "accept");  

  // FIT //
  double fit_cuts_min = thres-1.5 ;
  double fit_cuts_max = 150;
  xaxis.setRange("interesting",fit_cuts_min,fit_cuts_max);

  fichier << "Fit characteristics :" << endl
	  << "Threshold : "          << thres << endl 
	  << "Fit Range : ["         << fit_cuts_min << "," << fit_cuts_max << "]" << endl 
	  << endl << endl;

  RooFitResult* roofitres_EB = new RooFitResult("roofitres_EB","roofitres_EB");
  RooFitResult* roofitres_EE = new RooFitResult("roofitres_EE","roofitres_EE");

  // Fit #1 //
  roofitres_EB = eff_EB.fitTo(dataSetEB,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EB.plotOn(frame,LineColor(color1),LineWidth(2));

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;

  // Fit #2 //
  roofitres_EE = eff_EE.fitTo(dataSetEE,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EE.plotOn(frame,LineColor(color2),LineWidth(2));

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;


  ////////////////////////////  DRAWING PLOTS AND LEGENDS /////////////////////////////////
  TCanvas* ca = new TCanvas("ca","Trigger Efficiency") ;

  ca->SetGridx();
  ca->SetGridy();
  ca->cd();
  
  //gPad->SetLogx();
  gPad->SetObjectStat(1);

  frame->GetYaxis()->SetRangeUser(0,1.05);
  frame->GetXaxis()->SetRangeUser(1,150.);
  frame->GetYaxis()->SetTitle("Efficiency");
  frame->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame->Draw() ;

  TH1F *SCeta_EB = new TH1F("SCeta_EB","SCeta_EB",50,-2.5,2.5);
  TH1F *SCeta_EE = new TH1F("SCeta_EE","SCeta_EE",50,-2.5,2.5);

  SCeta_EB->SetLineColor(color1) ;
  SCeta_EB->SetMarkerColor(color1);
  SCeta_EB->SetMarkerStyle(style1);

  SCeta_EE->SetLineColor(color2) ;
  SCeta_EE->SetMarkerColor(color2);
  SCeta_EE->SetMarkerStyle(style2);

  TLegend *leg = new TLegend(0.40, 0.14, 0.63, 0.34, NULL, "brNDC");
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.0244755);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);  
  leg->AddEntry("NULL","e #tau electrons efficiency","h");
  //    entry->SetLineColor(1);
  //    entry->SetLineStyle(1);
  //    entry->SetLineWidth(1);
  //    entry->SetMarkerColor(1);
  //    entry->SetMarkerStyle(21);
  //    entry->SetMarkerSize(1);
  //    entry->SetTextFont(62);
  leg->AddEntry(SCeta_EB,"Barrel","p");
  leg->AddEntry(SCeta_EE,"Endcaps","p");
  leg->Draw(); 
  
  ostringstream ossi("");
  ossi << thres;
  TString tossi = ossi.str();

  leg = new TLegend(0.40, 0.30, 0.50, 0.50, NULL, "brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.0297203);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+tossi+" GeV","h");
  leg->Draw();
  
  ca->Print(name_image+".C","C");
  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");

  /////////////////////////////
  // SAVE THE ROO FIT RESULT //
  /////////////////////////////

  RooWorkspace *w = new RooWorkspace("workspace","workspace") ;

  w->import(dataSetEB);
  w->import(dataSetEE);
  
  w->import(*roofitres_EB,"roofitres_EB");
  w->import(*roofitres_EE,"roofitres_EE");

  cout << "CREATES WORKSPACE : " << endl;
  w->Print();
  
  w->writeToFile(name_image+"_fitres.root") ;
  //gDirectory->Add(w) ;

  // DELETE POINTERS
  // int a=0;
//   cin >> a;
//   delete treeTnP; delete cut; delete frame; delete roofitres_EB; delete roofitres_EE; delete ca; delete SCeta_EB; delete SCeta_EE; delete leg; delete w;

}