Esempio n. 1
0
TPaveText* getHeader(double lumi, TString channelName)
{
  TPaveText* pt = new TPaveText(0.18,0.75,0.18,0.88,"brNDC");

  pt->SetBorderSize(1);
  pt->SetTextFont(42);
  pt->SetTextSize(0.04);
  pt->SetLineColor(0);
  pt->SetLineStyle(1);
  pt->SetLineWidth(1);
  pt->SetFillColor(0);
  pt->SetFillStyle(1001);
  pt->SetTextAlign(12);
  pt->AddText("CMS Preliminary");
  pt->AddText(Form("%.1f fb^{-1} at  #sqrt{s} = 7 TeV", lumi));
  if ( channelName != "" ) pt->AddText(channelName);

  return pt;
}
Esempio n. 2
0
void BackgroundPrediction(std::string pname,int rebin_factor,int model_number = 0,int imass=750, bool plotBands = false)
{
    rebin = rebin_factor;
    std::string fname = std::string("../fitFilesMETPT34/") + pname + std::string("/histos_bkg.root");
    
    stringstream iimass ;
    iimass << imass;
    std::string dirName = "info_"+iimass.str()+"_"+pname;
    
    
    gStyle->SetOptStat(000000000);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    
    setTDRStyle();
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gStyle->SetOptStat(0000);
    
    writeExtraText = true;       // if extra text
    extraText  = "Preliminary";  // default extra text is "Preliminary"
    lumi_13TeV  = "2.7 fb^{-1}"; // default is "19.7 fb^{-1}"
    lumi_7TeV  = "4.9 fb^{-1}";  // default is "5.1 fb^{-1}"
    
    
    double ratio_tau=-1;
    
    TFile *f=new TFile(fname.c_str());
    TH1F *h_mX_CR_tau=(TH1F*)f->Get("distribs_18_10_1")->Clone("CR_tau");
    TH1F *h_mX_SR=(TH1F*)f->Get("distribs_18_10_0")->Clone("The_SR");
    double maxdata = h_mX_SR->GetMaximum();
    double nEventsSR = h_mX_SR->Integral(600,4000);
    ratio_tau=(h_mX_SR->GetSumOfWeights()/(h_mX_CR_tau->GetSumOfWeights()));
    //double nEventsSR = h_mX_SR->Integral(600,4000);
    
    std::cout<<"ratio tau "<<ratio_tau<<std::endl;
    
    TH1F *h_SR_Prediction;
    TH1F *h_SR_Prediction2;
    
    if(blind) {
        h_SR_Prediction2 = (TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction2");
        h_mX_CR_tau->Rebin(rebin);
        h_mX_CR_tau->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction");
    } else {
        h_SR_Prediction2=(TH1F*)h_mX_SR->Clone("h_SR_Prediction2");
        h_mX_SR->Rebin(rebin);
        h_mX_SR->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_SR->Clone("h_SR_Prediction");
        
    }
    h_SR_Prediction->SetMarkerSize(0.7);
    h_SR_Prediction->GetYaxis()->SetTitleOffset(1.2);
    h_SR_Prediction->Sumw2();
    
    /*TFile *f_sig = new TFile((dirName+"/w_signal_"+iimass.str()+".root").c_str());
    RooWorkspace* xf_sig = (RooWorkspace*)f_sig->Get("Vg");
    RooAbsPdf *xf_sig_pdf = (RooAbsPdf *)xf_sig->pdf((std::string("signal_fixed_")+pname).c_str());
    
    RooWorkspace w_sig("w");
    w_sig.import(*xf_sig_pdf,RooFit::RenameVariable((std::string("signal_fixed_")+pname).c_str(),(std::string("signal_fixed_")+pname+std::string("low")).c_str()),RooFit::RenameAllVariablesExcept("low","x"));
    xf_sig_pdf = w_sig.pdf((std::string("signal_fixed_")+pname+std::string("low")).c_str());
   
    RooArgSet* biasVars = xf_sig_pdf->getVariables();
    TIterator *it = biasVars->createIterator();
    RooRealVar* var = (RooRealVar*)it->Next();
    while (var) {
        var->setConstant(kTRUE);
        var = (RooRealVar*)it->Next();
    }
    */
    RooRealVar x("x", "m_{X} (GeV)", SR_lo, SR_hi);
    
    RooRealVar nBackground((std::string("bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    RooRealVar nBackground2((std::string("alt_bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    std::string blah = pname;
    //pname=""; //Antibtag=tag to constrain b-tag to the anti-btag shape
    
    
    /* RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 4.2, 0, 200.);
     RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", 4.5, 0, 300.);
     RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", 0.000047, 0, 10.1);
     RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(1-@0/13000,@1)/pow(@0/13000,@2+@3*log(@0/13000)))",RooArgList(x,bg_p0,bg_p1,bg_p2));
   */
    RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 0., -1000, 200.);
    RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", -13, -1000, 1000.);
    RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", -1.4, -1000, 1000.);
    bg_p0.setConstant(kTRUE);
    //RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
    RooGenericPdf bg = RooGenericPdf((std::string("bg_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
  

    /*TF1* biasFunc = new TF1("biasFunc","(0.63*x/1000-1.45)",1350,3600);
    TF1* biasFunc2 = new TF1("biasFunc2","TMath::Min(2.,2.3*x/1000-3.8)",1350,3600);
    double bias_term_s = 0;
    if ((imass > 2450 && blah == "antibtag") || (imass > 1640 && blah == "btag")) {
        if (blah == "antibtag") {
            bias_term_s = 2.7*biasFunc->Eval(imass);
        } else {
            bias_term_s = 2.7*biasFunc2->Eval(imass);
        }
       bias_term_s/=nEventsSR;
    }
    
    RooRealVar bias_term((std::string("bias_term_")+blah).c_str(), "bias_term", 0., -bias_term_s, bias_term_s);
    //bias_term.setConstant(kTRUE);
    RooAddPdf bg((std::string("bg_")+blah).c_str(), "bg_all", RooArgList(*xf_sig_pdf, bg_pure), bias_term);
    */
    string name_output = "CR_RooFit_Exp";
    
    std::cout<<"Nevents "<<nEventsSR<<std::endl;
    RooDataHist pred("pred", "Prediction from SB", RooArgList(x), h_SR_Prediction);
    RooFitResult *r_bg=bg.fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save(),RooFit::SumW2Error(kTRUE));
    std::cout<<" --------------------- Building Envelope --------------------- "<<std::endl;
    //std::cout<< "bg_p0_"<< pname << "   param   "<<bg_p0.getVal() <<  " "<<bg_p0.getError()<<std::endl;
    std::cout<< "bg_p1_"<< pname << "   param   "<<bg_p1.getVal() <<  " "<<100*bg_p1.getError()<<std::endl;
    std::cout<< "bg_p2_"<< pname << "   param   "<<bg_p2.getVal() <<  " "<<100*bg_p2.getError()<<std::endl;
    //std::cout<< "bias_term_"<< blah << "   param   0 "<<bias_term_s<<std::endl;
    
    RooPlot *aC_plot=x.frame();
    pred.plotOn(aC_plot, RooFit::MarkerColor(kPink+2));
    if (!plotBands) {
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 2), RooFit::FillColor(kYellow));
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 1), RooFit::FillColor(kGreen));
    }
    bg.plotOn(aC_plot, RooFit::LineColor(kBlue));
    //pred.plotOn(aC_plot, RooFit::LineColor(kBlack), RooFit::MarkerColor(kBlack));
    
    TGraph* error_curve[5]; //correct error bands
    TGraphAsymmErrors* dataGr = new TGraphAsymmErrors(h_SR_Prediction->GetNbinsX()); //data w/o 0 entries

    for (int i=2; i!=5; ++i) {
        error_curve[i] = new TGraph();
    }
    error_curve[2] = (TGraph*)aC_plot->getObject(1)->Clone("errs");
    int nPoints = error_curve[2]->GetN();
    
    error_curve[0] = new TGraph(2*nPoints);
    error_curve[1] = new TGraph(2*nPoints);
    
    error_curve[0]->SetFillStyle(1001);
    error_curve[1]->SetFillStyle(1001);
    
    error_curve[0]->SetFillColor(kGreen);
    error_curve[1]->SetFillColor(kYellow);
    
    error_curve[0]->SetLineColor(kGreen);
    error_curve[1]->SetLineColor(kYellow);
    
    if (plotBands) {
        RooDataHist pred2("pred2", "Prediction from SB", RooArgList(x), h_SR_Prediction2);

        error_curve[3]->SetFillStyle(1001);
        error_curve[4]->SetFillStyle(1001);
        
        error_curve[3]->SetFillColor(kGreen);
        error_curve[4]->SetFillColor(kYellow);
        
        error_curve[3]->SetLineColor(kGreen);
        error_curve[4]->SetLineColor(kYellow);
        
        error_curve[2]->SetLineColor(kBlue);
        error_curve[2]->SetLineWidth(3);
        
        double binSize = rebin;
        
        for (int i=0; i!=nPoints; ++i) {
            double x0,y0, x1,y1;
            error_curve[2]->GetPoint(i,x0,y0);
            
            RooAbsReal* nlim = new RooRealVar("nlim","y0",y0,-100000,100000);
            //double lowedge = x0 - (SR_hi - SR_lo)/double(2*nPoints);
            //double upedge = x0 + (SR_hi - SR_lo)/double(2*nPoints);
            
            double lowedge = x0 - binSize/2.;
            double upedge = x0 + binSize/2.;
            
            x.setRange("errRange",lowedge,upedge);
            
            RooExtendPdf* epdf = new RooExtendPdf("epdf","extpdf",bg, *nlim,"errRange");
            
            // Construct unbinned likelihood
            RooAbsReal* nll = epdf->createNLL(pred2,NumCPU(2));
            // Minimize likelihood w.r.t all parameters before making plots
            RooMinimizer* minim = new RooMinimizer(*nll);
            minim->setMinimizerType("Minuit2");
            minim->setStrategy(2);
            minim->setPrintLevel(-1);
            minim->migrad();
            
            minim->hesse();
            RooFitResult* result = minim->lastMinuitFit();
            double errm = nlim->getPropagatedError(*result);
            
            //std::cout<<x0<<" "<<lowedge<<" "<<upedge<<" "<<y0<<" "<<nlim->getVal()<<" "<<errm<<std::endl;
            
            error_curve[0]->SetPoint(i,x0,(y0-errm));
            error_curve[0]->SetPoint(2*nPoints-i-1,x0,y0+errm);
            
            error_curve[1]->SetPoint(i,x0,(y0-2*errm));
            error_curve[1]->SetPoint(2*nPoints-i-1,x0,(y0+2*errm));
            
            error_curve[3]->SetPoint(i,x0,-errm/sqrt(y0));
            error_curve[3]->SetPoint(2*nPoints-i-1,x0,errm/sqrt(y0));
            
            error_curve[4]->SetPoint(i,x0,-2*errm/sqrt(y0));
            error_curve[4]->SetPoint(2*nPoints-i-1,x0,2*errm/sqrt(y0));
            
        }
        
        int npois = 0;
        dataGr->SetMarkerSize(1.0);
        dataGr->SetMarkerStyle (20);
        
        const double alpha = 1 - 0.6827;
        
        for (int i=0; i!=h_SR_Prediction->GetNbinsX(); ++i){
            if (h_SR_Prediction->GetBinContent(i+1) > 0) {
                
                int N = h_SR_Prediction->GetBinContent(i+1);
                double L =  (N==0) ? 0  : (ROOT::Math::gamma_quantile(alpha/2,N,1.));
                double U =  ROOT::Math::gamma_quantile_c(alpha/2,N+1,1) ;
                
                dataGr->SetPoint(npois,h_SR_Prediction->GetBinCenter(i+1),h_SR_Prediction->GetBinContent(i+1));
                dataGr->SetPointEYlow(npois, N-L);
                dataGr->SetPointEYhigh(npois, U-N);
                npois++;
            }
        }
    }
    
    double xG[2] = {-10,4000};
    double yG[2] = {0.0,0.0};
    TGraph* unityG = new TGraph(2, xG, yG);
    unityG->SetLineColor(kBlue);
    unityG->SetLineWidth(1);

    double xPad = 0.3;
    TCanvas *c_rooFit=new TCanvas("c_rooFit", "c_rooFit", 800*(1.-xPad), 600);
    c_rooFit->SetFillStyle(4000);
    c_rooFit->SetFrameFillColor(0);
    
    TPad *p_1=new TPad("p_1", "p_1", 0, xPad, 1, 1);
    p_1->SetFillStyle(4000);
    p_1->SetFrameFillColor(0);
    p_1->SetBottomMargin(0.02);
    TPad* p_2 = new TPad("p_2", "p_2",0,0,1,xPad);
    p_2->SetBottomMargin((1.-xPad)/xPad*0.13);
    p_2->SetTopMargin(0.03);
    p_2->SetFillColor(0);
    p_2->SetBorderMode(0);
    p_2->SetBorderSize(2);
    p_2->SetFrameBorderMode(0);
    p_2->SetFrameBorderMode(0);
    
    p_1->Draw();
    p_2->Draw();
    p_1->cd();
    
    int nbins = (int) (SR_hi- SR_lo)/rebin;
    x.setBins(nbins);
    
    std::cout << "chi2(data) " <<  aC_plot->chiSquare()<<std::endl;
    
    //std::cout << "p-value: data     under hypothesis H0:  " << TMath::Prob(chi2_data->getVal(), nbins - 1) << std::endl;
    
    aC_plot->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    aC_plot->GetXaxis()->SetLabelOffset(0.02);
    aC_plot->GetYaxis()->SetRangeUser(0.1, 1000.);
    h_SR_Prediction->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    string rebin_ = itoa(rebin);
    
    aC_plot->GetXaxis()->SetTitle("M_{Z#gamma} [GeV] ");
    aC_plot->GetYaxis()->SetTitle(("Events / "+rebin_+" GeV ").c_str());
    aC_plot->SetMarkerSize(0.7);
    aC_plot->GetYaxis()->SetTitleOffset(1.2);
    aC_plot->Draw();
    
    if (plotBands) {
        error_curve[1]->Draw("Fsame");
        error_curve[0]->Draw("Fsame");
        error_curve[2]->Draw("Lsame");
        dataGr->Draw("p e1 same");
    }
    
    aC_plot->SetTitle("");
    TPaveText *pave = new TPaveText(0.85,0.4,0.67,0.5,"NDC");
    pave->SetBorderSize(0);
    pave->SetTextSize(0.05);
    pave->SetTextFont(42);
    pave->SetLineColor(1);
    pave->SetLineStyle(1);
    pave->SetLineWidth(2);
    pave->SetFillColor(0);
    pave->SetFillStyle(0);
    char name[1000];
    sprintf(name,"#chi^{2}/n = %.2f",aC_plot->chiSquare());
    pave->AddText(name);
    //pave->Draw();
    
    TLegend *leg = new TLegend(0.88,0.65,0.55,0.90,NULL,"brNDC");
    leg->SetBorderSize(0);
    leg->SetTextSize(0.05);
    leg->SetTextFont(42);
    leg->SetLineColor(1);
    leg->SetLineStyle(1);
    leg->SetLineWidth(2);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    h_SR_Prediction->SetMarkerColor(kBlack);
    h_SR_Prediction->SetLineColor(kBlack);
    h_SR_Prediction->SetMarkerStyle(20);
    h_SR_Prediction->SetMarkerSize(1.0);
    //h_mMMMMa_3Tag_SR->GetXaxis()->SetTitleSize(0.09);
    if (blind)
        leg->AddEntry(h_SR_Prediction, "Data: sideband", "ep");
    else {
        if (blah == "antibtag" )
            leg->AddEntry(h_SR_Prediction, "Data: anti-b-tag SR", "ep");
        else
            leg->AddEntry(h_SR_Prediction, "Data: b-tag SR", "ep");
        
    }
    
    leg->AddEntry(error_curve[2], "Fit model", "l");
    leg->AddEntry(error_curve[0], "Fit #pm1#sigma", "f");
    leg->AddEntry(error_curve[1], "Fit #pm2#sigma", "f");
    leg->Draw();
    
    aC_plot->Draw("axis same");
    
    
    CMS_lumi( p_1, iPeriod, iPos );
    
    p_2->cd();
    RooHist* hpull;
    hpull = aC_plot->pullHist();
    RooPlot* frameP = x.frame() ;
    frameP->SetTitle("");
    frameP->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    
    frameP->addPlotable(hpull,"P");
    frameP->GetYaxis()->SetRangeUser(-7,7);
    frameP->GetYaxis()->SetNdivisions(505);
    frameP->GetYaxis()->SetTitle("#frac{(data-fit)}{#sigma_{stat}}");
    
    frameP->GetYaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    frameP->GetYaxis()->SetTitleOffset(1.0/((1.-xPad)/xPad));
    frameP->GetXaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    //frameP->GetXaxis()->SetTitleOffset(1.0);
    frameP->GetXaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    frameP->GetYaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    
    
    frameP->Draw();
    if (plotBands) {
        error_curve[4]->Draw("Fsame");
        error_curve[3]->Draw("Fsame");
        unityG->Draw("same");
        hpull->Draw("psame");
        
        frameP->Draw("axis same");
    }
    
    
    c_rooFit->SaveAs((dirName+"/"+name_output+".pdf").c_str());
    
    const int nModels = 9;
    TString models[nModels] = {
        "env_pdf_0_13TeV_dijet2", //0
        "env_pdf_0_13TeV_exp1", //1
        "env_pdf_0_13TeV_expow1", //2
        "env_pdf_0_13TeV_expow2", //3 => skip
        "env_pdf_0_13TeV_pow1", //4
        "env_pdf_0_13TeV_lau1", //5
        "env_pdf_0_13TeV_atlas1", //6
        "env_pdf_0_13TeV_atlas2", //7 => skip
        "env_pdf_0_13TeV_vvdijet1" //8
    };
    
    int nPars[nModels] = {
        2, 1, 2, 3, 1, 1, 2, 3, 2
    };
    
    TString parNames[nModels][3] = {
        "env_pdf_0_13TeV_dijet2_log1","env_pdf_0_13TeV_dijet2_log2","",
        "env_pdf_0_13TeV_exp1_p1","","",
        "env_pdf_0_13TeV_expow1_exp1","env_pdf_0_13TeV_expow1_pow1","",
        "env_pdf_0_13TeV_expow2_exp1","env_pdf_0_13TeV_expow2_pow1","env_pdf_0_13TeV_expow2_exp2",
        "env_pdf_0_13TeV_pow1_p1","","",
        "env_pdf_0_13TeV_lau1_l1","","",
        "env_pdf_0_13TeV_atlas1_coeff1","env_pdf_0_13TeV_atlas1_log1","",
        "env_pdf_0_13TeV_atlas2_coeff1","env_pdf_0_13TeV_atlas2_log1","env_pdf_0_13TeV_atlas2_log2",
        "env_pdf_0_13TeV_vvdijet1_coeff1","env_pdf_0_13TeV_vvdijet1_log1",""
    }
    
    if(bias){
        //alternative model
        gSystem->Load("libHiggsAnalysisCombinedLimit");
        gSystem->Load("libdiphotonsUtils");
        
        TFile *f = new TFile("antibtag_multipdf.root");
        RooWorkspace* xf = (RooWorkspace*)f->Get("wtemplates");
        RooWorkspace *w_alt=new RooWorkspace("Vg");
        for(int i=model_number; i<=model_number; i++){
            RooMultiPdf *alternative = (RooMultiPdf *)xf->pdf("model_bkg_AntiBtag");
            std::cout<<"Number of pdfs "<<alternative->getNumPdfs()<<std::endl;
            for (int j=0; j!=alternative->getNumPdfs(); ++j){
                std::cout<<alternative->getPdf(j)->GetName()<<std::endl;
            }
            RooAbsPdf *alt_bg = alternative->getPdf(alternative->getCurrentIndex()+i);//->clone();
            w_alt->import(*alt_bg, RooFit::RenameVariable(alt_bg->GetName(),("alt_bg_"+blah).c_str()));
            w_alt->Print("V");
            std::cerr<<w_alt->var("x")<<std::endl;
            RooRealVar * range_ = w_alt->var("x");
            range_->setRange(SR_lo,SR_hi);
            char* asd = ("alt_bg_"+blah).c_str()	;
            w_alt->import(nBackground2);
            std::cout<<alt_bg->getVal() <<std::endl;
            w_alt->pdf(asd)->fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());

    	    RooArgSet* altVars = w_alt->pdf(asd)->getVariables();
            TIterator *it2 = altVars->createIterator();
            RooRealVar* varAlt = (RooRealVar*)it2->Next();
            while (varAlt) {
               varAlt->setConstant(kTRUE);
               varAlt = (RooRealVar*)it2->Next();
            }



            alt_bg->plotOn(aC_plot, RooFit::LineColor(i+1), RooFit::LineStyle(i+2));
            p_1->cd();
            aC_plot->GetYaxis()->SetRangeUser(0.01, maxdata*50.);
            aC_plot->Draw("same");
            TH1F *h=new TH1F();
            h->SetLineColor(1+i);
            h->SetLineStyle(i+2);
            leg->AddEntry(h, alt_bg->GetName(), "l");
            
            
            w_alt->SaveAs((dirName+"/w_background_alternative.root").c_str());
        }
        leg->Draw();
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+blah+"_multipdf.pdf").c_str());
        
        for (int i=0; i!=nPars[model_number]; ++i) {
            std::cout<<parNames[model_number][i]<<" param "<< w_alt->var(parNames[model_number][i])->getVal()<<"   "<<w_alt->var(parNames[model_number][i])->getError()<<std::endl;
        }
        
        
    } else {
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+"_log.pdf").c_str());
    }
    
    RooWorkspace *w=new RooWorkspace("Vg");
    w->import(bg);
    w->import(nBackground);
    w->SaveAs((dirName+"/w_background_GaussExp.root").c_str());
    
    TH1F *h_mX_SR_fakeData=(TH1F*)h_mX_SR->Clone("h_mX_SR_fakeData");
    h_mX_SR_fakeData->Scale(nEventsSR/h_mX_SR_fakeData->GetSumOfWeights());
    RooDataHist data_obs("data_obs", "Data", RooArgList(x), h_mX_SR_fakeData);
    std::cout<<" Background number of events = "<<nEventsSR<<std::endl;
    RooWorkspace *w_data=new RooWorkspace("Vg");
    w_data->import(data_obs);
    w_data->SaveAs((dirName+"/w_data.root").c_str());
    
}
void plot_BSM_MCFM(int SignalOnly=0){
  gROOT->ProcessLine(".x tdrstyle.cc");
  double mPOLE = 125.6;

  TString OUTPUT_NAME;
  OUTPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMPlots";
  if (SignalOnly==0) OUTPUT_NAME.Append(".root");
  else OUTPUT_NAME.Append("_SignalOnly.root");
  TString coutput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/Plots/";
  gSystem->Exec("mkdir -p " + coutput_common);
  TString coutput = coutput_common + OUTPUT_NAME;
  TFile* foutput = new TFile(coutput, "recreate");

  foutput->cd();

  float ZZMass = 0;
  float p0plus_VAJHU;
  float p0hplus_VAJHU;
  float p0minus_VAJHU;
  float p0_g1prime2_VAJHU;
  float p0_g1prime4_VAJHU;
  float pg1g2_VAJHU;
  float pg1g4_VAJHU;
  float pg1g1prime2_VAJHU;
  float pg1g1prime4_VAJHU;

  TChain* tc[2][3][4];
  TH1F* hfill[4][9];
  int nbinsx = 73;
  double xlimits[2]={ 160, 1620 };
  if (SignalOnly==1){
    xlimits[0]=100;
    nbinsx = 76;
  }
  for (int t=0; t<4; t++){
    for (int ac=0; ac<9; ac++){
      hfill[t][ac]= new TH1F(Form("hSum_BSI%i_Hypo%i", t, ac), "", nbinsx, xlimits[0], xlimits[1]);
      hfill[t][ac]->SetXTitle("m_{4l} (GeV)");
      hfill[t][ac]->SetYTitle(Form("Events / %.0f GeV", (xlimits[1]-xlimits[0])/nbinsx));
    }
  }
  double nCounted[2][3][9]={ { { 0 } } };
  double nCountedScaled[2][3][9]={ { { 0 } } };
  for (int erg_tev=7; erg_tev<9; erg_tev++){
    for (int folder=0; folder<3; folder++){
      TString comstring;
      comstring.Form("%iTeV", erg_tev);
      TString erg_dir;
      erg_dir.Form("LHC_%iTeV/", erg_tev);

      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;
      TString cinput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/";
      cinput_common.Append(+erg_dir);
      cinput_common += user_folder[folder] + "/";
      cout << cinput_common << endl;
      for (int t=0; t<4; t++){
        TString INPUT_NAME;
        INPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMTrees_";
        INPUT_NAME += sample_suffix[t] + ".root";
        INPUT_NAME.Prepend(cinput_common);

        tc[EnergyIndex][folder][t] = new TChain("GenTree");
        if (t!=3) tc[EnergyIndex][folder][t]->Add(INPUT_NAME);
        tc[EnergyIndex][folder][t]->SetBranchAddress("ZZMass", &ZZMass);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0plus_VAJHU", &p0plus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0hplus_VAJHU", &p0hplus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0minus_VAJHU", &p0minus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0_g1prime2_VAJHU", &p0_g1prime2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0_g1prime4_VAJHU", &p0_g1prime4_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g2_VAJHU", &pg1g2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g4_VAJHU", &pg1g4_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g1prime2_VAJHU", &pg1g1prime2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g1prime4_VAJHU", &pg1g1prime4_VAJHU);
      }

      double nsig_counted[9] ={ 0 };
      for (int ev=0; ev<tc[EnergyIndex][folder][0]->GetEntries(); ev++){
        tc[EnergyIndex][folder][0]->GetEntry(ev);
        if (fabs(ZZMass-mPOLE)<0.1){
          nsig_counted[0] += p0plus_VAJHU;
          nsig_counted[1] += p0hplus_VAJHU;
          nsig_counted[2] += p0minus_VAJHU;
          nsig_counted[3] += p0_g1prime2_VAJHU;
          nsig_counted[4] += p0_g1prime4_VAJHU;
          nsig_counted[5] += (2.*(p0plus_VAJHU+p0hplus_VAJHU)-pg1g2_VAJHU);
          nsig_counted[6] += pg1g4_VAJHU;
          nsig_counted[7] += pg1g1prime2_VAJHU;
          nsig_counted[8] += pg1g1prime4_VAJHU;
        }
      }

      for (int ac=0; ac<9; ac++) nCounted[EnergyIndex][folder][ac] = nsig_counted[ac];

    }
  }


  for (int erg_tev=7; erg_tev<9; erg_tev++){
    for (int folder=0; folder<3; folder++){
      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;

      double nsig_SM = nSM_ScaledPeak[EnergyIndex][folder];
      double SMscale = nsig_SM/nCounted[EnergyIndex][folder][0];
      double scale=1;
      for (int t=0; t<4; t++){
        for (int ev=0; ev<tc[EnergyIndex][folder][t]->GetEntries(); ev++){
          tc[EnergyIndex][folder][t]->GetEntry(ev);
          if (ZZMass<xlimits[0]) continue;
          if (ZZMass>=xlimits[1]) ZZMass=xlimits[1]*0.999;

          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][0] = nCounted[EnergyIndex][folder][0]*scale;
          hfill[t][0]->Fill(ZZMass, p0plus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][1] = nCounted[EnergyIndex][folder][1]*scale;
          hfill[t][1]->Fill(ZZMass, p0hplus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][2] = nCounted[EnergyIndex][folder][2]*scale;
          hfill[t][2]->Fill(ZZMass, p0minus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][3] = nCounted[EnergyIndex][folder][3]*scale;
          hfill[t][3]->Fill(ZZMass, p0_g1prime2_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][4] = nCounted[EnergyIndex][folder][4]*scale;
          hfill[t][4]->Fill(ZZMass, p0_g1prime4_VAJHU*scale);
          scale = SMscale;
          if (t>0){
            hfill[t][5]->Fill(ZZMass, pg1g2_VAJHU*scale);
          }
          else{
            scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][5]+nCounted[1][2][5]);
            hfill[t][5]->Fill(ZZMass, (2.*(p0plus_VAJHU+p0hplus_VAJHU)-pg1g2_VAJHU)*scale);
          }
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][5] = nCounted[EnergyIndex][folder][5]*scale;
          scale = SMscale;
          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][6]+nCounted[1][2][6]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][6] = nCounted[EnergyIndex][folder][6]*scale;
          hfill[t][6]->Fill(ZZMass, pg1g4_VAJHU*scale);
          scale = SMscale;
          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][7]+nCounted[1][2][7]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][7] = nCounted[EnergyIndex][folder][7]*scale;
          hfill[t][7]->Fill(ZZMass, pg1g1prime2_VAJHU*scale);
          scale = SMscale;
          //          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][8]+nCounted[1][2][8]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][8] = nCounted[EnergyIndex][folder][8]*scale;
          hfill[t][8]->Fill(ZZMass, pg1g1prime4_VAJHU*scale);
        }
        delete tc[EnergyIndex][folder][t];
      }
    }
  }
  for (int ac=1; ac<9; ac++){
    double nTotal[2]={ 0 };
    for (int erg_tev=7; erg_tev<9; erg_tev++){
      for (int folder=0; folder<3; folder++){
        int EnergyIndex = 1;
        if (erg_tev == 7) EnergyIndex = 0;

        nTotal[0] += nCountedScaled[EnergyIndex][folder][0];
        nTotal[1] += nCountedScaled[EnergyIndex][folder][ac];
      }
    }
    if (ac!=8) hfill[0][ac]->Scale(nTotal[0]/nTotal[1]);
    else hfill[0][ac]->Scale(0.5);
  }


  double maxplot=0;
  for (int t=0; t<4; t++){
    for (int ac=0; ac<9; ac++){
      if (SignalOnly==0 && ac<5) maxplot = max(maxplot, hfill[t][ac]->GetMaximum());
      else if (SignalOnly==1 && !(ac<5 && ac>0) && t==0) maxplot = max(maxplot, hfill[t][ac]->GetMaximum());
      hfill[t][ac]->SetLineWidth(2);
      if (t==0 && ac>=5){
        hfill[t][ac]->SetLineStyle(7);
        //        hfill[t][ac]->Add(hfill[1][ac]);
      }
      if (t==1) hfill[t][ac]->SetLineStyle(3);
      if (t==3) hfill[t][ac]->SetLineStyle(9);
      hfill[t][ac]->GetXaxis()->SetLabelFont(42);
      hfill[t][ac]->GetXaxis()->SetLabelOffset(0.007);
      hfill[t][ac]->GetXaxis()->SetLabelSize(0.04);
      hfill[t][ac]->GetXaxis()->SetTitleSize(0.06);
      hfill[t][ac]->GetXaxis()->SetTitleOffset(0.9);
      hfill[t][ac]->GetXaxis()->SetTitleFont(42);
      hfill[t][ac]->GetYaxis()->SetNdivisions(505);
      hfill[t][ac]->GetYaxis()->SetLabelFont(42);
      hfill[t][ac]->GetYaxis()->SetLabelOffset(0.007);
      hfill[t][ac]->GetYaxis()->SetLabelSize(0.04);
      hfill[t][ac]->GetYaxis()->SetTitleSize(0.06);
      hfill[t][ac]->GetYaxis()->SetTitleOffset(1.1);
      hfill[t][ac]->GetYaxis()->SetTitleFont(42);
    }
  }

  TPaveText* pt = new TPaveText(0.15, 0.93, 0.85, 1, "brNDC");
  pt->SetBorderSize(0);
  pt->SetFillStyle(0);
  pt->SetTextAlign(12);
  pt->SetTextFont(42);
  pt->SetTextSize(0.045);
  TText* text = pt->AddText(0.025, 0.45, "#font[61]{CMS}");
  text->SetTextSize(0.044);
  text = pt->AddText(0.165, 0.42, "#font[52]{Simulation}");
  text->SetTextSize(0.0315);
  TString cErgTev = "#font[42]{19.7 fb^{-1} (8 TeV) + 5.1 fb^{-1} (7 TeV)}";
  text = pt->AddText(0.537, 0.45, cErgTev);
  text->SetTextSize(0.0315);

  float lxmin = 0.22;
  float lxwidth = 0.38;
  float lymax = 0.9;
  float lywidth = 0.3;
  float lxmax = lxmin + lxwidth;
  float lymin = lymax;
  if (SignalOnly==0) lymin -= lywidth*4./5.;
  else lymin -= lywidth;

  float lxmin2 = 0.22+0.39;
  float lymax2 = lymax;
  float lxmax2 = lxmin2 + lxwidth;
  float lymin2 = lymax2;
  if (SignalOnly==0) lymin2 -= lywidth*2./5.;
  else lymin2 -= lywidth*4./5.;

  if (SignalOnly==1){
    float lxmin3 = lxmin2;
    float lymax3 = lymax2;
    float lxmax3 = lxmax2;
    float lymin3 = lymin2;

    lxmin2 = lxmin;
    lxmax2 = lxmax;
    lymin2 = lymin;
    lymax2 = lymax;
    lxmin = lxmin3;
    lxmax = lxmax3;
    lymin = lymin3;
    lymax = lymax3;
  }

  float pxmin = 0.756;
  float pymin = 0.76;
  float pxmax = 0.85;
  if (SignalOnly==1){
    pymin -= 0.12;
  }
  float pymax = pymin+0.05;
  TPaveText* ptx = new TPaveText(pxmin, pymin, pxmax, pymax, "brNDC");
  ptx->SetBorderSize(0);
  ptx->SetTextFont(42);
  ptx->SetTextSize(0.04);
  ptx->SetLineColor(1);
  ptx->SetLineStyle(1);
  ptx->SetLineWidth(1);
  ptx->SetFillColor(0);
  ptx->SetFillStyle(0);
  text = ptx->AddText(0.01, 0.01, "gg#rightarrow4l");
  text->SetTextSize(0.04);

  TString canvasname = "cCanvas_MCFMBSM_GenLevel";
  if (SignalOnly==1) canvasname.Append("_SignalOnly");
  TCanvas* cc = new TCanvas(canvasname, "", 8, 30, 800, 800);
  cc->cd();
  gStyle->SetOptStat(0);
  cc->SetFillColor(0);
  cc->SetBorderMode(0);
  cc->SetBorderSize(2);
  cc->SetTickx(1);
  cc->SetTicky(1);
  cc->SetLeftMargin(0.17);
  cc->SetRightMargin(0.05);
  cc->SetTopMargin(0.07);
  cc->SetBottomMargin(0.13);
  cc->SetFrameFillStyle(0);
  cc->SetFrameBorderMode(0);
  cc->SetFrameFillStyle(0);
  cc->SetFrameBorderMode(0);
  cc->SetLogy();

  TLegend* ll;
  TLegend* ll2;

  ll = new TLegend(lxmin2, lymin2, lxmax2, lymax2);
  ll2 = new TLegend(lxmin, lymin, lxmax, lymax);

  ll->SetBorderSize(0);
  ll->SetTextFont(42);
  ll->SetTextSize(0.04);
  ll->SetLineColor(1);
  ll->SetLineStyle(1);
  ll->SetLineWidth(1);
  ll->SetFillColor(0);
  ll->SetFillStyle(0);
  ll2->SetBorderSize(0);
  ll2->SetTextFont(42);
  ll2->SetTextSize(0.04);
  ll2->SetLineColor(1);
  ll2->SetLineStyle(1);
  ll2->SetLineWidth(1);
  ll2->SetFillColor(0);
  ll2->SetFillStyle(0);

  TString strACtitle[9]={ "",
    "f_{a2}=1", "f_{a3}=1", "f_{#Lambda1}=1", "f_{#LambdaQ}=1",
    "f_{a2}=0.5, #phi_{#lower[-0.2]{a2}}=#pi", "f_{a3}=0.5", "f_{#Lambda1}=0.5", "f_{#LambdaQ}=0.5"
  };

  int iDraw = 2 - 2*SignalOnly;

  if (SignalOnly==0) hfill[iDraw][0]->GetYaxis()->SetRangeUser(7e-3, maxplot*15.);
  else{
    double histmin = 7e-3;
    if (hfill[iDraw][0]->GetMinimum()>0) histmin = hfill[iDraw][0]->GetMinimum();
    hfill[iDraw][0]->GetYaxis()->SetRangeUser(histmin, maxplot*2000.);
  }
  hfill[iDraw][0]->GetXaxis()->SetRangeUser(xlimits[0], 800.);

  hfill[iDraw][0]->SetLineColor(kBlack);
  if (SignalOnly==0){
    hfill[iDraw][0]->SetFillColor(kAzure-2);
    hfill[iDraw][0]->SetFillStyle(1001);
  }
  hfill[iDraw][0]->Draw("hist");

  hfill[iDraw][1]->SetLineColor(kBlue);
  hfill[iDraw][1]->Draw("histsame");

  hfill[iDraw][2]->SetLineColor(kRed);
  hfill[iDraw][2]->Draw("histsame");

  hfill[iDraw][3]->SetLineColor(kViolet);
  hfill[iDraw][3]->Draw("histsame");

  hfill[iDraw][4]->SetLineColor(kGreen+2);
  hfill[iDraw][4]->Draw("histsame");

  if (SignalOnly==1){
    hfill[iDraw][5]->SetLineColor(kBlue);
    hfill[iDraw][5]->Draw("histsame");

    hfill[iDraw][6]->SetLineColor(kRed);
    hfill[iDraw][6]->Draw("histsame");

    hfill[iDraw][7]->SetLineColor(kViolet);
    hfill[iDraw][7]->Draw("histsame");

    hfill[iDraw][8]->SetLineColor(kGreen+2);
    hfill[iDraw][8]->Draw("histsame");
  }

  if (SignalOnly==0){
    hfill[1][0]->SetLineColor(kBlack);
    hfill[1][0]->SetLineStyle(3);
    hfill[1][0]->Draw("histsame");
  }

  hfill[iDraw][0]->Draw("histsame");

  TLegendEntry* legendtext;
  if (SignalOnly==0){
    legendtext = ll->AddEntry(hfill[iDraw][0], "SM total", "f");
    legendtext = ll->AddEntry(hfill[1][0], "SM bkg.", "f");
    legendtext->SetFillStyle(1001);
    legendtext->SetFillColor(hfill[1][0]->GetFillColor());
  }
  else{
    legendtext = ll->AddEntry(hfill[iDraw][0], "SM signal", "f");
    legendtext->SetFillStyle(3001);
  }

  if (SignalOnly==0){
    legendtext = ll2->AddEntry(hfill[iDraw][4], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[4].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][4]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][2], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[2].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][2]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][1], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[1].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][1]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][3], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[3].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][3]->GetFillColor());
  }
  else{
    legendtext = ll->AddEntry(hfill[iDraw][4], strACtitle[4].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][4]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][2], strACtitle[2].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][2]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][1], strACtitle[1].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][1]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][3], strACtitle[3].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][3]->GetFillColor());
  }
  if (SignalOnly==1){
    legendtext = ll2->AddEntry(hfill[iDraw][8], strACtitle[8].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][8]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][5], strACtitle[5].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][5]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][7], strACtitle[7].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][7]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][6], strACtitle[6].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][6]->GetFillColor());
  }

  ll->Draw("same");
  ll2->Draw("same");
  ptx->Draw();
  pt->Draw();
  cc->RedrawAxis();
  cc->Update();

  canvasname.Prepend(coutput_common);
  TString canvasname_pdf = canvasname;
  TString canvasname_eps = canvasname;
  TString canvasname_png = canvasname;
  TString canvasname_root = canvasname;
  TString canvasname_c = canvasname;
  canvasname_pdf.Append(".pdf");
  canvasname_eps.Append(".eps");
  canvasname_png.Append(".png");
  canvasname_root.Append(".root");
  canvasname_c.Append(".C");
  cc->SaveAs(canvasname_pdf);
  cc->SaveAs(canvasname_eps);
  cc->SaveAs(canvasname_png);
  cc->SaveAs(canvasname_root);
  cc->SaveAs(canvasname_c);

  foutput->WriteTObject(cc);
  delete ll2;
  delete ll;
  cc->Close();
  delete ptx;
  delete pt;
  for (int t=0; t<4; t++){
    for (int ac=0; ac<5; ac++){
      foutput->WriteTObject(hfill[t][ac]);
      delete hfill[t][ac];
    }
  }
  foutput->Close();
}