Exemplo n.º 1
0
// Called within makePlot when making the pu plot
// Basically adds in the +/- 5% systematic error bars
TGraphAsymmErrors makePUPlot( THStack stack, TString anaType, const float lumi ) {

  // Got the stack, now sum the =/- 5% histograms and make two new stacks
  // Make dummy legend etc.
  THStack p5Stack("Background MC p5","");
  THStack m5Stack("Background MC m5","");
  TLegend *legend= new TLegend(0.1,0.1,0.1,0.1);

  addBackgroundHistos( anaType, "nRecoPV_p5", p5Stack, legend, lumi );
  addBackgroundHistos( anaType, "nRecoPV_m5", m5Stack, legend, lumi );

  // Get last histogram in stacks i.e. sum of all backgrounds
  TH1F * hist = new TH1F( *(TH1F*)(stack.GetStack()->Last()) );
  TH1F * p5Hist = new TH1F( *(TH1F*)p5Stack.GetStack()->Last() );
  TH1F * m5Hist = new TH1F( *(TH1F*)m5Stack.GetStack()->Last() );

  // Create structures to make TGraphAssymErrors
  Int_t n=p5Hist->GetNbinsX();
  Double_t x[n]; // x values
  Double_t y[n]; // y values
  Double_t exl[n]; // low x error
  Double_t eyl[n]; // low y error
  Double_t exh[n]; // high x error
  Double_t eyh[n]; // high y error

  // Loop over histos and get values
  for ( int bin=1; bin < n+1; bin++ ) {
    x[bin-1]=hist->GetBinCenter( bin );
    y[bin-1]=hist->GetBinContent( bin );
    exl[bin-1]=hist->GetBinWidth( bin )/2;
    eyl[bin-1]=p5Hist->GetBinContent( bin )-y[bin-1];
    exh[bin-1]=hist->GetBinWidth( bin )/2;
    eyh[bin-1]=y[bin-1]-m5Hist->GetBinContent( bin );
  }


  // Make TGraphAssymErrors
  TGraphAsymmErrors gr(n,x,y,exl,exh,eyl,eyh);

  return gr;
}
int main(int argc, char** argv)
{ 
 TDRStyle();
 
 gStyle->SetPadTopMargin(0.11);
 gStyle->SetPadLeftMargin(0.07);
 gStyle->SetPadRightMargin(0.23);
 gStyle->cd(); 
 
 
 std::cout << " " << std::endl;
 std::cout << " " << std::endl;
 std::cout << "      ___|                       |                     \\  |   ___|         /      __ \\     \\  __ __|   \\          " << std::endl;
 std::cout << "     |       _ \\   |   |  __ \\   __|   _ \\   __|      |\\/ |  |            /       |   |   _ \\    |    _ \\       " << std::endl;
 std::cout << "     |      (   |  |   |  |   |  |     __/  |         |   |  |           /        |   |  ___ \\   |   ___ \\          " << std::endl;
 std::cout << "    \\____| \\___/  \\__,_| _|  _| \\__| \\___| _|        _|  _| \\____|     _/        ____/ _/    _\\ _| _/    _\\   " << std::endl; 
 std::cout << " " << std::endl;
 std::cout << " " << std::endl; 
 std::cout << " " << std::endl; 
 std::cout << "      ___|                |                            |   _)                         " << std::endl;
 std::cout << "    \\___ \\   |   |   __|  __|   _ \\  __ `__ \\    _` |  __|  |   __|   __|         " << std::endl;
 std::cout << "          |  |   | \\__ \\  |     __/  |   |   |  (   |  |    |  (    \\__ \\     " << std::endl;
 std::cout << "    _____/  \\__, | ____/ \\__| \\___| _|  _|  _| \\__,_| \\__| _| \\___| ____/       " << std::endl;
 std::cout << "            ____/                                                                     " << std::endl;
 std::cout << " " << std::endl;
 std::cout << " " << std::endl;
 
 
 
 
 char normal[] = { 0x1b, '[', '0', ';', '3', '9', 'm', 0 };
 char black[] = { 0x1b, '[', '0', ';', '3', '0', 'm', 0 };
 char red[] = { 0x1b, '[', '0', ';', '3', '1', 'm', 0 };
 char green[] = { 0x1b, '[', '0', ';', '3', '2', 'm', 0 };
 char yellow[] = { 0x1b, '[', '0', ';', '3', '3', 'm', 0 };
 char blue[] = { 0x1b, '[', '0', ';', '3', '4', 'm', 0 };
 char purple[] = { 0x1b, '[', '0', ';', '3', '5', 'm', 0 };
 char cyan[] = { 0x1b, '[', '0', ';', '3', '6', 'm', 0 };
 char Lgray[] = { 0x1b, '[', '0', ';', '3', '7', 'm', 0 };
 char Dgray[] = { 0x1b, '[', '0', ';', '3', '8', 'm', 0 };
 char Bred[] = { 0x1b, '[', '1', ';', '3', '1', 'm', 0 };
 //for bold colors, just change the 0 after the [ to a 1
 
 EColor vColor[1000] = {
  kGreen,
  //kMagenta,(EColor) (kMagenta+1),(EColor) (kMagenta+2),
  kTeal,//(EColor) (kTeal+1),
  kRed,
  kGray,
  kOrange,(EColor) (kOrange+1),
  kBlue,//(EColor)(kBlue+1),(EColor) (kBlue+2),
  (EColor) (kPink+2),//(EColor) (kPink+1),(EColor) (kPink+2),
  kViolet,
  kYellow,
  kGray,(EColor) (kGray+1),(EColor) (kViolet),(EColor) (kYellow),(EColor) (kGray)
 };
 
 
 
 
 //Check if all nedeed arguments to parse are there                                                                                                                               
 if(argc != 2)
 {
  std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
  return 1;
 }


 // Parse the config file                                                                                                                                                          
 parseConfigFile (argv[1]) ;
 
 std::string treeName  = gConfigParser -> readStringOption("Input::treeName");
 std::string treeNameSelections = gConfigParser -> readStringOption("Input::treeNameSelections");
 std::string fileSamples = gConfigParser -> readStringOption("Input::fileSamples");
 std::string inputDirectory = gConfigParser -> readStringOption("Input::inputDirectory");
 
 double LUMI = gConfigParser -> readDoubleOption("Input::Lumi");
 
 double LumiSyst = gConfigParser -> readDoubleOption("Input::LumiSyst");
 
 double Discovery = gConfigParser -> readDoubleOption("Input::Discovery");
 
 std::vector<std::string> SignalName;
 SignalName = gConfigParser -> readStringListOption("Input::SignalName");
 
 ///==== PU reweight (begin) ====
 std::vector<double> PUMC   = gConfigParser -> readDoubleListOption("PU::PUMC");
 std::vector<double> PUDATA = gConfigParser -> readDoubleListOption("PU::PUDATA");
 PUclass PU;
 
 std::cout << " PUMC.size()   = " << PUMC.size()   << std::endl;
 std::cout << " PUDATA.size() = " << PUDATA.size() << std::endl;
 
 if (PUMC.size() != PUDATA.size()) {
  std::cerr << " ERROR " << std::endl;
  return 1;
 }
 
 double sumPUMC = 0;
 for (int itVPU = 0; itVPU < PUMC.size(); itVPU++ ){
  sumPUMC += PUMC.at(itVPU);  
 }
 double sumPUDATA = 0;
 for (int itVPU = 0; itVPU < PUDATA.size(); itVPU++ ){
  sumPUDATA += PUDATA.at(itVPU);  
 } 
 
 for (int itVPU = 0; itVPU < PUMC.size(); itVPU++ ){
  PU.PUWeight.push_back(PUDATA.at(itVPU) / PUMC.at(itVPU) * sumPUMC / sumPUDATA);
 }

 PU.Write("autoWeight.cxx");
 gROOT->ProcessLine(".L autoWeight.cxx");
 ///==== PU reweight (end) ====
 
 ///==== save PU distribution in TH1F ====
 TH1F* hPUMC   = new TH1F("hPUMC","hPUMC",PUMC.size(),0,PUMC.size());
 TH1F* hPUDATA = new TH1F("hPUDATA","hPUDATA",PUDATA.size(),0,PUDATA.size());
 TH1F* hPUWeight = new TH1F("hPUWeight","hPUWeight",PUDATA.size(),0,PUDATA.size());
 
 for (int itVPU = 0; itVPU < PUMC.size(); itVPU++ ){
  hPUMC     -> SetBinContent(itVPU+1,PUMC.at(itVPU) / sumPUMC);
  hPUDATA   -> SetBinContent(itVPU+1,PUDATA.at(itVPU) / sumPUDATA);
  hPUWeight -> SetBinContent(itVPU+1,PUDATA.at(itVPU) / PUMC.at(itVPU) * sumPUMC / sumPUDATA);
 }
 
 
 
 TTree *treeEffVect[100];
 TTree *treeJetLepVect[100];
 

 
  //  [iCut] 
 TString* infoString[20];
 TLatex *infoLatex[20]; 
 TCanvas* ccCanvas[20];
 TCanvas* ccCanvasPull[20];
 TH1F* histoSumMC[20];
 //  [iName][iCut]
 TH1F* histo[100][20];
 TH1F* histo_temp[100][20];

 //  [iName][iCut]
 double numEvents[100][20];
 
 char *nameSample[1000];
 char *nameHumanReadable[1000];
 char* xsectionName[1000];
 
 double Normalization[1000];
 double xsection[1000];
 char nameFileIn[1000];
 sprintf(nameFileIn,"%s",fileSamples.c_str());

 int numberOfSamples = ReadFile(nameFileIn, nameSample, nameHumanReadable, xsectionName);

 
 double XSection  = gConfigParser -> readDoubleOption("Plot::XSection");
 
 ///==== list of selections to perform (NOT sequential additive selections) ====
 std::string CutFile = gConfigParser -> readStringOption("Selections::CutFile");
 std::vector<std::string> vCut;
 std::cout << " nCuts = " << ReadFileCut(CutFile, vCut) << std::endl;
 
 
 ///==== list of systematic variables to change ====
//  std::string CutSystematicFile = gConfigParser -> readfStringOption("Selections::CutSystematicFile");
// 
//  std::vector< std::pair< int, std::pair<std::string, double> > > listSystematics;
//  ReadFileSystematics(CutSystematicFile, listSystematics);
//  ModifyCut(vCut,listSystematics);

 
  std::string CutSystematicFile = gConfigParser -> readStringOption("Selections::CutSystematicFile");
 
  std::vector< std::pair< std::string, std::string> > listSystematics;
  ReadFileSystematicsWithRegion(CutSystematicFile, listSystematics);
  ModifyCutWithRegion(vCut,listSystematics);
  
  
  
  ///==== something to load/exec ====
  try {
   std::string toLoad = gConfigParser -> readStringOption("Exec::ToLoad");
   std::string toExec = ".L ";
   toExec += toLoad;
   toExec += ".cxx";
   gROOT->ProcessLine(toExec.c_str());
   std::cout << std::endl;
   std::cout << " load: " << toLoad.c_str() << std::endl;
   std::cout << " do:   " << toExec.c_str() << std::endl;
   std::cout << std::endl;
  }
  catch (char const* exceptionString){
   std::cerr << " exception = " << exceptionString << std::endl;
  }
  
 
 ///==== output file ====
 std::string OutFileName    = gConfigParser -> readStringOption("Output::outFileName");
 std::cout << ">>>>> Output::outFileName  " << OutFileName  << std::endl;  
 
 TFile outFile(OutFileName.c_str(),"RECREATE");
 outFile.cd();
 
 
 ///==== debug flag ====
 
 bool  debug = false; 
 try {
  debug = gConfigParser -> readBoolOption("Input::debug");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> input::debug  " << debug  << std::endl;  
 
 ///==== program ====
 
 
 double start, end;
 start = clock();
 
 
 for (int iSample=0; iSample<numberOfSamples; iSample++){
  xsection[iSample] = atof(xsectionName[iSample]);
 }
 
 for (int iSample=0; iSample<numberOfSamples; iSample++){
  
  char nameFile[20000];
  sprintf(nameFile,"%s/out_NtupleProducer_%s.root",inputDirectory.c_str(),nameSample[iSample]);  
  TFile* f = new TFile(nameFile, "READ");
  
  treeEffVect[iSample] = (TTree*) f->Get(treeNameSelections.c_str());
  char nameTreeEff[100];
  sprintf(nameTreeEff,"treeEff_%d",iSample); 
  treeEffVect[iSample]->SetName(nameTreeEff);      
  
  treeJetLepVect[iSample] = (TTree*) f->Get(treeName.c_str());
  char nameTreeJetLep[100];
  sprintf(nameTreeJetLep,"treeJetLep_%d",iSample); 
  treeJetLepVect[iSample]->SetName(nameTreeJetLep);
 }
 
 ///===== create map for joint sample ====
 
 std::vector<int> join_samples;
 std::vector<std::string> name_samples;
 for (int iSample=0; iSample<numberOfSamples; iSample++){
  name_samples.push_back(nameHumanReadable[iSample]);
  join_samples.push_back(-1);
 }
 
 
 std::vector<std::string> reduced_name_samples;
 std::vector<int>         reduced_name_samples_flag;
 for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
  bool flag_name = false;
  for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
   if (reduced_name_samples.at(iName) == name_samples.at(iSample)) flag_name = true;
  }
  if (flag_name == false) {
   reduced_name_samples.push_back(name_samples.at(iSample));
   reduced_name_samples_flag.push_back(-1);
  }
 }
 
 std::cout << " numberOfSamples = " << numberOfSamples << std::endl;
 
 for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
  double XSection;
  int numEntriesBefore;
  double preselection_efficiency;
  treeEffVect[iSample]->SetBranchAddress("XSection",&XSection);
  treeEffVect[iSample]->SetBranchAddress("numEntriesBefore",&numEntriesBefore);
  treeEffVect[iSample]->SetBranchAddress("preselection_efficiency",&preselection_efficiency);  
  treeEffVect[iSample]->GetEntry(0);
  
  std::cout << " Xsection = " << XSection << " ~~~> " << xsection[iSample] << std::endl;
  XSection = xsection[iSample];
  
  if (numEntriesBefore != 0) {
   Normalization[iSample] = LUMI * XSection * preselection_efficiency / numEntriesBefore;
  }
  else {
   Normalization[iSample] = 0; 
  }    
 }
 
 
 
 TLegend* leg = new TLegend(0.8,0.25,0.98,0.78);
 bool LegendBuilt = false;

 TString lumiName = Form("#splitline{L = %.1f pb^{-1}}{#splitline{#sqrt{s} = 7}{CMS preliminary}}", LUMI);
//  TString lumiName = Form("#sqrt{s}=7 TeV   L=%.1f pb^{-1}", LUMI);
 TLatex *latex = new TLatex(0.80, 0.90, lumiName); 
 latex->SetTextAlign(12);
 latex->SetNDC();
 latex->SetTextFont(42);
 latex->SetTextSize(0.03);
  
 ///==== get number in sample list that correspond to DATA ====
 int numDATA = -1;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  if (reduced_name_samples.at(iName) == "DATA") {
   numDATA = iName;
  }
 }
 
 
 if (debug) std::cout << " Cut size = " << vCut.size() << " ~~ " << std::endl;
 std::cout.precision (2) ;
 std::cout.unsetf(std::ios::scientific);
 ///==== cicle on selections ====
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  TString Cut = Form ("%s",vCut.at(iCut).c_str());
  if (debug) std::cout << " Cut[" << iCut << ":" << vCut.size() << "] = " << Cut.Data() << " ~~ " << std::endl;
  ///==== initialize ====
  for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
   reduced_name_samples_flag.at(iName) = -1;
  }
  
  ///==== cicle on samples ====
  for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
   if (debug) std::cout << " Sample[" << iSample << ":" << numberOfSamples << "] = " << nameSample[iSample] << " ~~ " << std::endl;
   TString name_histo_temp = Form("%s_%d_temp",nameSample[iSample], iCut);
   histo_temp[iSample][iCut] = new TH1F(name_histo_temp,name_histo_temp,100,-10,10000000000);
   char toDraw[1000];
   sprintf(toDraw,"eventId >> %s",name_histo_temp.Data());      
   histo_temp[iSample][iCut] -> Sumw2(); //---- così mette l'errore giusto!
   
   TString CutExtended;
   bool isData = false;
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    if (name_samples.at(iSample) == reduced_name_samples.at(iName)){
     if (iName == numDATA) {
      isData = true;
     }
    }
   }  
   if (!isData) {
    CutExtended = Form ("(%s) * autoWeight(numPUMC)",Cut.Data());    
   }
   else {
    CutExtended = Form ("(%s)",Cut.Data());    
   }
   if (debug) std::cerr << " drawing ..." << std::endl;
   treeJetLepVect[iSample]->Draw(toDraw,CutExtended,"");
   if (debug) std::cerr << " drawn ..." << std::endl;
   
   if (Normalization[iSample]>0) { 
    histo_temp[iSample][iCut] -> Scale(Normalization[iSample]); 
   }
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    if (name_samples.at(iSample) == reduced_name_samples.at(iName)){
     if (reduced_name_samples_flag.at(iName) == -1){
      TString name_histoTot_temp = Form("%s_%d_Tot_temp",reduced_name_samples.at(iName).c_str(),iCut);
      TString name_HR_histoTot_temp = Form("cut %d",iCut);
      histo[iName][iCut] = new TH1F(name_histoTot_temp,name_HR_histoTot_temp,100,-10,10000000000);
      histo[iName][iCut] -> Sumw2(); //---- così mette l'errore giusto!
      reduced_name_samples_flag.at(iName) = 1;
     }
     histo[iName][iCut] -> Add(histo_temp[iSample][iCut]);
    }
   }
   std::cout << "Processing: " << blue << (((double) iCut)/vCut.size())*100. << "% "  << normal <<  " -- " <<  red << (((double) numberOfSamples - iSample)/(numberOfSamples))*100. << "% \r"  << normal << std::flush;   
  } ///==== end cicle on samples ====
