示例#1
0
void WCompMvaNoPuMEt()
{
  InpFile = new TFile("MuonHighPU/Muon_WJetsToLNu_S10_MVAnoPUMEt.root");
  //InpFile = new TFile("ElectronHighPU/Ele_WJetsToLNu_S10_MVAnoPUMEt.root");
  //InpFile = new TFile("TauHighPU/Tau_WJetsToLNu_S10_MVAnoPUMEt.root");

  char ylabel[100];
  char histName[100];
  char histName_org[100];
  
  TH1D *diff1[4];
  TH1D *diff2[4];
  TH1D *diff3[4];
  
  TH1D *met[4];
  TH1D *NoPUmet[4];
  TH1D *MVAmet[4];
  TH1D *GENmet[4];
  TH1D *GENmetTrue[4];

  Double_t Range;
  
  //Plot PU distribution
  //==========================
  
  //TCanvas c1("c1","c1",800,700);
  //gStyle->SetOptTitle(0);
  //hPU =(TH1D*)InpFile->Get("h1_Vtx_Good1")->Clone();
  //Double_t PURange=1.1*hPU->GetMaximum();
  //sprintf(ylabel,"Events / %.1f GeV",hPU->GetBinWidth(1));
  //hPU->GetYaxis()->SetTitle(ylabel);
  //hPU->GetYaxis()->SetTitleOffset(1.2);
  //hPU->GetYaxis()->SetTitleSize(0.04);
  //hPU->GetYaxis()->SetLabelSize(0.04);
  //hPU->GetYaxis()->SetRangeUser(0,PURange);
  //hPU->GetXaxis()->SetTitleOffset(1.1);
  //hPU->GetXaxis()->SetTitleSize(0.04);
  //hPU->GetXaxis()->SetLabelSize(0.04);
  //hPU->GetXaxis()->SetTitle("PU");
  //hPU->Draw();
  //TLine l1(7,0,7,PURange);
  //l1.SetLineColor(kRed);
  //l1.SetLineStyle(9);
  //l1.Draw();
  //TLine l2(22,0,22,PURange);
  ////TLine l2(26,0,26,PURange); //Tau channel
  //l2.SetLineColor(kRed);
  //l2.SetLineStyle(9);
  //l2.Draw();

  //c1.SaveAs("PileUpDistribution.png");
  
  //==========================
  
  for(int i(0);i<4;i++)
  {
    sprintf(histName,"met_%d",i);
    sprintf(histName_org,"h1_W_Met_%d",i);
    met[i] =(TH1D*)InpFile->Get(histName_org)->Clone(histName);met[i]->Sumw2();
    
    sprintf(histName,"NoPUmet_%d",i);
    sprintf(histName_org,"h1_W_NoPU_Met_%d",i);
    NoPUmet[i] =(TH1D*)InpFile->Get(histName_org)->Clone(histName);NoPUmet[i]->Sumw2();
    
    sprintf(histName,"MVAmet_%d",i);
    sprintf(histName_org,"h1_W_MVA_Met_%d",i);
    MVAmet[i] =(TH1D*)InpFile->Get(histName_org)->Clone(histName);MVAmet[i]->Sumw2();

    sprintf(histName,"GENmet_%d",i);
    sprintf(histName_org,"h1_W_Gen_Met_%d",i);
    GENmet[i] =(TH1D*)InpFile->Get(histName_org)->Clone(histName);GENmet[i]->Sumw2();

    sprintf(histName,"GENmetTrue_%d",i);
    sprintf(histName_org,"h1_W_genMEtTrue_%d",i);
    GENmetTrue[i] =(TH1D*)InpFile->Get(histName_org)->Clone(histName);GENmetTrue[i]->Sumw2();

    //met =(TH1D*)InpFile->Get("h1_W_Met_0")->Clone();
    //NoPUmet =(TH1D*)InpFile->Get("h1_W_NoPU_Met_0")->Clone();
    //MVAmet =(TH1D*)InpFile->Get("h1_W_MVA_Met_0")->Clone();
    //GENmet =(TH1D*)InpFile->Get("h1_W_Gen_Met_0")->Clone();
    //GENmetTrue =(TH1D*)InpFile->Get("h1_W_genMEtTrue_0")->Clone();

    met[i]->SetFillStyle(3004);
    met[i]->SetLineWidth(2);
    met[i]->SetLineColor(kYellow+1);
    met[i]->SetFillColor(kYellow);
    NoPUmet[i]->SetFillStyle(3005);
    NoPUmet[i]->SetLineWidth(2);
    NoPUmet[i]->SetLineColor(kRed+1);
    NoPUmet[i]->SetFillColor(kRed);
    MVAmet[i]->SetFillStyle(3013);
    MVAmet[i]->SetLineWidth(2);
    MVAmet[i]->SetLineColor(kBlue+3);
    MVAmet[i]->SetFillColor(kBlue);
    //GENmet->SetLineColor(kCyan);
    //GENmetTrue[i]->SetFillStyle(4050);
    GENmetTrue[i]->SetFillStyle(1001);
    GENmetTrue[i]->SetLineWidth(2);
    GENmetTrue[i]->SetLineColor(kGreen+3);
    GENmetTrue[i]->SetFillColor(kGreen);
  
    //sprintf(ylabel,"Events / %.1f GeV",NoPUmet->GetBinWidth(1));
    //NoPUmet->GetYaxis()->SetTitle(ylabel);
    //NoPUmet->GetYaxis()->SetTitleOffset(1.2);
    //NoPUmet->GetYaxis()->SetTitleSize(0.04);
    //NoPUmet->GetYaxis()->SetLabelSize(0.04);

    //sprintf(ylabel,"Events / %.1f GeV",MVAmet[i]->GetBinWidth(1));
    //MVAmet[i]->GetYaxis()->SetTitle(ylabel);
    //MVAmet[i]->GetYaxis()->SetTitleOffset(1.2);
    //MVAmet[i]->GetYaxis()->SetTitleSize(0.04);
    //MVAmet[i]->GetYaxis()->SetLabelSize(0.04);

    //sprintf(ylabel,"Events / %.1f GeV",GENmet[i]->GetBinWidth(1));
    //GENmet[i]->GetYaxis()->SetTitle(ylabel);
    //GENmet[i]->GetYaxis()->SetTitleOffset(1.2);
    //GENmet[i]->GetYaxis()->SetTitleSize(0.04);
    //GENmet[i]->GetYaxis()->SetLabelSize(0.04);

    sprintf(ylabel,"Events / %.1f GeV",GENmetTrue[i]->GetBinWidth(1));
    GENmetTrue[i]->GetYaxis()->SetTitle(ylabel);
    GENmetTrue[i]->GetYaxis()->SetTitleOffset(1.2);
    GENmetTrue[i]->GetYaxis()->SetTitleSize(0.04);
    GENmetTrue[i]->GetYaxis()->SetLabelSize(0.04);

    TLegend *lL =new TLegend(0.7,0.7,0.9,0.85);
    lL->SetFillColor(0); lL->SetBorderSize(0);
    lL->AddEntry(MVAmet[i],"MVA Met","F");
    //lL->AddEntry(GENmet,"Gen Met","L");
    lL->AddEntry(NoPUmet[i],"No PU Met","F");
    lL->AddEntry(met[i],"PFMet","F");
    lL->AddEntry(GENmetTrue[i],"GenMetTrue","F");
    TCanvas *lC0 = new TCanvas("Can","Can",800,800); lC0->cd(); lC0->SetLogy();
    lC0->Divide(1,2,0,0);
    lC0->cd(1)->SetPad(0,0.35,0.95,1.0);
    lC0->cd(1)->SetTopMargin(0.1);
    lC0->cd(1)->SetBottomMargin(0.01);
    lC0->cd(1)->SetLeftMargin(0.15);
    lC0->cd(1)->SetRightMargin(0.07);
    lC0->cd(1)->SetTickx(1);
    lC0->cd(1)->SetTicky(1);
    gStyle->SetTitleOffset(1.100,"Y");
    gStyle->SetLineWidth(2.);
    gStyle->SetTextSize(1.1);
    gStyle->SetLabelSize(0.08,"xy");
    gStyle->SetTitleSize(0.08,"xy");
    gStyle->SetTitleOffset(1.2,"x");
    gStyle->SetTitleOffset(1.0,"y");
    gStyle->SetOptTitle(0);
    TGaxis::SetMaxDigits(3);

    //gPad->SetLogy(1); //Set Log scale in Y axis
    //GENmet->Draw("hist");
    GENmetTrue[i]->Draw("hist");
    //GENmetTrue[i]->Draw();
    //MVAmet->Draw("hist");
    //NoPUmet->Draw("hist");
    NoPUmet[i]->Draw("hist same");
    MVAmet[i]->Draw("hist same");
    //GENmet->Draw("hist same");
    met[i]->Draw("hist same");
    lL->Draw();
  
    lC0->cd(2)->SetPad(0,0,0.95,0.35);
    lC0->cd(2)->SetTopMargin(0.025);
    lC0->cd(2)->SetBottomMargin(0.3);
    lC0->cd(2)->SetLeftMargin(0.15);
    lC0->cd(2)->SetRightMargin(0.07);
    lC0->cd(2)->SetTickx(1);
    lC0->cd(2)->SetTicky(1);

    //Range - Maximum value of Y axis range in Resolution distribution

    if (i==0 || i==2) Range=60;
    if (i==1) Range=50;
    if (i==3) Range=100;
    //Range=50;

    diff1[i] = drawDifference(GENmetTrue[i],NoPUmet[i],"Resolution",Range,20,2);
    diff1[i]->Draw("EX0");
    diff1[i]->Draw("SAME Lhist");
    
    diff2[i] = drawDifference(GENmetTrue[i],MVAmet[i],"",Range,21,4);
    diff2[i]->Draw("SAME EX0");
    diff2[i]->Draw("SAME Lhist");
    
    diff3[i] = drawDifference(GENmetTrue[i],met[i],"",Range,22,5);
    diff3[i]->Draw("SAME EX0");
    diff3[i]->Draw("SAME Lhist");
    
    TLegend *rL =new TLegend(0.6,0.63,0.9,0.95);
    //TLegend *rL =new TLegend(0.2,0.63,0.5,0.95);
    rL->SetFillColor(0); rL->SetBorderSize(0);
    rL->AddEntry(diff1[i],"(NoPUmet-genMEtTrue)/genMEtTrue","PL");
    rL->AddEntry(diff2[i],"(MVAmet-genMEtTrue)/genMEtTrue","PL");
    rL->AddEntry(diff3[i],"(PFmet-genMEtTrue)/genMEtTrue","PL");
    rL->Draw();

    TLine *line = new TLine(0,0,100,0);
    line->SetLineStyle(2);
    line->SetLineColor(8);
    line->Draw();
  
    sprintf(histName,"WMetComp_WJetsToLNu_%d.png",i);
    lC0->SaveAs(histName);
  }
}
int theoryStudy_separate(const TString BaseName)
{
  TString tmpTStr;
  char tmpName[30],tmpName_org[30];
  int Numb;

  TFile *f_theory;
  TFile *f_Data;
  double fScale[14]={0};
  double fScale_WtoMu[14]={0};
  double fScale_WtoEle[14]={0};
  double fScale_WptoMu[14] = {0, 64.48, 1.105, 8.274, 9.716, 7.226, 8.534, 5.76, 6.4783, 4.5879, 1.3952, 0.52169, 0.2662, 0.09476};
  double fScale_WmtoMu[14] = {0, 45.388, 1.601, 4.628, 6.315, 4.866, 5.935, 4.1334, 4.6873, 3.4607, 1.0583, 0.36488, 0.18399, 0.063812};
  double fScale_WptoEle[14] = {0, 74.18, 2.079, 8.808, 10.496, 7.646, 8.934, 5.998, 6.6528, 4.7955, 1.4991, 0.4733, 0.28867, 0.09178};
  double fScale_WmtoEle[14] = {0, 48.427, 1.315, 5.692, 6.855, 5.33, 6.332, 4.3037, 4.9102, 3.7312, 1.1115, 0.38448, 0.19356, 0.062427};
  
  for(int i(0);i<14;i++)
  {
    fScale_WtoMu[i] = sqrt((fScale_WptoMu[i]*fScale_WptoMu[i])+(fScale_WmtoMu[i]*fScale_WmtoMu[i]));
    fScale_WtoEle[i] = sqrt((fScale_WptoEle[i]*fScale_WptoEle[i])+(fScale_WmtoEle[i]*fScale_WmtoEle[i]));
  } 
  if(BaseName=="WInclToMuNu")
  {
    for(int i(0);i<14;i++)
    {
      fScale[i] = fScale_WtoMu[i];
      cout << "fScale : " << fScale[i] << "\t fScale_WtoMu : " << fScale_WtoMu[i] << endl;
    }
    f_theory = new TFile("Theory_Muon.root");
    f_Data = new TFile("Result_WinclMu.root");
  }
  if(BaseName=="WInclToEleNu")
  {
    for(int i(0);i<14;i++)
    {
      fScale[i] = fScale_WtoEle[i];
      cout << "fScale : " << fScale[i] << "\t fScale_WtoEle : " << fScale_WtoEle[i] << endl;
    }
    f_theory = new TFile("Theory_Ele.root");
    f_Data = new TFile("Result_WinclEle.root");
  }

  TH1D *hResbosLog30 = new TH1D("hResbosLog30","hResbosLog30",13,WptLogBins);hResbosLog30->Sumw2();
  TH1D *hResbosLog31 = new TH1D("hResbosLog31","hResbosLog31",13,WptLogBins);hResbosLog31->Sumw2();
  TH1D *hResbosLog34 = new TH1D("hResbosLog34","hResbosLog34",13,WptLogBins);hResbosLog34->Sumw2();
  TH1D *hFewzLog     = new TH1D("hFewzLog","hFewzLog",13,WptLogBins);hFewzLog->Sumw2();
  TH1D *hPowhegLog   = new TH1D("hPowhegLog","hPowhegLog",13,WptLogBins);hPowhegLog->Sumw2();
  TH1D *hDataLog     = new TH1D("hDataLog","hDataLog",13,WptLogBins);hDataLog->Sumw2();
  TH1D *hDataNoLog   = new TH1D("hDataNoLog","hDataNoLog",13,WptBins);hDataNoLog->Sumw2();
  TH1D *hDataErrBand = new TH1D("hDataErrBand","hDataErrBand",13,WptLogBins);hDataErrBand->Sumw2();
  TH1D *hPowhegErrBand = new TH1D("hPowhegErrBand","hPowhegErrBand",13,WptLogBins);hPowhegErrBand->Sumw2();
  TH1D *hPowhegErrBandPDF = new TH1D("hPowhegErrBandPDF","hPowhegErrBandPDF",13,WptLogBins);hPowhegErrBandPDF->Sumw2();
  TH1D *hFewzErrBand = new TH1D("hFewzErrBand","hFewzErrBand",13,WptLogBins);hFewzErrBand->Sumw2();
  TH1D *hFewzTheoryErrBand = new TH1D("hFewzTheoryErrBand","hFewzTheoryErrBand",13,WptLogBins);hFewzTheoryErrBand->Sumw2();
  //FEWZ Scale Syst
  TH1D *hFewzScale = new TH1D("hFewzScale","hFewzScale",13,WptLogBins);hFewzScale->Sumw2();
  TH1D *hFewzScaleErrBand = new TH1D("hFewzScaleErrBand","hFewzScaleErrBand",13,WptLogBins);hFewzScaleErrBand->Sumw2();
  TH1D *hStatErr = new TH1D("hStatErr","hStatErr",13,WptLogBins);hStatErr->Sumw2();
  
  TH1D* lResbos[7];
  TH1D* lResbos30;
  TH1D* lResbos31;
  TH1D* lResbos34;
  TH1D* lFEWZ;
  TH1D* lPowheg;
  TH1D* lData;
  TH1D* hRD;
  
  for( int i(0);i<7;i++)
  {
    Numb = 29+i;
    sprintf(tmpName_org,"hResbos%d",Numb);
    sprintf(tmpName,"lResbos_%d",i);
    lResbos[i] = (TH1D*)f_theory->Get(tmpName_org)->Clone(tmpName);
  }

  lResbos30 = (TH1D*)f_theory->Get("hResbos30")->Clone();
  lResbos31 = (TH1D*)f_theory->Get("hResbos31")->Clone();
  lResbos34 = (TH1D*)f_theory->Get("hResbos34")->Clone();
  lFEWZ   = (TH1D*)f_theory->Get("hxsec")->Clone();
  
  lPowheg = (TH1D*)f_Data->Get("SVD_BornGen")->Clone();
  orgPowheg = (TH1D*)f_Data->Get("SVD_BornGen")->Clone();
  lData   = (TH1D*)f_Data->Get("BornEffCorr")->Clone();
  hRD     = (TH1D*)f_Data->Get("data_Rec")->Clone();
  
  for( int ipt(1);ipt<nBins;ipt++)
  {
    double tmp = sqrt(hRD->GetBinContent(ipt));
    hRD->SetBinError(ipt,tmp);
    cout<<ipt<<"\t"<<hRD->GetBinContent(ipt)<<"\t"<<hRD->GetBinError(ipt)<<endl;
  }

  lPowheg->Scale(1./18.429);
  lData->Scale(1./18.429);
  hRD->Scale(1./18.429);
  
  for( int ipt(1);ipt<nBins;ipt++)
  {
    cout<<ipt<<"\t"<<hRD->GetBinError(ipt)<<"\t"<<lData->GetBinError(ipt)<<endl;
  }

  cout << "Resbos Total Xsec: " << lResbos30->Integral() << endl;
  cout << "Data Total Xsec: " << lData->Integral() << endl;

  Double_t resb30[nBins-1];
  Double_t errMax[nBins-1];
  Double_t errMin[nBins-1];
  double tmpVal,tmpDiff;

  for( int ipt(0);ipt<nBins-1;ipt++)
  {
    resb30[ipt] = lResbos30->GetBinContent(ipt+1)/hDataNoLog->GetXaxis()->GetBinWidth(ipt+1);
    double norVal  = lResbos[1]->GetBinContent(ipt+1);
    errMax[ipt] = -99999;
    errMin[ipt] = 990009;
    for (int i(0);i<7;i++)
    {
      tmpVal  = lResbos[i]->GetBinContent(ipt+1);
      tmpDiff = tmpVal - norVal;
      if( tmpDiff > errMax[ipt] ) errMax[ipt] = tmpDiff;
      if( tmpDiff < errMin[ipt] ) errMin[ipt] = tmpDiff;
    }
    
    if (errMax[ipt] < 0) errMax[ipt] = 0.;
    if (errMin[ipt] > 0) errMin[ipt] = 0.;
    if (errMin[ipt] < 0) errMin[ipt] = -errMin[ipt];
    errMax[ipt] = errMax[ipt]/hDataNoLog->GetXaxis()->GetBinWidth(ipt+1);
    errMin[ipt] = errMin[ipt]/hDataNoLog->GetXaxis()->GetBinWidth(ipt+1);
  }
  
  Double_t errFewz[nBins-1];
  Double_t vPowheg[nBins-1];
  Double_t vFewz[nBins-1];
  Double_t resbVal[nBins-1],errResbosDataLo[nBins-1],errResbosDataHi[nBins-1];
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    hResbosLog30->SetBinContent(ipt,lResbos30->GetBinContent(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt) );
    hResbosLog31->SetBinContent(ipt,lResbos31->GetBinContent(ipt));
    hResbosLog34->SetBinContent(ipt,lResbos34->GetBinContent(ipt));
    
    hFewzLog->SetBinContent(ipt,lFEWZ->GetBinContent(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    //hFewzLog->SetBinError(ipt,lFEWZ->GetBinError(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    hFewzLog->SetBinError(ipt,sqrt((lFEWZ->GetBinError(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt))*(lFEWZ->GetBinError(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt))+(fScale[ipt]/hDataNoLog->GetXaxis()->GetBinWidth(ipt))*(fScale[ipt]/hDataNoLog->GetXaxis()->GetBinWidth(ipt))));
    
    hPowhegLog->SetBinContent(ipt,lPowheg->GetBinContent(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    hPowhegLog->SetBinError(ipt,sqrt(lPowheg->GetBinContent(ipt))/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    
    hDataLog->SetBinContent(ipt,lData->GetBinContent(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    hDataLog->SetBinError(ipt,lData->GetBinError(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    hDataErrBand->SetBinContent(ipt,1.);
    hDataErrBand->SetBinError(ipt,lData->GetBinError(ipt)/lData->GetBinContent(ipt));
    hStatErr->SetBinContent(ipt,1.);
    hStatErr->SetBinError(ipt,hRD->GetBinError(ipt)/lData->GetBinContent(ipt));
    
    hPowhegErrBand->SetBinContent(ipt,hPowhegLog->GetBinContent(ipt)/hDataLog->GetBinContent(ipt));
    hPowhegErrBand->SetBinError(ipt,sqrt(orgPowheg->GetBinContent(ipt))/orgPowheg->GetBinContent(ipt));
    hPowhegErrBandPDF->SetBinContent(ipt,hPowhegLog->GetBinContent(ipt)/hDataLog->GetBinContent(ipt));
    //hPowhegErrBandPDF->SetBinError(ipt,lPowheg->GetBinError(ipt)/hDataLog->GetBinContent(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    hPowhegErrBandPDF->SetBinError(ipt,sqrt(orgPowheg->GetBinContent(ipt))/orgPowheg->GetBinContent(ipt)+lPowheg->GetBinError(ipt)/hDataLog->GetBinContent(ipt)/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    hFewzErrBand->SetBinContent(ipt,hFewzLog->GetBinContent(ipt)/hDataLog->GetBinContent(ipt));
    hFewzErrBand->SetBinError(ipt,0.01);
    hFewzScale->SetBinContent(ipt,hFewzLog->GetBinContent(ipt)/hDataLog->GetBinContent(ipt));  
    hFewzScale->SetBinError(ipt,fScale[ipt]/hDataNoLog->GetXaxis()->GetBinWidth(ipt));
    hFewzTheoryErrBand->SetBinContent(ipt,hFewzLog->GetBinContent(ipt)/hDataLog->GetBinContent(ipt));
    //hFewzTheoryErrBand->SetBinError(ipt,hFewzLog->GetBinError(ipt)/hDataLog->GetBinContent(ipt));
    //hFewzTheoryErrBand->SetBinError(ipt,0.01+hFewzLog->GetBinError(ipt)/hDataLog->GetBinContent(ipt));
    hFewzTheoryErrBand->SetBinError(ipt,0.01+(hFewzLog->GetBinError(ipt)+hFewzScale->GetBinError(ipt))/hDataLog->GetBinContent(ipt));
    hFewzScaleErrBand->SetBinContent(ipt,hFewzLog->GetBinContent(ipt)/hDataLog->GetBinContent(ipt));
    hFewzScaleErrBand->SetBinError(ipt,0.01+hFewzScale->GetBinError(ipt)/hDataLog->GetBinContent(ipt));
    
    resbVal[ipt-1]=hResbosLog30->GetBinContent(ipt)/hDataLog->GetBinContent(ipt);
    errResbosDataLo[ipt-1]=errMin[ipt-1]/hDataLog->GetBinContent(ipt);
    errResbosDataHi[ipt-1]=errMax[ipt-1]/hDataLog->GetBinContent(ipt);
    
    cout<<ipt<<"\t"<<errMin[ipt-1]<<"\t"<<errMax[ipt-1]<<"\t"<<hDataLog->GetBinContent(ipt)<<"\t"<<errResbosDataLo[ipt-1]<<"\t"<<errResbosDataHi[ipt-1]<<endl;
    //cout<<ipt<<"\t"<<hResbosLog30->GetBinContent(ipt)<<"\t"<<hDataLog->GetBinContent(ipt)<<"\t"<<hPowhegLog->GetBinError(ipt)<<endl;
  }

  hDataLog->SetMarkerStyle(kFullCircle); hDataLog->SetMarkerColor(kBlack); hDataLog->SetMarkerSize(1);
  hStatErr->SetMarkerStyle(kFullCircle); hStatErr->SetMarkerColor(kBlack); hStatErr->SetMarkerSize(0.6);

  TGraphErrors *hData = new TGraphErrors(hDataLog);
  TGraphErrors *hPowheg = new TGraphErrors(hPowhegLog);
  TGraphErrors *hFewz = new TGraphErrors(hFewzLog);
  TGraphAsymmErrors* hResbos = new TGraphAsymmErrors(nBins-1, ax, resb30, aex, aex, errMin, errMax);
  TGraphAsymmErrors* ResbosErrBand = new TGraphAsymmErrors(nBins-1, ax, resbVal, aex, aex, errResbosDataLo, errResbosDataHi);
  TGraphErrors* pRatio = new TGraphErrors(hPowhegErrBand);
  TGraphErrors* pRatioPDF = new TGraphErrors(hPowhegErrBandPDF);
  TGraphErrors* fRatio = new TGraphErrors(hFewzErrBand);
  TGraphErrors* fTheoryRatio = new TGraphErrors(hFewzTheoryErrBand);
  TGraphErrors* fScaleRatio = new TGraphErrors(hFewzScaleErrBand);
  
  TGraphErrors* dataErrBand = new TGraphErrors(hDataErrBand);
  dataErrBand->SetFillColor(kBlack);
  dataErrBand->SetFillStyle(3354);
  
  ResbosErrBand->SetFillColor(kBlue-7);
  ResbosErrBand->SetFillStyle(3001);
  
  //pRatio->SetFillColor(kRed-7);
  pRatio->SetFillColor(kRed-10);
  pRatio->SetFillStyle(3001);
  
  pRatioPDF->SetFillColor(kRed+2);
  pRatioPDF->SetFillStyle(3001);
  
  fRatio->SetFillColor(kGreen);
  fRatio->SetFillStyle(3001);
  
  //fTheoryRatio->SetFillColor(kGreen-9);
  fTheoryRatio->SetFillColor(kGreen+3);
  fTheoryRatio->SetFillStyle(3001);

  fScaleRatio->SetFillColor(kGreen+7);
  fScaleRatio->SetFillStyle(3001);

  hFewz->SetFillColor(kGreen);
  hFewz->SetFillStyle(3305);

  hPowheg->SetFillColor(kRed);
  hPowheg->SetFillStyle(3345);
  hResbos->SetFillColor(kBlue);
  hResbos->SetFillStyle(3354);

  TLegend *lL =new TLegend(0.2,0.2,0.52,0.38); lL->SetFillColor(0); lL->SetBorderSize(0);
  lL->AddEntry(hData,"Unfolded","PL");
  lL->AddEntry(hPowheg,"Powheg CT10 NLO","f");
  lL->AddEntry(hFewz,"FEWZ CT10 NNLO","f");
  lL->AddEntry(hResbos,"ResBos CT10 NNLO","f");

  TPaveText *tb = new TPaveText(0.2,0.39,0.52,0.5,"NDC");
  tb->SetBorderSize(0);
  tb->SetFillStyle(0);
  tb->AddText("18.43 pb^{-1} at #sqrt{s} = 8 TeV");
  if (BaseName=="WpToMuNu")
    tb->AddText("W^{+} #rightarrow #mu^{+} #nu");
  if (BaseName=="WmToMuNu")
    tb->AddText("W^{-} #rightarrow #mu^{-} #bar{#nu}");
  if (BaseName=="WInclToMuNu")
    tb->AddText("W #rightarrow #mu #nu");
  if (BaseName=="WpToEleNu")
    tb->AddText("W^{+} #rightarrow e^{+} #nu");
  if (BaseName=="WmToEleNu")
    tb->AddText("W^{-} #rightarrow e^{-} #bar{#nu}");
  if (BaseName=="WInclToEleNu")
    tb->AddText("W #rightarrow e #nu");

  TCanvas *lC1 = new TCanvas("Can","Can",800,840); lC1->cd(); lC1->SetLogy();
  lC1->cd(1)->SetPad(0,0.05,0.95,1.0);
  lC1->cd(1)->SetTopMargin(0.05);
  lC1->cd(1)->SetBottomMargin(0.1);
  lC1->cd(1)->SetLeftMargin(0.15);
  lC1->cd(1)->SetRightMargin(0.07);
  lC1->cd(1)->SetTickx(1);
  lC1->cd(1)->SetTicky(1);
  gStyle->SetLineWidth(2.);
  gStyle->SetOptStat(0);
  gStyle->SetHatchesSpacing(0.75);
  gStyle->SetHatchesLineWidth(2);
  gPad->SetLogx(1);
  gPad->SetLogy(1);

  hPowheg->GetYaxis()->SetRangeUser(1e-4,5*resb30[0]);
  hPowheg->SetTitle("");
  hPowheg->GetYaxis()->SetTitle("Cross-section [pb (GeV/c)^{-1}]");
  hPowheg->GetXaxis()->SetTitle("W p_{T}");
  hPowheg->GetXaxis()->SetTitleOffset(1.);
  hPowheg->GetYaxis()->SetTitleOffset(1.5);
  hPowheg->GetYaxis()->SetTitleSize(0.03);
  hPowheg->GetYaxis()->SetLabelSize(0.03);
  hPowheg->GetXaxis()->SetTitleSize(0.03);
  hPowheg->GetXaxis()->SetLabelSize(0.03);
  
  hPowheg->Draw("A2");
  hFewz->Draw("2");
  hResbos->Draw("2");
  hData->Draw("p");
  lL->Draw();
  tb->Draw();
  
  if(BaseName=="WInclToMuNu")
    sprintf(tmpName,"winclmnCrossSec.png");
  if (BaseName=="WInclToEleNu")
    sprintf(tmpName,"winclenCrossSec.png");
  lC1->SaveAs(tmpName);
  
  TCanvas *lC2 = new TCanvas("Can","Can",800,800); lC2->cd(); lC2->SetLogy();
  lC2->Divide(1,3,0,0);
  lC2->cd(1)->SetPad(0,0.67,0.95,0.95);
  lC2->cd(1)->SetTopMargin(0.05);
  lC2->cd(1)->SetBottomMargin(0.01);
  lC2->cd(1)->SetLeftMargin(0.15);
  lC2->cd(1)->SetRightMargin(0.07);
  lC2->cd(1)->SetTickx(1);
  lC2->cd(1)->SetTicky(1);
  lC2->cd(1)->SetLogx(1);

  TPaveText *tb1 = new TPaveText(0.15,0.82,0.35,0.92,"NDC");
  tb1->SetBorderSize(0);
  tb1->SetFillStyle(0);
  tb1->SetTextSize(0.12);
  tb1->AddText("ResBos");
  TLegend *rL1 =new TLegend(0.2,0.05,0.86,0.15); rL1->SetFillColor(0); rL1->SetBorderSize(0);
  rL1-> SetNColumns(3);
  rL1->AddEntry(ResbosErrBand,"Theory unc. (gen)","F");
  rL1->AddEntry(hStatErr,"Statistic error (data)","PLE1");
  rL1->AddEntry(dataErrBand,"Stat. + Syst. (data)","F");
  rL1->SetTextSize(0.07);

  drawDifference(hResbosLog30,hDataLog,hDataErrBand,pRatio,1,pRatio,ResbosErrBand,hStatErr,fScaleRatio);
  rL1->Draw();
  tb1->Draw();

  lC2->cd(2)->SetPad(0,0.37,0.95,0.65);
  lC2->cd(2)->SetTopMargin(0.01);
  lC2->cd(2)->SetBottomMargin(0.01);
  lC2->cd(2)->SetLeftMargin(0.15);
  lC2->cd(2)->SetRightMargin(0.07);
  lC2->cd(2)->SetTickx(1);
  lC2->cd(2)->SetTicky(1);
  lC2->cd(2)->SetLogx(1);

  TPaveText *tb2 = new TPaveText(0.15,0.82,0.35,0.92,"NDC");
  tb2->SetBorderSize(0);
  tb2->SetFillStyle(0);
  tb2->SetTextSize(0.12);
  tb2->AddText("Powheg");
  TLegend *rL2 =new TLegend(0.2,0.05,0.68,0.30); rL2->SetFillColor(0); rL2->SetBorderSize(0);
  rL2-> SetNColumns(2);
  rL2->AddEntry(pRatioPDF,"PDF unc. (gen)","F");
  rL2->AddEntry(hStatErr,"Statistic error (data)","PLE1");
  rL2->AddEntry(pRatio,"Statistical unc. (gen)","F");
  rL2->AddEntry(dataErrBand,"Stat. + Syst. (data)","F");
  rL2->SetTextSize(0.07);

  drawDifference(hPowhegLog,hDataLog,hDataErrBand,pRatio,2,pRatioPDF,ResbosErrBand,hStatErr,fScaleRatio);
  rL2->Draw();
  tb2->Draw();

  lC2->cd(3)->SetPad(0,0.07,0.95,0.35);
  lC2->cd(3)->SetTopMargin(0.01);
  lC2->cd(3)->SetBottomMargin(0.05);
  lC2->cd(3)->SetLeftMargin(0.15);
  lC2->cd(3)->SetRightMargin(0.07);
  lC2->cd(3)->SetTickx(1);
  lC2->cd(3)->SetTicky(1);
  lC2->cd(3)->SetLogx(1);

  TPaveText *tb3 = new TPaveText(0.15,0.82,0.35,0.92,"NDC");
  tb3->SetBorderSize(0);
  tb3->SetFillStyle(0);
  tb3->SetTextSize(0.12);
  tb3->AddText("Fewz");
  TLegend *rL3 =new TLegend(0.2,0.1,0.68,0.30); rL3->SetFillColor(0); rL3->SetBorderSize(0);
  rL3-> SetNColumns(2);
  rL3->AddEntry(fTheoryRatio,"PDF unc. (gen)","F");
  rL3->AddEntry(fScaleRatio,"Scale unc. (gen)","F");
  rL3->AddEntry(hStatErr,"Statistic error (data)","PLE1");
  rL3->AddEntry(fRatio,"Statistical unc. (gen)","F");
  rL3->AddEntry(dataErrBand,"Stat. + Syst. (data)","F");
  rL3->SetTextSize(0.07);

  drawDifference(hFewzLog,hDataLog,hDataErrBand,fRatio,3,fTheoryRatio,ResbosErrBand,hStatErr,fScaleRatio);
  rL3->Draw();
  tb3->Draw();

  if(BaseName=="WInclToMuNu")
    sprintf(tmpName,"winclmnRatioTheoData.png");
  if (BaseName=="WInclToEleNu")
    sprintf(tmpName,"winclenRatioTheoData.png");
  lC2->SaveAs(tmpName);

  return 0;
}
示例#3
0
void CompMvaNoPuMEt()
{
//  InpFile = new TFile("ElectronHighPU/Ele_WToENu_S10_NoPUMEt.root");
//  InpFile = new TFile("ElectronHighPU/Ele_WJets_S10_MVAnoPUMEt.root");
//  InpFile = new TFile("ElectronHighPU/Ele_TTJets_S10_MVAnoPUMEt.root");
//  InpFile = new TFile("ElectronHighPU/Ele_ZG_Incl_S10_MVAnoPUMEt.root");
//  InpFile = new TFile("ElectronHighPU/Ele_ZGToNuNuG_S10_MVAnoPUMEt.root");
  InpFile = new TFile("ElectronHighPU/Ele_DYJetsToLL_S10_MVAnoPUMEt.root");

  char ylabel[100];

  TH1D *met;
  TH1D *NoPUmet;

  met =(TH1D*)InpFile->Get("h1_W_Met")->Clone();
  NoPUmet =(TH1D*)InpFile->Get("h1_W_NoPU_Met")->Clone();
  MVAmet =(TH1D*)InpFile->Get("h1_W_MVA_Met")->Clone();
  GENmet =(TH1D*)InpFile->Get("h1_W_Gen_Met")->Clone();

//  met =(TH1D*)InpFile->Get("h1_Z_Met")->Clone();
//  NoPUmet =(TH1D*)InpFile->Get("h1_Z_NoPU_Met")->Clone();
//  MVAmet =(TH1D*)InpFile->Get("h1_Z_MVA_Met")->Clone();

  met->SetLineColor(kBlack);
  NoPUmet->SetLineColor(kRed);
  MVAmet->SetLineColor(kBlue);
  GENmet->SetLineColor(kCyan);
  
//  sprintf(ylabel,"Events / %.1f GeV",NoPUmet->GetBinWidth(1));
//  NoPUmet->GetYaxis()->SetTitle(ylabel);
//  NoPUmet->GetYaxis()->SetTitleOffset(1.2);
//  NoPUmet->GetYaxis()->SetTitleSize(0.04);
//  NoPUmet->GetYaxis()->SetLabelSize(0.04);

  sprintf(ylabel,"Events / %.1f GeV",MVAmet->GetBinWidth(1));
  MVAmet->GetYaxis()->SetTitle(ylabel);
  MVAmet->GetYaxis()->SetTitleOffset(1.2);
  MVAmet->GetYaxis()->SetTitleSize(0.04);
  MVAmet->GetYaxis()->SetLabelSize(0.04);

//  sprintf(ylabel,"Events / %.1f GeV",GENmet->GetBinWidth(1));
//  GENmet->GetYaxis()->SetTitle(ylabel);
//  GENmet->GetYaxis()->SetTitleOffset(1.2);
//  GENmet->GetYaxis()->SetTitleSize(0.04);
//  GENmet->GetYaxis()->SetLabelSize(0.04);

  TLegend *lL =new TLegend(0.7,0.7,0.9,0.85);
  lL->SetFillColor(0); lL->SetBorderSize(0);
  lL->AddEntry(MVAmet,"MVA Met","L");
//  lL->AddEntry(GENmet,"Gen Met","L");
  lL->AddEntry(NoPUmet,"No PU Met","L");
  lL->AddEntry(met,"Met","L");
  TCanvas *lC0 = new TCanvas("Can","Can",800,800); lC0->cd(); lC0->SetLogy();
  lC0->Divide(1,2,0,0);
  lC0->cd(1)->SetPad(0,0.35,0.95,1.0);
  lC0->cd(1)->SetTopMargin(0.1);
  lC0->cd(1)->SetBottomMargin(0.01);
  lC0->cd(1)->SetLeftMargin(0.15);
  lC0->cd(1)->SetRightMargin(0.07);
  lC0->cd(1)->SetTickx(1);
  lC0->cd(1)->SetTicky(1);
  gStyle->SetTitleOffset(1.100,"Y");
  gStyle->SetLineWidth(2.);
  gStyle->SetTextSize(1.1);
  gStyle->SetLabelSize(0.08,"xy");
  gStyle->SetTitleSize(0.08,"xy");
  gStyle->SetTitleOffset(1.2,"x");
  gStyle->SetTitleOffset(1.0,"y");
  gStyle->SetOptTitle(0);
  TGaxis::SetMaxDigits(3);

//  gPad->SetLogy(1);
//  GENmet->Draw("hist");
  MVAmet->Draw("hist");
//  NoPUmet->Draw("hist");
  NoPUmet->Draw("hist same");
  MVAmet->Draw("hist same");
//  GENmet->Draw("hist same");
  met->Draw("hist same");
  lL->Draw();
  
  lC0->cd(2)->SetPad(0,0,0.95,0.35);
  lC0->cd(2)->SetTopMargin(0.025);
  lC0->cd(2)->SetBottomMargin(0.3);
  lC0->cd(2)->SetLeftMargin(0.15);
  lC0->cd(2)->SetRightMargin(0.07);
  lC0->cd(2)->SetTickx(1);
  lC0->cd(2)->SetTicky(1);
  drawDifference(met,NoPUmet);
//  lC0->SaveAs("WMetComp_TTJets.png");
//  lC0->SaveAs("ZMetComp_TTJets.png");
//  lC0->SaveAs("WMetComp_Z_Incl.png");
//  lC0->SaveAs("ZMetComp_Z_Incl.png");
//  lC0->SaveAs("WMetComp_WJetsToLNu.png");
//  lC0->SaveAs("ZMetComp_WJetsToLNu.png");
//  lC0->SaveAs("WMetComp_ZGToNuNuG.png");
//  lC0->SaveAs("ZMetComp_ZGToNuNuG.png");
  lC0->SaveAs("WMetComp_DYJets.png");
}
void addNuisanceWithToys(std::string iFileName,std::string iChannel,std::string iBkg,std::string iEnergy,std::string iName,std::string iDir,bool iRebin=true,bool iVarBin=false,int iFitModel=1,int iFitModel1=1,double iFirst=150,double iLast=1500,std::string iSigMass="800",double iSigScale=0.1,int iNToys=1000) { 
  std::cout << "======> " << iDir << "/" << iBkg << " -- " << iFileName << std::endl;  
  if(iVarBin) std::cout << "option not implemented yet!";
  if(iVarBin) return;
  //double lFirst = 200;
  //double lLast  = 1500;
  double lFirst = iFirst;
  double lLast  = iLast;

  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "Using Initial fit model: " << iFitModel << ", fitting range: " << iFirst << "-" << iLast << " , using alternative fit model: " << iFitModel1 << std::endl; 
  std::cout << "===================================================================================================================================================" <<std::endl;

  TFile *lFile = new TFile(iFileName.c_str());
  TH1F  *lH0   = (TH1F*) lFile->Get((iDir+"/"+iBkg).c_str());
  TH1F  *lData = (TH1F*) lFile->Get((iDir+"/data_obs").c_str());
  TH1F  *lSig = 0;

  // for now, use bbH signal for testing in b-tag and ggH in no-btag
  if(iDir.find("_btag") != std::string::npos) lSig = (TH1F*)lFile->Get((iDir+"/bbH"+iSigMass+"_fine_binning").c_str());
  else lSig = (TH1F*)lFile->Get((iDir+"/ggH"+iSigMass+"_fine_binning").c_str());

  TH1F *lH0Clone = (TH1F*)lH0->Clone("lH0Clone");     // binning too fine as of now? start by rebinning
  TH1F *lDataClone = (TH1F*)lData->Clone("lDataClone");   
  TH1F *lSigClone = (TH1F*)lSig->Clone("lSigClone");  
 // lH0Clone->Rebin(2);
 // lDataClone->Rebin(2);
 // lSigClone->Rebin(2);

  lSig->Rebin(10);  

  //Define the fit function
  RooRealVar lM("m","m" ,0,5000);
  lM.setRange(lFirst,lLast);
  RooRealVar lA("a","a" ,50,  0.1,200);
  RooRealVar lB("b","b" ,0.0 , -10.5,10.5);
  RooRealVar lA1("a1","a1" ,50,  0.1,1000);
  RooRealVar lB1("b1","b1" ,0.0 , -10.5,10.5);

  RooDataHist *pH0  =  new RooDataHist("Data","Data" ,RooArgList(lM),lH0);
  double lNB0 = lH0->Integral(lH0->FindBin(lFirst),lH0->FindBin(lLast));
  double lNSig0 = lSig->Integral(lSig->FindBin(lFirst),lSig->FindBin(lLast));
 //lNB0=500;
// lNSig0=500;
 lSig->Scale(iSigScale*lNB0/lNSig0);                                         // scale signal to iSigScale*(Background yield), could try other options
 lNSig0 = lSig->Integral(lSig->FindBin(lFirst),lSig->FindBin(lLast));        // readjust norm of signal hist   
  
  //Generate the "default" fit model 

  RooGenericPdf *lFit  = 0; lFit = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) lFit = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) {lA.setVal(0.3); lB.setVal(0.5);}
  if(iFitModel == 2) lFit = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB));
  if(iFitModel == 2) {lA.setVal(0.01); lA.setRange(0,10); }
  if(iFitModel == 3) lFit = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB));
 
  // Generate the alternative model
  
  RooGenericPdf *lFit1  = 0; lFit1 = new RooGenericPdf("genPdf","exp(-m/(a1+b1*m))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) lFit1 = new RooGenericPdf("genPdf","exp(-a1*pow(m,b1))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) {lA1.setVal(0.3); lB1.setVal(0.5);}
  if(iFitModel1 == 2) lFit1 = new RooGenericPdf("genPdf","a1*exp(b1*m)",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 2) {lA1.setVal(0.01); lA1.setRange(0,10); }
  if(iFitModel1 == 3) lFit1 = new RooGenericPdf("genPdf","a1/pow(m,b1)",RooArgList(lM,lA1,lB1));
  
  //=============================================================================================================================================
  //Perform the tail fit and generate the shift up and down histograms
  //=============================================================================================================================================

  RooFitResult  *lRFit = 0;
  lRFit = lFit->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(lFirst,lLast),RooFit::Strategy(0)); 
  TMatrixDSym lCovMatrix   = lRFit->covarianceMatrix(); 
  TMatrixD  lEigVecs(2,2);    lEigVecs = TMatrixDSymEigen(lCovMatrix).GetEigenVectors();
  TVectorD  lEigVals(2);      lEigVals = TMatrixDSymEigen(lCovMatrix).GetEigenValues();
  cout << " Ve---> " << lEigVecs(0,0) << " -- " << lEigVecs(1,0) << " -- " << lEigVecs(0,1) << " -- " << lEigVecs(1,1) << endl;
  cout << " Co---> " << lCovMatrix(0,0) << " -- " << lCovMatrix(1,0) << " -- " << lCovMatrix(0,1) << " -- " << lCovMatrix(1,1) << endl;
  double lACentral = lA.getVal();
  double lBCentral = lB.getVal();
  lEigVals(0) = sqrt(lEigVals(0));
  lEigVals(1) = sqrt(lEigVals(1));
  cout << "===> " << lEigVals(0) << " -- " << lEigVals(1) << endl;
  
  TH1F* lH     = (TH1F*) lFit->createHistogram("fit" ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral + lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral + lEigVals(0)*lEigVecs(1,0));
  TH1F* lHUp   = (TH1F*) lFit->createHistogram("Up"  ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral - lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral - lEigVals(0)*lEigVecs(1,0));
  TH1F* lHDown = (TH1F*) lFit->createHistogram("Down",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral + lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral + lEigVals(1)*lEigVecs(1,1));
  TH1F* lHUp1   = (TH1F*) lFit->createHistogram("Up1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral - lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral - lEigVals(1)*lEigVecs(1,1));
  TH1F* lHDown1 = (TH1F*) lFit->createHistogram("Down1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  std::string lNuisance1 =  iBkg+"_"+"CMS_"+iName+"1_" + iChannel + "_" + iEnergy;
  std::string lNuisance2 =  iBkg+"_"+"CMS_"+iName+"2_" + iChannel + "_" + iEnergy;
  lHUp    = merge(lNuisance1 + "Up"   ,lFirst,lH0,lHUp);
  lHDown  = merge(lNuisance1 + "Down" ,lFirst,lH0,lHDown);
  lHUp1   = merge(lNuisance2 + "Up"   ,lFirst,lH0,lHUp1);
  lHDown1 = merge(lNuisance2 + "Down" ,lFirst,lH0,lHDown1);
  lH      = merge(lH0->GetName()      ,lFirst,lH0,lH);

  //=============================================================================================================================================
  //=============================================================================================================================================
  
  //Set the variables A and B to the final central values from the tail fit

  lA.setVal(lACentral);
  lB.setVal(lBCentral);
 // lA.removeRange();
 // lB.removeRange();
 
  //Generate the background pdf corresponding to the final result of the tail fit
 
 RooGenericPdf *lFitFinal  = 0; lFitFinal = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) lFitFinal = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB));
  if(iFitModel == 2) lFitFinal = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB));
  if(iFitModel == 3) lFitFinal = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB));



  //=============================================================================================================================================
  //Perform the tail fit with the alternative fit function (once initially, before allowing tail fit to float in toy fit).
  //=============================================================================================================================================

  RooFitResult  *lRFit1 = 0;
 //lRFit1=lFit1->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(iFirst,iLast),RooFit::Strategy(0));  
 lRFit1=lFit1->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(200,1500),RooFit::Strategy(0));  
  
  //Generate the background pdf corresponding to the result of the alternative tail fit

  RooGenericPdf *lFit1Final  = 0; lFit1Final = new RooGenericPdf("genPdf","exp(-m/(a1+b1*m))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) lFit1Final = new RooGenericPdf("genPdf","exp(-a1*pow(m,b1))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 2) lFit1Final = new RooGenericPdf("genPdf","a1*exp(b1*m)",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 3) lFit1Final = new RooGenericPdf("genPdf","a1/pow(m,b1)",RooArgList(lM,lA1,lB1));

 // lA1.removeRange();
 // lB1.removeRange();
  
  //=============================================================================================================================================

  //Define RooRealVar for the normalization of the signal and background, starting from the initial integral of the input histograms

  lM.setRange(300,1500);  

  RooRealVar lNB("nb","nb",lNB0,0,10000);
  RooRealVar lNSig("nsig","nsig",lNSig0,-1000,1000);

  //Define a PDF for the signal histogram lSig
  
  RooDataHist  *pS      = new RooDataHist("sigH","sigH",RooArgList(lM),lSig);
  RooHistPdf   *lSPdf   = new RooHistPdf ("sigPdf","sigPdf",lM,*pS);
 
  //Define generator and fit functions for the RooMCStudy

  RooAddPdf    *lGenMod = new RooAddPdf  ("genmod","genmod",RooArgList(*lFitFinal ,*lSPdf),RooArgList(lNB,lNSig));
  RooAddPdf    *lFitMod = new RooAddPdf  ("fitmod","fitmod",RooArgList(*lFit1Final,*lSPdf),RooArgList(lNB,lNSig));

  //Generate plot of the signal and background models going into the toy generation   

  RooPlot* plot=lM.frame();
  lGenMod->plotOn(plot);
  lGenMod->plotOn(plot,RooFit::Components(*lSPdf),RooFit::LineColor(2));
  TCanvas* lC11 = new TCanvas("pdf","pdf",600,600) ;
  lC11->cd();
  plot->Draw();
  lC11->SaveAs(("SBModel_"+iBkg+"_" + iDir + "_" + iEnergy+".pdf").c_str());

  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "FIT PARAMETERS BEFORE ROOMCSTUDY: lA: " << lA.getVal() << " lB: " << lB.getVal() << " lA1: " << lA1.getVal() << " lB1: " << lB1.getVal() << std::endl;  
  std::cout << "===================================================================================================================================================" <<std::endl;


  RooMCStudy   *lToy    = new RooMCStudy(*lGenMod,lM,RooFit::FitModel(*lFitMod),RooFit::Binned(kTRUE),RooFit::Silence(),RooFit::Extended(kTRUE),RooFit::Verbose(kTRUE),RooFit::FitOptions(RooFit::Save(kTRUE),RooFit::Strategy(0)));

  // Generate and fit iNToys toy samples
  
  std::cout << "Number of background events: " << lNB0 << " Number of signal events: " << lNSig0 << " Sum: " << lNB0+lNSig0 << std::endl;
  
  //=============================================================================================================================================
  // Generate and fit toys
  //============================================================================================================================================= 
    
  lToy->generateAndFit(iNToys,lNB0+lNSig0,kTRUE);
 
  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "FIT PARAMETERS AFTER ROOMCSTUDY: lA: " << lA.getVal() << " lB: " << lB.getVal() << " lA1: " << lA1.getVal() << " lB1: " << lB1.getVal() << std::endl;  
  std::cout << "===================================================================================================================================================" <<std::endl;
  

  //=============================================================================================================================================
  // Generate plots relevant to the toy fit
  //=============================================================================================================================================

  RooPlot* lFrame1 = lToy->plotPull(lNSig,-5,5,100,kTRUE);
  lFrame1->SetTitle("distribution of pulls on signal yield from toys");
  lFrame1->SetXTitle("N_{sig} pull");
  
  TCanvas* lC00 = new TCanvas("pulls","pulls",600,600) ;
  lC00->cd();
  lFrame1->GetYaxis()->SetTitleOffset(1.2); 
  lFrame1->GetXaxis()->SetTitleOffset(1.0); 
  lFrame1->Draw() ;
  lC00->SaveAs(("sig_pulls_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame2 = lToy->plotParam(lA1);
  lFrame2->SetTitle("distribution of values of parameter 1 (a) after toy fit");
  lFrame2->SetXTitle("Parameter 1 (a)");
  TCanvas* lC01 = new TCanvas("valA","valA",600,600) ;
  lFrame2->Draw() ;
  lC01->SaveAs(("valA_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame3 = lToy->plotParam(lB1);
  lFrame3->SetTitle("distribution of values of parameter 2 (b) after toy fit");
  lFrame3->SetXTitle("Parameter 2 (b)");
  TCanvas* lC02 = new TCanvas("valB","valB",600,600) ;
  lFrame3->Draw() ;
  lC02->SaveAs(("valB_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
  
  RooPlot* lFrame6 = lToy->plotNLL(0,1000,100);
  lFrame6->SetTitle("-log(L)");
  lFrame6->SetXTitle("-log(L)");
  TCanvas* lC05 = new TCanvas("logl","logl",600,600) ;
  lFrame6->Draw() ;
  lC05->SaveAs(("logL_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame7 = lToy->plotParam(lNSig);
  lFrame7->SetTitle("distribution of values of N_{sig} after toy fit");
  lFrame7->SetXTitle("N_{sig}");
  TCanvas* lC06 = new TCanvas("Nsig","Nsig",600,600) ;
  lFrame7->Draw() ;
  lC06->SaveAs(("NSig_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
  
  RooPlot* lFrame8 = lToy->plotParam(lNB);
  lFrame8->SetTitle("distribution of values of N_{bkg} after toy fit");
  lFrame8->SetXTitle("N_{bkg}");
  TCanvas* lC07 = new TCanvas("Nbkg","Nbkg",600,600) ;
  lFrame8->Draw() ;
  lC07->SaveAs(("Nbkg_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
 

  if(iRebin) { 
    const int lNBins = lData->GetNbinsX();
    double *lAxis    = getAxis(lData);
    lH0     = rebin(lH0    ,lNBins,lAxis);
    lH      = rebin(lH     ,lNBins,lAxis);
    lHUp    = rebin(lHUp   ,lNBins,lAxis);
    lHDown  = rebin(lHDown ,lNBins,lAxis);
    lHUp1   = rebin(lHUp1  ,lNBins,lAxis);
    lHDown1 = rebin(lHDown1,lNBins,lAxis);
  }

  // we dont need this bin errors since we do not use them (fit tails replaces bin-by-bin error!), therefore i set all errors to 0, this also saves us from modifying the add_bbb_error.py script in which I otherwise would have to include a option for adding bbb only in specific ranges
  int lMergeBin = lH->GetXaxis()->FindBin(iFirst);
  for(int i0 = lMergeBin; i0 < lH->GetNbinsX()+1; i0++){
    lH->SetBinError  (i0,0);
    lHUp->SetBinError  (i0,0);
    lHDown->SetBinError  (i0,0);
    lHUp1->SetBinError  (i0,0);
    lHDown1->SetBinError  (i0,0);
  }


  TFile *lOutFile =new TFile("Output.root","RECREATE");
  cloneFile(lOutFile,lFile,iDir+"/"+iBkg);
  lOutFile->cd(iDir.c_str());
  lH     ->Write();
  lHUp   ->Write(); 
  lHDown ->Write(); 
  lHUp1  ->Write(); 
  lHDown1->Write(); 

  // Debug Plots
  lH0->SetStats(0);
  lH->SetStats(0);
  lHUp->SetStats(0);
  lHDown->SetStats(0);
  lHUp1->SetStats(0);
  lHDown1->SetStats(0);
  lH0    ->SetLineWidth(1); lH0->SetMarkerStyle(kFullCircle);
  lH     ->SetLineColor(kGreen);
  lHUp   ->SetLineColor(kRed);
  lHDown ->SetLineColor(kRed);
  lHUp1  ->SetLineColor(kBlue);
  lHDown1->SetLineColor(kBlue);
  TCanvas *lC0 = new TCanvas("Can","Can",800,600);
  lC0->Divide(1,2); lC0->cd();  lC0->cd(1)->SetPad(0,0.2,1.0,1.0); gPad->SetLeftMargin(0.2) ; 
  lH0->Draw();
  lH     ->Draw("hist sames");
  lHUp   ->Draw("hist sames");
  lHDown ->Draw("hist sames");
  lHUp1  ->Draw("hist sames");
  lHDown1->Draw("hist sames");
  gPad->SetLogy();
  
  TLegend* leg1;
  /// setup the CMS Preliminary
  leg1 = new TLegend(0.7, 0.80, 1, 1); 
  leg1->SetBorderSize( 0 );
  leg1->SetFillStyle ( 1001 );
  leg1->SetFillColor (kWhite);
  leg1->AddEntry( lH0 , "orignal",  "PL" );
  leg1->AddEntry( lH , "cental fit",  "L" );
  leg1->AddEntry( lHUp , "shift1 up",  "L" );
  leg1->AddEntry( lHDown , "shift1 down",  "L" );
  leg1->AddEntry( lHUp1 , "shift2 up",  "L" );
  leg1->AddEntry( lHDown1 , "shift2 down",  "L" );
  leg1->Draw("same");


  lC0->cd(2)->SetPad(0,0,1.0,0.2); gPad->SetLeftMargin(0.2) ;
  drawDifference(lH0,lH,lHUp,lHDown,lHUp1,lHDown1);
  lH0->SetStats(0);
  lC0->Update();
  lC0->SaveAs((iBkg+"_"+"CMS_"+iName+"1_" + iDir + "_" + iEnergy+".png").c_str());
  //lFile->Close();
  return;
}
void addNuisance(std::string iFileName,std::string iChannel,std::string iBkg,std::string iEnergy,std::string iName,std::string iDir,bool iRebin=true,bool iVarBin=false,int iFitModel=1,double iFirst=150,double iLast=1500) { 
  std::cout << "======> " << iDir << "/" << iBkg << " -- " << iFileName << std::endl;  
  if(iVarBin) addVarBinNuisance(iFileName,iChannel,iBkg,iEnergy,iName,iDir,iRebin,iFitModel,iFirst,iLast);
  if(iVarBin) return;

  TFile *lFile = new TFile(iFileName.c_str());
  TH1F  *lH0   = (TH1F*) lFile->Get((iDir+"/"+iBkg).c_str());
  TH1F  *lData = (TH1F*) lFile->Get((iDir+"/data_obs").c_str());

  //Define the fit function
  RooRealVar lM("m","m" ,0,5000);   //lM.setBinning(lBinning);
  RooRealVar lA("a","a" ,50,  0.1,100);
  RooRealVar lB("b","b" ,0.0 , -10.5,10.5); //lB.setConstant(kTRUE);
  RooDataHist *pH0  =  new RooDataHist("Data","Data" ,RooArgList(lM),lH0);
  RooGenericPdf *lFit  = 0; lFit = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) lFit = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) {lA.setVal(0.3); lB.setVal(0.5);}
  if(iFitModel == 2) lFit = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB));
  if(iFitModel == 3) lFit = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB));
  RooFitResult  *lRFit = 0;
  double lFirst = iFirst;
  double lLast  = iLast;
  //lRFit = lFit->chi2FitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(lFirst,lLast));
  lRFit = lFit->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(lFirst,lLast),RooFit::Strategy(0)); 
  TMatrixDSym lCovMatrix   = lRFit->covarianceMatrix(); 
  TMatrixD  lEigVecs(2,2);    lEigVecs = TMatrixDSymEigen(lCovMatrix).GetEigenVectors();
  TVectorD  lEigVals(2);      lEigVals = TMatrixDSymEigen(lCovMatrix).GetEigenValues();
  cout << " Ve---> " << lEigVecs(0,0) << " -- " << lEigVecs(1,0) << " -- " << lEigVecs(0,1) << " -- " << lEigVecs(1,1) << endl;
  cout << " Co---> " << lCovMatrix(0,0) << " -- " << lCovMatrix(1,0) << " -- " << lCovMatrix(0,1) << " -- " << lCovMatrix(1,1) << endl;
  double lACentral = lA.getVal();
  double lBCentral = lB.getVal();
  lEigVals(0) = sqrt(lEigVals(0));
  lEigVals(1) = sqrt(lEigVals(1));
  cout << "===> " << lEigVals(0) << " -- " << lEigVals(1) << endl;
  
  TH1F* lH     = (TH1F*) lFit->createHistogram("fit" ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));
  lA.setVal(lACentral + lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral + lEigVals(0)*lEigVecs(1,0));
  TH1F* lHUp   = (TH1F*) lFit->createHistogram("Up"  ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));
  lA.setVal(lACentral - lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral - lEigVals(0)*lEigVecs(1,0));
  TH1F* lHDown = (TH1F*) lFit->createHistogram("Down",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral + lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral + lEigVals(1)*lEigVecs(1,1));
  TH1F* lHUp1   = (TH1F*) lFit->createHistogram("Up1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));
  lA.setVal(lACentral - lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral - lEigVals(1)*lEigVecs(1,1));
  TH1F* lHDown1 = (TH1F*) lFit->createHistogram("Down1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  std::string lNuisance1 =  iBkg+"_"+"CMS_"+iName+"1_" + iChannel + "_" + iEnergy;
  std::string lNuisance2 =  iBkg+"_"+"CMS_"+iName+"2_" + iChannel + "_" + iEnergy;
  lHUp    = merge(lNuisance1 + "Up"   ,lFirst,lH0,lHUp);
  lHDown  = merge(lNuisance1 + "Down" ,lFirst,lH0,lHDown);
  lHUp1   = merge(lNuisance2 + "Up"   ,lFirst,lH0,lHUp1);
  lHDown1 = merge(lNuisance2 + "Down" ,lFirst,lH0,lHDown1);
  lH      = merge(lH0->GetName()      ,lFirst,lH0,lH);

  if(iRebin) { 
    const int lNBins = lData->GetNbinsX();
    double *lAxis    = getAxis(lData);
    lH0     = rebin(lH0    ,lNBins,lAxis);
    lH      = rebin(lH     ,lNBins,lAxis);
    lHUp    = rebin(lHUp   ,lNBins,lAxis);
    lHDown  = rebin(lHDown ,lNBins,lAxis);
    lHUp1   = rebin(lHUp1  ,lNBins,lAxis);
    lHDown1 = rebin(lHDown1,lNBins,lAxis);
  }

  // we dont need this bin errors since we do not use them (fit tails replaces bin-by-bin error!), therefore i set all errors to 0, this also saves us from modifying the add_bbb_error.py script in which I otherwise would have to include a option for adding bbb only in specific ranges
  int lMergeBin = lH->GetXaxis()->FindBin(iFirst);
  for(int i0 = lMergeBin; i0 < lH->GetNbinsX()+1; i0++){
    lH->SetBinError  (i0,0);
    lHUp->SetBinError  (i0,0);
    lHDown->SetBinError  (i0,0);
    lHUp1->SetBinError  (i0,0);
    lHDown1->SetBinError  (i0,0);
  }


  TFile *lOutFile =new TFile("Output.root","RECREATE");
  cloneFile(lOutFile,lFile,iDir+"/"+iBkg);
  lOutFile->cd(iDir.c_str());
  lH     ->Write();
  lHUp   ->Write(); 
  lHDown ->Write(); 
  lHUp1  ->Write(); 
  lHDown1->Write(); 

  // Debug Plots
  lH0->SetStats(0);
  lH->SetStats(0);
  lHUp->SetStats(0);
  lHDown->SetStats(0);
  lHUp1->SetStats(0);
  lHDown1->SetStats(0);
  lH0    ->SetLineWidth(1); lH0->SetMarkerStyle(kFullCircle);
  lH     ->SetLineColor(kGreen);
  lHUp   ->SetLineColor(kRed);
  lHDown ->SetLineColor(kRed);
  lHUp1  ->SetLineColor(kBlue);
  lHDown1->SetLineColor(kBlue);
  TCanvas *lC0 = new TCanvas("Can","Can",800,600);
  lC0->Divide(1,2); lC0->cd();  lC0->cd(1)->SetPad(0,0.2,1.0,1.0); gPad->SetLeftMargin(0.2) ; 
  lH0->Draw();
  lH     ->Draw("hist sames");
  lHUp   ->Draw("hist sames");
  lHDown ->Draw("hist sames");
  lHUp1  ->Draw("hist sames");
  lHDown1->Draw("hist sames");
  gPad->SetLogy();
  
  TLegend* leg1;
  /// setup the CMS Preliminary
  leg1 = new TLegend(0.7, 0.80, 1, 1); 
  leg1->SetBorderSize( 0 );
  leg1->SetFillStyle ( 1001 );
  leg1->SetFillColor (kWhite);
  leg1->AddEntry( lH0 , "orignal",  "PL" );
  leg1->AddEntry( lH , "cental fit",  "L" );
  leg1->AddEntry( lHUp , "shift1 up",  "L" );
  leg1->AddEntry( lHDown , "shift1 down",  "L" );
  leg1->AddEntry( lHUp1 , "shift2 up",  "L" );
  leg1->AddEntry( lHDown1 , "shift2 down",  "L" );
  leg1->Draw("same");


  lC0->cd(2)->SetPad(0,0,1.0,0.2); gPad->SetLeftMargin(0.2) ;
  drawDifference(lH0,lH,lHUp,lHDown,lHUp1,lHDown1);
  lH0->SetStats(0);
  lC0->Update();
  lC0->SaveAs((iBkg+"_"+"CMS_"+iName+"1_" + iDir + "_" + iEnergy+".png").c_str());
  //lFile->Close();
  return;
}
//I would recommend to use the other version of the fit code
void addVarBinNuisance(std::string iFileName,std::string iChannel,std::string iBkg,std::string iEnergy,std::string iName,std::string iDir,bool iRebin=true,int iFitModel=0,double iFirst=200,double iLast=1500) { 
  std::cout << "======> " << iDir << "/" << iBkg << " -- " << iFileName << std::endl;  
  TFile *lFile = new TFile(iFileName.c_str());
  TH1F  *lH0   = (TH1F*) lFile->Get((iDir+"/"+iBkg).c_str());
  TH1F  *lData = (TH1F*) lFile->Get((iDir+"/data_obs").c_str());
  
  for(int i0 = 0; i0 < lH0->GetNbinsX()+1; i0++) lH0->SetBinContent(i0,lH0->GetBinContent(i0)/lH0->GetXaxis()->GetBinWidth(i0));
  for(int i0 = 0; i0 < lH0->GetNbinsX()+1; i0++) lH0->SetBinError  (i0,lH0->GetBinError  (i0)/lH0->GetXaxis()->GetBinWidth(i0));
  //Define the fit function
  double lFirst = iFirst;
  double lLast  = iLast;
  //TF1 *lFit = new TF1("Fit","[2]*exp(-x/([0]+[1]*x))",0,5000);
  TF1 *lFit = new TF1("expspec","[2]*exp(-x/([0]+[1]*x))",0,5000);
  if(iFitModel == 1) lFit  = new TF1("expspec","[2]*exp(-[0]*pow(x,[1]))",0,5000);
  lFit->SetParLimits(2,0,10000000); lFit->SetParameter(2,lH0->Integral()); 
  lFit->SetParLimits(0,  0,100);    lFit->SetParameter(0,20);
  lFit->SetParLimits(1,-10,10);     lFit->SetParameter(1,0);
  if(iFitModel == 1) lFit->SetParameter(0,0.3);
  if(iFitModel == 2) lFit->SetParameter(1,0.5);
  
  //TFitResultPtr  lFitPtr = lH0->Fit("expspec","SEWL","IR",lFirst,lLast);
  TFitResultPtr  lFitPtr = lH0->Fit("expspec","SER","R",lFirst,lLast);
  TMatrixDSym lCovMatrix   = lFitPtr->GetCovarianceMatrix();
  TMatrixD  lEigVecs(3,3);    lEigVecs = TMatrixDSymEigen(lCovMatrix).GetEigenVectors();
  TVectorD  lEigVals(3);      lEigVals = TMatrixDSymEigen(lCovMatrix).GetEigenValues();
  double lACentral = lFit->GetParameter(0); 
  double lBCentral = lFit->GetParameter(1);
  lEigVals(0) = sqrt(lEigVals(1));
  lEigVals(1) = sqrt(lEigVals(2));

  for(int i0 = 0; i0 < lH0->GetNbinsX()+1; i0++) lH0->SetBinContent(i0,lH0->GetBinContent(i0)*lH0->GetXaxis()->GetBinWidth(i0));
  for(int i0 = 0; i0 < lH0->GetNbinsX()+1; i0++) lH0->SetBinError  (i0,lH0->GetBinError  (i0)*lH0->GetXaxis()->GetBinWidth(i0));

  lEigVecs(0,0) = lEigVecs(0,1);
  lEigVecs(1,0) = lEigVecs(1,1);
  lEigVecs(0,1) = lEigVecs(0,2);
  lEigVecs(1,1) = lEigVecs(1,2);
  
  TH1F* lH     = makeHist(lFit,lH0,"Def");
  lFit->SetParameter(0,lACentral + lEigVals(0)*lEigVecs(0,0));
  lFit->SetParameter(1,lBCentral + lEigVals(0)*lEigVecs(1,0));
  TH1F* lHUp   = makeHist(lFit,lH0,"Up");
  lFit->SetParameter(0,lACentral - lEigVals(0)*lEigVecs(0,0));
  lFit->SetParameter(1,lBCentral - lEigVals(0)*lEigVecs(1,0));
  TH1F* lHDown = makeHist(lFit,lH0,"Down");

  lFit->SetParameter(0,lACentral + lEigVals(1)*lEigVecs(0,1));
  lFit->SetParameter(1,lBCentral + lEigVals(1)*lEigVecs(1,1));
  TH1F* lHUp1   = makeHist(lFit,lH0,"Up1");
  lFit->SetParameter(0,lACentral - lEigVals(1)*lEigVecs(0,1));
  lFit->SetParameter(1,lBCentral - lEigVals(1)*lEigVecs(1,1));
  TH1F* lHDown1 = makeHist(lFit,lH0,"Down1");
  
  //lFirst = 200;
  std::string lNuisance1 =  iBkg+"_"+"CMS_"+iName+"1_" + iChannel + "_" + iEnergy;
  std::string lNuisance2 =  iBkg+"_"+"CMS_"+iName+"2_" + iChannel + "_" + iEnergy;
  lHUp    = merge(lNuisance1 + "Up"   ,lFirst,lH0,lHUp);
  lHDown  = merge(lNuisance1 + "Down" ,lFirst,lH0,lHDown);
  lHUp1   = merge(lNuisance2 + "Up"   ,lFirst,lH0,lHUp1);
  lHDown1 = merge(lNuisance2 + "Down" ,lFirst,lH0,lHDown1);
  lH      = merge(lH0->GetName()      ,lFirst,lH0,lH);  
  if(iRebin) { 
    const int lNBins = lData->GetNbinsX();
    double *lAxis    = getAxis(lData);
    lH0     = rebin(lH0    ,lNBins,lAxis);
    lH      = rebin(lH     ,lNBins,lAxis);
    lHUp    = rebin(lHUp   ,lNBins,lAxis);
    lHDown  = rebin(lHDown ,lNBins,lAxis);
    lHUp1   = rebin(lHUp1  ,lNBins,lAxis);
    lHDown1 = rebin(lHDown1,lNBins,lAxis);
  }
  TFile *lOutFile =new TFile("Output.root","RECREATE");
  cloneFile(lOutFile,lFile,iDir+"/"+iBkg);
  lOutFile->cd(iDir.c_str());
  lH     ->Write();
  lHUp   ->Write(); 
  lHDown ->Write(); 
  lHUp1  ->Write(); 
  lHDown1->Write(); 

  // Debug Plots
  lH0    ->SetLineWidth(1); lH0->SetMarkerStyle(kFullCircle);
  lH     ->SetLineColor(kGreen);
  lHUp   ->SetLineColor(kRed);
  lHDown ->SetLineColor(kRed);
  lHUp1  ->SetLineColor(kBlue);
  lHDown1->SetLineColor(kBlue);
  TCanvas *lC0 = new TCanvas("Can","Can",800,600);
  lC0->Divide(1,2); lC0->cd();  lC0->cd(1)->SetPad(0,0.2,1.0,1.0); gPad->SetLeftMargin(0.2) ;  
  lH0->Draw();
  lH     ->Draw("hist sames");
  lHUp   ->Draw("hist sames");
  lHDown ->Draw("hist sames");
  lHUp1  ->Draw("hist sames");
  lHDown1->Draw("hist sames");
  gPad->SetLogy();
  lC0->cd(2)->SetPad(0,0,1.0,0.2); gPad->SetLeftMargin(0.2) ;
  drawDifference(lH0,lH,lHUp,lHDown,lHUp1,lHDown1);
  lC0->SaveAs((iBkg+"_"+"CMS_"+iName+"1_" + iDir + "_" + iEnergy+".png").c_str());
  //lFile->Close();
  return;
}
int theoryStudy_separate(const TString BaseName)
{
  TString tmpTStr;
  char tmpName[30],tmpName_org[30];
  int Numb;

  TFile *f_Resbos;
  TFile *f_Fewz;
  TFile *f_Data;
  TFile *f_Data_PowhegErr;

  f_Resbos = new TFile("../../RstResbos/Resbos_"+BaseName+".root");
  f_Data = new TFile("../Result"+BaseName+"/Result_"+BaseName+".root");
  f_Data_PowhegErr = new TFile("../../Systematics/WptXsecErrors/"+BaseName+"Errors.root");

  if (BaseName=="WpToMuNu")
  {
    f_Fewz = new TFile("../../RstFEWZ/Wp_Mu_NNLO.root");
  }
  if (BaseName=="WmToMuNu")
  {
    f_Fewz = new TFile("../../RstFEWZ/Wm_Mu_NNLO.root");
  }
  if (BaseName=="WpToEleNu")
  {
    f_Fewz = new TFile("../../RstFEWZ/Wp_Ele_NNLO.root");
  }
  if (BaseName=="WmToEleNu")
  {
    f_Fewz = new TFile("../../RstFEWZ/Wm_Ele_NNLO.root");
  }


  TH1D *hWptBins_LinScale   = new TH1D("hWptBins_LinScale","hWptBins_LinScale",nBins-1,WptBins);hWptBins_LinScale->Sumw2();
  TH1D *hWptBins_LogScale   = new TH1D("hWptBins_LogScale","hWptBins_LogScale",nBins-1,WptLogBins);hWptBins_LogScale->Sumw2();
  

  ///=============Reading related stat, syst errors starts here==============
  //  
  TH1D* hData_StatErr		 = (TH1D*)f_Data_PowhegErr->Get("h_Stat")->Clone("hData_StatErr");

  TH1D* hData_MetResolSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_met")->Clone("hData_MetResolSystErr");
  TH1D* hData_EnMomScaleSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_scale")->Clone("hData_EnMomScaleSystErr");
  TH1D* hData_EnMomSmearSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_smear")->Clone("hData_EnMomSmearSystErr");
  TH1D* hData_QcdBckgrSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_qcdbckgr")->Clone("hData_QcdBckgrSystErr");
  TH1D* hData_QcdShapeSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_qcdshape")->Clone("hData_QcdShapeSystErr");
  TH1D* hData_EwkSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_ewk")->Clone("hData_EwkSystErr");
  TH1D* hData_FsrSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_fsr")->Clone("hData_FsrSystErr");
  TH1D* hData_SvdUnfSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_SvdUnf")->Clone("hData_SvdUnfSystErr");
  TH1D* hData_UnfoldBiasSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_UnfoldBias")->Clone("hData_UnfoldBiasSystErr");
  TH1D* hData_LumiSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_LumiSyst")->Clone("hData_LumiSystErr");
  
  ///Lepton Reconstruction related systematic errors
  //
  TH1D* hData_EffiToySystErr		 = (TH1D*)f_Data_PowhegErr->Get("h_toy")->Clone("hData_EffiToySystErr");
  TH1D* hData_IDIsoSigShapeSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_idisosig")->Clone("hData_IDIsoSigShapeSystErr");
  TH1D* hData_IDIsoBkgrShapeSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_idisobck")->Clone("hData_IDIsoBkgrShapeSystErr");
 
  
  TH1D *hData_TotalSystErr   = new TH1D("hData_TotalSystErr","hData_TotalSystErr",nBins-1,WptBins);hData_TotalSystErr->Sumw2();
  
  if(BaseName== "WpToMuNu" || BaseName== "WmToMuNu")
  {
    TH1D* hData_TrackSigShapeSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_tracksig")->Clone("hData_TrackSigShapeSystErr");
    TH1D* hData_TrackBkgrShapeSystErr	 = (TH1D*)f_Data_PowhegErr->Get("h_trackbck")->Clone("hData_TrackBkgrShapeSystErr");
    TH1D* hData_MuonPOGSystErr		 = (TH1D*)f_Data_PowhegErr->Get("h_POG")->Clone("hData_MuonPOGSystErr");
   
    //// Calculate total syst for muon
    for( int ipt(1);ipt<=nBins-1;ipt++)
    {
      hData_TotalSystErr->SetBinContent(ipt, sqrt( TMath::Power(hData_TrackSigShapeSystErr->GetBinContent(ipt),2) +  TMath::Power( hData_TrackBkgrShapeSystErr->GetBinContent(ipt),2) + TMath::Power( hData_MuonPOGSystErr->GetBinContent(ipt),2) + TMath::Power( hData_EffiToySystErr->GetBinContent(ipt),2)+ TMath::Power( hData_IDIsoSigShapeSystErr->GetBinContent(ipt),2)+ TMath::Power( hData_IDIsoBkgrShapeSystErr->GetBinContent(ipt),2) + TMath::Power( hData_MetResolSystErr->GetBinContent(ipt),2) + TMath::Power( hData_EnMomScaleSystErr->GetBinContent(ipt),2) + TMath::Power(hData_EnMomSmearSystErr->GetBinContent(ipt),2) + TMath::Power( hData_QcdBckgrSystErr->GetBinContent(ipt),2) + TMath::Power( hData_QcdShapeSystErr->GetBinContent(ipt),2) + TMath::Power( hData_EwkSystErr->GetBinContent(ipt),2) + TMath::Power( hData_FsrSystErr->GetBinContent(ipt),2) + TMath::Power( hData_SvdUnfSystErr->GetBinContent(ipt),2) + TMath::Power( hData_UnfoldBiasSystErr->GetBinContent(ipt),2)  + TMath::Power( hData_LumiSystErr->GetBinContent(ipt),2) ));

    }
    
  }
  else if(BaseName== "WpToEleNu" || BaseName== "WmToEleNu")
  {
    TH1D* hData_BinningSystErr		 = (TH1D*)f_Data_PowhegErr->Get("h_bin")->Clone("hData_BinningSystErr");
  
    //// Calculate total syst for electron
    for( int ipt(1);ipt<=nBins-1;ipt++)
    {
      hData_TotalSystErr->SetBinContent(ipt, sqrt( TMath::Power(hData_BinningSystErr->GetBinContent(ipt),2) + TMath::Power( hData_EffiToySystErr->GetBinContent(ipt),2) + TMath::Power( hData_IDIsoSigShapeSystErr->GetBinContent(ipt),2) + TMath::Power( hData_IDIsoBkgrShapeSystErr->GetBinContent(ipt),2) + TMath::Power( hData_MetResolSystErr->GetBinContent(ipt),2) + TMath::Power( hData_EnMomScaleSystErr->GetBinContent(ipt),2) + TMath::Power(hData_EnMomSmearSystErr->GetBinContent(ipt),2) + TMath::Power( hData_QcdBckgrSystErr->GetBinContent(ipt),2) + TMath::Power( hData_QcdShapeSystErr->GetBinContent(ipt),2) + TMath::Power( hData_EwkSystErr->GetBinContent(ipt),2) + TMath::Power( hData_FsrSystErr->GetBinContent(ipt),2) + TMath::Power( hData_SvdUnfSystErr->GetBinContent(ipt),2) + TMath::Power( hData_UnfoldBiasSystErr->GetBinContent(ipt),2) + TMath::Power( hData_LumiSystErr->GetBinContent(ipt),2) ));

    }
  }

  TH1D *hData_TotalUncer   = new TH1D("hData_TotalUncer","hData_TotalUncer",nBins-1,WptBins);hData_TotalUncer->Sumw2();
  for( int ipt(1);ipt<nBins;ipt++)
  {
    hData_TotalUncer->SetBinContent(ipt, sqrt(TMath::Power(hData_StatErr->GetBinContent(ipt),2)+ TMath::Power(hData_TotalSystErr->GetBinContent(ipt),2)));
    cout<<"hData_TotalUncer: "<<ipt<<"\t"<<hData_TotalUncer->GetBinContent(ipt)<<endl;
  } 
 

  for( int ipt(1);ipt<nBins;ipt++)
  {
    //cout<<"hData_TrackSigShapeSystErr: "<<ipt<<"\t"<<hData_TrackSigShapeSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_TrackBkgrShapeSystErr: "<<ipt<<"\t"<<hData_TrackBkgrShapeSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_IDIsoSigShapeSystErr: "<<ipt<<"\t"<<hData_IDIsoSigShapeSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_IDIsoBkgrShapeSystErr: "<<ipt<<"\t"<<hData_IDIsoBkgrShapeSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_MuonPOGSystErr: "<<ipt<<"\t"<<hData_MuonPOGSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_EffiToySystErr: "<<ipt<<"\t"<<hData_EffiToySystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_MetResolSystErr: "<<ipt<<"\t"<<hData_MetResolSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_EnMomScaleSystErr: "<<ipt<<"\t"<<hData_EnMomScaleSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_EnMomSmearSystErr: "<<ipt<<"\t"<<hData_EnMomSmearSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_QcdBckgrSystErr: "<<ipt<<"\t"<<hData_QcdBckgrSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_QcdShapeSystErr: "<<ipt<<"\t"<<hData_QcdShapeSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_EwkSystErr: "<<ipt<<"\t"<<hData_EwkSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_FsrSystErr: "<<ipt<<"\t"<<hData_FsrSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_SvdUnfSystErr: "<<ipt<<"\t"<<hData_SvdUnfSystErr->GetBinContent(ipt)<<endl;
    //cout<<"hData_UnfoldBiasSystErr: "<<ipt<<"\t"<<hData_UnfoldBiasSystErr->GetBinContent(ipt)<<endl;
  } 


  TH1D* hPowheg_PDFErr		 = (TH1D*)f_Data_PowhegErr->Get("h_PowhegPDF")->Clone("hPowheg_PDFErr");
  
  //TH1D* hData_TotalUncer = (TH1D*)f_Data_PowhegErr->Get("h_TotalUncer")->Clone("hData_TotalUncer");
  ///=============Reading related stat, syst errors Finished here==============
 




  /////==========Real Data Starts here=========================================
  //
  // Born Level RD Yield and Errors, and Converting to X sec yield and errors, making TGraph .
  
 

  TH1D* hData_Xsec_BornLinScale;
  hData_Xsec_BornLinScale   = (TH1D*)f_Data->Get("BornEffCorr")->Clone("hData_Xsec_BornLinScale");
  for( int ipt(1);ipt<nBins;ipt++)
  {
    hData_Xsec_BornLinScale->SetBinError(ipt, 0.01*hData_TotalUncer->GetBinContent(ipt)*hData_Xsec_BornLinScale->GetBinContent(ipt) );
  } 
  hData_Xsec_BornLinScale->Scale(1./18.429);

  TH1D* hData_Yield_ReconLinScale;
  hData_Yield_ReconLinScale = (TH1D*)f_Data->Get("data_Rec")->Clone("hData_Yield_ReconLinScale");
  for( int ipt(1);ipt<nBins;ipt++)
  {
    double tmp = sqrt(hData_Yield_ReconLinScale->GetBinContent(ipt));
    hData_Yield_ReconLinScale->SetBinError(ipt,tmp);
  }

  //Errors
  double Data_Xsec_BornStatErr[14];
  double Data_Xsec_BornTotalErr[14];
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    Data_Xsec_BornStatErr[ipt] = hData_Xsec_BornLinScale->GetBinContent(ipt) * ( hData_Yield_ReconLinScale->GetBinError(ipt)/hData_Yield_ReconLinScale->GetBinContent(ipt) );
    Data_Xsec_BornTotalErr[ipt] = hData_Xsec_BornLinScale->GetBinError(ipt);
  }

  // X-sex and error Log scale
  TH1D *hData_Xsec_BornLogScale     = new TH1D("hData_Xsec_BornLogScale","hData_Xsec_BornLogScale",nBins-1,WptLogBins);hData_Xsec_BornLogScale->Sumw2();
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    hData_Xsec_BornLogScale->SetBinContent(ipt,hData_Xsec_BornLinScale->GetBinContent(ipt)/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt    ));
    hData_Xsec_BornLogScale->SetBinError(ipt,Data_Xsec_BornTotalErr[ipt]/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt));
  }
  
  ///   Theory/Data ratio plot errors related to Real Data
  TH1D *hRatioDataErrBand = new TH1D("hRatioDataErrBand","hRatioDataErrBand",nBins-1,WptLogBins);hRatioDataErrBand->Sumw2();
  TH1D *hRatioDataStatErr = new TH1D("hRatioDataStatErr","hRatioDataStatErr",nBins-1,WptLogBins);hRatioDataStatErr->Sumw2();
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    hRatioDataErrBand->SetBinContent(ipt,1.);
    hRatioDataErrBand->SetBinError(ipt,hData_Xsec_BornLinScale->GetBinError(ipt)/hData_Xsec_BornLinScale->GetBinContent(ipt));
    
    hRatioDataStatErr->SetBinContent(ipt,1.);
    hRatioDataStatErr->SetBinError(ipt,Data_Xsec_BornStatErr[ipt]/hData_Xsec_BornLinScale->GetBinContent(ipt));
  }
  

  hData_Xsec_BornLogScale->SetMarkerStyle(kFullCircle); 
  hData_Xsec_BornLogScale->SetMarkerColor(kBlack); 
  hData_Xsec_BornLogScale->SetMarkerSize(1);
  
  hRatioDataStatErr->SetMarkerStyle(kFullCircle); 
  hRatioDataStatErr->SetMarkerColor(kBlack); 
  hRatioDataStatErr->SetMarkerSize(0.6);
  /// TGraph
  TGraphErrors *Data_Xsec_Born = new TGraphErrors(hData_Xsec_BornLogScale);
  TGraphErrors *RatioDataErrBand = new TGraphErrors(hRatioDataErrBand);

  /////==========Real Data related stuff Finished here=========================================



  /////==========Powheg Starts here==============================================
  //
  // Born Level Powheg Yield and Errors, and Converting to X sec yield and errors, making TGraph .
  
  
  TH1D* hPowheg_Xsec_BornLinScale;
  hPowheg_Xsec_BornLinScale   = (TH1D*)f_Data->Get("SVD_Born.Gen")->Clone("hPowheg_Xsec_BornLinScale");
  for( int ipt(1);ipt<nBins;ipt++)
  {
    hPowheg_Xsec_BornLinScale->SetBinError(ipt, 0.01*hPowheg_PDFErr->GetBinContent(ipt)*hPowheg_Xsec_BornLinScale->GetBinContent(ipt) );
  } 
  hPowheg_Xsec_BornLinScale->Scale(1./18.429);
    
  TH1D* hPowheg_Yield_BornAfterFidCut;
  hPowheg_Yield_BornAfterFidCut = (TH1D*)f_Data->Get("SVD_Born.Gen")->Clone("hPowheg_Yield_BornAfterFidCut");
  if(BaseName== "WpToMuNu")  { hPowheg_Yield_BornAfterFidCut->Scale(1./LumiWeight_Muon_WpToMuNu_S8); }
  if(BaseName== "WmToMuNu")  { hPowheg_Yield_BornAfterFidCut->Scale(1./LumiWeight_Muon_WmToMuNu_S8); }
  if(BaseName== "WpToEleNu") { hPowheg_Yield_BornAfterFidCut->Scale(1./LumiWeight_Ele_WpToEleNu_S8); }
  if(BaseName== "WmToEleNu") { hPowheg_Yield_BornAfterFidCut->Scale(1./LumiWeight_Ele_WmToEleNu_S8); }

  //Errors
  double Powheg_Xsec_BornStatErr[14];
  double Powheg_Xsec_BornTotalErr[14];
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    Powheg_Xsec_BornStatErr[ipt] = hPowheg_Xsec_BornLinScale->GetBinContent(ipt)*sqrt(hPowheg_Yield_BornAfterFidCut->GetBinContent(ipt))/hPowheg_Yield_BornAfterFidCut->GetBinContent(ipt);
    Powheg_Xsec_BornTotalErr[ipt] = sqrt(Powheg_Xsec_BornStatErr[ipt]*Powheg_Xsec_BornStatErr[ipt] + hPowheg_Xsec_BornLinScale->GetBinError(ipt)*hPowheg_Xsec_BornLinScale->GetBinError(ipt));
  }

  // X-sex and error Log scale
  TH1D *hPowheg_Xsec_BornLogScale   = new TH1D("hPowheg_Xsec_BornLogScale","hPowheg_Xsec_BornLogScale",nBins-1,WptLogBins);hPowheg_Xsec_BornLogScale->Sumw2();
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    hPowheg_Xsec_BornLogScale->SetBinContent(ipt,hPowheg_Xsec_BornLinScale->GetBinContent(ipt)/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt));
    hPowheg_Xsec_BornLogScale->SetBinError(ipt,Powheg_Xsec_BornTotalErr[ipt]/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt));
  }

  ///   Theory/Data ratio plot errors related to Real Data
  TH1D *hRatioPowhegStatErrBand = new TH1D("hRatioPowhegStatErrBand","hRatioPowhegStatErrBand",nBins-1,WptLogBins);hRatioPowhegStatErrBand->Sumw2();
  TH1D *hRatioPowhegPDFErrBand = new TH1D("hRatioPowhegPDFErrBand","hRatioPowhegPDFErrBand",nBins-1,WptLogBins);hRatioPowhegPDFErrBand->Sumw2();
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    hRatioPowhegStatErrBand->SetBinContent(ipt,hPowheg_Xsec_BornLogScale->GetBinContent(ipt)/hData_Xsec_BornLogScale->GetBinContent(ipt));
    hRatioPowhegStatErrBand->SetBinError(ipt,Powheg_Xsec_BornStatErr[ipt]/hData_Xsec_BornLinScale->GetBinContent(ipt));
    
    hRatioPowhegPDFErrBand->SetBinContent(ipt,hPowheg_Xsec_BornLogScale->GetBinContent(ipt)/hData_Xsec_BornLogScale->GetBinContent(ipt));
    hRatioPowhegPDFErrBand->SetBinError(ipt,(Powheg_Xsec_BornStatErr[ipt]/hData_Xsec_BornLinScale->GetBinContent(ipt))+(hPowheg_Xsec_BornLinScale->GetBinError(ipt)/hData_Xsec_BornLinScale->GetBinContent(ipt)));
  }
  
  /// TGraph
  TGraphErrors *Powheg_Xsec_Born = new TGraphErrors(hPowheg_Xsec_BornLogScale);
  TGraphErrors *RatioPowhegStatErrBand = new TGraphErrors(hRatioPowhegStatErrBand);
  TGraphErrors *RatioPowhegPDFErrBand = new TGraphErrors(hRatioPowhegPDFErrBand);

  /////==========Powheg related stuff Finished here=========================================
  
  
  
  /////==========FEWZ Starts here==============================================
  //
  // FEWZ X sec value and errors, making TGraph .
  TH1D* hFEWZ_Xsec_LinScale;
  hFEWZ_Xsec_LinScale = (TH1D*)f_Fewz->Get("hxsec")->Clone("hFEWZ_Xsec_LinScale");
  
  //Errors
  TH1D* hFEWZ_Xsec_ScaleError;
  hFEWZ_Xsec_ScaleError = (TH1D*)f_Fewz->Get("ScaleErr")->Clone("hFEWZ_Xsec_ScaleError");
  TH1D* hFEWZ_Xsec_PDFError;
  hFEWZ_Xsec_PDFError = (TH1D*)f_Fewz->Get("PDFErr")->Clone("hFEWZ_Xsec_PDFError");
  
  double FEWZ_Xsec_ScaleErr[14];
  double FEWZ_Xsec_PDFErr[14];
  double FEWZ_Xsec_TotalErr[14];
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    FEWZ_Xsec_ScaleErr[ipt] = 0.01*hFEWZ_Xsec_ScaleError->GetBinError(ipt)*hFEWZ_Xsec_LinScale->GetBinContent(ipt);
    FEWZ_Xsec_PDFErr[ipt]   = 0.01*hFEWZ_Xsec_PDFError->GetBinError(ipt)*hFEWZ_Xsec_LinScale->GetBinContent(ipt);
    
    FEWZ_Xsec_TotalErr[ipt] = sqrt( FEWZ_Xsec_ScaleErr[ipt]*FEWZ_Xsec_ScaleErr[ipt] + FEWZ_Xsec_PDFErr[ipt]*FEWZ_Xsec_PDFErr[ipt] );
  }
  
  // X-sex and error Log scale
  TH1D *hFEWZ_Xsec_LogScale   = new TH1D("hFEWZ_Xsec_LogScale","hFEWZ_Xsec_LogScale",nBins-1,WptLogBins);hFEWZ_Xsec_LogScale->Sumw2();
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    hFEWZ_Xsec_LogScale->SetBinContent(ipt,hFEWZ_Xsec_LinScale->GetBinContent(ipt)/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt));
    hFEWZ_Xsec_LogScale->SetBinError(ipt,FEWZ_Xsec_TotalErr[ipt]/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt));
  } 
  ///   Theory/Data ratio plot errors related to Real Data
  TH1D *hRatioFEWZStatErrBand = new TH1D("hRatioFEWZStatErrBand","hRatioFEWZStatErrBand",nBins-1,WptLogBins);hRatioFEWZStatErrBand->Sumw2();
  TH1D *hRatioFEWZScaleErr = new TH1D("hRatioFEWZScaleErr","hRatioFEWZScaleErr",nBins-1,WptLogBins);hRatioFEWZScaleErr->Sumw2();
  TH1D *hRatioFEWZQCDScaleErrBand = new TH1D("hRatioFEWZQCDScalePDFErrBand","hRatioFEWZQCDScalePDFErrBand",nBins-1,WptLogBins);hRatioFEWZQCDScalePDFErrBand->Sumw2();
  TH1D *hRatioFEWZScalePDFErrBand = new TH1D("hRatioFEWZScalePDFErrBand","hRatioFEWZScalePDFErrBand",nBins-1,WptLogBins);hRatioFEWZScalePDFErrBand->Sumw2();
  for( int ipt(1);ipt<=nBins-1;ipt++)
  {
    hRatioFEWZStatErrBand->SetBinContent(ipt,hFEWZ_Xsec_LogScale->GetBinContent(ipt)/hData_Xsec_BornLogScale->GetBinContent(ipt));
    hRatioFEWZStatErrBand->SetBinError(ipt,0.01);
    
    hRatioFEWZScaleErr->SetBinContent(ipt,hFEWZ_Xsec_LogScale->GetBinContent(ipt)/hData_Xsec_BornLogScale->GetBinContent(ipt));
    hRatioFEWZScaleErr->SetBinError(ipt,FEWZ_Xsec_ScaleErr[ipt]/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt));
  
    hRatioFEWZQCDScaleErrBand->SetBinContent(ipt,hFEWZ_Xsec_LogScale->GetBinContent(ipt)/hData_Xsec_BornLogScale->GetBinContent(ipt));
    hRatioFEWZQCDScaleErrBand->SetBinError(ipt,0.01 + hRatioFEWZScaleErr->GetBinError(ipt)/hData_Xsec_BornLogScale->GetBinContent(ipt));
  
    hRatioFEWZScalePDFErrBand->SetBinContent(ipt,hFEWZ_Xsec_LogScale->GetBinContent(ipt)/hData_Xsec_BornLogScale->GetBinContent(ipt));
    hRatioFEWZScalePDFErrBand->SetBinError(ipt,0.01+(hFEWZ_Xsec_LogScale->GetBinError(ipt)+hRatioFEWZScaleErr->GetBinError(ipt))/hData_Xsec_BornLogScale->GetBinContent(ipt));
  }
  
  /// TGraph
  TGraphErrors *FEWZ_Xsec = new TGraphErrors(hFEWZ_Xsec_LogScale);
  TGraphErrors* RatioFEWZStatErrBand = new TGraphErrors(hRatioFEWZStatErrBand);
  TGraphErrors* RatioFEWZQCDScaleErrBand = new TGraphErrors(hRatioFEWZQCDScaleErrBand);
  TGraphErrors* RatioFEWZScalePDFErrBand = new TGraphErrors(hRatioFEWZScalePDFErrBand);


  /////==========FEWZ related stuff Finished here=========================================
  
  
  /////==========ResBos Starts here==============================================
  //
  // ResBos X sec value and errors, making TGraph .
 
  TH1D* hResBos30_CentralYield_LinScale;
  hResBos30_CentralYield_LinScale = (TH1D*)f_Resbos->Get("hResbos30")->Clone("hResBos30_CentralYield_LinScale");

  TH1D* AllResbos[7];
  for( int i(0);i<7;i++)
  {
    Numb = 29+i;
    sprintf(tmpName_org,"hResbos%d",Numb);
    sprintf(tmpName,"AllResbos_%d",i);
    AllResbos[i] = (TH1D*)f_Resbos->Get(tmpName_org)->Clone(tmpName);
  }


  //Errors
  Double_t Resb_errMax[nBins-1];
  Double_t Resb_errMin[nBins-1];
  double tmpVal,tmpDiff;

  for( int ipt(0);ipt<nBins-1;ipt++)
  {
    double nomVal  = AllResbos[1]->GetBinContent(ipt+1);
    Resb_errMax[ipt] = -99999;
    Resb_errMin[ipt] = 990009;
    for (int i(0);i<7;i++)
    {
      tmpVal  = AllResbos[i]->GetBinContent(ipt+1);
      tmpDiff = tmpVal - nomVal;
      if( tmpDiff > Resb_errMax[ipt] ) Resb_errMax[ipt] = tmpDiff;
      if( tmpDiff < Resb_errMin[ipt] ) Resb_errMin[ipt] = tmpDiff;
    }

    if (Resb_errMax[ipt] < 0) Resb_errMax[ipt] = 0.;
    if (Resb_errMin[ipt] > 0) Resb_errMin[ipt] = 0.;
    if (Resb_errMin[ipt] < 0) Resb_errMin[ipt] = -Resb_errMin[ipt];
    Resb_errMax[ipt] = Resb_errMax[ipt]/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt+1);
    Resb_errMin[ipt] = Resb_errMin[ipt]/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt+1);
  }
  
  // X-sex and error Log scale
  TH1D *hResBos30_CentralYield_LogScale   = new TH1D("hResBos30_CentralYield_LogScale","hResBos30_CentralYield_LogScale",nBins-1,WptLogBins);hResBos30_CentralYield_LogScale->Sumw2();
  Double_t hResb30_CentralXsec[nBins-1];
  Double_t RatioResbVal[nBins-1],errResbosDataLo[nBins-1],errResbosDataHi[nBins-1];
  for( int ipt(0);ipt<nBins-1;ipt++)
  {
    hResBos30_CentralYield_LogScale->SetBinContent(ipt+1,hResBos30_CentralYield_LinScale->GetBinContent(ipt+1)/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt+1) );

    hResb30_CentralXsec[ipt] = hResBos30_CentralYield_LinScale->GetBinContent(ipt+1)/hWptBins_LinScale->GetXaxis()->GetBinWidth(ipt+1);
   
    RatioResbVal[ipt]=hResBos30_CentralYield_LogScale->GetBinContent(ipt+1)/hData_Xsec_BornLogScale->GetBinContent(ipt+1);
    errResbosDataLo[ipt]=Resb_errMin[ipt]/hData_Xsec_BornLogScale->GetBinContent(ipt+1);
    errResbosDataHi[ipt]=Resb_errMax[ipt]/hData_Xsec_BornLogScale->GetBinContent(ipt+1);

  }
  ///   Theory/Data ratio plot errors related to Real Data
  TGraphAsymmErrors *Resb30_CentralXsec = new TGraphAsymmErrors(nBins-1, ax, hResb30_CentralXsec, aex, aex, Resb_errMin, Resb_errMax);
  TGraphAsymmErrors *RatioResbosErrBand = new TGraphAsymmErrors(nBins-1, ax, RatioResbVal, aex, aex, errResbosDataLo, errResbosDataHi);
  

  /////==========ResBos related stuff Finished here=========================================
  
  
  
  
  //// Now design and Draw 
  
  //Data

  RatioDataErrBand->SetFillColor(kBlack);
  RatioDataErrBand->SetFillStyle(3354);
  
  //Powheg
  Powheg_Xsec_Born->SetFillColor(kRed);
  Powheg_Xsec_Born->SetFillStyle(3345);

  RatioPowhegStatErrBand->SetFillColor(kRed-10);
  RatioPowhegStatErrBand->SetFillStyle(3001);
  
  RatioPowhegPDFErrBand->SetFillColor(kRed+2);
  RatioPowhegPDFErrBand->SetFillStyle(3001);

  //FEWZ
  FEWZ_Xsec->SetFillColor(kGreen);
  FEWZ_Xsec->SetFillStyle(3444);
  
  RatioFEWZStatErrBand->SetFillColor(kGreen);
  RatioFEWZStatErrBand->SetFillStyle(3001);

  RatioFEWZQCDScaleErrBand->SetFillColor(kGreen+7);
  RatioFEWZQCDScaleErrBand->SetFillStyle(3001);

  RatioFEWZScalePDFErrBand->SetFillColor(kGreen+3);
  RatioFEWZScalePDFErrBand->SetFillStyle(3001);

  
  //ResBos
  Resb30_CentralXsec->SetFillColor(kBlue);
  Resb30_CentralXsec->SetFillStyle(3354);
 
  RatioResbosErrBand->SetFillColor(kBlue-7);
  RatioResbosErrBand->SetFillStyle(3001);
 

  TLegend *lL =new TLegend(0.2,0.2,0.52,0.38); lL->SetFillColor(0); lL->SetBorderSize(0);
  lL->AddEntry(Data_Xsec_Born,"data","PL");
  lL->AddEntry(Powheg_Xsec_Born,"POWHEG CT10 NLO","f");
  lL->AddEntry(FEWZ_Xsec,"FEWZ CT10 NNLO","f");
  lL->AddEntry(Resb30_CentralXsec,"ResBos CT10 NNLL","f");

  TPaveText *tb = new TPaveText(0.2,0.39,0.52,0.5,"NDC");
  tb->SetBorderSize(0);
  tb->SetFillStyle(0);
  tb->AddText("18.4 pb^{-1} at #sqrt{s} = 8 TeV");
  if (BaseName=="WpToMuNu")
    tb->AddText("W^{+} #rightarrow #mu^{+} #nu");
  if (BaseName=="WmToMuNu")
    tb->AddText("W^{-} #rightarrow #mu^{-} #bar{#nu}");
  if (BaseName=="WpToEleNu")
    tb->AddText("W^{+} #rightarrow e^{+} #nu");
  if (BaseName=="WmToEleNu")
    tb->AddText("W^{-} #rightarrow e^{-} #bar{#nu}");

  TCanvas *lC1 = new TCanvas("Can","Can",800,840); lC1->cd(); lC1->SetLogy();
  lC1->cd(1)->SetPad(0,0.05,0.95,1.0);
  lC1->cd(1)->SetTopMargin(0.05);
  lC1->cd(1)->SetBottomMargin(0.1);
  lC1->cd(1)->SetLeftMargin(0.15);
  lC1->cd(1)->SetRightMargin(0.07);
  lC1->cd(1)->SetTickx(1);
  lC1->cd(1)->SetTicky(1);
  gStyle->SetLineWidth(2.);
  gStyle->SetOptStat(0);
  gStyle->SetHatchesSpacing(0.75);
  gStyle->SetHatchesLineWidth(2);
  gPad->SetLogx(1);
  gPad->SetLogy(1);

  Powheg_Xsec_Born->GetYaxis()->SetRangeUser(1e-3,5*hResb30_CentralXsec[0]);
  Powheg_Xsec_Born->SetTitle("");
  Powheg_Xsec_Born->GetYaxis()->SetTitle("d#sigma/dp_{T}^{W} [pb/GeV]");
  Powheg_Xsec_Born->GetYaxis()->SetTitleOffset(1.8);
  Powheg_Xsec_Born->GetXaxis()->SetTitle("p_{T}^{W} [GeV]");
  
  TPaveText *cmspre = new TPaveText(0.63,0.95,0.95,0.99,"NDC");
  cmspre->SetBorderSize(0);
  cmspre->SetFillStyle(0);
  cmspre->AddText("CMS Preliminary");
  Powheg_Xsec_Born->Draw("A2");
  FEWZ_Xsec->Draw("2");
  Resb30_CentralXsec->Draw("2");
  Data_Xsec_Born->Draw("p");

  lL->Draw();
  tb->Draw();
  cmspre->Draw();
  
  if(BaseName=="WpToMuNu")
    sprintf(tmpName,"wpmnCrossSec.png");
  if(BaseName=="WmToMuNu")
    sprintf(tmpName,"wmmnCrossSec.png");
  if(BaseName=="WpToEleNu")
    sprintf(tmpName,"wpenCrossSec.png");
  if(BaseName=="WmToEleNu")
    sprintf(tmpName,"wmenCrossSec.png");
  lC1->SaveAs(tmpName);
  
  TCanvas *lC2 = new TCanvas("Can","Can",800,800); lC2->cd(); lC2->SetLogy();
  lC2->Divide(1,3,0,0);
  lC2->cd(1)->SetPad(0,0.67,0.95,0.95);
  lC2->cd(1)->SetTopMargin(0.15);
  lC2->cd(1)->SetBottomMargin(0.01);
  lC2->cd(1)->SetLeftMargin(0.15);
  lC2->cd(1)->SetRightMargin(0.07);
  lC2->cd(1)->SetTickx(1);
  lC2->cd(1)->SetTicky(1);
  lC2->cd(1)->SetLogx(1);

  TPaveText *tb1 = new TPaveText(0.15,0.72,0.35,0.82,"NDC");
  tb1->SetBorderSize(0);
  tb1->SetFillStyle(0);
  tb1->SetTextSize(0.12);
  tb1->AddText("ResBos");
  TLegend *rL1 =new TLegend(0.2,0.1,0.58,0.30); rL1->SetFillColor(0); rL1->SetBorderSize(0);
  rL1-> SetNColumns(2);
  rL1->AddEntry(RatioResbosErrBand,"Theory syst","F");
  rL1->AddEntry(hRatioDataStatErr,"Data stat","PLE1");
  hRatioDataStatErr->SetTitle("");
  rL1->AddEntry(hRatioDataStatErr,"","");
  rL1->AddEntry(RatioDataErrBand,"Data stat+syst","F");
  rL1->SetTextSize(0.07);
  
  TLegend *tL1 =new TLegend(0.17,0.72,0.37,0.82); tL1->SetFillColor(0); tL1->SetBorderSize(0);
  tL1->AddEntry(RatioResbosErrBand,"ResBos","F");
  tL1->SetTextSize(0.12);
  tL1->SetTextFont(2);

  TPaveText *cmspre2 = new TPaveText(0.05,0.92,0.85,0.99,"NDC");
  cmspre2->SetBorderSize(0);
  cmspre2->SetFillStyle(0);
  cmspre2->SetTextSize(0.10);
  cmspre2->AddText("CMS Preliminary, 18.4 pb^{-1} at #sqrt{s} = 8 TeV");

  TPaveText *tb4 = new TPaveText(0.35,0.72,0.67,0.83,"NDC");
  tb4->SetBorderSize(0);
  tb4->SetFillStyle(0);
  if (BaseName=="WpToMuNu")
    tb4->AddText("W^{+} #rightarrow #mu^{+} #nu");
  if (BaseName=="WmToMuNu")
    tb4->AddText("W^{-} #rightarrow #mu^{-} #bar{#nu}");
  if (BaseName=="WpToEleNu")
    tb4->AddText("W^{+} #rightarrow e^{+} #nu");
  if (BaseName=="WmToEleNu")
    tb4->AddText("W^{-} #rightarrow e^{-} #bar{#nu}");
  
  
  drawDifference(hResBos30_CentralYield_LogScale, hData_Xsec_BornLogScale, hRatioDataErrBand, RatioPowhegStatErrBand,1,RatioPowhegStatErrBand,RatioResbosErrBand,hRatioDataStatErr,RatioFEWZQCDScaleErrBand);
  rL1->Draw();
  //tb1->Draw();
  tL1->Draw();
  tb4->Draw();
  cmspre2->Draw();

  lC2->cd(2)->SetPad(0,0.37,0.95,0.65);
  lC2->cd(2)->SetTopMargin(0.01);
  lC2->cd(2)->SetBottomMargin(0.01);
  lC2->cd(2)->SetLeftMargin(0.15);
  lC2->cd(2)->SetRightMargin(0.07);
  lC2->cd(2)->SetTickx(1);
  lC2->cd(2)->SetTicky(1);
  lC2->cd(2)->SetLogx(1);

  TPaveText *tb2 = new TPaveText(0.15,0.82,0.35,0.92,"NDC");
  tb2->SetBorderSize(0);
  tb2->SetFillStyle(0);
  tb2->SetTextSize(0.12);
  tb2->AddText("Powheg");
  TLegend *rL2 =new TLegend(0.2,0.05,0.68,0.30); rL2->SetFillColor(0); rL2->SetBorderSize(0);
  rL2-> SetNColumns(2);
  rL2->AddEntry(RatioPowhegPDFErrBand,"PDF    ","F");
  rL2->AddEntry(hRatioDataStatErr,"Data stat","PLE1");
  rL2->AddEntry(RatioPowhegStatErrBand,"stat","F");
  rL2->AddEntry(RatioDataErrBand,"Data stat+syst","F");
  rL2->SetTextSize(0.07);

  TLegend *tL2 =new TLegend(0.17,0.85,0.37,0.95); tL2->SetFillColor(0); tL2->SetBorderSize(0);
  tL2->AddEntry(RatioPowhegPDFErrBand,"POWHEG","F");
  tL2->SetTextSize(0.12);
  tL2->SetTextFont(2);
  
  //drawDifference(hPowhegLog,hDataLog,hDataErrBand,pRatio,2,pRatioPDF,ResbosErrBand,hStatErr,fScaleRatio);
  //drawDifference(Powheg_Xsec_Born,hData_Xsec_BornLogScale,hRatioDataErrBand,RatioPowhegStatErrBand,2,RatioPowhegPDFErrBand,RatioResbosErrBand,hRatioDataStatErr,RatioFEWZQCDScaleErrBand);
  drawDifference(hPowheg_Xsec_BornLogScale,hData_Xsec_BornLogScale,hRatioDataErrBand,RatioPowhegStatErrBand,2,RatioPowhegPDFErrBand,RatioResbosErrBand,hRatioDataStatErr,RatioFEWZQCDScaleErrBand);
  rL2->Draw();
  tL2->Draw();

  lC2->cd(3)->SetPad(0,0.07,0.95,0.35);
  lC2->cd(3)->SetTopMargin(0.01);
  lC2->cd(3)->SetBottomMargin(0.05);
  lC2->cd(3)->SetLeftMargin(0.15);
  lC2->cd(3)->SetRightMargin(0.07);
  lC2->cd(3)->SetTickx(1);
  lC2->cd(3)->SetTicky(1);
  lC2->cd(3)->SetLogx(1);

  TPaveText *tb3 = new TPaveText(0.15,0.82,0.35,0.92,"NDC");
  tb3->SetBorderSize(0);
  tb3->SetFillStyle(0);
  tb3->SetTextSize(0.12);
  tb3->AddText("Fewz");
  TLegend *rL3 =new TLegend(0.2,0.1,0.58,0.30); rL3->SetFillColor(0); rL3->SetBorderSize(0);
  rL3-> SetNColumns(2);
  rL3->AddEntry(RatioFEWZScalePDFErrBand,"PDF","F");
  rL3->AddEntry(hRatioDataStatErr,"Data stat","PLE1");
  rL3->AddEntry(RatioFEWZQCDScaleErrBand,"QCD scales","F");
  rL3->AddEntry(RatioDataErrBand,"Data stat+syst","F");
  rL3->AddEntry(RatioFEWZStatErrBand,"stat","F");
  rL3->SetTextSize(0.07);

  TLegend *tL3 =new TLegend(0.17,0.85,0.37,0.95); tL3->SetFillColor(0); tL3->SetBorderSize(0);
  tL3->AddEntry(RatioFEWZScalePDFErrBand,"FEWZ","F");
  tL3->SetTextSize(0.12);
  tL3->SetTextFont(2);
  
  drawDifference(hFEWZ_Xsec_LogScale,hData_Xsec_BornLogScale,hRatioDataErrBand,RatioFEWZStatErrBand,3,RatioFEWZScalePDFErrBand,RatioResbosErrBand,hRatioDataStatErr,RatioFEWZQCDScaleErrBand);
  rL3->Draw();
  tL3->Draw();

  if(BaseName=="WpToMuNu")
    sprintf(tmpName,"wpmnRatioTheoData.png");
  if(BaseName=="WmToMuNu")
    sprintf(tmpName,"wmmnRatioTheoData.png");
  if(BaseName=="WpToEleNu")
    sprintf(tmpName,"wpenRatioTheoData.png");
  if(BaseName=="WmToEleNu")
    sprintf(tmpName,"wmenRatioTheoData.png");
  lC2->SaveAs(tmpName);

  return 0;
}