//   std::cout << "Processing: " << blue << (((double) iCut)/vCut.size())*100. << "% \r"  << normal << std::flush;   
 } ///==== end cicle on selections ====
 
 //  [iName]
 TH1F* hTrend[100];
 THStack* hsTrend;
 //  [iCut]
 TPie* hTrendPie[100];
 
 //  [iCut]
 THStack* hs[100];
 
 std::cout << std::endl;
 
 ///==== cicle on selections ====
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  TString nameStack = Form("%d_stack",iCut);
  hs[iCut] = new THStack(nameStack,nameStack);
  
  for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
   histo[iName][iCut]->GetXaxis()->SetTitle("eventId");
   histo[iName][iCut]->SetMarkerColor(vColor[iName]);
   histo[iName][iCut]->SetLineColor(vColor[iName]);
   histo[iName][iCut]->SetFillColor(vColor[iName]);
   histo[iName][iCut]->SetLineWidth(2);
   histo[iName][iCut]->SetFillStyle(3001);
   
   bool isSig = false;
   for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
    if (reduced_name_samples.at(iName) == *itSig) isSig = true;
   }
   
   if (!isSig && reduced_name_samples.at(iName) != "DATA") {
    hs[iCut]->Add(histo[iName][iCut]);
   }
   else {
    if (!isSig) {
     histo[iName][iCut]->SetMarkerStyle(20);
     histo[iName][iCut]->SetMarkerSize(1);
     histo[iName][iCut]->SetMarkerColor(kBlack);
     histo[iName][iCut]->SetLineColor(kBlack);
     histo[iName][iCut]->SetFillColor(kBlack);
     histo[iName][iCut]->SetLineWidth(2);
     histo[iName][iCut]->SetFillStyle(3001);  
    }
    else {
     histo[iName][iCut]->SetMarkerStyle(21);
     histo[iName][iCut]->SetMarkerSize(1);
     histo[iName][iCut]->SetLineWidth(2);
     histo[iName][iCut]->SetFillStyle(3001);  
    }
   }
  }
  ///==== histo sum MC ====    
  ///==== Add systrematic error ====
  AddError(hs[iCut],LumiSyst);
  histoSumMC[iCut] = ((TH1F*)(hs[iCut]->GetStack()->Last()));

  std::cout << " MC / DATA[" << iCut << "] = "<< histoSumMC[iCut]->Integral() << " / " << histo[numDATA][iCut]->Integral() << " = " << (histo[numDATA][iCut]->Integral() ? histoSumMC[iCut]->Integral()/ histo[numDATA][iCut]->Integral() : 0) << std::endl;
  
  ///==== legend ====
  if (!LegendBuilt){
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    leg->AddEntry(histo[iName][iCut],reduced_name_samples.at(iName).c_str(),"pf");    
    LegendBuilt = true;
   }
  }
 }
 std::cout << std::endl << std::endl;
 
 ///==== calculate number of events after each step of the analysis ====
 //  [iName][iCut]
 hsTrend = new THStack("Trend","Trend");
 
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  TString nameTHTrendPie = Form("%d_Trend_Pie",iCut);
  hTrendPie[iCut] = new TPie (nameTHTrendPie,nameTHTrendPie,reduced_name_samples.size());
 }
 
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  TString nameTHTrend = Form("%s_Trend",reduced_name_samples.at(iName).c_str());
  hTrend[iName] = new TH1F (nameTHTrend,nameTHTrend,vCut.size()+1,0,vCut.size()+1);
  hTrend[iName]->GetXaxis()->SetTitle("Selections");

  if (iName == numDATA) {
   hTrend[iName]->SetMarkerStyle(20);
   hTrend[iName]->SetMarkerSize(1);
   hTrend[iName]->SetMarkerColor(kBlack);
   hTrend[iName]->SetLineColor(kBlack);
   hTrend[iName]->SetFillColor(kBlack);
   hTrend[iName]->SetLineWidth(2);
   hTrend[iName]->SetFillStyle(3001);  
  }
  else {
   hTrend[iName]->SetMarkerColor(vColor[iName]);
   hTrend[iName]->SetLineColor(vColor[iName]);
   hTrend[iName]->SetFillColor(vColor[iName]);
   hTrend[iName]->SetLineWidth(2);
   hTrend[iName]->SetFillStyle(3001);
  }
  for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
   double error = 0;
   numEvents[iName][iCut] = histo[iName][iCut]->IntegralAndError(0,histo[iName][iCut]->GetNbinsX()+1,error);
   hTrend[iName]->SetBinContent(iCut+1,numEvents[iName][iCut]);
   hTrend[iName]->SetBinError(iCut+1,error);

   TString nameBin = Form("%d",iCut);
   hTrend[iName]->GetXaxis()->SetBinLabel(iCut+1,nameBin);
//     IntegralAndError
//     Double_t IntegralAndError(Int_t binx1, Int_t binx2, Double_t& err, Option_t* option = "") const
   std::cout << ">>>  numEvents[" << iName << "," << reduced_name_samples.at(iName) << "][" << iCut << "] = " << numEvents[iName][iCut] << " , " << histo[iName][iCut]->GetEntries() << " , " << histo[iName][iCut]->GetEffectiveEntries() << std::endl;
   
   if (iName != numDATA) {
    hTrendPie[iCut]->SetTextSize(0.04);
    hTrendPie[iCut]->SetTextFont(12);
    hTrendPie[iCut]->SetEntryFillColor(iName,vColor[iName]);
    hTrendPie[iCut]->SetEntryFillStyle(iName,3001);
    hTrendPie[iCut]->SetEntryLabel(iName, reduced_name_samples.at(iName).c_str());
    hTrendPie[iCut]->SetEntryLineColor(iName, vColor[iName]);
    hTrendPie[iCut]->SetEntryLineStyle(iName, 2);
    hTrendPie[iCut]->SetEntryLineWidth(iName, 2);
    hTrendPie[iCut]->SetEntryRadiusOffset(iName, 0.01);
    hTrendPie[iCut]->SetEntryVal(iName,numEvents[iName][iCut]);
   }
   else {
    hTrendPie[iCut]->SetEntryLabel(iName, "");
   }
  }
  if (iName != numDATA) {
   hsTrend->Add(hTrend[iName]);
  }
 }
 AddError(hsTrend,LumiSyst);
 
 TH1F* hTrendSumMC = ((TH1F*)(hsTrend->GetStack()->Last()));
 ///==== hTrend with pull plot ====
 TH1F* hPullTrendSumMC = PullPlot(hTrend[numDATA], hTrendSumMC);
  
 LumiSyst = 0; ///---- bug fix
 
 
 
 
 TCanvas* cTrendPie[100];
 TCanvas* cTrendPieAll = new TCanvas("cTrendPieAll","cTrendPieAll",400 * vCut.size(),400);
 cTrendPieAll -> Divide (vCut.size());
 TCanvas* cTrend = new TCanvas("cTrend","cTrend",400,400);
 TCanvas* cTrendSample[100];
 
 
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  TString nameCanvas = Form("%d_Canvas_Sample",iName);
  cTrendSample[iName] = new TCanvas(nameCanvas,nameCanvas,400,400);
  hTrend[iName] -> Draw();
  gPad->SetLogy();
  gPad->SetGrid();
 }
 
 
 
 
 
 
 ///~~~~ for efficiency calculation ~~~~
 
 std::vector<double> numEntriesFirstStep_reduced_samples;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  numEntriesFirstStep_reduced_samples.push_back(0);
  for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
   if (name_samples.at(iSample) == reduced_name_samples.at(iName)){
//     numEntriesFirstStep_reduced_samples.at(iName) += (Normalization[iSample] ? (1. / Normalization[iSample] * LUMI * xsection[iSample] * LUMI * xsection[iSample]) : -1);
    numEntriesFirstStep_reduced_samples.at(iName) += (xsection[iSample] * LUMI);
   }
  }
 }
//   Normalization[iSample] = LUMI * XSection * preselection_efficiency / numEntriesBefore;
//   1. / Normalization[iSample] = numEntriesBefore / preselection_efficiency / LUMI / XSection;
//   1. / Normalization[iSample] * LUMI * xsection[iSample] = numEntriesBefore / preselection_efficiency;
//   1. / Normalization[iSample] * LUMI * xsection[iSample] * LUMI * xsection[iSample] = numEntriesBefore / preselection_efficiency * LUMI * xsection[iSample];

 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << "[" << reduced_name_samples.at(iName) << "] = " << numEntriesFirstStep_reduced_samples.at(iName) << std::endl;
 }
 
 std::cout.precision (2) ;
 std::cout.unsetf(std::ios::scientific);


 
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << " *********************************** " << std::endl;
 std::cout << std::setw (12) << "sample";
 std::cout << " | " << std::setw (8) <<  -1;
 std::cout << " [" << std::setw (8) <<  "XXX";
 std::cout << " ]";
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  std::cout << " | " << std::setw (8) <<  iCut;
  std::cout << " [" << std::setw (8) <<  "XXX";
  std::cout << " ]";
 }
 std::cout << std::endl;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << std::setw (12) << reduced_name_samples.at(iName) ;
  std::cout << " | " << cyan << std::setw (8) <<  numEntriesFirstStep_reduced_samples.at(iName);
  std::cout << normal << " [" << std::setw (8) <<  "XXX";
  std::cout << " ]";
  for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
   std::cout << " | " << blue << std::setw (8) <<  hTrend[iName]->GetBinContent(iCut+1);
   std::cout << normal << " [" << std::setw (8) <<  hTrend[iName]->GetBinError(iCut+1);
   std::cout << " ]";
  }
  std::cout << std::endl;
 }
 
 std::cout << std::endl;
 std::cout << " *********************************** " << std::endl;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << " | " << std::setw (8) << reduced_name_samples.at(iName) ;
  std::cout << " [" << std::setw (8) <<  "err";
  std::cout << " ]";
 }
 std::cout << std::endl;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << " | " << cyan << std::setw (8) <<  numEntriesFirstStep_reduced_samples.at(iName);
  std::cout << normal << " [" << std::setw (8) <<  "XXX";
  std::cout << " ]";
 }
 std::cout << std::endl;
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
   std::cout << " | " << blue << std::setw (8) <<  hTrend[iName]->GetBinContent(iCut+1);
   std::cout << normal << " [" << std::setw (8) <<  hTrend[iName]->GetBinError(iCut+1);
   std::cout << " ]";
  }
  std::cout << std::endl;
 }
 
 
 
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << " *********************************** " << std::endl;
 std::cout << " ************* 1 fb-1 ************* " << std::endl;
 std::cout << std::setw (12) << "sample";
 std::cout << " | " << std::setw (8) <<  -1;
 std::cout << " [" << std::setw (8) <<  "XXX";
 std::cout << " ]";
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  std::cout << " | " << std::setw (8) <<  iCut;
  std::cout << " [" << std::setw (8) <<  "XXX";
  std::cout << " ]";
 }
 std::cout << std::endl;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << std::setw (12) << reduced_name_samples.at(iName) ;
  std::cout << " | " << purple << std::setw (9) <<  1000 / LUMI * numEntriesFirstStep_reduced_samples.at(iName);
  std::cout << normal << " [" << std::setw (9) <<  "XXX";
  std::cout << " ]";
  for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
   std::cout << " | " << red << std::setw (9) <<  hTrend[iName]->GetBinContent(iCut+1) / LUMI * 1000.;
   std::cout << normal << " [" << std::setw (9) <<  hTrend[iName]->GetBinError(iCut+1) / LUMI * 1000.;
   std::cout << " ]";
  }
  std::cout << std::endl;
 }
 
 std::cout << std::endl;
 std::cout << " *********************************** " << std::endl;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << " | " << red << std::setw (8) << reduced_name_samples.at(iName) ;
  std::cout << normal << " [" << std::setw (8) <<  "err";
  std::cout << " ]";
 }
 std::cout << std::endl;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << " | " << purple << std::setw (8) <<  1000 / LUMI * numEntriesFirstStep_reduced_samples.at(iName);
  std::cout << normal << " [" << std::setw (8) <<  "XXX";
  std::cout << " ]";
 }
 std::cout << std::endl;
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
   std::cout << " | " << red << std::setw (8) <<  hTrend[iName]->GetBinContent(iCut+1) / LUMI * 1000.;
   std::cout << normal << " [" << std::setw (8) <<  hTrend[iName]->GetBinError(iCut+1) / LUMI * 1000.;
   std::cout << " ]";
  }
  std::cout << std::endl;
 }
 
  
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << " **************************************** " << std::endl;
 std::cout << " ************* efficiency *************** " << std::endl;
 std::cout << std::setw (12) << "sample";
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  std::cout << " | " << std::setw (8) <<  iCut;
  std::cout << " [" << std::setw (8) <<  "XXX";
  std::cout << " ]";
 }
 std::cout << std::endl;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << std::setw (12) << reduced_name_samples.at(iName) ;
  for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
   std::cout << " | " << yellow << std::setw (8) <<  hTrend[iName]->GetBinContent(iCut+1) / numEntriesFirstStep_reduced_samples.at(iName);
   std::cout << normal << " [" << std::setw (8) <<  hTrend[iName]->GetBinError(iCut+1) / numEntriesFirstStep_reduced_samples.at(iName);
//    std::cout << " | " << yellow << std::setw (8) <<  hTrend[iName]->GetBinContent(iCut+1) << " / " << numEntriesFirstStep_reduced_samples.at(iName);
//    std::cout << normal << " [" << std::setw (8) <<  hTrend[iName]->GetBinError(iCut+1) << " / " << numEntriesFirstStep_reduced_samples.at(iName);
   std::cout << " ]";
  }
  std::cout << std::endl;
 }
 
 std::cout << std::endl;
 std::cout << " *********************************** " << std::endl;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  std::cout << " | " << std::setw (8) << reduced_name_samples.at(iName) ;
  std::cout << " [" << std::setw (8) <<  "err";
  std::cout << " ]";
 }
 std::cout << std::endl;
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
   std::cout << " | " << yellow << std::setw (8) <<  hTrend[iName]->GetBinContent(iCut+1) / numEntriesFirstStep_reduced_samples.at(iName);
   std::cout << normal << " [" << std::setw (8) <<  hTrend[iName]->GetBinError(iCut+1) / numEntriesFirstStep_reduced_samples.at(iName);
   std::cout << " ]";
  }
  std::cout << std::endl;
 }
 
 
 
 
 
 
 
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << " ****************************************************************** " << std::endl;
 std::cout << " ****************************************************************** " << std::endl;
 std::cout << " *********************** for Lands datacard *********************** " << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 
 
 
 std::string mass = "160";
 try {
  mass = gConfigParser -> readStringOption("Input::mass");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> input::mass  " << mass << std::endl;  
 
 std::ofstream myfile;
 std::string nameOutDataCard = "dataCard_H" + mass + ".txt";
 
 ///==== output - txt file name ====
 try {
  nameOutDataCard = gConfigParser -> readStringOption("Output::DataCard");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 
 myfile.open (nameOutDataCard.c_str());
 std::cout << "Writing to: " << nameOutDataCard << std::endl;
 std::cout << std::endl;
 
 
 myfile << "Limit" << std::endl;
 myfile << "imax 1 number of channels" << std::endl;
 myfile << "jmax "<< (reduced_name_samples.size() - SignalName.size() - 1) << " number of background" << std::endl;
 //---- -1 to take into account "DATA"
 myfile << "kmax "<< 0 << " number of nuisance parameters" << std::endl;
 
 double totalSig = 0;
 double totalBkg = 0;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  if (iName != numDATA) {
   bool isSig = false;
   for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
    if (reduced_name_samples.at(iName) == *itSig) isSig = true;
   }
   if (isSig) {
    totalSig += hTrend[iName]->GetBinContent(vCut.size());   ///---- last cut!
   }
   else {
    totalBkg += hTrend[iName]->GetBinContent(vCut.size());   ///---- last cut!
   }
  }
 }
 myfile << "-------------------------------------------------" << std::endl;
//  myfile << "Observation   " << ((Discovery==1) ? (int) (totalBkg+totalSig) : (int) (totalBkg)) << std::endl;
 myfile << "Observation   " << hTrend[numDATA]->GetBinContent(vCut.size()) << std::endl;
 //# 1 = discovery, 0 = exclusion
 myfile << "-------------------------------------------------" << std::endl;
 
 
 myfile << std::setw (12) << " bin  " << std::setw (8) << 1 << "  ";
 for (int i=0; i < (reduced_name_samples.size() - SignalName.size() - 1); i++){
  myfile << std::setw (8) << 1 << "  ";
 }
 myfile << std::endl;
 
 myfile << std::setw (12) << " process  " << std::setw (8) << "sig" << "  ";
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  if (iName != numDATA) {
   bool isSig = false;
   for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
    if (reduced_name_samples.at(iName) == *itSig) isSig = true;
   }
   if (!isSig) {
    myfile << std::setw (8) << reduced_name_samples.at(iName) << "  ";
   }
  }
 }
 myfile << std::endl;
 
 myfile << std::setw (12) << " process  " << std::setw (8) << 0 << "  ";
 for (int i=0; i < (reduced_name_samples.size() - SignalName.size() - 1); i++){
  myfile << std::setw (8) << i+1 << "  ";
 }
 myfile << std::endl;
 
 myfile << std::setw (12) << " rate  " << std::setw (8) << totalSig << "  ";
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  if (iName != numDATA) {
   bool isSig = false;
   for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
    if (reduced_name_samples.at(iName) == *itSig) isSig = true;
   }
   if (!isSig) {
    myfile << std::setw (8) << hTrend[iName]->GetBinContent(vCut.size()) << "  ";
   }
  }
 }
 myfile << std::endl;
 
 
 myfile << "-------------------------------------------------" << std::endl;
 
 myfile.close(); 
 
 
 
 
 ///==== plot on the screen ====
 
 std::cout << "Limit" << std::endl;
 std::cout << "imax 1 number of channels" << std::endl;
 std::cout << "jmax "<< (reduced_name_samples.size() - SignalName.size() - 1) << " number of background" << std::endl;
 //---- -1 to take into account "DATA"
 std::cout << "kmax "<< 0 << " number of nuisance parameters" << std::endl;
 
 totalSig = 0;
 totalBkg = 0;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  if (iName != numDATA) {
   bool isSig = false;
   for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
    if (reduced_name_samples.at(iName) == *itSig) isSig = true;
   }
   if (isSig) {
    totalSig += hTrend[iName]->GetBinContent(vCut.size());   ///---- last cut!
   }
   else {
    totalBkg += hTrend[iName]->GetBinContent(vCut.size());   ///---- last cut!
   }
  }
 }
 std::cout << "-------------------------------------------------" << std::endl;
//  std::cout << "Observation   " << ((Discovery==1) ? (int) (totalBkg+totalSig) : (int) (totalBkg)) << std::endl;
 std::cout << "Observation   " << hTrend[numDATA]->GetBinContent(vCut.size()) << std::endl;
 //# 1 = discovery, 0 = exclusion
 std::cout << "-------------------------------------------------" << std::endl;
 
 
 std::cout << std::setw (12) << " bin  " << std::setw (8) << 1 << "  ";
 for (int i=0; i < (reduced_name_samples.size() - SignalName.size() - 1); i++){
  std::cout << std::setw (8) << 1 << "  ";
 }
 std::cout << std::endl;
 
 std::cout << std::setw (12) << " process  " << std::setw (8) << "sig" << "  ";
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  if (iName != numDATA) {
   bool isSig = false;
   for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
    if (reduced_name_samples.at(iName) == *itSig) isSig = true;
   }
   if (!isSig) {
    std::cout << std::setw (8) << reduced_name_samples.at(iName) << "  ";
   }
  }
 }
 std::cout << std::endl;
 
 std::cout << std::setw (12) << " process  " << std::setw (8) << 0 << "  ";
 for (int i=0; i < (reduced_name_samples.size() - SignalName.size() - 1); i++){
  std::cout << std::setw (8) << i+1 << "  ";
 }
 std::cout << std::endl;
 
 std::cout << std::setw (12) << " rate  " << std::setw (8) << totalSig << "  ";
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  if (iName != numDATA) {
   bool isSig = false;
   for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
    if (reduced_name_samples.at(iName) == *itSig) isSig = true;
   }
   if (!isSig) {
    std::cout << std::setw (8) << hTrend[iName]->GetBinContent(vCut.size()) << "  ";
   }
  }
 }
 std::cout << std::endl;
 
 
 std::cout << "-------------------------------------------------" << std::endl;
 
 
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 std::cout << std::endl;
 
 
 
 
 
 
 ///==== draw trend vs cut (begin)
 cTrend->cd();
 DrawStack(hsTrend,1,LumiSyst);
 hTrend[numDATA] -> Draw("EsameP");
 gPad->SetLogy();
 gPad->SetGrid();
 leg->Draw();
 latex->Draw();
  
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  TString nameCanvas = Form("%d_Canvas_Trend",iCut);
  cTrendPie[iCut] = new TCanvas(nameCanvas,nameCanvas,400,400);
  cTrendPie[iCut]->cd();
  hTrendPie[iCut] -> Draw("3d t nol");
  hTrendPie[iCut]->SetX(.45);
  hTrendPie[iCut]->SetRadius(.22);
  leg->Draw();
  latex->Draw();
  
  cTrendPieAll->cd(iCut+1);
  hTrendPie[iCut] -> Draw("3d t nol");
  hTrendPie[iCut]->SetX(.45);
  hTrendPie[iCut]->SetRadius(.22);
  leg->Draw();
  latex->Draw();
 }
 ///==== draw trend vs cut (end)
 
 
 
 std::cerr << " ******************************************* end *******************************************" << std::endl;
 end = clock();
 std::cout <<"Time = " <<  ((double) (end - start)) << " (a.u.)" << std::endl;  
 
 
 
 ///==== save output ====
 outFile.cd();
 cTrend -> Write();
 
 outFile.mkdir("Trend");
 outFile.cd("Trend");
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  cTrendPie[iCut] -> Write();
 }
 cTrendPieAll -> Write();
 
 
 outFile.cd();
 outFile.mkdir("PU");
 outFile.cd("PU");
 
 hPUMC     -> Write();
 hPUDATA   -> Write();
 hPUWeight -> Write();
 
 
 outFile.cd();
 outFile.mkdir("Sample");
 outFile.cd("Sample");
 
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  cTrendSample[iName] ->Write();
 }  
 
 leg->Write();
 
}
Exemplo n.º 3
0
void makeStack(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, 
               vector<const Sample*>& listOfSignals, vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, 
               TString inFileName,
               bool isBlind, bool isLog, bool drawSignal, bool drawLegend,
               int nBins, float xLow, float xHigh,
               float* xlowVec)
{
  // prepare the input file
  TFile* infile = new TFile(inFileName, "READ"); 
  infile -> cd();
  
  // prepare the stack
  THStack *hs = new THStack("hs","");
  // prepare the histos pointers
  TH1F*   hist[20];
  // prepare the tree pointers
  TTree*  tree[20];
  // prepare the legend
  TLegend* leg = new TLegend(.7485,.7225,.9597,.9604);
  leg->SetFillColor(0);
  // prepare the colors
  Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58};
  // prepare the cut
  if (isBlind) myCut += "*(phoMetDeltaPhi < 2.9)";        
  // prepare the Y axis lable
  if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY;
  else {
    float binWidth = (xHigh-xLow)/nBins;
    TString tempString;
    tempString.Form("%.2f ",binWidth); 
    myAxisNameY = "Events/" + tempString + myAxisNameY;
  }
  // prepare the legend strings
  vector<TString> theLegends;
  
  // loop through the datasets and produce the plots
  TH1F* hdata;
  TH1F* hsignal;
  //prepare data and signal histos
  if (xlowVec != 0) hdata   = new TH1F("hdata","",nBins,xlowVec);
  else hdata = new TH1F("hdata","",nBins,xLow,xHigh);
  if (xlowVec != 0) hsignal = new TH1F("hsignal","",nBins,xlowVec);
  else hsignal = new TH1F("hsignal","",nBins,xLow,xHigh);

  TTree*  treedata[20];
  for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) {
    //get the tree
    treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data());

    //fill the histogram
    if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","evt_weight*kf_weight*pu_weight" + myCut);
    else treedata[iDatas] -> Draw(myVar + " >>+ hdata","evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( isBlind && iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl");    
    
  }//end loop on datasets
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError  (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin));
  }

  TTree*  treesignal[20];
  for (UInt_t iSignal=0; iSignal < listOfSignals.size(); iSignal++) {
    //get the tree
    treesignal[iSignal] = (TTree*) infile -> Get(listOfSignals.at(iSignal)->Name()->Data());

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSignals.at(iSignal)->Scale()));
    if ( iSignal == 0 ) treesignal[iSignal] -> Draw(myVar + " >> hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else treesignal[iSignal] -> Draw(myVar + " >>+ hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( drawSignal && iSignal == 0 ) leg -> AddEntry(hsignal, "Signal", "l");    
    
  }//end loop on signals
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinError  (iBin,hsignal->GetBinError(iBin)/hsignal->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinContent(iBin,hsignal->GetBinContent(iBin)/hsignal->GetBinWidth(iBin));
  }
  hsignal -> SetLineColor(49);
  hsignal -> SetLineWidth(4.0);
       
  int theHistCounter = 0;
  // loop through the samples and produce the plots
  for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) {

    //determine if the histo is first of the series
    bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" ");
    bool isLastOfSerie = false;
    if (iSample == listOfSamples.size() - 1) isLastOfSerie = true;
    if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true;
    
    //get the tree
    tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data());
    //if sample first of the list create a new histogram
    if (isFirstOfSerie) {
       TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name());
       //variable bin histo
       if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec);
       //fixed bin histo
       else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh);
       hist[theHistCounter] -> Sumw2();
       hist[theHistCounter] -> SetFillColor(col[theHistCounter]);
       hist[theHistCounter] -> SetFillStyle(1001);
       theLegends.push_back(*listOfSamples.at(iSample)->Legend());
    }

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale()));
    if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    //add the histogram to the stack if the last of the series:
    //either last sample or ~ sample followed by non ~ sample
    if (isLastOfSerie) {
       if (xlowVec != 0) {
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError  (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
       }
       hs -> Add(hist[theHistCounter]);
       theHistCounter++;
    }
    
  }//end loop on samples

  //Fix the legend
  for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) {
    leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f");   
  }
  
  //get the maximum to properly set the frame
  float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin());
  TH1* theMCSum = (TH1*) hs->GetStack()->Last();
  float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin());
  if (theMaxMC > theMax) theMax = theMaxMC;
  
  //prepare the ratio band and plot
  TH1* theMCRatioBand = makeRatioBand(theMCSum);
  TH1* theRatioPlot = makeRatioPlot(hdata,theMCSum);
    
  TCanvas* can = new TCanvas();
  can -> SetLogy(isLog);
  
  TPad *pad1 = new TPad("pad1","top pad",0,0.30,1,1);
  pad1->SetBottomMargin(0.02);
  pad1->SetLeftMargin(0.13);
  pad1->Draw();
  TPad *pad2 = new TPad("pad2","bottom pad",0,0.0,1,0.30);
  pad2->SetTopMargin(0.02);
  pad2->SetLeftMargin(0.13);
  pad2->SetBottomMargin(0.4);
  pad2->SetGridy();
  pad2->Draw();
  
  pad1->cd();
  hs->Draw("hist");
  hdata->Draw("same,pe");
  if (drawSignal) hsignal->Draw("same,hist");
  if (drawLegend) leg->Draw("same");
  //hs->GetXaxis()->SetTitle(myAxisNameX);
  hs->GetYaxis()->SetTitle(myAxisNameY);
  hs->GetXaxis()->SetLabelSize(0.04);
  hs->GetYaxis()->SetLabelSize(0.04);
  hs->GetXaxis()->SetLabelOffset(0.025);
  hs->GetYaxis()->SetLabelOffset(0.035);
  //hs->GetXaxis()->SetTitleOffset(1.1);
  hs->GetYaxis()->SetTitleOffset(1.1);
  hs->SetMaximum(theMax);
  if (isLog) hs->SetMinimum(0.01);
  
  pad2->cd();
  theMCRatioBand->GetXaxis()->SetTitle(myAxisNameX);
  theMCRatioBand->GetXaxis()->SetTitleSize(0.16);
  theMCRatioBand->GetXaxis()->SetTitleOffset(1.1);
  theMCRatioBand->GetXaxis()->SetLabelSize(0.12);
  theMCRatioBand->GetXaxis()->SetLabelOffset(0.07);
  theMCRatioBand->GetYaxis()->SetTitle("Data/MC");
  theMCRatioBand->GetYaxis()->SetTitleSize(0.10);
  theMCRatioBand->GetYaxis()->SetTitleOffset(0.6);
  theMCRatioBand->GetYaxis()->SetLabelSize(0.06);
  theMCRatioBand->GetYaxis()->SetLabelOffset(0.03);
  theMCRatioBand->SetFillStyle(3001);
  theMCRatioBand->SetFillColor(kBlue);
  theMCRatioBand->SetLineWidth(1);
  theMCRatioBand->SetLineColor(kBlack);
  theMCRatioBand->SetMarkerSize(0.1);
  theMCRatioBand->SetMaximum(4.);
  theMCRatioBand->SetMinimum(0.);
  theMCRatioBand->Draw("E2");
  TLine *line = new TLine(xLow,1,xHigh,1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  theRatioPlot->Draw("same,pe");
  
  can->cd();
  can->Modified();
  can -> SaveAs(myName + ".pdf","pdf");
  
  //cleanup the memory allocation
  delete theMCSum;
  delete hs;
  delete leg;
  delete hdata;
  delete pad1;
  delete pad2;
  delete can;
  delete theMCRatioBand;
  delete theRatioPlot;
  infile -> Close();
  delete infile;
  
  return;
}
Exemplo n.º 4
0
CalcMtEff(string outStr=""){
gStyle->SetOptStat(0);  ///to avoid the stat. on the plots
char tempname[200];
int W = 600;
int H = 600;
int H_ref = 600;
int W_ref = 800;
float T = 0.08*H_ref;
float B = 0.12*H_ref;
float L = 0.12*W_ref;
float R = 0.04*W_ref;

TCanvas* c1 = new TCanvas("name","name",10,10,W,H);
c1->SetFillColor(0);
c1->SetBorderMode(0);
c1->SetFrameFillStyle(0);
c1->SetFrameBorderMode(0);
c1->SetLeftMargin( L/W );
c1->SetRightMargin( R/W );
c1->SetTopMargin( T/H );
c1->SetBottomMargin( B/H );
c1->SetTickx(0);
c1->SetTicky(0);



Float_t legendX1 = .7; //.50;
Float_t legendX2 = .9; //.70;
Float_t legendY1 = .70; //.65;
Float_t legendY2 = .85;
TLegend* catLeg1 = new TLegend(legendX1,legendY1,legendX2,legendY2);
catLeg1->SetTextSize(0.032);
catLeg1->SetTextFont(42);
catLeg1->SetTextSize(0.04);
catLeg1->SetFillColor(0);
catLeg1->SetLineColor(0);
catLeg1->SetBorderSize(0);

TH1D * thist_tt, * thist_wj;
TH1D * thist_tt2, * thist_wj2;
TH1D * thist_t, * thist_t2;
THStack * stack;

TFile * after_tt = new TFile("Stack/Elog410_MTSelMinus_HadTauEstimation_TTbar_stacked.root","R");
TFile * before_tt = new TFile("Stack/Elog410_BeoreMT_HadTauEstimation_TTbar_stacked.root","R");
TFile * after_wj = new TFile("Stack/Elog410_MTSelMinus_HadTauEstimation_WJet_stacked.root","R");
TFile * before_wj = new TFile("Stack/Elog410_BeoreMT_HadTauEstimation_WJet_stacked.root","R");
TFile * after_t = new TFile("Stack/Elog410_MTSelMinus_HadTauEstimation_T_stacked.root","R");
TFile * before_t = new TFile("Stack/Elog410_BeoreMT_HadTauEstimation_T_stacked.root","R");

sprintf(tempname,"MtEff_%s_.root",outStr.c_str());
TFile * outFile = new TFile(tempname,"RECREATE");

////////
// ttbar
////////

stack = (THStack *) after_tt->Get("searchH")->Clone("after");
thist_tt = (TH1D *) stack->GetStack()->Last();
stack = (THStack *) before_tt->Get("searchH")->Clone("before");
thist_tt2 = (TH1D *) stack->GetStack()->Last(); 

TH1D * MtCutEff_tt = static_cast<TH1D*>(thist_tt->Clone("MtCutEff_tt"));
MtCutEff_tt->Divide(thist_tt,thist_tt2,1,1,"B");
//
//one time drawing options
//
double XUp = 46. , maxVal=2.;
  MtCutEff_tt->SetMaximum(maxVal);
    MtCutEff_tt->SetTitle("");
    MtCutEff_tt->GetXaxis()->SetLabelFont(42);
    MtCutEff_tt->GetXaxis()->SetLabelOffset(0.007);
    MtCutEff_tt->GetXaxis()->SetLabelSize(0.04);
    MtCutEff_tt->GetXaxis()->SetTitleSize(0.04);
    MtCutEff_tt->GetXaxis()->SetTitleOffset(0.9);
    MtCutEff_tt->GetXaxis()->SetTitleFont(42);
    MtCutEff_tt->GetYaxis()->SetLabelFont(42);
    MtCutEff_tt->GetYaxis()->SetLabelOffset(0.007);
    MtCutEff_tt->GetYaxis()->SetLabelSize(0.04);
    MtCutEff_tt->GetYaxis()->SetTitleSize(0.04);
    MtCutEff_tt->GetYaxis()->SetTitleOffset(1.25);
    MtCutEff_tt->GetYaxis()->SetTitleFont(42);
    MtCutEff_tt->GetXaxis()->SetTitle("search bins");
    MtCutEff_tt->GetYaxis()->SetTitle("MT efficiency");
    MtCutEff_tt->GetXaxis()->SetRangeUser(1.,XUp);
    MtCutEff_tt->SetMaximum(maxVal);
//
//end of drawing options
//
MtCutEff_tt->SetLineColor(1);
MtCutEff_tt->Draw("same");
MtCutEff_tt->Write();

////////
// wjet
////////
stack = (THStack *) after_wj->Get("searchH")->Clone("after");
thist_wj = (TH1D *) stack->GetStack()->Last();
stack = (THStack *) before_wj->Get("searchH")->Clone("before");
thist_wj2 = (TH1D *) stack->GetStack()->Last();

TH1D * MtCutEff_wj = static_cast<TH1D*>(thist_wj->Clone("MtCutEff_wj"));
MtCutEff_wj->Divide(thist_wj,thist_wj2,1,1,"B");
MtCutEff_wj->SetLineColor(2);
MtCutEff_wj->Draw("same");
MtCutEff_wj->Write();


////////
// single top
////////
stack = (THStack *) after_t->Get("searchH")->Clone("after");
thist_t = (TH1D *) stack->GetStack()->Last();
stack = (THStack *) before_t->Get("searchH")->Clone("before");
thist_t2 = (TH1D *) stack->GetStack()->Last();

TH1D * MtCutEff_t = static_cast<TH1D*>(thist_t->Clone("MtCutEff_t"));
MtCutEff_t->Divide(thist_t,thist_t2,1,1,"B");
MtCutEff_t->SetLineColor(2);
MtCutEff_t->Draw("same");
MtCutEff_t->Write();


////////
// tt+wj
////////
TH1D * thist_tot = static_cast<TH1D*>(thist_tt->Clone("thist_tot"));
thist_tot->Add(thist_wj);
thist_tot->Add(thist_t);
TH1D * thist_tot2 = static_cast<TH1D*>(thist_tt2->Clone("thist_tot2"));
thist_tot2->Add(thist_wj2);
thist_tot2->Add(thist_t2);
TH1D * MtCutEff_tot = static_cast<TH1D*>(thist_tot->Clone("MtCutEff"));
MtCutEff_tot->Divide(thist_tot,thist_tot2,1,1,"B");
MtCutEff_tot->SetLineColor(3);
MtCutEff_tot->SetLineStyle(2);
MtCutEff_tot->SetLineWidth(2);
MtCutEff_tot->Draw("same");
MtCutEff_tot->Write();


    sprintf(tempname,"t#bar{t}");
    catLeg1->AddEntry(MtCutEff_tt,tempname,"l");
    sprintf(tempname,"WJet");
    catLeg1->AddEntry(MtCutEff_wj,tempname,"l");
    catLeg1->AddEntry(MtCutEff_tot,"t#bar{t} + WJet + top","l");
    catLeg1->Draw();

sprintf(tempname,"MtEffi_%s_.png",outStr.c_str());
c1->Print(tempname);

//////////
//////////
//LowDphi
//////////
//////////
TCanvas* c2 = new TCanvas("name","name",10,10,W,H);
c2->SetFillColor(0);
c2->SetBorderMode(0);
c2->SetFrameFillStyle(0);
c2->SetFrameBorderMode(0);
c2->SetLeftMargin( L/W );
c2->SetRightMargin( R/W );
c2->SetTopMargin( T/H );
c2->SetBottomMargin( B/H );
c2->SetTickx(0);
c2->SetTicky(0);

TLegend* catLeg2 = new TLegend(legendX1,legendY1,legendX2,legendY2);
catLeg2->SetTextSize(0.032);
catLeg2->SetTextFont(42);
catLeg2->SetTextSize(0.04);
  catLeg2->SetFillColor(0);
  catLeg2->SetLineColor(0);
  catLeg2->SetBorderSize(0);

////////
// ttbar
////////
stack = (THStack *) after_tt->Get("searchH_lowDphi")->Clone("after");
thist_tt = (TH1D *) stack->GetStack()->Last();
stack = (THStack *) before_tt->Get("searchH_lowDphi")->Clone("before");
thist_tt2 = (TH1D *) stack->GetStack()->Last(); 

TH1D * MtCutEff_tt = static_cast<TH1D*>(thist_tt->Clone("MtCutEff_tt_lowDphi"));
MtCutEff_tt->Divide(thist_tt,thist_tt2,1,1,"B");
//
//one time drawing options
//
double XUp = 46. , maxVal=2.;
  MtCutEff_tt->SetMaximum(maxVal);
    MtCutEff_tt->SetTitle("");
    MtCutEff_tt->GetXaxis()->SetLabelFont(42);
    MtCutEff_tt->GetXaxis()->SetLabelOffset(0.007);
    MtCutEff_tt->GetXaxis()->SetLabelSize(0.04);
    MtCutEff_tt->GetXaxis()->SetTitleSize(0.04);
    MtCutEff_tt->GetXaxis()->SetTitleOffset(0.9);
    MtCutEff_tt->GetXaxis()->SetTitleFont(42);
    MtCutEff_tt->GetYaxis()->SetLabelFont(42);
    MtCutEff_tt->GetYaxis()->SetLabelOffset(0.007);
    MtCutEff_tt->GetYaxis()->SetLabelSize(0.04);
    MtCutEff_tt->GetYaxis()->SetTitleSize(0.04);
    MtCutEff_tt->GetYaxis()->SetTitleOffset(1.25);
    MtCutEff_tt->GetYaxis()->SetTitleFont(42);
    MtCutEff_tt->GetXaxis()->SetTitle("search bins");
    MtCutEff_tt->GetYaxis()->SetTitle("MT efficiency");
    MtCutEff_tt->GetXaxis()->SetRangeUser(1.,XUp);
    MtCutEff_tt->SetMaximum(maxVal);
//
//end of drawing options
//
MtCutEff_tt->SetLineColor(1);
MtCutEff_tt->Draw("same");
MtCutEff_tt->Write();

////////
// wjet
////////
stack = (THStack *) after_wj->Get("searchH_lowDphi")->Clone("after");
thist_wj = (TH1D *) stack->GetStack()->Last();
stack = (THStack *) before_wj->Get("searchH_lowDphi")->Clone("before");
thist_wj2 = (TH1D *) stack->GetStack()->Last();

TH1D * MtCutEff_wj = static_cast<TH1D*>(thist_wj->Clone("MtCutEff_wj_lowDphi"));
MtCutEff_wj->Divide(thist_wj,thist_wj2,1,1,"B");
MtCutEff_wj->SetLineColor(2);
MtCutEff_wj->Draw("same");
MtCutEff_wj->Write();

////////
// top
////////
stack = (THStack *) after_t->Get("searchH_lowDphi")->Clone("after");
thist_t = (TH1D *) stack->GetStack()->Last();
stack = (THStack *) before_t->Get("searchH_lowDphi")->Clone("before");
thist_t2 = (TH1D *) stack->GetStack()->Last();

TH1D * MtCutEff_t = static_cast<TH1D*>(thist_t->Clone("MtCutEff_t_lowDphi"));
MtCutEff_t->Divide(thist_t,thist_t2,1,1,"B");
MtCutEff_t->SetLineColor(2);
MtCutEff_t->Draw("same");
MtCutEff_t->Write();

////////
// tt+wj
////////
TH1D * thist_tot = static_cast<TH1D*>(thist_tt->Clone("thist_tot_lowDphi"));
thist_tot->Add(thist_wj);
thist_tot->Add(thist_t);
TH1D * thist_tot2 = static_cast<TH1D*>(thist_tt2->Clone("thist_tot2_lowDphi"));
thist_tot2->Add(thist_wj2);
thist_tot2->Add(thist_t2);
TH1D * MtCutEff_tot = static_cast<TH1D*>(thist_tot->Clone("MtCutEff_lowDphi"));
MtCutEff_tot->Divide(thist_tot,thist_tot2,1,1,"B");
MtCutEff_tot->SetLineColor(3);
MtCutEff_tot->SetLineStyle(2);
MtCutEff_tot->SetLineWidth(2);
MtCutEff_tot->Draw("same");
MtCutEff_tot->Write();


    sprintf(tempname,"t#bar{t}");
    catLeg2->AddEntry(MtCutEff_tt,tempname,"l");
    sprintf(tempname,"WJet");
    catLeg2->AddEntry(MtCutEff_wj,tempname,"l");
    catLeg2->AddEntry(MtCutEff_tot,"t#bar{t} + WJet + top","l");
    catLeg2->Draw();

sprintf(tempname,"MtEff_lowDphi_%s_.png",outStr.c_str());
c2->Print(tempname);


/*
stack = (THStack *)after_tt->Get("searchH_lowDphi")->Clone("after_lowDphi");
thist_tt = (TH1D *) stack->GetStack()->Last();
stack = (THStack *)before_tt->Get("searchH_lowDphi")->Clone("before_lowDphi");
thist_tt2 = (TH1D *) stack->GetStack()->Last();

TH1D * MtCutEff_lowDphi = static_cast<TH1D*>(thist_tt->Clone("MtCutEff_lowDphi"));
MtCutEff_lowDphi->Divide(thist_tt,thist_tt2,1,1,"B");

MtCutEff_lowDphi->Draw();
sprintf(tempname,"MtEff_lowDphi.png");
c1->Print(tempname);

MtCutEff_lowDphi->Write();
*/

outFile->Close();


}
Exemplo n.º 5
0
Plot_searchBin_Data(string sample="stacked",string histname="searchH",int choice=1){

  ///////////////////////////////////////////////////////////////////////////////////////////
  ////Some cosmetic work for official documents.
  //
  // Set basic style
  //
  gROOT->LoadMacro("tdrstyle.C");
  setTDRStyle();
  gStyle->SetPalette(1) ; // for better color output
  gROOT->LoadMacro("CMS_lumi_v2.C");

  int W = 600;
  int H = 600;
  int H_ref = 600;
  int W_ref = 800;
  float T = 0.08*H_ref;
  float B = 0.12*H_ref;
  float L = 0.12*W_ref;
  float R = 0.08*W_ref;

  ///////////////////////////////////////////////////////////////////////////////////////////
  //
  // More specific style set, opening input files etc

  gStyle->SetOptStat(0);  ///to avoid the stat. on the plots
  char tempname[200];
  char xtitlename[200];
  char ytitlename[200];

  if(sample.find("stack")==string::npos)sprintf(tempname,"TauHad/GenInfo_HadTauEstimation_%s.root",sample.c_str());
  else sprintf(tempname,"TauHad/Stack/GenInfo_HadTauEstimation_%s.root",sample.c_str());
//cout << "warning:\n Warning \n \n  using elog195 for pre and  exp \n \n ";
  TFile * GenFile = new TFile(tempname,"R");
  sprintf(tempname,"TauHad2/Elog378_HadTauEstimation_data_SingleMuon_v15cd_.root");
  TFile * EstFile = new TFile(tempname,"R");

  //
  // Define legend
  //
  Float_t legendX1 = .55; //.50;
  Float_t legendX2 = .85; //.70;
  Float_t legendY1 = .75; //.65;
  Float_t legendY2 = .90;

  TLegend* catLeg1 = new TLegend(legendX1,legendY1,legendX2,legendY2);
  catLeg1->SetTextSize(0.032);
  catLeg1->SetTextFont(42);

  catLeg1->SetTextSize(0.042);
  catLeg1->SetTextFont(42);
  catLeg1->SetFillColor(0);
  catLeg1->SetLineColor(0);
  catLeg1->SetBorderSize(0);

  //
  // Define canvas
  //
  TCanvas *canvas = new TCanvas("canvas","canvas",10,10,W,H);

  canvas->SetFillColor(0);
  canvas->SetBorderMode(0);
  canvas->SetFrameFillStyle(0);
  canvas->SetFrameBorderMode(0);
  canvas->SetLeftMargin( L/W );
  canvas->SetRightMargin( R/W );
  canvas->SetRightMargin( 0.2 );
  canvas->SetTopMargin( T/H );
  canvas->SetBottomMargin( B/H );
  canvas->SetTickx(0);
  canvas->SetTicky(0);

  canvas->Divide(1, 2);

  //
  // Define pads
  //
  TPad* canvas_up = (TPad*) canvas->GetListOfPrimitives()->FindObject("canvas_1");
  TPad* canvas_dw = (TPad*) canvas->GetListOfPrimitives()->FindObject("canvas_2");
 
  // define the size
  double up_height     = 0.8;  // please tune so that the upper figures size will meet your requirement
  double dw_correction = 1.30; // please tune so that the smaller canvas size will work in your environment
  double font_size_dw  = 0.1;  // please tune the font size parameter for bottom figure
  double dw_height    = (1. - up_height) * dw_correction;
  double dw_height_offset = 0.040; // KH, added to put the bottom one closer to the top panel
 
  // set pad size
  canvas_up->SetPad(0., 1 - up_height, 0.97, 1.);
  canvas_dw->SetPad(0., dw_height_offset, 0.97, dw_height+dw_height_offset);
  canvas_up->SetFrameFillColor(0);
  canvas_up->SetFillColor(0);
  canvas_dw->SetFillColor(0);
  canvas_dw->SetFrameFillColor(0);
  canvas_dw->SetBottomMargin(0.25);
  
  // set top margin 0 for bottom figure
  canvas_dw->SetTopMargin(0);
  
  // draw top figure
  canvas_up->cd();

  TH1D * GenHist, * EstHist,* thist;
  TH1D * histTemplate;
  THStack * tempstack;

  double HT_x_max=2500.;
  double HT_x_min=400.;
  double MHT_x_max=1000.;
  double NJet_x_max=15.;
  double NBtag_x_max=4.;
  double search_x_max=19.;
  double search_x_min=1.;


  sprintf(tempname,"%s",histname.c_str());
  if(sample.find("stacked")!=string::npos){
   
    EstHist=(TH1D*)EstFile->Get(tempname)->Clone();
    tempstack=(THStack*)GenFile->Get(tempname)->Clone();   
    GenHist=(TH1D*) tempstack->GetStack()->Last();
    
    EstHistD=(TH1D*) EstFile->Get(tempname)->Clone();
    tempstack=(THStack*)GenFile->Get(tempname)->Clone();
    GenHistD=(TH1D*) tempstack->GetStack()->Last();
    
  }
  else{
    EstHist=(TH1D*) EstFile->Get(tempname)->Clone();
    GenHist=(TH1D*) GenFile->Get(tempname)->Clone();
    EstHistD=(TH1D*) EstFile->Get(tempname)->Clone();
    GenHistD=(TH1D*) GenFile->Get(tempname)->Clone();
  }

  GenHist->SetLineColor(2);
  EstHist->SetLineColor(4);
  //GenHist->GetXaxis()->SetLabelFont(42);
  //GenHist->GetXaxis()->SetLabelOffset(0.007);
  //GenHist->GetXaxis()->SetLabelSize(0.04);
  GenHist->GetXaxis()->SetTitleSize(0.05);
  GenHist->GetXaxis()->SetTitleOffset(0.9);
  GenHist->GetXaxis()->SetTitleFont(42);
  //GenHist->GetYaxis()->SetLabelFont(42);
  //GenHist->GetYaxis()->SetLabelOffset(0.007);
  //GenHist->GetYaxis()->SetLabelSize(0.04);
  GenHist->GetYaxis()->SetTitleSize(0.05);
  GenHist->GetYaxis()->SetTitleOffset(1.25);
  GenHist->GetYaxis()->SetTitleFont(42);

  //EstHist->GetXaxis()->SetLabelFont(42);
  //EstHist->GetXaxis()->SetLabelOffset(0.007);
  //EstHist->GetXaxis()->SetLabelSize(0.04);
  EstHist->GetXaxis()->SetTitleSize(0.05);
  EstHist->GetXaxis()->SetTitleOffset(0.9);
  EstHist->GetXaxis()->SetTitleFont(42);
  //EstHist->GetYaxis()->SetLabelFont(42);
  //EstHist->GetYaxis()->SetLabelOffset(0.007);
  //EstHist->GetYaxis()->SetLabelSize(0.04);
  EstHist->GetYaxis()->SetTitleSize(0.05);
  EstHist->GetYaxis()->SetTitleOffset(1.25);
  EstHist->GetYaxis()->SetTitleFont(42);
  sprintf(xtitlename,"search bins");
  sprintf(ytitlename,"Events");
  gPad->SetLogy();
  GenHist->SetMaximum(200000);
  GenHist->SetMinimum(0.1);
  GenHist->GetXaxis()->SetRangeUser(search_x_min,search_x_max);

  GenHist->SetFillStyle(3004);
  GenHist->SetFillColor(kGreen-3);
  GenHist->SetTitle("");
  GenHist->Draw("e2");
  //KH GenHist->Draw("same");
  EstHist->Draw("same");

  TH1D * GenHist_Clone = static_cast<TH1D*>(GenHist->Clone("denominator"));

  sprintf(tempname,"#tau_{hadronic} BG");
  catLeg1->AddEntry(GenHist,tempname,"l");
  sprintf(tempname,"Data");
  catLeg1->AddEntry(EstHist,tempname,"l");
  GenHist->GetXaxis()->SetTitle(xtitlename);
  GenHist->GetYaxis()->SetTitle(ytitlename);
  catLeg1->Draw();

  TText * ttext = new TText(10. , 1700. , "4 fb-1");
  //  ttext->Draw();
  //
  // Bottom ratio plot
  //
  // ----------

  if(choice==0){
      //KH -- flip the numerator and denominator
      EstHistD->Divide(GenHistD);

      // draw bottom figure
      canvas_dw->cd();
      // font size
      EstHistD->GetXaxis()->SetLabelSize(font_size_dw);
      EstHistD->GetXaxis()->SetTitleSize(font_size_dw);
      EstHistD->GetYaxis()->SetLabelSize(font_size_dw);
      EstHistD->GetYaxis()->SetTitleSize(font_size_dw);
      
      //
      // Common to all bottom plots
      //
      sprintf(ytitlename,"Estimate / #tau_{had} BG");
      EstHistD->SetMaximum(2.65);
      EstHistD->SetMinimum(0.0);

      //
      // Specific to each bottom plot
      //
      sprintf(xtitlename,"search bin");
      EstHistD->GetXaxis()->SetRangeUser(search_x_min,search_x_max);
      TLine *tline = new TLine(search_x_min,1.,search_x_max,1.);

      // Setting style
      //EstHistD->SetMaximum(1.4);
      //EstHistD->GetXaxis()->SetLabelFont(42);
      //EstHistD->GetXaxis()->SetLabelOffset(0.007);
      //EstHistD->GetXaxis()->SetLabelSize(0.04);
      EstHistD->GetXaxis()->SetTitleSize(0.12);
      EstHistD->GetXaxis()->SetTitleOffset(0.9);
      EstHistD->GetXaxis()->SetTitleFont(42);
      //EstHistD->GetYaxis()->SetLabelFont(42);
      //EstHistD->GetYaxis()->SetLabelOffset(0.007);
      //EstHistD->GetYaxis()->SetLabelSize(0.04);
      EstHistD->GetYaxis()->SetTitleSize(0.13);
      EstHistD->GetYaxis()->SetTitleOffset(0.5);
      EstHistD->GetYaxis()->SetTitleFont(42);

      EstHistD->GetXaxis()->SetTitle(xtitlename);
      EstHistD->GetYaxis()->SetTitle(ytitlename);

      EstHistD->SetTitle("");
      EstHistD->Draw();
      tline->SetLineStyle(2);
      tline->Draw();
  }

  if(choice==1){

    /*
      TH1D * denominator = static_cast<TH1D*>(EstHist->Clone("denominator"));
      EstHistD->Add(GenHistD,-1);
      denominator->Divide(EstHistD,GenHistD,1,1,"");
    */
      TH1D * denominator = static_cast<TH1D*>(EstHist->Clone("denominator"));
      //EstHistD->Add(GenHistD,-1);
      denominator->Divide(GenHistD,EstHistD,1,1,"");

      // draw bottom figure
      canvas_dw->cd();
      // font size
      denominator->GetXaxis()->SetLabelSize(font_size_dw);
      denominator->GetXaxis()->SetTitleSize(font_size_dw);
      denominator->GetYaxis()->SetLabelSize(font_size_dw);
      denominator->GetYaxis()->SetTitleSize(font_size_dw);
      
      TLine *tline = new TLine(search_x_min,1.,search_x_max,1.);

      //
      // Common to all bottom plots
      //
      //sprintf(ytitlename,"#frac{Estimate - #tau_{had} BG}{#tau_{had} BG} ");
      sprintf(ytitlename,"#frac{Expectation}{Prediction} ");
      denominator->SetMaximum(2.65);
      denominator->SetMinimum(0.0);

      //
      // Specific to each bottom plot
      //
      // Setting style
      //denominator->SetMaximum(1.4);
      //denominator->GetXaxis()->SetLabelFont(42);
      //denominator->GetXaxis()->SetLabelOffset(0.007);
      //denominator->GetXaxis()->SetLabelSize(0.04);
      denominator->GetXaxis()->SetTitleSize(0.12);
      denominator->GetXaxis()->SetTitleOffset(0.9);
      denominator->GetXaxis()->SetTitleFont(42);
      //denominator->GetYaxis()->SetLabelFont(42);
      //denominator->GetYaxis()->SetLabelOffset(0.007);
      //denominator->GetYaxis()->SetLabelSize(0.04);
      denominator->GetYaxis()->SetTitleSize(0.13);
      denominator->GetYaxis()->SetTitleOffset(0.5);
      denominator->GetYaxis()->SetTitleFont(42);

      denominator->GetXaxis()->SetTitle(xtitlename);
      denominator->GetYaxis()->SetTitle(ytitlename);

      denominator->SetTitle("");
      denominator->Draw();
      tline->SetLineStyle(2);
      tline->Draw();
  }

  sprintf(tempname,"%s_SearchBin_Plot.png",sample.c_str());
  canvas->Print(tempname);

}
OptRes Optimization(string var = "topness", string signal = "T2tt_850_100", string region = "baseline", string channel = "allChannels", string filename = "plots/plotsProducer/1DStack.root"){

	OptRes res;
	
	//TFile* fplots = new TFile("plots/plotsProducer/1DStack.root","READ");
	TFile* fplots = new TFile(filename.c_str(),"READ");
	//string channel = "allChannels";
	//string region = "baseline";
	//string var = "topness";
	//string var = "topness_m5";
	//string signal = "T2tt_850_100";
	
	
	//retrieve canvas
	string cname = channel+"/"+region+"/"+var;
	TCanvas* c = fplots->Get(cname.c_str());
	//c->Draw();
	
	//signal
	string splot_name = "v:"+var+"|p:"+signal+"|r:"+region+"|c:"+channel+"|t:1DEntries";
	TH1F* h_sig = (TH1F*) c->GetPrimitive(splot_name.c_str());
	//sig->Draw();
	
	//////////////////////////////////////////////
	// Search the Stack that contains all bkg
	//////////////////////////////////////////////
	vector<TH1F*> h_bkgs;
	//c->GetListOfPrimitives()->Print();
	TIter next(c->GetListOfPrimitives());
	TObject* h;
	while ((h = (TH1F*) next())){
	//obj->Draw(next.GetOption());
		if(h->InheritsFrom("THStack")){
			THStack* stack = (THStack*) h;
			for(int i=0;i<stack->GetStack()->GetEntries();i++){
				TH1F* hist = (TH1F*) stack->GetStack()->At(i);
				//cout<<hist->IsA()->GetName()<<endl;
				//cout<<hist->GetName()<<" "<<hist->Integral()<<endl;
				//search tt_2l
				//if(string(hist->GetName()).find("W+jets")!=string::npos) continue;
				if(string(hist->GetName()).find("ttbar_2l")!=string::npos){
					//cout<<"mean = "<<hist->GetMean()<<" rms = "<<hist->GetRMS()<<" kurtosis = "<<hist->GetKurtosis()<<" skewness = "<<hist->GetSkewness()<<endl;
				}
				//else continue;
				//conly save the last one because plots are cumulative !!!
				// that's cheat ....
				if(i==stack->GetStack()->GetEntries()-1) h_bkgs.push_back(hist);
			}
			//cout<<((THStack*)h)->GetStack()->GetEntries()<<endl;
			//TH1* h_bkg = ((TH1*)(h->GetStack()->Last()));
		}
	}
	
	
	////////////////////////////////////////////////
	//     Loop over all bins and compute eff/sig
	////////////////////////////////////////////////
	
	res.h_eff_sig = (TH1F*) h_sig->Clone();	
	res.h_eff_bkg = (TH1F*) h_sig->Clone();	
	res.h_Zbi = (TH1F*) h_sig->Clone();	
	TH1F* h_ROC = new TH1F("h_ROC","ROC curve",10,0,1);

	//Compute the integral
	float integ_sig = res.h_eff_sig->Integral(0,res.h_eff_sig->GetNbinsX()+1);
	float integ_bkg = 0;
	for(unsigned ih=0;ih<h_bkgs.size();ih++){
		integ_bkg+=h_bkgs[ih]->Integral(0,h_bkgs[ih]->GetNbinsX()+1);
	}
	///////////////////////

	//-- efficiencoy for signal
	for(int i=1;i<res.h_eff_sig->GetNbinsX()+1;i++){
		float eff = 0;
		if(integ_sig!=0)  eff = res.h_eff_sig->Integral(i,res.h_eff_sig->GetNbinsX()+1)/integ_sig;
		res.h_eff_sig->SetBinContent(i,eff);
		res.h_eff_sig->SetBinError(i,0);
	}
	//-- efficiency for bkg
	for(int i=1;i<res.h_eff_sig->GetNbinsX()+1;i++){
		float eff = 0;
		for(unsigned ih=0;ih<h_bkgs.size();ih++){
			eff += h_bkgs[ih]->Integral(i,h_bkgs[ih]->GetNbinsX()+1);
		}
		if(integ_bkg!=0)  eff /= integ_bkg;
		res.h_eff_bkg->SetBinContent(i,eff);
		res.h_eff_bkg->SetBinError(i,0);
	}
	//-- compute significance
	//vector<pair<float,float> > roc_v;
	float* roc_sig = new float[res.h_eff_sig->GetNbinsX()];
	float* roc_bkg = new float[res.h_eff_sig->GetNbinsX()];
	int imax = 0;
	for(int i=1;i<res.h_eff_sig->GetNbinsX()+1;i++){
		float Ns = res.h_eff_sig->GetBinContent(i)*integ_sig;
		//float Ns = res.h_eff_sig->GetBinContent(i);
		//float Nb = res.h_eff_bkg->GetBinContent(i);
		float Nb = res.h_eff_bkg->GetBinContent(i)*integ_bkg;
		float signif = 0;
		if(Nb!=0) signif = Ns/sqrt(Nb);
		double zbi = Zbi(Ns, Nb);
		//res.h_Zbi->SetBinContent(i,signif);
		res.h_Zbi->SetBinContent(i,zbi);
		res.h_Zbi->SetBinError(i,0);
		

		//ROC curve
		//h_ROC->SetBinContent(h_ROC->FindBin(res.h_eff_sig->GetBinContent(i)),res.h_eff_bkg->GetBinContent(i));
		//h_ROC->SetBinContent(h_ROC->FindBin(res.h_eff_bkg->GetBinContent(i)),res.h_eff_sig->GetBinContent(i));
		//roc_v.push_back(pair<float,float>(res.h_eff_sig->GetBinContent(i),res.h_eff_bkg->GetBinContent(i));
		roc_sig[imax] = res.h_eff_sig->GetBinContent(i);
		roc_bkg[imax] = 1-res.h_eff_bkg->GetBinContent(i);
		imax++;
	}
	res.gROC = new TGraph(imax,roc_sig,roc_bkg);

	res.h_Zbi->GetXaxis()->SetTitle(var.c_str());
	res.h_Zbi->GetYaxis()->SetTitle("Zbi");

	res.h_eff_bkg->SetTitle("Efficiency on background");
	res.h_eff_bkg->GetXaxis()->SetTitle(var.c_str());
	res.h_eff_bkg->GetYaxis()->SetTitle("#epsilon_{bkg}");
	
	res.h_eff_sig->SetTitle("Efficiency on signal");
	res.h_eff_sig->GetXaxis()->SetTitle(var.c_str());
	res.h_eff_sig->GetYaxis()->SetTitle("#epsilon_{sig}");

	res.gROC->SetTitle("ROC");
	res.gROC->GetXaxis()->SetTitle("#epsilon_{signal}");
	res.gROC->GetYaxis()->SetTitle("1-#epsilon_{bkg}");
	res.gROC->SetLineWidth(2);

 	res.cplots = new TCanvas();
	res.cplots->Divide(2,2);
	res.h_eff_sig->GetYaxis()->SetRangeUser(0,1);
	res.cplots->cd(1);
	res.h_eff_sig->Draw();
	res.h_eff_bkg->SetLineColor(kRed);
	res.cplots->cd(2);
	res.h_eff_bkg->Draw("");
	res.cplots->cd(3);
	res.h_Zbi->Draw();
	res.cplots->cd(4);
   	//h_ROC->Draw();	
	res.gROC->Draw("ACP");
	
	int mbin = res.h_Zbi->GetMaximumBin();
	float maxZbi = -9999;
	for(int i=1;i<res.h_Zbi->GetNbinsX();i++){
		if(res.h_Zbi->GetBinContent(i)>maxZbi && res.h_eff_sig->GetBinContent(i)>0.1){
			maxZbi = res.h_Zbi->GetBinContent(i);
			mbin = i;
		}
	}
	cout<<"@max - Zbi = "<<res.h_Zbi->GetMaximum()<<" cut = "<<res.h_Zbi->GetBinLowEdge(mbin)<<" effs = "<<res.h_eff_sig->GetBinContent(mbin)<<" effb = "<<res.h_eff_bkg->GetBinContent(mbin)<<endl;
	cout<<"Ns = "<<res.h_eff_sig->GetBinContent(mbin)*integ_sig<<" Nb = "<<res.h_eff_bkg->GetBinContent(mbin)*integ_bkg<<endl;
	cout<<"ROC-integral: "<<res.gROC->Integral()<<endl;
	//looking for a bin with eff = XXX
	int mbin2 = 0;
	int mbin7 = 0;
	float eff_ref = 0.75;
	float d_eff_closest = 100;
	for(int i=1;i<res.h_eff_sig->GetNbinsX();i++){
		if(res.h_eff_sig->GetBinLowEdge(i) == 7) mbin7 = i;
		float eff = res.h_eff_sig->GetBinContent(i);
		if(fabs(eff-eff_ref)<d_eff_closest){
			d_eff_closest = fabs(eff-eff_ref);
			//cout<<eff<<" "<<d_eff_closest<<endl;
			mbin2 = i;
		}
	}	
	cout<<"ref - Zbi = "<<res.h_Zbi->GetBinContent(mbin2)<<" cut = "<<res.h_Zbi->GetBinLowEdge(mbin2)<<" effs = "<<res.h_eff_sig->GetBinContent(mbin2)<<" effb = "<<res.h_eff_bkg->GetBinContent(mbin2)<<endl;
	cout<<"Ns = "<<res.h_eff_sig->GetBinContent(mbin2)*integ_sig<<" Nb = "<<res.h_eff_bkg->GetBinContent(mbin2)*integ_bkg<<endl;
	
	//cout<<"cut@7 - Zbi = "<<res.h_Zbi->GetBinContent(mbin7)<<" cut = "<<res.h_Zbi->GetBinLowEdge(mbin7)<<" effs = "<<res.h_eff_sig->GetBinContent(mbin7)<<" effb = "<<res.h_eff_bkg->GetBinContent(mbin7)<<endl;
	//cout<<"Ns = "<<res.h_eff_sig->GetBinContent(mbin7)*integ_sig<<" Nb = "<<res.h_eff_bkg->GetBinContent(mbin7)*integ_bkg<<endl;
	
	//cout<<"Ns_tot = "<<integ_sig<<" Nb_tot = "<<integ_bkg<<endl;
	/*
	THStack* stack = c->GetPrimitive("");
	stack->Draw();
	cout<<stack<<endl;
	//TH1* h_bkg = stack->GetHistogram();
	//cout<<h_bkg<<endl;
	G//h_bkg->Draw();
	TH1* h_bkg = ((TH1*)(stack->GetStack()->Last()));
	h_bkg->Draw();
	cout<<h_bkg->GetNbinsX()<<endl;
*/
	
	/*
	//Compute eff
	TH1* h_eff_bkg = (TH1*) h_bkg->Clone("");
	cout<<h_eff_bkg->GetNbinsX()<<endl;
	for(int i=1;i<h_eff_bkg->GetNbinsX();i++){
		float num = h_bkg->Integral(i,h_bkg->GetNbinsX()+1);
		float den = h_bkg->Integral(0,h_bkg->GetNbinsX()+1);
		float eff = 0;
		if(den!=0) eff== num/den;
		h_eff_bkg->SetBinContent(i,eff);
	}
	h_eff_bkg->Draw();
	cout<<"max = "<<stack->GetHistogram()->GetMaximum()<<endl;
	cout<<c->GetPrimitive("::THStack")<<endl;
	cout<<h_bkg<<endl;
	*/

	return res;
	
}
void makeTable(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, 
               vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, TString inFileName,
               bool isBlind, bool isLog, 
               int nBins, float xLow, float xHigh,
               float* xlowVec)
{
  // prepare the input file
  TFile* infile = new TFile(inFileName, "READ"); 
  infile -> cd();

  // prepare the necessary for the scale factor estimation
  float defScaleFactor = 1.3;
  float newScaleFactor = 1.;
  float varScaleFactor = 1.;
  float nBkg = 0;
  float nBkgErrSq = 0;
  float nSig = 0;
  float nSigErrSq = 0;
    
  // prepare the stack
  THStack *hs = new THStack("hs","");
  // prepare the histos pointers
  TH1F*   hist[20];
  // prepare the tree pointers
  TTree*  tree[20];
  // prepare the legend
  TLegend* leg = new TLegend(.7485,.7225,.9597,.9604);
  leg->SetFillColor(0);
  // prepare the colors
  Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58};
  // prepare the Y axis lable
  if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY;
  else {
    float binWidth = (xHigh-xLow)/nBins;
    TString tempString;
    tempString.Form("%.2f ",binWidth); 
    myAxisNameY = "Events/" + tempString + myAxisNameY;
  }
  // prepare the legend strings
  vector<TString> theLegends;
  
  // loop through the datasets and produce the plots
  TH1F* hdata;
  //variable bin histo
  if (xlowVec != 0) hdata = new TH1F("hdata","",nBins,xlowVec);
  //fixed bin histo
  else hdata = new TH1F("hdata","",nBins,xLow,xHigh);
  
  TTree*  treedata[20];
  for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) {
    //get the tree
    treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data());

    //fill the histogram
    if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    else treedata[iDatas] -> Draw(myVar + " >>+ hdata","hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    
    if ( iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl");    
    
  }//end loop on datasets
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError  (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin));
  }
       
  int theHistCounter = 0;
  // loop through the samples and produce the plots
  for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) {

    //determine if the histo is first of the series
    bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" ");
    bool isLastOfSerie = false;
    if (iSample == listOfSamples.size() - 1) isLastOfSerie = true;
    if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true;
    
    //get the tree
    tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data());
    //if sample first of the list create a new histogram
    if (isFirstOfSerie) {
       TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name());
       //variable bin histo
       if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec);
       //fixed bin histo
       else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh);
       hist[theHistCounter] -> Sumw2();
       hist[theHistCounter] -> SetFillColor(col[theHistCounter]);
       hist[theHistCounter] -> SetFillStyle(1001);
       theLegends.push_back(*listOfSamples.at(iSample)->Legend());
       cout << *listOfSamples.at(iSample)->Legend() << " ";
    }

    //fill the histogram
    
    TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale()));
    if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
        
    //add the histogram to the stack if the last of the series:
    //either last sample or ~ sample followed by non ~ sample
    if (isLastOfSerie) {
       if (xlowVec != 0) {
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError  (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
       }
       hs -> Add(hist[theHistCounter]);
       cout << hist[theHistCounter] -> GetBinContent(1) << " +/- " <<  hist[theHistCounter] -> GetBinError(1) << endl;
       if ( listOfSamples.at(iSample)->Name()->Contains("wgptg130") ) {
         nSig +=  hist[theHistCounter] -> GetBinContent(1) ;
         nSigErrSq +=  pow(hist[theHistCounter] -> GetBinError(1),2) ;
       }
       else {
         nBkg +=  hist[theHistCounter] -> GetBinContent(1) ;
         nBkgErrSq +=  pow(hist[theHistCounter] -> GetBinError(1),2) ;
       }
       theHistCounter++;
    }
    
  }//end loop on samples

  //Fix the legend
  for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) {
    leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f");   
  }
  
  //get the maximum to properly set the frame
  float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin());
  TH1* theMCSum = (TH1*) hs->GetStack()->Last();
  cout << "total MC " << theMCSum -> GetBinContent(1) << " +/- " << theMCSum -> GetBinError(1) << endl;
  float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin());
  if (theMaxMC > theMax) theMax = theMaxMC;
  
    
  if (isBlind) cout << "total DATA " << hdata -> GetBinContent(1) << " +/- " <<  hdata -> GetBinError(1) << endl;

  //compute the scale factor
  float nData =  hdata -> GetBinContent(1);
  float nDataErr =  hdata -> GetBinError(1);
  newScaleFactor = (nData - nBkg)/(nSig/defScaleFactor);
  float newScaleFactorErr = sqrt( (pow(nDataErr,2) + nBkgErrSq)/(nData - nBkg)/(nData - nBkg) + nSigErrSq/nSig/nSig ) * newScaleFactor;
  cout << "\n The scale factor is " << newScaleFactor << " +/- " << newScaleFactorErr << endl;
  
  //cleanup the memory allocation
  delete theMCSum;
  delete hs;
  delete leg;
  delete hdata;
  infile -> Close();
  delete infile;
  
  return;
}
Exemplo n.º 8
0
int Plot_tauPt_Stage1_DD() {

  double totalMC =0.0;
  double lumi= 35.865; //20.011 ;  // B->5.882  // C->2.646   D->4.353 ;  // E->4.049 ; F->3.16 ;  G->7.554;  H->5.942  //--inv fb--//

  unsigned long long evt_DYJetsToLL_M50=1;
  unsigned long long evt_DYJetsToLL_M5to50=1;
  unsigned long long evt_TT=1;
 
  TFile *file_DYJetsToLL_M50  = new TFile("../python/crab_projects_March3/crab_DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");             
  double xs_DYJetsToLL_M50=4895000;  //--fb--//                                                                                                                    

  TFile *file_DYJetsToLL_M5to50  = new TFile("../python/crab_projects_March3/crab_DYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");    
  double xs_DYJetsToLL_M5to50=7160000;  //--fb--//                                                                                                                    

  TFile *file_TT              = new TFile("../python/crab_projects_March3/crab_TT_TuneCUETP8M2T4_13TeV-powheg-pythia8/results/hist.root");
  double xs_TT=730000; //--fb--//
  double kfact_TT= 1.139;

  TFile *file_TT_Mtt_700to1000      = new TFile("../python/crab_projects_March3/crab_TT_Mtt-700to1000_TuneCUETP8M1_13TeV-powheg-pythia8/results/hist.root");
  double xs_TT_Mtt_700to1000=730000; //--fb--//
  double kfact_TT_Mtt_700to1000= 0.0921;

  TFile *file_TT_Mtt_1000toInf              = new TFile("../python/crab_projects_March3/crab_TT_Mtt-1000toInf_TuneCUETP8M1_13TeV-powheg-pythia8/results/hist.root");
  double xs_TT_Mtt_1000toInf=730000; //--fb--//
  double kfact_TT_Mtt_1000toInf= 0.02474;


  //TFile *file_WJetsToLNu      = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/results/hist.root");
  //double xs_WJetsToLNu=60290000; //--fb--//

  TFile *file_WJetsToLNu      = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu= 50690000; //--fb--//
  //
  TFile *file_WToTauNu_M100  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-100_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M100 = 165000; //--fb--//
  double kfact_WToTauNu_M100 = 1.0 ; 
  //
  TFile *file_WToTauNu_M200  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-200_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M200 = 6370; //--fb--//
  double kfact_WToTauNu_M200 = 1.0 ; 
  //
  TFile *file_WToTauNu_M500  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-500_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M500 = 224.0; //--fb--//
  double kfact_WToTauNu_M500 = 1.0 ; 
  //
  TFile *file_WToTauNu_M1000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-1000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M1000 = 13.7; //--fb--//
  double kfact_WToTauNu_M1000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M2000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-2000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M2000 = 0.437; //--fb--//
  double kfact_WToTauNu_M2000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M3000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-3000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M3000 = 0.0342; //--fb--//
  double kfact_WToTauNu_M3000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M4000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-4000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M4000 = 0.00292; //--fb--//
  double kfact_WToTauNu_M4000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M5000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-5000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M5000 = 0.000233; //--fb--//
  double kfact_WToTauNu_M5000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M6000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-6000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M6000 = 0.000015; //--fb--//
  double kfact_WToTauNu_M6000 = 1.0 ; 
  //
  TFile *file_WJetsToLNu_HT100To200  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-100To200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT100To200 = 1345000 ; //--fb--//
  double kfact_WJetsToLNu_HT100To200 = 1.0 ; 

  TFile *file_WJetsToLNu_HT200To400  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-200To400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT200To400 = 359700 ; //--fb--//
  double kfact_WJetsToLNu_HT200To400 = 1.0 ;

  TFile *file_WJetsToLNu_HT400To600  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-400To600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT400To600 = 48910 ; //--fb--//
  double kfact_WJetsToLNu_HT400To600 = 1.0 ;

  TFile *file_WJetsToLNu_HT600To800  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-600To800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT600To800 = 12050 ; //--fb--//
  double kfact_WJetsToLNu_HT600To800 = 1.0 ;

  TFile *file_WJetsToLNu_HT800To1200  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-800To1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT800To1200 = 5501 ; //--fb--//
  double kfact_WJetsToLNu_HT800To1200 = 1.0 ;

  TFile *file_WJetsToLNu_HT1200To2500  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-1200To2500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT1200To2500 = 1329 ; //--fb--//
  double kfact_WJetsToLNu_HT1200To2500 = 1.0 ;

  TFile *file_WJetsToLNu_HT2500ToInf  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-2500ToInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT2500ToInf = 32.16  ; //--fb--//
  double kfact_WJetsToLNu_HT2500ToInf = 1.0 ;

  TFile *file_ST_tchannel_antitop=new TFile("../python/crab_projects_March3/crab_ST_t-channel_antitop_4f_inclusiveDecays_TuneCUETP8M2T4_13TeV-powhegV2-madspin/results/hist.root");
  double xs_ST_tchannel_antitop = 80950; //--fb--//
  double kfact_ST_tchannel_antitop = 1.0; //0.326;
  //
  TFile *file_ST_tchannel_top=new TFile("../python/crab_projects_March3/crab_ST_t-channel_top_4f_inclusiveDecays_TuneCUETP8M2T4_13TeV-powhegV2-madspin/results/hist.root");
  double xs_ST_tchannel_top =136020; //103200; //--fb--//
  double kfact_ST_tchannel_top = 1.0; //0.43;
  //
  TFile *file_ST_tW_antitop=new TFile("../python/crab_projects_March3/crab_ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M2T4/results/hist.root");
  double xs_ST_tW_antitop = 38090; //--fb--//
  double kfact_ST_tW_antitop =1.0; // 0.94;
  //
  TFile *file_ST_tW_top=new TFile("../python/crab_projects_March3/crab_ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M2T4/results/hist.root");
  double xs_ST_tW_top = 38090; //--fb--//
  double kfact_ST_tW_top = 1.0; //0.94;
  //
  TFile *file_WW=new TFile("../python/crab_projects_March3/crab_WW_TuneCUETP8M1_13TeV-pythia8/results/hist.root");
  double xs_WW = 63210; //--fb--//
  //
  TFile *file_WZ=new TFile("../python/crab_projects_March3/crab_WZ_TuneCUETP8M1_13TeV-pythia8/results/hist.root");
  double xs_WZ = 22820; //--fb--//
  double kfact_WZ = 2.06; // 47.13/22.82
  //
  TFile *file_ZZ=new TFile("../python/crab_projects_March3/crab_ZZ_TuneCUETP8M1_13TeV-pythia8/results/hist.root");
  double xs_ZZ = 10320; //--fb--//
  double kfact_ZZ = 1.60 ; //16523/10320
  //
  std::cout << "get datadriven root file" << std::endl;
  TFile *file_Datadriven  = new TFile("/net/scratch_cms3a/materok/wprime/qcd/dataDrivenTree15_pt_base_Mar7_fromData.root");


  /// DATA ///
  TFile *file_Tau_Run2016B = new TFile("../python/crab_projects_March3/crab_Tau_Run2016B/results/hist.root");
  TFile *file_Tau_Run2016C = new TFile("../python/crab_projects_March3/crab_Tau_Run2016C/results/hist.root");
  TFile *file_Tau_Run2016D = new TFile("../python/crab_projects_March3/crab_Tau_Run2016D/results/hist.root");
  TFile *file_Tau_Run2016E = new TFile("../python/crab_projects_March3/crab_Tau_Run2016E/results/hist.root");
  TFile *file_Tau_Run2016F = new TFile("../python/crab_projects_March3/crab_Tau_Run2016F/results/hist.root");
  TFile *file_Tau_Run2016G = new TFile("../python/crab_projects_March3/crab_Tau_Run2016G/results/hist.root");
  TFile *file_Tau_Run2016H_v2 = new TFile("../python/crab_projects_March3/crab_Tau_Run2016H_1/results/hist.root");
  TFile *file_Tau_Run2016H_v3 = new TFile("../python/crab_projects_March3/crab_Tau_Run2016H_2/results/hist.root");


  /// Signal ///
  TFile *file_Wprime_M4000 = new TFile("../python/crab_projects_March3/crab_WprimeToTauNu_M-4000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_Wprime_M4000= 2.04; // --fb-- //

  //--//
  TH1D* h1_evt_DYJetsToLL_M50 = (TH1D*)file_DYJetsToLL_M50->Get("demo/histoDir/eventCount");
  evt_DYJetsToLL_M50 = h1_evt_DYJetsToLL_M50->GetEntries(); // Integral();
  double wt_DYJetsToLL_M50 = (xs_DYJetsToLL_M50*lumi)/evt_DYJetsToLL_M50 ;
  TH1D* tauPt_Stage1_DYJetsToLL_M50 = (TH1D*)file_DYJetsToLL_M50->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_DYJetsToLL_M50->Scale(wt_DYJetsToLL_M50);
  std::cout << "DYJetsToLL_M50 weighted nevt=" << tauPt_Stage1_DYJetsToLL_M50->Integral() << std::endl;
  totalMC += tauPt_Stage1_DYJetsToLL_M50->Integral();

  TH1D* h1_evt_DYJetsToLL_M5to50 = (TH1D*)file_DYJetsToLL_M5to50->Get("demo/histoDir/eventCount");
  evt_DYJetsToLL_M5to50 = h1_evt_DYJetsToLL_M5to50->GetEntries(); // Integral();
  double wt_DYJetsToLL_M5to50 = (xs_DYJetsToLL_M5to50*lumi)/evt_DYJetsToLL_M5to50 ;
  TH1D* tauPt_Stage1_DYJetsToLL_M5to50 = (TH1D*)file_DYJetsToLL_M5to50->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_DYJetsToLL_M5to50->Scale(wt_DYJetsToLL_M5to50);
  std::cout << "DYJetsToLL_M5to50 weighted nevt=" << tauPt_Stage1_DYJetsToLL_M5to50->Integral() << std::endl;
  totalMC += tauPt_Stage1_DYJetsToLL_M5to50->Integral() ;
  //
  TH1D* total_DY = (TH1D*)tauPt_Stage1_DYJetsToLL_M50->Clone(); 
  total_DY->Add(tauPt_Stage1_DYJetsToLL_M5to50);
  total_DY->SetFillColorAlpha(kRed,0.5);
  total_DY->SetLineColor(kBlack);
  total_DY->Rebin(10);
  //

  TH1D* h1_evt_TT = (TH1D*)file_TT->Get("demo/histoDir/eventCount");
  evt_TT = h1_evt_TT->GetEntries(); // Integral();
  double wt_TT = (xs_TT*lumi)/evt_TT ;
  TH1D* tauPt_Stage1_TT  = (TH1D*)file_TT->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_TT->Scale(wt_TT);
  tauPt_Stage1_TT->Scale(kfact_TT);
  std::cout << "TTbar weighted nevt=" << tauPt_Stage1_TT->Integral() << std::endl;
  totalMC += tauPt_Stage1_TT->Integral();

  //file_TT_Mtt_700to1000
  TH1D* h1_evt_TT_Mtt_700to1000 = (TH1D*)file_TT_Mtt_700to1000->Get("demo/histoDir/eventCount");
  evt_TT_Mtt_700to1000 = h1_evt_TT_Mtt_700to1000->GetEntries(); // Integral();
  double wt_TT_Mtt_700to1000 = (xs_TT_Mtt_700to1000*lumi)/evt_TT_Mtt_700to1000 ;
  TH1D* tauPt_Stage1_TT_Mtt_700to1000  = (TH1D*)file_TT_Mtt_700to1000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_TT_Mtt_700to1000->Scale(wt_TT_Mtt_700to1000);
  tauPt_Stage1_TT_Mtt_700to1000->Scale(kfact_TT_Mtt_700to1000);
  std::cout << "TT_Mtt_700to1000bar weighted nevt=" << tauPt_Stage1_TT_Mtt_700to1000->Integral() << std::endl;
  totalMC += tauPt_Stage1_TT_Mtt_700to1000->Integral() ;

  //file_TT_Mtt_1000toInf
  TH1D* h1_evt_TT_Mtt_1000toInf = (TH1D*)file_TT_Mtt_1000toInf->Get("demo/histoDir/eventCount");
  evt_TT_Mtt_1000toInf = h1_evt_TT_Mtt_1000toInf->GetEntries(); // Integral();
  double wt_TT_Mtt_1000toInf = (xs_TT_Mtt_1000toInf*lumi)/evt_TT_Mtt_1000toInf ;
  TH1D* tauPt_Stage1_TT_Mtt_1000toInf  = (TH1D*)file_TT_Mtt_1000toInf->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_TT_Mtt_1000toInf->Scale(wt_TT_Mtt_1000toInf);
  tauPt_Stage1_TT_Mtt_1000toInf->Scale(kfact_TT_Mtt_1000toInf);
  std::cout << "TT_Mtt_1000toInfbar weighted nevt=" << tauPt_Stage1_TT_Mtt_1000toInf->Integral() << std::endl;
  totalMC += tauPt_Stage1_TT_Mtt_1000toInf->Integral() ;

  TH1D* total_TT = (TH1D*)tauPt_Stage1_TT->Clone(); 
  total_TT->Add(tauPt_Stage1_TT_Mtt_700to1000);
  total_TT->Add(tauPt_Stage1_TT_Mtt_1000toInf);
  total_TT->SetFillColor(kBlue-7);
  total_TT->SetLineColor(kBlack);
  total_TT->Rebin(10);


  /*
  TH1D* h1_evt_WJetsToLNu = (TH1D*)file_WJetsToLNu->Get("demo/histoDir/eventCount");
  evt_WJetsToLNu = h1_evt_WJetsToLNu->GetEntries(); //Integral();
  std::cout << "evt_WJetsToLNu = " << evt_WJetsToLNu << std::endl;
  double wt_WJetsToLNu = (xs_WJetsToLNu*lumi)/evt_WJetsToLNu ;
  TH1D* tauPt_Stage1_WJetsToLNu  = (TH1D*)file_WJetsToLNu->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //
  tauPt_Stage1_WJetsToLNu->Sumw2(kFALSE);
  tauPt_Stage1_WJetsToLNu->SetBinErrorOption(TH1::kPoisson);
  std::cout << "**WJets** unweighted nevt=" << tauPt_Stage1_WJetsToLNu->Integral() << std::endl;
  std::cout << "wt_WJetsToLNu = " << wt_WJetsToLNu << std::endl;
  tauPt_Stage1_WJetsToLNu->Scale(wt_WJetsToLNu);
  tauPt_Stage1_WJetsToLNu->SetFillColorAlpha(kGreen-7,0.5);
  tauPt_Stage1_WJetsToLNu->SetLineColor(kGreen-7);
  tauPt_Stage1_WJetsToLNu->Rebin(40);
  std::cout << "**WJets** weighted nevt=" << tauPt_Stage1_WJetsToLNu->Integral() << std::endl;
  */

  //file_ST_tchannel_antitop
  TH1D* h1_evt_ST_tchannel_antitop = (TH1D*)file_ST_tchannel_antitop->Get("demo/histoDir/eventCount");
  unsigned long long evt_ST_tchannel_antitop = h1_evt_ST_tchannel_antitop->GetEntries(); //Integral();
  double wt_ST_tchannel_antitop = (xs_ST_tchannel_antitop*lumi)/evt_ST_tchannel_antitop ;
  TH1D* tauPt_Stage1_ST_tchannel_antitop  = (TH1D*)file_ST_tchannel_antitop->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_ST_tchannel_antitop->Scale(wt_ST_tchannel_antitop);
  tauPt_Stage1_ST_tchannel_antitop->Scale(kfact_ST_tchannel_antitop);
  std::cout << "ST_tchannel_antitop weighted nevt=" << tauPt_Stage1_ST_tchannel_antitop->Integral() << std::endl;
  totalMC += tauPt_Stage1_ST_tchannel_antitop->Integral();

  //file_ST_tchannel_top
  TH1D* h1_evt_ST_tchannel_top = (TH1D*)file_ST_tchannel_top->Get("demo/histoDir/eventCount");
  unsigned long long evt_ST_tchannel_top = h1_evt_ST_tchannel_top->GetEntries(); //Integral();
  double wt_ST_tchannel_top = (xs_ST_tchannel_top*lumi)/evt_ST_tchannel_top ;
  TH1D* tauPt_Stage1_ST_tchannel_top  = (TH1D*)file_ST_tchannel_top->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_ST_tchannel_top->Scale(wt_ST_tchannel_top);
  tauPt_Stage1_ST_tchannel_top->Scale(kfact_ST_tchannel_top);
  std::cout << "ST_tchannel_top weighted nevt=" << tauPt_Stage1_ST_tchannel_top->Integral() << std::endl;
  totalMC += tauPt_Stage1_ST_tchannel_top->Integral() ;

  //file_ST_tW_antitop
  TH1D* h1_evt_ST_tW_antitop = (TH1D*)file_ST_tW_antitop->Get("demo/histoDir/eventCount");
  unsigned long long evt_ST_tW_antitop = h1_evt_ST_tW_antitop->GetEntries(); //Integral();
  double wt_ST_tW_antitop = (xs_ST_tW_antitop*lumi)/evt_ST_tW_antitop ;
  TH1D* tauPt_Stage1_ST_tW_antitop  = (TH1D*)file_ST_tW_antitop->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_ST_tW_antitop->Scale(wt_ST_tW_antitop);
  tauPt_Stage1_ST_tW_antitop->Scale(kfact_ST_tW_antitop);
  std::cout << "ST_tW_antitop weighted nevt=" << tauPt_Stage1_ST_tW_antitop->Integral() << std::endl;
  totalMC += tauPt_Stage1_ST_tW_antitop->Integral();

  //file_ST_tW_top
  TH1D* h1_evt_ST_tW_top = (TH1D*)file_ST_tW_top->Get("demo/histoDir/eventCount");
  unsigned long long evt_ST_tW_top = h1_evt_ST_tW_top->GetEntries(); //Integral();
  double wt_ST_tW_top = (xs_ST_tW_top*lumi)/evt_ST_tW_top ;
  TH1D* tauPt_Stage1_ST_tW_top  = (TH1D*)file_ST_tW_top->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_ST_tW_top->Scale(wt_ST_tW_top);
  tauPt_Stage1_ST_tW_top->Scale(kfact_ST_tW_top);
  std::cout << "ST_tW_top weighted nevt=" << tauPt_Stage1_ST_tW_top->Integral() << std::endl;
  totalMC += tauPt_Stage1_ST_tW_top->Integral() ;

  TH1D* total_ST = (TH1D*)tauPt_Stage1_ST_tchannel_antitop->Clone(); 
  total_ST->Add(tauPt_Stage1_ST_tchannel_top);
  total_ST->Add(tauPt_Stage1_ST_tW_antitop);
  total_ST->Add(tauPt_Stage1_ST_tW_top);
  total_ST->SetFillColorAlpha(kCyan,0.5);
  total_ST->SetLineColor(kBlack);
  total_ST->Rebin(10);

  //file_WJetsToLNu_HT100To200
  TH1D* h1_evt_WJetsToLNu_HT100To200 = (TH1D*)file_WJetsToLNu_HT100To200->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT100To200 = h1_evt_WJetsToLNu_HT100To200->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT100To200 = (xs_WJetsToLNu_HT100To200*lumi)/evt_WJetsToLNu_HT100To200 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT100To200  = (TH1D*)file_WJetsToLNu_HT100To200->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                           
  //  tauPt_Stage1_WJetsToLNu_HT100To200->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT100To200->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT100To200->Scale(wt_WJetsToLNu_HT100To200);
  std::cout << "WJetsToLNu_HT100To200 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT100To200->Integral() << std::endl;
  totalMC += tauPt_Stage1_WJetsToLNu_HT100To200->Integral();
  //tauPt_Stage1_WJetsToLNu_HT100To200->Scale(kfact_WJetsToLNu_HT100To200);
  //  std::cout << tauPt_Stage1_WJetsToLNu_HT100To200->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT200To400
  TH1D* h1_evt_WJetsToLNu_HT200To400 = (TH1D*)file_WJetsToLNu_HT200To400->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT200To400 = h1_evt_WJetsToLNu_HT200To400->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT200To400 = (xs_WJetsToLNu_HT200To400*lumi)/evt_WJetsToLNu_HT200To400 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT200To400  = (TH1D*)file_WJetsToLNu_HT200To400->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  // tauPt_Stage1_WJetsToLNu_HT200To400->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT200To400->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT200To400->Scale(wt_WJetsToLNu_HT200To400);
 std::cout << "WJetsToLNu_HT200To400 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT200To400->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu_HT200To400->Integral();
  //tauPt_Stage1_WJetsToLNu_HT200To400->Scale(kfact_WJetsToLNu_HT200To400);
  //std::cout << tauPt_Stage1_WJetsToLNu_HT200To400->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT400To600
  TH1D* h1_evt_WJetsToLNu_HT400To600 = (TH1D*)file_WJetsToLNu_HT400To600->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT400To600 = h1_evt_WJetsToLNu_HT400To600->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT400To600 = (xs_WJetsToLNu_HT400To600*lumi)/evt_WJetsToLNu_HT400To600 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT400To600  = (TH1D*)file_WJetsToLNu_HT400To600->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  // tauPt_Stage1_WJetsToLNu_HT400To600->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT400To600->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT400To600->Scale(wt_WJetsToLNu_HT400To600);
  std::cout << "WJetsToLNu_HT400To600 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT400To600->Integral() << std::endl;
  totalMC += tauPt_Stage1_WJetsToLNu_HT400To600->Integral();
  // tauPt_Stage1_WJetsToLNu_HT400To600->Scale(kfact_WJetsToLNu_HT400To600);
  // std::cout << tauPt_Stage1_WJetsToLNu_HT400To600->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT600To800
  TH1D* h1_evt_WJetsToLNu_HT600To800 = (TH1D*)file_WJetsToLNu_HT600To800->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT600To800 = h1_evt_WJetsToLNu_HT600To800->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT600To800 = (xs_WJetsToLNu_HT600To800*lumi)/evt_WJetsToLNu_HT600To800 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT600To800  = (TH1D*)file_WJetsToLNu_HT600To800->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  //  tauPt_Stage1_WJetsToLNu_HT600To800->Sumw2(kFALSE);
  // tauPt_Stage1_WJetsToLNu_HT600To800->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT600To800->Scale(wt_WJetsToLNu_HT600To800);
  std::cout << "WJetsToLNu_HT600To800 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT600To800->Integral() << std::endl;
  totalMC +=  tauPt_Stage1_WJetsToLNu_HT600To800->Integral();
  // tauPt_Stage1_WJetsToLNu_HT600To800->Scale(kfact_WJetsToLNu_HT600To800);
  // std::cout << tauPt_Stage1_WJetsToLNu_HT600To800->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT800To1200
  TH1D* h1_evt_WJetsToLNu_HT800To1200 = (TH1D*)file_WJetsToLNu_HT800To1200->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT800To1200 = h1_evt_WJetsToLNu_HT800To1200->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT800To1200 = (xs_WJetsToLNu_HT800To1200*lumi)/evt_WJetsToLNu_HT800To1200 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT800To1200  = (TH1D*)file_WJetsToLNu_HT800To1200->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  // tauPt_Stage1_WJetsToLNu_HT800To1200->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT800To1200->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT800To1200->Scale(wt_WJetsToLNu_HT800To1200);
 std::cout << "WJetsToLNu_HT800To1200 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT800To1200->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu_HT800To1200->Integral();
  //tauPt_Stage1_WJetsToLNu_HT800To1200->Scale(kfact_WJetsToLNu_HT800To1200);
  // std::cout << tauPt_Stage1_WJetsToLNu_HT800To1200->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT1200To2500
  TH1D* h1_evt_WJetsToLNu_HT1200To2500 = (TH1D*)file_WJetsToLNu_HT1200To2500->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT1200To2500 = h1_evt_WJetsToLNu_HT1200To2500->GetEntries(); //Integral();                                                             
  double wt_WJetsToLNu_HT1200To2500 = (xs_WJetsToLNu_HT1200To2500*lumi)/evt_WJetsToLNu_HT1200To2500 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT1200To2500  = (TH1D*)file_WJetsToLNu_HT1200To2500->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  // tauPt_Stage1_WJetsToLNu_HT1200To2500->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT1200To2500->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT1200To2500->Scale(wt_WJetsToLNu_HT1200To2500);
 std::cout << "WJetsToLNu_HT1200To2500 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT1200To2500->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu_HT1200To2500->Integral();
  // tauPt_Stage1_WJetsToLNu_HT1200To2500->Scale(kfact_WJetsToLNu_HT1200To2500);
  //std::cout << tauPt_Stage1_WJetsToLNu_HT1200To2500->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT2500ToInf
  TH1D* h1_evt_WJetsToLNu_HT2500ToInf = (TH1D*)file_WJetsToLNu_HT2500ToInf->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT2500ToInf = h1_evt_WJetsToLNu_HT2500ToInf->GetEntries(); //Integral();                                                             
  double wt_WJetsToLNu_HT2500ToInf = (xs_WJetsToLNu_HT2500ToInf*lumi)/evt_WJetsToLNu_HT2500ToInf ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT2500ToInf  = (TH1D*)file_WJetsToLNu_HT2500ToInf->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  //tauPt_Stage1_WJetsToLNu_HT2500ToInf->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT2500ToInf->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT2500ToInf->Scale(wt_WJetsToLNu_HT2500ToInf);
 std::cout << "WJetsToLNu_HT2500ToInf weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT2500ToInf->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu_HT2500ToInf->Integral();
  //tauPt_Stage1_WJetsToLNu_HT2500ToInf->Scale(kfact_WJetsToLNu_HT2500ToInf);
  ///std::cout << tauPt_Stage1_WJetsToLNu_HT2500ToInf->GetBinError(300) << std::endl;

  //file_WToTauNu_M100
  TH1D* h1_evt_WToTauNu_M100 = (TH1D*)file_WToTauNu_M100->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M100 = h1_evt_WToTauNu_M100->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M100 = (xs_WToTauNu_M100*lumi)/evt_WToTauNu_M100 ;
  TH1D* tauPt_Stage1_WToTauNu_M100  = (TH1D*)file_WToTauNu_M100->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M100->Scale(wt_WToTauNu_M100);
 std::cout << "WToTauNu_M100 weighted nevt=" << tauPt_Stage1_WToTauNu_M100->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M100->Integral() ;

  //file_WToTauNu_M200
  TH1D* h1_evt_WToTauNu_M200 = (TH1D*)file_WToTauNu_M200->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M200 = h1_evt_WToTauNu_M200->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M200 = (xs_WToTauNu_M200*lumi)/evt_WToTauNu_M200 ;
  TH1D* tauPt_Stage1_WToTauNu_M200  = (TH1D*)file_WToTauNu_M200->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M200->Scale(wt_WToTauNu_M200);
 std::cout << "WToTauNu_M200 weighted nevt=" << tauPt_Stage1_WToTauNu_M200->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M200->Integral();

  //file_WToTauNu_M500
  TH1D* h1_evt_WToTauNu_M500 = (TH1D*)file_WToTauNu_M500->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M500 = h1_evt_WToTauNu_M500->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M500 = (xs_WToTauNu_M500*lumi)/evt_WToTauNu_M500 ;
  TH1D* tauPt_Stage1_WToTauNu_M500  = (TH1D*)file_WToTauNu_M500->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M500->Scale(wt_WToTauNu_M500);
 std::cout << "WToTauNu_M500 weighted nevt=" << tauPt_Stage1_WToTauNu_M500->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M500->Integral() ;

  //file_WToTauNu_M1000
  TH1D* h1_evt_WToTauNu_M1000 = (TH1D*)file_WToTauNu_M1000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M1000 = h1_evt_WToTauNu_M1000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M1000 = (xs_WToTauNu_M1000*lumi)/evt_WToTauNu_M1000 ;
  TH1D* tauPt_Stage1_WToTauNu_M1000  = (TH1D*)file_WToTauNu_M1000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M1000->Scale(wt_WToTauNu_M1000);
 std::cout << "WToTauNu_M1000 weighted nevt=" << tauPt_Stage1_WToTauNu_M1000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M1000->Integral();

  //file_WToTauNu_M2000
  TH1D* h1_evt_WToTauNu_M2000 = (TH1D*)file_WToTauNu_M2000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M2000 = h1_evt_WToTauNu_M2000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M2000 = (xs_WToTauNu_M2000*lumi)/evt_WToTauNu_M2000 ;
  TH1D* tauPt_Stage1_WToTauNu_M2000  = (TH1D*)file_WToTauNu_M2000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M2000->Scale(wt_WToTauNu_M2000);
 std::cout << "WToTauNu_M2000 weighted nevt=" << tauPt_Stage1_WToTauNu_M2000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M2000->Integral();

  //file_WToTauNu_M3000
  TH1D* h1_evt_WToTauNu_M3000 = (TH1D*)file_WToTauNu_M3000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M3000 = h1_evt_WToTauNu_M3000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M3000 = (xs_WToTauNu_M3000*lumi)/evt_WToTauNu_M3000 ;
  TH1D* tauPt_Stage1_WToTauNu_M3000  = (TH1D*)file_WToTauNu_M3000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M3000->Scale(wt_WToTauNu_M3000);
 std::cout << "WToTauNu_M3000 weighted nevt=" << tauPt_Stage1_WToTauNu_M3000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M3000->Integral();

  //file_WToTauNu_M4000
  TH1D* h1_evt_WToTauNu_M4000 = (TH1D*)file_WToTauNu_M4000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M4000 = h1_evt_WToTauNu_M4000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M4000 = (xs_WToTauNu_M4000*lumi)/evt_WToTauNu_M4000 ;
  TH1D* tauPt_Stage1_WToTauNu_M4000  = (TH1D*)file_WToTauNu_M4000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M4000->Scale(wt_WToTauNu_M4000);
 std::cout << "WToTauNu_M4000 weighted nevt=" << tauPt_Stage1_WToTauNu_M4000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M4000->Integral();

  //file_WToTauNu_M5000
  TH1D* h1_evt_WToTauNu_M5000 = (TH1D*)file_WToTauNu_M5000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M5000 = h1_evt_WToTauNu_M5000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M5000 = (xs_WToTauNu_M5000*lumi)/evt_WToTauNu_M5000 ;
  TH1D* tauPt_Stage1_WToTauNu_M5000  = (TH1D*)file_WToTauNu_M5000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M5000->Scale(wt_WToTauNu_M5000);
 std::cout << "WToTauNu_M5000 weighted nevt=" << tauPt_Stage1_WToTauNu_M5000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M5000->Integral();

  //file_WToTauNu_M6000
  TH1D* h1_evt_WToTauNu_M6000 = (TH1D*)file_WToTauNu_M6000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M6000 = h1_evt_WToTauNu_M6000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M6000 = (xs_WToTauNu_M6000*lumi)/evt_WToTauNu_M6000 ;
  TH1D* tauPt_Stage1_WToTauNu_M6000  = (TH1D*)file_WToTauNu_M6000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M6000->Scale(wt_WToTauNu_M6000);
 std::cout << "WToTauNu_M6000 weighted nevt=" << tauPt_Stage1_WToTauNu_M6000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M6000->Integral();

  //file_WJetsToLNu
  TH1D* h1_evt_WJetsToLNu = (TH1D*)file_WJetsToLNu->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu = h1_evt_WJetsToLNu->GetEntries(); //Integral();                                                             
  double wt_WJetsToLNu = (xs_WJetsToLNu*lumi)/evt_WJetsToLNu ;
  TH1D* tauPt_Stage1_WJetsToLNu  = (TH1D*)file_WJetsToLNu->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WJetsToLNu->Scale(wt_WJetsToLNu);
 std::cout << "WJetsToLNu weighted nevt=" << tauPt_Stage1_WJetsToLNu->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu->Integral();

  TH1D* total_WJets = (TH1D*)tauPt_Stage1_WJetsToLNu_HT100To200->Clone();
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT200To400);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT400To600);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT600To800);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT800To1200);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT1200To2500);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT2500ToInf);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M100);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M200);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M500);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M1000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M2000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M3000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M4000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M5000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M6000);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu);
  total_WJets->SetFillColorAlpha(kGreen-8,0.5);
  total_WJets->SetLineColor(kBlack);
  //std::cout << "Wjets " << total_WJets->GetBinError(300) << std::endl;

  total_WJets->Rebin(10);


  //file_WW
  TH1D* h1_evt_WW = (TH1D*)file_WW->Get("demo/histoDir/eventCount");
  unsigned long long evt_WW = h1_evt_WW->GetEntries(); //Integral();                                                                         
  double wt_WW = (xs_WW*lumi)/evt_WW ;
  TH1D* tauPt_Stage1_WW  = (TH1D*)file_WW->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //
  //tauPt_Stage1_WW->Sumw2(kFALSE);
  //tauPt_Stage1_WW->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WW->Scale(wt_WW);
 std::cout << "WW weighted nevt=" << tauPt_Stage1_WW->Integral() << std::endl;
 totalMC +=tauPt_Stage1_WW->Integral() ;

  //file_WZ
  TH1D* h1_evt_WZ = (TH1D*)file_WZ->Get("demo/histoDir/eventCount");
  unsigned long long evt_WZ = h1_evt_WZ->GetEntries(); //Integral();                                                                         
  double wt_WZ = (xs_WZ*lumi)/evt_WZ ;
  TH1D* tauPt_Stage1_WZ  = (TH1D*)file_WZ->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //
  //tauPt_Stage1_WZ->Sumw2(kFALSE);
  // tauPt_Stage1_WZ->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WZ->Scale(wt_WZ);
  tauPt_Stage1_WZ->Scale(kfact_WZ);
 std::cout << "WZ weighted nevt=" << tauPt_Stage1_WZ->Integral() << std::endl;
 totalMC +=  tauPt_Stage1_WZ->Integral();

  //file_ZZ
  TH1D* h1_evt_ZZ = (TH1D*)file_ZZ->Get("demo/histoDir/eventCount");
  unsigned long long evt_ZZ = h1_evt_ZZ->GetEntries(); //Integral();                                                                         
  double wt_ZZ = (xs_ZZ*lumi)/evt_ZZ ;
  TH1D* tauPt_Stage1_ZZ  = (TH1D*)file_ZZ->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //
  //tauPt_Stage1_ZZ->Sumw2(kFALSE);
  //tauPt_Stage1_ZZ->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_ZZ->Scale(wt_ZZ);
  tauPt_Stage1_ZZ->Scale(kfact_ZZ);
 std::cout << "ZZ weighted nevt=" << tauPt_Stage1_ZZ->Integral() << std::endl;
 totalMC += tauPt_Stage1_ZZ->Integral();

  TH1D* total_diboson = (TH1D*)tauPt_Stage1_WW->Clone();
  total_diboson->Add(tauPt_Stage1_WZ);
  total_diboson->Add(tauPt_Stage1_ZZ);
  total_diboson->SetFillColorAlpha(kOrange+2,0.5);
  total_diboson->SetLineColor(kBlack);
  total_diboson->Rebin(10);


  //datadriven                                                                                                                                                                                                           
  //  double wt_Datadriven = (lumi/33.507) ;                                                                                                                                                                             
  TH1D* total_QCD = (TH1D*)file_Datadriven->Get("demo/histoDir/tauPt_Stage1");
  total_QCD->SetFillStyle(3001);
  total_QCD->SetFillColor(kPink+1);
  total_QCD->SetLineColor(kBlack);
  total_QCD->Rebin(10);  //datadriven                                                                                                                                                                                  

  std::cout << "totalMC(w/o DD) =" << totalMC << std::endl;

   std::cout << "will do data" << std::endl;
  
  //--Data--//
   TH1D* tauPt_Stage1_Run2016F  =  (TH1D*)file_Tau_Run2016F->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016E  =  (TH1D*)file_Tau_Run2016E->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016D  =  (TH1D*)file_Tau_Run2016D->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016C  =  (TH1D*)file_Tau_Run2016C->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016B  =  (TH1D*)file_Tau_Run2016B->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016G  =  (TH1D*)file_Tau_Run2016G->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016H_v2  = (TH1D*)file_Tau_Run2016H_v2->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016H_v3  = (TH1D*)file_Tau_Run2016H_v3->Get("demo/histoDir/tauPt_Stage1");
   
   /*
  std::cout << "Will Clone B" << std::endl;
  TH1D* tauPt_Stage1_Run2016BCD = (TH1D*)tauPt_Stage1_Run2016B->Clone();
 
  std::cout << "Will add C" << std::endl;
  tauPt_Stage1_Run2016BCD->Add(tauPt_Stage1_Run2016C);

  std::cout << "Will add D" << std::endl;
  tauPt_Stage1_Run2016BCD->Add(tauPt_Stage1_Run2016D);

  //  std::cout << "Will add E" << std::endl;
  // tauPt_Stage1_Run2016BCDEF->Add(tauPt_Stage1_Run2016E);

  // std::cout << "Will add F" << std::endl;
  //  tauPt_Stage1_Run2016BCDEF->Add(tauPt_Stage1_Run2016F);
  */

  TH1D* tauPt_Stage1_Run2016all = (TH1D*)tauPt_Stage1_Run2016B->Clone();
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016C);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016D);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016E);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016F);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016G);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016H_v2);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016H_v3);
                                                                                                                                    
  tauPt_Stage1_Run2016all->SetMarkerStyle(20);
  tauPt_Stage1_Run2016all->SetMarkerColor(kBlack);
  tauPt_Stage1_Run2016all->SetLineColor(kBlack);
  tauPt_Stage1_Run2016all->Rebin(10);
  
  std::cout << "will do signal " << std::endl;
  //--Signal--//
  TH1D* h1_evt_Wprime_M4000 = (TH1D*)file_Wprime_M4000->Get("demo/histoDir/eventCount");
  unsigned long long evt_Wprime_M4000 = h1_evt_Wprime_M4000->GetEntries(); //Integral();                                                                          
  // std::cout << "evt_Wprime_M4000 = " << evt_Wprime_M4000 << std::endl;
  double wt_Wprime_M4000 = (xs_Wprime_M4000*lumi)/evt_Wprime_M4000 ;
  TH1D* tauPt_Stage1_Wprime_M4000  = (TH1D*)file_Wprime_M4000->Get("demo/histoDir/tauPt_Stage1");
  std::cout << "Sig Eff W' M4000 : " << ( tauPt_Stage1_Wprime_M4000->GetEntries() / evt_Wprime_M4000 ) << std::endl;
  tauPt_Stage1_Wprime_M4000->Scale(wt_Wprime_M4000);
  //  tauPt_Stage1_Wprime_M4000->SetFillColorAlpha(kGreen-7,0.5);
  tauPt_Stage1_Wprime_M4000->SetLineColor(kMagenta);
  tauPt_Stage1_Wprime_M4000->SetLineWidth(2);
  tauPt_Stage1_Wprime_M4000->SetLineStyle(5);
  tauPt_Stage1_Wprime_M4000->Rebin(10) ;
 
  //--Plotting Styles//
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.05);
  gStyle->SetPadBottomMargin(0.12);  
  gStyle->SetPadTopMargin(0.05);   
  gStyle->SetTitleXSize(0.05);
  gStyle->SetTitleXOffset(1.05);
  gStyle->SetTitleYSize(0.05);
  gStyle->SetTitleYOffset(1.05);

  //////// Output File /////////
  TFile* outputFile = new TFile("Out_tauPt_Stage1.root","RECREATE");
  outputFile->cd();

  //--//
  THStack *hs = new THStack("hs","");
  // hs->Add(tauPt_Stage1_WJetsToLNu);
  hs->Add(total_diboson);
  hs->Add(total_DY);
  hs->Add(total_ST);
  hs->Add(total_TT);
  //  hs->Add(tauPt_Stage1_DYJetsToLL_M50);
  hs->Add(total_QCD);
  //  hs->Add(total_ZJets);
  hs->Add(total_WJets);
  //tauPt_Stage1_->SetTitle("");
    /*
  eff1->GetYaxis()->SetTitle("Events");
  //eff1->SetMarkerStyle(0);
  //eff1->SetMarkerColor(kBlack);
  eff1->SetLineColor(kBlack);
  eff1->SetLineWidth(2);
  */
  TCanvas* my_canvas = new TCanvas("canvas","canvas",800,600);
  my_canvas->cd();
  //  hs->Draw();
  gPad->SetLogy();
  hs->Draw("HIST");                                                                                                                                        
  hs->SetMaximum(100000);
  hs->SetMinimum(0.1);
  hs->GetXaxis()->SetRangeUser(0, 1000);
  //  hs->GetXaxis()->SetLimits(40, 3200);
  hs->GetXaxis()->SetTitle("#tau pT [GeV]");
  hs->GetYaxis()->SetTitle("Events");

  TH1F* total =  (TH1F*)hs->GetStack()->Last()->Clone();
  // total->SetFillStyle(3004);                                                                                                                                      
  // total->SetFillColor(kGray+1); 
  //  total->SetMarkerColor(0);
  // total->Draw("SAME E2");
  //hs->GetStack()->Last()->Draw("same E");
  // hs->Draw("SAME HIST");

  //  tauPt_Stage1_Run2016E->Draw("SAME E0");
  tauPt_Stage1_Run2016all->Draw("SAME E0");
  TH1F* mydata =  (TH1F*)tauPt_Stage1_Run2016all->Clone();

  //tauPt_Stage1_Run2016C->Draw("SAME E0");
  //tauPt_Stage1_Run2016CDE->Draw("SAME E0");
  //
  tauPt_Stage1_Wprime_M4000->Draw("SAME HIST");
  //  hs->SetOption("HIST L");
  
  TLatex* CMS_text = new TLatex(0.20,0.90,"CMS");
  CMS_text->SetNDC();
  CMS_text->SetTextSize(0.05);
  CMS_text->SetTextAngle(0);
  CMS_text->Draw("same");
  TLatex* CMS_text_2 = new TLatex(0.20,0.85,"Preliminary");
  CMS_text_2->SetNDC();
  CMS_text_2->SetTextFont(42);
  CMS_text_2->SetTextSize(0.05);
  CMS_text_2->SetTextAngle(0);
  CMS_text_2->Draw("same");    

  TLatex* lumiText = new TLatex(0.92,0.975,"35.9 fb^{-1} (13 TeV)");
  lumiText->SetNDC();
  lumiText->SetTextFont(42);
  lumiText->SetTextSize(0.04);
  lumiText->SetTextAlign(32);
  lumiText->Draw("same");     

  TLegend *leg_example = new TLegend(0.75,0.50,0.94,0.94);
  leg_example->SetFillColor(0);
  leg_example->SetTextFont(42);
  leg_example->SetBorderSize(0);
  leg_example->AddEntry(total_WJets, "Wjets","f");
  leg_example->AddEntry(total_DY, "DY","f");
  leg_example->AddEntry(total_TT, "TT","f");
  //leg_example->AddEntry(tauPt_Stage1_WJetsToLNu, "Wjets","f");
  leg_example->AddEntry(total_ST, "Single Top", "f");
  leg_example->AddEntry(total_diboson, "Diboson", "f");
  leg_example->AddEntry(total_QCD, "QCD datadriven", "f");
  // leg_example->AddEntry(total_ZJets, "Z", "f");
  leg_example->AddEntry(tauPt_Stage1_Wprime_M4000, "SSM W' 4 TeV", "l");
  leg_example->AddEntry(tauPt_Stage1_Run2016all, "Data", "pl" );
  // leg_example->AddEntry(tauPt_Stage1_Run2016E, "Data", "pl" );
  // leg_example->AddEntry(tauPt_Stage1_Run2016D, "Data", "pl" );
  leg_example->Draw("same");
  
  my_canvas->Write();
  my_canvas->Print("tauPt_Stage1_DD.pdf");


  /*

  TCanvas* my_canvas2 = new TCanvas("canvas2","canvas2");
  my_canvas2->cd();
  gPad->SetLogy();
  total->SetMaximum(1000);
  total->SetMarkerStyle(20);
  total->Draw("E");
  my_canvas2->Write();
  */
  TCanvas* ratio_c = new TCanvas("ratio","ratio_canvas",800,700);
  ratio_c->SetTopMargin(0.); 
  ratio_c->SetBottomMargin(0.); 
  ratio_c->Update();
  ratio_c->Divide(1, 2);
  ratio_c->cd(1);

  gPad->SetPad(.005, .30, .995, .995);
  TPad* pad1 = (TPad*)ratio_c->GetPad(1); 
  pad1->SetTopMargin(0.05);
  pad1->SetBottomMargin(0.05); 
  
  ratio_c->Update();
  gPad->SetLogy();
  
  hs->Draw("HIST");                                                                                                                                        
  hs->SetMaximum(100000);
  hs->SetMinimum(0.01);
  //  hs->GetXaxis()->SetLimits(40, 3200);
  hs->GetXaxis()->SetRangeUser(0, 1000);
  hs->GetXaxis()->SetTitle("");
  // total->Draw("SAME E2");
  mydata->Draw("SAME E1");
  tauPt_Stage1_Wprime_M4000->Draw("SAME HIST");
  CMS_text->Draw("same");
  CMS_text_2->Draw("same");
  lumiText->Draw("same");
  leg_example->Draw("same");
  ratio_c->cd(2);

  gPad->SetPad(.005, .08, .995, .28); 
  gStyle->SetOptStat(false);
  ratio_c->Update();
  TPad* pad2 = (TPad*)ratio_c->GetPad(2);
  pad2->SetTopMargin(0.04); 
  pad2->SetBottomMargin(0.30); 
  pad2->SetGridx();
  pad2->SetGridy();

  std::cout << "data bins = " << mydata->GetNbinsX() << " width=" << mydata->GetBinWidth(2);
  std::cout << " MC bins = " << total->GetNbinsX() << " width=" << total->GetBinWidth(2) << std::endl;

  int nbin=mydata->GetNbinsX() ;
  float width=mydata->GetBinWidth(2);
  TH1F *data_by_MC = new TH1F("h1", "ratio", nbin, 0, 4000);
  std::cout << "before D/MC bins=" << data_by_MC->GetNbinsX() << " width=" << data_by_MC->GetBinWidth(2) << std::endl;

  for (int i=0; i<nbin; i++) {
    float data = mydata->GetBinContent(i);
    float MC = total->GetBinContent(i);
    float ratio=0;
    if (MC>0) ratio=data/MC ;
    data_by_MC->SetBinContent(i,ratio);
    if (data>0) {
      float stat_err = sqrt(data)/data ;  
      data_by_MC->SetBinError(i,stat_err);
    }

    // data_by_MC->SetBinWidth(i,width);  
  }

  //  TH1F* data_by_MC = (TH1F*)mydata->Clone();
  // data_by_MC->Divide(total);
  data_by_MC->SetMarkerStyle(20);
  data_by_MC->Draw("E");
  data_by_MC->GetXaxis()->SetTitle("#tau pT [GeV]");
  data_by_MC->GetYaxis()->SetTitle("#frac{DATA}{MC}");
  data_by_MC->GetYaxis()->SetLabelSize(0.12);
  data_by_MC->GetXaxis()->SetLabelSize(0.12);
  data_by_MC->GetYaxis()->SetTitleSize(0.18);
  data_by_MC->GetXaxis()->SetTitleSize(0.18);
  data_by_MC->GetYaxis()->SetTitleOffset(0.20);
  data_by_MC->GetXaxis()->SetTitleOffset(0.75);
  data_by_MC->SetTitle("");
  data_by_MC->GetXaxis()->SetRangeUser(0, 1000);
  data_by_MC->SetMaximum(4);
  data_by_MC->SetMinimum(0);
  data_by_MC->GetYaxis()->SetNdivisions(4);



  TLine *l=new TLine(0,1,1000,1);
  l->SetLineColor(kRed);
  l->Draw("same");

  std::cout << "D/MC bins=" << data_by_MC->GetNbinsX() << " width=" << data_by_MC->GetBinWidth(2) << std::endl;
  ratio_c->Write();
  ratio_c->Print("tauPt_Stage1_ratio_DD.pdf");

 
  return 0;

}
void distribution(const string folderNameWithRootFiles = "", const Int_t signalRegion0_controlRegion1 = 0, const Int_t mumu0_ee1 = 0, const Int_t data0_noData1 = 0, const string var = "met", const Int_t yAxisLog_flag = 0, const Int_t MCpoissonUncertainty_flag = 0, const Double_t xAxisMin = 0, const Double_t xAxisMax = -1, const Double_t yAxisMin = 0, const Double_t yAxisMax = -1, const Int_t binDensity_flag = 0, const Int_t MCnormalizedToData_flag = 0) {

  // if signalRegion0_controlRegion1 == 0 (default), will do met distribution in the monojet signal region, else it will do the control region

  // mumu0_ee1 is for lepton flavour in CS (not used in SR)

  // data0_noData1 is to use or not a data file to compared with MC

  // yAxisLog_flag is to choose whether or not to use log scale in Y axis (default is 0, that is, normal scale)
  // xAxisMin and xAxisMax are the ranges for x Axis. Default values are used if xAxisMin > xAxisMax (otherwise user values are used)

  TH1::SetDefaultSumw2();            //all the following histograms will automatically call TH1::Sumw2() 

  gROOT->SetStyle("Plain");  // to have white legend (on my pc it's already white, but in tier2 it appears grey)
  gStyle->SetFillColor(10);

  string filenameExtension = ".root";
  // string fileDirectoryPath = "spring15_25ns_rootfiles/";
  string fileDirectoryPath = "/cmshome/ciprianim/CMSSW721/output/" + folderNameWithRootFiles + "/";

  string plotDirectoryPath = fileDirectoryPath;
  // string plotDirectoryPath = "/cmshome/ciprianim/CMSSW721/pdfsFromAnalysis/plots/monojet/met_distribution/";
  //string plotDirectoryPath = "./distributions/";
  string plotFileExtension = ".pdf";
  string suffix;

  if (mumu0_ee1 == 0) suffix = "_mumu";
  else if (mumu0_ee1 == 1) suffix = "_ee";
  else {
    cout << "Error: mumu0_ee1 must be 0 or 1. End of programme." << endl;
    exit(EXIT_FAILURE);
  }

  TH1D* hvar = NULL;   // to get histogram from file
  string hvarName;          // name of histogram to take from file
  string xAxisName;        // name of X axis when plotting distribution. It is a tex string (with ROOT standard), e.g. "#slash{E}_{T} [GeV]" for MET

  // ===== TO BE MODIFIED =====

  // hvarName = "HmetNoLepDistribution";
  // xAxisName = "#slash{E}_{T} [GeV]";

  setDistribution(signalRegion0_controlRegion1, mumu0_ee1, var, hvarName, xAxisName);
    
  // =====================

  vector<TH1D*> hMC;
  TH1D* hdata = NULL;

  vector<string> sampleName;
  vector<string> MC_TexLabel;
  if (data0_noData1 == 1) setSampleName(signalRegion0_controlRegion1, sampleName, MC_TexLabel, mumu0_ee1);
  else setSampleName2lepSkim(signalRegion0_controlRegion1, sampleName, MC_TexLabel, mumu0_ee1);

  string data_TexLabel = "data";

  Int_t nFiles = (Int_t) sampleName.size();

  vector<Int_t> histColor;
   setHistColor(histColor, nFiles);

   string filenameBase;
   string canvasName;

   if (signalRegion0_controlRegion1 == 0) {

     filenameBase = "monojet_SR_spring15_25ns_";
     canvasName = var + "_monojetSR_";

   } else {

     canvasName = var + "_zjetsCS" + suffix;

     if (mumu0_ee1 == 0) filenameBase = "zmumujets_CS_spring15_25ns_";
     else if (mumu0_ee1 == 1) filenameBase = "zeejets_CS_spring15_25ns_";

   }
 

  vector<string> MCfileName;
  for (Int_t i = 0; i < nFiles; i++) {
    MCfileName.push_back(fileDirectoryPath + filenameBase + sampleName[i] + filenameExtension);
  }

  for(Int_t i = 0; i < nFiles; i++) {

    cout<<"fileName : "<<MCfileName[i]<<endl;

    TFile* f = TFile::Open(MCfileName[i].c_str(),"READ");
    if (!f || !f->IsOpen()) {
      cout<<"*******************************"<<endl;
      cout<<"Error opening file \""<<MCfileName[i]<<"\".\nApplication will be terminated."<<endl;
      cout<<"*******************************"<<endl;
      exit(EXIT_FAILURE);
    }

    //cout << "check 1 " << endl;    

    hvar = (TH1D*)f->Get(hvarName.c_str());
    if (!hvar) {
      cout << "Error: histogram not found in file ' " << MCfileName[i] << "'. End of programme." << endl;
      exit(EXIT_FAILURE);
    }
    hMC.push_back( (TH1D*)hvar->Clone() );

  } 

  // ==== FILE NAME WILL HAVE TO BE MODIFIED, NOW IT IS JUST A TEST =====

  string datafileName = fileDirectoryPath;

  if (data0_noData1 == 0) {

    if (signalRegion0_controlRegion1 == 0) {

      datafileName += "monojet_SR_spring15_25ns_DATA.root";

    } else {

      if (mumu0_ee1 == 0) datafileName += "zmumujets_CS_spring15_25ns_DATA.root";
      else if (mumu0_ee1 == 1) datafileName += "zeejets_CS_spring15_25ns_DATA.root";

    }

  }

  // ==== opening data file ======

  if (data0_noData1 == 0) {

    cout<<"fileName : "<<datafileName<<endl;

    TFile* f = TFile::Open(datafileName.c_str(),"READ");
    if (!f || !f->IsOpen()) {
      cout<<"*******************************"<<endl;
      cout<<"Error opening file \""<<datafileName<<"\".\nApplication will be terminated."<<endl;
      cout<<"*******************************"<<endl;
      exit(EXIT_FAILURE);
    }

    hvar = (TH1D*)f->Get(hvarName.c_str());

    if (!hvar) {
      cout << "Error: histogram not found in file ' " << datafileName << "'. End of programme." << endl;
      exit(EXIT_FAILURE);
    }
    hdata = (TH1D*)hvar->Clone();

  }

  // ===============================

  THStack* hMCstack = new THStack("hMCstack","");
  Double_t stackNorm = 0.0;

  for (Int_t j = 0; j < nFiles; j++) {

    for (Int_t i = 1; i <= hMC[j]->GetNbinsX(); i++) {

      if (MCpoissonUncertainty_flag == 1) {

	hMC[j]->SetBinError(i,sqrt(hMC[j]->GetBinContent(i)));
	
      }

    }

    hMC[j]->SetFillColor(histColor[j]);
    stackNorm += hMC[j]->Integral();

  }

  // loop again on MC histograms to scale them and then fill the thstack

  for (Int_t j = 0; j < nFiles; j++) {

    if (data0_noData1 == 0 && MCnormalizedToData_flag != 0) {

      Double_t dataNorm = hdata->Integral();

      if (binDensity_flag != 0) hMC[j]->Scale(dataNorm/stackNorm,"width");
      else hMC[j]->Scale(dataNorm/stackNorm);

    } else if (binDensity_flag != 0) hMC[j]->Scale(1.0,"width");  // option width divides by bin width and manages the correct error setting

    hMCstack->Add(hMC[j]);

  }

  if (data0_noData1 == 0) {

    cout << "Events in data: " << hdata->Integral() << endl;
    cout << "Events in MC   : " << ((TH1D*) hMCstack->GetStack()->Last())->Integral() << endl;

  }
  
  if (data0_noData1 == 0 && binDensity_flag != 0) hdata->Scale(1.0,"width");
  //if (data0_noData1 == 0 && MCnormalizedToData_flag != 0)

  // now here we go with the canvas

  TH1D * ratioplot = NULL; // will use it for the ratio plots

  TPad *subpad_1 = NULL;  // will use it to access specific subpad in canvas
  TPad *subpad_2 = NULL; 

  TCanvas *c;
  if (data0_noData1 == 0) c = new TCanvas(canvasName.c_str(), (var + " distribution").c_str(), 700, 700);
  else c = new TCanvas(canvasName.c_str(), (var + " distribution").c_str());
  TLegend *leg = new TLegend(0.7,0.6,0.99,0.94);  

  // if there are data, split canvas to draw the dta/MC ratio plot

  if (data0_noData1 == 0) {

    subpad_1 = new TPad("pad_1","",0.0,0.28,1.0,1.0);
    if (yAxisLog_flag) subpad_1->SetLogy();
    //subpad_1->SetBottomMargin(0);
    subpad_2 = new TPad("pad_2","",0.0,0.0,1.0,0.32);
    subpad_2->SetGridy();
    //subpad_2->SetTopMargin(0);
    subpad_2->SetBottomMargin(0.3);
    subpad_1->Draw();
    subpad_2->Draw();

    subpad_1->cd();

  } else if (yAxisLog_flag) c->SetLogy();

  
  hMCstack->Draw("HIST");
  //if (yAxisMin > 0) hMCstack->SetMinimum(yAxisMin);

  if (yAxisMin < yAxisMax) {
    if (data0_noData1 == 0) subpad_1->Update();  // to be done after Draw() to access pad parameters such as default axis range
    else c->Update();  
    hMCstack->GetYaxis()->SetRangeUser(yAxisMin,yAxisMax);
  }

  // if (data0_noData1 == 0) {

  //   if (yAxisMin > 0) hMCstack->GetYaxis()->SetRangeUser(yAxisMin, subpad_1->GetY2());
  //   else hMCstack->GetYaxis()->SetRangeUser(yAxisMin, c->GetY2());

  // }

  //hMCstack->SetMaximum(4000.0);
  TH1D* stackCopy = (TH1D*)(((TH1D*)hMCstack->GetStack()->Last())->DrawCopy("E2 SAME"));
  stackCopy->SetFillColor(kBlack);
  stackCopy->SetFillStyle(3144);

  if (data0_noData1 == 1) {    //  when using data ( == 0) the x axis will not have labels (they will only be below in the ratio plot
    hMCstack->GetXaxis()->SetTitle(xAxisName.c_str());
    hMCstack->GetXaxis()->SetTitleSize(0.06);
    hMCstack->GetXaxis()->SetTitleOffset(0.6);
  }

  if (xAxisMin < xAxisMax) {
    if (data0_noData1 == 0) subpad_1->Update();  // to be done after Draw() to access pad parameters such as default axis range
    else c->Update();  
    hMCstack->GetXaxis()->SetRangeUser(xAxisMin,xAxisMax);
  }

  if (binDensity_flag == 0) hMCstack->GetYaxis()->SetTitle("events");
  else hMCstack->GetYaxis()->SetTitle("events / GeV");
  hMCstack->GetYaxis()->SetTitleSize(0.06);
  hMCstack->GetYaxis()->SetTitleOffset(0.8);
  hMCstack->GetYaxis()->CenterTitle();
  for (Int_t j = (nFiles-1); j >= 0; j--) {
    leg->AddEntry(hMC[j],Form("%s",MC_TexLabel[j].c_str()),"lf");
  }

  if (data0_noData1 == 0) {    
    hdata->SetMarkerStyle(8); // large dot
    hdata->Draw("EX0 SAME"); //X0 doesn't draw x error
    leg->AddEntry(hdata,Form("%s",data_TexLabel.c_str()),"p");
  }

  gStyle->SetStatStyle(0);
  leg->Draw(); 
  leg->SetMargin(0.3); 
  leg->SetBorderSize(0);

  if (data0_noData1 == 0) { // if using data, draw the ratio plot

    subpad_2->cd();
    ratioplot = new TH1D(*hdata);
    ratioplot->Divide(stackCopy);
    ratioplot->SetStats(0);
    ratioplot->SetTitle("");
    ratioplot->GetXaxis()->SetLabelSize(0.10);
    ratioplot->GetXaxis()->SetTitle(xAxisName.c_str());
    ratioplot->GetXaxis()->SetTitleSize(0.14);
    ratioplot->GetXaxis()->SetTitleOffset(0.8);
    ratioplot->GetYaxis()->SetLabelSize(0.10);
    ratioplot->GetYaxis()->SetTitle("data / MC");
    ratioplot->GetYaxis()->SetTitleSize(0.15);
    ratioplot->GetYaxis()->SetTitleOffset(0.3);
    ratioplot->GetYaxis()->CenterTitle();
    ratioplot->GetYaxis()->SetRangeUser(0.5,1.5);
    ratioplot->GetYaxis()->SetNdivisions(011);
    if (xAxisMin < xAxisMax) {
      //subpad_2->Update();  // to be done after Draw() to access pad parameters such as default axis range  
      ratioplot->GetXaxis()->SetRangeUser(xAxisMin,xAxisMax);
    }
    ratioplot->SetMarkerStyle(8);  //medium dot
    ratioplot->DrawCopy("E");  

  }

  c->SaveAs( (plotDirectoryPath + c->GetName() + plotFileExtension).c_str() );

}
////////////////////////////////////////////////////////////////////////////////////////
// Draw and save the canvas
// This bit shouldn't need to be updated except the region and channel labels
// As of Jan 10,2013 - the known issues are:
// ++ Error bands don't show correctly
// ++ Data histogram needs to be converted to TGraphAsymmErrors and 
//    plotted w/ poisson errors
// ++ Ratio plot needs to divide the Data TGraphAsymmErrors and
//    TGraphAsymmErrors for the total SM (by turning off the errors since they are
//    shown explicitly)
////////////////////////////////////////////////////////////////////////////////////////
void PlotUnifier(
                  TH1F* histos[9],                   // Array of pointers to histograms
                  TGraphAsymmErrors* smErrorBand,    // Error band for the top pad
                  TGraphAsymmErrors* ratioErrorBand  // Error band for the bottom pad
                )
{
  ////////////////////////////////////////////////////////////////////////////////////////
  // Set Histogram Properties, build the stack and make the ratio plot
  histos[0]->SetMarkerStyle(20)     ; histos[0]->SetMarkerSize(1.2); 
  histos[1]->SetFillColor(kOrange-2); histos[4]->SetLineWidth (2);
  histos[2]->SetFillColor(kAzure-9 ); histos[1]->SetLineWidth (2);
  histos[3]->SetFillColor(kSpring+1); histos[2]->SetLineWidth (2);
  histos[4]->SetFillColor(kAzure+4 ); histos[3]->SetLineWidth (2);
  histos[5]->SetFillColor(kGray    ); histos[5]->SetLineWidth (2);
  histos[6]->SetFillColor(kYellow-9); histos[6]->SetLineWidth (2);
  histos[7]->SetLineColor(kMagenta ); histos[7]->SetLineWidth (3); histos[7]->SetLineStyle(2);
  histos[8]->SetLineColor(kGreen+1 ); histos[8]->SetLineWidth (3); histos[8]->SetLineStyle(2);
  
  ////////////////////////////////////////////////////////////////////////////////////////
  // Here comes the stack 
  THStack* sm = new THStack("sm","sm");
  sm->Add(histos[6]);
  sm->Add(histos[5]);
  sm->Add(histos[4]);
  sm->Add(histos[3]);
  sm->Add(histos[2]);
  sm->Add(histos[1]);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Define the legend and fill in the stack order
  TLegend* legendA        = new TLegend(0.49,0.65,0.74,0.85);
  TLegend* legendB        = new TLegend(0.62,0.65,0.87,0.85);
  legendA->SetTextFont(42);    
  legendB->SetTextFont(42);    
  legendA->SetTextSize(0.03);
  legendB->SetTextSize(0.03);
  legendA->SetBorderSize(0);
  legendB->SetBorderSize(0);
  legendA->SetFillColor(0);
  legendB->SetFillColor(0);
  legendA->AddEntry(histos[0],"Data"               ,"p");
  legendA->AddEntry(histos[1],"Z+jets"             ,"f");
  legendA->AddEntry(histos[2],"WW"                 ,"f");
  legendA->AddEntry(histos[3],"t#bar{t}+Wt"        ,"f");
  legendA->AddEntry(histos[4],"ZV"                 ,"f");
  legendB->AddEntry(histos[5],"Non-prompt leptons" ,"f");
  legendB->AddEntry(histos[6],"Higgs"              ,"f");
  TH1F* histoError = new TH1F("histoError"         ,"histoError",1,0,1);
  histoError->SetFillStyle(3004);
  histoError->SetFillColor(kBlack);
  legendB->AddEntry(histoError,"Bkg. Uncert."      ,"f");
  legendB->AddEntry(histos[7],"Signal 1"           ,"l");
  legendB->AddEntry(histos[8],"Signal 2"           ,"l");

  ////////////////////////////////////////////////////////////////////////////////////////
  // Ratio plot 
  TH1F* ratio      = (TH1F*) histos[0]->Clone(); ratio->Reset(); 
  TH1F* stackHisto = (TH1F*) sm->GetStack()->Last();
  ratio->Divide(histos[0],stackHisto);
  ratio->SetMarkerSize(1.2);
  ratio->SetMarkerStyle(20);
  ratio->SetLineColor(kBlack);
  ratio->SetLineWidth(2);

  ratio->GetXaxis()->SetTitle("Observable");
  ratio->GetYaxis()->SetTitle("Data/SM");
  ratio->GetXaxis()->SetLabelSize(0.13);
  ratio->GetXaxis()->SetLabelOffset(0.02);
  ratio->GetXaxis()->SetTitleSize(0.14);
  ratio->GetXaxis()->SetTitleOffset(1.2);

  ratio->GetYaxis()->SetRangeUser(0,2);
  ratio->GetYaxis()->SetLabelSize(0.13);
  ratio->GetYaxis()->SetLabelOffset(0.0125);
  ratio->GetYaxis()->SetTitleSize(0.14);
  ratio->GetYaxis()->SetTitleOffset(0.5);
  ratio->GetYaxis()->SetNdivisions(5);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Error bands
  smErrorBand->SetMarkerSize(0); 
  smErrorBand->SetFillStyle(3004);
  smErrorBand->SetFillColor(kBlack);
  ratioErrorBand->SetMarkerSize(0); 
  ratioErrorBand->SetFillStyle(3004);
  ratioErrorBand->SetFillColor(kBlack);
 
  ////////////////////////////////////////////////////////////////////////////////////////
  // Draw and save the canvas
  TCanvas* canvas = new TCanvas("canvas","canvas",500,500);
  TPad*    topPad = new TPad("pTop","pTop",0,0.2,1,1);
  TPad*    botPad = new TPad("pBot","pBot",0,0.0,1,0.3);
  topPad->Draw();
  botPad->Draw();

  ////////////////////////////////////////////////////////////////////////////////////////
  // Data is special since I use it to draw the axis labels etc.
  histos[0]->GetXaxis()->SetTitle("Observable"); 
  histos[0]->GetYaxis()->SetTitle("Events / Bin"); 
  histos[0]->GetXaxis()->SetLabelOffset(1.2); 
  histos[0]->GetXaxis()->SetLabelSize(0.03);
  histos[0]->GetYaxis()->SetRangeUser(1.e-2,1.e5);
  histos[0]->GetYaxis()->SetTitleSize(0.055);
  histos[0]->GetYaxis()->SetTitleOffset(1.28);
  histos[0]->GetYaxis()->SetLabelSize(0.05);
  histos[0]->GetYaxis()->SetLabelOffset(0.01);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Top Pad
  topPad      ->cd();
  topPad      ->SetBottomMargin(0.15);
  histos[0]   ->Draw("p && e && x0");
  sm          ->Draw("same && hists");
  smErrorBand ->Draw("same && E2");
  histos[0]   ->Draw("same && p && e && x0");
  histos[7]   ->Draw("same && hist");
  histos[8]   ->Draw("same && hist");
  legendA     ->Draw();
  legendB     ->Draw();
  gPad        ->RedrawAxis();
  gPad        ->SetLogy(1);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Decoration
  char annoyingLabel1[100] = "#bf{#it{ATLAS}}, #sqrt{s} = 8 TeV, 20.3 fb^{-1}";
  char annoyingLabel2[100] = "SF/DF channel"; 
  char annoyingLabel3[100] = "- Top CR for SR-#scale[0.9]{m_{T2}} and SR-WWb/c";
  myText(0.53,0.880,kBlack,annoyingLabel1);
  myText(0.17,0.965,kBlack,annoyingLabel2);
  myText(0.37,0.965,kBlack,annoyingLabel3);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Bottom Pad
  botPad ->cd();
  botPad ->SetBottomMargin(0.4);
  
  ////////////////////////////////////////////////////////////////////////////////////////
  // 1 Line
  TLine* line = new TLine(histos[0]->GetXaxis()->GetXmin(),1,histos[0]->GetXaxis()->GetXmax(),1);
  line   ->SetLineColor(kRed);
  line   ->SetLineStyle(7);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Draw
  ratio          ->Draw("p && e && x0");
  ratioErrorBand ->Draw("same && E2");
  line           ->Draw("same");
  ratio          ->Draw("same && p && e && x0");
  gPad           ->SetGridy(1);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Save
  canvas ->SaveAs("Test_v3.eps");

}